Search in sources :

Example 81 with JMXServiceURL

use of javax.management.remote.JMXServiceURL in project wildfly-swarm by wildfly-swarm.

the class JMXRemoteManagementAutoEndpointArquillianTest method testRemoteConnection.

@Test
@RunAsClient
public void testRemoteConnection() throws Exception {
    String urlString = "service:jmx:remote+http://localhost:8080";
    JMXServiceURL serviceURL = new JMXServiceURL(urlString);
    JMXConnector jmxConnector = JMXConnectorFactory.connect(serviceURL, null);
    MBeanServerConnection connection = jmxConnector.getMBeanServerConnection();
    int count = connection.getMBeanCount();
    assertThat(count).isGreaterThan(1);
    jmxConnector.close();
}
Also used : JMXServiceURL(javax.management.remote.JMXServiceURL) JMXConnector(javax.management.remote.JMXConnector) MBeanServerConnection(javax.management.MBeanServerConnection) RunAsClient(org.jboss.arquillian.container.test.api.RunAsClient) Test(org.junit.Test)

Example 82 with JMXServiceURL

use of javax.management.remote.JMXServiceURL in project wildfly-swarm by wildfly-swarm.

the class JMXRemoteManagementEndpointArquillianTest method testRemoteConnection.

@Test
@RunAsClient
public void testRemoteConnection() throws Exception {
    String urlString = "service:jmx:remote+http://localhost:9990";
    JMXServiceURL serviceURL = new JMXServiceURL(urlString);
    JMXConnector jmxConnector = JMXConnectorFactory.connect(serviceURL, null);
    MBeanServerConnection connection = jmxConnector.getMBeanServerConnection();
    int count = connection.getMBeanCount();
    assertThat(count).isGreaterThan(1);
    jmxConnector.close();
}
Also used : JMXServiceURL(javax.management.remote.JMXServiceURL) JMXConnector(javax.management.remote.JMXConnector) MBeanServerConnection(javax.management.MBeanServerConnection) RunAsClient(org.jboss.arquillian.container.test.api.RunAsClient) Test(org.junit.Test)

Example 83 with JMXServiceURL

use of javax.management.remote.JMXServiceURL in project sis by apache.

the class AboutCommand method run.

/**
 * Prints the information to the output stream.
 *
 * @return 0 on success, or an exit code if the command failed for a reason other than an uncaught Java exception.
 * @throws Exception if an error occurred while executing the sub-command.
 */
