com.clustercontrol.agent.log.LogfileMonitorManager.java Source code

Java tutorial

Introduction

Here is the source code for com.clustercontrol.agent.log.LogfileMonitorManager.java

Source

/*
    
 Copyright (C) 2011 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.agent.log;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

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

import com.clustercontrol.agent.Agent;
import com.clustercontrol.agent.SendQueue;
import com.clustercontrol.agent.log.ReadingStatusRoot.ReadingStatus;
import com.clustercontrol.agent.log.ReadingStatusRoot.ReadingStatusDir;
import com.clustercontrol.agent.util.AgentProperties;
import com.clustercontrol.bean.HinemosModuleConstant;
import com.clustercontrol.util.HinemosTime;
import com.clustercontrol.ws.agent.OutputBasicInfo;
import com.clustercontrol.ws.jobmanagement.RunInstructionInfo;
import com.clustercontrol.ws.monitor.LogfileCheckInfo;
import com.clustercontrol.ws.monitor.MonitorInfo;

/**
 * ???<BR>
 * 
 * ?????????
 * 
 */
public class LogfileMonitorManager {
    private static Log log = LogFactory.getLog(LogfileMonitorManager.class);

    /** ????????? */
    private static Map<String, LogfileMonitor> logfileMonitorCache = new HashMap<String, LogfileMonitor>();

    //   // 
    //   private static Map<RunInstructionInfo, MonitorInfo> monitorMapForMonitorJob
    //      = new HashMap<RunInstructionInfo, MonitorInfo>();

    /** Queue?  */
    private static SendQueue sendQueue;

    /**  */
    private static int runInterval = 10000; // 10sec

    //   /** ??? */
    //   private static List<MonitorInfo> monitorList;

    /** ?? */
    private static ReadingStatusRoot statusRoot;

    private static LogfileThread thread;

    private static List<MonitorInfoWrapper> monitorList;

    /**
     * 
     * 
     * @param ejbConnectionManager EJB??
     * @param sendQueue ?Queue?
     * @param props ?
     */
    public static void setSendQueue(SendQueue sendQueue) {
        LogfileMonitorManager.sendQueue = sendQueue;
    }

    static {
        String key1 = "monitor.logfile.filter.interval";
        try {
            String runIntervalStr = AgentProperties.getProperty(key1, Integer.toString(runInterval));
            runInterval = Integer.parseInt(runIntervalStr);
        } catch (Exception e) {
            log.warn("LogfileThread : " + e.getMessage());
        }
        log.info(key1 + "=" + runInterval);
    }

    /**
     * ??????<BR>
     * 
     * @param list ?
     */
    public static synchronized void pushMonitorInfoList(List<MonitorInfo> monitorList,
            Map<RunInstructionInfo, MonitorInfo> monitorMap) {
        List<MonitorInfoWrapper> wrapperList = new ArrayList<>();

        String fileName = "";
        for (MonitorInfo info : monitorList) {
            LogfileCheckInfo check = info.getLogfileCheckInfo();
            fileName += "[" + check.getDirectory() + "," + check.getFileName() + "]";

            wrapperList.add(new MonitorInfoWrapper(info, null));

            // ??
            File directory = new File(check.getDirectory());
            log.debug("setLogfileMonitor() : directoryExistsMap put monitorId = " + check.getMonitorId()
                    + ", directoryStr = " + check.getDirectory() + ", exists = " + directory.isDirectory());
        }
        log.info("setLogfileMonitor() : m_monitorList=" + fileName);

        for (Map.Entry<RunInstructionInfo, MonitorInfo> entry : monitorMap.entrySet()) {
            LogfileCheckInfo check = entry.getValue().getLogfileCheckInfo();
            fileName += "[" + check.getDirectory() + "," + check.getFileName() + "]";

            wrapperList.add(new MonitorInfoWrapper(entry.getValue(), entry.getKey()));

            // ??
            File directory = new File(check.getDirectory());
            log.debug(
                    "setMonitorInfoListForMonitorJob() : directoryExistsMap put monitorId = " + check.getMonitorId()
                            + ", directoryStr = " + check.getDirectory() + ", exists = " + directory.isDirectory());

        }
        log.info("setLogfileMonitor() : m_monitorList=" + fileName);
        LogfileMonitorManager.monitorList = wrapperList;
    }

    /**
     * ????<BR>
     */
    private static synchronized List<MonitorInfoWrapper> popMonitorInfoList() {
        List<MonitorInfoWrapper> list = LogfileMonitorManager.monitorList;
        LogfileMonitorManager.monitorList = null;
        return list;
    }

