Commit deacd8b0 by 钱炳权

切面实现aflnet数据库存入成功,解决多线程错误捕获问题

parent 7752009e
......@@ -7,7 +7,6 @@ import org.springframework.cloud.openfeign.EnableFeignClients;
import java.util.Arrays;
@SpringBootApplication
@EnableFeignClients
public class FuzzIntegration {
public static void main(String[] args) {
Arrays.stream(args).forEach(System.out::println);
......
package com.example.fuzzControll.annotion;
import java.lang.annotation.*;
/**
* 切片标识注解
*/
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface NeedCut {
String name() default "";
String moment() default "";
String function() default "";
}
package com.example.fuzzControll.aop;
import com.example.fuzzControll.annotion.NeedCut;
import com.example.fuzzControll.constents.LogicDeleteEnum;
import com.example.fuzzControll.constents.MissionStateEnum;
import com.example.fuzzControll.constents.TableClassEnum;
import com.example.fuzzControll.mapper.MissionInfoMapper;
import com.example.fuzzControll.pojo.vo.MissionInfo;
import com.example.fuzzControll.service.AflnetPersistenceService;
import com.example.fuzzControll.tools.GlobalParameters;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@Aspect
@Component
@Slf4j
public class IntegrationAop implements Ordered {
@Pointcut(value = "@annotation(com.example.fuzzControll.annotion.NeedCut)")
private void cut() {
}
@Before("cut()")
private void before(JoinPoint point) {
List<String> needProcess = Arrays.asList("aflnet");
Signature signature = point.getSignature();
MethodSignature methodSignature = null;
if (!(signature instanceof MethodSignature)) {
throw new IllegalArgumentException("该注解只能用于方法");
}
methodSignature = (MethodSignature) signature;
Object target = point.getTarget();
Method currentMethod = null;
try {
currentMethod = target.getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes());
} catch (NoSuchMethodException e) {
log.error("NoSuchMethod!");
e.printStackTrace();
throw new RuntimeException(e);
}
NeedCut logotype = currentMethod.getAnnotation(NeedCut.class);
if ("before".equals(logotype.moment())) {//需要进行处理
if ("aflnet".equals(logotype.name())) {//aflnet测试信息存储
int missionId = GlobalParameters.missionInfoMapper.selectTopMissionId() + 1;
GlobalParameters.missionInfoMapper.insertMission(new MissionInfo(missionId, TableClassEnum.AFLNET.getTableId(), new Date(), GlobalParameters.aflnetData.get("missionName"),
MissionStateEnum.RUNNING.getStateCode(), 0L));
}
}
}
@Around("cut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
Signature signature = point.getSignature();
MethodSignature methodSignature = null;
if (!(signature instanceof MethodSignature)) {
throw new IllegalArgumentException("该注解只能用于方法");
}
methodSignature = (MethodSignature) signature;
Object target = point.getTarget();
Method currentMethod = target.getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes());
NeedCut logotype = currentMethod.getAnnotation(NeedCut.class);
// if (datasource != null) {
// DataSourceContextHolder.setDataSourceType(logotype.name());
// log.debug("设置数据源为:" + datasource.name());
// } else {
// DataSourceContextHolder.setDataSourceType(DSEnum.DATA_SOURCE_CORE);
// log.debug("设置数据源为:dataSourceCore");
// }
// try {
return point.proceed();
// } finally {
// log.debug("清空数据源信息!");
// DataSourceContextHolder.clearDataSourceType();
// }
}
@Override
public int getOrder() {
return 1;
}
}
package com.example.fuzzControll.conf;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableFeignClients
public class SystemConfig {
}
package com.example.fuzzControll.constents;
public enum LogicDeleteEnum {
ALIVE("alive",0),
LOGIC_DELETE("logic_delete",1);
private String name;
private int code;
LogicDeleteEnum(String name, int code) {
this.name = name;
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
package com.example.fuzzControll.constents;
public enum MissionStateEnum {
DONE("done",1),
RUNNING("running",2),
FAILED("failed",3);
private String stateName;
private int stateCode;
MissionStateEnum(String stateName, int stateCode) {
this.stateName = stateName;
this.stateCode = stateCode;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public int getStateCode() {
return stateCode;
}
public void setStateCode(int stateCode) {
this.stateCode = stateCode;
}
}
package com.example.fuzzControll.controller;
import com.example.fuzzControll.exception.AflnetException;
import com.example.fuzzControll.exception.BaseException;
import com.example.fuzzControll.exception.CmdException;
import com.example.fuzzControll.exception.MysqlException;
import com.example.fuzzControll.exception.*;
import com.example.fuzzControll.pojo.vo.AjaxResult;
import com.example.fuzzControll.pojo.vo.CmdStartParams;
import com.example.fuzzControll.service.TestService;
......@@ -33,16 +30,20 @@ public class AlfnetController {
//todo 捕获子线程错误
try {
GlobalParameters.aflnetData.put("missionName", cmdStartParams.getProtopcol());
new Thread(new Runnable() {
Thread subThread = new Thread(new Runnable() {
@Override
public void run() {
service.testStart(cmdStartParams);
}
}).start();
} catch (Exception e) {
if (e instanceof AflnetException || e instanceof CmdException) {
log.error(((BaseException) e).getDefaultMessage());
});
GlobalParameters.ThreadState.put(subThread,"start");
subThread.setUncaughtExceptionHandler(new MyExceptionHandler());
subThread.start();
subThread.join();
if ("error".equals(GlobalParameters.ThreadState.get(subThread))) {
throw new Exception();
}
} catch (Exception e) {
return AjaxResult.error("测试启动失败!");
}
return AjaxResult.success("测试已启动!");
......@@ -58,7 +59,7 @@ public class AlfnetController {
} catch (AflnetException e) {
log.error(e.getDefaultMessage());
return AjaxResult.error("测试停止失败!");
} catch (MysqlException e){
} catch (MysqlException e) {
log.error("File backup error: " + e.getMessage());
}
return AjaxResult.success("测试停止成功!");
......
package com.example.fuzzControll.exception;
import com.example.fuzzControll.tools.GlobalParameters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyExceptionHandler implements Thread.UncaughtExceptionHandler
{
@Override
public void uncaughtException(Thread t, Throwable e)
{
GlobalParameters.ThreadState.put(t,"error");
}
}
......@@ -11,25 +11,30 @@ public class MissionInfo {
private int id;
private int missionId;
@JsonIgnore
private int tableId;//返回数据忽略字段
private int tableId;//返回数据忽略字段;aflnet 为1 kitty为2
private Date createTime;
private String missionName;
@JsonIgnore
private int state;
private Long runTime;
private String stateName;
public MissionInfo() {
}
public MissionInfo(int id, int missionId, int tableId, Date createTime, String missionName) {
this.id = id;
public MissionInfo(int missionId, int tableId, Date createTime, String missionName, int state, Long runTime) {
this.missionId = missionId;
this.tableId = tableId;
this.createTime = createTime;
this.missionName = missionName;
this.state = state;
this.runTime = runTime;
}
public MissionInfo(int missionId, int tableId, Date createTime, String missionName) {
public MissionInfo(int missionId, Date createTime, String missionName, Long runTime, String stateName) {
this.missionId = missionId;
this.tableId = tableId;
this.createTime = createTime;
this.missionName = missionName;
this.runTime = runTime;
this.stateName = stateName;
}
}
package com.example.fuzzControll.service;
public interface AflnetPersistenceService {
public int aflnetResultBackup(String filename,String missionName);
public int aflnetResultBackup(String filename, String missionName,int state,int logicDelete,Long runTime);
public void loadInFile(int missionId,String filePath);
}
......@@ -29,8 +29,8 @@ public class AflnetPersistenceServiceImpl implements AflnetPersistenceService {
FileTools fileTools = new FileTools();
@Override
public int aflnetResultBackup(String filename, String missionName) {
return mysqlTransaction(filename, missionName);
public int aflnetResultBackup(String filename, String missionName,int state,int logicDelete,Long runTime) {
return mysqlTransaction(filename, missionName,state,logicDelete,runTime);
}
@Override
......@@ -46,11 +46,11 @@ public class AflnetPersistenceServiceImpl implements AflnetPersistenceService {
}
@Transactional(rollbackFor = MysqlException.class)
public int mysqlTransaction(String filename,String missionName) {
public int mysqlTransaction(String filename, String missionName,int state,int logicDelete,Long runTime) {
int topMissionId = missionInfoMapper.selectTopMissionId() + 1;//获取最新的missionId
AflnetResult result = new AflnetResult(topMissionId, fileTools.fileReadAndTranstoBytes(aflnetProperties.getOutputPath(), filename), filename);
aflnetMapper.aflnetOutputBackup(result);//存入日志文件
missionInfoMapper.insertMission(new MissionInfo(topMissionId, TableClassEnum.AFLNET.getTableId(), new Date(), missionName));//插入任务信息
missionInfoMapper.insertMission(new MissionInfo(topMissionId, TableClassEnum.AFLNET.getTableId(), new Date(), missionName, state, runTime));//插入任务信息
return 1;
}
}
......@@ -26,7 +26,8 @@ import java.util.concurrent.CountDownLatch;
@Slf4j
public class TestServiceImpl implements TestService {
CmdTools cmdTools = new CmdTools();
@Autowired
CmdTools cmdTools ;
@Autowired
AflnetPersistenceService aflnetPersistenceService;
......@@ -40,18 +41,18 @@ public class TestServiceImpl implements TestService {
String cmd = cmdTools.parse(cmdStartParams);
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss-");
String outputFileName = df.format(date)+cmdStartParams.getProtopcol()+"-output";
String finalCmd = CmdConstent.RUN_AFLNET_BEFORE + outputFileName + CmdConstent.RUN_AFLNET_AFTER + cmd + aflnetProperties.getAflnetPath() + "live555/testProgs/"+"testOnDemandRTSPServer 8554";
String outputFileName = df.format(date) + cmdStartParams.getProtopcol() + "-output";
String finalCmd = CmdConstent.RUN_AFLNET_BEFORE + outputFileName + CmdConstent.RUN_AFLNET_AFTER + cmd + aflnetProperties.getAflnetPath() + "live555/testProgs/" + "testOnDemandRTSPServer 8554";
GlobalParameters.aflnetData.put("aflnetName", outputFileName);
log.info("The cmd is [{}]",finalCmd);
log.info("The cmd is [{}]", finalCmd);
cmdTools.runProgramCmd(finalCmd, outputFileName + ".zip");
}
@Override
public void testStop() {
TestControlTools.setIsRunning(false);
GlobalParameters.testTimeMessage.get("aflnet").put("end",System.currentTimeMillis());
log.info("Aflnet has been stopped ! ");
try {
new Thread(new Runnable() {
......@@ -63,16 +64,17 @@ public class TestServiceImpl implements TestService {
cmdTools.runCmd(CmdConstent.RUN_ZIP_FILE + fileZipName + " " + fileName, "zip file in testStart");
List<String> files = cmdTools.runCmd(CmdConstent.GET_FILE_NAME + aflnetProperties.getOutputPath(), "getSeedFiles");
files.stream().forEach(System.out::println);
if(!files.contains(fileZipName)){
if (!files.contains(fileZipName)) {
log.error("File zip error!");
}
while (files.contains(fileZipName) && flag == 0) {//当前存在压缩包才存入
flag = aflnetPersistenceService.aflnetResultBackup(fileZipName,GlobalParameters.aflnetData.get("missionName"));
flag = aflnetPersistenceService.aflnetResultBackup(fileZipName, GlobalParameters.aflnetData.get("missionName"), 1, 0,
GlobalParameters.testTimeMessage.get("aflnet").get("end")-GlobalParameters.testTimeMessage.get("aflnet").get("start"));
}
/*清除生成的文件*/
try {
cmdTools.runCmd(CmdConstent.DELETE_FILE+fileName,"delete file");
cmdTools.runCmd(CmdConstent.DELETE_FILE+fileZipName,"delete zipFile");
cmdTools.runCmd(CmdConstent.DELETE_FILE + fileName, "delete file");
cmdTools.runCmd(CmdConstent.DELETE_FILE + fileZipName, "delete zipFile");
} catch (CmdException e) {
e.printStackTrace();
log.error("file delete failed!");
......
package com.example.fuzzControll.tools;
import com.alibaba.fastjson.JSONObject;
import com.example.fuzzControll.annotion.NeedCut;
import com.example.fuzzControll.conf.AflnetProperties;
import com.example.fuzzControll.conf.SpringContextUtil;
import com.example.fuzzControll.constents.CmdConstent;
......@@ -13,6 +14,7 @@ import com.example.fuzzControll.pojo.vo.*;
import com.example.fuzzControll.service.AflnetPersistenceService;
import com.example.fuzzControll.service.impl.websocketClientServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import javax.swing.*;
......@@ -24,6 +26,7 @@ import java.util.stream.Collectors;
//todo need modify
@Slf4j
@Component
public class CmdTools {
Boolean send = false;
......@@ -35,12 +38,12 @@ public class CmdTools {
public List<String> runCmd(String cmd, String caller) throws CmdException {
List<String> result = new ArrayList<String>();
try {
log.info(caller+" is running!");
log.info(caller + " is running!");
Process process = Runtime.getRuntime().exec(cmd);
printMessage(process.getInputStream(), result);
printMessage(process.getErrorStream(), new ArrayList<String>());
process.waitFor();
log.info(caller+" end!");
log.info(caller + " end!");
} catch (Exception e) {
e.printStackTrace();
throw new CmdException(caller + " run cmd failed!");
......@@ -54,6 +57,7 @@ public class CmdTools {
* 运行需要后台运行cmd
* 通过websocket返回数据
*/
@NeedCut(name ="aflnet",moment = "before",function = "backup")
public void runProgramCmd(String cmd, String outputFileName) throws AflnetException {
try {
Process process = Runtime.getRuntime().exec(cmd);
......@@ -62,7 +66,7 @@ public class CmdTools {
process.waitFor();
log.info("Aflnet cmd have been run.");
} catch (Exception e) {
e.printStackTrace();
log.error("alfnet run error!:"+e.getMessage());
throw new AflnetException("Aflnet run error");
}
}
......@@ -76,6 +80,7 @@ public class CmdTools {
List<String> out = Collections.synchronizedList(new ArrayList<String>());
List<String> error = Collections.synchronizedList(new ArrayList<String>());
try {
GlobalParameters.testTimeMessage.get("kitty").put("start",System.currentTimeMillis());
Process process = Runtime.getRuntime().exec(cmd);
printMessageByProgramCmd(process.getInputStream(), out);
printMessageByProgramCmd(process.getErrorStream(), error);
......@@ -92,6 +97,7 @@ public class CmdTools {
/*新开一个线程存入数据*/
List<String> finalOut = out;
List<String> finalError = error;
GlobalParameters.testTimeMessage.get("kitty").put("end",System.currentTimeMillis());
new Thread(new Runnable() {
@Override
public void run() {
......@@ -164,11 +170,13 @@ public class CmdTools {
if (line.contains("All set and ready to roll!") || line.contains("american fuzzy") || line.contains("process timing overall results")) {
show = false;
} else if (line.contains("PROGRAM ABORT")) {
log.error("Aflnet run failed !");
throw new AflnetException("Aflnet run failed !");
}
if (show) {
log.info(line);
}
GlobalParameters.testTimeMessage.get("aflnet").put("start",System.currentTimeMillis());
if (line.contains("run time")) {
send = false;
int run_time = line.indexOf(":");
......@@ -264,37 +272,37 @@ public class CmdTools {
}
StringBuilder cmd = new StringBuilder();
if (cmdStartParams.getNetinfo() != "" && cmdStartParams.getNetinfo() != null) {
cmd.append(" -N " + cmdStartParams.getNetinfo()+ " ");
cmd.append(" -N " + cmdStartParams.getNetinfo() + " ");
} else {
log.error("There is no netinfo !");
throw new AflnetException("There is no netinfo !");
}
if (cmdStartParams.getProtopcol() != "") {
cmd.append(" -P " + cmdStartParams.getProtopcol()+ " ");
cmd.append(" -P " + cmdStartParams.getProtopcol() + " ");
}
if (cmdStartParams.getWaiting() != 0) {
cmd.append(" -D " + cmdStartParams.getWaiting()+ " ");
cmd.append(" -D " + cmdStartParams.getWaiting() + " ");
}
if (cmdStartParams.getNsname() != "") {
cmd.append(" -e " + cmdStartParams.getNsname()+ " ");
cmd.append(" -e " + cmdStartParams.getNsname() + " ");
}
if (cmdStartParams.getKill()) {
cmd.append(" -K ");
}
if (cmdStartParams.getAwareMode()) {
cmd.append(" -E "+ " ");
cmd.append(" -E " + " ");
}
if (cmdStartParams.getRegionMutationOperators()) {
cmd.append(" -R "+ " ");
cmd.append(" -R " + " ");
}
if (cmdStartParams.getFalseNegativeMode()) {
cmd.append(" -F "+ " ");
cmd.append(" -F " + " ");
}
if (cmdStartParams.getScript() != "") {
cmd.append(" -c " + cmdStartParams.getScript()+ " ");
cmd.append(" -c " + cmdStartParams.getScript() + " ");
}
if (cmdStartParams.getStateSelectionAlgo() != 0) {
cmd.append(" -q " + cmdStartParams.getStateSelectionAlgo()+ " ");
cmd.append(" -q " + cmdStartParams.getStateSelectionAlgo() + " ");
}
if (cmdStartParams.getSeedSelectionAlgo() != 0) {
cmd.append(" -s " + cmdStartParams.getSeedSelectionAlgo() + " ");
......@@ -313,13 +321,13 @@ public class CmdTools {
e.printStackTrace();
log.error("kitty backup error!");
}
/*kitty的协议模板方法的日志和数据包文件存入数据库*/
if (caller.equals("protocolTemplate")) {
// GlobalParameters.kittyFuzzPersistenceService.KittyPackagesBackup(missionId);
GlobalParameters.missionInfoMapper.insertMission(new MissionInfo(missionId, 2, new Date(), missionName));
} else {
/*存入missionInfo信息*/
GlobalParameters.missionInfoMapper.insertMission(new MissionInfo(missionId, 3, new Date(), missionName));
}
// /*kitty的协议模板方法的日志和数据包文件存入数据库*/
// if (caller.equals("protocolTemplate")) {
//// GlobalParameters.kittyFuzzPersistenceService.KittyPackagesBackup(missionId);
// GlobalParameters.missionInfoMapper.insertMission(new MissionInfo(missionId, 2, new Date(), missionName,));
// } else {
// /*存入missionInfo信息*/
// GlobalParameters.missionInfoMapper.insertMission(new MissionInfo(missionId, 3, new Date(), missionName));
// }
}
}
\ No newline at end of file
......@@ -18,4 +18,12 @@ public class GlobalParameters {
public static AflnetProperties aflnetProperties = (AflnetProperties) SpringContextUtil.getBean("AflnetProperties");
public static AflnetPersistenceService aflnetPersistenceService = (AflnetPersistenceService) SpringContextUtil.getBean("AflnetPersistenceService");
public static MissionInfoMapper missionInfoMapper = (MissionInfoMapper) SpringContextUtil.getBean("MissionInfoMapper");
/**
* 系统全局测试时间参数
*/
public static ConcurrentHashMap<String, ConcurrentHashMap<String,Long>> testTimeMessage = new ConcurrentHashMap<>();
/**
* 多线程异常控制
*/
public static ConcurrentHashMap<Thread, String> ThreadState = new ConcurrentHashMap<>();
}
......@@ -5,6 +5,6 @@ spring:
active: dev #默认为开发环境
server:
port: 8104
port: 8103
......@@ -4,25 +4,35 @@
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.fuzzControll.mapper.MissionInfoMapper">
<resultMap type="com.example.fuzzControll.pojo.vo.MissionInfo" id="MissionInfo">
<resultMap type="com.example.fuzzControll.pojo.vo.MissionInfo" id="MissionInfoInDataBase">
<result property="id" column="id" />
<result property="missionId" column="missionId" />
<result property="tableId" column="tableId" />
<result property="createTime" column="createTime" />
<result property="missionName" column="missionName" />
<result property="state" column="state" />
<result property="runTime" column="runTime" />
</resultMap>
<resultMap type="com.example.fuzzControll.pojo.vo.MissionInfo" id="MissionInfoInVo">
<result property="id" column="id" />
<result property="missionId" column="missionId" />
<result property="createTime" column="createTime" />
<result property="missionName" column="missionName" />
<result property="stateName" column="state" />
<result property="runTime" column="runTime" />
</resultMap>
<sql id="selectMissionInfo">
select id, missionId,tableId, createTime,missionName from missionIdInfo
select id, missionId, createTime,missionName ,state,runTime from missionIdInfo
</sql>
<insert id="insertMission">
insert into missionIdInfo(missionId,tableId, createTime,missionName) values(#{missionId}, #{tableId},#{createTime}, #{missionName})
insert into missionIdInfo(missionId, tableId, createTime, missionName, state, runTime)
values (#{missionId}, #{tableId}, #{createTime}, #{missionName}, #{state}, #{runTime})
</insert>
<select id="selectByMissionId" resultMap="MissionInfo">
<select id="selectByMissionId" resultMap="MissionInfoInVo">
<include refid="selectMissionInfo"/>
where missionId = #{missionId}
and missionId = #{missionId}
</select>
<select id="selectMissionInfoList" resultType="com.example.fuzzControll.pojo.vo.MissionInfo">
<select id="selectMissionInfoList" resultMap="MissionInfoInVo">
<include refid="selectMissionInfo"/>
</select>
<select id="selectTopMissionId" resultType="java.lang.Integer">
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment