All Downloads are FREE. Search and download functionalities are using the official Maven repository.

atom.metrics.MetricsContainer Maven / Gradle / Ivy

/*
 * Copyright © 2015 Geeoz, and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * The Research Projects is dual-licensed under the GNU General Public
 * License, version 2.0 (GPLv2) and the Geeoz Commercial License.
 *
 * Solely for non-commercial purposes. A purpose is non-commercial only if
 * it is in no manner primarily intended for or directed toward commercial
 * advantage or private monetary compensation.
 *
 * This Geeoz Software is supplied to you by Geeoz in consideration of your
 * agreement to the following terms, and your use, installation, modification
 * or redistribution of this Geeoz Software constitutes acceptance of these
 * terms. If you do not agree with these terms, please do not use, install,
 * modify or redistribute this Geeoz Software.
 *
 * Neither the name, trademarks, service marks or logos of Geeoz may be used
 * to endorse or promote products derived from the Geeoz Software without
 * specific prior written permission from Geeoz.
 *
 * The Geeoz Software is provided by Geeoz on an "AS IS" basis. GEEOZ MAKES NO
 * WARRANTIES, EXPRESS  OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
 * WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE, REGARDING THE GEEOZ SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
 * COMBINATION WITH YOUR PRODUCTS.
 *
 * IN NO EVENT SHALL GEEOZ BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION
 * AND/OR DISTRIBUTION OF THE GEEOZ SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER
 * THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR
 * OTHERWISE, EVEN IF GEEOZ HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * A copy of the GNU General Public License is included in the distribution in
 * the file LICENSE and at
 *
 *     http://www.gnu.org/licenses/gpl-2.0.html
 *
 * If you are using the Research Projects for commercial purposes, we
 * encourage you to visit
 *
 *     http://products.geeoz.com/license
 *
 * for more details.
 *
 * This software or hardware and documentation may provide access to
 * or information on content, products, and services from third parties.
 * Geeoz and its affiliates are not responsible for and expressly disclaim
 * all warranties of any kind with respect to third-party content, products,
 * and services. Geeoz and its affiliates will not be responsible for any loss,
 * costs, or damages incurred due to your access to or use of third-party
 * content, products, or services. If a third-party content exists, the
 * additional copyright notices and license terms applicable to portions of the
 * software are set forth in the THIRD_PARTY_LICENSE_README file.
 *
 * Please contact Geeoz or visit www.geeoz.com if you need additional
 * information or have any questions.
 */

package atom.metrics;

import atom.app.AuditEvent;
import atom.app.AuditManager;
import atom.content.Context;
import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.CsvReporter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.health.HealthCheckRegistry;
import com.codahale.metrics.jvm.FileDescriptorRatioGauge;
import com.codahale.metrics.jvm.GarbageCollectorMetricSet;
import com.codahale.metrics.jvm.MemoryUsageGaugeSet;
import com.codahale.metrics.jvm.ThreadStatesGaugeSet;

import java.io.File;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

/**
 * Metrics container.
 *
 * @author Eugene Shevchenko
 * @version 1.1 1/1/15
 */
class MetricsContainer {
    /**
     * Audit manager service.
     */
    private static final AuditManager AUDIT =
            Context.getSystemService(AuditManager.class);
    /**
     * Initialization parameter for
     * {@link com.codahale.metrics.ConsoleReporter}.
     * if not set, default value is 1 min.
     */
    private static final String CONSOLE_REPORTER_PERIOD_PARAM =
            System.getProperty("metrics.console.period", "-1");
    /**
     * Value for {@link com.codahale.metrics.ConsoleReporter} in minutes.
     */
    private static final int LOG_REPORTER_PERIOD =
            Integer.parseInt(CONSOLE_REPORTER_PERIOD_PARAM);
    /**
     * Initialization parameter for
     * {@link com.codahale.metrics.CsvReporter}.
     * if not set, default value is 1 min.
     */
    private static final String CSV_REPORTER_PERIOD_PARAM =
            System.getProperty("metrics.csv.period", "-1");
    /**
     * Value for {@link com.codahale.metrics.CsvReporter} in minutes.
     */
    private static final int CSV_REPORTER_PERIOD =
            Integer.parseInt(CSV_REPORTER_PERIOD_PARAM);
    /**
     * A registry of metric instance.
     */
    private final MetricRegistry metrics = new MetricRegistry();
    /**
     * A registry for health checks instance.
     */
    private final HealthCheckRegistry healthChecks = new HealthCheckRegistry();

