Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gzip compression #915

Merged
merged 7 commits into from
Jan 19, 2021
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,15 @@

package kamon.prometheus.embeddedhttp

import java.net.{InetAddress, InetSocketAddress}
import java.nio.charset.StandardCharsets

import com.sun.net.httpserver.{HttpExchange, HttpHandler, HttpServer}
import com.typesafe.config.Config
import kamon.prometheus.ScrapeSource
import kamon.prometheus.embeddedhttp.SunEmbeddedHttpServer.shouldUseCompression

import java.net.{InetAddress, InetSocketAddress}
import java.nio.charset.StandardCharsets
import java.util.zip.GZIPOutputStream
import scala.collection.JavaConverters._

class SunEmbeddedHttpServer(hostname: String, port: Int, scrapeSource: ScrapeSource, config: Config) extends EmbeddedHttpServer(hostname, port, scrapeSource, config) {
private val server = {
Expand All @@ -32,24 +35,40 @@ class SunEmbeddedHttpServer(hostname: String, port: Int, scrapeSource: ScrapeSou
if (httpExchange.getRequestURI.getPath == "/metrics") {
val data = scrapeSource.scrapeData()
val bytes = data.getBytes(StandardCharsets.UTF_8)
httpExchange.sendResponseHeaders(200, bytes.length)
val os = httpExchange.getResponseBody
try {
os.write(bytes)
}
finally
os.close()
}
else {
httpExchange.sendResponseHeaders(404, -1)
}
if (shouldUseCompression(httpExchange)) {
val gzip = new GZIPOutputStream(os)
saeltz marked this conversation as resolved.
Show resolved Hide resolved
httpExchange.sendResponseHeaders(200, 0)
gzip.write(bytes)
gzip.close()
saeltz marked this conversation as resolved.
Show resolved Hide resolved
} else httpExchange.sendResponseHeaders(200, bytes.length)
saeltz marked this conversation as resolved.
Show resolved Hide resolved
} finally os.close()
} else httpExchange.sendResponseHeaders(404, -1)
}

}

s.createContext("/metrics", handler)
s.start()
s
}

def stop(): Unit = server.stop(0)
}

object SunEmbeddedHttpServer {
def shouldUseCompression(httpExchange: HttpExchange): Boolean = {
val encodingHeaders = httpExchange.getRequestHeaders.asScala.get("Accept-Encoding")
encodingHeaders match {
case Some(headerList) =>
val trimmedEncodings = for {
encodingHeader <- headerList.asScala
encodings = encodingHeader.split(",")
encoding <- encodings
} yield encoding.trim().toLowerCase()
trimmedEncodings.contains("gzip")
case None => false
}
}
}
saeltz marked this conversation as resolved.
Show resolved Hide resolved