    private static void refresh() {
        synchronized (LogfileMonitorManager.class) {
            log.debug("refresh() : start");

            List<MonitorInfoWrapper> monitorList = popMonitorInfoList();

            // ???????????????
            if (monitorList != null) {
                log.debug("refresh() : m_monitorList.size=" + monitorList.size());

                // ????
                if (statusRoot == null) {
                    statusRoot = new ReadingStatusRoot(monitorList, getReadingStatesStorePath());
                    log.debug("refresh() : ReadingStatusRoot is initialized.");
                } else {
                    statusRoot.update(monitorList);
                    log.debug("refresh() : ReadingStatusRoot is updated.");
                }
            } else {
                // ???
                if (statusRoot != null)
                    statusRoot.update();
            }

            if (statusRoot == null) {
                log.debug("refresh() : ReadingStatusRoot is not initialized.");
                return;
            }

            log.debug("refresh() : monitoring files.");

            Set<String> newLogfileMonitorCacheKeySet = new HashSet<String>();
            for (ReadingStatusDir miDir : statusRoot.getReadingStatusDirList()) {
                MonitorInfoWrapper wrapper = miDir.getMonitorInfo();

                String monitorId = wrapper.monitorInfo.getMonitorId();
                String directoryPath = wrapper.monitorInfo.getLogfileCheckInfo().getDirectory();
                String fileNamePattern = wrapper.monitorInfo.getLogfileCheckInfo().getFileName();
                String fileEncoding = wrapper.monitorInfo.getLogfileCheckInfo().getFileEncoding();
                String fileReturnCode = wrapper.monitorInfo.getLogfileCheckInfo().getFileReturnCode();
                log.debug("refresh() : monitorId=" + monitorId + ", directory=" + directoryPath
                        + ", filenamePattern=" + fileNamePattern + ", fileEncoding=" + fileEncoding
                        + ", fileReturnCode=" + fileReturnCode);

                for (ReadingStatus status : miDir.list()) {
                    log.debug("refresh() : filePath=" + status.filePath.getPath());

                    String cacheKey = monitorId + status.rsFilePath.getPath();
                    LogfileMonitor logfileMonitor = logfileMonitorCache.get(cacheKey);
                    if (logfileMonitor == null) {
                        // ?
                        logfileMonitor = new LogfileMonitor(wrapper, status);
                        logfileMonitorCache.put(cacheKey, logfileMonitor);
                        log.debug("refresh() : LogfileMonitor is created.");
                    } else {
                        log.debug("refresh() : LogfileMonitor is being cached.");
                    }

                    logfileMonitor.setMonitor(wrapper);

                    newLogfileMonitorCacheKeySet.add(cacheKey);
                }
            }

            /*
             * ?????logfileMonitor????
             */
            Iterator<Entry<String, LogfileMonitor>> it = logfileMonitorCache.entrySet().iterator();
            while (it.hasNext()) {
                Entry<String, LogfileMonitor> entry = it.next();
                if (!newLogfileMonitorCacheKeySet.contains(entry.getKey())) {
                    entry.getValue().clean();
                    it.remove();
                }
            }
        }
    }

    public static synchronized void start() {
        if (thread != null) {
            log.info("start() : LogfileThread is already started.");
            return;
        }

        thread = new LogfileThread();
        thread.setName("LogFileMonitor");
        thread.start();

        log.info("start() : LogfileThread is started.");
    }

    public static synchronized void terminate() {
        if (thread == null) {
            log.info("terminate() : LogfileThread is not started.");
            return;
        }

        thread.terminate();
        thread = null;

        log.info("terminate() : LogfileThread is terminated.");
    }

    private static class LogfileThread extends Thread {

        private boolean loop = true;

        @Override
        public void run() {
            log.info("run LogfileThread");
            while (loop) {
                synchronized (LogfileMonitorManager.class) {
                    try {
                        refresh();
                        for (String filePath : logfileMonitorCache.keySet()) {
                            LogfileMonitor logfileMonitor = logfileMonitorCache.get(filePath);
                            logfileMonitor.run();
                        }
                    } catch (Exception e) {
                        log.warn("LogfileThread : " + e.getClass().getCanonicalName() + ", " + e.getMessage(), e);
                    } catch (Throwable e) {
                        log.error("LogfileThread : " + e.getClass().getCanonicalName() + ", " + e.getMessage(), e);
                    }
                }

                try {
                    Thread.sleep(runInterval);
                } catch (InterruptedException e) {
                    log.info("LogfileThread is Interrupted");
                    break;
                }
            }
            log.info("terminate LogfileThread");
        }

        public void terminate() {
            loop = false;
        }
    }

    /**
     * ??JMS????<BR>
     * 
     * @param priority ??
     * @param app 
     * @param msg 
     * @param msgOrg 
     */
    public static void sendMessage(String filePath, int priority, String app, String msg, String msgOrg,
            String monitorId, RunInstructionInfo runInstructionInfo) {
        // 
        OutputBasicInfo output = new OutputBasicInfo();
        output.setPluginId(HinemosModuleConstant.MONITOR_LOGFILE);
        output.setPriority(priority);
        output.setApplication(app);
        output.setMessage(msg);
        output.setMessageOrg(msgOrg);

        output.setGenerationDate(HinemosTime.getDateInstance().getTime());
        output.setMonitorId(monitorId);
        output.setFacilityId(""); // ???
        output.setScopeText(""); // ???
        output.setRunInstructionInfo(runInstructionInfo);

        sendQueue.put(output);
    }

    protected static int getRunInterval() {
        return runInterval;
    }

    public static String getReadingStatesStorePath() {
        String home = Agent.getAgentHome();
        String storepath = new File(new File(home), "readingstatus").getAbsolutePath();
        return storepath;
    }
}