예제 #1
0
    void checkThreadInfo(ThreadInfo info) {
      if (!getName().equals(info.getThreadName())) {
        throw new RuntimeException(
            "Name: " + info.getThreadName() + " not matched. Expected: " + getName());
      }

      MonitorInfo[] monitors = info.getLockedMonitors();
      if (monitors.length != OWNED_MONITORS) {
        throw new RuntimeException(
            "Number of locked monitors = "
                + monitors.length
                + " not matched. Expected: "
                + OWNED_MONITORS);
      }
      MonitorInfo m = monitors[0];
      StackTraceElement ste = m.getLockedStackFrame();
      int depth = m.getLockedStackDepth();
      StackTraceElement[] stacktrace = info.getStackTrace();
      if (!ste.equals(stacktrace[depth])) {
        System.out.println("LockedStackFrame:- " + ste);
        System.out.println("StackTrace at " + depth + " :-" + stacktrace[depth]);
        throw new RuntimeException(
            "LockedStackFrame does not match " + "stack frame in ThreadInfo.getStackTrace");
      }

      String className = lock.getClass().getName();
      int hcode = System.identityHashCode(lock);
      if (!className.equals(m.getClassName())
          || hcode != m.getIdentityHashCode()
          || !m.getLockedStackFrame().getMethodName().equals("run")) {
        System.out.println(info);
        throw new RuntimeException("MonitorInfo " + m + " doesn't match.");
      }

      LockInfo[] syncs = info.getLockedSynchronizers();
      if (syncs.length != OWNED_SYNCS) {
        throw new RuntimeException(
            "Number of locked syncs = " + syncs.length + " not matched. Expected: " + OWNED_SYNCS);
      }
      AbstractOwnableSynchronizer s = mutex.getSync();
      String lockName = s.getClass().getName();
      hcode = System.identityHashCode(s);
      if (!lockName.equals(syncs[0].getClassName())) {
        throw new RuntimeException(
            "LockInfo : " + syncs[0] + " class name not matched. Expected: " + lockName);
      }
      if (hcode != syncs[0].getIdentityHashCode()) {
        throw new RuntimeException(
            "LockInfo: " + syncs[0] + " IdentityHashCode not matched. Expected: " + hcode);
      }
      LockInfo li = info.getLockInfo();
      if (li == null) {
        throw new RuntimeException("Expected non-null LockInfo");
      }
    }
예제 #2
0
  /**
   * A utility method that will wait until all displays are finished being created. This looks at
   * the DisplayControls, data sources, global wait cursor count, the visad thread pool and looks at
   * any active java3d threads
   *
   * @param uiManager The ui manager. We use this to access the wait cursor count
   * @param timeToWait (milliseconds) elapsed time to wait for nothing to be active
   */
  public static void waitUntilDisplaysAreDone(IdvUIManager uiManager, long timeToWait) {
    Trace.call1("Waiting on displays");
    int successiveTimesWithNoActive = 0;
    int sleepTime = 10;
    long firstTime = System.currentTimeMillis();
    int cnt = 0;
    while (true) {
      boolean cursorCount = (uiManager.getWaitCursorCount() > 0);
      boolean actionCount = ActionImpl.getTaskCount() > 0;
      boolean dataActive = DataSourceImpl.getOutstandingGetDataCalls() > 0;
      boolean anyJ3dActive = anyJava3dThreadsActive();
      boolean allDisplaysInitialized = uiManager.getIdv().getAllDisplaysIntialized();

      //            System.err.println ("\tAll displays init:" + allDisplaysInitialized +" cursor
      // cnt:" + uiManager.getWaitCursorCount() + " action cnt:" +actionCount + " data active: " +
      // dataActive);
      //            if ((cnt++) % 30 == 0) {
      //                System.err.println ("\tcnt:" + uiManager.getWaitCursorCount() + " "
      // +actionCount + " " + dataActive);
      //            }
      boolean anyActive =
          actionCount || cursorCount || dataActive || !allDisplaysInitialized || anyJ3dActive;
      if (dataActive) {
        firstTime = System.currentTimeMillis();
      }

      if (anyActive) {
        successiveTimesWithNoActive = 0;
      } else {
        successiveTimesWithNoActive++;
      }
      if ((timeToWait == 0) && !anyActive) {
        break;
      }
      if (successiveTimesWithNoActive * sleepTime > timeToWait) {
        break;
      }
      Misc.sleep(sleepTime);
      // At most wait 120 seconds
      if (System.currentTimeMillis() - firstTime > 120000) {
        System.err.println("Error waiting for to be done:" + LogUtil.getStackDump(false));
        return;
      }
    }
    Trace.call2("Waiting on displays");
  }
예제 #3
0
 /**
  * Callback routine called by JVM after full gc run. Has two functions: 1) sets the amount of
  * memory to be cleaned from the cache by the Cleaner 2) sets the CAN_ALLOC flag to false if
  * memory level is critical
  *
  * <p>The callback happens in a system thread, and hence not through the usual water.Boot loader
  * - and so any touched classes are in the wrong class loader and you end up with new classes
  * with uninitialized global vars. Limit to touching global vars in the Boot class.
  */
 public void handleNotification(Notification notification, Object handback) {
   String notifType = notification.getType();
   if (notifType.equals(MemoryNotificationInfo.MEMORY_COLLECTION_THRESHOLD_EXCEEDED)) {
     // Memory used after this FullGC
     Boot.TIME_AT_LAST_GC = System.currentTimeMillis();
     Boot.HEAP_USED_AT_LAST_GC = _allMemBean.getHeapMemoryUsage().getUsed();
     Boot.kick_store_cleaner();
   }
 }
 public static void main(String[] args) throws Exception {
   MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
   final Boolean isNotificationSupported =
       AccessController.doPrivileged(
           new PrivilegedAction<Boolean>() {
             public Boolean run() {
               try {
                 Class cl = Class.forName("sun.management.VMManagementImpl");
                 Field f = cl.getDeclaredField("gcNotificationSupport");
                 f.setAccessible(true);
                 return f.getBoolean(null);
               } catch (ClassNotFoundException e) {
                 return false;
               } catch (NoSuchFieldException e) {
                 return false;
               } catch (IllegalAccessException e) {
                 return false;
               }
             }
           });
   if (!isNotificationSupported) {
     System.out.println("GC Notification not supported by the JVM, test skipped");
     return;
   }
   final ObjectName gcMXBeanPattern = new ObjectName("java.lang:type=GarbageCollector,*");
   Set<ObjectName> names = mbs.queryNames(gcMXBeanPattern, null);
   if (names.isEmpty()) throw new Exception("Test incorrect: no GC MXBeans");
   number = names.size();
   for (ObjectName n : names) {
     if (mbs.isInstanceOf(n, "javax.management.NotificationEmitter")) {
       listenerInvoked.put(n.getCanonicalName(), null);
       GcListener listener = new GcListener();
       mbs.addNotificationListener(n, listener, null, null);
     }
   }
   // Invocation of System.gc() to trigger major GC
   System.gc();
   // Allocation of many short living and small objects to trigger minor GC
   Object data[] = new Object[32];
   for (int i = 0; i < 100000000; i++) {
     data[i % 32] = new int[8];
   }
   int wakeup = 0;
   synchronized (synchronizer) {
     while (count != number) {
       synchronizer.wait(10000);
       wakeup++;
       if (wakeup > 10) break;
     }
   }
   for (GarbageCollectionNotificationInfo notif : listenerInvoked.values()) {
     checkGarbageCollectionNotificationInfoContent(notif);
   }
   System.out.println("Test passed");
 }
예제 #5
0
  private static void checkMap() throws Exception {
    // Add new system properties
    System.setProperty(KEY1, VALUE1);
    System.setProperty(KEY2, VALUE2);

    TabularData props1 = (TabularData) server.getAttribute(runtime, "SystemProperties");

    String value1 = getProperty(props1, KEY1);
    if (value1 == null || !value1.equals(VALUE1)) {
      throw new RuntimeException(
          "TEST FAILED: "
              + KEY1
              + " property found"
              + " with value = "
              + value1
              + " but expected to be "
              + VALUE1);
    }

    String value2 = getProperty(props1, KEY2);
    if (value2 == null || !value2.equals(VALUE2)) {
      throw new RuntimeException(
          "TEST FAILED: "
              + KEY2
              + " property found"
              + " with value = "
              + value2
              + " but expected to be "
              + VALUE2);
    }

    String value3 = getProperty(props1, KEY3);
    if (value3 != null) {
      throw new RuntimeException(
          "TEST FAILED: " + KEY3 + " property found" + " but should not exist");
    }
  }
예제 #6
0
  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());
      }
    }
  }
예제 #7
0
class DBPortPool extends SimplePool<DBPort> {

  static class Holder {

    Holder(MongoOptions options) {
      _options = options;
    }

