Search in sources :

Example 56 with MBeanServerConnection

use of javax.management.MBeanServerConnection in project voldemort by voldemort.

the class AbstractFailureDetectorTest method assertJmxEquals.

protected void assertJmxEquals(String attributeName, Object attributeValue) throws Exception {
    JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(new JMXServiceURL("service:jmx:rmi://"), null, ManagementFactory.getPlatformMBeanServer());
    cs.start();
    JMXConnector cc = null;
    try {
        cc = JMXConnectorFactory.connect(cs.getAddress());
        MBeanServerConnection mbsc = cc.getMBeanServerConnection();
        ObjectName objectName = JmxUtils.createObjectName(JmxUtils.getPackageName(failureDetector.getClass()), failureDetector.getClass().getSimpleName());
        Object availableNodes = mbsc.getAttribute(objectName, attributeName);
        assertEquals(attributeValue, availableNodes);
    } finally {
        if (cc != null)
            cc.close();
        cs.stop();
    }
}
Also used : JMXServiceURL(javax.management.remote.JMXServiceURL) JMXConnector(javax.management.remote.JMXConnector) MBeanServerConnection(javax.management.MBeanServerConnection) JMXConnectorServer(javax.management.remote.JMXConnectorServer) ObjectName(javax.management.ObjectName)

Example 57 with MBeanServerConnection

use of javax.management.MBeanServerConnection in project jdk8u_jdk by JetBrains.

the class ScanDirClient method main.

/**
     * Connects to a secured JMX <i>scandir</i> application.
     * @param args The {@code main} method takes two parameters:
     *        <ul>
     *        <li>args[0] must be the server's host</li>
     *        <li>args[1] must be the rmi port number at which the
     *        JMX <i>scandir</i> daemon is listening for connections
     *        - that is, the port number of its JMX RMI Connector which
     *        was configured in {@code management.properties}
     *        </li>
     *        <ul>
     **/
public static void main(String[] args) {
    try {
        //
        if (args == null || args.length != 2) {
            System.err.println("Bad number of arguments: usage is: \n\t" + USAGE);
            System.exit(1);
        }
        try {
            InetAddress.getByName(args[0]);
        } catch (UnknownHostException x) {
            System.err.println("No such host: " + args[0] + "\n usage is: \n\t" + USAGE);
            System.exit(2);
        } catch (Exception x) {
            System.err.println("Bad address: " + args[0] + "\n usage is: \n\t" + USAGE);
            System.exit(2);
        }
        try {
            if (Integer.parseInt(args[1]) <= 0) {
                System.err.println("Bad port value: " + args[1] + "\n usage is: \n\t" + USAGE);
                System.exit(2);
            }
        } catch (Exception x) {
            System.err.println("Bad argument: " + args[1] + "\n usage is: \n\t" + USAGE);
            System.exit(2);
        }
        // Create an environment map to hold connection properties
        // like credentials etc... We will later pass this map
        // to the JMX Connector.
        //
        System.out.println("\nInitialize the environment map");
        final Map<String, Object> env = new HashMap<String, Object>();
        // Provide the credentials required by the server
        // to successfully perform user authentication
        //
        final String[] credentials = new String[] { "guest", "guestpasswd" };
        env.put("jmx.remote.credentials", credentials);
        // Provide the SSL/TLS-based RMI Client Socket Factory required
        // by the JNDI/RMI Registry Service Provider to communicate with
        // the SSL/TLS-protected RMI Registry
        //
        env.put("com.sun.jndi.rmi.factory.socket", new SslRMIClientSocketFactory());
        // Create the RMI connector client and
        // connect it to the RMI connector server
        // args[0] is the server's host - localhost
        // args[1] is the secure server port - 4545
        //
        System.out.println("\nCreate the RMI connector client and " + "connect it to the RMI connector server");
        final JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + args[0] + ":" + args[1] + "/jmxrmi");
        System.out.println("Connecting to: " + url);
        final JMXConnector jmxc = JMXConnectorFactory.connect(url, env);
        // Get an MBeanServerConnection
        //
        System.out.println("\nGet the MBeanServerConnection");
        final MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
        // Create a proxy for the ScanManager MXBean
        //
        final ScanManagerMXBean proxy = ScanManager.newSingletonProxy(mbsc);
        // Get the ScanDirConfig MXBean from the scan manager
        //
        System.out.println("\nGet ScanDirConfigMXBean from ScanManagerMXBean");
        final ScanDirConfigMXBean configMBean = proxy.getConfigurationMBean();
        // Print the scan dir configuration
        //
        System.out.println("\nGet 'Configuration' attribute on ScanDirConfigMXBean");
        System.out.println("\nConfiguration:\n" + configMBean.getConfiguration());
        // Try to invoke the "close" method on the ScanManager MXBean.
        //
        // Should get a SecurityException as the user "guest" doesn't
        // have readwrite access.
        //
        System.out.println("\nInvoke 'close' on ScanManagerMXBean");
        try {
            proxy.close();
        } catch (SecurityException e) {
            System.out.println("\nGot expected security exception: " + e);
        }
        // Close MBeanServer connection
        //
        System.out.println("\nClose the connection to the server");
        jmxc.close();
        System.out.println("\nBye! Bye!");
    } catch (Exception e) {
        System.out.println("\nGot unexpected exception: " + e);
        e.printStackTrace();
        System.exit(3);
    }
}
Also used : JMXServiceURL(javax.management.remote.JMXServiceURL) UnknownHostException(java.net.UnknownHostException) HashMap(java.util.HashMap) UnknownHostException(java.net.UnknownHostException) SslRMIClientSocketFactory(javax.rmi.ssl.SslRMIClientSocketFactory) JMXConnector(javax.management.remote.JMXConnector) MBeanServerConnection(javax.management.MBeanServerConnection)

Example 58 with MBeanServerConnection

use of javax.management.MBeanServerConnection in project midpoint by Evolveum.

the class RemoteNodesManager method startRemoteScheduler.

void startRemoteScheduler(String nodeIdentifier, OperationResult result) {
    NodeType node = getNode(nodeIdentifier, result);
    if (node == null) {
        return;
    }
    String nodeName = node.getNodeIdentifier();
    String address = node.getHostname() + ":" + node.getJmxPort();
    JMXConnector connector = null;
    try {
        MBeanServerConnection mbsc;
        try {
            connector = connectViaJmx(address);
            mbsc = connector.getMBeanServerConnection();
        } catch (IOException e) {
            LoggingUtils.logUnexpectedException(LOGGER, "Cannot connect to the remote node {} at {}", e, nodeName, address);
            result.recordFatalError("Cannot connect to the remote node " + nodeName + " at " + address + ": " + e.getMessage(), e);
            return;
        }
        try {
            QuartzSchedulerMBean mbeanProxy = getMBeanProxy(nodeName, mbsc);
            if (mbeanProxy != null) {
                mbeanProxy.start();
                result.recordSuccessIfUnknown();
            } else {
                result.recordFatalError("Cannot start remote scheduler " + nodeName + " at " + address + " because it cannot be found on that node.");
            }
            return;
        } catch (Exception e) {
            LoggingUtils.logUnexpectedException(LOGGER, "Cannot start remote scheduler; remote node {} at {}", e, nodeName, address);
            result.recordFatalError("Cannot start remote scheduler " + nodeName + " at " + address + ": " + e.getMessage());
            return;
        }
    } finally {
        try {
            if (connector != null) {
                connector.close();
            }
        } catch (IOException e) {
            LoggingUtils.logUnexpectedException(LOGGER, "Cannot close JMX connection to {}", e, address);
        }
    }
}
Also used : JMXConnector(javax.management.remote.JMXConnector) NodeType(com.evolveum.midpoint.xml.ns._public.common.common_3.NodeType) IOException(java.io.IOException) MBeanServerConnection(javax.management.MBeanServerConnection) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) IOException(java.io.IOException) MalformedObjectNameException(javax.management.MalformedObjectNameException) SystemException(com.evolveum.midpoint.util.exception.SystemException) QuartzSchedulerMBean(org.quartz.core.jmx.QuartzSchedulerMBean)

Example 59 with MBeanServerConnection

use of javax.management.MBeanServerConnection in project midpoint by Evolveum.

the class RemoteNodesManager method addNodeStatusFromRemoteNode.

/**
     * Used exclusively for collecting running task information.
     *
     * @param info A structure to which information should be added
     * @param node Node which to query
     */
