Java tutorial
/* * Copyright (c) Koala 2012-2014 All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.openkoala.koala.monitor.support; import java.io.File; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.apache.commons.lang.time.DateFormatUtils; import org.hyperic.sigar.CpuInfo; import org.hyperic.sigar.CpuPerc; import org.hyperic.sigar.FileSystem; import org.hyperic.sigar.FileSystemUsage; import org.hyperic.sigar.Mem; import org.hyperic.sigar.NetInterfaceConfig; import org.hyperic.sigar.NetInterfaceStat; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.Swap; import org.openkoala.koala.monitor.model.ServerStatusVo; import org.openkoala.koala.monitor.model.ServerStatusVo.CpuInfoVo; import org.openkoala.koala.monitor.model.ServerStatusVo.DiskInfoVo; /** * * ????<br /> * * 2013-6-19 ?9:17:40 <br /> * * ??Copyright (c) 2013 Koala All Rights Reserved<br /> * * <a href="mailto:vakinge@gmail.com">vakin jiang</a><br /> * * <br /> * */ public class ServerStatusCollector { //??? private static Map<String, String> diskWritesAndReadsOnInit = new HashMap<String, String>(); private static long initTime; static { initTime = System.currentTimeMillis(); resetClasspath(); Sigar sigar = null; try { sigar = new Sigar(); FileSystem fslist[] = sigar.getFileSystemList(); FileSystemUsage usage = null; for (int i = 0; i < fslist.length; i++) { FileSystem fs = fslist[i]; if (fs.getType() != 2) continue; usage = sigar.getFileSystemUsage(fs.getDirName()); diskWritesAndReadsOnInit.put(fs.getDevName(), usage.getDiskReadBytes() + "|" + usage.getDiskWriteBytes()); } } catch (Exception e) { } finally { if (sigar != null) sigar.close(); } } /** * ?CLASSPATH,sigar?dll,so? */ private static void resetClasspath() { String libPath = System.getProperty("java.library.path"); String classpath = ServerStatusCollector.class.getResource("/").getPath(); System.setProperty("java.library.path", classpath + File.separator + "sigar" + File.pathSeparator + libPath); } /** * ???? * @return */ public static ServerStatusVo getServerAllStatus() { ServerStatusVo status = new ServerStatusVo(); Sigar sigar = null; try { getServerBaseInfo(status); sigar = new Sigar(); getServerCpuInfo(sigar, status); getServerDiskInfo(sigar, status); getServerMemoryInfo(sigar, status); } catch (Exception e) { return null; } finally { if (sigar != null) sigar.close(); } return status; } /** * ??? * @return */ public static void getServerBaseInfo(ServerStatusVo status) { status.setServerTime(DateFormatUtils.format(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss")); status.setServerName(System.getenv().get("COMPUTERNAME")); // status.setJavaServer(RuntimeContext.getContext().getServerName()); // status.setDeployPath(RuntimeContext.getContext().getDeployPath()); Runtime rt = Runtime.getRuntime(); status.setJvmTotalMem(rt.totalMemory() / (1024 * 1024)); status.setJvmFreeMem(rt.freeMemory() / (1024 * 1024)); Properties props = System.getProperties(); status.setServerOs(props.getProperty("os.name") + " " + props.getProperty("os.arch") + " " + props.getProperty("os.version")); status.setJavaHome(props.getProperty("java.home")); status.setJavaVersion(props.getProperty("java.version")); status.setJavaTmpPath(props.getProperty("java.io.tmpdir")); } public static void getServerCpuInfo(Sigar sigar, ServerStatusVo status) { try { CpuInfo infos[] = sigar.getCpuInfoList(); CpuPerc cpuList[] = sigar.getCpuPercList(); //??CPU Map<String, CpuInfoVo> cpuTypeByModel = new HashMap<String, ServerStatusVo.CpuInfoVo>(); CpuInfoVo cpuInfo; for (int i = 0; i < infos.length; i++) { CpuPerc perc = cpuList[i]; if (!cpuTypeByModel.containsKey(infos[i].getModel())) { cpuInfo = new CpuInfoVo(); cpuInfo.setCacheSize(infos[i].getCacheSize()); cpuInfo.setModel(infos[i].getModel()); cpuInfo.setTotalMHz(infos[i].getMhz()); cpuInfo.setVendor(infos[i].getVendor()); cpuTypeByModel.put(infos[i].getModel(), cpuInfo); } else { cpuInfo = cpuTypeByModel.get(infos[i].getModel()); } cpuInfo.setUsed(cpuInfo.getUsed() + perc.getCombined()); cpuInfo.setIdle(cpuInfo.getIdle() + perc.getIdle()); cpuInfo.setCoreCount(cpuInfo.getCoreCount() + 1); } // status.getCpuInfos().addAll(cpuTypeByModel.values()); } catch (Exception e) { // TODO: handle exception } } public static void getServerMemoryInfo(Sigar sigar, ServerStatusVo status) { try { Mem mem = sigar.getMem(); status.setTotalMem(mem.getTotal() / (1024 * 1024)); status.setUsedMem(mem.getUsed() / (1024 * 1024)); status.setFreeMem(mem.getFree() / (1024 * 1024)); //? Swap swap = sigar.getSwap(); status.setTotalSwap(swap.getTotal() / (1024 * 1024)); status.setUsedSwap(swap.getUsed() / (1024 * 1024)); status.setFreeSwap(swap.getFree() / (1024 * 1024)); } catch (Exception e) { } } public static void getServerDiskInfo(Sigar sigar, ServerStatusVo status) { try { FileSystem fslist[] = sigar.getFileSystemList(); FileSystemUsage usage = null; for (int i = 0; i < fslist.length; i++) { FileSystem fs = fslist[i]; switch (fs.getType()) { case 0: // TYPE_UNKNOWN case 1: // TYPE_NONE case 3:// TYPE_NETWORK case 4:// TYPE_RAM_DISK case 5:// TYPE_CDROM case 6:// TYPE_SWAP ?? break; case 2: // TYPE_LOCAL_DISK : DiskInfoVo disk = new DiskInfoVo(); disk.setDevName(fs.getDevName()); disk.setDirName(fs.getDirName()); usage = sigar.getFileSystemUsage(fs.getDirName()); disk.setTotalSize(usage.getTotal() / (1024 * 1024)); //disk.setFreeSize(usage.getFree()/(1024*1024)); disk.setAvailSize(usage.getAvail() / (1024 * 1024)); disk.setUsedSize(usage.getUsed() / (1024 * 1024)); disk.setUsePercent(usage.getUsePercent() * 100D + "%"); disk.setTypeName(fs.getTypeName()); disk.setSysTypeName(fs.getSysTypeName()); String val = diskWritesAndReadsOnInit.get(fs.getDevName()); if (val != null) { long timePeriod = (System.currentTimeMillis() - initTime) / 1000; long origRead = Long.parseLong(val.split("\\|")[0]); long origWrite = Long.parseLong(val.split("\\|")[1]); disk.setDiskReadRate((double) (usage.getDiskReadBytes() - origRead) / timePeriod); disk.setDiskWriteRate((double) (usage.getDiskWriteBytes() - origWrite) / timePeriod); } status.getDiskInfos().add(disk); } } } catch (Exception e) { } } public static void getNetInfo(Sigar sigar, ServerStatusVo status) { try { String ifNames[] = sigar.getNetInterfaceList(); for (int i = 0; i < ifNames.length; i++) { String name = ifNames[i]; NetInterfaceConfig ifconfig = sigar.getNetInterfaceConfig(name); if ((ifconfig.getFlags() & 1L) <= 0L) { System.out.println("!IFF_UP...skipping getNetInterfaceStat"); continue; } NetInterfaceStat ifstat = sigar.getNetInterfaceStat(name); System.out.println(name + ":" + ifstat.getRxPackets());// System.out.println(name + "??:" + ifstat.getTxPackets());// ?? System.out.println(name + ":" + ifstat.getRxBytes());// System.out.println(name + "??:" + ifstat.getTxBytes());// ?? System.out.println(name + ":" + ifstat.getRxErrors());// System.out.println(name + "???:" + ifstat.getTxErrors());// ??? System.out.println(name + ":" + ifstat.getRxDropped());// System.out.println(name + "??:" + ifstat.getTxDropped());// ?? } } catch (Exception e) { } } public static void main(String[] args) { ServerStatusVo status = new ServerStatusVo(); Sigar sigar = null; try { sigar = new Sigar(); getServerCpuInfo(sigar, status); CpuInfoVo x = status.getCpuInfos().get(0); System.out.println(x.getIdlePercent()); System.out.println(x.getUsedPercent()); } catch (Exception e) { // TODO: handle exception } } }