    DBPortPool get(InetSocketAddress addr) {

      DBPortPool p = _pools.get(addr);

      if (p != null) return p;

      synchronized (_pools) {
        p = _pools.get(addr);
        if (p != null) {
          return p;
        }

        p = new DBPortPool(addr, _options);
        _pools.put(addr, p);
        String name = "com.mongodb:type=ConnectionPool,host=" + addr.toString().replace(':', '_');

        try {
          ObjectName on = new ObjectName(name);
          if (_server.isRegistered(on)) {
            _server.unregisterMBean(on);
            Bytes.LOGGER.log(
                Level.INFO, "multiple Mongo instances for same host, jmx numbers might be off");
          }
          _server.registerMBean(p, on);
        } catch (JMException e) {
          Bytes.LOGGER.log(Level.WARNING, "jmx registration error, continuing", e);
        } catch (java.security.AccessControlException e) {
          Bytes.LOGGER.log(Level.WARNING, "jmx registration error, continuing", e);
        }
      }

      return p;
    }

    void close() {
      synchronized (_pools) {
        for (DBPortPool p : _pools.values()) {
          p.close();
        }
      }
    }

    final MongoOptions _options;
    final Map<InetSocketAddress, DBPortPool> _pools =
        Collections.synchronizedMap(new HashMap<InetSocketAddress, DBPortPool>());
    final MBeanServer _server = ManagementFactory.getPlatformMBeanServer();
  }

  // ----

  public static class NoMoreConnection extends MongoInternalException {
    NoMoreConnection(String msg) {
      super(msg);
    }
  }

  public static class SemaphoresOut extends NoMoreConnection {
    SemaphoresOut() {
      super("Out of semaphores to get db connection");
    }
  }

  public static class ConnectionWaitTimeOut extends NoMoreConnection {
    ConnectionWaitTimeOut(int timeout) {
      super("Connection wait timeout after " + timeout + " ms");
    }
  }

  // ----

  DBPortPool(InetSocketAddress addr, MongoOptions options) {
    super("DBPortPool-" + addr.toString(), options.connectionsPerHost, options.connectionsPerHost);
    _options = options;
    _addr = addr;
    _waitingSem =
        new Semaphore(
            _options.connectionsPerHost * _options.threadsAllowedToBlockForConnectionMultiplier);
  }

  protected long memSize(DBPort p) {
    return 0;
  }

  protected int pick(int iThink, boolean couldCreate) {
    final int id = Thread.currentThread().hashCode();
    final int s = _availSafe.size();
    for (int i = 0; i < s; i++) {
      DBPort p = _availSafe.get(i);
      if (p._lastThread == id) return i;
    }

    if (couldCreate) return -1;
    return iThink;
  }

  public DBPort get() {
    DBPort port = null;
    if (!_waitingSem.tryAcquire()) throw new SemaphoresOut();

    try {
      port = get(_options.maxWaitTime);
    } finally {
      _waitingSem.release();
    }

    if (port == null) throw new ConnectionWaitTimeOut(_options.maxWaitTime);

    port._lastThread = Thread.currentThread().hashCode();
    return port;
  }

  void gotError(Exception e) {
    if (e instanceof java.nio.channels.ClosedByInterruptException
        || e instanceof InterruptedException) {
      // this is probably a request that is taking too long
      // so usually doesn't mean there is a real db problem
      return;
    }

    if (e instanceof java.net.SocketTimeoutException && _options.socketTimeout > 0) {
      // we don't want to clear the port pool for 1 connection timing out
      return;
    }

    // We don't want to clear the entire pool for the occasional error.
    if (e instanceof SocketException) {
      if (recentFailures < ALLOWED_ERRORS_BEFORE_CLEAR) {
        return;
      }
    }

    Bytes.LOGGER.log(Level.INFO, "emptying DBPortPool b/c of error", e);
    clear();
  }

  void close() {
    clear();
  }

  public void cleanup(DBPort p) {
    p.close();
  }

  public boolean ok(DBPort t) {
    return _addr.equals(t._addr);
  }

  protected DBPort createNew() throws MongoInternalException {
    try {
      return new DBPort(_addr, this, _options);
    } catch (IOException ioe) {
      throw new MongoInternalException("can't create port to:" + _addr, ioe);
    }
  }

  public int getRecentFailures() {
    return recentFailures;
  }

  public void incrementRecentFailures() {
    _logger.warning("Failure recorded:" + _addr.toString());
    this.recentFailures++;
  }

  public void resetRecentFailures() {
    if (this.recentFailures > 0) {
      _logger.warning("Successful Request. Reseting recent failures:" + _addr.toString());
    }

    this.recentFailures = 0;
  }

  final MongoOptions _options;
  private final Semaphore _waitingSem;
  final InetSocketAddress _addr;
  boolean _everWorked = false;
  public static final Integer ALLOWED_ERRORS_BEFORE_CLEAR =
      Integer.valueOf(System.getProperty("MONGO.ERRORS_BEFORE_CLEAR", "5"));
  private Logger _logger = Logger.getLogger(DBPortPool.class.toString());

