001/*
002 *  Copyright 2019 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016
017package org.ametys.runtime.plugins.admin.jvmstatus.monitoring.sample;
018
019import java.io.IOException;
020import java.util.HashMap;
021import java.util.List;
022import java.util.Map;
023
024import org.apache.avalon.framework.service.ServiceException;
025import org.apache.avalon.framework.service.ServiceManager;
026import org.apache.avalon.framework.service.Serviceable;
027import org.rrd4j.DsType;
028import org.rrd4j.core.RrdDef;
029import org.rrd4j.core.Sample;
030
031import org.ametys.core.cache.AbstractCacheManager;
032import org.ametys.core.cache.Cache;
033import org.ametys.runtime.plugins.admin.jvmstatus.monitoring.SampleManager;
034
035/**
036 * {@link SampleManager} for collecting the throughput and the number of active
037 * HTTP requests .
038 */
039public class CacheSampleManager extends AbstractSampleManager implements Serviceable
040{
041
042    private AbstractCacheManager _cacheManager;
043
044    @Override
045    public void service(ServiceManager manager) throws ServiceException
046    {
047        _cacheManager = (AbstractCacheManager) manager.lookup(AbstractCacheManager.ROLE);
048    }
049
050    @Override
051    protected void _configureDatasources(RrdDef rrdDef)
052    {
053        _registerDatasources(rrdDef, "total", DsType.GAUGE, 0, Double.NaN);
054    }
055
056    @Override
057    protected Map<String, Object> _internalCollect(Sample sample) throws IOException
058    {
059        try
060        {
061            long sum = _cacheManager.getAllCaches()
062                    .values()
063                    .stream()
064                    .flatMap(List::stream)
065                    .filter(Cache::isComputableSize)
066                    .mapToLong(Cache::getMemorySize)
067                    .sum();
068            float value = sum / (1024f * 1024f);
069            
070            sample.setValue("total", value);
071            
072            Map<String, Object> result = new HashMap<>();
073            result.put("total", value);
074            return result;
075        }
076        catch (RuntimeException e)
077        {
078            throw new IOException(e);
079        }
080    }
081
082    @Override
083    protected String _getGraphTitle()
084    {
085        return "Cache";
086    }
087}