Java Code Examples for org.apache.brooklyn.util.core.config.ConfigBag#put()

The following examples show how to use org.apache.brooklyn.util.core.config.ConfigBag#put() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JmxFeedTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testJmxAttributeSensor() throws Exception {
    GeneralisedDynamicMBean mbean = jmxService.registerMBean(ImmutableMap.of(attributeName, 42), objectName);

    String sensorName = "testJmxAttributeSensorName";

    ConfigBag params = new ConfigBag();
    params.put(AddSensor.SENSOR_NAME, sensorName);
    params.put(AddSensor.SENSOR_TYPE, "java.lang.Integer");
    params.put(AddSensor.SENSOR_PERIOD, Duration.millis(SHORT_WAIT_MS));
    params.put(JmxAttributeSensor.ATTRIBUTE, attributeName);
    params.put(JmxAttributeSensor.OBJECT_NAME, objectName);
    JmxAttributeSensor<Integer> mySensor = new JmxAttributeSensor<>(params);

    mySensor.apply(entity);

    final AttributeSensor<Integer> sensor = (AttributeSensor<Integer>) entity.getEntityType().getSensor(sensorName);

    // Starts with value defined when registering...
    assertSensorEventually(sensor, 42, TIMEOUT_MS);

    // Change the value and check it updates
    mbean.updateAttributeValue(attributeName, 64);
    assertSensorEventually(sensor, 64, TIMEOUT_MS);
}
 
Example 2
Source File: LocationConfigUtilsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public void testReadsPrivateKeyFileWithMultipleColonSeparatedFilesWithGoodFirst() throws Exception {
    ConfigBag config = ConfigBag.newInstance();
    config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE+File.pathSeparator+"/path/does/not/exist");

    String data = LocationConfigUtils.getOsCredential(config).getPreferredCredential();
    assertTrue(data != null && data.length() > 0);
}
 
Example 3
Source File: JcloudsLocationReachabilityPredicateInstantiationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testInitMapConstructor() {
    Assert.assertEquals(TEST_INIT_MAP_CONSTRUCTOR_COUNTER.get(), 0);
    ConfigBag predicateConfig = new ConfigBag();
    predicateConfig.put(CloudLocationConfig.POLL_FOR_FIRST_REACHABLE_ADDRESS_PREDICATE_TYPE, RecordingReachabilityCheckMapConstructor.class);
    predicateConfig.putStringKey(CloudLocationConfig.POLL_FOR_FIRST_REACHABLE_ADDRESS_PREDICATE.getName() + ".key1", "val1");
    predicateConfig.putStringKey(CloudLocationConfig.POLL_FOR_FIRST_REACHABLE_ADDRESS_PREDICATE.getName() + ".key2", "val2");
    jcloudsLocation.getFirstReachableAddress(node, predicateConfig);
    Assert.assertEquals(TEST_INIT_MAP_CONSTRUCTOR_COUNTER.get(), 1);
}
 
Example 4
Source File: JcloudsLocationReachabilityPredicateInstantiationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testInitDefaultConstructor() throws Exception {
    Assert.assertEquals(TEST_INIT_DEFAULT_CONSTRUCTOR_COUNTER.get(), 0);
    ConfigBag predicateConfig = new ConfigBag();
    predicateConfig.put(CloudLocationConfig.POLL_FOR_FIRST_REACHABLE_ADDRESS_PREDICATE_TYPE, RecordingReachabilityCheck.class);
    jcloudsLocation.getFirstReachableAddress(node, predicateConfig);
    Assert.assertEquals(TEST_INIT_DEFAULT_CONSTRUCTOR_COUNTER.get(), 1);
}
 
Example 5
Source File: JcloudsLocationReachabilityPredicateInstantiationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testConfigLocationWithReachabilityPredicate() {
    List<String> hostsMatchedHolder = new ArrayList<>();
    Predicate<HostAndPort> hostAndPortPredicate = new RecordingReachabilityCheckMapAndFlagsConstructor(ImmutableMap.<String, Object>of("hostsMatchedHolder", hostsMatchedHolder));
    ConfigBag predicateConfig = new ConfigBag();
    predicateConfig.put(CloudLocationConfig.POLL_FOR_FIRST_REACHABLE_ADDRESS_PREDICATE, hostAndPortPredicate);
    jcloudsLocation.getFirstReachableAddress(node, predicateConfig);
    Assert.assertTrue(hostsMatchedHolder.contains(ALLOWED_HOST_AND_PORT.getHostText()));
}
 
Example 6
Source File: BrooklynNodeImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Void call(ConfigBag parameters) {
    Duration timeout = parameters.get(TIMEOUT);

    ConfigBag stopParameters = ConfigBag.newInstanceCopying(parameters);
    stopParameters.put(ShutdownEffector.STOP_APPS_FIRST, Boolean.FALSE);
    stopParameters.putIfAbsent(ShutdownEffector.SHUTDOWN_TIMEOUT, timeout);
    stopParameters.putIfAbsent(ShutdownEffector.REQUEST_TIMEOUT, timeout);
    DynamicTasks.queue(Effectors.invocation(entity(), STOP, stopParameters)).asTask().getUnchecked();
    return null;
}
 
Example 7
Source File: SoftwareProcessImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected Map<String,Object> obtainProvisioningFlags(MachineProvisioningLocation location) {
    ConfigBag result = ConfigBag.newInstance(location.getProvisioningFlags(ImmutableList.of(getClass().getName())));

    // copy provisioning properties raw in case they contain deferred values
    // normal case is to have provisioning.properties.xxx in the map, so this is how we get it
    Map<String, Object> raw1 = PROVISIONING_PROPERTIES.rawValue(config().getBag().getAllConfigRaw());
    // do this also, just in case a map is stored at the key itself (not sure this is needed, raw1 may include it already)
    Maybe<Object> raw2 = config().getRaw(PROVISIONING_PROPERTIES);
    if (raw2.isPresentAndNonNull()) {
        Object pp = raw2.get();
        if (!(pp instanceof Map)) {
            LOG.debug("When obtaining provisioning properties for "+this+" to deploy to "+location+", detected that coercion was needed, so coercing sooner than we would otherwise");
            pp = config().get(PROVISIONING_PROPERTIES);
        }
        result.putAll((Map<?,?>)pp);
    }
    // finally write raw1 on top
    result.putAll(raw1);

    if (result.get(CloudLocationConfig.INBOUND_PORTS) == null) {
        Collection<Integer> ports = getRequiredOpenPorts();
        Object requiredPorts = result.get(CloudLocationConfig.ADDITIONAL_INBOUND_PORTS);
        if (requiredPorts instanceof Integer) {
            ports.add((Integer) requiredPorts);
        } else if (requiredPorts instanceof Iterable) {
            for (Object o : (Iterable<?>) requiredPorts) {
                if (o instanceof Integer) ports.add((Integer) o);
            }
        }
        if (ports != null && ports.size() > 0) result.put(CloudLocationConfig.INBOUND_PORTS, ports);
    }
    result.put(LocationConfigKeys.CALLER_CONTEXT, this);
    return result.getAllConfigMutable();
}
 
Example 8
Source File: BrooklynNodeImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Void call(ConfigBag parameters) {
    Duration timeout = parameters.get(TIMEOUT);

    ConfigBag stopParameters = ConfigBag.newInstanceCopying(parameters);
    stopParameters.put(ShutdownEffector.STOP_APPS_FIRST, Boolean.TRUE);
    stopParameters.putIfAbsent(ShutdownEffector.SHUTDOWN_TIMEOUT, timeout);
    stopParameters.putIfAbsent(ShutdownEffector.REQUEST_TIMEOUT, timeout);
    DynamicTasks.queue(Effectors.invocation(entity(), STOP, stopParameters)).asTask().getUnchecked();
    return null;
}
 
Example 9
Source File: DefaultAzureArmNetworkCreatorTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testVanillaWhereExistingNetworkButNoSubnet() throws Exception {
    //Setup config bag
    ConfigBag configBag = ConfigBag.newInstance();
    configBag.put(CLOUD_REGION_ID, TEST_LOCATION);

    //Setup mocks
    when(subnetApi.get(TEST_SUBNET_NAME)).thenReturn(null).thenReturn(subnet); //null first time, subnet next
    when(virtualNetworkApi.get(TEST_NETWORK_NAME)).thenReturn(virtualNetwork);
    when(resourceGroupApi.get(TEST_RESOURCE_GROUP)).thenReturn(resourceGroup);
    when(subnet.properties().provisioningState()).thenReturn("Updating").thenReturn("Succeeded");

    //Test
    DefaultAzureArmNetworkCreator.createDefaultNetworkAndAddToTemplateOptionsIfRequired(computeService, configBag);

    //verify
    verify(subnetApi).createOrUpdate(eq(TEST_SUBNET_NAME), any());
    verify(subnetApi, atLeast(2)).get(TEST_SUBNET_NAME);
    verify(subnet).id();

    verify(resourceGroupApi).get(TEST_RESOURCE_GROUP);
    verify(resourceGroupApi, never()).create(any(), any(), any());

    verify(virtualNetworkApi, never()).createOrUpdate(any(), any(), any(), any());

    //verify templateOptions updated to include defaults
    Map<String, Object> templateOptions = configBag.get(TEMPLATE_OPTIONS);
    Map<String, Object> ipOptions = (Map<String, Object>) ((List)templateOptions.get("ipOptions")).iterator().next();
    assertEquals(ipOptions.get("subnet"), TEST_SUBNET_ID);
    assertEquals(ipOptions.get("allocateNewPublicIp"), true);
}
 
Example 10
Source File: DefaultAzureArmNetworkCreatorTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testVanillaWhereExistingResourceGroup() throws Exception {
    //Setup config bag
    ConfigBag configBag = ConfigBag.newInstance();
    configBag.put(CLOUD_REGION_ID, TEST_LOCATION);

    //Setup mocks
    when(subnetApi.get(TEST_SUBNET_NAME)).thenReturn(null).thenReturn(subnet); //null first time, subnet next
    when(resourceGroupApi.get(TEST_RESOURCE_GROUP)).thenReturn(resourceGroup);
    when(subnet.properties().provisioningState()).thenReturn("Updating").thenReturn("Succeeded");

    //Test
    DefaultAzureArmNetworkCreator.createDefaultNetworkAndAddToTemplateOptionsIfRequired(computeService, configBag);

    //verify
    verify(subnetApi, atLeast(2)).get(TEST_SUBNET_NAME);
    verify(subnet).id();

    verify(resourceGroupApi).get(TEST_RESOURCE_GROUP);
    verify(resourceGroupApi, never()).create(any(), any(), any());

    verify(virtualNetworkApi).createOrUpdate(eq(TEST_NETWORK_NAME), eq(TEST_LOCATION), any(), any());

    //verify templateOptions updated to include defaults
    Map<String, Object> templateOptions = configBag.get(TEMPLATE_OPTIONS);
    Map<String, Object> ipOptions = (Map<String, Object>) ((List)templateOptions.get("ipOptions")).iterator().next();
    assertEquals(ipOptions.get("subnet"), TEST_SUBNET_ID);
    assertEquals(ipOptions.get("allocateNewPublicIp"), true);
}
 
Example 11
Source File: LocationConfigUtilsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions=IllegalStateException.class)
public void testInvalidKeyData() throws Exception {
    ConfigBag config = ConfigBag.newInstance();
    config.put(LocationConfigKeys.PRIVATE_KEY_DATA, "mydata");
    
    LocationConfigUtils.OsCredential creds = LocationConfigUtils.getOsCredential(config).doKeyValidation(false);
    Assert.assertTrue(creds.hasKey());
    Assert.assertFalse(creds.getWarningMessages().isEmpty());
    
    creds.checkNoErrors();
}
 
Example 12
Source File: LocationConfigUtilsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public void testInfersPublicKeyFileFromPrivateKeyFile() throws Exception {
    ConfigBag config = ConfigBag.newInstance();
    config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE);
    
    String data = LocationConfigUtils.getOsCredential(config).getPublicKeyData();
    assertTrue(data != null && data.length() > 0);
}
 
Example 13
Source File: JcloudsMachineNamer.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected String generateNewIdOfLength(ConfigBag setup, int len) {

    // if it's azurecompute-arm it needs a different VM_NAME_ALLOWED_PATTERN
    String pattern = setup.get(CloudLocationConfig.VM_NAME_ALLOWED_CHARACTERS);
    if ((pattern == null || pattern == CloudLocationConfig.VM_NAME_ALLOWED_CHARACTERS.getDefaultValue()) &&
            "azurecompute-arm".equals(setup.peek(JcloudsLocationConfig.CLOUD_PROVIDER))) {
    setup.put(CloudLocationConfig.VM_NAME_ALLOWED_CHARACTERS, Identifiers.UPPER_CASE_ALPHA+Identifiers.LOWER_CASE_ALPHA+Identifiers.NUMERIC);
    }

    return super.generateNewIdOfLength(setup, len);
}
 
