Skip to content

Instantly share code, notes, and snippets.

@mhewedy
Last active June 17, 2022 07:24
Show Gist options
  • Save mhewedy/47869d9ae49c36ead7a9953ad64d1a87 to your computer and use it in GitHub Desktop.
Save mhewedy/47869d9ae49c36ead7a9953ad64d1a87 to your computer and use it in GitHub Desktop.
invoke springboot jmx endpoints
#!/usr/lib/jvm/java/bin/java --source 17
/* example
jmx_endpoint_invoker.sh Health health
*/
import com.sun.tools.attach.AttachOperationFailedException;
import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.spi.AttachProvider;
import javax.management.ObjectName;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.util.Properties;
public class JmxEndpointInvoker {
public static final String JMX_PORT = "5555";
public static void main(String... args) throws Exception {
executeJmx(() -> invokeJmxEndpoint(args[0], args[1]));
}
private static void executeJmx(Runnable action) throws Exception {
var vm = VirtualMachine.attach(AttachProvider.providers()
.stream().flatMap(it -> it.listVirtualMachines().stream())
.filter(it -> it.displayName().contains("com.elm.tamm.Application"))
.findFirst()
.orElseThrow()
);
var props = new Properties();
props.put("com.sun.management.jmxremote.port", JMX_PORT);
props.put("com.sun.management.jmxremote.authenticate", "false");
props.put("com.sun.management.jmxremote.ssl", "false");
try {
vm.startManagementAgent(props);
} catch (AttachOperationFailedException ex) {
if (!ex.getMessage().contains("Invalid agent state: Agent already started")) {
throw ex;
}
}
action.run();
vm.detach();
}
private static void invokeJmxEndpoint(String endpointName, String operationName) {
try (var jmxConnector = JMXConnectorFactory.connect(
new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:" + JMX_PORT + "/jmxrmi"))) {
var conn = jmxConnector.getMBeanServerConnection();
var result = conn.invoke(new ObjectName("org.springframework.boot:type=Endpoint,name=" + endpointName),
operationName, new Object[]{}, new String[]{});
System.out.println(result);
var status = "" + result;
var state = status.substring(8, 10);
var ok = state.compareTo("UP") == 0;
if (!ok) {
System.exit(1);
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment