From 5eba7d107cffa81198bb964f7d6ff9b23b5466c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=81=AF=E7=BE=BD?= Date: Mon, 22 Feb 2016 17:22:15 +0800 Subject: [PATCH] add sigar --- pom.xml | 6 + src/main/java/darks/grid/GridConstant.java | 24 ++ src/main/java/darks/grid/GridContext.java | 5 +- .../grid/commons/BlankMachineInfoFactory.java | 56 +++++ .../commons/GenericMachineInfoFactory.java | 216 ++---------------- .../grid/commons/MachineInfoFactory.java | 61 +++++ .../java/darks/grid/commons/PlatformType.java | 51 +++++ .../grid/commons/SigarMachineInfoFactory.java | 88 +++++++ .../darks/grid/config/ConstantConfig.java | 51 +++++ .../darks/grid/config/GridConfigFactory.java | 15 ++ .../darks/grid/config/GridConfiguration.java | 15 +- .../java/darks/grid/utils/MachineUtils.java | 167 ++++++++++++++ src/main/java/darks/grid/utils/OSUtils.java | 148 ++++++++++++ .../java/darks/grid/utils/ReflectUtils.java | 35 ++- 14 files changed, 740 insertions(+), 198 deletions(-) create mode 100644 src/main/java/darks/grid/GridConstant.java create mode 100644 src/main/java/darks/grid/commons/BlankMachineInfoFactory.java create mode 100644 src/main/java/darks/grid/commons/PlatformType.java create mode 100644 src/main/java/darks/grid/commons/SigarMachineInfoFactory.java create mode 100644 src/main/java/darks/grid/config/ConstantConfig.java create mode 100644 src/main/java/darks/grid/utils/OSUtils.java diff --git a/pom.xml b/pom.xml index 7f1c02d..9931b1c 100644 --- a/pom.xml +++ b/pom.xml @@ -89,6 +89,12 @@ 3.18.0-GA true + + org.hyperic + sigar + 1.6.5.132 + true + diff --git a/src/main/java/darks/grid/GridConstant.java b/src/main/java/darks/grid/GridConstant.java new file mode 100644 index 0000000..54e0ea8 --- /dev/null +++ b/src/main/java/darks/grid/GridConstant.java @@ -0,0 +1,24 @@ +/** + * + * Copyright 2015 The Darks Grid Project (Liu lihua) + * + * 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 darks.grid; + +public class GridConstant { + + public static final String CFG_MACHINE_FACTORY = "machine.info.factory"; + +} diff --git a/src/main/java/darks/grid/GridContext.java b/src/main/java/darks/grid/GridContext.java index 9f30fad..76672b9 100644 --- a/src/main/java/darks/grid/GridContext.java +++ b/src/main/java/darks/grid/GridContext.java @@ -20,7 +20,6 @@ import java.net.InetSocketAddress; import darks.grid.beans.MachineInfo; -import darks.grid.commons.GenericMachineInfoFactory; import darks.grid.commons.MachineInfoFactory; import darks.grid.config.GridConfiguration; import darks.grid.manager.GridManager; @@ -46,13 +45,13 @@ public class GridContext implements Serializable, GridManager public GridContext() { - machineInfoFactory = new GenericMachineInfoFactory(); - machineInfo = machineInfoFactory.createMachineInfo(); } @Override public boolean initialize(GridConfiguration config) { + machineInfoFactory = MachineInfoFactory.buildFactory(config); + machineInfo = machineInfoFactory.createMachineInfo(); clusterName = config.getClusterName(); startupTime = System.currentTimeMillis(); startupNanoTime = System.nanoTime(); diff --git a/src/main/java/darks/grid/commons/BlankMachineInfoFactory.java b/src/main/java/darks/grid/commons/BlankMachineInfoFactory.java new file mode 100644 index 0000000..60d77b3 --- /dev/null +++ b/src/main/java/darks/grid/commons/BlankMachineInfoFactory.java @@ -0,0 +1,56 @@ +/** + * + * Copyright 2015 The Darks Grid Project (Liu lihua) + * + * 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 darks.grid.commons; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import darks.grid.beans.MachineInfo; +import darks.grid.beans.NodeHealth; + +public class BlankMachineInfoFactory extends MachineInfoFactory +{ + private static final Logger log = LoggerFactory.getLogger(BlankMachineInfoFactory.class); + + + public BlankMachineInfoFactory() + { + log.info("Create blank machine info factory"); + } + + @Override + public MachineInfo createMachineInfo() + { + MachineInfo info = new MachineInfo(); + return updateMachineInfo(info); + } + + @Override + public MachineInfo updateMachineInfo(MachineInfo info) + { + long maxMemory = Runtime.getRuntime().maxMemory(); + long totalMemory = Runtime.getRuntime().totalMemory(); + long freeMemory = Runtime.getRuntime().freeMemory(); + info.setUsedMaxMemoryUsage((float) ((double) (maxMemory - freeMemory) / (double) maxMemory)); + info.setUsedTotalMemoryUsage((float) ((double) (totalMemory - freeMemory) / (double) totalMemory)); + info.setProcessCpuUsage(-1f); + info.setSystemCpuUsage(-1f); + info.setHealthyScore(NodeHealth.evaluateLocal(info)); + return info; + } + +} diff --git a/src/main/java/darks/grid/commons/GenericMachineInfoFactory.java b/src/main/java/darks/grid/commons/GenericMachineInfoFactory.java index a88c554..3ccea25 100644 --- a/src/main/java/darks/grid/commons/GenericMachineInfoFactory.java +++ b/src/main/java/darks/grid/commons/GenericMachineInfoFactory.java @@ -16,13 +16,8 @@ */ package darks.grid.commons; -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.LineNumberReader; import java.lang.management.ManagementFactory; import java.lang.reflect.Method; -import java.util.StringTokenizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -31,22 +26,21 @@ import darks.grid.beans.MachineInfo; import darks.grid.beans.NodeHealth; -import darks.grid.utils.BytesUtils; -import darks.grid.utils.IOUtils; import darks.grid.utils.MachineUtils; +import darks.grid.utils.OSUtils; import darks.grid.utils.ReflectUtils; +@SuppressWarnings("restriction") public class GenericMachineInfoFactory extends MachineInfoFactory { private static final Logger log = LoggerFactory.getLogger(GenericMachineInfoFactory.class); - private static final int CPUTIME = 5000; - - private static final int PERCENT = 100; - - private static final int FAULTLENGTH = 10; - - @Override + public GenericMachineInfoFactory() + { + log.info("Create generic machine info factory"); + } + + @Override public MachineInfo createMachineInfo() { MachineInfo info = new MachineInfo(); @@ -71,15 +65,22 @@ public MachineInfo updateMachineInfo(MachineInfo info) private void updateProcessCpuUsage(OperatingSystemMXBean osmxb, MachineInfo info) { - Method method = ReflectUtils.getDeepMethod(OperatingSystemMXBean.class, "getProcessCpuLoad"); + Method method = ReflectUtils.getDeepMethod(OperatingSystemMXBean.class, "getProcessCpuLoad"); if (method != null) { Object ret = ReflectUtils.invokeMethod(osmxb, method); if (ret != null) { - info.setProcessCpuUsage((Float) ret); + info.setProcessCpuUsage(((Double) ret).floatValue()); } } + else + { + if (OSUtils.isWindows()) + info.setProcessCpuUsage(MachineUtils.getCpuUsageForWindows()); + else + info.setProcessCpuUsage(MachineUtils.getCpuUsageForLinux()); + } } private void updateSystemCpuUsage(OperatingSystemMXBean osmxb, MachineInfo info) @@ -90,182 +91,15 @@ private void updateSystemCpuUsage(OperatingSystemMXBean osmxb, MachineInfo info) Object ret = ReflectUtils.invokeMethod(osmxb, method); if (ret != null) { - info.setSystemCpuUsage((Float) ret); - } - } - } - - private static float getCpuUsageForLinux() - { - String version = System.getProperty("os.version"); - InputStream is = null; - InputStreamReader isr = null; - BufferedReader brStat = null; - StringTokenizer tokenStat = null; - try - { - Process process = Runtime.getRuntime().exec("top -b -n 1"); - is = process.getInputStream(); - isr = new InputStreamReader(is); - brStat = new BufferedReader(isr); - - if ("2.4".equals(version)) - { - brStat.readLine(); - brStat.readLine(); - brStat.readLine(); - brStat.readLine(); - - tokenStat = new StringTokenizer(brStat.readLine()); - tokenStat.nextToken(); - tokenStat.nextToken(); - String user = tokenStat.nextToken(); - tokenStat.nextToken(); - String system = tokenStat.nextToken(); - tokenStat.nextToken(); - String nice = tokenStat.nextToken(); - - System.out.println(user + " , " + system + " , " + nice); - - user = user.substring(0, user.indexOf("%")); - system = system.substring(0, system.indexOf("%")); - nice = nice.substring(0, nice.indexOf("%")); - - float userUsage = new Float(user).floatValue(); - float systemUsage = new Float(system).floatValue(); - float niceUsage = new Float(nice).floatValue(); - - return (userUsage + systemUsage + niceUsage) / 100; - } - else - { - brStat.readLine(); - brStat.readLine(); - - tokenStat = new StringTokenizer(brStat.readLine()); - tokenStat.nextToken(); - tokenStat.nextToken(); - tokenStat.nextToken(); - tokenStat.nextToken(); - tokenStat.nextToken(); - tokenStat.nextToken(); - tokenStat.nextToken(); - String cpuUsage = tokenStat.nextToken(); - Float usage = new Float(cpuUsage.substring(0, cpuUsage.indexOf("%"))); - return (1 - usage.floatValue() / 100); - } - - } - catch (Exception e) - { - log.error(e.getMessage(), e); - } - finally - { - IOUtils.closeStream(is); - IOUtils.closeStream(isr); - IOUtils.closeStream(brStat); - } - return 0; - } - - private double getCpuRatioForWindows() - { - try - { - String procCmd = System.getenv("windir") + "//system32//wbem//wmic.exe process get Caption,CommandLine," - + "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount"; - // 取进程信息 - long[] c0 = readCpuInfo(Runtime.getRuntime().exec(procCmd)); - Thread.sleep(CPUTIME); - long[] c1 = readCpuInfo(Runtime.getRuntime().exec(procCmd)); - if (c0 != null && c1 != null) - { - long idletime = c1[0] - c0[0]; - long busytime = c1[1] - c0[1]; - return Double.valueOf(PERCENT * (busytime) / (busytime + idletime)).doubleValue(); - } - else - { - return 0.0; + info.setSystemCpuUsage(((Double) ret).floatValue()); } } - catch (Exception ex) - { - ex.printStackTrace(); - return 0.0; - } - } - - /** */ - /** - * 读取CPU信息. - * - * @param proc - * @return - * @author amg * Creation date: 2008-4-25 - 下午06:10:14 - */ - private long[] readCpuInfo(Process proc) - { - long[] retn = new long[2]; - try - { - proc.getOutputStream().close(); - InputStreamReader ir = new InputStreamReader(proc.getInputStream()); - LineNumberReader input = new LineNumberReader(ir); - String line = input.readLine(); - if (line == null || line.length() < FAULTLENGTH) - { - return null; - } - int capidx = line.indexOf("Caption"); - int cmdidx = line.indexOf("CommandLine"); - int rocidx = line.indexOf("ReadOperationCount"); - int umtidx = line.indexOf("UserModeTime"); - int kmtidx = line.indexOf("KernelModeTime"); - int wocidx = line.indexOf("WriteOperationCount"); - long idletime = 0; - long kneltime = 0; - long usertime = 0; - while ((line = input.readLine()) != null) - { - if (line.length() < wocidx) - { - continue; - } - // 字段出现顺序:Caption,CommandLine,KernelModeTime,ReadOperationCount, - // ThreadCount,UserModeTime,WriteOperation - String caption = BytesUtils.subString(line, capidx, cmdidx - 1).trim(); - String cmd = BytesUtils.subString(line, cmdidx, kmtidx - 1).trim(); - if (cmd.indexOf("wmic.exe") >= 0) - { - continue; - } - // log.info("line="+line); - if (caption.equals("System Idle Process") || caption.equals("System")) - { - idletime += Long.valueOf(BytesUtils.subString(line, kmtidx, rocidx - 1).trim()).longValue(); - idletime += Long.valueOf(BytesUtils.subString(line, umtidx, wocidx - 1).trim()).longValue(); - continue; - } - - kneltime += Long.valueOf(BytesUtils.subString(line, kmtidx, rocidx - 1).trim()).longValue(); - usertime += Long.valueOf(BytesUtils.subString(line, umtidx, wocidx - 1).trim()).longValue(); - } - retn[0] = idletime; - retn[1] = kneltime + usertime; - return retn; - } - catch (Exception ex) - { - log.error(ex.getMessage(), ex); - } - finally - { - IOUtils.closeStream(proc.getErrorStream()); - IOUtils.closeStream(proc.getInputStream()); - proc.destroy(); - } - return null; + else + { + if (OSUtils.isWindows()) + info.setSystemCpuUsage(MachineUtils.getCpuUsageForWindows()); + else + info.setSystemCpuUsage(MachineUtils.getCpuUsageForLinux()); + } } } diff --git a/src/main/java/darks/grid/commons/MachineInfoFactory.java b/src/main/java/darks/grid/commons/MachineInfoFactory.java index 81278cd..8f61140 100644 --- a/src/main/java/darks/grid/commons/MachineInfoFactory.java +++ b/src/main/java/darks/grid/commons/MachineInfoFactory.java @@ -16,13 +16,74 @@ */ package darks.grid.commons; +import java.lang.reflect.Method; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import darks.grid.GridConstant; import darks.grid.beans.MachineInfo; +import darks.grid.config.GridConfiguration; +import darks.grid.utils.ReflectUtils; public abstract class MachineInfoFactory { + + private static final Logger log = LoggerFactory.getLogger(MachineInfoFactory.class); public abstract MachineInfo createMachineInfo(); public abstract MachineInfo updateMachineInfo(MachineInfo info); + public static MachineInfoFactory buildFactory(GridConfiguration config) + { + String customFactory = config.getConstantConfig().getConstant(GridConstant.CFG_MACHINE_FACTORY); + if (customFactory != null && !"".equals(customFactory.trim())) + { + try { + MachineInfoFactory factory = (MachineInfoFactory) ReflectUtils.newInstance(Class.forName(customFactory)); + if (factory != null) + return factory; + } catch (Exception e) { + log.error("Fail to instance custom machine factory. Cause " + e.getMessage(), e); + } + } + if (isGenericJdk7Valid()) + return new GenericMachineInfoFactory(); + if (isSigarValid()) + return new SigarMachineInfoFactory(); + if (isGenericValid()) + return new GenericMachineInfoFactory(); + return new BlankMachineInfoFactory(); + } + + private static boolean isGenericValid() { + try { + return Class.forName("com.sun.management.OperatingSystemMXBean") != null; + } catch (Exception e) { + return false; + } + } + + private static boolean isGenericJdk7Valid() { + try { + Class clazz = Class.forName("com.sun.management.OperatingSystemMXBean"); + if (clazz != null) + { + Method method = ReflectUtils.getDeepMethod(clazz, "getProcessCpuLoad"); + return method != null; + } + } catch (Exception e) { + } + return false; + } + + private static boolean isSigarValid() { + try { + return Class.forName("org.hyperic.sigar.CpuPerc") != null + && Class.forName("org.hyperic.sigar.ProcCpu") != null; + } catch (Exception e) { + return false; + } + } } diff --git a/src/main/java/darks/grid/commons/PlatformType.java b/src/main/java/darks/grid/commons/PlatformType.java new file mode 100644 index 0000000..01dacbc --- /dev/null +++ b/src/main/java/darks/grid/commons/PlatformType.java @@ -0,0 +1,51 @@ +/** + * + * Copyright 2015 The Darks Grid Project (Liu lihua) + * + * 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 darks.grid.commons; + +public enum PlatformType { + + Any("any"), + Linux("Linux"), + Mac_OS("Mac OS"), + Mac_OS_X("Mac OS X"), + Windows("Windows"), + OS2("OS/2"), + Solaris("Solaris"), + SunOS("SunOS"), + MPEiX("MPE/iX"), + HP_UX("HP-UX"), + AIX("AIX"), + OS390("OS/390"), + FreeBSD("FreeBSD"), + Irix("Irix"), + Digital_Unix("Digital Unix"), + NetWare_411("NetWare"), + OSF1("OSF1"), + OpenVMS("OpenVMS"), + Others("Others"); + + private PlatformType(String name){ + this.name = name; + } + + public String toString(){ + return name; + } + + private String name; +} diff --git a/src/main/java/darks/grid/commons/SigarMachineInfoFactory.java b/src/main/java/darks/grid/commons/SigarMachineInfoFactory.java new file mode 100644 index 0000000..1ec5a3c --- /dev/null +++ b/src/main/java/darks/grid/commons/SigarMachineInfoFactory.java @@ -0,0 +1,88 @@ +/** + * + * Copyright 2015 The Darks Grid Project (Liu lihua) + * + * 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 darks.grid.commons; + +import org.hyperic.sigar.CpuPerc; +import org.hyperic.sigar.Mem; +import org.hyperic.sigar.ProcCpu; +import org.hyperic.sigar.Sigar; +import org.hyperic.sigar.SigarException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import darks.grid.beans.MachineInfo; +import darks.grid.beans.NodeHealth; + +public class SigarMachineInfoFactory extends MachineInfoFactory +{ + private static final Logger log = LoggerFactory.getLogger(SigarMachineInfoFactory.class); + + public SigarMachineInfoFactory() + { + log.info("Create sigar machine info factory"); + } + + @Override + public MachineInfo createMachineInfo() + { + MachineInfo info = new MachineInfo(); + return updateMachineInfo(info); + } + + @Override + public MachineInfo updateMachineInfo(MachineInfo info) + { + Sigar sigar = new Sigar(); + long maxMemory = Runtime.getRuntime().maxMemory(); + long totalMemory = Runtime.getRuntime().totalMemory(); + long freeMemory = Runtime.getRuntime().freeMemory(); + info.setUsedMaxMemoryUsage((float) ((double) (maxMemory - freeMemory) / (double) maxMemory)); + info.setUsedTotalMemoryUsage((float) ((double) (totalMemory - freeMemory) / (double) totalMemory)); + Mem memory = null; + try { + memory = sigar.getMem(); + info.setUsedPhysicalMemoryUsage((float)((double) memory.getUsed() / (double)memory.getTotal())); + } catch (SigarException e) { + log.error(e.getMessage(), e); + } + updateProcessCpuUsage(sigar, info); + updateSystemCpuUsage(sigar, info); + info.setHealthyScore(NodeHealth.evaluateLocal(info)); + return info; + } + + private void updateProcessCpuUsage(Sigar sigar, MachineInfo info) + { + try { + long pid = sigar.getPid(); + ProcCpu cpu = sigar.getProcCpu(pid); + info.setProcessCpuUsage((float) cpu.getPercent()); + } catch (SigarException e) { + log.error(e.getMessage(), e); + } + } + + private void updateSystemCpuUsage(Sigar sigar, MachineInfo info) + { + try { + CpuPerc perc = sigar.getCpuPerc(); + info.setSystemCpuUsage((float) perc.getCombined()); + } catch (SigarException e) { + log.error(e.getMessage(), e); + } + } +} diff --git a/src/main/java/darks/grid/config/ConstantConfig.java b/src/main/java/darks/grid/config/ConstantConfig.java new file mode 100644 index 0000000..c69bc89 --- /dev/null +++ b/src/main/java/darks/grid/config/ConstantConfig.java @@ -0,0 +1,51 @@ +/** + * + * Copyright 2015 The Darks Grid Project (Liu lihua) + * + * 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 darks.grid.config; + +import java.util.HashMap; +import java.util.Map; + +public class ConstantConfig { + + Map constantMap = new HashMap(); + + public ConstantConfig() + { + + } + + public void setConstant(String key, String value) + { + constantMap.put(key, value); + } + + public String getConstant(String key) + { + return constantMap.get(key); + } + + public Map getConstantMap() { + return constantMap; + } + + public void setConstantMap(Map constantMap) { + this.constantMap = constantMap; + } + + +} diff --git a/src/main/java/darks/grid/config/GridConfigFactory.java b/src/main/java/darks/grid/config/GridConfigFactory.java index e2accd8..83463b8 100644 --- a/src/main/java/darks/grid/config/GridConfigFactory.java +++ b/src/main/java/darks/grid/config/GridConfigFactory.java @@ -123,6 +123,10 @@ else if ("component".equalsIgnoreCase(el.getNodeName())) { parseComponent(config, el); } + else if ("constant".equalsIgnoreCase(el.getNodeName())) + { + parseConstant(config.getConstantConfig(), el); + } else { parseCustomComponent(config, el); @@ -171,6 +175,17 @@ private static void parseMaster(GridConfiguration config, Element el) } } } + + private static void parseConstant(ConstantConfig config, Element el) + { + String name = el.getAttribute("name"); + String value = el.getAttribute("name"); + if (name == null || "".equals(name.trim())) + throw new GridException("Invalid constant name " + name); + if (value == null || "".equals(value.trim())) + throw new GridException("Invalid constant value " + value + " for name " + name); + config.setConstant(name, value); + } private static void parseComponent(GridConfiguration config, Element el) { diff --git a/src/main/java/darks/grid/config/GridConfiguration.java b/src/main/java/darks/grid/config/GridConfiguration.java index 653a733..417d004 100644 --- a/src/main/java/darks/grid/config/GridConfiguration.java +++ b/src/main/java/darks/grid/config/GridConfiguration.java @@ -36,6 +36,8 @@ public class GridConfiguration implements Serializable private StorageConfig storageConfig = new StorageConfig(); private MasterConfig masterConfig = new MasterConfig(); + + private ConstantConfig constantConfig = new ConstantConfig(); public GridConfiguration() { @@ -85,7 +87,18 @@ public MasterConfig getMasterConfig() return masterConfig; } - @Override + + public ConstantConfig getConstantConfig() + { + return constantConfig; + } + + public void setConstantConfig(ConstantConfig constantConfig) + { + this.constantConfig = constantConfig; + } + + @Override public String toString() { return "GridConfiguration [clusterName=" + clusterName + ", networkConfig=" + networkConfig diff --git a/src/main/java/darks/grid/utils/MachineUtils.java b/src/main/java/darks/grid/utils/MachineUtils.java index 9b6d3b0..219010b 100644 --- a/src/main/java/darks/grid/utils/MachineUtils.java +++ b/src/main/java/darks/grid/utils/MachineUtils.java @@ -17,6 +17,10 @@ package darks.grid.utils; +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.LineNumberReader; import java.lang.management.ManagementFactory; import java.lang.reflect.Field; @@ -29,6 +33,12 @@ public final class MachineUtils { private static final Logger log = LoggerFactory.getLogger(MachineUtils.class); + + private static final int CPUTIME = 500; + + private static final int PERCENT = 100; + + private static final int FAULTLENGTH = 10; private MachineUtils() { @@ -86,4 +96,161 @@ public static Long getReservedDirectMemory() return null; } } + + public static float getCpuUsageForLinux() + { + InputStream is = null; + InputStreamReader isr = null; + BufferedReader reader = null; + Process process = null; + try + { + process = Runtime.getRuntime().exec("top -b -n 1"); + is = process.getInputStream(); + isr = new InputStreamReader(is); + reader = new BufferedReader(isr); + float sumUsage = 0; + boolean flag = false; + int cpuIndex = -1; + int cmdIndex = -1; + String line = null; + while ((line = reader.readLine()) != null) + { + line = line.trim(); + if ("".equals(line)) + continue; + if (!flag && line.indexOf("PID") >= 0 && line.indexOf("CPU") >= 0) + { + flag = true; + String[] captions = line.split("[\\s\\t]+"); + for (int i = 0; i < captions.length; i++) + { + String caption = captions[i]; + if ("%CPU".equals(caption)) + cpuIndex = i; + if ("COMMAND".equals(caption)) + cmdIndex = i; + } + } + else if (flag && cpuIndex >=0 && cmdIndex >= 0) + { + String[] datas = line.split("[\\s\\t]+"); + String cpuInfo = datas[cpuIndex]; + String cmdInfo = datas[cmdIndex].toLowerCase().trim(); + if (cmdInfo.startsWith("top")) + continue; + float radio = Float.parseFloat(cpuInfo); + sumUsage += radio; + } + } + if (cpuIndex < 0) + return -1; + return sumUsage / 100.f; + } + catch (Exception e) + { + log.error(e.getMessage(), e); + } + finally + { + IOUtils.closeStream(is); + IOUtils.closeStream(isr); + IOUtils.closeStream(reader); + if (process != null) + process.destroy(); + } + return -1; + } + + public static float getCpuUsageForWindows() + { + try + { + String procCmd = System.getenv("windir") + "//system32//wbem//wmic.exe process get Caption,CommandLine," + + "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount"; + // 取进程信息 + long[] c0 = readWindowsCpuInfo(Runtime.getRuntime().exec(procCmd)); + Thread.sleep(CPUTIME); + long[] c1 = readWindowsCpuInfo(Runtime.getRuntime().exec(procCmd)); + if (c0 != null && c1 != null) + { + long idletime = c1[0] - c0[0]; + long busytime = c1[1] - c0[1]; + return (float) (PERCENT * (busytime)) / (float) (busytime + idletime); + } + else + { + return 0.0f; + } + } + catch (Exception ex) + { + ex.printStackTrace(); + return 0.0f; + } + } + + private static long[] readWindowsCpuInfo(Process proc) + { + long[] retn = new long[2]; + try + { + proc.getOutputStream().close(); + InputStreamReader ir = new InputStreamReader(proc.getInputStream()); + LineNumberReader input = new LineNumberReader(ir); + String line = input.readLine(); + if (line == null || line.length() < FAULTLENGTH) + { + return null; + } + int capidx = line.indexOf("Caption"); + int cmdidx = line.indexOf("CommandLine"); + int rocidx = line.indexOf("ReadOperationCount"); + int umtidx = line.indexOf("UserModeTime"); + int kmtidx = line.indexOf("KernelModeTime"); + int wocidx = line.indexOf("WriteOperationCount"); + long idletime = 0; + long kneltime = 0; + long usertime = 0; + while ((line = input.readLine()) != null) + { + if (line.length() < wocidx) + { + continue; + } + // 字段出现顺序:Caption,CommandLine,KernelModeTime,ReadOperationCount, + // ThreadCount,UserModeTime,WriteOperation + String caption = line.substring(capidx, cmdidx - 1).trim(); + String cmd = line.substring(cmdidx, kmtidx - 1).trim(); + if (cmd.indexOf("wmic.exe") >= 0) + { + continue; + } + // log.info("line="+line); + if (caption.equals("System Idle Process") || caption.equals("System")) + { + idletime += Long.valueOf(line.substring(kmtidx, rocidx - 1).trim()).longValue(); + idletime += Long.valueOf(line.substring(umtidx, wocidx - 1).trim()).longValue(); + continue; + } + + kneltime += Long.valueOf(line.substring(kmtidx, rocidx - 1).trim()).longValue(); + usertime += Long.valueOf(line.substring(umtidx, wocidx - 1).trim()).longValue(); + } + retn[0] = idletime; + retn[1] = kneltime + usertime; + return retn; + } + catch (Exception ex) + { + log.error(ex.getMessage(), ex); + } + finally + { + IOUtils.closeStream(proc.getErrorStream()); + IOUtils.closeStream(proc.getInputStream()); + proc.destroy(); + } + return null; + } } diff --git a/src/main/java/darks/grid/utils/OSUtils.java b/src/main/java/darks/grid/utils/OSUtils.java new file mode 100644 index 0000000..86ae955 --- /dev/null +++ b/src/main/java/darks/grid/utils/OSUtils.java @@ -0,0 +1,148 @@ +/** + * + * Copyright 2015 The Darks Grid Project (Liu lihua) + * + * 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 darks.grid.utils; + +import darks.grid.commons.PlatformType; + +public final class OSUtils { + + private static String OS = System.getProperty("os.name").toLowerCase(); + + private static PlatformType platform; + + static + { + initPlatformType(); + } + + private OSUtils() { + + } + + public static boolean isLinux() { + return OS.indexOf("linux") >= 0; + } + + public static boolean isMacOS() { + return OS.indexOf("mac") >= 0 && OS.indexOf("os") > 0 && OS.indexOf("x") < 0; + } + + public static boolean isMacOSX() { + return OS.indexOf("mac") >= 0 && OS.indexOf("os") > 0 && OS.indexOf("x") > 0; + } + + public static boolean isWindows() { + return OS.indexOf("windows") >= 0; + } + + public static boolean isOS2() { + return OS.indexOf("os/2") >= 0; + } + + public static boolean isSolaris() { + return OS.indexOf("solaris") >= 0; + } + + public static boolean isSunOS() { + return OS.indexOf("sunos") >= 0; + } + + public static boolean isMPEiX() { + return OS.indexOf("mpe/ix") >= 0; + } + + public static boolean isHPUX() { + return OS.indexOf("hp-ux") >= 0; + } + + public static boolean isAix() { + return OS.indexOf("aix") >= 0; + } + + public static boolean isOS390() { + return OS.indexOf("os/390") >= 0; + } + + public static boolean isFreeBSD() { + return OS.indexOf("freebsd") >= 0; + } + + public static boolean isIrix() { + return OS.indexOf("irix") >= 0; + } + + public static boolean isDigitalUnix() { + return OS.indexOf("digital") >= 0 && OS.indexOf("unix") > 0; + } + + public static boolean isNetWare() { + return OS.indexOf("netware") >= 0; + } + + public static boolean isOSF1() { + return OS.indexOf("osf1") >= 0; + } + + public static boolean isOpenVMS() { + return OS.indexOf("openvms") >= 0; + } + + public static PlatformType getPlatform() { + return platform; + } + + private static PlatformType initPlatformType() { + if (isAix()) { + platform = PlatformType.AIX; + } else if (isDigitalUnix()) { + platform = PlatformType.Digital_Unix; + } else if (isFreeBSD()) { + platform = PlatformType.FreeBSD; + } else if (isHPUX()) { + platform = PlatformType.HP_UX; + } else if (isIrix()) { + platform = PlatformType.Irix; + } else if (isLinux()) { + platform = PlatformType.Linux; + } else if (isMacOS()) { + platform = PlatformType.Mac_OS; + } else if (isMacOSX()) { + platform = PlatformType.Mac_OS_X; + } else if (isMPEiX()) { + platform = PlatformType.MPEiX; + } else if (isNetWare()) { + platform = PlatformType.NetWare_411; + } else if (isOpenVMS()) { + platform = PlatformType.OpenVMS; + } else if (isOS2()) { + platform = PlatformType.OS2; + } else if (isOS390()) { + platform = PlatformType.OS390; + } else if (isOSF1()) { + platform = PlatformType.OSF1; + } else if (isSolaris()) { + platform = PlatformType.Solaris; + } else if (isSunOS()) { + platform = PlatformType.SunOS; + } else if (isWindows()) { + platform = PlatformType.Windows; + } else { + platform = PlatformType.Others; + } + return platform; + } + +} diff --git a/src/main/java/darks/grid/utils/ReflectUtils.java b/src/main/java/darks/grid/utils/ReflectUtils.java index 387da1c..c1b4664 100644 --- a/src/main/java/darks/grid/utils/ReflectUtils.java +++ b/src/main/java/darks/grid/utils/ReflectUtils.java @@ -85,7 +85,7 @@ public static Field getDeepField(Class clazz, String fieldName) clazz = clazz.getSuperclass(); } } - while (!clazz.equals(Object.class) && field == null); + while (clazz != null && !clazz.equals(Object.class) && field == null); return field; } catch (Exception e) @@ -95,8 +95,22 @@ public static Field getDeepField(Class clazz, String fieldName) } } + public static Method getMethod(Class clazz, String methodName, Class... types) + { + try + { + return clazz.getMethod(methodName, types); + } + catch (Exception e) + { + return null; + } + } + public static Method getDeepMethod(Class clazz, String methodName, Class... types) { + if (clazz.isInterface()) + return getMethod(clazz, methodName, types); try { Method method = null; @@ -111,10 +125,25 @@ public static Method getDeepMethod(Class clazz, String methodName, Class.. } catch (NoSuchMethodException e) { - clazz = clazz.getSuperclass(); + if (!clazz.isInterface()) + clazz = clazz.getSuperclass(); + else + { + Class[] interfaceClass = clazz.getInterfaces(); + if (interfaceClass != null) + { + for (Class c : interfaceClass) + { + method = getMethod(c, methodName, types); + if (method != null) + break; + } + } + clazz = null; + } } } - while (!clazz.equals(Object.class) && method == null); + while (clazz != null && !clazz.equals(Object.class) && method == null); return method; } catch (Exception e)