  /** The number of failures that this port pool has recently experienced. */
  private int recentFailures = 0;
}
예제 #8
0
  // Set K/V cache goals.
  // Allow (or disallow) allocations.
  // Called from the Cleaner, when "cacheUsed" has changed significantly.
  // Called from any FullGC notification, and HEAP/POJO_USED changed.
  // Called on any OOM allocation
  public static void set_goals(String msg, boolean oom, long bytes) {
    // Our best guess of free memory, as of the last GC cycle
    final long heapUsed = Boot.HEAP_USED_AT_LAST_GC;
    final long timeGC = Boot.TIME_AT_LAST_GC;
    final long freeHeap = MEM_MAX - heapUsed;
    assert freeHeap >= 0
        : "I am really confused about the heap usage; MEM_MAX=" + MEM_MAX + " heapUsed=" + heapUsed;
    // Current memory held in the K/V store.
    final long cacheUsage = myHisto.histo(false)._cached;
    // Our best guess of POJO object usage: Heap_used minus cache used
    final long pojoUsedGC = Math.max(heapUsed - cacheUsage, 0);

    // Block allocations if:
    // the cache is > 7/8 MEM_MAX, OR
    // we cannot allocate an equal amount of POJOs, pojoUsedGC > freeHeap.
    // Decay POJOS_USED by 1/8th every 5 sec: assume we got hit with a single
    // large allocation which is not repeating - so we do not need to have
    // double the POJO amount.
    // Keep at least 1/8th heap for caching.
    // Emergency-clean the cache down to the blocking level.
    long d = MEM_CRITICAL;
    // Decay POJO amount
    long p = pojoUsedGC;
    long age = (System.currentTimeMillis() - timeGC); // Age since last FullGC
    age = Math.min(age, 10 * 60 * 1000); // Clip at 10mins
    while ((age -= 5000) > 0) p = p - (p >> 3); // Decay effective POJO by 1/8th every 5sec
    d -= 2 * p - bytes; // Allow for the effective POJO, and again to throttle GC rate
    d = Math.max(d, MEM_MAX >> 3); // Keep at least 1/8th heap
    H2O.Cleaner.DESIRED = d;

    String m = "";
    if (cacheUsage > H2O.Cleaner.DESIRED) {
      m = (CAN_ALLOC ? "Blocking!  " : "blocked:   ");
      if (oom) setMemLow(); // Stop allocations; trigger emergency clean
      Boot.kick_store_cleaner();
    } else { // Else we are not *emergency* cleaning, but may be lazily cleaning.
      if (!CAN_ALLOC) m = "Unblocking:";
      else m = "MemGood:   ";
      setMemGood();
      if (oom) // Confused? OOM should have FullGCd should have set low-mem goals
      Log.warn(
            Sys.CLEAN,
            "OOM but no FullGC callback?  MEM_MAX = "
                + MEM_MAX
                + ", DESIRED = "
                + d
                + ", CACHE = "
                + cacheUsage
                + ", p = "
                + p
                + ", bytes = "
                + bytes);
    }

    // No logging if under memory pressure: can deadlock the cleaner thread
    if (Log.flag(Sys.CLEAN)) {
      String s =
          m
              + msg
              + ", HEAP_LAST_GC="
              + (heapUsed >> 20)
              + "M, KV="
              + (cacheUsage >> 20)
              + "M, POJO="
              + (pojoUsedGC >> 20)
              + "M, free="
              + (freeHeap >> 20)
              + "M, MAX="
              + (MEM_MAX >> 20)
              + "M, DESIRED="
              + (H2O.Cleaner.DESIRED >> 20)
              + "M"
              + (oom ? " OOM!" : " NO-OOM");
      if (CAN_ALLOC) Log.debug(Sys.CLEAN, s);
      else Log.unwrap(System.err, s);
    }
  }
  public static void main(String[] args) throws Exception {
    System.out.println(
        "Checking that all known MBeans that are "
            + "NotificationBroadcasters have sane "
            + "MBeanInfo.getNotifications()");

    System.out.println("Checking platform MBeans...");
    checkPlatformMBeans();

    URL codeBase = ClassLoader.getSystemResource("javax/management/MBeanServer.class");
    if (codeBase == null) {
      throw new Exception("Could not determine codeBase for " + MBeanServer.class);
    }

    System.out.println();
    System.out.println("Looking for standard MBeans...");
    String[] classes = findStandardMBeans(codeBase);

    System.out.println("Testing standard MBeans...");
    for (int i = 0; i < classes.length; i++) {
      String name = classes[i];
      Class<?> c;
      try {
        c = Class.forName(name);
      } catch (Throwable e) {
        System.out.println(name + ": cannot load (not public?): " + e);
        continue;
      }
      if (!NotificationBroadcaster.class.isAssignableFrom(c)) {
        System.out.println(name + ": not a NotificationBroadcaster");
        continue;
      }
      if (Modifier.isAbstract(c.getModifiers())) {
        System.out.println(name + ": abstract class");
        continue;
      }

      NotificationBroadcaster mbean;
      Constructor<?> constr;
      try {
        constr = c.getConstructor();
      } catch (Exception e) {
        System.out.println(name + ": no public no-arg constructor: " + e);
        continue;
      }
      try {
        mbean = (NotificationBroadcaster) constr.newInstance();
      } catch (Exception e) {
        System.out.println(name + ": no-arg constructor failed: " + e);
        continue;
      }

      check(mbean);
    }

    System.out.println();
    System.out.println("Testing some explicit cases...");

    check(new RelationService(false));
    /*
      We can't do this:
        check(new RequiredModelMBean());
      because the Model MBean spec more or less forces us to use the
      names GENERIC and ATTRIBUTE_CHANGE for its standard notifs.
    */
    checkRMIConnectorServer();

    System.out.println();
    if (!suspicious.isEmpty()) System.out.println("SUSPICIOUS CLASSES: " + suspicious);

    if (failed.isEmpty()) System.out.println("TEST PASSED");
    else {
      System.out.println("TEST FAILED: " + failed);
      System.exit(1);
    }
  }
