|
| 1 | +// Copyright (c) 2021-2022 VMware, Inc. or its affiliates. All rights reserved. |
| 2 | +// |
| 3 | +// This software, the RabbitMQ Stream Java client library, is dual-licensed under the |
| 4 | +// Mozilla Public License 2.0 ("MPL"), and the Apache License version 2 ("ASL"). |
| 5 | +// For the MPL, please see LICENSE-MPL-RabbitMQ. For the ASL, |
| 6 | +// please see LICENSE-APACHE2. |
| 7 | +// |
| 8 | +// This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, |
| 9 | +// either express or implied. See the LICENSE file for specific language governing |
| 10 | +// rights and limitations of this software. |
| 11 | +// |
| 12 | +// If you have any questions regarding licensing, please contact us at |
| 13 | + |
| 14 | +package com.rabbitmq.stream.perf; |
| 15 | + |
| 16 | +import com.sun.net.httpserver.HttpHandler; |
| 17 | +import com.sun.net.httpserver.HttpServer; |
| 18 | +import io.micrometer.core.instrument.composite.CompositeMeterRegistry; |
| 19 | +import java.net.InetSocketAddress; |
| 20 | +import java.util.LinkedHashMap; |
| 21 | +import java.util.Map; |
| 22 | +import java.util.Map.Entry; |
| 23 | +import org.slf4j.Logger; |
| 24 | +import org.slf4j.LoggerFactory; |
| 25 | + |
| 26 | +class MonitoringContext { |
| 27 | + |
| 28 | + private static final Logger LOGGER = LoggerFactory.getLogger(MonitoringContext.class); |
| 29 | + |
| 30 | + private final int monitoringPort; |
| 31 | + private final CompositeMeterRegistry meterRegistry; |
| 32 | + |
| 33 | + private final Map<String, HttpHandler> handlers = new LinkedHashMap<>(); |
| 34 | + |
| 35 | + private volatile HttpServer server; |
| 36 | + |
| 37 | + MonitoringContext(int monitoringPort, CompositeMeterRegistry meterRegistry) { |
| 38 | + this.monitoringPort = monitoringPort; |
| 39 | + this.meterRegistry = meterRegistry; |
| 40 | + } |
| 41 | + |
| 42 | + void addHttpEndpoint(String path, HttpHandler handler) { |
| 43 | + this.handlers.put(path, handler); |
| 44 | + } |
| 45 | + |
| 46 | + void start() throws Exception { |
| 47 | + if (!handlers.isEmpty()) { |
| 48 | + server = HttpServer.create(new InetSocketAddress(this.monitoringPort), 0); |
| 49 | + |
| 50 | + for (Entry<String, HttpHandler> entry : handlers.entrySet()) { |
| 51 | + String path = entry.getKey().startsWith("/") ? entry.getKey() : "/" + entry.getKey(); |
| 52 | + HttpHandler handler = entry.getValue(); |
| 53 | + server.createContext(path, handler); |
| 54 | + } |
| 55 | + |
| 56 | + server.start(); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + void close() { |
| 61 | + if (server != null) { |
| 62 | + LOGGER.debug("Closing HTTP server"); |
| 63 | + long start = System.currentTimeMillis(); |
| 64 | + server.stop(0); |
| 65 | + LOGGER.debug("Closed HTTP server in {} ms", (System.currentTimeMillis() - start)); |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + CompositeMeterRegistry meterRegistry() { |
| 70 | + return meterRegistry; |
| 71 | + } |
| 72 | +} |
0 commit comments