wtorek, czerwca 17, 2014

JMX query for Tibco BW

public static class VMStats {
 String nameOrDesc = "UNKNOWN";
 int memUsage = 0;
 int memMax = 0;
 int cpuUsage = 0;
 int gcUsage = 0;
 int cores = 0;
 int overloaded = 0;
  
 public void toStdout() {
  System.out.println(String.format("%s|%d|%d|%d|%d|%d|%d", nameOrDesc, memUsage, memMax, cpuUsage, gcUsage, cores, overloaded));   
 }
}

public final static VMStats query(VirtualMachineDescriptor vmd, CyclicBarrier sync) throws Exception {
 VirtualMachine vm = VirtualMachine.attach(vmd);
 long timeStart = System.currentTimeMillis();
 try {
  String address = vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress");
  MBeanServerConnection conn = null;
  for (int i=0; i < 2; i++) {
   try {
    if (address == null) {
     String javaHome = vm.getSystemProperties().getProperty("java.home");
     File managementAgentJarFile = new File(javaHome + File.separator + "lib" + File.separator + "management-agent.jar");
     vm.loadAgent(managementAgentJarFile.getAbsolutePath());
     address = vm.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress");
    }
    JMXServiceURL jmxUrl = new JMXServiceURL(address);
           conn = JMXConnectorFactory.connect(jmxUrl).getMBeanServerConnection();
   }
   catch (Exception e) {
    if (i==0) {
     address = null; /* try to reload agent */
    }
    else
     throw e;
   }
  }
  String file = vm.getSystemProperties().getProperty("wrapper.tra.file");
         MemoryMXBean memBean = ManagementFactory.newPlatformMXBeanProxy(conn, ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class);
         RuntimeMXBean rtBean = ManagementFactory.newPlatformMXBeanProxy(conn, ManagementFactory.RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
         OperatingSystemMXBean osBean = ManagementFactory.newPlatformMXBeanProxy(conn, ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);
         
         long memMax = (memBean.getHeapMemoryUsage().getMax() + memBean.getNonHeapMemoryUsage().getMax());
  int memUsage = (int)(100.0 * (memBean.getHeapMemoryUsage().getUsed() + memBean.getNonHeapMemoryUsage().getUsed()) / memMax);
         int memMB = (int) (memMax / 1024 / 1024);
         long time0 = osBean.getProcessCpuTime();
         long refTime0 = System.currentTimeMillis();
         Thread.sleep(1000);
         double load = (osBean.getProcessCpuTime() - time0) / (System.currentTimeMillis() - refTime0) / 10000.0;
         if (Double.isInfinite(load) || Double.isNaN(load) || load < 0)
          load = 0;
  load = Math.round(load);
         String appId = "PID|"+vm.id() + "|"+rtBean.getSystemProperties().get("user.dir");
   if (file!=null) {
          appId = file.endsWith(".tra") ? "TRA|"+file.substring(file.lastIndexOf(File.separator+"")+1) : appId;
  }
         long gcDiff = 0;
  List gcmbList = ManagementFactory.getGarbageCollectorMXBeans();
  long[] gcTime = new long[gcmbList.size()];
         for (int i=0; i < 5; i++) {
          for (int j=0; j < gcmbList.size(); j++) {
           GarbageCollectorMXBean gcBean = ManagementFactory.newPlatformMXBeanProxy(conn, gcmbList.get(j).getObjectName().toString(), GarbageCollectorMXBean.class);
           if (i > 0)
     gcDiff += (gcBean.getCollectionTime() - gcTime[j]);
           gcTime[j] = gcBean.getCollectionTime();
          }
          if (i!=4)
           Thread.sleep(1000);
         }
         VMStats stats = new VMStats();
         stats.nameOrDesc = appId;
         stats.memUsage = memUsage;
         stats.memMax = memMB;
         stats.cpuUsage = (int) load;
         stats.gcUsage = (int) gcDiff;
         stats.cores = osBean.getAvailableProcessors();
         stats.overloaded = System.currentTimeMillis() - timeStart >= 60000 ? 1 : 0;
         if (vm.getSystemProperties().getProperty("VMSTAT_TOKEN", "").equals(System.getProperty("VMSTAT_TOKEN")))
          stats.nameOrDesc = ""; /* this is me */
         return stats;
 }
 finally {
  vm.detach();
 }
}

public void invoke() { 
 List list = VirtualMachine.list();
 ExecutorService es = Executors.newFixedThreadPool(list.size()+1);
 final CyclicBarrier sync = new CyclicBarrier(list.size()+1);
 final ConcurrentLinkedQueue result = new ConcurrentLinkedQueue();  
 System.setProperty("VMSTAT_TOKEN", System.currentTimeMillis()+"X"+Thread.currentThread().getId());
  
 for (final VirtualMachineDescriptor vmd : list) {
  Runnable r = new Runnable() {
   public void run() {
    try {
     VMStats stats = query(vmd, sync);
     if (!("".equals(stats.nameOrDesc)))
      result.add(stats);
    }
    catch (Exception e) {
     new RuntimeException("Error while querying JMX for "+vmd.id(), e).printStackTrace();
     VMStats vms = new VMStats();
     vms.nameOrDesc = "PID|"+vmd.id()+"|"+vmd.id();
     vms.overloaded = 1;
     result.add(vms);
    }
    finally {
     try {
      sync.await(180, TimeUnit.SECONDS);
     }
     catch (Exception e) {}
    }
   }
  };
                es.execute(r);  
 }
 try {
  sync.await(180, TimeUnit.SECONDS);
 }
 catch (Exception te) {}
 es.shutdownNow();
 try {
  Thread.sleep(1000);
 }
 catch (InterruptedException e) {}
 
 while (result.size() > 0) {
         result.remove().toStdout();
 }
}
 
public final static void main(String[] args) {
 new VMStat().invoke();
 try {
  Thread.sleep(1000);
 }
 catch (InterruptedException e) {}
 System.exit(0);  
}

0 komentarze: