builder.put("cpus", cpus); builder.put("memory", memory); builder.put("openPorts", Ints.toArray(entityOpenPorts)); sensors().set(DockerAttributes.DOCKER_CONTAINER_OPEN_PORTS, ImmutableList.copyOf(entityOpenPorts)); entity.sensors().set(DockerAttributes.DOCKER_CONTAINER_OPEN_PORTS, ImmutableList.copyOf(entityOpenPorts)); builder.put("portBindings", Lists.newArrayList(marathonBindings.entrySet())); builder.put("extraHosts", Lists.newArrayList(extraHosts.entrySet())); builder.put("environment", Lists.newArrayList(Maps.transformValues(environment, Functions.toStringFunction()).entrySet())); builder.put("volumes", Lists.newArrayList(volumes.entrySet())); sensors().set(TASK_URI_LIST, uris); entity.sensors().set(TASK_URI_LIST, uris); builder.put("uris", uris); builder.put("imageName", imageName.get()); builder.put("imageVersion", config().get(DOCKER_IMAGE_TAG)); builder.putIfNotNull("command", command); List<String> args = MutableList.copyOf(config().get(ARGS)); builder.putIfNotNull("args", args); } else { builder.put("imageName", "clockercentral/" + imageName.get());
.putAll(flags) .put("useSsh", useSsh) .put("entity", entity) .putIfNotNull("imageId", imageId) .putIfNotNull("imageName", imageId == null ? imageName : null) .putIfNotNull("imageTag", imageId == null ? imageTag : null) .putIfNotNull("hardwareId", hardwareId) .build(); Group cluster = dockerHost.getDockerContainerCluster(); EntitySpec<DockerContainer> spec = EntitySpec.create(getOwner().sensors().get(DockerHost.DOCKER_CONTAINER_SPEC));
result.put("com.sun.management.jmxremote", null); result.put("java.rmi.server.hostname", hostName); result.put(JmxmpAgent.RMI_REGISTRY_PORT_PROPERTY, rmiRegistryPort); case JMXMP: if (jmxRemotePort==null || jmxRemotePort<=0) throw new IllegalStateException("Unsupported JMX port "+jmxRemotePort+" - when applying system properties ("+getJmxAgentMode()+" / "+getEntity()+")"); result.put(JmxmpAgent.JMXMP_PORT_PROPERTY, jmxRemotePort); result.remove("java.rmi.server.hostname"); break; case JMX_RMI_CUSTOM_AGENT: if (jmxRemotePort==null || jmxRemotePort<=0) throw new IllegalStateException("Unsupported JMX port "+jmxRemotePort+" - when applying system properties ("+getJmxAgentMode()+" / "+getEntity()+")"); result.put(JmxRmiAgent.RMI_REGISTRY_PORT_PROPERTY, Preconditions.checkNotNull(entity.getAttribute(UsesJmx.RMI_REGISTRY_PORT), "registry port")); result.put(JmxRmiAgent.JMX_SERVER_PORT_PROPERTY, jmxRemotePort); break; case NONE: jmxRemotePort = fixPortsForModeNone(); case JMX_RMI: result.put("com.sun.management.jmxremote.port", jmxRemotePort); result.put("java.rmi.server.useLocalHostname", "true"); break; default: } else { result. put("com.sun.management.jmxremote.ssl", false). put("com.sun.management.jmxremote.authenticate", false);
.putAll(itemMetadata) .remove("item") .remove("items") .build(); .putAll(parentMetadata) .putAll(itemMetadataWithoutItemDef) .putIfNotNull("item", itemMetadata.get("item")) .putIfNotNull("items", itemMetadata.get("items")) .build();
.put("identity", certPath) .put("credential", keyPath) .build()); sensors().set(JCLOUDS_DOCKER_LOCATION, jcloudsLocation); .putAll(config().get(LOCATION_FLAGS)) .put("machine", found.get()) .put("jcloudsLocation", jcloudsLocation) .put("portForwarder", portForwarder) .build(); createLocation(flags);
.putIfNotNull("user", user) .put("address", InetAddress.getByName(address)) .build()); try { final File tempFile = Os.newTempFile("brooklyn-sftp", "tmp");
.putAll(FlagUtils.getFieldsWithFlagsWithModifiers(location, Modifier.TRANSIENT)) .putAll(FlagUtils.getFieldsWithFlagsWithModifiers(location, Modifier.STATIC)) .put("id", String.class) .filterValues(Predicates.not(Predicates.instanceOf(ConfigKey.class))) .build() .keySet(); Map<String, Object> persistableFlags = MutableMap.<String, Object>builder() .putAll(FlagUtils.getFieldsWithFlagsExcludingModifiers(location, Modifier.STATIC ^ Modifier.TRANSIENT)) .removeAll(nonPersistableFlagNames) .build(); ConfigBag persistableConfig = new ConfigBag().copy( ((LocationInternal)location).config().getLocalBag() ).removeAll(nonPersistableFlagNames);
@BeforeMethod(alwaysRun=true) @Override public void setUp() throws Exception { // Don't let any defaults from brooklyn.properties (except credentials) interfere with test brooklynProperties = BrooklynProperties.Factory.newDefault(); brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".image-description-regex"); brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".image-name-regex"); brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".image-id"); brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".inboundPorts"); brooklynProperties.remove("brooklyn.jclouds."+PROVIDER+".hardware-id"); // Also removes scriptHeader (e.g. if doing `. ~/.bashrc` and `. ~/.profile`, then that can cause "stdin: is not a tty") brooklynProperties.remove("brooklyn.ssh.config.scriptHeader"); mgmt = new LocalManagementContextForTests(brooklynProperties); super.setUp(); Map<String,?> allFlags = MutableMap.<String,Object>builder() .put("tags", ImmutableList.of(getClass().getName())) .putAll(ImmutableMap.of("imageId", UBUNTU_12, "loginUser", "ubuntu", "hardwareId", "m1.small")) .build(); loc = mgmt.getLocationRegistry().getLocationManaged(LOCATION_SPEC, allFlags); testEntity = app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class)); app.start(ImmutableList.of(loc)); EntityAsserts.assertAttributeEqualsEventually(MutableMap.of("timeout", TIMEOUT_MS), testEntity, Startable.SERVICE_UP, true); SshMachineLocation sshLoc = Locations.findUniqueSshMachineLocation(testEntity.getLocations()).get(); jcloudsMachineLocation = (JcloudsMachineLocation)sshLoc; computeService = jcloudsMachineLocation.getParent().getComputeService(); }
@Override public String generateConfigFile(NginxDriver driver, NginxController nginx) { // Check template URL exists String templateUrl = driver.getEntity().getConfig(NginxController.SERVER_CONF_TEMPLATE_URL); ResourceUtils.create(this).checkUrlExists(templateUrl); // Check SSL configuration ProxySslConfig ssl = driver.getEntity().getConfig(NginxController.SSL_CONFIG); if (ssl != null && Strings.isEmpty(ssl.getCertificateDestination()) && Strings.isEmpty(ssl.getCertificateSourceUrl())) { throw new IllegalStateException("ProxySslConfig can't have a null certificateDestination and null certificateSourceUrl. One or both need to be set"); } // For mapping by URL Iterable<UrlMapping> mappings = ((NginxController) driver.getEntity()).getUrlMappings(); Multimap<String, UrlMapping> mappingsByDomain = LinkedHashMultimap.create(); for (UrlMapping mapping : mappings) { Collection<String> addrs = mapping.getAttribute(UrlMapping.TARGET_ADDRESSES); if (addrs != null && addrs.size() > 0) { mappingsByDomain.put(mapping.getDomain(), mapping); } } Map<String, Object> substitutions = MutableMap.<String, Object>builder() .putIfNotNull("ssl", ssl) .put("urlMappings", mappings) .put("domainMappings", mappingsByDomain) .build(); // Get template contents and process String contents = ResourceUtils.create(driver.getEntity()).getResourceAsString(templateUrl); return TemplateProcessor.processTemplateContents(contents, driver, substitutions); }
private Map<String,?> toFlags() { return MutableMap.<String,Object>builder() .putIfNotNull("id", id) .putIfNotNull("name", name) .putIfNotNull("metric", metric) .putIfNotNull("entityWithMetric", entityWithMetric) .putIfNotNull("metricUpperBound", metricUpperBound) .putIfNotNull("metricLowerBound", metricLowerBound) .putIfNotNull("minPoolSize", minPoolSize) .putIfNotNull("maxPoolSize", maxPoolSize) .putIfNotNull("resizeUpIterationMax", resizeUpIterationMax) .putIfNotNull("resizeUpIterationIncrement", resizeUpIterationIncrement) .putIfNotNull("resizeDownIterationMax", resizeDownIterationMax) .putIfNotNull("resizeDownIterationIncrement", resizeDownIterationIncrement) .putIfNotNull("minPeriodBetweenExecs", minPeriodBetweenExecs) .putIfNotNull("resizeUpStabilizationDelay", resizeUpStabilizationDelay) .putIfNotNull("resizeDownStabilizationDelay", resizeDownStabilizationDelay) .putIfNotNull("resizeOperator", resizeOperator) .putIfNotNull("currentSizeOperator", currentSizeOperator) .putIfNotNull("poolHotSensor", poolHotSensor) .putIfNotNull("poolColdSensor", poolColdSensor) .putIfNotNull("poolOkSensor", poolOkSensor) .putIfNotNull("maxSizeReachedSensor", maxSizeReachedSensor) .putIfNotNull("maxReachedNotificationDelay", maxReachedNotificationDelay) .build(); } }
/** * Given a policy, extracts its state for serialization. * * @deprecated since 0.7.0, see {@link #newBasicMemento(BrooklynObject)} */ @Deprecated public static PolicyMemento newPolicyMemento(Policy policy) { BasicPolicyMemento.Builder builder = BasicPolicyMemento.builder(); populateBrooklynObjectMementoBuilder(policy, builder); // TODO persist config keys as well? Or only support those defined on policy class; // current code will lose the ConfigKey type on rebind for anything not defined on class. // Whereas entities support that. // TODO Do we need the "nonPersistableFlagNames" that locations use? Map<ConfigKey<?>, Object> config = ((AbstractPolicy)policy).config().getInternalConfigMap().getAllConfigLocalRaw(); for (Map.Entry<ConfigKey<?>, Object> entry : config.entrySet()) { ConfigKey<?> key = checkNotNull(entry.getKey(), "config=%s", config); Object value = configValueToPersistable(entry.getValue(), policy, key.getName()); builder.config.put(key.getName(), value); } builder.highlights(policy.getHighlights()); Map<String, Object> persistableFlags = MutableMap.<String, Object>builder() .putAll(FlagUtils.getFieldsWithFlagsExcludingModifiers(policy, Modifier.STATIC ^ Modifier.TRANSIENT)) .remove("id") .remove("name") .build(); builder.config.putAll(persistableFlags); return builder.build(); }
@Override protected void provisionMore(int size, Map<?,?> flags) { for (int i=0; i<size; i++) { Map<Object,Object> flags2 = MutableMap.<Object,Object>builder() .putAll(flags) .put("address", elvis(address, getLocalhostInetAddress())) .build(); // copy inherited keys for ssh; // shouldn't be necessary but not sure that all contexts traverse the hierarchy // NOTE: changed Nov 2013 to copy only those ssh config keys actually set, rather than all of them // TODO should take the plunge and try removing this altogether! // (or alternatively switch to copying all ancestor keys) for (HasConfigKey<?> k: SshMachineLocation.ALL_SSH_CONFIG_KEYS) { if (config().getRaw(k).isPresent()) flags2.put(k, getConfig(k)); } if (isManaged()) { addChild(LocationSpec.create(LocalhostMachine.class).configure(flags2)); } else { addChild(new LocalhostMachine(flags2)); // TODO legacy way } } }
/** * Gets all single-word properties that start with either of the given prefixes. The {@code fullPreferredPrefix} * properties will override any duplicates in {@code fullDeprecatedPrefix}. If there are any * properties that match the {@code fullDeprecatedPrefix}, then a warning will be logged. * * @see #getMatchingSingleWordProperties(String, Map) */ protected Map<String, Object> getMatchingSingleWordProperties(String fullPreferredPrefix, String fullDeprecatedPrefix, Map<String, ?> properties) { Map<String, Object> deprecatedResults = getMatchingSingleWordProperties(fullDeprecatedPrefix, properties); Map<String, Object> results = getMatchingSingleWordProperties(fullPreferredPrefix, properties); if (deprecatedResults.size() > 0) { LOG.warn("Deprecated use of properties prefix "+fullDeprecatedPrefix+"; instead use "+fullPreferredPrefix); return MutableMap.<String, Object>builder() .putAll(deprecatedResults) .putAll(results) .build(); } else { return results; } }
/** * Given an enricher, extracts its state for serialization. * @deprecated since 0.7.0, see {@link #newBasicMemento(BrooklynObject)} */ @Deprecated public static EnricherMemento newEnricherMemento(Enricher enricher) { BasicEnricherMemento.Builder builder = BasicEnricherMemento.builder(); populateBrooklynObjectMementoBuilder(enricher, builder); // TODO persist config keys as well? Or only support those defined on policy class; // current code will lose the ConfigKey type on rebind for anything not defined on class. // Whereas entities support that. // TODO Do we need the "nonPersistableFlagNames" that locations use? Map<ConfigKey<?>, Object> config = ((AbstractEnricher)enricher).config().getInternalConfigMap().getAllConfigLocalRaw(); for (Map.Entry<ConfigKey<?>, Object> entry : config.entrySet()) { ConfigKey<?> key = checkNotNull(entry.getKey(), "config=%s", config); Object value = configValueToPersistable(entry.getValue(), enricher, key.getName()); builder.config.put(key.getName(), value); } Map<String, Object> persistableFlags = MutableMap.<String, Object>builder() .putAll(FlagUtils.getFieldsWithFlagsExcludingModifiers(enricher, Modifier.STATIC ^ Modifier.TRANSIENT)) .remove("id") .remove("name") .build(); builder.config.putAll(persistableFlags); return builder.build(); }
/** * Gets all properties that start with either of the given prefixes. The {@code fullPreferredPrefix} * properties will override any duplicates in {@code fullDeprecatedPrefix}. If there are any * properties that match the {@code fullDeprecatedPrefix}, then a warning will be logged. * * @see #getMatchingProperties(String, Map) */ protected Map<String, Object> getMatchingProperties(String fullPreferredPrefix, String fullDeprecatedPrefix, Map<String, ?> properties) { Map<String, Object> deprecatedResults = getMatchingProperties(fullDeprecatedPrefix, properties); Map<String, Object> results = getMatchingProperties(fullPreferredPrefix, properties); if (deprecatedResults.size() > 0) { LOG.warn("Deprecated use of properties prefix "+fullDeprecatedPrefix+"; instead use "+fullPreferredPrefix); return MutableMap.<String, Object>builder() .putAll(deprecatedResults) .putAll(results) .build(); } else { return results; } }
@Override public void doStart(Collection<? extends Location> locs) { addLocations(locs); List<Location> locations = MutableList.copyOf(Locations.getLocationsCheckingAncestors(locs, this)); sensors().set(SERVICE_UP, Boolean.FALSE); ServiceStateLogic.setExpectedState(this, Lifecycle.STARTING); // TODO support multiple provisioners Location provisioner = Iterables.getOnlyElement(locations); LOG.info("Creating new DockerLocation wrapping {}", provisioner); Map<String, ?> flags = MutableMap.<String, Object>builder() .putAll(config().get(LOCATION_FLAGS)) .put("provisioner", provisioner) .putIfNotNull("strategies", config().get(PLACEMENT_STRATEGIES)) .build(); createLocation(flags); super.doStart(locations); ServiceStateLogic.setExpectedState(this, Lifecycle.RUNNING); sensors().set(SERVICE_UP, Boolean.TRUE); }
protected PublicIPAddress systemCreatePublicIpHostname() { PublicIPAddress ip; Location l = Iterables.getOnlyElement(getLocations()); String vpcId = getVpcId(l); if (vpcId==null) { String zoneId = getZoneId(l); String networkId = getAttribute(NETWORK_ID); AsyncCreateResponse response = cloudstackClient.getCloudstackGlobalClient().getAddressApi().associateIPAddressInZone(zoneId, AssociateIPAddressOptions.Builder.networkId(networkId)); cloudstackClient.waitForJobSuccess(response.getJobId()); ip = cloudstackClient.getCloudstackGlobalClient().getAddressApi().getPublicIPAddress(response.getId()); } else { ip = cloudstackClient.createIpAddressForVpc(vpcId); } synchronized (this) { Map<String, String> ips = getAttribute(PUBLIC_HOSTNAME_IP_IDS); if (ips == null) { ips = ImmutableMap.of(); } Map<String,String> newips = MutableMap.<String,String>builder().putAll(ips).put(ip.getIPAddress(), ip.getId()).build(); sensors().set(PUBLIC_HOSTNAME_IP_IDS, newips); } return ip; }
@Override public Map<String, String> getShellEnvironment() { JmxAgentModes jmxAgentMode = getEntity().getConfig(KafkaBroker.JMX_AGENT_MODE); String jmxPort; if (jmxAgentMode == JmxAgentModes.NONE) { // seems odd to pass RMI port here, as it gets assigned to com.sun.mgmt.jmx.port in kafka-run-class.sh // but RMI server/registry port works, whereas JMX port does not jmxPort = String.valueOf(entity.getAttribute(UsesJmx.JMX_PORT)); } else { /* * See ./bin/kafka-server-start.sh and ./bin/kafka-run-class.sh * Really hard to turn off jmxremote on kafka! And can't use default because * uses 9999, which means could only run one kafka broker per server. */ jmxPort = String.valueOf(entity.getAttribute(KafkaBroker.INTERNAL_JMX_PORT)); } return MutableMap.<String, String> builder() .putAll(super.getShellEnvironment()) .put("JMX_PORT", jmxPort) .build(); } }
@Test public void testEnricherSpecPropagatesSpecificSensorAndMapsOthers() throws Exception { final AttributeSensor<String> ANOTHER_ATTRIBUTE = Sensors.newStringSensor("another.attribute", ""); app.enrichers().add(EnricherSpec.create(Propagator.class) .configure(MutableMap.builder() .putIfNotNull(Propagator.PRODUCER, entity) .putIfNotNull(Propagator.SENSOR_MAPPING, ImmutableMap.of(TestEntity.NAME, ANOTHER_ATTRIBUTE)) .putIfNotNull(Propagator.PROPAGATING, ImmutableList.of(TestEntity.SEQUENCE)) .build())); // name propagated as alternative sensor entity.sensors().set(TestEntity.NAME, "foo"); EntityAsserts.assertAttributeEqualsEventually(app, ANOTHER_ATTRIBUTE, "foo"); // sequence also propagated entity.sensors().set(TestEntity.SEQUENCE, 2); EntityAsserts.assertAttributeEqualsEventually(app, TestEntity.SEQUENCE, 2); // name not propagated as original sensor EntityAsserts.assertAttributeEqualsContinually(MutableMap.of("timeout", 100), app, TestEntity.NAME, null); }