解析xml
httpserver
public class HttpServer {
private final static Logger logger = LoggerFactory.getLogger(HttpServer.class);
private static com.sun.net.httpserver.HttpServer server;
private final static String APPLICATION_JSON = "application/json;charset=UTF-8";
private final static String TEXT_PLAIN = "text/plain;charset=UTF-8";
private static int port;
public static void start() {
try {
port = 1111;
InetSocketAddress addr = new InetSocketAddress(port);
server = com.sun.net.httpserver.HttpServer.create(addr, AgentConfig.getConfig().getInt("httpServer.accepts", 100));
ExecutorService executorService =ThreadPoolFactory.newFixedThreadPool("SunHttp-Worker", 100, 100);
server.setExecutor(executorService);
if(executorService instanceof ThreadPoolExecutor){
ThreadPoolRegistor.regist("SunHttp-Worker", (ThreadPoolExecutor) executorService);
}
server.createContext("/", new HttpHandler() {
@Override
public void handle(HttpExchange httpExchange) throws IOException {
String path = httpExchange.getRequestURI().getPath();
try {
switch (path) {
case "/exec":
//url参数
String query = httpExchange.getRequestURI().getQuery();
String body = IOUtils.toString(httpExchange.getRequestBody(), Charsets.UTF_8);
if (StringUtils.isNotEmpty(body)) {
if (StringUtils.isNotBlank(query)) {
query = body + "&" + query;
} else {
query = body;
}
}
//解析URL参数,放到Map当中(TreeMap根据Key排序)
TreeMap<String, String> params = new TreeMap<>();
String[] paramsArray = query.split("&");
for (String param : paramsArray) {
String[] tmp = param.split("=");
String key = tmp[0].trim();
if (StringUtils.isNotEmpty(key)) {
//参数名命令行注入检查
if (ShellInjectUtils.containsInjectChars(key)) {
throw new AgentLogicException("参数名[" + key + "]包含命令行注入字符");
}
if (tmp.length == 1) {
params.put(key, null);
} else {
String value = tmp[1].trim();
//参数值命令行注入检查
if (ShellInjectUtils.containsInjectChars(value)) {
throw new AgentLogicException("参数[" + key + "=" + value + "]包含命令行注入字符");
}
params.put(key, value);
}
}
}
if (AgentConfig.getConfig().getBoolean("verifySign", true)) {
//验证参数签名
String sign = params.get("sign");
params.remove("sign");
if (StringUtils.isEmpty(sign) || !SignatureUtils.verifyCommandSign(params, sign)) {
throw new AgentLogicException("参数签名验证失败");
}
}
//插件名称
String pluginName = params.get("plugin");
params.remove("plugin");
if (StringUtils.isEmpty(pluginName)) {
throw new AgentLogicException("参数[plugin]不能为空");
}
if (logger.isDebugEnabled()) {
logger.debug("plugin={},params={}", pluginName, params.toString());
}
writeResponse(httpExchange, 200, Dispatcher.dispatch(pluginName, params));
return;
case "/agent/jvm/profile.json":
writeResponse(httpExchange, 200, APPLICATION_JSON, Result.success(JvmApi.getJVMInfo()));
return;
case "/agent/status":
writeResponse(httpExchange, 200, APPLICATION_JSON, Result.success(200));
return;
default:
writeResponse(httpExchange, 404, APPLICATION_JSON, Result.fail(path + " don't exist"));
}
} catch (AgentLogicException e) {
logger.error("agent logic error", e);
writeResponse(httpExchange, 500, TEXT_PLAIN, Result.fail(e.getCode(),e.getMessage()));
} catch (Throwable e) {
logger.error("dispatch handler error", e);
writeResponse(httpExchange, 500, TEXT_PLAIN, Result.fail(ExceptionUtils.getStackTrace(e)));
} finally {
IOUtils.closeQuietly(httpExchange.getRequestBody());
IOUtils.closeQuietly(httpExchange.getResponseBody());
}
}
});
server.createContext("/agent/ui", new StaticFileHandler());
server.start();
System.err.println("SunHttpServer is listening on port " + port);
} catch (Exception e) {
logger.error("Failed to start SunHttpServer on port " + port, e);
System.exit(0);
}
}
private static void writeResponse(HttpExchange httpExchange, int code, String contentType, Result body) throws IOException {
if (contentType != null) {
httpExchange.getResponseHeaders().set("Content-Type", contentType);
}
writeResponse(httpExchange, code, body);
}
private static void writeResponse(HttpExchange httpExchange, int code, Result body) throws IOException {
if (body == null) {
body = Result.fail("target interface return null!");
}
byte[] realBodyBytes = GsonUtils.toBytes(body);
httpExchange.sendResponseHeaders(code, realBodyBytes.length);
IOUtils.write(realBodyBytes, httpExchange.getResponseBody());
}
public static void shutdown() {
try {
server.stop(0);
} catch (Exception e) {
logger.warn(" SunHttpServer shutdown error," + e.getMessage(), e);
}
System.err.println("********************Sun Http Server[" + port + "] closed!**********************");
}
}
转发
public class Dispatcher {
public static Result dispatch(String pluginName, Map<String, String> params) throws Exception {
PluginInfo pluginInfo = PluginFactory.getInstance().getInfo(pluginName);
switch (pluginInfo.getType()) {
case PYTHON:
String ptyhonUser = pluginInfo.getParams().get("user");
if (StringUtils.isBlank(ptyhonUser)) {
throw new AgentLogicException("插件[" + pluginName + "]没有配置参数user");
}
if ("root".equalsIgnoreCase(ptyhonUser)) {
throw new AgentLogicException("PYTHON插件不允许以root用户运行");
}
ExecUtil.CommandResult pythonResult = ExecUtil.executePython(pluginInfo.getPath() + toCommandParams(params));
return pythonResult.isSuccess() ? Result.success(pythonResult.getOut()) : Result.fail(pythonResult.getErr());
case BASH:
String osUser = pluginInfo.getParams().get("user");
if (StringUtils.isBlank(osUser)) {
throw new AgentLogicException("插件[" + pluginName + "]没有配置参数user");
}
if ("root".equalsIgnoreCase(osUser)) {
throw new AgentLogicException("BASH插件不允许以root用户运行");
}
ExecUtil.CommandResult shellResult = ExecUtil.executeShell(osUser, pluginInfo.getPath() + toCommandParams(params));
return shellResult.isSuccess() ? Result.success(shellResult.getOut()) : Result.fail(shellResult.getErr());
case JAVA:
IPlugin plugin = ExtensionFactory.getSingletonExtension(pluginInfo.getPath());
Result result = plugin.execute(params);
return result;
default:
throw new AgentLogicException("未知才插件类型:" + pluginInfo.getType());
}
}
/**
* 转换为脚本参数 -parameterName parameterValue 形式
*
* @param params
* @return
*/
private static String toCommandParams(Map<String, String> params) {
StringBuilder paramsString = new StringBuilder();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> row : params.entrySet()) {
paramsString.append(" -").append(row.getKey()).append(" ").append(row.getValue());
}
}
return paramsString.toString();
}
/**
* 分发命令给插件
*
* @param pluginName
* @param params
* @return
*/
public static void main(String[] args) {
System.out.println(System.getProperty("java.library.path"));
}
}
调用
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AgentUtils {
public static final Logger AGENT_LOG = LoggerFactory.getLogger("yy_AGENT");
private static final int AGENT_PORT = 1111;
private static Gson gson = (new GsonBuilder()).create();
public AgentUtils() {
}
public static final Result doRequest(String ip, String path, String bodyWithSign, int readTimeout) {
String url = String.format("http://%s:%d%s", ip, AGENT_PORT, path);
AGENT_LOG.info("do agent request, ip={},path={},body={}", new Object[]{ip, path, bodyWithSign});
HttpURLConnection httpUrlConnection = null;
InputStream inputStream = null;
InputStream errorStream = null;
OutputStream outputStream = null;
Result var12;
try {
Result responseBody;
try {
httpUrlConnection = (HttpURLConnection)(new URL(url)).openConnection();
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
httpUrlConnection.setInstanceFollowRedirects(false);
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setRequestProperty("Connection", "close");
httpUrlConnection.setConnectTimeout(2000);
httpUrlConnection.setReadTimeout(readTimeout);
outputStream = httpUrlConnection.getOutputStream();
IOUtils.write(bodyWithSign, outputStream, "UTF-8");
IOUtils.closeQuietly(outputStream);
int responseCode = httpUrlConnection.getResponseCode();
responseBody = null;
String responseBody;
if (responseCode == 200) {
inputStream = httpUrlConnection.getInputStream();
responseBody = IOUtils.toString(inputStream, "UTF-8");
AGENT_LOG.info("agent{} response success,code{},body{}", new Object[]{ip, responseCode, responseBody});
} else {
errorStream = httpUrlConnection.getErrorStream();
responseBody = IOUtils.toString(errorStream, "UTF-8");
AGENT_LOG.info("agent{} response error, code{},body{}", new Object[]{ip, responseCode, responseBody});
}
if (!StringUtils.isNotBlank(responseBody)) {
return Result.fail("请求失败");
}
Result agentResult;
try {
agentResult = (Result)gson.fromJson(responseBody, Result.class);
} catch (JsonSyntaxException var22) {
AGENT_LOG.debug("fail to parse Result.class", var22);
Result var13 = Result.fail("Agent1 JSON转换失败:" + responseBody);
return var13;
}
if (responseCode == 200) {
var12 = agentResult;
return var12;
}
var12 = Result.fail(agentResult.getMsg());
} catch (ConnectException var24) {
AGENT_LOG.error("agent1 connection error ", var24);
try {
InetAddress address = InetAddress.getByName(ip);
boolean reachable = address.isReachable(3000);
if (!reachable) {
var12 = Result.fail("主机不可达");
return var12;
}
} catch (Exception var23) {
;
}
responseBody = Result.fail("Agent连接失败");
return responseBody;
} catch (SocketTimeoutException var25) {
AGENT_LOG.error("agent1 get timeout", var25);
responseBody = Result.fail("Agent请求超时");
return responseBody;
} catch (MalformedURLException var26) {
AGENT_LOG.error("URL格式不合法:{}", url, var26);
responseBody = Result.fail("请求URL不合法");
return responseBody;
} catch (Throwable var27) {
AGENT_LOG.error("agent io exception", var27);
responseBody = Result.fail(ExceptionUtils.getStackTrace(var27));
return responseBody;
}
} finally {
IOUtils.closeQuietly(outputStream);
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(errorStream);
if (httpUrlConnection != null) {
httpUrlConnection.disconnect();
}
}
return var12;
}
public static final Result doRequest(String ip, String path, String bodyWithSign) {
return doRequest(ip, path, bodyWithSign, 10000);
}
}