| 68 | |
| 69 | |
| 70 | class LocalCountLine(object): |
| 71 | def __init__(self, task_request): |
| 72 | self._params = task_request["task_params"] |
| 73 | self._task_dir = task_request["task_dir"] |
| 74 | self._result_filepath = os.path.join(self._task_dir, "codeline_data.json") |
| 75 | self._thread_event = threading.Event() |
| 76 | |
| 77 | def start_thread(self): |
| 78 | """ |
| 79 | 启动代码行统计线程 |
| 80 | :return: |
| 81 | """ |
| 82 | # 启动一个线程,统计代码行 |
| 83 | self._thread_event.set() |
| 84 | count_line_tread = CountLineThread(self._thread_event, self._params, self._task_dir, self._result_filepath) |
| 85 | count_line_tread.start() |
| 86 | |
| 87 | def get_result(self): |
| 88 | """ |
| 89 | 获取代码行统计结果 |
| 90 | :return: |
| 91 | """ |
| 92 | LogPrinter.info("Get code line data...") |
| 93 | max_wait_time = 60 * 5 # 超时限制 5 min |
| 94 | sleep_interval = 10 # 每10秒判断一次 |
| 95 | count_time = 0 # 计时器 |
| 96 | |
| 97 | stat_result = None |
| 98 | while self._thread_event.is_set(): |
| 99 | LogPrinter.info("代码统计任务仍在执行,等待任务结束...(等待超时5min)") |
| 100 | time.sleep(sleep_interval) |
| 101 | count_time += sleep_interval |
| 102 | # 如果累计时间大于等于日志打印间隔,打印日志,并重置累计时间 |
| 103 | if count_time >= max_wait_time: |
| 104 | LogPrinter.info("代码行统计超时,不再等待统计结果...") |
| 105 | self._thread_event.clear() # 中止掉代码统计任务线程 |
| 106 | # scc进程可能未正常退出,增加杀进程逻辑 |
| 107 | self.kill_scc_process() |
| 108 | break |
| 109 | |
| 110 | if os.path.exists(self._result_filepath): |
| 111 | with open(self._result_filepath, 'r') as fp: |
| 112 | stat_result = json.load(fp) |
| 113 | if stat_result: |
| 114 | LogPrinter.info(f"本次分析代码行数: {stat_result.get('filtered_total_line_num')}") |
| 115 | LogPrinter.info(f"全量代码行数: {stat_result.get('total_line_num')}") |
| 116 | else: |
| 117 | LogPrinter.warning("%s结果文件不存在,未获取到代码行统计数据." % self._result_filepath) |
| 118 | |
| 119 | return stat_result |
| 120 | |
| 121 | def kill_scc_process(self): |
| 122 | scc_workdir = PathMgr().format_path(self._task_dir) |
| 123 | pids = psutil.pids() |
| 124 | for pid in pids: |
| 125 | try: |
| 126 | # 运行时候可能刚好有个进程退出,导致出现找不到进程错误 |
| 127 | # 2020/4/28 windows的进程命令不一样,并且杀进程时候不一定三个子进程已经起起来 |