001/*
002 * The contents of this file are subject to the license and copyright
003 * detailed in the LICENSE and NOTICE files at the root of the source
004 * tree.
005 */
006package org.fcrepo.http.commons.metrics;
007
008import io.prometheus.client.CollectorRegistry;
009import io.prometheus.client.exporter.MetricsServlet;
010import org.springframework.web.context.support.WebApplicationContextUtils;
011
012import javax.servlet.ServletConfig;
013import javax.servlet.ServletException;
014
015/**
016 * This class is an extension of Prometheus's MetricsServlet. It only exists because there isn't an easy way to
017 * set the CollectorRegistry on with a Spring bean.
018 *
019 * @author pwinckles
020 */
021public class PrometheusMetricsServlet extends MetricsServlet {
022
023    @Override
024    public void init(final ServletConfig config) throws ServletException {
025        final var context = WebApplicationContextUtils
026                .getRequiredWebApplicationContext(config.getServletContext());
027        final var collector = context.getBean(CollectorRegistry.class);
028
029        try {
030            final var field = MetricsServlet.class.getDeclaredField("registry");
031            field.setAccessible(true);
032            field.set(this, collector);
033        } catch (final NoSuchFieldException | IllegalAccessException e) {
034            throw new ServletException(e);
035        }
036
037        super.init(config);
038    }
039
040}