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

The following examples show how to use org.apache.brooklyn.util.core.config.ConfigBag#configure() . 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: ProcessToolIntegrationTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups="Integration")
public void testLoginShell() {
    // this detection scheme only works for commands; can't test whether it works for scripts without 
    // requiring stuff in bash_profile / profile / etc, which gets hard to make portable;
    // it is nearly the same code path on the impl so this is probably enough 
    
    final String LOGIN_SHELL_CHECK = "shopt -q login_shell && echo 'yes, login shell' || echo 'no, not login shell'";
    ConfigBag config = ConfigBag.newInstance().configure(ProcessTool.PROP_NO_EXTRA_OUTPUT, true);
    String out;
    
    out = execCommands(config, Arrays.asList(LOGIN_SHELL_CHECK), null);
    Assert.assertEquals(out.trim(), "no, not login shell", "out = "+out);
    
    config.configure(ProcessTool.PROP_LOGIN_SHELL, true);
    out = execCommands(config, Arrays.asList(LOGIN_SHELL_CHECK), null);
    Assert.assertEquals(out.trim(), "yes, login shell", "out = "+out);
}
 
Example 2
Source File: DockerJcloudsLocation.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected MachineLocation obtainOnce(ConfigBag setup) throws NoMachinesAvailableException {
    // Use the provider name that jclouds expects; rely on resolver to have validated this.
    setup.configure(JcloudsLocation.CLOUD_PROVIDER, "docker");

    // Inject default image, if absent
    String imageId = setup.get(JcloudsLocation.IMAGE_ID);
    String imageNameRegex = setup.get(JcloudsLocation.IMAGE_NAME_REGEX);
    String imageDescriptionRegex = setup.get(JcloudsLocation.IMAGE_DESCRIPTION_REGEX);
    String defaultImageDescriptionRegex = setup.get(DEFAULT_IMAGE_DESCRIPTION_REGEX);
    OsFamily osFamily = setup.get(OS_FAMILY);
    String osVersionRegex = setup.get(OS_VERSION_REGEX);

    if (Strings.isBlank(imageId) && Strings.isBlank(imageNameRegex) && Strings.isBlank(imageDescriptionRegex)) {
        if (osFamily != null || osVersionRegex != null) {
            for (ImageMetadata imageMetadata : DEFAULT_IMAGES) {
                if (imageMetadata.matches(osFamily, osVersionRegex)) {
                    String imageDescription = imageMetadata.getImageDescription();
                    LOG.debug("Setting default image regex to {}, for obtain call in {}; removing osFamily={} and osVersionRegex={}",
                            new Object[]{imageDescription, this, osFamily, osVersionRegex});
                    setup.configure(JcloudsLocation.IMAGE_DESCRIPTION_REGEX, imageDescription);
                    setup.configure(OS_FAMILY, null);
                    setup.configure(OS_VERSION_REGEX, null);
                    break;
                }
            }
        } else if (Strings.isNonBlank(defaultImageDescriptionRegex)) {
            LOG.debug("Setting default image regex to {}, for obtain call in {}", defaultImageDescriptionRegex, this);
            setup.configure(JcloudsLocation.IMAGE_DESCRIPTION_REGEX, defaultImageDescriptionRegex);
        }
    }

    return super.obtainOnce(setup);
}
 
Example 3
Source File: KubernetesLocation.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the {@code BROOKLYN_ROOT_PASSWORD} variable in the container environment if appropriate.
 * This is (approximately) the same behaviour as the {@link DockerJcloudsLocation} used for
 * Swarm.
 * <p>
 * Side-effects the location {@code config} to set the {@link KubernetesLocationConfig#LOGIN_USER_PASSWORD loginUser.password}
 * if one is auto-generated. Note that this injected value overrides any other settings configured for the
 * container environment.
 */
protected Map<String, String> findEnvironmentVariables(Entity entity, ConfigBag setup, String imageName) {
    String loginUser = setup.get(LOGIN_USER);
    String loginPassword = setup.get(LOGIN_USER_PASSWORD);
    Map<String, String> injections = Maps.newLinkedHashMap();

    // Check if login credentials should be injected
    Boolean injectLoginCredentials = setup.get(INJECT_LOGIN_CREDENTIAL);
    if (injectLoginCredentials == null) {
        for (String regex : IMAGE_DESCRIPTION_REGEXES_REQUIRING_INJECTED_LOGIN_CREDS) {
            if (imageName != null && imageName.matches(regex)) {
                injectLoginCredentials = true;
                break;
            }
        }
    }

    if (Boolean.TRUE.equals(injectLoginCredentials)) {
        if ((Strings.isBlank(loginUser) || "root".equals(loginUser))) {
            loginUser = "root";
            setup.configure(LOGIN_USER, loginUser);

            if (Strings.isBlank(loginPassword)) {
                loginPassword = Identifiers.makeRandomPassword(12);
                setup.configure(LOGIN_USER_PASSWORD, loginPassword);
            }

            injections.put(BROOKLYN_ROOT_PASSWORD, loginPassword);
        }
    }

    Map<String, Object> rawEnv = MutableMap.<String, Object>builder()
            .putAll(MutableMap.copyOf(setup.get(ENV)))
            .putAll(MutableMap.copyOf(entity.config().get(DockerContainer.CONTAINER_ENVIRONMENT)))
            .putAll(injections)
            .build();
    return Maps.transformValues(rawEnv, Functions.toStringFunction());
}
 
Example 4
Source File: AddEffector.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** returns a ConfigBag containing the merger of the supplied parameters with default values on the effector-defined parameters */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static ConfigBag getMergedParams(Effector<?> eff, ConfigBag params) {
    ConfigBag result = ConfigBag.newInstanceCopying(params);
    for (ParameterType<?> param: eff.getParameters()) {
        ConfigKey key = Effectors.asConfigKey(param);
        if (!result.containsKey(key))
            result.configure(key, params.get(key));
    }
    return result;
}
 
Example 5
Source File: CouchbaseNodeImpl.java    From brooklyn-library with Apache License 2.0 4 votes vote down vote up
@Override
protected Map<String, Object> obtainProvisioningFlags(@SuppressWarnings("rawtypes") MachineProvisioningLocation location) {
    ConfigBag result = ConfigBag.newInstance(super.obtainProvisioningFlags(location));
    result.configure(CloudLocationConfig.OS_64_BIT, true);
    return result.getAllConfig();
}
 
Example 6
Source File: RiakNodeImpl.java    From brooklyn-library with Apache License 2.0 4 votes vote down vote up
@Override
protected Map<String, Object> obtainProvisioningFlags(@SuppressWarnings("rawtypes") MachineProvisioningLocation location) {
    ConfigBag result = ConfigBag.newInstance(super.obtainProvisioningFlags(location));
    result.configure(CloudLocationConfig.OS_64_BIT, true);
    return result.getAllConfig();
}
 
Example 7
Source File: WinRmMachineLocation.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
protected WinRmTool newWinRmTool(Map<?,?> props) {
    // TODO See comments/TODOs in SshMachineLocation.connectSsh()
    try {
        ConfigBag args = new ConfigBag();

        for (Map.Entry<ConfigKey<?>, ?> entry: config().getBag().getAllConfigAsConfigKeyMap().entrySet()) {

            boolean include = false;
            String keyName = entry.getKey().getName();
            if (keyName.startsWith(WinRmTool.BROOKLYN_CONFIG_KEY_PREFIX)) {
                keyName = Strings.removeFromStart(keyName, WinRmTool.BROOKLYN_CONFIG_KEY_PREFIX);
                include = true;
            }
            
            if (keyName.startsWith(WINRM_TOOL_CLASS_PROPERTIES_PREFIX)) {
                keyName = Strings.removeFromStart(keyName, WINRM_TOOL_CLASS_PROPERTIES_PREFIX);
                include = true;
            }
            
            if (ALL_WINRM_CONFIG_KEY_NAMES.contains(keyName)) {
                // key should be included, and does not need to be changed

                // TODO make this config-setting mechanism more universal
                // currently e.g. it will not admit a tool-specific property.
                // thinking either we know about the tool here,
                // or we don't allow unadorned keys to be set
                // (require use of BROOKLYN_CONFIG_KEY_PREFIX)
                include = true;
            }

            if (include) {
                args.putStringKey(keyName, config().get(entry.getKey()));
            }
        }
        
        args.putAll(props);
        args.configure(SshTool.PROP_HOST, getAddress().getHostAddress());
        args.configure(WinRmTool.USE_NTLM, getConfig(WinRmMachineLocation.USE_NTLM));
        args.configure(WinRmTool.PROP_PORT, getPort());

        if (LOG.isTraceEnabled()) LOG.trace("creating WinRM session for "+Sanitizer.sanitize(args));

        // look up tool class
        String toolClass = args.get(WINRM_TOOL_CLASS);
        if (toolClass == null) toolClass = Winrm4jTool.class.getName();
        WinRmTool tool = (WinRmTool) new ClassLoaderUtils(this, getManagementContext()).loadClass(toolClass).getConstructor(Map.class).newInstance(args.getAllConfig());
        if (tool instanceof ManagementContextInjectable) {
            ((ManagementContextInjectable)tool).setManagementContext(getManagementContext());
        }

        if (LOG.isTraceEnabled()) LOG.trace("using ssh-tool {} (of type {}); props ", tool, toolClass);

        return tool;
    } catch (Exception e) {
        throw Exceptions.propagate(e);
    }
}
 
Example 8
Source File: ExecWithLoggingHelpers.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public int execWithLogging(Map<String,?> props, final String summaryForLogging, final List<String> commands,
        final Map<String,?> env, String expectedCommandHeaders, final ExecRunner execCommand) {
    if (commandLogger!=null && commandLogger.isDebugEnabled()) {
        String allcmds = (Strings.isBlank(expectedCommandHeaders) ? "" : expectedCommandHeaders + " ; ") + Strings.join(commands, " ; ");
        commandLogger.debug("{}, initiating "+shortName.toLowerCase()+" on machine {}{}: {}",
                new Object[] {summaryForLogging, getTargetName(),
                env!=null && !env.isEmpty() ? " (env "+Sanitizer.sanitize(env)+")": "", allcmds});
    }

    if (commands.isEmpty()) {
        if (commandLogger!=null && commandLogger.isDebugEnabled())
            commandLogger.debug("{}, on machine {}, ending: no commands to run", summaryForLogging, getTargetName());
        return 0;
    }

    final ConfigBag execFlags = new ConfigBag().putAll(props);
    // some props get overridden in execFlags, so remove them from the tool flags
    final ConfigBag toolFlags = new ConfigBag().putAll(props).removeAll(
            LOG_PREFIX, STDOUT, STDERR, ShellTool.PROP_NO_EXTRA_OUTPUT);

    execFlags.configure(ShellTool.PROP_SUMMARY, summaryForLogging);
    
    preExecChecks();
    
    String logPrefix = execFlags.get(LOG_PREFIX);
    if (logPrefix==null) logPrefix = constructDefaultLoggingPrefix(execFlags);

    if (!execFlags.get(NO_STDOUT_LOGGING)) {
        String stdoutLogPrefix = "["+(logPrefix != null ? logPrefix+":stdout" : "stdout")+"] ";
        OutputStream outO = LoggingOutputStream.builder()
                .outputStream(execFlags.get(STDOUT))
                .logger(commandLogger)
                .logPrefix(stdoutLogPrefix)
                .build();

        execFlags.put(STDOUT, outO);
    }

    if (!execFlags.get(NO_STDERR_LOGGING)) {
        String stderrLogPrefix = "["+(logPrefix != null ? logPrefix+":stderr" : "stderr")+"] ";
        OutputStream outE = LoggingOutputStream.builder()
                .outputStream(execFlags.get(STDERR))
                .logger(commandLogger)
                .logPrefix(stderrLogPrefix)
                .build();
        execFlags.put(STDERR, outE);
    }

    Tasks.setBlockingDetails(shortName+" executing, "+summaryForLogging);
    try {
        return execWithTool(MutableMap.copyOf(toolFlags.getAllConfig()), new Function<ShellTool, Integer>() {
            @Override
            public Integer apply(ShellTool tool) {
                int result = execCommand.exec(tool, MutableMap.copyOf(execFlags.getAllConfig()), commands, env);
                if (commandLogger!=null && commandLogger.isDebugEnabled()) 
                    commandLogger.debug("{}, on machine {}, completed: return status {}",
                            new Object[] {summaryForLogging, getTargetName(), result});
                return result;
            }});

    } finally {
        Tasks.setBlockingDetails(null);
    }
}