@Override
public int run() throws Exception {
    DataDirectory.quiet();
    /*
         * Check the number of arguments, which can be 0 or 1. If present,
         * the argument is the name and port number of a remote machine.
         *
         * In the current implementation, the --brief option is supported only on the local machine.
         */
    final boolean brief = options.containsKey(Option.BRIEF);
    if (hasUnexpectedFileCount(0, brief ? 0 : 1)) {
        return Command.INVALID_ARGUMENT_EXIT_CODE;
    }
    String[] warnings = null;
    final String configuration;
    if (brief && files.isEmpty()) {
        configuration = Vocabulary.getResources(locale).getString(Vocabulary.Keys.Version_2, "Apache SIS", Version.SIS);
    } else {
        final EnumSet<About> sections = EnumSet.allOf(About.class);
        if (!options.containsKey(Option.VERBOSE)) {
            sections.remove(About.LIBRARIES);
        }
        if (files.isEmpty()) {
            /*
                 * Provide information about the local SIS installation.
                 */
            configuration = About.configuration(sections, locale, timezone).toString();
        } else {
            /*
                 * Provide information about a remote SIS installation. Those information are accessible
                 * only if explicitely enabled at JVM startup time.
                 *
                 * Tutorial: http://docs.oracle.com/javase/tutorial/jmx/remote/custom.html
                 */
            final String address = files.get(0);
            final String path = toRemoteURL(address);
            final long time = System.nanoTime();
            final TreeTable table;
            try {
                final JMXServiceURL url = new JMXServiceURL(path);
                try (JMXConnector jmxc = JMXConnectorFactory.connect(url)) {
                    final MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
                    final SupervisorMBean bean = JMX.newMBeanProxy(mbsc, new ObjectName(Supervisor.NAME), SupervisorMBean.class);
                    table = bean.configuration(sections, locale, timezone);
                    warnings = bean.warnings(locale);
                }
            } catch (IOException e) {
                error(Errors.format(Errors.Keys.CanNotConnectTo_1, path), e);
                return Command.IO_EXCEPTION_EXIT_CODE;
            }
            /*
                 * Logs a message telling how long it took to receive the reply.
                 * Sometime the delay gives a hint about the server charge.
                 */
            // In seconds.
            double delay = (System.nanoTime() - time) / (double) StandardDateFormat.NANOS_PER_SECOND;
            if (delay >= 0.1) {
                final double scale = (delay >= 10) ? 1 : (delay >= 1) ? 10 : 100;
                delay = Math.rint(delay * scale) / scale;
            }
            final LogRecord record = Messages.getResources(locale).getLogRecord(Level.INFO, Messages.Keys.ConfigurationOf_3, address, new Date(), delay);
            record.setLoggerName(Loggers.APPLICATION);
            Logging.log(Command.class, "main", record);
            /*
                 * Replace the root node label from "Local configuration" to "Remote configuration"
                 * before to get the string representation of the configuration as a tree-table.
                 */
            table.getRoot().setValue(TableColumn.NAME, Vocabulary.getResources(locale).getString(Vocabulary.Keys.RemoteConfiguration));
            configuration = table.toString();
        }
    }
    out.println(configuration);
    if (warnings != null) {
        out.println();
        if (colors) {
            out.print(X364.BACKGROUND_RED.sequence());
            out.print(X364.BOLD.sequence());
            out.print(' ');
        }
        Vocabulary.getResources(locale).appendLabel(Vocabulary.Keys.Warnings, out);
        if (colors) {
            out.print(' ');
            out.println(X364.RESET.sequence());
            out.print(X364.FOREGROUND_RED.sequence());
        } else {
            out.println();
        }
        for (final String warning : warnings) {
            out.println(warning);
        }
        if (colors) {
            out.print(X364.FOREGROUND_DEFAULT.sequence());
        }
    }
    out.flush();
    return 0;
}
Also used : JMXServiceURL(javax.management.remote.JMXServiceURL) TreeTable(org.apache.sis.util.collection.TreeTable) IOException(java.io.IOException) Date(java.util.Date) About(org.apache.sis.setup.About) ObjectName(javax.management.ObjectName) LogRecord(java.util.logging.LogRecord) JMXConnector(javax.management.remote.JMXConnector) SupervisorMBean(org.apache.sis.internal.system.SupervisorMBean) MBeanServerConnection(javax.management.MBeanServerConnection)

Example 84 with JMXServiceURL

use of javax.management.remote.JMXServiceURL in project openj9 by eclipse.

the class TestOperatingSystemMXBean method runTestOSMXBean.

/**
 * Starting point for the test program.
 * Invokes the tests for the new API's that are added for the OperatingSystemMXBean
 *
 * @param args
 */
