com.clustercontrol.notify.factory.NotifyDispatcher.java Source code

Java tutorial

Introduction

Here is the source code for com.clustercontrol.notify.factory.NotifyDispatcher.java

Source

/*
    
Copyright (C) 2010 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.notify.factory;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.clustercontrol.bean.PriorityConstant;
import com.clustercontrol.calendar.session.CalendarControllerBean;
import com.clustercontrol.commons.util.HinemosEntityManager;
import com.clustercontrol.commons.util.JpaTransactionManager;
import com.clustercontrol.fault.CalendarNotFound;
import com.clustercontrol.fault.HinemosUnknown;
import com.clustercontrol.fault.InvalidRole;
import com.clustercontrol.fault.NotifyNotFound;
import com.clustercontrol.maintenance.util.HinemosPropertyUtil;
import com.clustercontrol.notify.bean.NotifyRequestMessage;
import com.clustercontrol.notify.bean.NotifyTypeConstant;
import com.clustercontrol.notify.bean.OutputBasicInfo;
import com.clustercontrol.notify.bean.RenotifyTypeConstant;
import com.clustercontrol.notify.entity.MonitorStatusPK;
import com.clustercontrol.notify.model.NotifyHistoryEntity;
import com.clustercontrol.notify.model.NotifyHistoryEntityPK;
import com.clustercontrol.notify.model.NotifyInfo;
import com.clustercontrol.notify.model.NotifyInfoDetail;
import com.clustercontrol.notify.util.MonitorResultStatusUpdater;
import com.clustercontrol.notify.util.NotifyCache;
import com.clustercontrol.notify.util.QueryUtil;
import com.clustercontrol.plugin.impl.AsyncWorkerPlugin;
import com.clustercontrol.util.HinemosTime;
import com.clustercontrol.util.XMLUtil;

/**
 * ID?????
 */
public class NotifyDispatcher {

    /** ? */
    private static Log m_log = LogFactory.getLog(NotifyDispatcher.class);

    public static final String MODE_VERBOSE = "verbose";
    public static final String MODE_NORMAL = "normal";

    private static final String NOTIFY_MODE_KEY = "notify.mode";

    /**
     * ????????<BR>
     * ???????
     *
     * @see com.clustercontrol.notify.ejb.mdb.NotifyEventBean#onMessage(javax.jms.Message)
     * @see com.clustercontrol.notify.ejb.mdb.NotifyStatusBean#onMessage(javax.jms.Message)
     * @see com.clustercontrol.notify.ejb.mdb.NotifyMailBean#onMessage(javax.jms.Message)
     * @see com.clustercontrol.notify.ejb.mdb.NotifyJobBean#onMessage(javax.jms.Message)
     * @see com.clustercontrol.notify.ejb.mdb.NotifyLogEscalationBean#onMessage(javax.jms.Message)
     *
     * @param info 
     * @param notifyIdList ?ID
     * @param queueDeliveryMode JMS?
     * @throws HinemosUnknown 
     */
    public static void notifyAction(OutputBasicInfo info, List<String> notifyIdList, boolean persist)
            throws HinemosUnknown {
        List<OutputBasicInfo> infoList = new ArrayList<OutputBasicInfo>();
        infoList.add(info);
        notifyAction(infoList, notifyIdList, persist);
    }

