001package io.prometheus.jmx; 002 003import java.io.File; 004import java.lang.instrument.Instrumentation; 005import java.net.InetSocketAddress; 006 007import io.prometheus.client.CollectorRegistry; 008import io.prometheus.client.exporter.HTTPServer; 009import io.prometheus.client.hotspot.DefaultExports; 010 011public class JavaAgent { 012 013 static HTTPServer server; 014 015 public static void premain(String agentArgument, Instrumentation instrumentation) throws Exception { 016 // Bind to all interfaces by default (this includes IPv6). 017 String host = "0.0.0.0"; 018 019 // If we have IPv6 address in square brackets, extract it first and then 020 // remove it from arguments to prevent confusion from too namy colons. 021 Integer indexOfClosingSquareBracket = agentArgument.indexOf("]:"); 022 if (indexOfClosingSquareBracket >= 0) { 023 host = agentArgument.substring(0, indexOfClosingSquareBracket + 1); 024 agentArgument = agentArgument.substring(indexOfClosingSquareBracket + 2); 025 } 026 027 String[] args = agentArgument.split(":"); 028 if (args.length < 2 || args.length > 3) { 029 System.err.println("Usage: -javaagent:/path/to/JavaAgent.jar=[host:]<port>:<yaml configuration file>"); 030 System.exit(1); 031 } 032 033 int port; 034 String file; 035 InetSocketAddress socket; 036 037 if (args.length == 3) { 038 port = Integer.parseInt(args[1]); 039 socket = new InetSocketAddress(args[0], port); 040 file = args[2]; 041 } else { 042 port = Integer.parseInt(args[0]); 043 socket = new InetSocketAddress(host, port); 044 file = args[1]; 045 } 046 047 new JmxCollector(new File(file)).register(); 048 DefaultExports.initialize(); 049 server = new HTTPServer(socket, CollectorRegistry.defaultRegistry, true); 050 } 051}