001/*
002 * (C) Copyright 2013 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *      Delbosc Benoit
016 */
017package org.nuxeo.runtime.metrics;
018
019import org.apache.commons.logging.Log;
020import org.apache.commons.logging.LogFactory;
021import org.nuxeo.runtime.model.ComponentContext;
022import org.nuxeo.runtime.model.ComponentInstance;
023import org.nuxeo.runtime.model.DefaultComponent;
024
025import com.codahale.metrics.Counter;
026import com.codahale.metrics.MetricRegistry;
027import com.codahale.metrics.SharedMetricRegistries;
028
029public class MetricsServiceImpl extends DefaultComponent implements MetricsService {
030
031    protected static final Log log = LogFactory.getLog(MetricsServiceImpl.class);
032
033    protected MetricRegistry registry = SharedMetricRegistries.getOrCreate(MetricsService.class.getName());
034
035    private final Counter instanceUp = registry.counter(MetricRegistry.name("nuxeo", "instance-up"));
036
037    protected static final String CONFIGURATION_EP = "configuration";
038
039    public static MetricsDescriptor config;
040
041    public MetricsServiceImpl() {
042        super();
043    }
044
045    @Override
046    public void registerContribution(Object contribution, String extensionPoint, ComponentInstance contributor) {
047        if (CONFIGURATION_EP.equals(extensionPoint) && contribution instanceof MetricsDescriptor) {
048            log.debug("Registering metrics contribution");
049            config = (MetricsDescriptor) contribution;
050        } else {
051            log.warn("Unknown EP " + extensionPoint);
052        }
053    }
054
055    @Override
056    public void deactivate(ComponentContext context) {
057        try {
058            config.disable(registry);
059        } finally {
060            instanceUp.dec();
061        }
062        log.debug("Deactivate component.");
063    }
064
065    @Override
066    public void applicationStarted(ComponentContext context) {
067        if (config == null) {
068            // Use a default config
069            config = new MetricsDescriptor();
070        }
071        log.info("Setting up metrics configuration");
072        config.enable(registry);
073        instanceUp.inc();
074    }
075
076}