Example 14
Source File: LocationConfigUtilsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public void testPreferPublicKeyDataOverFileAndNoPrivateKeyRequired() throws Exception {
    ConfigBag config = ConfigBag.newInstance();
    config.put(LocationConfigKeys.PUBLIC_KEY_DATA, "mydata");
    config.put(LocationConfigKeys.PUBLIC_KEY_FILE, SSH_PUBLIC_KEY_FILE);
    config.put(LocationConfigKeys.PRIVATE_KEY_FILE, "");
    
    LocationConfigUtils.OsCredential creds = LocationConfigUtils.getOsCredential(config);
    String data = creds.getPublicKeyData();
    assertEquals(data, "mydata");
    Assert.assertNull(creds.getPreferredCredential());
    Assert.assertFalse(creds.hasPassword());
    Assert.assertFalse(creds.hasKey());
    // and not even any warnings here
    Assert.assertTrue(creds.getWarningMessages().isEmpty());
}
 
Example 15
Source File: SimpleEffectorInitializer.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static Effectors.EffectorBuilder<Void> newEffectorBuilder() {
    ConfigBag bag = ConfigBag.newInstance();
    bag.put(EFFECTOR_NAME, SimpleEffectorInitializer.class.getSimpleName());

    return AddEffector.newEffectorBuilder(Void.class, bag)
            .description("A bare-bones effector")
            .impl(new Body());
}
 
Example 16
Source File: LocationConfigUtilsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups="Integration")  // requires ~/.ssh/id_rsa
public void testReadsPrivateKeyFileWithTildePath() throws Exception {
    ConfigBag config = ConfigBag.newInstance();
    config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE_WITH_TILDE);

    // don't mind if it has a passphrase
    String data = LocationConfigUtils.getOsCredential(config).doKeyValidation(false).getPreferredCredential();
    assertTrue(data != null && data.length() > 0);
}
 
Example 17
Source File: JcloudsLocation.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void setHostnameUpdatingCredentials(ConfigBag setup, NodeMetadata metadata) {
    List<String> usersTried = new ArrayList<String>();

    String originalUser = getUser(setup);
    if (groovyTruth(originalUser)) {
        if (setHostname(setup, metadata, false)) return;
        usersTried.add(originalUser);
    }

    LoginCredentials credentials = metadata.getCredentials();
    if (credentials!=null) {
        if (Strings.isNonBlank(credentials.getUser())) setup.put(USER, credentials.getUser());
        if (Strings.isNonBlank(credentials.getOptionalPrivateKey().orNull())) setup.put(PRIVATE_KEY_DATA, credentials.getOptionalPrivateKey().orNull());
        if (setHostname(setup, metadata, false)) {
            if (originalUser!=null && !originalUser.equals(getUser(setup))) {
                LOG.warn("Switching to cloud-specified user at "+metadata+" as "+getUser(setup)+" (failed to connect using: "+usersTried+")");
            }
            return;
        }
        usersTried.add(getUser(setup));
    }

    for (String u: COMMON_USER_NAMES_TO_TRY) {
        setup.put(USER, u);
        if (setHostname(setup, metadata, false)) {
            LOG.warn("Auto-detected user at "+metadata+" as "+getUser(setup)+" (failed to connect using: "+usersTried+")");
            return;
        }
        usersTried.add(getUser(setup));
    }
    // just repeat, so we throw exception
    LOG.warn("Failed to log in to "+metadata+", tried as users "+usersTried+" (throwing original exception)");
    setup.put(USER, originalUser);
    setHostname(setup, metadata, true);
}
 
Example 18
Source File: JcloudsLocation.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts the user that jclouds tells us about (i.e. from the jclouds node).
 * <p>
 * Modifies <code>setup</code> to set {@link #USER} if it is unset when the method is called or
 * if the value in the bag is {@link #ROOT_USERNAME} and the user on the node is contained in
 * {@link #ROOT_ALIASES}.
 */
protected LoginCredentials extractVmCredentials(ConfigBag setup, NodeMetadata node, LoginCredentials nodeCredentials) {
    boolean windows = isWindows(node, setup);
    String user = getUser(setup);
    OsCredential localCredentials = LocationConfigUtils.getOsCredential(setup).checkNoErrors();
    
    LOG.debug("Credentials extracted for {}: {}/{} with {}/{}", new Object[] {
            node, user, nodeCredentials.getUser(), localCredentials, nodeCredentials });

    if (Strings.isNonBlank(nodeCredentials.getUser())) {
        if (Strings.isBlank(user)) {
            setup.put(USER, user = nodeCredentials.getUser());
        } else if (ROOT_USERNAME.equals(user) && ROOT_ALIASES.contains(nodeCredentials.getUser())) {
            // deprecated, we used to default username to 'root'; now we leave null, then use autodetected credentials if no user specified
            LOG.warn("overriding username 'root' in favour of '"+nodeCredentials.getUser()+"' at {}; this behaviour may be removed in future", node);
            setup.put(USER, user = nodeCredentials.getUser());
        }

        String pkd = Strings.maybeNonBlank(localCredentials.getPrivateKeyData())
                .or(nodeCredentials.getOptionalPrivateKey().orNull());
        String pwd = Strings.maybeNonBlank(localCredentials.getPassword())
                .or(nodeCredentials.getOptionalPassword().orNull());
        if (Strings.isBlank(user) || (Strings.isBlank(pkd) && pwd==null)) {
            String missing = (user==null ? "user" : "credential");
            LOG.warn("Not able to determine "+missing+" for "+this+" at "+node+"; will likely fail subsequently");
            return null;
        } else {
            LoginCredentials.Builder resultBuilder = LoginCredentials.builder().user(user);
            if (pwd != null && (Strings.isBlank(pkd) || localCredentials.isUsingPassword() || windows)) {
                resultBuilder.password(pwd);
            } else { // pkd guaranteed non-blank due to above
                resultBuilder.privateKey(pkd);
            }
            return resultBuilder.build();
        }
    }

    LOG.warn("No node-credentials or admin-access available for node "+node+" in "+this+"; will likely fail subsequently");
    return null;
}
 
Example 19
Source File: ConfigKeys.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** creates a new {@link ConfigKey} given a name (e.g. as a key in a larger map) and a map of other definition attributes */
public static ConfigKey<?> newNamedInstance(String name, Map<?,?> keyDefs) {
    ConfigBag defs = ConfigBag.newInstance(keyDefs);
    String oldName = defs.put(NAME, name);
    if (oldName!=null && !oldName.equals(name))
        log.warn("Dynamic key '"+oldName+"' being overridden as key '"+name+"' in "+keyDefs);
    return newInstance(defs);
}
 
Example 20
Source File: ByonLocationResolver.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
protected ConfigBag extractConfig(Map<?,?> locationFlags, String spec, LocationRegistry registry) {
    ConfigBag config = super.extractConfig(locationFlags, spec, registry);

    Object hosts = config.getStringKey("hosts");
    config.remove("hosts");
    String user = (String) config.getStringKey("user");
    Integer port = TypeCoercions.coerce(config.getStringKey("port"), Integer.class);
    Class<? extends MachineLocation> locationClass = getLocationClass(config.get(OS_FAMILY));

    MutableMap<String, Object> defaultProps = MutableMap.of();
    defaultProps.addIfNotNull("user", user);
    defaultProps.addIfNotNull("port", port);

    List<?> hostAddresses;
    
    if (hosts instanceof String) {
        if (((String) hosts).isEmpty()) {
            hostAddresses = ImmutableList.of();
        } else {
            hostAddresses = WildcardGlobs.getGlobsAfterBraceExpansion("{"+hosts+"}",
                    true /* numeric */, /* no quote support though */ PhraseTreatment.NOT_A_SPECIAL_CHAR, PhraseTreatment.NOT_A_SPECIAL_CHAR);
        }
    } else if (hosts instanceof Iterable) {
        hostAddresses = ImmutableList.copyOf((Iterable<?>)hosts);
    } else {
        throw new IllegalArgumentException("Invalid location '"+spec+"'; at least one host must be defined");
    }
    if (hostAddresses.isEmpty()) {
        throw new IllegalArgumentException("Invalid location '"+spec+"'; at least one host must be defined");
    }
    
    List<LocationSpec<? extends MachineLocation>> machineSpecs = Lists.newArrayList();
    for (Object host : hostAddresses) {
        LocationSpec<? extends MachineLocation> machineSpec;
        if (host instanceof String) {
            machineSpec = parseMachine((String)host, locationClass, defaultProps, spec);
        } else if (host instanceof Map) {
            machineSpec = parseMachine((Map<String, ?>)host, locationClass, defaultProps, spec);
        } else {
            throw new IllegalArgumentException("Expected machine to be String or Map, but was "+host.getClass().getName()+" ("+host+")");
        }
        machineSpec.configureIfNotNull(LocalLocationManager.CREATE_UNMANAGED, config.get(LocalLocationManager.CREATE_UNMANAGED));
        machineSpecs.add(machineSpec);
    }
    
    config.put(FixedListMachineProvisioningLocation.MACHINE_SPECS, machineSpecs);

    return config;
}