void addNodeStatusFromRemoteNode(ClusterStatusInformation info, PrismObject<NodeType> node, OperationResult parentResult) {
    OperationResult result = parentResult.createSubresult(RemoteNodesManager.class.getName() + ".addNodeStatusFromRemoteNode");
    result.addParam("node", node);
    NodeType nodeInfo = node.asObjectable();
    String nodeIdentifier = nodeInfo.getNodeIdentifier();
    String address = nodeInfo.getHostname() + ":" + nodeInfo.getJmxPort();
    if (!taskManager.getClusterManager().isUp(nodeInfo)) {
        nodeInfo.setExecutionStatus(NodeExecutionStatusType.DOWN);
        info.addNodeInfo(nodeInfo);
        result.recordStatus(OperationResultStatus.SUCCESS, "Node is down");
        return;
    }
    JMXConnector connector = null;
    try {
        MBeanServerConnection mbsc;
        try {
            connector = connectViaJmx(address);
            mbsc = connector.getMBeanServerConnection();
        } catch (IOException e) {
            LoggingUtils.logUnexpectedException(LOGGER, "Cannot connect to the remote node {} at {}", e, nodeIdentifier, address);
            result.recordWarning("Cannot connect to the remote node " + nodeIdentifier + " at " + address + ": " + e.getMessage(), e);
            nodeInfo.setExecutionStatus(NodeExecutionStatusType.COMMUNICATION_ERROR);
            nodeInfo.setConnectionResult(result.createOperationResultType());
            info.addNodeInfo(nodeInfo);
            return;
        }
        try {
            QuartzSchedulerMBean mbeanProxy = getMBeanProxy(nodeIdentifier, mbsc);
            boolean running = false, down = true;
            if (mbeanProxy != null) {
                try {
                    running = mbeanProxy.isStarted() && !mbeanProxy.isShutdown() && !mbeanProxy.isStandbyMode();
                    down = mbeanProxy.isShutdown();
                } catch (Exception e) {
                    // was: InstanceNotFoundException but it does not seem to work
                    String message = "Cannot get information from scheduler " + nodeIdentifier + " because it does not exist or is shut down.";
                    LoggingUtils.logUnexpectedException(LOGGER, message, e);
                    result.recordWarning(message, e);
                    nodeInfo.setConnectionResult(result.createOperationResultType());
                }
            } else {
                result.recordWarning("Cannot get information from node " + nodeIdentifier + " at " + address + " because the JMX object for scheduler cannot be found on that node.");
                nodeInfo.setConnectionResult(result.createOperationResultType());
            }
            LOGGER.trace(" - scheduler found = " + (mbeanProxy != null) + ", running = " + running + ", shutdown = " + down);
            if (down) {
                // this is a mark of error situation (we expect that during ordinary shutdown the node quickly goes down so there is little probability of getting this status on that occasion)
                nodeInfo.setExecutionStatus(NodeExecutionStatusType.ERROR);
            } else if (running) {
                nodeInfo.setExecutionStatus(NodeExecutionStatusType.RUNNING);
            } else {
                nodeInfo.setExecutionStatus(NodeExecutionStatusType.PAUSED);
            }
            List<ClusterStatusInformation.TaskInfo> taskInfoList = new ArrayList<ClusterStatusInformation.TaskInfo>();
            if (mbeanProxy != null) {
                TabularData jobs = mbeanProxy.getCurrentlyExecutingJobs();
                for (CompositeData job : (Collection<CompositeData>) jobs.values()) {
                    String oid = (String) job.get("jobName");
                    LOGGER.trace(" - task oid = " + oid);
                    taskInfoList.add(new ClusterStatusInformation.TaskInfo(oid));
                }
            }
            if (result.isUnknown()) {
                result.recordStatus(OperationResultStatus.SUCCESS, "Node " + nodeIdentifier + ": status = " + nodeInfo.getExecutionStatus() + ", # of running tasks: " + taskInfoList.size());
            }
            info.addNodeAndTaskInfo(nodeInfo, taskInfoList);
        } catch (Exception e) {
            // unfortunately, mbeanProxy.getCurrentlyExecutingJobs is declared to throw an Exception
            LoggingUtils.logUnexpectedException(LOGGER, "Cannot get information from the remote node {} at {}", e, nodeIdentifier, address);
            result.recordWarning("Cannot get information from the remote node " + nodeIdentifier + " at " + address + ": " + e.getMessage(), e);
            nodeInfo.setExecutionStatus(NodeExecutionStatusType.COMMUNICATION_ERROR);
            nodeInfo.setConnectionResult(result.createOperationResultType());
            info.addNodeInfo(nodeInfo);
            return;
        }
    } finally {
        try {
            if (connector != null) {
                connector.close();
            }
        } catch (IOException e) {
            LoggingUtils.logUnexpectedException(LOGGER, "Cannot close JMX connection to {}", e, address);
        }
        result.recordSuccessIfUnknown();
    }
}
Also used : CompositeData(javax.management.openmbean.CompositeData) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) IOException(java.io.IOException) ClusterStatusInformation(com.evolveum.midpoint.task.quartzimpl.cluster.ClusterStatusInformation) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) IOException(java.io.IOException) MalformedObjectNameException(javax.management.MalformedObjectNameException) SystemException(com.evolveum.midpoint.util.exception.SystemException) QuartzSchedulerMBean(org.quartz.core.jmx.QuartzSchedulerMBean) TabularData(javax.management.openmbean.TabularData) JMXConnector(javax.management.remote.JMXConnector) NodeType(com.evolveum.midpoint.xml.ns._public.common.common_3.NodeType) MBeanServerConnection(javax.management.MBeanServerConnection)

Example 60 with MBeanServerConnection

use of javax.management.MBeanServerConnection in project bnd by bndtools.

the class JMXBundleDeployer method getLocalConnectorAddress.

/**
	 * Uses Oracle JDK's Attach API to try to search VMs on this machine looking
	 * for the osgi.core MBeans. This will stop searching for VMs once the
	 * MBeans are found. Beware if you have multiple JVMs with osgi.core MBeans
	 * published.
	 *
	 */
@SuppressWarnings("unchecked")
static String getLocalConnectorAddress() {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    ClassLoader toolsClassloader = null;
    try {
        toolsClassloader = getToolsClassLoader(cl);
        if (toolsClassloader != null) {
            Thread.currentThread().setContextClassLoader(toolsClassloader);
            Class<?> vmClass = toolsClassloader.loadClass("com.sun.tools.attach.VirtualMachine");
            Method listMethod = vmClass.getMethod("list");
            List<Object> vmds = (List<Object>) listMethod.invoke(null);
            for (Object vmd : vmds) {
                try {
                    Class<?> vmdClass = toolsClassloader.loadClass("com.sun.tools.attach.VirtualMachineDescriptor");
                    Method idMethod = vmdClass.getMethod("id");
                    String id = (String) idMethod.invoke(vmd);
                    Method attachMethod = vmClass.getMethod("attach", String.class);
                    Object vm = attachMethod.invoke(null, id);
                    try {
                        Method getAgentPropertiesMethod = vmClass.getMethod("getAgentProperties");
                        Properties agentProperties = (Properties) getAgentPropertiesMethod.invoke(vm);
                        String localConnectorAddress = agentProperties.getProperty("com.sun.management.jmxremote.localConnectorAddress");
                        if (localConnectorAddress == null) {
                            File agentJar = findJdkJar("management-agent.jar");
                            if (agentJar != null) {
                                Method loadAgent = vmClass.getMethod("loadAgent", String.class);
                                loadAgent.invoke(vm, agentJar.getCanonicalPath());
                                agentProperties = (Properties) getAgentPropertiesMethod.invoke(vm);
                                localConnectorAddress = agentProperties.getProperty("com.sun.management.jmxremote.localConnectorAddress");
                            }
                        }
                        if (localConnectorAddress != null) {
                            final JMXServiceURL jmxServiceUrl = new JMXServiceURL(localConnectorAddress);
                            final JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxServiceUrl, null);
                            final MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection();
                            if (mBeanServerConnection != null) {
                                final ObjectName framework = getFramework(mBeanServerConnection);
                                if (framework != null) {
                                    return localConnectorAddress;
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        Method detachMethod = vmClass.getMethod("detach");
                        detachMethod.invoke(vm);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        Thread.currentThread().setContextClassLoader(cl);
        // try to get custom classloader to unload native libs
        try {
            if (toolsClassloader != null) {
                Field nl = ClassLoader.class.getDeclaredField("nativeLibraries");
                nl.setAccessible(true);
                Vector<?> nativeLibs = (Vector<?>) nl.get(toolsClassloader);
                for (Object nativeLib : nativeLibs) {
                    Field nameField = nativeLib.getClass().getDeclaredField("name");
                    nameField.setAccessible(true);
                    String name = (String) nameField.get(nativeLib);
                    if (new File(name).getName().contains("attach")) {
                        Method f = nativeLib.getClass().getDeclaredMethod("finalize");
                        f.setAccessible(true);
                        f.invoke(nativeLib);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return null;
}
Also used : JMXServiceURL(javax.management.remote.JMXServiceURL) Method(java.lang.reflect.Method) Properties(java.util.Properties) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) MalformedObjectNameException(javax.management.MalformedObjectNameException) ObjectName(javax.management.ObjectName) Field(java.lang.reflect.Field) JMXConnector(javax.management.remote.JMXConnector) URLClassLoader(java.net.URLClassLoader) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File) Vector(java.util.Vector) MBeanServerConnection(javax.management.MBeanServerConnection)

Aggregations

MBeanServerConnection (javax.management.MBeanServerConnection)125 JMXConnector (javax.management.remote.JMXConnector)84 ObjectName (javax.management.ObjectName)73 JMXServiceURL (javax.management.remote.JMXServiceURL)59 JMXConnectorServer (javax.management.remote.JMXConnectorServer)38 Test (org.junit.Test)35 IOException (java.io.IOException)31 MBeanServer (javax.management.MBeanServer)28 HashMap (java.util.HashMap)23 Attribute (javax.management.Attribute)15 NotificationListener (javax.management.NotificationListener)13 MalformedURLException (java.net.MalformedURLException)12 ArrayList (java.util.ArrayList)12 Notification (javax.management.Notification)12 MalformedObjectNameException (javax.management.MalformedObjectNameException)11 Map (java.util.Map)10 List (java.util.List)8 RemoteException (java.rmi.RemoteException)7 LocateRegistry (java.rmi.registry.LocateRegistry)7 Registry (java.rmi.registry.Registry)7