private void checkCompatibility() {
      OperatingSystemMXBean osmx = ManagementFactory.getOperatingSystemMXBean();
      if (osmx == null) {
        throw new UnsupportedOperationException("Failed to get OperatingSystemMXBean");
      }
      Class[] interfaces = osmx.getClass().getInterfaces();
      boolean hasInterface = false;
      if (interfaces != null) {
        for (Class i : interfaces) {
          if ("com.sun.management.OperatingSystemMXBean".equals(i.getName())
              || "com.sun.management.UnixOperatingSystemMXBean".equals(i.getName())) {
            hasInterface = true;
            break;
          }
        }
      }

      if (!hasInterface) {
        throw new UnsupportedOperationException(
            "Incompatible OperatingSystemMXBean class: " + osmx.getClass().getName());
      }

      RuntimeMXBean rtmx = ManagementFactory.getRuntimeMXBean();
      if (rtmx == null) {
        throw new UnsupportedOperationException("Failed to get RuntimeMXBean");
      }
    }
  static class MinuteReport {

    final long time = System.currentTimeMillis() / 1000;

    final TicksRecord ticksRecord = new TicksRecord();
    final PingRecord pingRecord = new PingRecord();
    final TimingData fst = TimingsManager.FULL_SERVER_TICK.minuteData.clone();
    final double tps = 1E9 / (System.nanoTime() - lastMinuteTime) * this.ticksRecord.timed;
    final double usedMemory = TimingsManager.FULL_SERVER_TICK.avgUsedMemory;
    final double freeMemory = TimingsManager.FULL_SERVER_TICK.avgFreeMemory;
    final double loadAvg = ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage();

    public JsonArray export() {
      return JSONUtil.arrayOf(
          this.time,
          Math.round(this.tps * 100D) / 100D,
          Math.round(this.pingRecord.avg * 100D) / 100D,
          this.fst.export(),
          JSONUtil.arrayOf(
              this.ticksRecord.timed,
              this.ticksRecord.player,
              this.ticksRecord.entity,
              this.ticksRecord.activatedEntity,
              this.ticksRecord.tileEntity),
          this.usedMemory,
          this.freeMemory,
          this.loadAvg);
    }
  }
Beispiel #3
0
  private class PerformanceMonitor {
    private long lastSystemTime = 0;
    private long lastProcessCpuTime = 0;
    OperatingSystemMXBean osMxBean =
        (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();

    public synchronized double getCpuUsage() {
      if (lastSystemTime == 0) {
        baselineCounters();
        return 0;
      }

      long systemTime = System.nanoTime();
      long processCpuTime = osMxBean.getProcessCpuTime();

      double cpuUsage =
          (double) (processCpuTime - lastProcessCpuTime) / (systemTime - lastSystemTime);

      lastSystemTime = systemTime;
      lastProcessCpuTime = processCpuTime;

      return cpuUsage / osMxBean.getAvailableProcessors();
    }

    private void baselineCounters() {
      lastSystemTime = System.nanoTime();
      lastProcessCpuTime = osMxBean.getProcessCpuTime();
    }
  }
Beispiel #4
0
  static {
    try {

      InetAddress addr = InetAddress.getLocalHost();
      HOST_NAME = addr.getHostName();
      Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
      for (NetworkInterface netint : Collections.list(nets)) {
        if (null != netint.getHardwareAddress()) {
          List<InterfaceAddress> list = netint.getInterfaceAddresses();
          for (InterfaceAddress interfaceAddress : list) {
            InetAddress ip = interfaceAddress.getAddress();
            if (ip instanceof Inet4Address) {
              HOST_IP += interfaceAddress.getAddress().toString();
            }
          }
        }
      }
      HOST_IP = HOST_IP.replaceAll("null", "");
    } catch (Exception e) {
      System.out.println("获取服务器IP出错");
    }

    try {
      osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();

      TotalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;
    } catch (Exception e) {
      System.out.println("获取系统信息失败");
      e.printStackTrace();
    }
  }
Beispiel #5
0
  public static void main(String args[]) {

    MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();

    long init = heapMemoryUsage.getInit();
    long used = heapMemoryUsage.getUsed();
    long max = heapMemoryUsage.getMax();
    long committed = heapMemoryUsage.getCommitted();
    long free = max - used;
    int usedPercent = (int) (used / max);
    int freePercent = (int) (usedPercent / max);

    MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage();

    List<GarbageCollectorMXBean> garbageCollectorMXBeans =
        ManagementFactory.getGarbageCollectorMXBeans();

    List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();

    com.sun.management.OperatingSystemMXBean operatingSystemMXBean =
        (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    long commitVirtual = operatingSystemMXBean.getCommittedVirtualMemorySize();

    println(init, used, max, committed);
    println(commitVirtual);
  }
  @Override
  public OsStats osStats() {
    final long uptime = -1L;
    final double systemLoadAverage =
        ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage();
    final double[] loadAverage =
        systemLoadAverage < 0.0d ? new double[0] : new double[] {systemLoadAverage};
    final Processor processor =
        Processor.create(
            "Unknown",
            "Unknown",
            -1,
            -1,
            -1,
            -1,
            -1L,
            (short) -1,
            (short) -1,
            (short) -1,
            (short) -1);
    final Memory memory = Memory.create(-1L, -1L, (short) -1, -1L, (short) -1, -1L, -1L);
    final Swap swap = Swap.create(-1L, -1L, -1L);

    return OsStats.create(loadAverage, uptime, processor, memory, swap);
  }
 public AutoConfigurator(String dbPath, boolean useMemoryMapped, boolean dump) {
   this.dbPath = dbPath;
   this.useMemoryMapped = useMemoryMapped;
   OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
   long mem = -1;
   try {
     Class<?> beanClass = Class.forName("com.sun.management.OperatingSystemMXBean");
     Method method = beanClass.getMethod("getTotalPhysicalMemorySize");
     mem = (Long) method.invoke(osBean);
   } catch (
       Exception e) { // ok we tried but probably 1.5 JVM or other class library implementation
   } catch (
       LinkageError e) { // ok we tried but probably 1.5 JVM or other class library implementation
   }
   if (mem != -1) {
     totalPhysicalMemMb = (int) (mem / 1024 / 1024);
   } else {
     totalPhysicalMemMb = -1;
   }
   mem = Runtime.getRuntime().maxMemory();
   maxVmUsageMb = (int) (mem / 1024 / 1024);
   if (dump) {
     System.out.println(getNiceMemoryInformation());
   }
 }
 /**
  * 获取当前系统的内存占用率
  *
  * @return
  */
 public double getMemoryState() {
   OperatingSystemMXBean osmb =
       (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
   double totalMem = osmb.getTotalPhysicalMemorySize() / 1024 / 1024;
   double freeMem = osmb.getFreePhysicalMemorySize() / 1024 / 1024;
   double memPercentage = 100 * (totalMem - freeMem) / totalMem;
   return memPercentage;
 }
Beispiel #9
0
 static {
   ExecutionPoolPulseWorker worker = new ExecutionPoolPulseWorker();
   int processorCount = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
   for (int i = 0; i < processorCount; i++) {
     Thread t = new Thread(worker);
     t.setDaemon(true);
     t.setName("ExecutionPoolPulseWorker(" + i + ")");
     t.start();
   }
 }
Beispiel #10
0
 public String checkCPUInfo() {
   com.sun.management.OperatingSystemMXBean os =
       (com.sun.management.OperatingSystemMXBean)
           java.lang.management.ManagementFactory.getOperatingSystemMXBean();
   return "Available processors: "
       + os.getAvailableProcessors()
       + "; System avg load: "
       + os.getSystemLoadAverage()
       + "; ";
 }
Beispiel #11
0
  public static long committedVirtualMemorySize() {

    if (oracleJVMAndUnix) {

      UnixOperatingSystemMXBean unix =
          (UnixOperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
      return unix.getCommittedVirtualMemorySize();
    } else {
      return -1;
    }
  }
Beispiel #12
0
  public static long openFileDescriptorCount() {

    if (oracleJVMAndUnix) {

      UnixOperatingSystemMXBean unix =
          (UnixOperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
      return unix.getOpenFileDescriptorCount();
    } else {
      return -1;
    }
  }
Beispiel #13
0
 public String checkRAMInfo() {
   com.sun.management.OperatingSystemMXBean os =
       (com.sun.management.OperatingSystemMXBean)
           java.lang.management.ManagementFactory.getOperatingSystemMXBean();
   long physicalMemorySize = os.getTotalPhysicalMemorySize() - os.getFreePhysicalMemorySize();
   return "memoryUsage (MB): ("
       + (physicalMemorySize / 1024 / 1024)
       + "/"
       + (os.getTotalPhysicalMemorySize() / 1024 / 1024)
       + "; ";
 }
Beispiel #14
0
  public static long freeSwapSpaceSize() {

    if (oracleJVMAndUnix) {

      UnixOperatingSystemMXBean unix =
          (UnixOperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
      return unix.getFreeSwapSpaceSize();
    } else {
      return -1;
    }
  }
Beispiel #15
0
  public static long totalPhysicalMemorySize() {

    if (oracleJVMAndUnix) {

      UnixOperatingSystemMXBean unix =
          (UnixOperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
      return unix.getTotalPhysicalMemorySize();
    } else {
      return -1;
    }
  }
Beispiel #16
0
  public static double processCpuLoad() {

    if (oracleJVMAndUnix) {

      UnixOperatingSystemMXBean unix =
          (UnixOperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
      return unix.getProcessCpuLoad();
    } else {
      return -1;
    }
  }
 private long getCpuTime() {
   OperatingSystemMXBean osmx = ManagementFactory.getOperatingSystemMXBean();
   try {
     Method getProcessCpuTime = osmx.getClass().getDeclaredMethod("getProcessCpuTime");
     getProcessCpuTime.setAccessible(true);
     Object o = getProcessCpuTime.invoke(osmx);
     if (o instanceof Long) {
       return (Long) o;
     }
   } catch (Throwable e) {
   }
   return 0L;
 }
 private void jvmSummary() {
   OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
   RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
   stdout.format(
       "JVM: %s %s %s\n",
       runtimeBean.getVmVendor(), runtimeBean.getVmName(), runtimeBean.getVmVersion());
   stdout.format("  on %s %s %s\n", "", osBean.getName(), osBean.getVersion(), osBean.getArch());
   try {
     stdout.format(
         "  running as %s on %s\n",
         System.getProperty("user.name"), InetAddress.getLocalHost().getHostName());
   } catch (UnknownHostException e) {
   }
   stdout.format("  cwd  %s\n", path(new File(".").getAbsoluteFile().getParentFile()));
   stdout.format("  site %s\n", path(sitePath));
 }
Beispiel #19
0
 public static ScheduledExecutorService getExecutor(
     ThreadGroup group, String namePrefix, int threadCount, boolean preStart) {
   if (threadCount == 0) {
     threadCount = 1;
   } else if (threadCount < 0) {
     int numCpus = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
     threadCount = Math.abs(threadCount) * numCpus;
   }
   ThreadFactory threadFactory = createThreadFactory(group, namePrefix);
   ScheduledThreadPoolExecutor executor =
       new ScheduledThreadPoolExecutor(threadCount, threadFactory);
   if (preStart) {
     executor.prestartAllCoreThreads();
   }
   return executor;
 }
  public MonitorInfoBean getMonitorInfoBean() throws Exception {
    int kb = 1024;

    // 可使用內存
    long totalMemory = Runtime.getRuntime().totalMemory() / kb;
    // 剩餘內存
    long freeMemory = Runtime.getRuntime().freeMemory() / kb;
    // 最大可使用內存
    long maxMemory = Runtime.getRuntime().maxMemory() / kb;

    OperatingSystemMXBean osmxb =
        (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();

    // 操作系統
    String osName = System.getProperty("os.name");
    // 總物理內存
    long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;
    // 剩餘的物理內存
    long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / kb;
    // 已使用的物理內存
    long usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb.getFreePhysicalMemorySize()) / kb;

    // 獲得線程總數
    ThreadGroup parentThread;
    for (parentThread = Thread.currentThread().getThreadGroup();
        parentThread.getParent() != null;
        parentThread = parentThread.getParent()) ;
    int totalThread = parentThread.activeCount();

    double cpuRatio = 0;
    if (osName.toLowerCase().startsWith("windows")) {
      cpuRatio = this.getCpuRatioForWindows();
    }

    // 返回對象
    MonitorInfoBean infoBean = new MonitorInfoBean();
    infoBean.setFreeMemory(freeMemory);
    infoBean.setFreePhysicalMemorySize(freePhysicalMemorySize);
    infoBean.setMaxMemory(maxMemory);
    infoBean.setOsName(osName);
    infoBean.setTotalMemory(totalMemory);
    infoBean.setTotalMemorySize(totalMemorySize);
    infoBean.setTotalThread(totalThread);
    infoBean.setUsedMemory(usedMemory);
    infoBean.setCpuRatio(cpuRatio);
    return infoBean;
  }
  public synchronized void addMutation(String table, Mutation m) throws MutationsRejectedException {

    if (closed) throw new IllegalStateException("Closed");
    if (m.size() == 0) throw new IllegalArgumentException("Can not add empty mutations");

    checkForFailures();

    while ((totalMemUsed >= maxMem || flushing) && !somethingFailed) {
      waitRTE();
    }

    // do checks again since things could have changed while waiting and not holding lock
    if (closed) throw new IllegalStateException("Closed");
    checkForFailures();

    if (startTime == 0) {
      startTime = System.currentTimeMillis();

      List<GarbageCollectorMXBean> gcmBeans = ManagementFactory.getGarbageCollectorMXBeans();
      for (GarbageCollectorMXBean garbageCollectorMXBean : gcmBeans) {
        initialGCTimes += garbageCollectorMXBean.getCollectionTime();
      }

      CompilationMXBean compMxBean = ManagementFactory.getCompilationMXBean();
      if (compMxBean.isCompilationTimeMonitoringSupported()) {
        initialCompileTimes = compMxBean.getTotalCompilationTime();
      }

      initialSystemLoad = ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage();
    }

    // create a copy of mutation so that after this method returns the user
    // is free to reuse the mutation object, like calling readFields... this
    // is important for the case where a mutation is passed from map to reduce
    // to batch writer... the map reduce code will keep passing the same mutation
    // object into the reduce method
    m = new Mutation(m);

    totalMemUsed += m.estimatedMemoryUsed();
    mutations.addMutation(table, m);
    totalAdded++;

    if (mutations.getMemoryUsed() >= maxMem / 2) {
      startProcessing();
      checkForFailures();
    }
  }
Beispiel #22
0
 private static long physicalMemory() {
   OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
   long mem;
   try {
     Class<?> beanClass =
         Thread.currentThread()
             .getContextClassLoader()
             .loadClass("com.sun.management.OperatingSystemMXBean");
     Method method = beanClass.getMethod("getTotalPhysicalMemorySize");
     mem = (Long) method.invoke(osBean);
   } catch (Exception e) {
     // ok we tried but probably 1.5 JVM or other class library implementation
     mem = -1; // Be explicit about how this error is handled.
   } catch (LinkageError e) {
     // ok we tried but probably 1.5 JVM or other class library implementation
     mem = -1; // Be explicit about how this error is handled.
   }
   return mem;
 }
  @Test
  public void testLargeMessageFileLeak() throws Exception {
    OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();

    // only run this on *nix systems which will have the
    // com.sun.management.UnixOperatingSystemMXBean (needed to check open file count)
    Assume.assumeTrue(os instanceof UnixOperatingSystemMXBean);

    long fdBaseline = ((UnixOperatingSystemMXBean) os).getOpenFileDescriptorCount();
    final int SIZE = 2 * 1024;
    SimpleString dla = new SimpleString("DLA");
    SimpleString qName = new SimpleString("q1");
    SimpleString adName = new SimpleString("ad1");

    AddressSettings addressSettings =
        new AddressSettings().setMaxDeliveryAttempts(1).setDeadLetterAddress(dla);
    server.getAddressSettingsRepository().addMatch(adName.toString(), addressSettings);
    SimpleString dlq = new SimpleString("DLQ1");
    clientSession.createQueue(dla, dlq, null, false);
    clientSession.createQueue(adName, qName, null, false);
    for (int i = 0; i < 10; i++) {
      ClientProducer producer = clientSession.createProducer(adName);
      ClientMessage clientFile = clientSession.createMessage(true);
      clientFile.setBodyInputStream(ActiveMQTestBase.createFakeLargeStream(SIZE));
      producer.send(clientFile);
      clientSession.start();
      ClientConsumer clientConsumer = clientSession.createConsumer(qName);
      ClientMessage m = clientConsumer.receive(500);
      m.acknowledge();
      Assert.assertNotNull(m);

      // force a cancel
      clientSession.rollback();
      m = clientConsumer.receiveImmediate();
      Assert.assertNull(m);
      clientConsumer.close();
    }
    assertEquals(
        "File descriptors are leaking",
        0,
        ((UnixOperatingSystemMXBean) os).getOpenFileDescriptorCount() - fdBaseline);
  }
  /* (non-Javadoc)
   * @see org.epics.pvaccess.server.plugins.BeaconServerStatusProvider#getServerStatusData()
   */
  public PVField getServerStatusData() {

    status
        .getIntField("connections")
        .put(context.getTransportRegistry().numberOfActiveTransports());
    status.getLongField("allocatedMemory").put(Runtime.getRuntime().totalMemory());
    status.getLongField("freeMemory").put(Runtime.getRuntime().freeMemory());

    ThreadMXBean threadMBean = ManagementFactory.getThreadMXBean();
    status.getIntField("threads").put(threadMBean.getThreadCount());

    final long[] deadlocks =
        threadMBean.isSynchronizerUsageSupported()
            ? threadMBean.findDeadlockedThreads()
            : threadMBean.findMonitorDeadlockedThreads();
    status.getIntField("deadlocks").put((deadlocks != null) ? deadlocks.length : 0);

    OperatingSystemMXBean osMBean = ManagementFactory.getOperatingSystemMXBean();
    status.getDoubleField("averageSystemLoad").put(osMBean.getSystemLoadAverage());

    return status;
  }
 public OperatingSystemMetricSet() {
   this(ManagementFactory.getOperatingSystemMXBean());
 }
Beispiel #26
0
public class OsProbe {

  private static final OperatingSystemMXBean osMxBean =
      ManagementFactory.getOperatingSystemMXBean();

  private static final Method getFreePhysicalMemorySize;
  private static final Method getTotalPhysicalMemorySize;
  private static final Method getFreeSwapSpaceSize;
  private static final Method getTotalSwapSpaceSize;
  private static final Method getSystemLoadAverage;
  private static final Method getSystemCpuLoad;

  static {
    getFreePhysicalMemorySize = getMethod("getFreePhysicalMemorySize");
    getTotalPhysicalMemorySize = getMethod("getTotalPhysicalMemorySize");
    getFreeSwapSpaceSize = getMethod("getFreeSwapSpaceSize");
    getTotalSwapSpaceSize = getMethod("getTotalSwapSpaceSize");
    getSystemLoadAverage = getMethod("getSystemLoadAverage");
    getSystemCpuLoad = getMethod("getSystemCpuLoad");
  }

  /** Returns the amount of free physical memory in bytes. */
  public long getFreePhysicalMemorySize() {
    if (getFreePhysicalMemorySize == null) {
      return -1;
    }
    try {
      return (long) getFreePhysicalMemorySize.invoke(osMxBean);
    } catch (Throwable t) {
      return -1;
    }
  }

  /** Returns the total amount of physical memory in bytes. */
  public long getTotalPhysicalMemorySize() {
    if (getTotalPhysicalMemorySize == null) {
      return -1;
    }
    try {
      return (long) getTotalPhysicalMemorySize.invoke(osMxBean);
    } catch (Throwable t) {
      return -1;
    }
  }

  /** Returns the amount of free swap space in bytes. */
  public long getFreeSwapSpaceSize() {
    if (getFreeSwapSpaceSize == null) {
      return -1;
    }
    try {
      return (long) getFreeSwapSpaceSize.invoke(osMxBean);
    } catch (Throwable t) {
      return -1;
    }
  }

  /** Returns the total amount of swap space in bytes. */
  public long getTotalSwapSpaceSize() {
    if (getTotalSwapSpaceSize == null) {
      return -1;
    }
    try {
      return (long) getTotalSwapSpaceSize.invoke(osMxBean);
    } catch (Throwable t) {
      return -1;
    }
  }

  /** Returns the system load averages */
  public double[] getSystemLoadAverage() {
    if (Constants.LINUX) {
      double[] loadAverage = readProcLoadavg("/proc/loadavg");
      if (loadAverage != null) {
        return loadAverage;
      }
      // fallback
    }
    if (getSystemLoadAverage == null) {
      return null;
    }
    try {
      double oneMinuteLoadAverage = (double) getSystemLoadAverage.invoke(osMxBean);
      return new double[] {oneMinuteLoadAverage, -1, -1};
    } catch (Throwable t) {
      return null;
    }
  }

  @SuppressForbidden(reason = "access /proc")
  private static double[] readProcLoadavg(String procLoadavg) {
    try {
      List<String> lines = Files.readAllLines(PathUtils.get(procLoadavg));
      if (!lines.isEmpty()) {
        String[] fields = lines.get(0).split("\\s+");
        return new double[] {
          Double.parseDouble(fields[0]),
          Double.parseDouble(fields[1]),
          Double.parseDouble(fields[2])
        };
      }
    } catch (IOException e) {
      // do not fail Elasticsearch if something unexpected
      // happens here
    }
    return null;
  }

  public short getSystemCpuPercent() {
    return Probes.getLoadAndScaleToPercent(getSystemCpuLoad, osMxBean);
  }

  private static class OsProbeHolder {
    private static final OsProbe INSTANCE = new OsProbe();
  }

  public static OsProbe getInstance() {
    return OsProbeHolder.INSTANCE;
  }

  private OsProbe() {}

  public OsInfo osInfo() {
    OsInfo info = new OsInfo();
    info.availableProcessors = Runtime.getRuntime().availableProcessors();
    info.name = Constants.OS_NAME;
    info.arch = Constants.OS_ARCH;
    info.version = Constants.OS_VERSION;
    return info;
  }

  public OsStats osStats() {
    OsStats stats = new OsStats();
    stats.timestamp = System.currentTimeMillis();
    stats.cpu = new OsStats.Cpu();
    stats.cpu.percent = getSystemCpuPercent();
    stats.cpu.loadAverage = getSystemLoadAverage();

    OsStats.Mem mem = new OsStats.Mem();
    mem.total = getTotalPhysicalMemorySize();
    mem.free = getFreePhysicalMemorySize();
    stats.mem = mem;

    OsStats.Swap swap = new OsStats.Swap();
    swap.total = getTotalSwapSpaceSize();
    swap.free = getFreeSwapSpaceSize();
    stats.swap = swap;

    return stats;
  }

  /**
   * Returns a given method of the OperatingSystemMXBean, or null if the method is not found or
   * unavailable.
   */
  private static Method getMethod(String methodName) {
    try {
      return Class.forName("com.sun.management.OperatingSystemMXBean").getMethod(methodName);
    } catch (Throwable t) {
      // not available
      return null;
    }
  }
}
  static void doTserverList(
      HttpServletRequest req,
      StringBuilder sb,
      List<TabletServerStatus> tservers,
      String tableId,
      Table tServerList) {
    int guessHighLoad = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
    long now = System.currentTimeMillis();

    double avgLastContact = 0.;
    for (TabletServerStatus status : tservers) {
      avgLastContact += (now - status.lastContact);
    }
    final long MINUTES = 3 * 60 * 1000;
    tServerList.addSortableColumn("Server", new TServerLinkType(), null);
    tServerList.addSortableColumn(
        "Hosted&nbsp;Tablets", new NumberType<Integer>(0, Integer.MAX_VALUE), null);
    tServerList.addSortableColumn(
        "Last&nbsp;Contact",
        new DurationType(0l, (long) Math.min(avgLastContact * 4, MINUTES)),
        null);
    tServerList.addSortableColumn(
        "Entries", new NumberType<Long>(), "The number of key/value pairs.");
    tServerList.addSortableColumn(
        "Ingest",
        new NumberType<Long>(),
        "The number of key/value pairs inserted. (Note that deletes are also 'inserted')");
    tServerList.addSortableColumn(
        "Query",
        new NumberType<Long>(),
        "The number of key/value pairs returned to clients. (Not the number of scans)");
    tServerList.addSortableColumn(
        "Hold&nbsp;Time",
        new DurationType(),
        "The amount of time ingest is suspended waiting for data to be written to disk.");
    tServerList.addSortableColumn(
        "Running<br />Scans",
        new CompactionsType("scans"),
        "The number of scans running and queued on this tablet server.");
    tServerList.addSortableColumn(
        "Minor<br />Compactions",
        new CompactionsType("minor"),
        "The number of minor compactions running and (queued waiting for resources). Minor compactions are the operations where entries are flushed from memory to disk.");
    tServerList.addSortableColumn(
        "Major<br />Compactions",
        new CompactionsType("major"),
        "The number of major compactions running and (queued waiting for resources). "
            + "Major compactions are the operations where many smaller files are grouped into a larger file, eliminating duplicates and cleaning up deletes.");
    tServerList.addSortableColumn(
        "Index Cache<br />Hit Rate", new PercentageType(), "The recent index cache hit rate.");
    tServerList.addSortableColumn(
        "Data Cache<br />Hit Rate", new PercentageType(), "The recent data cache hit rate.");
    tServerList.addSortableColumn(
        "OS&nbsp;Load",
        new NumberType<Double>(0., guessHighLoad * 1., 0., guessHighLoad * 3.),
        "The Unix one minute load average. The average number of processes in the run queue over a one minute interval.");

    log.debug("tableId: " + tableId);
    for (TabletServerStatus status : tservers) {
      if (status == null) status = NO_STATUS;
      TableInfo summary = Monitor.summarizeTableStats(status);
      if (tableId != null) summary = status.tableMap.get(tableId);
      if (summary == null) continue;
      TableRow row = tServerList.prepareRow();
      row.add(status); // add for server name
      row.add(summary.tablets);
      row.add(now - status.lastContact);
      row.add(summary.recs);
      row.add(summary.ingestRate);
      row.add(summary.queryRate);
      row.add(status.holdTime);
      row.add(summary); // add for scans
      row.add(summary); // add for minor compactions
      row.add(summary); // add for major compactions
      double indexCacheHitRate =
          status.indexCacheHits / (double) Math.max(status.indexCacheRequest, 1);
      row.add(indexCacheHitRate);
      double dataCacheHitRate =
          status.dataCacheHits / (double) Math.max(status.dataCacheRequest, 1);
      row.add(dataCacheHitRate);
      row.add(status.osLoad);
      tServerList.addRow(row);
    }
    tServerList.generate(req, sb);
  }
 // Get the current load on this machine
 private double getLoad() {
   OperatingSystemMXBean mxBean = ManagementFactory.getOperatingSystemMXBean();
   return mxBean.getSystemLoadAverage();
 }
Beispiel #29
0
  protected void handleCommand(String command) {
    if (command.contains("__")) {
      namespace = command.split("__")[0];
      command = command.substring(command.indexOf("__") + 2);
    }

    if (echo) {
      if (Thread.currentThread().getName().toLowerCase().indexOf("main") < 0)
        println(" [" + Thread.currentThread().getName() + "] " + command);
      else println(command);
    }
    if (command == null || command.startsWith("//")) return;
    command = command.trim();
    if (command == null || command.length() == 0) {
      return;
    }
    String first = command;
    int spaceIndex = command.indexOf(' ');
    String[] argsSplit = command.split(" ");
    String[] args = new String[argsSplit.length];
    for (int i = 0; i < argsSplit.length; i++) {
      args[i] = argsSplit[i].trim();
    }
    if (spaceIndex != -1) {
      first = args[0];
    }
    if (command.startsWith("help")) {
      handleHelp(command);
    } else if (first.startsWith("#") && first.length() > 1) {
      int repeat = Integer.parseInt(first.substring(1));
      long t0 = Clock.currentTimeMillis();
      for (int i = 0; i < repeat; i++) {
        handleCommand(command.substring(first.length()).replaceAll("\\$i", "" + i));
      }
      println("ops/s = " + repeat * 1000 / (Clock.currentTimeMillis() - t0));
      return;
    } else if (first.startsWith("&") && first.length() > 1) {
      final int fork = Integer.parseInt(first.substring(1));
      ExecutorService pool = Executors.newFixedThreadPool(fork);
      final String threadCommand = command.substring(first.length());
      for (int i = 0; i < fork; i++) {
        final int threadID = i;
        pool.submit(
            new Runnable() {
              public void run() {
                String command = threadCommand;
                String[] threadArgs = command.replaceAll("\\$t", "" + threadID).trim().split(" ");
                // TODO &t #4 m.putmany x k
                if ("m.putmany".equals(threadArgs[0]) || "m.removemany".equals(threadArgs[0])) {
                  if (threadArgs.length < 4) {
                    command += " " + Integer.parseInt(threadArgs[1]) * threadID;
                  }
                }
                handleCommand(command);
              }
            });
      }
      pool.shutdown();
      try {
        pool.awaitTermination(60 * 60, TimeUnit.SECONDS); // wait 1h
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else if (first.startsWith("@")) {
      if (first.length() == 1) {
        println("usage: @<file-name>");
        return;
      }
      File f = new File(first.substring(1));
      println("Executing script file " + f.getAbsolutePath());
      if (f.exists()) {
        try {
          BufferedReader br = new BufferedReader(new FileReader(f));
          String l = br.readLine();
          while (l != null) {
            handleCommand(l);
            l = br.readLine();
          }
          br.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      } else {
        println("File not found! " + f.getAbsolutePath());
      }
    } else if (command.indexOf(';') != -1) {
      StringTokenizer st = new StringTokenizer(command, ";");
      while (st.hasMoreTokens()) {
        handleCommand(st.nextToken());
      }
      return;
    } else if ("silent".equals(first)) {
      silent = Boolean.parseBoolean(args[1]);
    } else if ("shutdown".equals(first)) {
      hazelcast.getLifecycleService().shutdown();
    } else if ("echo".equals(first)) {
      echo = Boolean.parseBoolean(args[1]);
      println("echo: " + echo);
    } else if ("ns".equals(first)) {
      if (args.length > 1) {
        namespace = args[1];
        println("namespace: " + namespace);
        //                init();
      }
    } else if ("whoami".equals(first)) {
      println(hazelcast.getCluster().getLocalMember());
    } else if ("who".equals(first)) {
      println(hazelcast.getCluster());
    } else if ("jvm".equals(first)) {
      System.gc();
      println("Memory max: " + Runtime.getRuntime().maxMemory() / 1024 / 1024 + "M");
      println(
          "Memory free: "
              + Runtime.getRuntime().freeMemory() / 1024 / 1024
              + "M "
              + (int) (Runtime.getRuntime().freeMemory() * 100 / Runtime.getRuntime().maxMemory())
              + "%");
      long total = Runtime.getRuntime().totalMemory();
      long free = Runtime.getRuntime().freeMemory();
      println("Used Memory:" + ((total - free) / 1024 / 1024) + "MB");
      println("# procs: " + Runtime.getRuntime().availableProcessors());
      println(
          "OS info: "
              + ManagementFactory.getOperatingSystemMXBean().getArch()
              + " "
              + ManagementFactory.getOperatingSystemMXBean().getName()
              + " "
              + ManagementFactory.getOperatingSystemMXBean().getVersion());
      println(
          "JVM: "
              + ManagementFactory.getRuntimeMXBean().getVmVendor()
              + " "
              + ManagementFactory.getRuntimeMXBean().getVmName()
              + " "
              + ManagementFactory.getRuntimeMXBean().getVmVersion());
    } else if (first.indexOf("ock") != -1 && first.indexOf(".") == -1) {
      handleLock(args);
    } else if (first.indexOf(".size") != -1) {
      handleSize(args);
    } else if (first.indexOf(".clear") != -1) {
      handleClear(args);
    } else if (first.indexOf(".destroy") != -1) {
      handleDestroy(args);
    } else if (first.indexOf(".iterator") != -1) {
      handleIterator(args);
    } else if (first.indexOf(".contains") != -1) {
      handleContains(args);
    } else if (first.indexOf(".stats") != -1) {
      handStats(args);
    } else if ("t.publish".equals(first)) {
      handleTopicPublish(args);
    } else if ("q.offer".equals(first)) {
      handleQOffer(args);
    } else if ("q.take".equals(first)) {
      handleQTake(args);
    } else if ("q.poll".equals(first)) {
      handleQPoll(args);
    } else if ("q.peek".equals(first)) {
      handleQPeek(args);
    } else if ("q.capacity".equals(first)) {
      handleQCapacity(args);
    } else if ("q.offermany".equals(first)) {
      handleQOfferMany(args);
    } else if ("q.pollmany".equals(first)) {
      handleQPollMany(args);
    } else if ("s.add".equals(first)) {
      handleSetAdd(args);
    } else if ("s.remove".equals(first)) {
      handleSetRemove(args);
    } else if ("s.addmany".equals(first)) {
      handleSetAddMany(args);
    } else if ("s.removemany".equals(first)) {
      handleSetRemoveMany(args);
    } else if (first.equals("m.replace")) {
      handleMapReplace(args);
    } else if (first.equalsIgnoreCase("m.putIfAbsent")) {
      handleMapPutIfAbsent(args);
    } else if (first.equals("m.putAsync")) {
      handleMapPutAsync(args);
    } else if (first.equals("m.getAsync")) {
      handleMapGetAsync(args);
    } else if (first.equals("m.put")) {
      handleMapPut(args);
    } else if (first.equals("m.get")) {
      handleMapGet(args);
    } else if (first.equalsIgnoreCase("m.getMapEntry")) {
      handleMapGetMapEntry(args);
    } else if (first.equals("m.remove")) {
      handleMapRemove(args);
    } else if (first.equals("m.evict")) {
      handleMapEvict(args);
    } else if (first.equals("m.putmany") || first.equalsIgnoreCase("m.putAll")) {
      handleMapPutMany(args);
    } else if (first.equals("m.getmany")) {
      handleMapGetMany(args);
    } else if (first.equals("m.removemany")) {
      handleMapRemoveMany(args);
    } else if (command.equalsIgnoreCase("m.localKeys")) {
      handleMapLocalKeys();
    } else if (command.equals("m.keys")) {
      handleMapKeys();
    } else if (command.equals("m.values")) {
      handleMapValues();
    } else if (command.equals("m.entries")) {
      handleMapEntries();
    } else if (first.equals("m.lock")) {
      handleMapLock(args);
    } else if (first.equalsIgnoreCase("m.tryLock")) {
      handleMapTryLock(args);
    } else if (first.equals("m.unlock")) {
      handleMapUnlock(args);
    } else if (first.indexOf(".addListener") != -1) {
      handleAddListener(args);
    } else if (first.equals("m.removeMapListener")) {
      handleRemoveListener(args);
    } else if (first.equals("m.unlock")) {
      handleMapUnlock(args);
    } else if (first.equals("l.add")) {
      handleListAdd(args);
    } else if (first.equals("l.set")) {
      handleListSet(args);
    } else if ("l.addmany".equals(first)) {
      handleListAddMany(args);
    } else if (first.equals("l.remove")) {
      handleListRemove(args);
    } else if (first.equals("l.contains")) {
      handleListContains(args);
    } else if ("a.get".equals(first)) {
      handleAtomicNumberGet(args);
    } else if ("a.set".equals(first)) {
      handleAtomicNumberSet(args);
    } else if ("a.inc".equals(first)) {
      handleAtomicNumberInc(args);
    } else if ("a.dec".equals(first)) {
      handleAtomicNumberDec(args);
      //        } else if (first.equals("execute")) {
      //            execute(args);
    } else if (first.equals("partitions")) {
      handlePartitions(args);
      //        } else if (first.equals("txn")) {
      //            hazelcast.getTransaction().begin();
      //        } else if (first.equals("commit")) {
      //            hazelcast.getTransaction().commit();
      //        } else if (first.equals("rollback")) {
      //            hazelcast.getTransaction().rollback();
      //        } else if (first.equalsIgnoreCase("executeOnKey")) {
      //            executeOnKey(args);
      //        } else if (first.equalsIgnoreCase("executeOnMember")) {
      //            executeOnMember(args);
      //        } else if (first.equalsIgnoreCase("executeOnMembers")) {
      //            executeOnMembers(args);
      //        } else if (first.equalsIgnoreCase("longOther") ||
      // first.equalsIgnoreCase("executeLongOther")) {
      //            executeLongTaskOnOtherMember(args);
      //        } else if (first.equalsIgnoreCase("long") || first.equalsIgnoreCase("executeLong"))
      // {
      //            executeLong(args);
    } else if (first.equalsIgnoreCase("instances")) {
      handleInstances(args);
    } else if (first.equalsIgnoreCase("quit") || first.equalsIgnoreCase("exit")) {
      System.exit(0);
    } else {
      println("type 'help' for help");
    }
  }
Beispiel #30
0
/**
 * A CPU.
 *
 * @author alessandro[at]perucchi[dot]org
 * @author alessio.fachechi[at]gmail[dot]com
 * @author widdis[at]gmail[dot]com
 */
@SuppressWarnings("restriction")
public class MacCentralProcessor implements CentralProcessor {
  private static final Logger LOG = LoggerFactory.getLogger(MacCentralProcessor.class);

  private static final java.lang.management.OperatingSystemMXBean OS_MXBEAN =
      ManagementFactory.getOperatingSystemMXBean();
  private static boolean sunMXBean;

  static {
    try {
      Class.forName("com.sun.management.OperatingSystemMXBean");
      // Initialize CPU usage
      ((com.sun.management.OperatingSystemMXBean) OS_MXBEAN).getSystemCpuLoad();
      sunMXBean = true;
      LOG.debug("Oracle MXBean detected.");
    } catch (ClassNotFoundException e) {
      sunMXBean = false;
      LOG.debug("Oracle MXBean not detected.");
      LOG.trace("", e);
    }
  }

  // Logical and Physical Processor Counts
  private int logicalProcessorCount = 0;
  private int physicalProcessorCount = 0;

  // Maintain previous ticks to be used for calculating usage between them.
  // System ticks
  private long tickTime;
  private long[] prevTicks;
  private long[] curTicks;

  // Per-processor ticks [cpu][type]
  private long procTickTime;
  private long[][] prevProcTicks;
  private long[][] curProcTicks;

  // Processor info
  private String cpuVendor;
  private String cpuName;
  private String cpuIdentifier = null;
  private String cpuStepping;
  private String cpuModel;
  private String cpuFamily;
  private Long cpuVendorFreq = null;
  private Boolean cpu64;

  /** Create a Processor */
  public MacCentralProcessor() {
    // Processor counts
    calculateProcessorCounts();

    // System ticks
    this.prevTicks = new long[4];
    this.curTicks = new long[4];
    updateSystemTicks();

    // Per-processor ticks
    this.prevProcTicks = new long[logicalProcessorCount][4];
    this.curProcTicks = new long[logicalProcessorCount][4];
    updateProcessorTicks();

    LOG.debug("Initialized Processor");
  }

  /** Updates logical and physical processor counts from sysctl calls */
  private void calculateProcessorCounts() {
    IntByReference size = new IntByReference(SystemB.INT_SIZE);
    Pointer p = new Memory(size.getValue());

    // Get number of logical processors
    if (0 != SystemB.INSTANCE.sysctlbyname("hw.logicalcpu", p, size, null, 0)) {
      LOG.error("Failed to get number of logical CPUs. Error code: " + Native.getLastError());
      this.logicalProcessorCount = 1;
    } else this.logicalProcessorCount = p.getInt(0);

    // Get number of physical processors
    if (0 != SystemB.INSTANCE.sysctlbyname("hw.physicalcpu", p, size, null, 0)) {
      LOG.error("Failed to get number of physical CPUs. Error code: " + Native.getLastError());
      this.physicalProcessorCount = 1;
    } else this.physicalProcessorCount = p.getInt(0);
  }

  /** {@inheritDoc} */
  @Override
  public String getVendor() {
    if (this.cpuVendor == null) {
      IntByReference size = new IntByReference();
      if (0 != SystemB.INSTANCE.sysctlbyname("machdep.cpu.vendor", null, size, null, 0)) {
        LOG.error("Failed to get Vendor. Error code: " + Native.getLastError());
        return "";
      }
      Pointer p = new Memory(size.getValue() + 1);
      if (0 != SystemB.INSTANCE.sysctlbyname("machdep.cpu.vendor", p, size, null, 0)) {
        LOG.error("Failed to get Vendor. Error code: " + Native.getLastError());
        return "";
      }
      this.cpuVendor = p.getString(0);
    }
    return this.cpuVendor;
  }

  /** {@inheritDoc} */
  @Override
  public void setVendor(String vendor) {
    this.cpuVendor = vendor;
  }

  /** {@inheritDoc} */
  @Override
  public String getName() {
    if (this.cpuName == null) {
      IntByReference size = new IntByReference();
      if (0 != SystemB.INSTANCE.sysctlbyname("machdep.cpu.brand_string", null, size, null, 0)) {
        LOG.error("Failed to get Name. Error code: " + Native.getLastError());
        return "";
      }
      Pointer p = new Memory(size.getValue() + 1);
      if (0 != SystemB.INSTANCE.sysctlbyname("machdep.cpu.brand_string", p, size, null, 0)) {
        LOG.error("Failed to get Name. Error code: " + Native.getLastError());
        return "";
      }
      this.cpuName = p.getString(0);
    }
    return this.cpuName;
  }

  /** {@inheritDoc} */
  @Override
  public void setName(String name) {
    this.cpuName = name;
  }

  /** {@inheritDoc} */
  @Override
  public long getVendorFreq() {
    if (this.cpuVendorFreq == null) {
      Pattern pattern = Pattern.compile("@ (.*)$");
      Matcher matcher = pattern.matcher(getName());

      if (matcher.find()) {
        String unit = matcher.group(1);
        this.cpuVendorFreq = Long.valueOf(ParseUtil.parseHertz(unit));
      } else {
        this.cpuVendorFreq = Long.valueOf(-1L);
      }
    }

    return this.cpuVendorFreq.longValue();
  }

  /** {@inheritDoc} */
  @Override
  public void setVendorFreq(long freq) {
    this.cpuVendorFreq = Long.valueOf(freq);
  }

  /** {@inheritDoc} */
  @Override
  public String getIdentifier() {
    if (this.cpuIdentifier == null) {
      StringBuilder sb = new StringBuilder();
      if (getVendor().contentEquals("GenuineIntel")) {
        sb.append(isCpu64bit() ? "Intel64" : "x86");
      } else {
        sb.append(getVendor());
      }
      sb.append(" Family ").append(getFamily());
      sb.append(" Model ").append(getModel());
      sb.append(" Stepping ").append(getStepping());
      this.cpuIdentifier = sb.toString();
    }
    return this.cpuIdentifier;
  }

  /** {@inheritDoc} */
  @Override
  public void setIdentifier(String identifier) {
    this.cpuIdentifier = identifier;
  }

  /** {@inheritDoc} */
  @Override
  public boolean isCpu64bit() {
    if (this.cpu64 == null) {
      IntByReference size = new IntByReference(SystemB.INT_SIZE);
      Pointer p = new Memory(size.getValue());
      if (0 != SystemB.INSTANCE.sysctlbyname("hw.cpu64bit_capable", p, size, null, 0)) {
        LOG.error("Failed to get 64Bit_capable. Error code: " + Native.getLastError());
        return false;
      }
      this.cpu64 = p.getInt(0) != 0;
    }
    return this.cpu64.booleanValue();
  }

  /** {@inheritDoc} */
  @Override
  public void setCpu64(boolean value) {
    this.cpu64 = Boolean.valueOf(value);
  }

  /** {@inheritDoc} */
  @Override
  public String getStepping() {
    if (this.cpuStepping == null) {
      IntByReference size = new IntByReference(SystemB.INT_SIZE);
      Pointer p = new Memory(size.getValue());
      if (0 != SystemB.INSTANCE.sysctlbyname("machdep.cpu.stepping", p, size, null, 0)) {
        LOG.error("Failed to get Stepping. Error code: " + Native.getLastError());
        return "";
      }
      this.cpuStepping = Integer.toString(p.getInt(0));
    }
    return this.cpuStepping;
  }

  /** {@inheritDoc} */
  @Override
  public void setStepping(String stepping) {
    this.cpuStepping = stepping;
  }

  /** {@inheritDoc} */
  @Override
  public String getModel() {
    if (this.cpuModel == null) {
      IntByReference size = new IntByReference(SystemB.INT_SIZE);
      Pointer p = new Memory(size.getValue());
      if (0 != SystemB.INSTANCE.sysctlbyname("machdep.cpu.model", p, size, null, 0)) {
        LOG.error("Failed to get Model. Error code: " + Native.getLastError());
        return "";
      }
      this.cpuModel = Integer.toString(p.getInt(0));
    }
    return this.cpuModel;
  }

  /** {@inheritDoc} */
  @Override
  public void setModel(String model) {
    this.cpuModel = model;
  }

  /** {@inheritDoc} */
  @Override
  public String getFamily() {
    if (this.cpuFamily == null) {
      IntByReference size = new IntByReference(SystemB.INT_SIZE);
      Pointer p = new Memory(size.getValue());
      if (0 != SystemB.INSTANCE.sysctlbyname("machdep.cpu.family", p, size, null, 0)) {
        LOG.error("Failed to get Family. Error code: " + Native.getLastError());
        return "";
      }
      this.cpuFamily = Integer.toString(p.getInt(0));
    }
    return this.cpuFamily;
  }

  /** {@inheritDoc} */
  @Override
  public void setFamily(String family) {
    this.cpuFamily = family;
  }

  /** {@inheritDoc} */
  @Override
  public synchronized double getSystemCpuLoadBetweenTicks() {
    // Check if > ~ 0.95 seconds since last tick count.
    long now = System.currentTimeMillis();
    LOG.trace("Current time: {}  Last tick time: {}", now, tickTime);
    if (now - tickTime > 950) {
      // Enough time has elapsed.
      updateSystemTicks();
    }
    // Calculate total
    long total = 0;
    for (int i = 0; i < curTicks.length; i++) {
      total += (curTicks[i] - prevTicks[i]);
    }
    // Calculate idle from last field [3]
    long idle = curTicks[3] - prevTicks[3];
    LOG.trace("Total ticks: {}  Idle ticks: {}", total, idle);

    return (total > 0 && idle >= 0) ? (double) (total - idle) / total : 0d;
  }

  /** {@inheritDoc} */
  @Override
  public long[] getSystemCpuLoadTicks() {
    long[] ticks = new long[curTicks.length];
    int machPort = SystemB.INSTANCE.mach_host_self();
    HostCpuLoadInfo cpuLoadInfo = new HostCpuLoadInfo();
    if (0
        != SystemB.INSTANCE.host_statistics(
            machPort,
            SystemB.HOST_CPU_LOAD_INFO,
            cpuLoadInfo,
            new IntByReference(cpuLoadInfo.size()))) {
      LOG.error("Failed to get System CPU ticks. Error code: " + Native.getLastError());
      return ticks;
    }
    // Switch order to match linux
    ticks[0] = cpuLoadInfo.cpu_ticks[SystemB.CPU_STATE_USER];
    ticks[1] = cpuLoadInfo.cpu_ticks[SystemB.CPU_STATE_NICE];
    ticks[2] = cpuLoadInfo.cpu_ticks[SystemB.CPU_STATE_SYSTEM];
    ticks[3] = cpuLoadInfo.cpu_ticks[SystemB.CPU_STATE_IDLE];
    return ticks;
  }

  /**
   * Updates system tick information from native host_statistics query. Stores in array with four
   * elements representing clock ticks or milliseconds (platform dependent) spent in User (0), Nice
   * (1), System (2), and Idle (3) states. By measuring the difference between ticks across a time
   * interval, CPU load over that interval may be calculated.
   */
  private void updateSystemTicks() {
    LOG.trace("Updating System Ticks");
    // Copy to previous
    System.arraycopy(curTicks, 0, prevTicks, 0, curTicks.length);
    this.tickTime = System.currentTimeMillis();
    long[] ticks = getSystemCpuLoadTicks();
    System.arraycopy(ticks, 0, curTicks, 0, ticks.length);
  }

  /** {@inheritDoc} */
  @Override
  public double getSystemCpuLoad() {
    if (sunMXBean) {
      return ((com.sun.management.OperatingSystemMXBean) OS_MXBEAN).getSystemCpuLoad();
    }
    return getSystemCpuLoadBetweenTicks();
  }

  /** {@inheritDoc} */
  @Override
  public double getSystemLoadAverage() {
    return OS_MXBEAN.getSystemLoadAverage();
  }

  /** {@inheritDoc} */
  @Override
  public double[] getProcessorCpuLoadBetweenTicks() {
    // Check if > ~ 0.95 seconds since last tick count.
    long now = System.currentTimeMillis();
    LOG.trace("Current time: {}  Last tick time: {}", now, procTickTime);
    if (now - procTickTime > 950) {
      // Enough time has elapsed.
      // Update latest
      updateProcessorTicks();
    }
    double[] load = new double[logicalProcessorCount];
    for (int cpu = 0; cpu < logicalProcessorCount; cpu++) {
      long total = 0;
      for (int i = 0; i < this.curProcTicks[cpu].length; i++) {
        total += (this.curProcTicks[cpu][i] - this.prevProcTicks[cpu][i]);
      }
      // Calculate idle from last field [3]
      long idle = this.curProcTicks[cpu][3] - this.prevProcTicks[cpu][3];
      LOG.trace("CPU: {}  Total ticks: {}  Idle ticks: {}", cpu, total, idle);
      // update
      load[cpu] = (total > 0 && idle >= 0) ? (double) (total - idle) / total : 0d;
    }
    return load;
  }

  /** {@inheritDoc} */
  @Override
  public long[][] getProcessorCpuLoadTicks() {
    long[][] ticks = new long[logicalProcessorCount][4];

    int machPort = SystemB.INSTANCE.mach_host_self();

    IntByReference procCount = new IntByReference();
    PointerByReference procCpuLoadInfo = new PointerByReference();
    IntByReference procInfoCount = new IntByReference();
    if (0
        != SystemB.INSTANCE.host_processor_info(
            machPort, SystemB.PROCESSOR_CPU_LOAD_INFO, procCount, procCpuLoadInfo, procInfoCount)) {
      LOG.error("Failed to update CPU Load. Error code: " + Native.getLastError());
      return ticks;
    }

    int[] cpuTicks = procCpuLoadInfo.getValue().getIntArray(0, procInfoCount.getValue());
    for (int cpu = 0; cpu < procCount.getValue(); cpu++) {
      for (int j = 0; j < 4; j++) {
        int offset = cpu * SystemB.CPU_STATE_MAX;
        ticks[cpu][0] = FormatUtil.getUnsignedInt(cpuTicks[offset + SystemB.CPU_STATE_USER]);
        ticks[cpu][1] = FormatUtil.getUnsignedInt(cpuTicks[offset + SystemB.CPU_STATE_NICE]);
        ticks[cpu][2] = FormatUtil.getUnsignedInt(cpuTicks[offset + SystemB.CPU_STATE_SYSTEM]);
        ticks[cpu][3] = FormatUtil.getUnsignedInt(cpuTicks[offset + SystemB.CPU_STATE_IDLE]);
      }
    }
    return ticks;
  }

  /**
   * Updates the tick array for all processors by calling host_processor_info(). Stores in 2D array;
   * an array for each logical processor with four elements representing clock ticks or milliseconds
   * (platform dependent) spent in User (0), Nice (1), System (2), and Idle (3) states. By measuring
   * the difference between ticks across a time interval, CPU load over that interval may be
   * calculated.
   */
  private void updateProcessorTicks() {
    LOG.trace("Updating Processor Ticks");
    // Copy to previous
    for (int cpu = 0; cpu < logicalProcessorCount; cpu++) {
      System.arraycopy(curProcTicks[cpu], 0, prevProcTicks[cpu], 0, curProcTicks[cpu].length);
    }
    this.procTickTime = System.currentTimeMillis();
    long[][] ticks = getProcessorCpuLoadTicks();
    for (int cpu = 0; cpu < logicalProcessorCount; cpu++) {
      System.arraycopy(ticks[cpu], 0, curProcTicks[cpu], 0, ticks[cpu].length);
    }
  }

  /** {@inheritDoc} */
  @Override
  public long getSystemUptime() {
    IntByReference size = new IntByReference();
    if (0 != SystemB.INSTANCE.sysctlbyname("kern.boottime", null, size, null, 0)) {
      LOG.error("Failed to get Boot Time. Error code: " + Native.getLastError());
      return 0L;
    }
    // This should point to a 16-byte structure. If not, this code is valid
    if (size.getValue() != 16)
      throw new UnsupportedOperationException("sysctl kern.boottime should be 16 bytes but isn't.");
    Pointer p = new Memory(size.getValue() + 1);
    if (0 != SystemB.INSTANCE.sysctlbyname("kern.boottime", p, size, null, 0)) {
      LOG.error("Failed to get Boot Time. Error code: " + Native.getLastError());
      return 0L;
    }
    // p now points to a 16-bit timeval structure for boot time.
    // First 8 bytes are seconds, second 8 bytes are microseconds (ignore)
    return System.currentTimeMillis() / 1000 - p.getLong(0);
  }

  /** {@inheritDoc} */
  @Override
  public String getSystemSerialNumber() {
    String sn = null;
    ArrayList<String> hwInfo = ExecutingCommand.runNative("system_profiler SPHardwareDataType");
    // Mavericks and later
    for (String checkLine : hwInfo) {
      if (checkLine.contains("Serial Number (system)")) {
        String[] snSplit = checkLine.split("\\s+");
        sn = snSplit[snSplit.length - 1];
        break;
      }
    }
    // Panther and later
    if (sn == null) {
      for (String checkLine : hwInfo) {
        if (checkLine.contains("r (system)")) {
          String[] snSplit = checkLine.split("\\s+");
          sn = snSplit[snSplit.length - 1];
          break;
        }
      }
    }
    return (sn == null) ? "unknown" : sn;
  }

  @Override
  public int getLogicalProcessorCount() {
    return logicalProcessorCount;
  }

  @Override
  public int getPhysicalProcessorCount() {
    return physicalProcessorCount;
  }

  @Override
  public String toString() {
    return getName();
  }
}