    /**
     * NotifyDispatcher#notifyAction(List<OutputBasicInfo>, List, boolean)??<BR>
     * NotifyDispatcher#notifyAction(OutputBasicInfo, List, boolean)??<BR>
     * (outputBasicInfoListList????????)<BR>
     * <BR>
     * List<OutputBasicInfo>???OutputBasicInfo?PluginId?MonitorId?????????<BR>
     * 
     * @see NotifyDispatcher#notifyAction(OutputBasicInfo, List, boolean)
     * 
     * @param outputBasicInfoList
     * @param notifyIdList
     * @param persist
     */
    public static void notifyAction(List<OutputBasicInfo> outputBasicInfoList, List<String> notifyIdList,
            boolean persist) throws HinemosUnknown {
        if (notifyIdList == null) {
            return;
        }
        if (outputBasicInfoList.isEmpty()) {
            return;
        }

        //NotifyHistory??
        OutputBasicInfo firstOutputBasicInfo = outputBasicInfoList.get(0);
        List<NotifyHistoryEntity> notifyHistoryEntityList = null;
        if (outputBasicInfoList.size() > 1) {// 
            notifyHistoryEntityList = QueryUtil.getNotifyHistoryByPluginIdAndMonitorId(
                    firstOutputBasicInfo.getPluginId(), firstOutputBasicInfo.getMonitorId());
        } else {// ?????
            notifyHistoryEntityList = QueryUtil.getNotifyHistoryByPluginIdAndMonitorIdAndFacilityId(
                    firstOutputBasicInfo.getPluginId(), firstOutputBasicInfo.getMonitorId(),
                    firstOutputBasicInfo.getFacilityId());
        }
        Map<NotifyHistoryEntityPK, NotifyHistoryEntity> notifyHistoryEntityMap = new ConcurrentHashMap<NotifyHistoryEntityPK, NotifyHistoryEntity>();
        for (NotifyHistoryEntity notifyHistoryEntity : notifyHistoryEntityList) {
            notifyHistoryEntityMap.put(notifyHistoryEntity.getId(), notifyHistoryEntity);
        }

        //??(???????)
        for (OutputBasicInfo info : outputBasicInfoList) {
            String pluginId = info.getPluginId();
            boolean flag = HinemosPropertyUtil.getHinemosPropertyBool("notify.remove.subkey." + pluginId, false);
            if (flag) {
                info.setSubKey("");
            }
        }

        // ???
        String notify_mode = HinemosPropertyUtil.getHinemosPropertyStr(NOTIFY_MODE_KEY, MODE_NORMAL);

        // cc_monitor_status?counter1?
        HashMap<OutputBasicInfo, Boolean> priorityChangeMap = new HashMap<>();
        for (OutputBasicInfo info : outputBasicInfoList) {
            priorityChangeMap.put(info, MonitorResultStatusUpdater.update(info));
        }

        // ???
        for (String notifyId : notifyIdList) {
            NotifyInfo notifyInfo = NotifyCache.getNotifyInfo(notifyId);
            Integer notifyType = notifyInfo.getNotifyType();
            Boolean notifyValid = notifyInfo.getValidFlg();
            if (notifyType == null || notifyValid == null) {
                // ?ID??????????ID???
                m_log.info("notifyAction() : notifyId = " + notifyId + " not found.");
                continue;
            }
            if (!notifyValid.booleanValue()) {
                m_log.debug("notifyAction() : notifyId = " + notifyId + " invalid.");
                continue;
            }

            if (!checkCalendar(notifyInfo.getCalendarId())) {
                m_log.debug("notifyAction() : notifyId = " + notifyId + " calendar is disabled now.");
                continue;
            }

            ArrayList<NotifyRequestMessage> msgList = new ArrayList<NotifyRequestMessage>();
            for (OutputBasicInfo info : outputBasicInfoList) {
                boolean prioityChangeFlag = priorityChangeMap.get(info);
                Timestamp outputDate = new Timestamp(HinemosTime.currentTimeMillis());

                // ????????????
                boolean isNotify = notifyCheck(info.getFacilityId(), info.getPluginId(), info.getMonitorId(),
                        info.getSubKey(), notifyId, info.getPriority(), outputDate, prioityChangeFlag, notify_mode,
                        notifyHistoryEntityMap);

                if (!isNotify) {
                    continue;
                }

                // ?AsyncWorkerPlugin.addTask???
                OutputBasicInfo clonedInfo = info.clone();

                // Ignore Invalid XML Chars
                clonedInfo.setMessage(XMLUtil.ignoreInvalidString(clonedInfo.getMessage()));
                clonedInfo.setMessageOrg(XMLUtil.ignoreInvalidString(clonedInfo.getMessageOrg()));

                // ID?????????????
                NotifyRequestMessage msg = new NotifyRequestMessage(clonedInfo, notifyId, outputDate,
                        prioityChangeFlag);

                msgList.add(msg);
            }

            try {
                addNotifyTask(persist, notifyType, msgList);
            } catch (HinemosUnknown e) {
                m_log.warn(e);
                throw e;
            }
        }
    }

    private static void addNotifyTask(boolean persist, Integer notifyType, ArrayList<NotifyRequestMessage> msgList)
            throws HinemosUnknown {
        //???????
        if (notifyType == NotifyTypeConstant.TYPE_EVENT) {
            AsyncWorkerPlugin.addTask(NotifyEventTaskFactory.class.getSimpleName(), msgList, persist);
            return;
        } else if (notifyType == NotifyTypeConstant.TYPE_STATUS) {
            AsyncWorkerPlugin.addTask(NotifyStatusTaskFactory.class.getSimpleName(), msgList, persist);
            return;
        }

        for (NotifyRequestMessage msg : msgList) {
            switch (notifyType) {
            case NotifyTypeConstant.TYPE_MAIL:
                AsyncWorkerPlugin.addTask(NotifyMailTaskFactory.class.getSimpleName(), msg, persist);
                break;
            case NotifyTypeConstant.TYPE_COMMAND:
                AsyncWorkerPlugin.addTask(NotifyCommandTaskFactory.class.getSimpleName(), msg, persist);
                break;
            case NotifyTypeConstant.TYPE_LOG_ESCALATE:
                AsyncWorkerPlugin.addTask(NotifyLogEscalationTaskFactory.class.getSimpleName(), msg, persist);
                break;
            case NotifyTypeConstant.TYPE_JOB:
                AsyncWorkerPlugin.addTask(NotifyJobTaskFactory.class.getSimpleName(), msg, persist);
                break;
            case NotifyTypeConstant.TYPE_INFRA:
                AsyncWorkerPlugin.addTask(NotifyInfraTaskFactory.class.getSimpleName(), msg, persist);
                break;
            default:
                m_log.warn("notify type is invalid. (notifyType = " + notifyType + ")");
            }
        }
    }