    /**
     * Report statistic to csv files. A reporter which creates a comma-separated
     * values file of the measurements for each metric.
     */
    private CsvReporter csvReporter;
    /**
     * Report measurements to output like {@code System.out}.
     */
    private ConsoleReporter consoleReporter;

    /**
     * Register a set of gauges for the counts and elapsed times of
     * garbage collections.
     *
     * @return instance of MetricsContainer.
     */
    MetricsContainer registerGarbageCollectorMetric() {
        metrics.register(
                MetricRegistry.name("jvm", "gc"),
                new GarbageCollectorMetricSet());
        return this;
    }

    /**
     * Register a set of gauges for JVM memory usage, including stats on heap
     * vs. non-heap memory, plus GC-specific memory pools.
     *
     * @return instance of MetricsContainer.
     */
    MetricsContainer registerMemoryUsageGauge() {
        metrics.register(
                MetricRegistry.name("jvm", "memory"),
                new MemoryUsageGaugeSet());
        return this;
    }

    /**
     * Register a set of gauges for the number of threads in their various
     * states and deadlock detection.
     *
     * @return instance of MetricsContainer.
     */
    MetricsContainer registerThreadStatesGauge() {
        metrics.register(
                MetricRegistry.name("jvm", "thread-states"),
                new ThreadStatesGaugeSet());
        return this;
    }

    /**
     * Register a gauge for the ratio of used to total file descriptors.
     *
     * @return instance of MetricsContainer.
     */
    MetricsContainer registerFileDescriptorRatioGauge() {
        metrics.register(
                MetricRegistry.name("jvm", "fd", "usage"),
                new FileDescriptorRatioGauge());
        return this;
    }

    /**
     * Initialize {@link CsvReporter} and launch it.
     *
     * @param folderPath path to the folder where will be stored csv files.
     * @return instance of MetricsContainer.
     */
    MetricsContainer withCsvReporter(final String folderPath) {
        return withCsvReporter(folderPath, CSV_REPORTER_PERIOD);
    }

    /**
     * Initialize {@link CsvReporter} and launch it.
     *
     * @param folderPath path to the folder where will be stored csv files.
     * @param period     the amount of time(in minutes) between polls.
     * @return instance of MetricsContainer.
     */
    MetricsContainer withCsvReporter(
            final String folderPath, final int period) {
        if (period < 0) {
            AUDIT.log(AuditEvent.create(
                    this,
                    this.getClass().getName(),
                    AuditEvent.WARNING,
                    "CSV reporter period parameter hasn't been configured!"));
        } else if (csvReporter == null) {
            final File folder = new File(folderPath);
            if (!folder.exists()) {
                if (!folder.mkdirs()) {
                    return this;
                }
            } else if (!folder.isDirectory()) {
                return this;
            }
            csvReporter = CsvReporter.forRegistry(metrics)
                    .formatFor(Locale.ENGLISH)
                    .convertRatesTo(TimeUnit.SECONDS)
                    .convertDurationsTo(TimeUnit.MILLISECONDS)
                    .build(folder);
            csvReporter.start(period, TimeUnit.MINUTES);
        }
        return this;
    }

    /**
     * Initialize {@link ConsoleReporter} and launch it.
     *
     * @return instance of MetricsContainer.
     */
    MetricsContainer withConsoleReporter() {
        return withConsoleReporter(LOG_REPORTER_PERIOD);
    }

    /**
     * Initialize {@link ConsoleReporter} and launch it.
     *
     * @param period the amount of time(in minutes) between polls.
     * @return instance of MetricsContainer.
     */
    MetricsContainer withConsoleReporter(final int period) {
        if (period < 0) {
            AUDIT.log(AuditEvent.create(
                 this,
                 this.getClass().getName(),
                 AuditEvent.WARNING,
                 "Console reporter period parameter hasn't been configured!"));
        } else if (consoleReporter == null) {
            consoleReporter = ConsoleReporter.forRegistry(metrics)
                    .convertRatesTo(TimeUnit.SECONDS)
                    .convertDurationsTo(TimeUnit.MILLISECONDS)
                    .build();
            consoleReporter.start(period, TimeUnit.MINUTES);
        }
        return this;
    }

    /**
     * Get registry of metric instance.
     *
     * @return a registry of metric instance.
     */
    MetricRegistry getMetricsRegistryInstance() {
        return metrics;
    }

    /**
     * Get registry for health checks instance.
     *
     * @return a registry for health checks instance.
     */
    HealthCheckRegistry getHealthCheckRegistryInstance() {
        return healthChecks;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy