Search in sources :

Example 1 with JmxServerConnectionWrapper

use of org.opennms.netmgt.jmx.connection.JmxServerConnectionWrapper in project opennms by OpenNMS.

the class Jsr160ConnectionFactory method getMBeanServerConnection.

public static JmxServerConnectionWrapper getMBeanServerConnection(Map<String, String> propertiesMap, InetAddress address) throws IOException {
    final long timeout = DEFAULT_TIMEOUT;
    propertiesMap.putIfAbsent("factory", "STANDARD");
    propertiesMap.putIfAbsent("port", "1099");
    propertiesMap.putIfAbsent("protocol", "rmi");
    propertiesMap.putIfAbsent("urlPath", "/jmxrmi");
    propertiesMap.putIfAbsent("timeout", Long.toString(timeout));
    final Callable<JmxServerConnectionWrapper> task = new Callable<JmxServerConnectionWrapper>() {

        @Override
        public JmxServerConnectionWrapper call() throws Exception {
            return new DefaultJmxConnector().createConnection(address, propertiesMap);
        }
    };
    final Future<JmxServerConnectionWrapper> future = executor.submit(task);
    try {
        final JmxServerConnectionWrapper connectionWrapper = future.get(timeout, TimeUnit.MILLISECONDS);
        return connectionWrapper;
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        final String url = JmxConnectionConfigBuilder.buildFrom(address, propertiesMap).build().getUrl();
        LOG.info("Exception connecting JMXConnectorFactory url {} , Error: {}", url, e.getMessage());
        if (!future.isDone()) {
            future.cancel(true);
            LOG.info(" the task {}", future.isCancelled() ? "was cancelled" : "could not be cancelled");
        }
        throw new ConnectException("Error connecting JMXConnectionFactory  " + url);
    }
}
Also used : JmxServerConnectionWrapper(org.opennms.netmgt.jmx.connection.JmxServerConnectionWrapper) ExecutionException(java.util.concurrent.ExecutionException) Callable(java.util.concurrent.Callable) TimeoutException(java.util.concurrent.TimeoutException) ConnectException(java.net.ConnectException)

Example 2 with JmxServerConnectionWrapper

use of org.opennms.netmgt.jmx.connection.JmxServerConnectionWrapper in project opennms by OpenNMS.

the class PlatformMBeanServerConnector method createConnection.

public JmxServerConnectionWrapper createConnection() {
    final MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
    final JmxServerConnectionWrapper jmxConnectionWrapper = new JmxServerConnectionWrapper() {

        @Override
        public MBeanServerConnection getMBeanServerConnection() {
            return platformMBeanServer;
        }

        @Override
        public void close() {
        }
    };
    return jmxConnectionWrapper;
}
Also used : JmxServerConnectionWrapper(org.opennms.netmgt.jmx.connection.JmxServerConnectionWrapper) MBeanServer(javax.management.MBeanServer)

Example 3 with JmxServerConnectionWrapper

use of org.opennms.netmgt.jmx.connection.JmxServerConnectionWrapper in project opennms by OpenNMS.

the class DetectMBeansJob method execute.

@Override
public JmxDatacollectionConfig execute() throws JobManager.TaskRunException {
    final JmxConnectionConfig connectionConfig = new JmxConnectionConfigBuilder().withUrl(config.getConnection()).withUsername(config.getUser()).withPassword(config.getPassword()).build();
    try (JmxServerConnectionWrapper connector = new DefaultJmxConnector().createConnection(connectionConfig)) {
        final JmxDatacollectionConfiggenerator jmxConfigGenerator = new JmxDatacollectionConfiggenerator(new Slf4jLogAdapter(JmxDatacollectionConfiggenerator.class));
        final JmxDatacollectionConfig generatedJmxConfigModel = jmxConfigGenerator.generateJmxConfigModel(connector.getMBeanServerConnection(), "anyservice", !config.isSkipDefaultVM(), config.isSkipNonNumber(), JmxHelper.loadInternalDictionary());
        applyFilters(generatedJmxConfigModel);
        return generatedJmxConfigModel;
    } catch (IOException | MBeanServerQueryException | JMException | JmxServerConnectionException e) {
        if (e instanceof UnknownHostException || e.getCause() instanceof UnknownHostException) {
            throw new JobManager.TaskRunException(String.format("Unknown host: %s", config.getConnection()), e);
        }
        if (e instanceof MalformedURLException || e.getCause() instanceof MalformedURLException) {
            throw new JobManager.TaskRunException(String.format("Cannot create valid JMX Connection URL. Connection: '%s'", config.getConnection()), e);
        }
        throw new JobManager.TaskRunException("Error while retrieving MBeans from server.", e);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) UnknownHostException(java.net.UnknownHostException) Slf4jLogAdapter(org.opennms.features.jmxconfiggenerator.log.Slf4jLogAdapter) MBeanServerQueryException(org.opennms.features.jmxconfiggenerator.jmxconfig.query.MBeanServerQueryException) JmxDatacollectionConfig(org.opennms.xmlns.xsd.config.jmx_datacollection.JmxDatacollectionConfig) IOException(java.io.IOException) JmxConnectionConfig(org.opennms.netmgt.jmx.connection.JmxConnectionConfig) JmxServerConnectionException(org.opennms.netmgt.jmx.connection.JmxServerConnectionException) JmxDatacollectionConfiggenerator(org.opennms.features.jmxconfiggenerator.jmxconfig.JmxDatacollectionConfiggenerator) DefaultJmxConnector(org.opennms.netmgt.jmx.impl.connection.connectors.DefaultJmxConnector) JMException(javax.management.JMException) JmxServerConnectionWrapper(org.opennms.netmgt.jmx.connection.JmxServerConnectionWrapper) JmxConnectionConfigBuilder(org.opennms.netmgt.jmx.connection.JmxConnectionConfigBuilder)

Example 4 with JmxServerConnectionWrapper

use of org.opennms.netmgt.jmx.connection.JmxServerConnectionWrapper in project opennms by OpenNMS.

the class JMXMonitor method poll.

/**
     * {@inheritDoc}
     */
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> map) {
    final InetAddress ipv4Addr = svc.getAddress();
    PollStatus serviceStatus = PollStatus.unavailable();
    try {
        final Timer timer = new Timer();
        final JmxConnectionManager connectionManager = new DefaultConnectionManager(ParameterMap.getKeyedInteger(map, "retry", 3));
        final JmxConnectionManager.RetryCallback retryCallback = new JmxConnectionManager.RetryCallback() {

            @Override
            public void onRetry() {
                timer.reset();
            }
        };
        try (JmxServerConnectionWrapper connection = connectionManager.connect(getConnectionName(), ipv4Addr, JmxUtils.convertToStringMap(map), retryCallback)) {
            // Start with simple communication
            connection.getMBeanServerConnection().getMBeanCount();
            // Take time just here to get not influenced by test execution
            // time
            final long nanoResponseTime = System.nanoTime() - timer.getStartTime();
            // Find all variable definitions
            final Map<String, Object> variables = Maps.newHashMap();
            for (final String key : map.keySet()) {
                // Skip fast if it does not start with the prefix
                if (!key.startsWith(PARAM_BEAN_PREFIX)) {
                    continue;
                }
                // Get the variable name
                final String variable = key.substring(PARAM_BEAN_PREFIX.length());
                // Get the variable definition
                final String definition = ParameterMap.getKeyedString(map, key, null);
                // Store wrapper for variable definition
                variables.put(variable, ObjectNameWrapper.create(connection.getMBeanServerConnection(), definition));
            }
            // Find all test definitions
            final Map<String, Expression> tests = Maps.newHashMap();
            for (final String key : map.keySet()) {
                // Skip fast if it does not start with the prefix
                if (!key.startsWith(PARAM_TEST_PREFIX)) {
                    continue;
                }
                // Get the test name
                final String variable = key.substring(PARAM_TEST_PREFIX.length());
                // Get the test definition
                final String definition = ParameterMap.getKeyedString(map, key, null);
                // Build the expression from the definition
                final Expression expression = JEXL_ENGINE.createExpression(definition);
                // Store expressions
                tests.put(variable, expression);
            }
            // Also handle a single test
            if (map.containsKey(PARAM_TEST)) {
                // Get the test definition
                final String definition = ParameterMap.getKeyedString(map, PARAM_TEST, null);
                // Build the expression from the definition
                final Expression expression = JEXL_ENGINE.createExpression(definition);
                // Store expressions
                tests.put(null, expression);
            }
            // Build the context for all tests
            final JexlContext context = new ReadonlyContext(new MapContext(variables));
            serviceStatus = PollStatus.up(nanoResponseTime / 1000000.0);
            // Execute all tests
            for (final Map.Entry<String, Expression> e : tests.entrySet()) {
                if (!(boolean) e.getValue().evaluate(context)) {
                    serviceStatus = PollStatus.down("Test failed: " + e.getKey());
                    break;
                }
            }
        } catch (JmxServerConnectionException mbse) {
            // Number of retries exceeded
            String reason = "IOException while polling address: " + ipv4Addr;
            LOG.debug(reason);
            serviceStatus = PollStatus.unavailable(reason);
        }
    } catch (Throwable e) {
        String reason = "Monitor - failed! " + InetAddressUtils.str(ipv4Addr);
        LOG.debug(reason);
        serviceStatus = PollStatus.unavailable(reason);
    }
    return serviceStatus;
}
Also used : PollStatus(org.opennms.netmgt.poller.PollStatus) DefaultConnectionManager(org.opennms.netmgt.jmx.impl.connection.connectors.DefaultConnectionManager) JmxConnectionManager(org.opennms.netmgt.jmx.connection.JmxConnectionManager) ReadonlyContext(org.apache.commons.jexl2.ReadonlyContext) MapContext(org.apache.commons.jexl2.MapContext) JmxServerConnectionException(org.opennms.netmgt.jmx.connection.JmxServerConnectionException) Expression(org.apache.commons.jexl2.Expression) JexlContext(org.apache.commons.jexl2.JexlContext) JmxServerConnectionWrapper(org.opennms.netmgt.jmx.connection.JmxServerConnectionWrapper) InetAddress(java.net.InetAddress) HashMap(java.util.HashMap) Map(java.util.Map) ParameterMap(org.opennms.core.utils.ParameterMap)

Example 5 with JmxServerConnectionWrapper

use of org.opennms.netmgt.jmx.connection.JmxServerConnectionWrapper in project opennms by OpenNMS.

the class DefaultJmxCollector method collect.

@Override
public void collect(JmxCollectorConfig config, MBeanServer mBeanServer, JmxSampleProcessor sampleProcessor) throws JmxServerConnectionException {
    Map<String, String> mergedStringMap = new HashMap<>(config.getServiceProperties());
    if (mBeanServer != null) {
        mergedStringMap.putAll(mBeanServer.getParameterMap());
    }
    JmxConnectionManager connectionManager = new DefaultConnectionManager(config.getRetries());
    try (JmxServerConnectionWrapper connectionWrapper = connectionManager.connect(config.getConnectionName(), InetAddressUtils.addr(config.getAgentAddress()), mergedStringMap, null)) {
        Objects.requireNonNull(connectionWrapper, "connectionWrapper should never be null");
        Objects.requireNonNull(connectionWrapper.getMBeanServerConnection(), "connectionWrapper.getMBeanServerConnection() should never be null");
        final MBeanServerConnection concreteConnection = connectionWrapper.getMBeanServerConnection();
        collect(concreteConnection, config.getJmxCollection(), sampleProcessor);
    }
}
Also used : HashMap(java.util.HashMap) DefaultConnectionManager(org.opennms.netmgt.jmx.impl.connection.connectors.DefaultConnectionManager) JmxConnectionManager(org.opennms.netmgt.jmx.connection.JmxConnectionManager) JmxServerConnectionWrapper(org.opennms.netmgt.jmx.connection.JmxServerConnectionWrapper) MBeanServerConnection(javax.management.MBeanServerConnection)

Aggregations

JmxServerConnectionWrapper (org.opennms.netmgt.jmx.connection.JmxServerConnectionWrapper)8 JmxServerConnectionException (org.opennms.netmgt.jmx.connection.JmxServerConnectionException)4 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 ConnectException (java.net.ConnectException)2 MalformedURLException (java.net.MalformedURLException)2 MBeanServerConnection (javax.management.MBeanServerConnection)2 JmxConnectionManager (org.opennms.netmgt.jmx.connection.JmxConnectionManager)2 DefaultConnectionManager (org.opennms.netmgt.jmx.impl.connection.connectors.DefaultConnectionManager)2 InterruptedIOException (java.io.InterruptedIOException)1 InetAddress (java.net.InetAddress)1 NoRouteToHostException (java.net.NoRouteToHostException)1 PortUnreachableException (java.net.PortUnreachableException)1 UnknownHostException (java.net.UnknownHostException)1 Map (java.util.Map)1 Callable (java.util.concurrent.Callable)1 ExecutionException (java.util.concurrent.ExecutionException)1 TimeoutException (java.util.concurrent.TimeoutException)1 InstanceNotFoundException (javax.management.InstanceNotFoundException)1 JMException (javax.management.JMException)1