All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.kits.agent.DynamicAgent Maven / Gradle / Ivy

The newest version!
package io.github.kits.agent;

import com.sun.tools.attach.AgentInitializationException;
import com.sun.tools.attach.AgentLoadException;
import com.sun.tools.attach.VirtualMachine;
import io.github.kits.EnvKit;
import io.github.kits.FileKit;
import io.github.kits.LambdaExKit;
import io.github.kits.log.Logger;

import java.io.IOException;
import java.lang.instrument.Instrumentation;
import java.util.List;

/**
 * @project: kits
 * @created: with IDEA
 * @author: whimthen
 * @date: 2019-03-01-14:52 | March. Friday
 */
public class DynamicAgent {

	private static Instrumentation instrumentation;

	public DynamicAgent() {
	}

	public static Instrumentation getInstrumentation() {
		return instrumentation;
	}

	/**
	 * 代理实现
	 *
	 * @param agentArgs 参数
	 * @param inst
	 */
	public static void agentmain(String agentArgs, Instrumentation inst) {
		synchronized (DynamicAgent.class) {
			if (instrumentation == null) {
				instrumentation = inst;
			}
		}
		inst.addTransformer(new AgentHandler());
	}

	/**
	 * 启动代理
	 *
	 * @param excludeAgentJar 需要排除的代理jar
	 */
	public static void start(String... excludeAgentJar) {
		long         currentPID = EnvKit.getCurrentPID();
		List agentJars  = FileKit.findAgentJar(excludeAgentJar);
		try {
			VirtualMachine vm = VirtualMachine.attach(String.valueOf(currentPID));
			agentJars.parallelStream()
					 .forEach(LambdaExKit.rethrowConsumer(vm::loadAgent));
			vm.detach();
		} catch (IOException | AgentInitializationException | AgentLoadException e) {
			Logger.error("VirtualMachine loadAgent error", e);
		} catch (Exception e) {
			Logger.errorf("VirtualMachine attach error, the current PID is [{}]", e, currentPID);
		}
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy