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

The following examples show how to use org.apache.brooklyn.util.core.config.ConfigBag#putStringKey() . 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: JcloudsLocation.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected ConfigBag extractWinrmConfig(ConfigBag setup, ConfigBag alt) {
    ConfigBag winrmConfig = new ConfigBag();
    
    for (HasConfigKey<?> key : WinRmMachineLocation.ALL_WINRM_CONFIG_KEYS) {
        String keyName = key.getConfigKey().getName();
        if (setup.containsKey(keyName)) {
            winrmConfig.putStringKey(keyName, setup.getStringKey(keyName));
        } else if (alt.containsKey(keyName)) {
            winrmConfig.putStringKey(keyName, setup.getStringKey(keyName));
        }
    }
    
    Map<String, Object> winrmToolClassProperties = Maps.filterKeys(setup.getAllConfig(), StringPredicates.startsWith(WinRmMachineLocation.WINRM_TOOL_CLASS_PROPERTIES_PREFIX));
    winrmConfig.putAll(winrmToolClassProperties);
    
    return winrmConfig;
}
 
Example 2
Source File: SshCommandSensor.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public String get() {
    // Note that entity may be null during rebind (e.g. if this SshFeed is orphaned, with no associated entity):
    // See https://issues.apache.org/jira/browse/BROOKLYN-568.
    // We therefore guard against null in makeCommandExecutingInDirectory.
    ConfigBag params = ConfigBag.newInstance();
    if (rawSensorCommand != null) {
        params.putStringKey(SENSOR_COMMAND.getName(), rawSensorCommand);
    }
    if (rawSensorExecDir != null) {
        params.putStringKey(SENSOR_EXECUTION_DIR.getName(), rawSensorExecDir);
    }
    String command = Preconditions.checkNotNull(EntityInitializers.resolve(params, SENSOR_COMMAND));
    String dir = EntityInitializers.resolve(params, SENSOR_EXECUTION_DIR);
    return makeCommandExecutingInDirectory(command, dir, entity);
}
 
Example 3
Source File: JcloudsLocation.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected void logAvailableTemplates(ConfigBag config) {
    LOG.info("Loading available images at "+this+" for reference...");
    ConfigBag m1 = ConfigBag.newInstanceCopying(config);
    if (m1.containsKey(IMAGE_ID)) {
        // if caller specified an image ID, remove that, but don't apply default filters
        m1.remove(IMAGE_ID);
        // TODO use key
        m1.putStringKey("anyOwner", true);
    }
    ComputeService computeServiceLessRestrictive = getComputeService(m1);
    Set<? extends Image> imgs = computeServiceLessRestrictive.listImages();
    LOG.info(""+imgs.size()+" available images at "+this);
    for (Image img: imgs) {
        LOG.info(" Image: "+img);
    }

    Set<? extends Hardware> profiles = computeServiceLessRestrictive.listHardwareProfiles();
    LOG.info(""+profiles.size()+" available profiles at "+this);
    for (Hardware profile: profiles) {
        LOG.info(" Profile: "+profile);
    }

    Set<? extends org.jclouds.domain.Location> assignableLocations = computeServiceLessRestrictive.listAssignableLocations();
    LOG.info(""+assignableLocations.size()+" available locations at "+this);
    for (org.jclouds.domain.Location assignableLocation: assignableLocations) {
        LOG.info(" Location: "+assignableLocation);
    }
}
 
Example 4
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 5
Source File: JcloudsLocationReachabilityPredicateInstantiationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testInitMapConstructorWithFlags() {
    ConfigBag predicateConfig = new ConfigBag();
    predicateConfig.put(CloudLocationConfig.POLL_FOR_FIRST_REACHABLE_ADDRESS_PREDICATE_TYPE, RecordingReachabilityCheckMapAndFlagsConstructor.class);
    List<String> hostsMatchedHolder = new ArrayList<>();
    predicateConfig.putStringKey(CloudLocationConfig.POLL_FOR_FIRST_REACHABLE_ADDRESS_PREDICATE.getName() + ".hostsMatchedHolder", hostsMatchedHolder);
    jcloudsLocation.getFirstReachableAddress(node, predicateConfig);
    Assert.assertTrue(hostsMatchedHolder.contains(ALLOWED_HOST_AND_PORT.getHostText()));
}
 
Example 6
Source File: AbstractCloudMachineProvisioningLocation.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected ConfigBag extractSshConfig(ConfigBag setup, ConfigBag alt) {
    ConfigBag sshConfig = new ConfigBag();
    
    for (HasConfigKey<?> key : SshMachineLocation.ALL_SSH_CONFIG_KEYS) {
        String keyName = key.getConfigKey().getName();
        if (setup.containsKey(keyName)) {
            sshConfig.putStringKey(keyName, setup.getStringKey(keyName));
        } else if (alt.containsKey(keyName)) {
            sshConfig.putStringKey(keyName, setup.getStringKey(keyName));
        }
    }
    
    Map<String, Object> sshToolClassProperties = Maps.filterKeys(setup.getAllConfig(), StringPredicates.startsWith(SshMachineLocation.SSH_TOOL_CLASS_PROPERTIES_PREFIX));
    sshConfig.putAll(sshToolClassProperties);

    // Special cases (preserving old code!)
    if (setup.containsKey(PASSWORD)) {
        sshConfig.copyKeyAs(setup, PASSWORD, SshTool.PROP_PASSWORD);
    } else if (alt.containsKey(PASSWORD)) {
        sshConfig.copyKeyAs(alt, PASSWORD, SshTool.PROP_PASSWORD);
    }
    
    if (setup.containsKey(PRIVATE_KEY_DATA)) {
        sshConfig.copyKeyAs(setup, PRIVATE_KEY_DATA, SshTool.PROP_PRIVATE_KEY_DATA);
    } else if (setup.containsKey(PRIVATE_KEY_FILE)) {
        sshConfig.copyKeyAs(setup, PRIVATE_KEY_FILE, SshTool.PROP_PRIVATE_KEY_FILE);
    } else if (alt.containsKey(PRIVATE_KEY_DATA)) {
        sshConfig.copyKeyAs(setup, PRIVATE_KEY_DATA, SshTool.PROP_PRIVATE_KEY_DATA);
    }
    
    if (setup.containsKey(PRIVATE_KEY_PASSPHRASE)) {
        // NB: not supported in jclouds (but it is by our ssh tool)
        sshConfig.copyKeyAs(setup, PRIVATE_KEY_PASSPHRASE, SshTool.PROP_PRIVATE_KEY_PASSPHRASE);
    }

    return sshConfig;
}
 
