TestServiceImpl.java 7.24 KB
package com.example.fuzzControll.service.impl;

import com.alibaba.fastjson2.JSON;
import com.example.fuzzControll.annotion.NeedCutBefore;
import com.example.fuzzControll.conf.AflnetProperties;
import com.example.fuzzControll.constents.CmdConstent;
import com.example.fuzzControll.domain.bo.FuzzParams;
import com.example.fuzzControll.exception.testException.AflnetException;
import com.example.fuzzControll.exception.testException.CmdException;
import com.example.fuzzControll.domain.bo.CmdStartParams;
import com.example.fuzzControll.service.AflnetPersistenceService;
import com.example.fuzzControll.service.FuzzParamsService;
import com.example.fuzzControll.service.TestService;
import com.example.fuzzControll.tools.file.FileTools;
import com.example.fuzzControll.tools.system.GlobalClass;
import com.example.fuzzControll.tools.test.JsonUtils;
import com.example.fuzzControll.tools.test.TestCmdTools;
import com.example.fuzzControll.tools.test.TestControlTools;
import com.example.fuzzControll.tools.system.SystemRunningParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Service("testService")
@Slf4j
public class TestServiceImpl implements TestService {

    @Autowired
    TestCmdTools cmdTools;
    @Autowired
    AflnetPersistenceService aflnetPersistenceService;

    @Autowired
    AflnetProperties aflnetProperties;
    @Autowired
    FuzzParamsService fuzzParamsService;

    //todo 不同服务不同端口
    @Override
    public void testStart(CmdStartParams cmdStartParams) throws AflnetException, CmdException {
        /*存入参数*/
        int missionId = GlobalClass.missionInfoMapper.selectTopMissionId() + 1;
        boolean flag = false;
        try {
//            flag = fuzzParamsService.saveFuzzParams(new FuzzParams(JSON.toJSONString(cmdStartParams), new Date(), missionId));
            System.out.println("flag = " + flag);
        } catch (Exception e) {
            log.error("Save fuzz error:{}", e.getMessage());
            throw new RuntimeException(e);
        }
        if (!flag) {
            log.error("Save fuzzParams failed!");
            throw new AflnetException("Save params error!");
        }
        /*拼接指令*/
        TestControlTools.setIsRunning(true);
        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";
        SystemRunningParams.aflnetData.put("aflnetName", outputFileName);
        log.info("The cmd is [{}]", finalCmd);
        /*执行指令*/
        System.out.println("testStart");
        cmdTools.runProgramCmd(finalCmd, outputFileName + ".zip");
    }

    @Override
    @NeedCutBefore(name = "aflnet", function = "stopBackup")//停止时完成数据入库
    public void testStop() {
        TestControlTools.setIsRunning(false);//指令终止 todo 后期需要考虑,发送终止指令停止测试
        SystemRunningParams.testTimeMessage.get("aflnet").put("end", System.currentTimeMillis());//指令停止时间
        log.info("Aflnet has been stopped ! ");
    }

    @Override
    public LinkedHashMap<String, String> getProcessInfo() {
        return SystemRunningParams.TestProgressMap;
    }

    @Override
    public void analyse(String codePath, String programPath) {
        String cmd = "gdb " + codePath + programPath + " " + codePath + "core";
        log.info("Replay cmd is {}", cmd);
        SystemRunningParams.ReplayResults = new ArrayList<>();
        try {
            SystemRunningParams.ReplayResults = cmdTools.runCmd(cmd, "replay");
        } catch (CmdException e) {
            log.error("Replay failed:{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<String> getReplayResult() {
        /*停止GDB*/
        SystemRunningParams.ReplayResults = new ArrayList<>();
        try {
            cmdTools.runCmd("pkill gdb", "getReplayResult-stopGdb");
        } catch (CmdException e) {
            log.error("StopGdb failed:{}", e.getMessage());
            throw new RuntimeException(e);
        }
        /*给程序停止并存放数据反应时间*/
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        /*读取文件内容到响应*/
//        FileTools fileTools = new FileTools();
//        List<String> result = null;
//        try {
//            result = fileTools.fileReadAndTranstoStringList("/usr/", "dump.txt");
//        } catch (Exception e) {
//            log.error("File read failed:{}", e.getMessage());
//            throw new RuntimeException(e);
//        }
        return SystemRunningParams.ReplayResults;
    }

    @Override
    public void replay(String targetServer, String targetServerCodePath, String targetServerPort, String protocol, String pathToCrash) {
        /*删除当前目录生成的dump文件*/
        try {
            List<String> temp = new ArrayList<String>();
            int m = 0;
            while (m <= 1) {
                temp = cmdTools.runCmdReturnError(CmdConstent.DELETE_FILE + targetServerCodePath + "core", "replay-removeFile");
                m++;
            }
            if (temp.stream().noneMatch(s -> s.contains("No such file or directory"))) {
                throw new RuntimeException("Remove failed!");
            }
        } catch (RuntimeException e) {
            log.error("File remove failed:{}", e.getMessage());
            throw new RuntimeException(e);
        }
        /*启动目标服务器,存在阻塞所以新开另外起线程*/
        SystemRunningParams.ReplayRunServerMessage = new ArrayList<>();
        int i = 0;
        while (i <= 1) {//两次保证服务器可以启动
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String runServerCmd = targetServerCodePath + targetServer + " " + targetServerPort;
                    log.info("Server start cmd is:[{}]", runServerCmd);
                    TestCmdTools cmdTools = new TestCmdTools();
                    cmdTools.runClogCmd(runServerCmd, SystemRunningParams.ReplayRunServerMessage, "replay-startServer");
                }
            }).start();
            i++;
        }
        /*异常重放,会自动引起服务器关闭*/
        try {//保证服务器成功启动
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        String crashCmd = "aflnet-replay" + " " + pathToCrash + " " + protocol + " " + targetServerPort;
        log.info("Replay crash cmd is:[{}]", crashCmd);
        cmdTools.runCmd(crashCmd, "replay-crash");
    }
}