@Test
public void runTestOSMXBean() {
    boolean localTest = true;
    boolean isConnected = false;
    boolean error = false;
    ObjectName objName = null;
    JMXServiceURL urlForRemoteMachine = null;
    JMXConnector connector = null;
    MBeanServerConnection mbeanConnection = null;
    com.ibm.lang.management.OperatingSystemMXBean osmxbean = null;
    logger.info(" ----------------------------------------------------------");
    logger.info(" Starting the OperatingSystemMXBean usage API tests........");
    logger.info(" ----------------------------------------------------------");
    if (System.getProperty("RUNLOCAL").equalsIgnoreCase("false")) {
        localTest = false;
    } else if (!System.getProperty("RUNLOCAL").equalsIgnoreCase("true")) {
        /* Failed parsing a sensible option specified by the user. */
        logger.error("TestOperatingSystemMXBean usage: ");
        logger.error(" -DRUNLOCAL=[false, true]  $TestOperatingSystemMXBean");
        logger.error("Valid options are 'true' and 'false'.");
        logger.error("In absence of a specified option, test defaults to local.");
        Assert.fail("Invalid property");
    }
    /* Perform the appropriate test as instructed through the command line. */
    if (false == localTest) {
        /* A remote test needs to be performed. Start the remote server if it is not running yet.
			 * Also, attach a watch dog to this, to bail out, in case it hangs.
			 */
        if (null == remoteServer) {
            startRemoteServer();
            watchdog = new ChildWatchdog(remoteServer, 30000);
        }
        int retryCounter = 0;
        /* Try connecting to the server; retry until limit reached. */
        while (retryCounter < 10 && !isConnected) {
            retryCounter++;
            try {
                urlForRemoteMachine = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi");
                /* Connect to remote host and create a proxy to be used to get an OperatingSystemMBean
					 * instance.
					 */
                connector = JMXConnectorFactory.connect(urlForRemoteMachine, null);
                mbeanConnection = connector.getMBeanServerConnection();
                /* Obtain an mxbean object using the connection and the object name for the class
					 * OperatingSystemMXBean.
					 */
                objName = new ObjectName("java.lang:type=OperatingSystem");
                osmxbean = (com.ibm.lang.management.OperatingSystemMXBean) JMX.newMXBeanProxy(mbeanConnection, objName, com.ibm.lang.management.OperatingSystemMXBean.class);
                /* If we reached here, it means we are connected (no connection failure exception thrown). */
                isConnected = true;
            } catch (MalformedURLException e) {
                Assert.fail("Unexpected MalformedURLException occured, please check the url supplied to JMXServiceURL!", e);
            } catch (IOException e) {
                /* Waiting 1000 ms before retrying to connnect to remote server. */
                logger.warn("Connection request failed: " + e.getMessage());
                logger.warn("Connection failed at: " + System.currentTimeMillis() + " ms.  Retry " + retryCounter + " after 1000 ms.");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ie) {
                    logger.warn("Sleeping thread interrupted", ie);
                }
            } catch (Exception e) {
                Assert.fail("Unexpected exception occured", e);
            }
        }
        Assert.assertTrue(isConnected, "!!!Test(s) couldn't be started in remote mode: Connection setup failed !!!");
    } else {
        // A local test has been requested.
        osmxbean = (com.ibm.lang.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    }
    /* Proceed with testing only if either (1) we are running local testing or (2) if we are
		 * running remote testing and have successfully set up a JMX connection.
		 */
    try {
        if ((localTest) || (!localTest && isConnected)) {
            logger.info("Tests starting at: " + System.currentTimeMillis() + " ms.");
            if (!isPlatformZOS()) {
                /* Call the API test methods */
                error |= test_PhysicalMemoryAPIs(osmxbean);
                error |= test_SwapSpaceSizeAPIs(osmxbean);
                error |= test_getProcessVirtualMemorySize(osmxbean);
                error |= test_memoryInfo(osmxbean);
                error |= test_processorInfo(osmxbean);
            }
            /* At this point, we have enabled support for only these API's on z/OS. */
            error |= test_getProcessCpuTimeByNS(osmxbean, localTest);
            error |= test_getProcessCpuLoad(osmxbean, localTest);
            error |= test_getHardwareModel(osmxbean);
            error |= test_isHardwareEmulated(osmxbean, localTest);
        }
    } finally {
        /* Do all clean up here. */
        if (!localTest) {
            /* Close the connection and Stop the remote Server */
            try {
                connector.close();
                stopRemoteServer();
            } catch (Exception e) {
                Assert.fail("Failed to stop remote server or close connetor" + e.getMessage(), e);
            }
        }
        logger.info("Tests finished at: " + System.currentTimeMillis() + " ms.");
    }
    Assert.assertFalse(error, "!!!Test(s) Failed !!!");
}
Also used : JMXServiceURL(javax.management.remote.JMXServiceURL) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) MalformedObjectNameException(javax.management.MalformedObjectNameException) ObjectName(javax.management.ObjectName) com.ibm.lang.management(com.ibm.lang.management) JMXConnector(javax.management.remote.JMXConnector) MBeanServerConnection(javax.management.MBeanServerConnection) Test(org.testng.annotations.Test)

