001/*
002 * (C) Copyright 2020 Nuxeo (http://nuxeo.com/) and others.
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 * Contributors:
017 *     bdelbosc
018 */
019package org.nuxeo.runtime.metrics.reporter;
020
021import java.io.IOException;
022import java.util.Set;
023
024import org.apache.logging.log4j.LogManager;
025import org.apache.logging.log4j.Logger;
026import org.nuxeo.runtime.metrics.AbstractMetricsReporter;
027
028import io.dropwizard.metrics5.MetricAttribute;
029import io.dropwizard.metrics5.MetricFilter;
030import io.dropwizard.metrics5.MetricRegistry;
031import io.opencensus.contrib.zpages.ZPageHandlers;
032
033/**
034 * Expose zPages endpoint to control tracing.
035 *
036 * @since 11.1
037 */
038public class ZPageReporter extends AbstractMetricsReporter {
039
040    private static final Logger log = LogManager.getLogger(ZPageReporter.class);
041
042    public static final String PORT = "port";
043
044    public static final String DEFAULT_PORT = "8887";
045
046    protected boolean activated;
047
048    @Override
049    public void start(MetricRegistry registry, MetricFilter filter, Set<MetricAttribute> deniedExpansions) {
050        if (activated) {
051            log.debug("Already activated");
052            return;
053        }
054        int port = Integer.parseInt(options.getOrDefault(PORT, DEFAULT_PORT));
055        log.warn("Creating ZPage reporter on port: {}", port);
056        try {
057            ZPageHandlers.startHttpServerAndRegisterAll(port);
058        } catch (IOException e) {
059            throw new IllegalArgumentException("Cannot start ZPage server on port: " + port, e);
060        }
061        activated = true;
062    }
063
064    @Override
065    public void stop() {
066        log.debug("Stop reporting");
067        // there is no way to stop ZPage not a big deal
068    }
069}