// Copyright 2017 The Promagent Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package io.promagent.internal;

import com.sun.net.httpserver.HttpServer;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.exporter.common.TextFormat;

import java.io.StringWriter;
import java.net.InetSocketAddress;
import java.util.Collections;

/**
 * Use the Java runtime's built-in {@link HttpServer} to export Prometheus metrics.
 */
class BuiltInServer {

    static void run(String host, String portString, CollectorRegistry registry) throws Exception {
        try {
            int port = Integer.parseInt(portString);
            InetSocketAddress address = host == null ? new InetSocketAddress(port) : new InetSocketAddress(host, port);
            HttpServer httpServer = HttpServer.create(address, 10);
            httpServer.createContext("/metrics", httpExchange -> {
                StringWriter respBodyWriter = new StringWriter();
                TextFormat.write004(respBodyWriter, registry.metricFamilySamples());
                byte[] respBody = respBodyWriter.toString().getBytes("UTF-8");
                httpExchange.getResponseHeaders().put("Context-Type", Collections.singletonList("text/plain; charset=UTF-8"));
                httpExchange.sendResponseHeaders(200, respBody.length);
                httpExchange.getResponseBody().write(respBody);
                httpExchange.getResponseBody().close();
            });
            httpServer.start();
        } catch (NumberFormatException e) {
            throw new RuntimeException("Failed to parse command line arguments: '" + portString + "' is not a valid port number.");
        }
    }
}

@@ -620,16 +620,60 @@
 ernal;%0A%0A
+import com.sun.net.httpserver.HttpExchange;%0A
 import c
@@ -810,16 +810,44 @@
 ormat;%0A%0A
+import java.io.IOException;%0A
 import j
@@ -1445,110 +1445,785 @@
 t(%22/
-metrics%22, httpExchange -%3E %7B%0A                StringWriter respBodyWriter = new StringWriter();%0A        
+%22, httpExchange -%3E %7B%0A                if (%22/metrics%22.equals(httpExchange.getRequestURI().getPath())) %7B%0A                    respondMetrics(registry, httpExchange);%0A                %7D else %7B%0A                    respondRedirect(httpExchange);%0A                %7D%0A            %7D);%0A            httpServer.start();%0A        %7D catch (NumberFormatException e) %7B%0A            throw new RuntimeException(%22Failed to parse command line arguments: '%22 + portString + %22' is not a valid port number.%22);%0A        %7D%0A    %7D%0A%0A    private static void respondMetrics(CollectorRegistry registry, HttpExchange httpExchange) throws IOException %7B%0A        StringWriter respBodyWriter = new StringWriter();%0A        respBodyWriter.write(%22# Metrics will become visible when they are updated for the first time.%5Cn%22);%0A
     
@@ -2291,32 +2291,24 @@
 Samples());%0A
-        
         byte
@@ -2370,32 +2370,24 @@
 %22);%0A        
-     
-   
 httpExchange
@@ -2489,32 +2489,24 @@
 ));%0A        
-       
- 
 httpExchange
@@ -2549,24 +2549,16 @@
 ength);%0A
-        
         
@@ -2609,32 +2609,24 @@
 y);%0A        
- 
-       
 httpExchange
@@ -2661,237 +2661,550 @@
     
+%7D%0A%0A
     
-    %7D);%0A            httpServer.start();%0A        %7D catch (NumberFormatException e) %7B%0A            throw new RuntimeException(%22Failed to parse command line arguments: '%22 + portString + %22' is not a valid port number.%22);%0A        %7D
+private static void respondRedirect(HttpExchange httpExchange) throws IOException %7B%0A        byte%5B%5D respBody = %22Metrics are provided on the /metrics endpoint.%22.getBytes(%22UTF-8%22);%0A        httpExchange.getResponseHeaders().add(%22Location%22, %22/metrics%22);%0A        httpExchange.getResponseHeaders().put(%22Context-Type%22, Collections.singletonList(%22text/plain; charset=UTF-8%22));%0A        httpExchange.sendResponseHeaders(302, respBody.length);%0A        httpExchange.getResponseBody().write(respBody);%0A        httpExchange.getResponseBody().close();
 %0A   

increase usability of built-in http server