Example 85 with JMXServiceURL

use of javax.management.remote.JMXServiceURL in project openj9 by eclipse.

the class GuestOSMXBeanTest method runGuestOSMXBeanTest.

/**
 * Starting point for the test program. Invokes the memory and processor test routines and
 * indicates success or failure accordingly.
 *
 * @param args
 */
@Test
public static void runGuestOSMXBeanTest() {
    int retryCounter = 0;
    boolean localTest = true;
    boolean isConnected = false;
    boolean error = false;
    JMXServiceURL urlForRemoteMachine = null;
    JMXConnector connector = null;
    MBeanServerConnection mbeanConnection = null;
    MBeanServer mbeanServer = null;
    ObjectName mxbeanName = null;
    GuestOSMXBean mxbeanProxy = null;
    logger.info(" ---------------------------------------");
    logger.info(" Starting the GuestOSMXBean API tests....");
    logger.info(" ---------------------------------------");
    /* Check and set flag 'localTest'. If the user specified 'local' or nothing, select local testing,
		 * while under explicit specification of the option 'remote' do we platform remote testing.
		 */
    if (System.getProperty("RUNLOCAL").equalsIgnoreCase("false")) {
        localTest = false;
    } else if (!System.getProperty("RUNLOCAL").equalsIgnoreCase("true")) {
        /* Failed parsing a sensible option specified by the user. */
        logger.error("GuestOSMXBeanTest usage:");
        logger.error(" -DRUNLOCAL=[false, true]  $GuestOSMXBeanTest");
        logger.error("Valid options are 'true' and 'false'.");
        logger.error("In absence of a specified option, test defaults to local.");
        Assert.fail("Invalid property");
    }
    /* We need the object name in any case - remote as well as local. */
    try {
        mxbeanName = new ObjectName("com.ibm.virtualization.management:type=GuestOS");
    } catch (MalformedObjectNameException e) {
        Assert.fail("MalformedObjectNameException!", e);
    }
    /* Perform the appropriate test as instructed through the command line. */
    if (false == localTest) {
        /* A remote test needs to be performed. Start the remote server if it is not running yet.
			 * Also, attach a watch dog to this, to bail out, in case it hangs.
			 */
        if (null == remoteServer) {
            startRemoteServer();
            watchdog = new ChildWatchdog(remoteServer, 30000);
        }
        /* Try connecting to the server; retry until limit reached. */
        while (retryCounter < 10 && !isConnected) {
            retryCounter++;
            try {
                urlForRemoteMachine = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi");
                /* Connect to remote host and create a proxy to be used to get an GuestOSMXBean
					 * instance.
					 */
                connector = JMXConnectorFactory.connect(urlForRemoteMachine, null);
                mbeanConnection = connector.getMBeanServerConnection();
                /* Obtain an MBean handle using the connection and the
					 *  object name for the class GuestOSMXBean.
					 */
                mxbeanProxy = JMX.newMXBeanProxy(mbeanConnection, mxbeanName, GuestOSMXBean.class);
                if (true != mbeanConnection.isRegistered(mxbeanName)) {
                    Assert.fail("GuestOSMXBean is not registered. Cannot Proceed with the test. !!!Test Failed !!!");
                }
                /* If we reached here, it means we are connected (no connection failure exception thrown). */
                isConnected = true;
            } catch (MalformedURLException e) {
                Assert.fail("Please check the url supplied to JMXServiceURL!", e);
            } catch (IOException e) {
                /* Waiting 1000 ms before retrying to connect to remote server. */
                logger.warn("Failed connecting. Retry " + retryCounter + " after 1000 ms.");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ie) {
                    logger.warn("Exception occurred while sleeping thread: " + ie.getMessage(), e);
                }
            } catch (Exception e) {
                Assert.fail("Exception occurred in setting up remote test environment.");
            }
            if (!isConnected) {
                Assert.fail("Unable to connect to Remote Server. !!!Test Failed !!!");
            }
        }
    } else {
        /*
			 * A local test has been requested.
			 */
        try {
            mbeanServer = ManagementFactory.getPlatformMBeanServer();
            if (true != mbeanServer.isRegistered(mxbeanName)) {
                Assert.fail("GuestOSMXBean is not registered. Cannot Proceed with the test.");
            }
            mxbeanProxy = JMX.newMXBeanProxy(mbeanServer, mxbeanName, GuestOSMXBean.class);
        } catch (Exception e) {
            Assert.fail("Exception occurred in setting up local test environment." + e.getMessage(), e);
        }
    }
    try {
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        HypervisorMXBean bean = ManagementFactory.getPlatformMXBean(mbs, HypervisorMXBean.class);
        HypervisorName = bean.getVendor();
        if (null == HypervisorName) {
            HypervisorName = "none";
        }
    } catch (Exception e) {
        Assert.fail("Unexpected exception occured" + e.getMessage(), e);
    }
    try {
        error |= test_memoryInfo(mxbeanProxy);
        error |= test_processorInfo(mxbeanProxy);
    } finally {
        /* Do all clean up here. */
        if (false == localTest) {
            /* Close the connection and Stop the remote Server */
            try {
                connector.close();
                stopRemoteServer();
            } catch (Exception e) {
                Assert.fail("Unexpected exception occured when close connector" + e.getMessage(), e);
            }
        }
    }
    if (false != error) {
        Assert.fail(" !!!Test Failed !!!");
    }
}
Also used : JMXServiceURL(javax.management.remote.JMXServiceURL) MalformedObjectNameException(javax.management.MalformedObjectNameException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) MalformedObjectNameException(javax.management.MalformedObjectNameException) ObjectName(javax.management.ObjectName) JMXConnector(javax.management.remote.JMXConnector) ChildWatchdog(org.openj9.test.management.util.ChildWatchdog) MBeanServerConnection(javax.management.MBeanServerConnection) MBeanServer(javax.management.MBeanServer) Test(org.testng.annotations.Test)

Aggregations

JMXServiceURL (javax.management.remote.JMXServiceURL)280 JMXConnector (javax.management.remote.JMXConnector)150 MBeanServerConnection (javax.management.MBeanServerConnection)107 ObjectName (javax.management.ObjectName)90 IOException (java.io.IOException)78 HashMap (java.util.HashMap)75 MBeanServer (javax.management.MBeanServer)71 JMXConnectorServer (javax.management.remote.JMXConnectorServer)64 MalformedURLException (java.net.MalformedURLException)45 RemoteException (java.rmi.RemoteException)22 Test (org.junit.Test)22 Map (java.util.Map)16 UnknownHostException (java.net.UnknownHostException)14 Properties (java.util.Properties)14 Notification (javax.management.Notification)14 NotificationListener (javax.management.NotificationListener)14 MalformedObjectNameException (javax.management.MalformedObjectNameException)13 LocateRegistry (java.rmi.registry.LocateRegistry)12 Registry (java.rmi.registry.Registry)12 ArrayList (java.util.ArrayList)11