private static boolean test(String proto, MBeanServer mbs) throws Exception {
    System.out.println("Testing for proto " + proto);

    JMXConnectorServer cs;
    JMXServiceURL url = new JMXServiceURL(proto, null, 0);
    try {
      cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    } catch (MalformedURLException e) {
      System.out.println("System does not recognize URL: " + url + "; ignoring");
      return true;
    }
    cs.start();
    JMXServiceURL addr = cs.getAddress();
    JMXServiceURL rmiurl = new JMXServiceURL("rmi", null, 0);
    JMXConnector client = JMXConnectorFactory.connect(addr);
    MBeanServerConnection mbsc = client.getMBeanServerConnection();
    ObjectName on = new ObjectName("x:proto=" + proto + ",ok=yes");
    mbsc.createMBean(
        RMIConnectorServer.class.getName(),
        on,
        mletName,
        new Object[] {rmiurl, null},
        new String[] {JMXServiceURL.class.getName(), Map.class.getName()});
    System.out.println("Successfully deserialized with " + proto);
    mbsc.unregisterMBean(on);

    client.close();
    cs.stop();
    return true;
  }
Beispiel #2
0
  private static void test(String proto) throws Exception {
    System.out.println(">>> Test for protocol " + proto);

    JMXServiceURL u = null;
    JMXConnectorServer server = null;

    HashMap env = new HashMap(2);
    // server will close a client connection after 1 second
    env.put("jmx.remote.x.server.connection.timeout", "1000");

    // disable the client ping
    env.put("jmx.remote.x.client.connection.check.period", "0");

    try {
      u = new JMXServiceURL(proto, null, 0);
      server = JMXConnectorServerFactory.newJMXConnectorServer(u, env, mbs);
    } catch (MalformedURLException e) {
      System.out.println(">>> Skipping unsupported URL " + proto);
    }

    server.start();

    JMXServiceURL addr = server.getAddress();

    long st = 2000;
    MyListener myListener;

    // a cycle to make sure that we test the blocking problem.
    do {
      JMXConnector client = JMXConnectorFactory.connect(addr, env);
      MBeanServerConnection conn = client.getMBeanServerConnection();
      myListener = new MyListener(conn);
      client.addConnectionNotificationListener(myListener, null, null);

      // wait the server to close the client connection
      Thread.sleep(st);

      // makes the listener to do a remote request via the connection
      // which should be closed by the server.
      conn.getDefaultDomain();

      // allow the listner to have time to work
      Thread.sleep(100);

      // get a closed notif, should no block.
      client.close();
      Thread.sleep(100);

      st += 2000;

    } while (!myListener.isDone());

    server.stop();
  }
Beispiel #3
0
 public void disconnect() {
   // Reset remote stub
   stub = null;
   // Close MBeanServer connection
   if (jmxc != null) {
     try {
       jmxc.close();
     } catch (IOException e) {
       // Ignore ???
     }
   }
   // Reset platform MBean references
   classLoadingMBean = null;
   compilationMBean = null;
   memoryMBean = null;
   operatingSystemMBean = null;
   runtimeMBean = null;
   threadMBean = null;
   sunOperatingSystemMXBean = null;
   garbageCollectorMBeans = null;
   // Set connection state to DISCONNECTED
   if (!isDead) {
     isDead = true;
     setConnectionState(ConnectionState.DISCONNECTED);
   }
 }
  public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub
    if (args.length != 4) {
      System.err.println("Please provide process id zabbix-host zabbix-port host-guid");
      System.exit(-1);
    }
    String processPid = args[0];
    String zabbixHost = args[1];
    String zabbixPort = args[2];
    String hostGuid = args[3];

    VirtualMachine vm = VirtualMachine.attach(processPid);
    String connectorAddr =
        vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress");
    if (connectorAddr == null) {
      String agent =
          vm.getSystemProperties().getProperty("java.home")
              + File.separator
              + "lib"
              + File.separator
              + "management-agent.jar";
      vm.loadAgent(agent);
      connectorAddr =
          vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress");
    }
    JMXServiceURL serviceURL = new JMXServiceURL(connectorAddr);
    JMXConnector connector = JMXConnectorFactory.connect(serviceURL);
    MBeanServerConnection mbsc = connector.getMBeanServerConnection();
    ObjectName objName = new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME);
    Set<ObjectName> mbeans = mbsc.queryNames(objName, null);
    for (ObjectName name : mbeans) {
      ThreadMXBean threadBean;
      threadBean =
          ManagementFactory.newPlatformMXBeanProxy(mbsc, name.toString(), ThreadMXBean.class);
      long threadIds[] = threadBean.getAllThreadIds();
      for (long threadId : threadIds) {
        ThreadInfo threadInfo = threadBean.getThreadInfo(threadId);
        System.out.println(threadInfo.getThreadName() + " / " + threadInfo.getThreadState());
      }
    }
  }
