001/* 002 * Licensed to DuraSpace under one or more contributor license agreements. 003 * See the NOTICE file distributed with this work for additional information 004 * regarding copyright ownership. 005 * 006 * DuraSpace licenses this file to you under the Apache License, 007 * Version 2.0 (the "License"); you may not use this file except in 008 * compliance with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.fcrepo.http.commons.metrics; 019 020import io.prometheus.client.CollectorRegistry; 021import io.prometheus.client.exporter.MetricsServlet; 022import org.springframework.web.context.support.WebApplicationContextUtils; 023 024import javax.servlet.ServletConfig; 025import javax.servlet.ServletException; 026 027/** 028 * This class is an extension of Prometheus's MetricsServlet. It only exists because there isn't an easy way to 029 * set the CollectorRegistry on with a Spring bean. 030 * 031 * @author pwinckles 032 */ 033public class PrometheusMetricsServlet extends MetricsServlet { 034 035 @Override 036 public void init(final ServletConfig config) throws ServletException { 037 final var context = WebApplicationContextUtils 038 .getRequiredWebApplicationContext(config.getServletContext()); 039 final var collector = context.getBean(CollectorRegistry.class); 040 041 try { 042 final var field = MetricsServlet.class.getDeclaredField("registry"); 043 field.setAccessible(true); 044 field.set(this, collector); 045 } catch (final NoSuchFieldException | IllegalAccessException e) { 046 throw new ServletException(e); 047 } 048 049 super.init(config); 050 } 051 052}