    /**
     * ????????????
     *
     * @param facilityId ID
     * @param pluginId ID
     * @param monitorId ID
     * @param subkey 
     * @param notifyId ID
     * @param priority ??
     * @param outputDate 
     * @param priorityChangeFlag ??
     * @param mode VERBOSE:????????, NORMAL:?????????????????
     * @param notifyHistoryEntityMap
     * @return ??? true
     */
    private static boolean notifyCheck(String facilityId, String pluginId, String monitorId, String subkey,
            String notifyId, int priority, Date outputDate, boolean priorityChangeFlag, String mode,
            Map<NotifyHistoryEntityPK, NotifyHistoryEntity> notifyHistoryEntityMap) {

        JpaTransactionManager jtm = new JpaTransactionManager();
        HinemosEntityManager em = jtm.getEntityManager();

        if (m_log.isDebugEnabled()) {
            m_log.debug("notifyCheck() " + "facilityId=" + facilityId + ", pluginId=" + pluginId + ", monitorId="
                    + monitorId + ", subkey=" + subkey + ", notifyId=" + notifyId + ", priority=" + priority
                    + ", outputDate=" + outputDate + ", priorityChangeFlag=" + priorityChangeFlag + ", mode="
                    + mode);
        }

        MonitorStatusPK mspk = new MonitorStatusPK(facilityId, pluginId, monitorId, subkey);

        // ??ID, ID, ID, ??
        NotifyHistoryEntityPK entityPk = new NotifyHistoryEntityPK(facilityId, pluginId, monitorId, notifyId,
                subkey);
        String pkStr = "facilityId = " + facilityId + ", pluginId  " + pluginId + ", monitorId  " + monitorId
                + ", notifyId  " + notifyId + ", subkey  " + subkey;
        try {
            boolean isNotifyPriority = true;

            if (MODE_VERBOSE.equals(mode)) {
                // ???????
                if (priorityChangeFlag == true) {
                    m_log.debug("priorityChangeFlag == true. remove entity. pk = " + pkStr);

                    // ??
                    try {
                        NotifyHistoryEntity entity = null;
                        try {
                            entity = getNotifyHistoryEntity(entityPk, notifyHistoryEntityMap);
                        } catch (NotifyNotFound e) {
                        }
                        if (entity != null) {
                            em.remove(entity);
                        }
                    } catch (Exception e) {
                        m_log.warn("notifyCheck() : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e);
                    }
                }
            }

            // ???????
            NotifyInfo notifyInfo = NotifyCache.getNotifyInfo(notifyId);
            NotifyInfoDetail notifyDetail = NotifyCache.getNotifyInfoDetail(notifyId);

            // ??????
            if (priority == PriorityConstant.TYPE_INFO) {
                if (!notifyDetail.getInfoValidFlg().booleanValue()) {
                    // ??????
                    m_log.debug("ValidFlg is invalid. " + pkStr + ", priority = " + priority);
                    m_log.debug("notify NG. (VALIDFLAG IS INVALID)." + pkStr);
                    isNotifyPriority = false;
                }
            } else if (priority == PriorityConstant.TYPE_WARNING) {
                if (!notifyDetail.getWarnValidFlg().booleanValue()) {
                    // ??????
                    m_log.debug("ValidFlg is invalid. " + pkStr + ", priority = " + priority);
                    m_log.debug("notify NG. (VALIDFLAG IS INVALID)." + pkStr);
                    isNotifyPriority = false;
                }
            } else if (priority == PriorityConstant.TYPE_CRITICAL) {
                if (!notifyDetail.getCriticalValidFlg().booleanValue()) {
                    // ??????
                    m_log.debug("ValidFlg is invalid. " + pkStr + ", priority = " + priority);
                    m_log.debug("notify NG. (VALIDFLAG IS INVALID)." + pkStr);
                    isNotifyPriority = false;
                }
            } else if (priority == PriorityConstant.TYPE_UNKNOWN) {
                if (!notifyDetail.getUnknownValidFlg().booleanValue()) {
                    // ??????
                    m_log.debug("ValidFlg is invalid. " + pkStr + ", priority = " + priority);
                    m_log.debug("notify NG. (VALIDFLAG IS INVALID)." + pkStr);
                    isNotifyPriority = false;
                }
            } else {
                m_log.info("unknown priority : " + priority);
                return false;
            }

            // ????????????
            // ???????
            Long counter = null;
            try {
                // MonitorStatus?????????????????
                counter = MonitorResultStatusUpdater.getCounter(mspk);
            } catch (NotifyNotFound e) {
                // ?????
                m_log.debug("notify OK. (MONITOR STATUS NOT FOUND)." + pkStr);
                return isNotifyPriority;
            }

            if (counter >= notifyInfo.getInitialCount()) {
                // ???????
                m_log.debug("counter check. " + counter + " >= " + notifyInfo.getInitialCount() + "  " + pkStr);

                try {
                    NotifyHistoryEntity history = null;
                    if (!MODE_VERBOSE.equals(mode)) {
                        history = getNotifyHistoryEntity(entityPk, notifyHistoryEntityMap);
                        // ???????????????
                        if (priority != history.getPriority()) {
                            m_log.debug("update notify history." + pkStr);
                            history.setLastNotify(outputDate.getTime());
                            history.setPriority(priority);
                            m_log.debug("notify OK. (PRIORITY CHANGE)." + pkStr);
                            return isNotifyPriority;
                        }
                    }

                    // ????
                    // ??
                    if (notifyInfo.getRenotifyType() == RenotifyTypeConstant.TYPE_NO_NOTIFY) {
                        // ?????
                        m_log.debug("notify NG. (RENOTIFY NO)." + pkStr);
                        return false;
                    } else if (notifyInfo.getRenotifyType() == RenotifyTypeConstant.TYPE_ALWAYS_NOTIFY) {
                        // ????
                        // history.setLastNotify(new Timestamp(outputDate.getTime())); ?????????
                        // history.setPriority(priority); ?????????
                        m_log.debug("notify OK. (RENOTIFY ALWAYS)." + pkStr);
                        return isNotifyPriority;
                    } else {
                        if (history == null) {
                            history = getNotifyHistoryEntity(entityPk, notifyHistoryEntityMap);
                        }
                        if (outputDate != null && outputDate.getTime() >= (history.getLastNotify()
                                + (notifyInfo.getRenotifyPeriod() * 60 * 1000l))) {
                            m_log.debug("update notify history." + pkStr);
                            // ?????
                            history.setLastNotify(outputDate.getTime());
                            history.setPriority(priority);
                            m_log.debug("notify OK. (RENOTIFY PERIOD)." + pkStr);
                            return isNotifyPriority;
                        } else {
                            m_log.debug("notify NG. (RENOTIFY PERIOD)." + pkStr);
                            return false;
                        }
                    }
                } catch (NotifyNotFound e) {
                    // ??????
                    // ?
                    m_log.debug("first notify. " + pkStr + ", priority = " + priority);

                    // ????
                    NotifyHistoryEntity newHistoryEntity = new NotifyHistoryEntity(facilityId, pluginId, monitorId,
                            notifyId, subkey);
                    newHistoryEntity.setLastNotify(outputDate == null ? null : outputDate.getTime());
                    newHistoryEntity.setPriority(priority);
                    m_log.debug("notify OK. (NEW)." + pkStr);
                    notifyHistoryEntityMap.put(entityPk, newHistoryEntity);

                    if (notifyInfo.getNotFirstNotify().booleanValue()) {
                        // ?????????
                        return false;
                    }
                    return isNotifyPriority;
                }
            } else {
                m_log.debug("notify NG. (PRIORITY CHANGE)." + pkStr);
                return false;
            }
        } catch (Exception e) {
            m_log.warn("notifyCheck() : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e);
        }

        m_log.info("notifyCheck() notify OK. (cause unexpected errors)" + pkStr);
        return true;
    }

    private static NotifyHistoryEntity getNotifyHistoryEntity(NotifyHistoryEntityPK pk,
            Map<NotifyHistoryEntityPK, NotifyHistoryEntity> notifyHistoryEntityMap) throws NotifyNotFound {
        NotifyHistoryEntity entity = notifyHistoryEntityMap.get(pk);
        if (entity == null) {
            throw new NotifyNotFound();
        }
        return entity;
    }

    private static boolean checkCalendar(String calendarId) throws HinemosUnknown {
        long now = HinemosTime.getDateInstance().getTime();

        // ?????
        try {
            CalendarControllerBean calendar = new CalendarControllerBean();
            if (!calendar.isRun(calendarId, now)) {
                // ???????
                m_log.debug("checkCalendar() " + " calenderId = " + calendarId
                        + ". The notice is not executed because of non-operating day.");
                return false;
            }
        } catch (InvalidRole e) {
            // ??ID??????????
            // ?????????
            // ADMINISTRATORS???????????????
            return false;
        } catch (CalendarNotFound e) {
            // ??ID???????????
            return false;
        }

        return true;
    }
}