Beispiel #5
0
 /** Connect to a JMX agent of a given URL. */
 private void connect(String urlPath) {
   try {
     JMXServiceURL url = new JMXServiceURL("rmi", "", 0, urlPath);
     this.jmxc = JMXConnectorFactory.connect(url);
     this.server = jmxc.getMBeanServerConnection();
   } catch (MalformedURLException e) {
     // should not reach here
   } catch (IOException e) {
     System.err.println("\nCommunication error: " + e.getMessage());
     System.exit(1);
   }
 }
 public void use() {
   JMXConnector jmxc = null;
   try {
     JMXServiceURL serviceURL = new JMXServiceURL(this.serviceUrl);
     jmxc = JMXConnectorFactory.connect(serviceURL, null);
     MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
     ObjectName mbeanName = new ObjectName(MBeanName);
     StatusMBean mbeanProxy = JMX.newMBeanProxy(mbsc, mbeanName, StatusMBean.class, true);
     System.out.println(mbeanProxy.getName());
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     if (jmxc != null) {
       try {
         jmxc.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
 }
Beispiel #7
0
  /**
   * Program Main.
   *
   * <p>Lookup all JMX agents in the LDAP Directory and list their MBeans and attributes.
   *
   * <p>You may wish to use the following properties on the Java command line:
   *
   * <ul>
   *   <li><code>-Dagent.name=&lt;AgentName&gt;</code>: specifies an AgentName to lookup (default is
   *       null, meaning any agent).
   *   <li><code>-Dprotocol=&lt;ProtocolType&gt;</code>: restrains the client to lookup for a
   *       specific protocol type (default is null, meaning any type).
   *   <li><code>-Djava.naming.factory.initial=&lt;initial-context-factory&gt;
   *     </code>: The initial context factory to use for accessing the LDAP directory (see {@link
   *       Context#INITIAL_CONTEXT_FACTORY Context.INITIAL_CONTEXT_FACTORY}) - default is <code>
   *       "com.sun.jndi.ldap.LdapCtxFactory"</code>.
   *   <li><code>-Djava.naming.provider.url=&lt;provider-url&gt;</code>: The LDAP Provider URL (see
   *       {@link Context#PROVIDER_URL Context.PROVIDER_URL}).
   *   <li><code>-Djava.naming.security.principal=&lt;ldap-principal&gt;
   *     </code>: The security principal (login) to use to connect with the LDAP directory (see
   *       {@link Context#SECURITY_PRINCIPAL Context.SECURITY_PRINCIPAL} - default is <code>
   *       "cn=Directory Manager"</code>.
   *   <li><code>-Djava.naming.security.credentials=&lt;ldap-credentials&gt;
   *     </code>: The security credentials (password) to use to connect with the LDAP directory (see
   *       {@link Context#SECURITY_CREDENTIALS Context.SECURITY_CREDENTIALS}).
   *   <li><code>-Ddebug="true|false"</code>: switch the Server debug flag on/off (default is
   *       "false")
   * </ul>
   */
  public static void main(String[] args) {
    try {
      // Get the value of the debug flag.
      //
      debug = (Boolean.valueOf(System.getProperty("debug", "false"))).booleanValue();

      // Get a pointer to the LDAP Directory.
      //
      final DirContext root = getRootContext();
      debug("root is: " + root.getNameInNamespace());

      final String protocolType = System.getProperty("protocol");
      final String agentName = System.getProperty("agent.name");

      // Lookup all matching agents in the LDAP Directory.
      //
      List l = lookup(root, protocolType, agentName);

      // Attempt to connect to retrieved agents
      //
      System.out.println("Number of agents found : " + l.size());
      int j = 1;
      for (Iterator i = l.iterator(); i.hasNext(); j++) {
        JMXConnector c1 = (JMXConnector) i.next();
        if (c1 != null) {

          // Connect
          //
          System.out.println("----------------------------------------------------");
          System.out.println("\tConnecting to agent number " + j);
          System.out.println("----------------------------------------------------");
          debug("JMXConnector is: " + c1);

          // Prepare the environment Map
          //
          final HashMap env = new HashMap();
          final String factory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY);
          final String ldapServerUrl = System.getProperty(Context.PROVIDER_URL);
          final String ldapUser = System.getProperty(Context.SECURITY_PRINCIPAL);
          final String ldapPasswd = System.getProperty(Context.SECURITY_CREDENTIALS);

          // Transfer some system properties to the Map
          //
          if (factory != null) // this should not be needed
          env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
          if (ldapServerUrl != null) // this should not be needed
          env.put(Context.PROVIDER_URL, ldapServerUrl);
          if (ldapUser != null) // this is needed when LDAP is used
          env.put(Context.SECURITY_PRINCIPAL, ldapUser);
          if (ldapPasswd != null) // this is needed when LDAP is used
          env.put(Context.SECURITY_CREDENTIALS, ldapPasswd);

          try {
            c1.connect(env);
          } catch (IOException x) {
            System.err.println("Connection failed: " + x);
            x.printStackTrace(System.err);
            continue;
          }

          // Get MBeanServerConnection
          //
          MBeanServerConnection conn = c1.getMBeanServerConnection();
          debug("Connection is:" + conn);
          System.out.println("Server domain is: " + conn.getDefaultDomain());

          // List all MBeans
          //
          try {
            listMBeans(conn);
          } catch (IOException x) {
            System.err.println("Failed to list MBeans: " + x);
            x.printStackTrace(System.err);
          }

          // Close connector
          //
          try {
            c1.close();
          } catch (IOException x) {
            System.err.println("Failed to close connection: " + x);
            x.printStackTrace(System.err);
          }
        }
      }
    } catch (Exception x) {
      System.err.println("Unexpected exception caught in main: " + x);
      x.printStackTrace(System.err);
    }
  }
Beispiel #8
0
  /**
   * Program Main
   *
   * <p>Lookup all JMX agents in the Jini Lookup Service and list their MBeans and attributes.
   *
   * <p>You may wish to use the following properties on the Java command line:
   *
   * <ul>
   *   <li><code>-Dagent.name=&lt;AgentName&gt;</code>: specifies an AgentName to lookup (default is
   *       null, meaning any agent).
   *   <li><code>-Djini.lookup.url=&lt;jini-url&gt;</code>: the Jini Lookup Service URL (default is
   *       "jini://localhost"), see {@link #getRegistrar()}.
   *   <li><code>-Ddebug="true|false"</code>: switch the Client debug flag on/off (default is
   *       "false").
   * </ul>
   */
  public static void main(String[] args) {
    try {
      // Jini requires a security manager.
      //
      if (System.getSecurityManager() == null) System.setSecurityManager(new RMISecurityManager());

      // Get the value of the debug flag.
      //
      debug = (Boolean.valueOf(System.getProperty("debug", "false"))).booleanValue();

      // Get AgentName to lookup. If not defined, all agents
      // are looked up.
      //
      final String agentName = System.getProperty("agent.name");

      // Get a pointer to the Jini Lookup Service.
      //
      final ServiceRegistrar registrar = getRegistrar();
      debug("registrar is: " + registrar);

      // Lookup all matching agents in the Jini Lookup Service.
      //
      List l = lookup(registrar, agentName);

      // Attempt to connect to retrieved agents
      //
      System.out.println("Number of agents found : " + l.size());
      int j = 1;
      for (Iterator i = l.iterator(); i.hasNext(); j++) {
        JMXConnector c1 = (JMXConnector) i.next();
        if (c1 != null) {

          // Connect
          //
          System.out.println("----------------------------------------------------");
          System.out.println("\tConnecting to agent number " + j);
          System.out.println("----------------------------------------------------");
          debug("JMXConnector is: " + c1);

          try {
            c1.connect(null);
          } catch (IOException x) {
            System.err.println("Connection failed: " + x);
            if (debug) x.printStackTrace(System.err);
            continue;
          }

          // Get MBeanServerConnection
          //
          MBeanServerConnection conn = c1.getMBeanServerConnection();
          debug("Connection is:" + conn);
          System.out.println("Server domain is: " + conn.getDefaultDomain());

          // List all MBeans
          //
          try {
            listMBeans(conn);
          } catch (IOException x) {
            System.err.println("Failed to list MBeans: " + x);
            if (debug) x.printStackTrace(System.err);
          }

          // Close connector
          //
          try {
            c1.close();
          } catch (IOException x) {
            System.err.println("Failed to close connection: " + x);
            if (debug) x.printStackTrace(System.err);
          }
        }
      }
    } catch (Exception x) {
      System.err.println("Unexpected exception caught in main: " + x);
      x.printStackTrace(System.err);
    }
  }
Beispiel #9
0
  private void tryConnect(boolean requireRemoteSSL) throws IOException {
    if (jmxUrl == null && "localhost".equals(hostName) && port == 0) {
      // Monitor self
      this.jmxc = null;
      this.mbsc = ManagementFactory.getPlatformMBeanServer();
      this.server = Snapshot.newSnapshot(mbsc);
    } else {
      // Monitor another process
      if (lvm != null) {
        if (!lvm.isManageable()) {
          lvm.startManagementAgent();
          if (!lvm.isManageable()) {
            // FIXME: what to throw
            throw new IOException(lvm + "not manageable");
          }
        }
        if (this.jmxUrl == null) {
          this.jmxUrl = new JMXServiceURL(lvm.connectorAddress());
        }
      }
      Map<String, Object> env = new HashMap<String, Object>();
      if (requireRemoteSSL) {
        env.put("jmx.remote.x.check.stub", "true");
      }
      // Need to pass in credentials ?
      if (userName == null && password == null) {
        if (isVmConnector()) {
          // Check for SSL config on reconnection only
          if (stub == null) {
            checkSslConfig();
          }
          this.jmxc = new RMIConnector(stub, null);
          jmxc.connect(env);
        } else {
          this.jmxc = JMXConnectorFactory.connect(jmxUrl, env);
        }
      } else {
        env.put(JMXConnector.CREDENTIALS, new String[] {userName, password});
        if (isVmConnector()) {
          // Check for SSL config on reconnection only
          if (stub == null) {
            checkSslConfig();
          }
          this.jmxc = new RMIConnector(stub, null);
          jmxc.connect(env);
        } else {
          this.jmxc = JMXConnectorFactory.connect(jmxUrl, env);
        }
      }
      this.mbsc = jmxc.getMBeanServerConnection();
      this.server = Snapshot.newSnapshot(mbsc);
    }
    this.isDead = false;

    try {
      ObjectName on = new ObjectName(THREAD_MXBEAN_NAME);
      this.hasPlatformMXBeans = server.isRegistered(on);
      this.hasHotSpotDiagnosticMXBean =
          server.isRegistered(new ObjectName(HOTSPOT_DIAGNOSTIC_MXBEAN_NAME));
      // check if it has 6.0 new APIs
      if (this.hasPlatformMXBeans) {
        MBeanOperationInfo[] mopis = server.getMBeanInfo(on).getOperations();
        // look for findDeadlockedThreads operations;
        for (MBeanOperationInfo op : mopis) {
          if (op.getName().equals("findDeadlockedThreads")) {
            this.supportsLockUsage = true;
            break;
          }
        }

        on = new ObjectName(COMPILATION_MXBEAN_NAME);
        this.hasCompilationMXBean = server.isRegistered(on);
      }
    } catch (MalformedObjectNameException e) {
      // should not reach here
      throw new InternalError(e.getMessage());
    } catch (IntrospectionException e) {
      InternalError ie = new InternalError(e.getMessage());
      ie.initCause(e);
      throw ie;
    } catch (InstanceNotFoundException e) {
      InternalError ie = new InternalError(e.getMessage());
      ie.initCause(e);
      throw ie;
    } catch (ReflectionException e) {
      InternalError ie = new InternalError(e.getMessage());
      ie.initCause(e);
      throw ie;
    }

    if (hasPlatformMXBeans) {
      // WORKAROUND for bug 5056632
      // Check if the access role is correct by getting a RuntimeMXBean
      getRuntimeMXBean();
    }
  }
  private static boolean test(String proto, MBeanServer mbs, ObjectName on) throws Exception {
    System.out.println("Testing for protocol " + proto);

    JMXConnectorServer cs;
    JMXServiceURL url = new JMXServiceURL(proto, null, 0);
    try {
      cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    } catch (MalformedURLException e) {
      System.out.println("System does not recognize URL: " + url + "; ignoring");
      return true;
    }
    cs.start();
    JMXServiceURL addr = cs.getAddress();
    JMXConnector client = JMXConnectorFactory.connect(addr);
    MBeanServerConnection mbsc = client.getMBeanServerConnection();
    Object getAttributeExotic = mbsc.getAttribute(on, "Exotic");
    AttributeList getAttrs = mbsc.getAttributes(on, new String[] {"Exotic"});
    AttributeList setAttrs = new AttributeList();
    setAttrs.add(new Attribute("Exotic", new Exotic()));
    setAttrs = mbsc.setAttributes(on, setAttrs);
    Object invokeExotic = mbsc.invoke(on, "anExotic", new Object[] {}, new String[] {});
    MBeanInfo exoticMBI = mbsc.getMBeanInfo(on);

    mbsc.setAttribute(on, new Attribute("Exception", Boolean.TRUE));
    Exception getAttributeException, setAttributeException, invokeException;
    try {
      try {
        mbsc.getAttribute(on, "Exotic");
        throw noException("getAttribute");
      } catch (Exception e) {
        getAttributeException = e;
      }
      try {
        mbsc.setAttribute(on, new Attribute("Exotic", new Exotic()));
        throw noException("setAttribute");
      } catch (Exception e) {
        setAttributeException = e;
      }
      try {
        mbsc.invoke(on, "anExotic", new Object[] {}, new String[] {});
        throw noException("invoke");
      } catch (Exception e) {
        invokeException = e;
      }
    } finally {
      mbsc.setAttribute(on, new Attribute("Exception", Boolean.FALSE));
    }
    client.close();
    cs.stop();

    boolean ok = true;

    ok &= checkAttrs("getAttributes", getAttrs);
    ok &= checkAttrs("setAttributes", setAttrs);

    ok &= checkType("getAttribute", getAttributeExotic, Exotic.class);
    ok &= checkType("getAttributes", attrValue(getAttrs), Exotic.class);
    ok &= checkType("setAttributes", attrValue(setAttrs), Exotic.class);
    ok &= checkType("invoke", invokeExotic, Exotic.class);
    ok &= checkType("getMBeanInfo", exoticMBI, ExoticMBeanInfo.class);

    ok &= checkExceptionType("getAttribute", getAttributeException, ExoticException.class);
    ok &= checkExceptionType("setAttribute", setAttributeException, ExoticException.class);
    ok &= checkExceptionType("invoke", invokeException, ExoticException.class);

    if (ok) System.out.println("Test passes for protocol " + proto);
    return ok;
  }