Example 7
Source File: JcloudsLocation.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
protected JcloudsMachineLocation registerMachine(Map<?, ?> flags, NodeMetadata metadata) throws NoMachinesAvailableException {
    ConfigBag setup = ConfigBag.newInstanceExtending(config().getBag(), flags);
    if (!setup.containsKey("id")) setup.putStringKey("id", metadata.getId());
    setHostnameUpdatingCredentials(setup, metadata);
    return registerMachine(setup);
}
 
Example 8
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 9
Source File: SshMachineLocation.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
protected SshTool connectSsh(Map<?,?> props) {
    try {
        if (!groovyTruth(user)) {
            String newUser = getUser();
            if (LOG.isTraceEnabled()) LOG.trace("For "+this+", setting user in connectSsh: oldUser="+user+"; newUser="+newUser);
            user = newUser;
        }

        ConfigBag args = new ConfigBag()
            .configure(SshTool.PROP_USER, user)
            // default value of host, overridden if SSH_HOST is supplied
            .configure(SshTool.PROP_HOST, address.getHostName());

        for (Map.Entry<ConfigKey<?>, ?> entry: config().getBag().getAllConfigAsConfigKeyMap().entrySet()) {
            boolean include = false;
            String keyName = entry.getKey().getName();
            if (keyName.startsWith(SshTool.BROOKLYN_CONFIG_KEY_PREFIX)) {
                keyName = Strings.removeFromStart(keyName, SshTool.BROOKLYN_CONFIG_KEY_PREFIX);
                include = true;
            }
            
            if (keyName.startsWith(SSH_TOOL_CLASS_PROPERTIES_PREFIX)) {
                keyName = Strings.removeFromStart(keyName, SSH_TOOL_CLASS_PROPERTIES_PREFIX);
                include = true;
            }
            
            if (ALL_SSH_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()));
            }
        }

        // Explicit props trump all.
        args.putAll(props);

        if (LOG.isTraceEnabled()) LOG.trace("creating ssh session for "+Sanitizer.sanitize(args));
        if (!user.equals(args.get(SshTool.PROP_USER))) {
            LOG.warn("User mismatch configuring ssh for "+this+": preferring user "+args.get(SshTool.PROP_USER)+" over "+user);
            user = args.get(SshTool.PROP_USER);
        }

        // look up tool class
        String sshToolClass = args.get(SSH_TOOL_CLASS);
        String legacySshToolClass = args.get(SshTool.PROP_TOOL_CLASS);
        if (Strings.isNonBlank(legacySshToolClass)) {
            String msg;
            if (Strings.isNonBlank(sshToolClass)) {
                msg = "Ignoring deprecated config "+SshTool.PROP_TOOL_CLASS.getName()+"="+legacySshToolClass
                        +", preferring "+SSH_TOOL_CLASS.getName()+"="+sshToolClass+" for "+SshMachineLocation.this;
                
            } else {
                sshToolClass = legacySshToolClass;
                msg = "Using deprecated config "+SshTool.PROP_TOOL_CLASS.getName()+"="+legacySshToolClass
                        +", preferring "+SSH_TOOL_CLASS.getName()+"="+sshToolClass+" for "+SshMachineLocation.this;
            }
            if (!loggedLegcySshToolClassConfig) {
                LOG.warn(msg);
                loggedLegcySshToolClassConfig = true;
            }
        }
        if (sshToolClass==null) sshToolClass = SshjTool.class.getName();
        SshTool ssh = (SshTool) new ClassLoaderUtils(this, getManagementContext()).loadClass(sshToolClass).getConstructor(Map.class).newInstance(args.getAllConfig());

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

        Tasks.setBlockingDetails("Opening ssh connection");
        try { ssh.connect(); } finally { Tasks.setBlockingDetails(null); }
        previouslyConnected = true;
        return ssh;
    } catch (Exception e) {
        if (previouslyConnected) throw Throwables.propagate(e);
        // subsequence connection (above) most likely network failure, our remarks below won't help
        // on first connection include additional information if we can't connect, to help with debugging
        String rootCause = Throwables.getRootCause(e).getMessage();
        throw new IllegalStateException("Cannot establish ssh connection to "+user+" @ "+this+
                (rootCause!=null && !rootCause.isEmpty() ? " ("+rootCause+")" : "")+". \n"+
                "Ensure that passwordless and passphraseless ssh access is enabled using standard keys from ~/.ssh or " +
                "as configured in brooklyn.properties. " +
                "Check that the target host is accessible, " +
                "that credentials are correct (location and permissions if using a key), " +
                "that the SFTP subsystem is available on the remote side, " +
                "and that there is sufficient random noise in /dev/random on both ends. " +
                "To debug less common causes, see the original error in the trace or log, and/or enable 'net.schmizz' (sshj) logging."
                , e);
    }
}