예제 #10
0
  synchronized Result formatSummary() {
    Result result = new Result();
    ProxyClient proxyClient = vmPanel.getProxyClient();
    if (proxyClient.isDead()) {
      return null;
    }

    buf = new StringBuilder();
    append("<table cellpadding=1>");

    try {
      RuntimeMXBean rmBean = proxyClient.getRuntimeMXBean();
      CompilationMXBean cmpMBean = proxyClient.getCompilationMXBean();
      ThreadMXBean tmBean = proxyClient.getThreadMXBean();
      MemoryMXBean memoryBean = proxyClient.getMemoryMXBean();
      ClassLoadingMXBean clMBean = proxyClient.getClassLoadingMXBean();
      OperatingSystemMXBean osMBean = proxyClient.getOperatingSystemMXBean();
      com.sun.management.OperatingSystemMXBean sunOSMBean =
          proxyClient.getSunOperatingSystemMXBean();

      append("<tr><td colspan=4>");
      append("<center><b>" + Messages.SUMMARY_TAB_TAB_NAME + "</b></center>");
      String dateTime = headerDateTimeFormat.format(System.currentTimeMillis());
      append("<center>" + dateTime + "</center>");

      append(newDivider);

      { // VM info
        append(newLeftTable);
        append(Messages.CONNECTION_NAME, vmPanel.getDisplayName());
        append(
            Messages.VIRTUAL_MACHINE,
            Resources.format(
                Messages.SUMMARY_TAB_VM_VERSION, rmBean.getVmName(), rmBean.getVmVersion()));
        append(Messages.VENDOR, rmBean.getVmVendor());
        append(Messages.NAME, rmBean.getName());
        append(endTable);

        append(newRightTable);
        result.upTime = rmBean.getUptime();
        append(Messages.UPTIME, formatTime(result.upTime));
        if (sunOSMBean != null) {
          result.processCpuTime = sunOSMBean.getProcessCpuTime();
          append(Messages.PROCESS_CPU_TIME, formatNanoTime(result.processCpuTime));
        }

        if (cmpMBean != null) {
          append(Messages.JIT_COMPILER, cmpMBean.getName());
          append(
              Messages.TOTAL_COMPILE_TIME,
              cmpMBean.isCompilationTimeMonitoringSupported()
                  ? formatTime(cmpMBean.getTotalCompilationTime())
                  : Messages.UNAVAILABLE);
        } else {
          append(Messages.JIT_COMPILER, Messages.UNAVAILABLE);
        }
        append(endTable);
      }

      append(newDivider);

      { // Threads and Classes
        append(newLeftTable);
        int tlCount = tmBean.getThreadCount();
        int tdCount = tmBean.getDaemonThreadCount();
        int tpCount = tmBean.getPeakThreadCount();
        long ttCount = tmBean.getTotalStartedThreadCount();
        String[] strings1 =
            formatLongs(
                tlCount, tpCount,
                tdCount, ttCount);
        append(Messages.LIVE_THREADS, strings1[0]);
        append(Messages.PEAK, strings1[1]);
        append(Messages.DAEMON_THREADS, strings1[2]);
        append(Messages.TOTAL_THREADS_STARTED, strings1[3]);
        append(endTable);

        append(newRightTable);
        long clCount = clMBean.getLoadedClassCount();
        long cuCount = clMBean.getUnloadedClassCount();
        long ctCount = clMBean.getTotalLoadedClassCount();
        String[] strings2 = formatLongs(clCount, cuCount, ctCount);
        append(Messages.CURRENT_CLASSES_LOADED, strings2[0]);
        append(Messages.TOTAL_CLASSES_LOADED, strings2[2]);
        append(Messages.TOTAL_CLASSES_UNLOADED, strings2[1]);
        append(null, "");
        append(endTable);
      }

      append(newDivider);

      { // Memory
        MemoryUsage u = memoryBean.getHeapMemoryUsage();

        append(newLeftTable);
        String[] strings1 = formatKByteStrings(u.getUsed(), u.getMax());
        append(Messages.CURRENT_HEAP_SIZE, strings1[0]);
        append(Messages.MAXIMUM_HEAP_SIZE, strings1[1]);
        append(endTable);

        append(newRightTable);
        String[] strings2 = formatKByteStrings(u.getCommitted());
        append(Messages.COMMITTED_MEMORY, strings2[0]);
        append(
            Messages.SUMMARY_TAB_PENDING_FINALIZATION_LABEL,
            Messages.SUMMARY_TAB_PENDING_FINALIZATION_VALUE,
            memoryBean.getObjectPendingFinalizationCount());
        append(endTable);

        append(newTable);
        Collection<GarbageCollectorMXBean> garbageCollectors =
            proxyClient.getGarbageCollectorMXBeans();
        for (GarbageCollectorMXBean garbageCollectorMBean : garbageCollectors) {
          String gcName = garbageCollectorMBean.getName();
          long gcCount = garbageCollectorMBean.getCollectionCount();
          long gcTime = garbageCollectorMBean.getCollectionTime();

          append(
              Messages.GARBAGE_COLLECTOR,
              Resources.format(
                  Messages.GC_INFO,
                  gcName,
                  gcCount,
                  (gcTime >= 0) ? formatTime(gcTime) : Messages.UNAVAILABLE),
              4);
        }
        append(endTable);
      }

      append(newDivider);

      { // Operating System info
        append(newLeftTable);
        String osName = osMBean.getName();
        String osVersion = osMBean.getVersion();
        String osArch = osMBean.getArch();
        result.nCPUs = osMBean.getAvailableProcessors();
        append(Messages.OPERATING_SYSTEM, osName + " " + osVersion);
        append(Messages.ARCHITECTURE, osArch);
        append(Messages.NUMBER_OF_PROCESSORS, result.nCPUs + "");

        if (pathSeparator == null) {
          // Must use separator of remote OS, not File.pathSeparator
          // from this local VM. In the future, consider using
          // RuntimeMXBean to get the remote system property.
          pathSeparator = osName.startsWith("Windows ") ? ";" : ":";
        }

        if (sunOSMBean != null) {
          String[] kbStrings1 = formatKByteStrings(sunOSMBean.getCommittedVirtualMemorySize());

          String[] kbStrings2 =
              formatKByteStrings(
                  sunOSMBean.getTotalPhysicalMemorySize(),
                  sunOSMBean.getFreePhysicalMemorySize(),
                  sunOSMBean.getTotalSwapSpaceSize(),
                  sunOSMBean.getFreeSwapSpaceSize());

          append(Messages.COMMITTED_VIRTUAL_MEMORY, kbStrings1[0]);
          append(endTable);

          append(newRightTable);
          append(Messages.TOTAL_PHYSICAL_MEMORY, kbStrings2[0]);
          append(Messages.FREE_PHYSICAL_MEMORY, kbStrings2[1]);
          append(Messages.TOTAL_SWAP_SPACE, kbStrings2[2]);
          append(Messages.FREE_SWAP_SPACE, kbStrings2[3]);
        }

        append(endTable);
      }

      append(newDivider);

      { // VM arguments and paths
        append(newTable);
        String args = "";
        java.util.List<String> inputArguments = rmBean.getInputArguments();
        for (String arg : inputArguments) {
          args += arg + " ";
        }
        append(Messages.VM_ARGUMENTS, args, 4);
        append(Messages.CLASS_PATH, rmBean.getClassPath(), 4);
        append(Messages.LIBRARY_PATH, rmBean.getLibraryPath(), 4);
        append(
            Messages.BOOT_CLASS_PATH,
            rmBean.isBootClassPathSupported() ? rmBean.getBootClassPath() : Messages.UNAVAILABLE,
            4);
        append(endTable);
      }
    } catch (IOException e) {
      if (JConsole.isDebug()) {
        e.printStackTrace();
      }
      proxyClient.markAsDead();
      return null;
    } catch (UndeclaredThrowableException e) {
      if (JConsole.isDebug()) {
        e.printStackTrace();
      }
      proxyClient.markAsDead();
      return null;
    }

    append("</table>");

    result.timeStamp = System.currentTimeMillis();
    result.summary = buf.toString();

    return result;
  }
예제 #11
0
  /** Exports stats related to the JVM and runtime environment. */
  public static void export() {
    final OperatingSystemMXBean osMbean = ManagementFactory.getOperatingSystemMXBean();
    if (osMbean instanceof com.sun.management.OperatingSystemMXBean) {
      final com.sun.management.OperatingSystemMXBean sunOsMbean =
          (com.sun.management.OperatingSystemMXBean) osMbean;

      Stats.exportAll(
          ImmutableList.<Stat<? extends Number>>builder()
              .add(
                  new StatImpl<Long>("system_free_physical_memory_mb") {
                    @Override
                    public Long read() {
                      return sunOsMbean.getFreePhysicalMemorySize() / BYTES_PER_MB;
                    }
                  })
              .add(
                  new StatImpl<Long>("system_free_swap_mb") {
                    @Override
                    public Long read() {
                      return sunOsMbean.getFreeSwapSpaceSize() / BYTES_PER_MB;
                    }
                  })
              .add(
                  Rate.of(
                          new StatImpl<Long>("process_cpu_time_nanos") {
                            @Override
                            public Long read() {
                              return sunOsMbean.getProcessCpuTime();
                            }
                          })
                      .withName("process_cpu_cores_utilized")
                      .withScaleFactor(SECS_PER_NANO)
                      .build())
              .build());
    }
    if (osMbean instanceof com.sun.management.UnixOperatingSystemMXBean) {
      final com.sun.management.UnixOperatingSystemMXBean unixOsMbean =
          (com.sun.management.UnixOperatingSystemMXBean) osMbean;

      Stats.exportAll(
          ImmutableList.<Stat<? extends Number>>builder()
              .add(
                  new StatImpl<Long>("process_max_fd_count") {
                    @Override
                    public Long read() {
                      return unixOsMbean.getMaxFileDescriptorCount();
                    }
                  })
              .add(
                  new StatImpl<Long>("process_open_fd_count") {
                    @Override
                    public Long read() {
                      return unixOsMbean.getOpenFileDescriptorCount();
                    }
                  })
              .build());
    }

    final Runtime runtime = Runtime.getRuntime();
    final ClassLoadingMXBean classLoadingBean = ManagementFactory.getClassLoadingMXBean();
    MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
    final MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage();
    final MemoryUsage nonHeapUsage = memoryBean.getNonHeapMemoryUsage();
    final ThreadMXBean threads = ManagementFactory.getThreadMXBean();
    final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();

    Stats.exportAll(
        ImmutableList.<Stat<? extends Number>>builder()
            .add(
                new StatImpl<Long>("jvm_time_ms") {
                  @Override
                  public Long read() {
                    return System.currentTimeMillis();
                  }
                })
            .add(
                new StatImpl<Integer>("jvm_available_processors") {
                  @Override
                  public Integer read() {
                    return runtime.availableProcessors();
                  }
                })
            .add(
                new StatImpl<Long>("jvm_memory_free_mb") {
                  @Override
                  public Long read() {
                    return runtime.freeMemory() / BYTES_PER_MB;
                  }
                })
            .add(
                new StatImpl<Long>("jvm_memory_max_mb") {
                  @Override
                  public Long read() {
                    return runtime.maxMemory() / BYTES_PER_MB;
                  }
                })
            .add(
                new StatImpl<Long>("jvm_memory_mb_total") {
                  @Override
                  public Long read() {
                    return runtime.totalMemory() / BYTES_PER_MB;
                  }
                })
            .add(
                new StatImpl<Integer>("jvm_class_loaded_count") {
                  @Override
                  public Integer read() {
                    return classLoadingBean.getLoadedClassCount();
                  }
                })
            .add(
                new StatImpl<Long>("jvm_class_total_loaded_count") {
                  @Override
                  public Long read() {
                    return classLoadingBean.getTotalLoadedClassCount();
                  }
                })
            .add(
                new StatImpl<Long>("jvm_class_unloaded_count") {
                  @Override
                  public Long read() {
                    return classLoadingBean.getUnloadedClassCount();
                  }
                })
            .add(
                new StatImpl<Long>("jvm_gc_collection_time_ms") {
                  @Override
                  public Long read() {
                    long collectionTimeMs = 0;
                    for (GarbageCollectorMXBean bean :
                        ManagementFactory.getGarbageCollectorMXBeans()) {
                      collectionTimeMs += bean.getCollectionTime();
                    }
                    return collectionTimeMs;
                  }
                })
            .add(
                new StatImpl<Long>("jvm_gc_collection_count") {
                  @Override
                  public Long read() {
                    long collections = 0;
                    for (GarbageCollectorMXBean bean :
                        ManagementFactory.getGarbageCollectorMXBeans()) {
                      collections += bean.getCollectionCount();
                    }
                    return collections;
                  }
                })
            .add(
                new StatImpl<Long>("jvm_memory_heap_mb_used") {
                  @Override
                  public Long read() {
                    return heapUsage.getUsed() / BYTES_PER_MB;
                  }
                })
            .add(
                new StatImpl<Long>("jvm_memory_heap_mb_committed") {
                  @Override
                  public Long read() {
                    return heapUsage.getCommitted() / BYTES_PER_MB;
                  }
                })
            .add(
                new StatImpl<Long>("jvm_memory_heap_mb_max") {
                  @Override
                  public Long read() {
                    return heapUsage.getMax() / BYTES_PER_MB;
                  }
                })
            .add(
                new StatImpl<Long>("jvm_memory_non_heap_mb_used") {
                  @Override
                  public Long read() {
                    return nonHeapUsage.getUsed() / BYTES_PER_MB;
                  }
                })
            .add(
                new StatImpl<Long>("jvm_memory_non_heap_mb_committed") {
                  @Override
                  public Long read() {
                    return nonHeapUsage.getCommitted() / BYTES_PER_MB;
                  }
                })
            .add(
                new StatImpl<Long>("jvm_memory_non_heap_mb_max") {
                  @Override
                  public Long read() {
                    return nonHeapUsage.getMax() / BYTES_PER_MB;
                  }
                })
            .add(
                new StatImpl<Long>("jvm_uptime_secs") {
                  @Override
                  public Long read() {
                    return runtimeMXBean.getUptime() / 1000;
                  }
                })
            .add(
                new StatImpl<Double>("system_load_avg") {
                  @Override
                  public Double read() {
                    return osMbean.getSystemLoadAverage();
                  }
                })
            .add(
                new StatImpl<Integer>("jvm_threads_peak") {
                  @Override
                  public Integer read() {
                    return threads.getPeakThreadCount();
                  }
                })
            .add(
                new StatImpl<Long>("jvm_threads_started") {
                  @Override
                  public Long read() {
                    return threads.getTotalStartedThreadCount();
                  }
                })
            .add(
                new StatImpl<Integer>("jvm_threads_daemon") {
                  @Override
                  public Integer read() {
                    return threads.getDaemonThreadCount();
                  }
                })
            .add(
                new StatImpl<Integer>("jvm_threads_active") {
                  @Override
                  public Integer read() {
                    return threads.getThreadCount();
                  }
                })
            .build());

    // Export per memory pool gc time and cycle count like Ostrich
    // This is based on code in Bridcage: https://cgit.twitter.biz/birdcage/tree/ \
    // ostrich/src/main/scala/com/twitter/ostrich/stats/StatsCollection.scala
    Stats.exportAll(
        Iterables.transform(
            ManagementFactory.getGarbageCollectorMXBeans(),
            new Function<GarbageCollectorMXBean, Stat<? extends Number>>() {
              @Override
              public Stat<? extends Number> apply(final GarbageCollectorMXBean gcMXBean) {
                return new StatImpl<Long>(
                    "jvm_gc_" + Stats.normalizeName(gcMXBean.getName()) + "_collection_count") {
                  @Override
                  public Long read() {
                    return gcMXBean.getCollectionCount();
                  }
                };
              }
            }));

    Stats.exportAll(
        Iterables.transform(
            ManagementFactory.getGarbageCollectorMXBeans(),
            new Function<GarbageCollectorMXBean, Stat<? extends Number>>() {
              @Override
              public Stat<? extends Number> apply(final GarbageCollectorMXBean gcMXBean) {
                return new StatImpl<Long>(
                    "jvm_gc_" + Stats.normalizeName(gcMXBean.getName()) + "_collection_time_ms") {
                  @Override
                  public Long read() {
                    return gcMXBean.getCollectionTime();
                  }
                };
              }
            }));

    Stats.exportString(
        new StatImpl<String>("jvm_input_arguments") {
          @Override
          public String read() {
            return runtimeMXBean.getInputArguments().toString();
          }
        });

    for (final String property : System.getProperties().stringPropertyNames()) {
      Stats.exportString(
          new StatImpl<String>("jvm_prop_" + Stats.normalizeName(property)) {
            @Override
            public String read() {
              return System.getProperty(property);
            }
          });
    }
  }