⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cmsmemorymonitor.java

📁 找了很久才找到到源代码
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
    }

    /**
     * Returns the total size of key strings within a monitored map.<p>
     * 
     * the keys must be of type String.<p>
     * 
     * @param map the map
     * @param depth the max recursion depth for calculation the size
     * @return total size of key strings
     */
    private long getKeySize(Map map, int depth) {

        long keySize = 0;
        try {
            Object[] values = map.values().toArray();
            for (int i = 0, s = values.length; i < s; i++) {

                Object obj = values[i];

                if ((obj instanceof Map) && (depth < MAX_DEPTH)) {
                    keySize += getKeySize((Map)obj, depth + 1);
                    continue;
                }
            }
            values = null;

            Object[] keys = map.keySet().toArray();
            for (int i = 0, s = keys.length; i < s; i++) {

                Object obj = keys[i];

                if (obj instanceof String) {
                    String st = (String)obj;
                    keySize += (st.length() * 2);
                }
            }
        } catch (ConcurrentModificationException e) {
            // this might happen since even the .toArray() method internally creates an iterator
        } catch (Throwable t) {
            // catch all other exceptions otherwise the whole monitor will stop working
            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_CAUGHT_THROWABLE_1, t.getMessage()));
            }
        }

        return keySize;
    }

    /**
     * Returns the total size of key strings within a monitored object.<p>
     * 
     * obj must be of type {@link Map}, the keys must be of type {@link String}.<p>
     * 
     * @param obj the object
     * 
     * @return the total size of key strings
     */
    private long getKeySize(Object obj) {

        if (obj instanceof Map) {
            return getKeySize((Map)obj, 1);
        }

        return 0;
    }

    /**
     * Returns the max costs for all items within a monitored object.<p>
     * 
     * obj must be of type {@link CmsLruCache} or {@link LRUMap}.<p>
     * 
     * @param obj the object
     * 
     * @return max cost limit or "-"
     */
    private String getLimit(Object obj) {

        if (obj instanceof CmsLruCache) {
            return Integer.toString(((CmsLruCache)obj).getMaxCacheCosts());
        }
        if (obj instanceof LRUMap) {
            return Integer.toString(((LRUMap)obj).maxSize());
        }

        return "-";
    }

    /**
     * Returns the total value size of a list object.<p>
     * 
     * @param listValue the list object
     * @param depth the max recursion depth for calculation the size
     * 
     * @return the size of the list object
     */
    private long getValueSize(List listValue, int depth) {

        long totalSize = 0;
        try {
            Object[] values = listValue.toArray();
            for (int i = 0, s = values.length; i < s; i++) {

                Object obj = values[i];

                if (obj instanceof CmsAccessControlList) {
                    obj = ((CmsAccessControlList)obj).getPermissionMap();
                }

                if (obj instanceof CmsFlexCacheVariation) {
                    obj = ((CmsFlexCacheVariation)obj).m_map;
                }

                if ((obj instanceof Map) && (depth < MAX_DEPTH)) {
                    totalSize += getValueSize((Map)obj, depth + 1);
                    continue;
                }

                if ((obj instanceof List) && (depth < MAX_DEPTH)) {
                    totalSize += getValueSize((List)obj, depth + 1);
                    continue;
                }

                totalSize += getMemorySize(obj);
            }
        } catch (ConcurrentModificationException e) {
            // this might happen since even the .toArray() method internally creates an iterator
        } catch (Throwable t) {
            // catch all other exceptions otherwise the whole monitor will stop working
            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_CAUGHT_THROWABLE_1, t.getMessage()));
            }
        }

        return totalSize;
    }

    /**
     * Returns the total value size of a map object.<p>
     * 
     * @param mapValue the map object
     * @param depth the max recursion depth for calculation the size
     * 
     * @return the size of the map object
     */
    private long getValueSize(Map mapValue, int depth) {

        long totalSize = 0;
        try {
            Object[] values = mapValue.values().toArray();
            for (int i = 0, s = values.length; i < s; i++) {

                Object obj = values[i];

                if (obj instanceof CmsAccessControlList) {
                    obj = ((CmsAccessControlList)obj).getPermissionMap();
                }

                if (obj instanceof CmsFlexCacheVariation) {
                    obj = ((CmsFlexCacheVariation)obj).m_map;
                }

                if ((obj instanceof Map) && (depth < MAX_DEPTH)) {
                    totalSize += getValueSize((Map)obj, depth + 1);
                    continue;
                }

                if ((obj instanceof List) && (depth < MAX_DEPTH)) {
                    totalSize += getValueSize((List)obj, depth + 1);
                    continue;
                }

                totalSize += getMemorySize(obj);
            }
        } catch (ConcurrentModificationException e) {
            // this might happen since even the .toArray() method internally creates an iterator
        } catch (Throwable t) {
            // catch all other exceptions otherwise the whole monitor will stop working
            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_CAUGHT_THROWABLE_1, t.getMessage()));
            }
        }

        return totalSize;
    }

    /**
     * Returns the value sizes of value objects within the monitored object.<p>
     * 
     * @param obj the object 
     * 
     * @return the value sizes of value objects or "-"-fields
     */
    private long getValueSize(Object obj) {

        if (obj instanceof CmsLruCache) {
            return ((CmsLruCache)obj).size();
        }

        if (obj instanceof Map) {
            return getValueSize((Map)obj, 1);
        }

        if (obj instanceof List) {
            return getValueSize((List)obj, 1);
        }

        try {
            return getMemorySize(obj);
        } catch (Exception exc) {
            return 0;
        }
    }

    /**
     * Sends a warning or status email with OpenCms Memory information.<p>
     * 
     * @param warning if true, send a memory warning email 
     */
    private void monitorSendEmail(boolean warning) {

        if ((m_configuration.getEmailSender() == null) || (m_configuration.getEmailReceiver() == null)) {
            // send no mails if not fully configured
            return;
        } else if (warning
            && (m_warningSendSinceLastStatus && !((m_intervalEmail <= 0) && (System.currentTimeMillis() < (m_lastEmailWarning + m_intervalWarning))))) {
            // send no warning email if no status email has been send since the last warning
            // if status is disabled, send no warn email if warn interval has not passed
            return;
        } else if ((!warning) && (m_intervalEmail <= 0)) {
            // if email iterval is <= 0 status email is disabled
            return;
        }
        String date = CmsDateUtil.getDateTimeShort(System.currentTimeMillis());
        String subject;
        String content = "";
        if (warning) {
            m_warningSendSinceLastStatus = true;
            m_lastEmailWarning = System.currentTimeMillis();
            subject = "OpenCms Memory W A R N I N G ["
                + OpenCms.getSystemInfo().getServerName().toUpperCase()
                + "/"
                + date
                + "]";
            content += "W A R N I N G !\nOpenCms memory consumption on server "
                + OpenCms.getSystemInfo().getServerName().toUpperCase()
                + " has reached a critical level !\n\n"
                + "The configured limit is "
                + m_maxUsagePercent
                + "%\n\n";
        } else {
            m_warningSendSinceLastStatus = false;
            m_lastEmailStatus = System.currentTimeMillis();
            subject = "OpenCms Memory Status ["
                + OpenCms.getSystemInfo().getServerName().toUpperCase()
                + "/"
                + date
                + "]";
        }

        content += "Memory usage report of OpenCms server "
            + OpenCms.getSystemInfo().getServerName().toUpperCase()
            + " at "
            + date
            + "\n\n"
            + "Memory maximum heap size: "
            + m_memoryCurrent.getMaxMemory()
            + " mb\n"
            + "Memory current heap size: "
            + m_memoryCurrent.getTotalMemory()
            + " mb\n\n"
            + "Memory currently used   : "
            + m_memoryCurrent.getUsedMemory()
            + " mb ("
            + m_memoryCurrent.getUsage()
            + "%)\n"
            + "Memory currently unused : "
            + m_memoryCurrent.getFreeMemory()
            + " mb\n\n\n";

        if (warning) {
            content += "*** Please take action NOW to ensure that no OutOfMemoryException occurs.\n\n\n";
        }

        CmsSessionManager sm = OpenCms.getSessionManager();

        if (sm != null) {
            content += "Current status of the sessions:\n\n";
            content += "Logged in users          : " + sm.getSessionCountAuthenticated() + "\n";
            content += "Currently active sessions: " + sm.getSessionCountCurrent() + "\n";
            content += "Total created sessions   : " + sm.getSessionCountTotal() + "\n\n\n";
        }

        sm = null;

        content += "Current status of the caches:\n\n";
        List keyList = Arrays.asList(m_monitoredObjects.keySet().toArray());
        Collections.sort(keyList);
        long totalSize = 0;
        for (Iterator keys = keyList.iterator(); keys.hasNext();) {
            String key = (String)keys.next();
            String[] shortKeys = key.split("\\.");
            String shortKey = shortKeys[shortKeys.length - 2] + '.' + shortKeys[shortKeys.length - 1];
            PrintfFormat form = new PrintfFormat("%9s");
            Object obj = m_monitoredObjects.get(key);

            long size = getKeySize(obj) + getValueSize(obj) + getCosts(obj);
            totalSize += size;

            content += new PrintfFormat("%-42.42s").sprintf(shortKey)
                + "  "
                + "Entries: "
                + form.sprintf(getItems(obj))
                + "   "
                + "Limit: "
                + form.sprintf(getLimit(obj))
                + "   "
                + "Size: "
                + form.sprintf(Long.toString(size))
                + "\n";
        }
        content += "\nTotal size of cache memory monitored: " + totalSize + " (" + totalSize / 1048576 + ")\n\n";

        String from = m_configuration.getEmailSender();
        List receivers = new ArrayList();
        List receiverEmails = m_configuration.getEmailReceiver();
        try {
            if ((from != null) && (receiverEmails != null) && !receiverEmails.isEmpty()) {
                Iterator i = receiverEmails.iterator();
                while (i.hasNext()) {
                    receivers.add(new InternetAddress((String)i.next()));
                }
                CmsSimpleMail email = new CmsSimpleMail();
                email.setFrom(from);
                email.setTo(receivers);
                email.setSubject(subject);
                email.setMsg(content);
                new CmsMailTransport(email).send();
            }
            if (LOG.isInfoEnabled()) {
                if (warning) {
                    LOG.info(Messages.get().getBundle().key(Messages.LOG_MM_WARNING_EMAIL_SENT_0));
                } else {
                    LOG.info(Messages.get().getBundle().key(Messages.LOG_MM_STATUS_EMAIL_SENT_0));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Write a warning or status log entry with OpenCms Memory information.<p>
     * 
     * @param warning if true, write a memory warning log entry 
     */
    private void monitorWriteLog(boolean warning) {

        if (!LOG.isWarnEnabled()) {
            // we need at last warn level for this output
            return;
        } else if ((!warning) && (!LOG.isInfoEnabled())) {
            // if not warning we need info level
            return;
        } else if (warning
            && (m_warningLoggedSinceLastStatus && !(((m_intervalLog <= 0) && (System.currentTimeMillis() < (m_lastLogWarning + m_intervalWarning)))))) {
            // write no warning log if no status log has been written since the last warning
            // if status is disabled, log no warn entry if warn interval has not passed
            return;
        } else if ((!warning) && (m_intervalLog <= 0)) {
            // if log iterval is <= 0 status log is disabled
            return;
        }

        if (warning) {
            m_lastLogWarning = System.currentTimeMillis();
            m_warningLoggedSinceLastStatus = true;
            LOG.warn(Messages.get().getBundle().key(
                Messages.LOG_MM_WARNING_MEM_CONSUME_2,
                new Long(m_memoryCurrent.getUsage()),
                new Integer(m_maxUsagePercent)));
        } else {
            m_warningLoggedSinceLastStatus = false;
            m_lastLogStatus = System.currentTimeMillis();
        }

        if (warning) {
            LOG.warn(Messages.get().getBundle().key(
                Messages.LOG_MM_WARNING_MEM_STATUS_6,
                new Object[] {
                    new Long(m_memoryCurrent.getMaxMemory()),
                    new Long(m_memoryCurrent.getTotalMemory()),
                    new Long(m_memoryCurrent.getFreeMemory()),
                    new Long(m_memoryCurrent.getUsedMemory()),
                    new Long(m_memoryCurrent.getUsage()),
                    new Integer(m_maxUsagePercent)}));
        } else {
            m_logCount++;
            LOG.info(Messages.get().getBundle().key(
                Messages.LOG_MM_LOG_INFO_2,
                OpenCms.getSystemInfo().getServerName().toUpperCase(),
                String.valueOf(m_logCount)));

            List keyList = Arrays.asList(m_monitoredObjects.keySet().toArray());
            Collections.sort(keyList);
            long totalSize = 0;
            for (Iterator keys = keyList.iterator(); keys.hasNext();) {

                String key = (String)keys.next()

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -