Java tutorial
/* Copyright (C) 2006 NTT DATA Corporation This program is free software; you can redistribute it and/or Modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package com.clustercontrol.ping.factory; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.clustercontrol.bean.HinemosModuleConstant; import com.clustercontrol.bean.PriorityConstant; import com.clustercontrol.collect.bean.Sample; import com.clustercontrol.collect.util.CollectDataUtil; import com.clustercontrol.fault.FacilityNotFound; import com.clustercontrol.fault.HinemosUnknown; import com.clustercontrol.fault.MonitorNotFound; import com.clustercontrol.monitor.run.bean.MonitorRunResultInfo; import com.clustercontrol.monitor.run.factory.RunMonitor; import com.clustercontrol.monitor.run.factory.RunMonitorNumericValueType; import com.clustercontrol.monitor.run.model.MonitorJudgementInfo; import com.clustercontrol.performance.bean.CollectedDataErrorTypeConstant; import com.clustercontrol.ping.bean.PingResult; import com.clustercontrol.ping.bean.PingRunCountConstant; import com.clustercontrol.ping.bean.PingRunIntervalConstant; import com.clustercontrol.ping.model.PingCheckInfo; import com.clustercontrol.ping.util.PingProperties; import com.clustercontrol.ping.util.QueryUtil; import com.clustercontrol.ping.util.ReachAddress; import com.clustercontrol.ping.util.ReachAddressFping; import com.clustercontrol.repository.model.NodeInfo; import com.clustercontrol.repository.session.RepositoryControllerBean; import com.clustercontrol.util.HinemosTime; import com.clustercontrol.util.MessageConstant; import com.clustercontrol.util.apllog.AplLogger; /** * ping?<BR> * * @version 4.0.0 * @since 2.0.0 */ public class RunMonitorPing extends RunMonitorNumericValueType { private static Log m_log = LogFactory.getLog(RunMonitorPing.class); /** ping */ private PingCheckInfo m_ping = null; /** */ private int m_runCount = PingRunCountConstant.TYPE_COUNT_01; /** */ private int m_runInterval = PingRunIntervalConstant.TYPE_SEC_01; /** */ private int m_pingTimeout; /** */ private String m_message = null; /** */ private String m_messageOrg = null; /** % */ private int m_lost = 0; /** ? */ private long m_average = 0; //ping private ReachAddress m_reachability = null; //fping private ReachAddressFping m_reachabilityFping = null; //fping?fping private ArrayList<String> m_MsgErr = null; //fping?fping private ArrayList<String> m_MsgErrV6 = null; private Hashtable<String, String[]> m_Target; /** * * * */ public RunMonitorPing() { super(); PingProperties.getProperties(); } /** * ???CallableTask??????? * * @see com.clustercontrol.monitor.run.factory.RunMonitor#runMonitorInfo() * @see com.clustercontrol.monitor.run.util.MonitorExecuteTask */ @Override protected RunMonitor createMonitorInstance() { return new RunMonitorPing(); } /** * ping????<BR> * * @param facilityId ID * @return ???????true */ @Override public boolean collect(String facilityId) { if (m_now != null) { m_nodeDate = m_now.getTime(); } m_message = ""; m_messageOrg = ""; m_lost = 0; m_average = 0; if (m_reachability == null) { m_reachability = new ReachAddress(m_runCount, m_runInterval, m_pingTimeout); } try { // ?? NodeInfo info = new RepositoryControllerBean().getNode(facilityId); String ipNetworkNumber = info.getIpAddressV4(); String nodeName = info.getNodeName(); boolean result = m_reachability.isReachable(ipNetworkNumber, nodeName); m_message = m_reachability.getMessage(); m_messageOrg = m_reachability.getMessageOrg(); if (result) { m_lost = m_reachability.getLost(); m_average = m_reachability.getAverage(); m_value = m_average; } return result; } catch (FacilityNotFound e) { m_message = MessageConstant.MESSAGE_COULD_NOT_GET_NODE_ATTRIBUTES_PING.getMessage(); m_messageOrg = e.getMessage(); return false; } catch (HinemosUnknown e) { m_message = MessageConstant.MESSAGE_COULD_NOT_GET_NODE_ATTRIBUTES_PING.getMessage(); m_messageOrg = e.getMessage(); return false; } } /** * fping?ping?????<BR> * @param facilityId Ping?ID()collect?facilityID??? * @return ???????true * @throws HinemosUnknown */ private boolean collectFping(ArrayList<String> facilityList, ArrayList<Integer> priporityList) throws HinemosUnknown { //??? if (m_now != null) { m_nodeDate = m_now.getTime(); } //?????? // hosts[] IP(String ??) // hostsv6[] IPv6(String??) // node IP???? // target nodo? HashSet<String> hosts = new HashSet<String>(); HashSet<String> hostsv6 = new HashSet<String>(); m_Target = new Hashtable<String, String[]>(); String facilityId = null; int version = 4; String[] node; for (int index = 0; index < facilityList.size(); index++) { facilityId = facilityList.get(index); if (facilityId != null && !"".equals(facilityId)) { node = new String[2]; try { // ?? NodeInfo info = new RepositoryControllerBean().getNode(facilityId); //m_log.error(facilityAttrMap.get(FacilityAttributeConstant.IPPROTOCOLNUMBER)); //???????version? if (info.getIpAddressVersion() != null) { version = info.getIpAddressVersion(); } else { version = 4; } if (version == 6) { InetAddress[] ip = InetAddress.getAllByName(info.getIpAddressV6()); if (ip.length != 1) { //IPInetAddress??????1???????? //UnnownHostExcption UnknownHostException e = new UnknownHostException(); m_log.info("collectFping() : " + e.getClass().getSimpleName() + ", " + e.getMessage()); throw e; } node[0] = ip[0].getHostAddress(); if (node[0] != null && !node[0].equals("")) { //IPHashSet????? hostsv6.add(node[0]); } } else { node[0] = info.getIpAddressV4(); if (node[0] != null && !node[0].equals("")) { //IPHashSet????? hosts.add(node[0]); } } if (node[0] != null && !node[0].equals("")) { node[1] = info.getNodeName(); //target?????? m_Target.put(facilityId, node); } } catch (FacilityNotFound e) { m_message = MessageConstant.MESSAGE_COULD_NOT_GET_NODE_ATTRIBUTES_PING.getMessage(); m_messageOrg = e.getMessage(); return false; } catch (UnknownHostException e) { // ??? } } } if (m_reachabilityFping == null) { m_reachabilityFping = new ReachAddressFping(m_runCount, m_runInterval, m_pingTimeout); } boolean result = true; boolean resultTmp = true; //IPv4???fping?? if (hosts.size() != 0) { result = m_reachabilityFping.isReachable(hosts, 4); m_MsgErr = m_reachabilityFping.getM_errMsg(); } //IPv6???fping6?? if (hostsv6.size() != 0) { resultTmp = m_reachabilityFping.isReachable(hostsv6, 6); m_MsgErrV6 = m_reachabilityFping.getM_errMsg(); //??&???? result = result & resultTmp; } return result; } /** * fping???IP??????<BR> * nodeMap?????public * * @param hosts fping??? * @param message * @param count ping * @return (IP ??)?? */ public Hashtable<String, PingResult> wrapUpFping(ArrayList<String> messages, int count, int version) { Hashtable<String, PingResult> ret = new Hashtable<String, PingResult>(); HashMap<String, String> normalMap = new HashMap<String, String>(); //IP, HashMap<String, String> aberrantMap = new HashMap<String, String>(); //IP, HashSet<String> hostSet = new HashSet<String>(); /** * ????????5? * ??? * **/ String msg; String msgOrg; int lost; float average = 0; float reachRatio; //IP??? Pattern patternIp; if (version == 6) { patternIp = Pattern.compile("^([0-9].*)|^(\\:\\:.*)"); } else { patternIp = Pattern.compile("^([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}.*)"); } //fping?? Pattern patternSp = Pattern.compile("(\\s:\\s|\\s)+"); //? Pattern patternNormal = Pattern.compile("([0-9]+\\.[0-9]+|-)"); //IP Matcher matcherIp; Matcher matcherValue; String message; /* * fping??? * ??? 127.0.0.1 : 0.10 1.23 * ???? 127.0.0.1 : - - * ???(?IP???) 127.0.0.1 : duplicate for [0], xx bytes, x.xx ms * ???(GW??????) 127.0.0.1 : () * ?? * ???????????????????? * 2???????????? * ???????IP???????? * ????? */ /* * ????? */ Iterator<String> itr = messages.iterator(); m_log.debug("wrapUpFping(): start logic: " + messages.size()); while (itr.hasNext()) { message = itr.next(); m_log.debug("wrapUpFping(): checkpoint"); //IP?????????? boolean bValidIP = false; if (version == 6) { m_log.debug("wrapUpFping(): into IPv6 loop"); String[] strs = message.split(" "); try { InetAddress.getByName(strs[0]); bValidIP = true; } catch (Exception e) { m_log.warn("wrapUpFping() invalid IPv6 adress: original message: " + message, e); m_log.warn("wrapUpFping() stack trace: " + e.getClass().getSimpleName() + ", " + e.getMessage(), e); } } else { matcherIp = patternIp.matcher(message); if (matcherIp.matches()) { bValidIP = true; } } if (bValidIP) { //?IP???????? String[] strs = patternSp.split(message); //?IP??? boolean isNormal = true; for (int i = 1; i < strs.length; i++) { matcherValue = patternNormal.matcher(strs[i]); if (!matcherValue.matches()) { isNormal = false; } } if (isNormal) { normalMap.put(strs[0], message); m_log.debug("wrapUpFping() : normalValue : " + message); } else { // ??IP??????? if (aberrantMap.get(strs[0]) != null && !(aberrantMap.get(strs[0])).equals("")) { String aberrantMessage = aberrantMap.get(strs[0]); aberrantMessage = aberrantMessage + "\n" + message; aberrantMap.put(strs[0], aberrantMessage); } else { aberrantMap.put(strs[0], message); } m_log.debug("wrapUpFping() : aberrantValue : " + message); } hostSet.add(strs[0]); } } /* * ?????????? */ itr = hostSet.iterator(); m_log.debug("wrapUpFping() : before into check result append loop"); while (itr.hasNext()) { m_log.debug("wrapUpFping() : after into check result append loop"); String host = itr.next(); String normalMessage = normalMap.get(host); String aberrantMessage = aberrantMap.get(host); if (normalMessage != null && !normalMessage.equals("")) { // String ?? String[] strs = patternSp.split(normalMessage); /*????????*/ float max = 0; //(?0) float min = Float.MAX_VALUE; //?(?Float?) int num = 0; //? //???????? for (int i = 1; i <= count; i++) { if (strs[i].equals("-")) { //?-???????? } else { //?count up num++; //??? if (max < Float.parseFloat(strs[i])) { max = Float.parseFloat(strs[i]); } //???? if (min > Float.parseFloat(strs[i])) { min = Float.parseFloat(strs[i]); } //? average += Float.parseFloat(strs[i]); } } //????????????? average /= num; /* * ??? */ StringBuffer buffer = new StringBuffer(); buffer.append("Pinging " + host + " (" + host + ") .\n\n"); // ??0?? if (num == 0) { //??0??lost100 reach0 lost = 100; reachRatio = 0; for (int i = 0; i < count; i++) // buffer.append("From " + strs[0] + " icmp_seq="+ index +" Destination Host Unreachable"); buffer.append("Reply from " + host + " icmp_seq=" + i + " Destination Host Unreachable\n"); buffer.append("\nPing statistics for " + host + ":\n"); buffer.append("Packets: Sent = " + count + ", Received = " + num + ", Lost = " + (count - num) + " (" + lost + "% loss),"); } else { lost = (count - num) * 100 / count; reachRatio = (float) num * 100 / count; buffer.append("\nPing statistics for " + host + ":\n"); buffer.append("Packets: Sent = " + count + ", Received = " + num + ", Lost = " + (count - num) + " (" + lost + "% loss),"); buffer.append("Approximate round trip times in milli-seconds:\n"); buffer.append( "\tMinimum = " + min + "ms, Maximum = " + max + "ms, Average = " + average + "ms\n"); } // ?????msgOrg? if (aberrantMessage != null && !aberrantMessage.equals("")) { buffer.append("\n\n" + aberrantMessage + "\n"); } msgOrg = buffer.toString(); msg = "Packets: Sent = " + count + ", Received = " + num + ", Lost = " + (count - num) + " (" + lost + "% loss)"; PingResult res = new PingResult(host, msg, msgOrg, lost, average, reachRatio); ret.put(host, res); m_log.debug("wrapUpFping() : success msg = " + msg + ", msgOrg = " + msgOrg); msg = ""; msgOrg = ""; lost = 100; average = 0; reachRatio = 0; } // ?????? else { msg = "Failed to get a value."; msgOrg = "Failed to get a value."; if (aberrantMessage != null && !aberrantMessage.equals("")) { msgOrg = msgOrg + "\n\n" + aberrantMessage; } PingResult res = new PingResult(host, msg, msgOrg, -1, -1, -1); ret.put(host, res); m_log.debug("wrapUpFping() : failure msg = " + msg + ", msgOrg = " + msgOrg); msg = ""; msgOrg = ""; } } return ret; } /* (? Javadoc) * ping * @see com.clustercontrol.monitor.run.factory.OperationNumericValueInfo#setMonitorAdditionInfo() */ @Override protected void setCheckInfo() throws MonitorNotFound { // ping? if (!m_isMonitorJob) { m_ping = QueryUtil.getMonitorPingInfoPK(m_monitorId); } else { m_ping = QueryUtil.getMonitorPingInfoPK(m_monitor.getMonitorId()); } // ping if (m_ping.getRunCount() != null) m_runCount = m_ping.getRunCount().intValue(); if (m_ping.getRunInterval() != null) m_runInterval = m_ping.getRunInterval().intValue(); if (m_ping.getTimeout() != null) m_pingTimeout = m_ping.getTimeout().intValue(); } /* (? Javadoc) * ?? * @see com.clustercontrol.monitor.run.factory.RunMonitorNumericValueType#getCheckResult(boolean) */ @Override public int getCheckResult(boolean ret) { // lowerLimit : // upperLimit : int result = -1; MonitorJudgementInfo info = null; // ??? if (ret) { // ? info = m_judgementInfoList.get(Integer.valueOf(PriorityConstant.TYPE_INFO)); if (m_lost < info.getThresholdUpperLimit() && m_average < info.getThresholdLowerLimit()) { result = PriorityConstant.TYPE_INFO; } else { // ?? info = m_judgementInfoList.get(Integer.valueOf(PriorityConstant.TYPE_WARNING)); if (m_lost < info.getThresholdUpperLimit() && m_average < info.getThresholdLowerLimit()) { result = PriorityConstant.TYPE_WARNING; } else { // ? result = PriorityConstant.TYPE_CRITICAL; } } } return result; } /* (? Javadoc) * ? * @see com.clustercontrol.monitor.run.factory.OperationMonitor#getMessage(int) */ @Override public String getMessage(int id) { return m_message; } /* (? Javadoc) * ? * @see com.clustercontrol.monitor.run.factory.OperationMonitor#getMessageOrg(int) */ @Override public String getMessageOrg(int id) { return m_messageOrg; } /** * ping??? * <p> * <ol> * <li>fping?????RunMonitor?runMonitorInfooverride???</li> * <li>????????{@link #setMonitorInfo(String, String)}</li> * <li>?????????{@link #setJudgementInfo()}</li> * <li>??????????{@link #setCheckInfo()}</li> * <li>??????? {@link #collect(String)}</li> * <li>???????? {@link #getCheckResult(boolean)}</li> * <li>?????????{@link #getPriority(int)}</li> * <li>????{@link #notify(boolean, String, int, Date)}</li> * </ol> * * @return ??????</code> true </code> * @throws MonitorNotFound * @throws HinemosUnknown * * @see #setMonitorInfo(String, String) * @see #setJudgementInfo() * @see #setCheckInfo() * @see #collect(String) * @see #getCheckResult(boolean) * @see #getPriority(int) * @see #notify(boolean, String, int, Date) */ @Override protected boolean runMonitorInfo() throws MonitorNotFound, HinemosUnknown { m_now = HinemosTime.getDateInstance(); m_priorityMap = new HashMap<Integer, ArrayList<String>>(); m_priorityMap.put(Integer.valueOf(PriorityConstant.TYPE_INFO), new ArrayList<String>()); m_priorityMap.put(Integer.valueOf(PriorityConstant.TYPE_WARNING), new ArrayList<String>()); m_priorityMap.put(Integer.valueOf(PriorityConstant.TYPE_CRITICAL), new ArrayList<String>()); m_priorityMap.put(Integer.valueOf(PriorityConstant.TYPE_UNKNOWN), new ArrayList<String>()); List<Sample> sampleList = new ArrayList<Sample>(); // boolean run = this.setMonitorInfo(m_monitorTypeId, m_monitorId); if (!run) { // ? return true; } // setJudgementInfo(); // ?? setCheckInfo(); // ID????? ArrayList<String> facilityList = new RepositoryControllerBean().getExecTargetFacilityIdList(m_facilityId, m_monitor.getOwnerRoleId()); if (facilityList.size() == 0) return true; // ?? ArrayList<Integer> priorityList = new ArrayList<Integer>(); // ??? Sample sample = null; if (m_monitor.getCollectorFlg()) { sample = new Sample(HinemosTime.getDateInstance(), m_monitor.getMonitorId()); } //fping?false??ver2.2?????ping? if (!PingProperties.isFpingEnable()) { String facilityId = null; for (int index = 0; index < facilityList.size(); index++) { facilityId = facilityList.get(index); if (facilityId != null && !"".equals(facilityId)) { // ? boolean ret = collect(facilityId); // ?? int checkResult = getCheckResult(ret); // ?? if (m_nodeDate > m_scopeDate) { m_scopeDate = m_nodeDate; } // ?? // ?? if (!m_isMonitorJob) { notify(true, facilityId, checkResult, new Date(m_nodeDate)); } else { m_monitorRunResultInfo = new MonitorRunResultInfo(); MonitorJudgementInfo info = m_judgementInfoList.get(checkResult); if (info != null) { m_monitorRunResultInfo.setPriority(info.getPriority()); } else { m_monitorRunResultInfo.setPriority(m_failurePriority); } m_monitorRunResultInfo.setMessageOrg(makeJobOrgMessage(m_messageOrg, m_message)); m_monitorRunResultInfo.setNodeDate(m_nodeDate); } // ?? if (sample != null) { int errorCode = -1; if (ret) { errorCode = CollectedDataErrorTypeConstant.NOT_ERROR; } else { errorCode = CollectedDataErrorTypeConstant.UNKNOWN; } sample.set(facilityId, m_monitor.getItemName(), m_value, errorCode); } } } } //fping?true????ping? else { // ? // fping?????????ping??? boolean ret = collectFping(facilityList, priorityList); if (ret) { Hashtable<String, PingResult> fpingResultSet = new Hashtable<String, PingResult>(); Hashtable<String, PingResult> fpingResultSetV6 = new Hashtable<String, PingResult>(); //???? if (m_MsgErr != null) { fpingResultSet = wrapUpFping(m_MsgErr, m_runCount, 4); } if (m_MsgErrV6 != null) { m_log.debug("runMonitorInfo(): fpingResultSetV6 check"); fpingResultSetV6 = wrapUpFping(m_MsgErrV6, m_runCount, 6); } //IPv4????????IPv6????? m_log.debug("runMonitorInfo(): before fpingResultSet check"); if (fpingResultSet.size() == 0) { m_log.debug("runMonitorInfo(): after fpingResultSet check"); fpingResultSet = fpingResultSetV6; } //IPv4??????IPv6?? else if (fpingResultSetV6.size() != 0) { fpingResultSet.putAll(fpingResultSetV6); } //?????IP? Iterator<String> it = facilityList.iterator(); String targetFacility; PingResult nodeResult; String[] node; while (it.hasNext()) { //??FacilityId? targetFacility = it.next(); //???IP? node = m_Target.get(targetFacility); // ??????(IP?)?? if (node != null) { m_log.debug("runMonitorInfo(): before fpingResultSet.get()"); nodeResult = fpingResultSet.get(node[0]); if (nodeResult == null) { m_log.debug("runMonitorInfo(): after fpingResultSet.get()"); /* fping??????*/ String[] args = { m_monitorId }; String logMsg = ""; if (m_MsgErr != null) { logMsg = m_MsgErr.toString(); } if (m_MsgErrV6 != null) { logMsg += " , " + m_MsgErrV6.toString(); } AplLogger.put(PriorityConstant.TYPE_CRITICAL, HinemosModuleConstant.MONITOR_PING, MessageConstant.MESSAGE_SYS_001_MON_PNG, args, logMsg); m_log.info("Fping no response."); /* fping??????*/ sample.set(targetFacility, m_monitor.getItemName(), Double.NaN, CollectedDataErrorTypeConstant.UNKNOWN); } else { //?????????? m_lost = nodeResult.getLost(); //?????msec(long)????? m_average = (long) nodeResult.getAverage(); m_message = nodeResult.getMesseage(); m_messageOrg = nodeResult.getMesseageOrg(); m_value = m_average; if (m_log.isDebugEnabled()) { m_log.debug("runMonitorInfo() monitorId = " + m_monitorId + ", facilityId = " + targetFacility + ", average = " + nodeResult.getAverage() + ", value = " + m_value); } // ?? int checkResult; // ?????? if (m_lost == -1) { checkResult = getCheckResult(false); } else { checkResult = getCheckResult(true); } boolean collectorResult = true; if (m_lost == -1 || m_lost == 100) { collectorResult = false; } // ?? if (m_nodeDate > m_scopeDate) { m_scopeDate = m_nodeDate; } // ?? // ?? if (!m_isMonitorJob) { notify(true, targetFacility, checkResult, new Date(m_nodeDate)); } else { m_monitorRunResultInfo = new MonitorRunResultInfo(); m_monitorRunResultInfo.setPriority(checkResult); m_monitorRunResultInfo.setMessageOrg(makeJobOrgMessage(m_messageOrg, m_message)); m_monitorRunResultInfo.setNodeDate(m_nodeDate); } // ?? if (sample != null) { int errorCode = -1; if (collectorResult) { errorCode = CollectedDataErrorTypeConstant.NOT_ERROR; } else { errorCode = CollectedDataErrorTypeConstant.UNKNOWN; } sample.set(targetFacility, m_monitor.getItemName(), (double) nodeResult.getAverage(), errorCode); } } } } } } // ????? if (sample != null) { sampleList.add(sample); } if (!sampleList.isEmpty()) { CollectDataUtil.put(sampleList); } return true; } @Override protected String makeJobOrgMessage(String orgMsg, String msg) { if (m_monitor == null || m_monitor.getPingCheckInfo() == null) { return ""; } String[] args = { String.valueOf(m_monitor.getPingCheckInfo().getRunCount()), String.valueOf(m_monitor.getPingCheckInfo().getRunInterval()), String.valueOf(m_monitor.getPingCheckInfo().getTimeout()) }; return MessageConstant.MESSAGE_JOB_MONITOR_ORGMSG_PING.getMessage(args) + "\n" + orgMsg; } }