Spaces:
Paused
Paused
Update scheduler.py
Browse files123456789101112136 unmodified lines20212223242526272829306 unmodified lines373839404142434445461 unmodified line48495051525354555657582 unmodified lines6162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281 unmodified line1301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661 unmodified line1681691701711721731741751761771781791801811821831841851861871881891904 unmodified lines1951961971981992002016 unmodified lines2082092102112122132142152162171 unmodified line2192202212222232242252262272282292302312322332342352363 unmodified lines240241242243244245246247248249250251252253254255256257258259260261262263264265266import subprocessimport timeimport signalimport sysimport osfrom pathlib import Pathfrom datetime import datetimeimport threading # 用于可选的日志打印print(f"[{datetime.now()}] scheduler.py: Script execution started.", file=sys.stderr) # 打印到 stderr 确保能看到# --- 辅助函数 ---6 unmodified lines# 如果 include 文件存在且非空,则添加 -include 参数if include_path.exists() and include_path.stat().st_size > 0:command.extend(["-include", str(include_path)])print(f"[{datetime.now()}] Including forwarders from: {include_path}")else:print(f"[{datetime.now()}] Warning: Include file '{include_path}' not found or empty. Starting glider without extra forwarders.")print(f"[{datetime.now()}] Starting glider with command: {' '.join(command)}")try:# 使用 subprocess.PIPE 捕获输出以便调试process = subprocess.Popen(6 unmodified lines# 启动线程来打印 glider 的输出 (可选, 但推荐用于调试)threading.Thread(target=lambda: print_output(process.stdout, "Glider STDOUT"), daemon=True).start()threading.Thread(target=lambda: print_output(process.stderr, "Glider STDERR"), daemon=True).start()print(f"[{datetime.now()}] Glider process started (PID: {process.pid}).")return processexcept Exception as e:print(f"[{datetime.now()}] Error starting glider: {e}")return None# (可选) 打印子进程输出的辅助函数1 unmodified linetry:for line in iter(stream.readline, ''):if line:print(f"[{prefix}] {line.strip()}")except Exception as e:# 忽略 stream closed 错误,因为进程终止时这很正常if 'stream closed' not in str(e).lower():print(f"Error reading stream for {prefix}: {e}")# finally:# # 不在这里关闭 stream,让 Popen 自己管理# pass2 unmodified linesdef kill_glider(process):"""终止glider进程"""if process and process.poll() is None: # 检查进程是否仍在运行print(f"[{datetime.now()}] Terminating glider process (PID: {process.pid})...")try:# 先尝试 SIGTERMprocess.terminate()process.wait(timeout=5)print(f"[{datetime.now()}] Glider process terminated.")except subprocess.TimeoutExpired:print(f"[{datetime.now()}] Glider process did not terminate gracefully, killing (SIGKILL)...")process.kill()process.wait() # 等待 kill 完成print(f"[{datetime.now()}] Glider process killed.")except Exception as e:print(f"[{datetime.now()}] Error killing glider: {e}")elif process:# print(f"[{datetime.now()}] Glider process (PID: {process.pid}) already terminated.")pass # 进程已结束,无需操作else:# print(f"[{datetime.now()}] No active glider process to kill.")pass # 没有进程,无需操作def run_collector(collector_script_path):"""运行收集器脚本"""print(f"[{datetime.now()}] Running collector script: {collector_script_path}...")try:result = subprocess.run(["python", str(collector_script_path)],check=True,capture_output=True,text=True,encoding='utf-8',timeout=600 # 添加超时,例如 10 分钟)print(f"[{datetime.now()}] Collector ran successfully.")# print(f"Collector stdout:\n{result.stdout}") # (可选) 打印输出return Trueexcept subprocess.TimeoutExpired:print(f"[{datetime.now()}] Error: Collector script timed out.")return Falseexcept subprocess.CalledProcessError as e:print(f"[{datetime.now()}] Error running collector (return code {e.returncode}): {e}")print(f"Collector stdout:\n{e.stdout}")print(f"Collector stderr:\n{e.stderr}")return Falseexcept FileNotFoundError:print(f"[{datetime.now()}] Error: Collector script '{collector_script_path}' not found.")return Falsedef run_parser_and_save_output(parser_script_path, input_path, output_path):"""运行解析器脚本,捕获其标准输出并写入到文件"""print(f"[{datetime.now()}] Running parser script: {parser_script_path}...")if not input_path.exists():print(f"[{datetime.now()}] Error: Parser input file '{input_path}' not found.")return False# 命令是:python parse.py <输入yaml路径>command = ["python", str(parser_script_path), str(input_path)]print(f"[{datetime.now()}] Parser command: {' '.join(command)}")try:# 运行 parse.py 并捕获其标准输出result = subprocess.run(command,check=True, # 如果 parse.py 返回非 0 退出码,则抛出异常1 unmodified linetext=True, # 让 stdout/stderr 成为字符串encoding='utf-8' # 指定编码)# 将捕获到的 stdout 写入到输出文件print(f"[{datetime.now()}] Parser ran successfully. Writing output to '{output_path}'...")with open(output_path, 'w', encoding='utf-8') as f:f.write(result.stdout)# 检查文件是否成功写入且非空if output_path.exists() and output_path.stat().st_size > 0:print(f"[{datetime.now()}] Successfully wrote {output_path.stat().st_size} bytes to '{output_path}'.")return Trueelse:print(f"[{datetime.now()}] Warning: Output file '{output_path}' was created but is empty.")# 可以根据需要决定空文件是否算成功return True # 即使为空也认为解析成功,让 Glider 启动(可能没有代理)except subprocess.CalledProcessError as e:print(f"[{datetime.now()}] Error running parser (return code {e.returncode}): {e}")print(f"Parser stdout:\n{e.stdout}")print(f"Parser stderr:\n{e.stderr}")return Falseexcept FileNotFoundError:print(f"[{datetime.now()}] Error: Parser script '{parser_script_path}' not found.")return Falseexcept Exception as e:print(f"[{datetime.now()}] An unexpected error occurred during parsing or writing file: {e}")return False# --- 主执行逻辑 ---def main():print(f"[{datetime.now()}] scheduler.py: Entering main() function.", file=sys.stderr)current_dir = Path(__file__).parent.absolute() # /appglider_path = current_dir / "glider" / "glider"1 unmodified linecollector_script_path = current_dir / "run_collector.py"parser_script_path = current_dir / "parse.py"clash_yaml_path = current_dir / "aggregator" / "data" / "clash.yaml"# 新增:用于存放 parse.py 输出的 forward 规则的文件路径forwarders_conf_path = current_dir / "forwarders.conf"# 检查必要文件required_files = [glider_path, config_path, collector_script_path, parser_script_path]for f_path in required_files:if not f_path.exists():print(f"[{datetime.now()}] Error: Required file not found at {f_path}")sys.exit(1)glider_process = None# --- 清理函数 ---def cleanup(signum, frame):print(f"\n[{datetime.now()}] Received signal {signal.Signals(signum).name}. Cleaning up...")kill_glider(glider_process)print(f"[{datetime.now()}] Exiting.")sys.exit(0)signal.signal(signal.SIGTERM, cleanup)4 unmodified linesupdate_cycle_count = 0while True:update_cycle_count += 1print(f"\n===== [{datetime.now()}] Starting Update Cycle #{update_cycle_count} =====")# 1. 运行收集器collector_success = run_collector(collector_script_path)6 unmodified linesforwarders_conf_path)# 3. 无论解析是否成功(也许是空文件),都尝试重启 Glider# 如果解析失败,forwarders_conf_path 可能不��在或为空,# run_glider_with_includes 会处理这种情况。print(f"[{datetime.now()}] Restarting glider process...")kill_glider(glider_process) # 先停止旧的glider_process = run_glider_with_includes( # 启动新的glider_path,1 unmodified lineforwarders_conf_path # 传入包含 forward 规则的文件路径)if not glider_process:print(f"[{datetime.now()}] Error: Failed to restart glider process!")# 这里可以决定是退出还是继续等待下次循环# sys.exit(1)else:print(f"[{datetime.now()}] Glider process restarted successfully.")else:# 收集器失败,保留当前运行的 Glider 进程(如果有的话)print(f"[{datetime.now()}] Collector failed. Keeping current glider process running (if any).")# 检查 Glider 是否意外退出了,如果退出了尝试重启if glider_process and glider_process.poll() is not None:print(f"[{datetime.now()}] Detected that glider process was not running. Attempting restart...")glider_process = run_glider_with_includes(glider_path,config_path,3 unmodified lines# 等待下一次更新wait_time = 1800 # 30分钟print(f"[{datetime.now()}] Update cycle finished. Waiting {wait_time / 60:.1f} minutes until next cycle...")time.sleep(wait_time)except KeyboardInterrupt:# 用户按 Ctrl+C 时也会触发 SIGINT,由 cleanup 处理print(f"\n[{datetime.now()}] KeyboardInterrupt detected.")except Exception as e:print(f"\n[{datetime.now()}] An unexpected error occurred in the main loop: {e}")kill_glider(glider_process) # 尝试清理sys.exit(1) # 异常退出if __name__ == "__main__":print(f"[{datetime.now()}] scheduler.py: Entering __main__ block.", file=sys.stderr)# 添加一个初始运行,避免启动后长时间没有代理print(f"[{datetime.now()}] Performing initial run before starting the main loop...")if run_collector(Path(__file__).parent.absolute() / "run_collector.py"):run_parser_and_save_output(Path(__file__).parent.absolute() / "parse.py",Path(__file__).parent.absolute() / "aggregator" / "data" / "clash.yaml",Path(__file__).parent.absolute() / "forwarders.conf")# 无论初始运行是否成功,都启动主逻辑main()12345678910111213141516176 unmodified lines24252627282930313233346 unmodified lines41424344454647484950511 unmodified line535455565758596061626364652 unmodified lines68697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491 unmodified line1511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911 unmodified line1931941951961971981992002012022032042052062072082092102112122132144 unmodified lines2192202212222232242256 unmodified lines2322332342352362372382391 unmodified line2412422432442452462472482492502512522532542552563 unmodified lines260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332import subprocessimport timeimport signalimport sys # 确保导入 sysimport osfrom pathlib import Pathfrom datetime import datetimeimport threading # 用于可选的日志打印import traceback # 用于打印详细错误信息# 确保导入了你的 parse.py 可能需要的库,比如 yaml# import yaml # 如果你的其他脚本需要但这里没导入,可能会有问题# 在所有 import 之后,但在任何函数定义之前print(f"[{datetime.now()}] scheduler.py: Script execution started.", file=sys.stderr)# --- 辅助函数 ---6 unmodified lines# 如果 include 文件存在且非空,则添加 -include 参数if include_path.exists() and include_path.stat().st_size > 0:command.extend(["-include", str(include_path)])print(f"[{datetime.now()}] run_glider: Including forwarders from: {include_path}", file=sys.stderr)else:print(f"[{datetime.now()}] run_glider: Warning: Include file '{include_path}' not found or empty. Starting glider without extra forwarders.", file=sys.stderr)print(f"[{datetime.now()}] run_glider: Starting glider with command: {' '.join(command)}", file=sys.stderr)try:# 使用 subprocess.PIPE 捕获输出以便调试process = subprocess.Popen(6 unmodified lines# 启动线程来打印 glider 的输出 (可选, 但推荐用于调试)threading.Thread(target=lambda: print_output(process.stdout, "Glider STDOUT"), daemon=True).start()threading.Thread(target=lambda: print_output(process.stderr, "Glider STDERR"), daemon=True).start()print(f"[{datetime.now()}] run_glider: Glider process started (PID: {process.pid}).", file=sys.stderr)return processexcept Exception as e:print(f"[{datetime.now()}] run_glider: !!! ERROR starting glider: {e}", file=sys.stderr)traceback.print_exc(file=sys.stderr)return None# (可选) 打印子进程输出的辅助函数1 unmodified linetry:for line in iter(stream.readline, ''):if line:# 直接打印,避免双重时间戳和前缀混乱print(f"[{prefix}] {line.strip()}")sys.stdout.flush() # 确保日志实时输出except Exception as e:# 忽略 stream closed 错误,因为进程终止时这很正常if 'stream closed' not in str(e).lower() and 'valueerror' not in str(e).lower():print(f"Error reading stream for {prefix}: {e}", file=sys.stderr)# finally:# # 不在这里关闭 stream,让 Popen 自己管理# pass2 unmodified linesdef kill_glider(process):"""终止glider进程"""if process and process.poll() is None: # 检查进程是否仍在运行print(f"[{datetime.now()}] kill_glider: Terminating glider process (PID: {process.pid})...", file=sys.stderr)try:# 先尝试 SIGTERMprocess.terminate()process.wait(timeout=5)print(f"[{datetime.now()}] kill_glider: Glider process terminated.", file=sys.stderr)except subprocess.TimeoutExpired:print(f"[{datetime.now()}] kill_glider: Glider process did not terminate gracefully, killing (SIGKILL)...", file=sys.stderr)process.kill()process.wait() # 等待 kill 完成print(f"[{datetime.now()}] kill_glider: Glider process killed.", file=sys.stderr)except Exception as e:print(f"[{datetime.now()}] kill_glider: !!! ERROR killing glider: {e}", file=sys.stderr)traceback.print_exc(file=sys.stderr)elif process:# print(f"[{datetime.now()}] kill_glider: Glider process (PID: {process.pid}) already terminated.", file=sys.stderr)pass # 进程已结束,无需操作else:# print(f"[{datetime.now()}] kill_glider: No active glider process to kill.", file=sys.stderr)pass # 没有进程,无需操作def run_collector(collector_script_path):"""运行收集器脚本"""# 函数入口日志print(f"[{datetime.now()}] run_collector: Function called with script: {collector_script_path}", file=sys.stderr)try:# try 块入口日志print(f"[{datetime.now()}] run_collector: Executing subprocess.run for collector...", file=sys.stderr)result = subprocess.run(["python", str(collector_script_path)],check=True,capture_output=True,text=True,encoding='utf-8',timeout=600 # 保持超时设置 (10分钟))# try 块成功结束日志print(f"[{datetime.now()}] run_collector: Subprocess finished successfully.", file=sys.stderr)# print(f"Collector stdout:\n{result.stdout}") # 可以取消注释这个来看 collector 的输出return Trueexcept subprocess.TimeoutExpired:# 超时错误日志print(f"[{datetime.now()}] run_collector: !!! ERROR - Collector script timed out after 600 seconds.", file=sys.stderr)return Falseexcept subprocess.CalledProcessError as e:# 子进程返回错误码日志print(f"[{datetime.now()}] run_collector: !!! ERROR - Collector script failed (return code {e.returncode}).", file=sys.stderr)print(f"Collector stdout:\n{e.stdout}", file=sys.stderr) # 错误时的输出打印到 stderrprint(f"Collector stderr:\n{e.stderr}", file=sys.stderr) # 错误时的输出打印到 stderrreturn Falseexcept FileNotFoundError:# 文件未找到错误日志print(f"[{datetime.now()}] run_collector: !!! ERROR - Collector script '{collector_script_path}' not found.", file=sys.stderr)return Falseexcept Exception as e:# 其他意外错误日志print(f"[{datetime.now()}] run_collector: !!! UNEXPECTED ERROR: {e}", file=sys.stderr)traceback.print_exc(file=sys.stderr)return Falsedef run_parser_and_save_output(parser_script_path, input_path, output_path):"""运行解析器脚本,捕获其标准输出并写入到文件"""# 函数入口日志print(f"[{datetime.now()}] run_parser: Function called with parser={parser_script_path}, input={input_path}, output={output_path}", file=sys.stderr)if not input_path.exists():print(f"[{datetime.now()}] run_parser: !!! ERROR - Parser input file '{input_path}' not found.", file=sys.stderr)return False# 命令是:python parse.py <输入yaml路径>command = ["python", str(parser_script_path), str(input_path)]print(f"[{datetime.now()}] run_parser: Parser command: {' '.join(command)}", file=sys.stderr)try:# try 块入口日志print(f"[{datetime.now()}] run_parser: Executing subprocess.run for parser...", file=sys.stderr)result = subprocess.run(command,check=True, # 如果 parse.py 返回非 0 退出码,则抛出异常1 unmodified linetext=True, # 让 stdout/stderr 成为字符串encoding='utf-8' # 指定编码)# try 块成功结束日志print(f"[{datetime.now()}] run_parser: Subprocess finished successfully. Result stdout length: {len(result.stdout)}", file=sys.stderr)# 写入文件日志print(f"[{datetime.now()}] run_parser: Writing output to '{output_path}'...", file=sys.stderr)with open(output_path, 'w', encoding='utf-8') as f:f.write(result.stdout)print(f"[{datetime.now()}] run_parser: Finished writing to output file.", file=sys.stderr)if output_path.exists() and output_path.stat().st_size > 0:print(f"[{datetime.now()}] run_parser: Successfully wrote {output_path.stat().st_size} bytes to '{output_path}'.", file=sys.stderr)else:print(f"[{datetime.now()}] run_parser: Warning: Output file '{output_path}' was created but is empty.", file=sys.stderr)return True # 即使为空也认为解析成功except subprocess.CalledProcessError as e:# 子进程返回错误码日志print(f"[{datetime.now()}] run_parser: !!! ERROR - Parser script failed (return code {e.returncode}).", file=sys.stderr)print(f"Parser stdout:\n{e.stdout}", file=sys.stderr) # 错误时的输出打印到 stderrprint(f"Parser stderr:\n{e.stderr}", file=sys.stderr) # 错误时的输出打印到 stderrreturn Falseexcept FileNotFoundError:# 文件未找到错误日志print(f"[{datetime.now()}] run_parser: !!! ERROR - Parser script '{parser_script_path}' not found.", file=sys.stderr)return Falseexcept Exception as e:# 其他意外错误日志print(f"[{datetime.now()}] run_parser: !!! UNEXPECTED ERROR during parsing or writing file: {e}", file=sys.stderr)traceback.print_exc(file=sys.stderr)return False# --- 主执行逻辑 ---def main():# main 函数入口日志print(f"[{datetime.now()}] scheduler.py: Entering main() function.", file=sys.stderr)current_dir = Path(__file__).parent.absolute() # /appglider_path = current_dir / "glider" / "glider"1 unmodified linecollector_script_path = current_dir / "run_collector.py"parser_script_path = current_dir / "parse.py"clash_yaml_path = current_dir / "aggregator" / "data" / "clash.yaml"forwarders_conf_path = current_dir / "forwarders.conf" # 包含 forward 规则的文件# 检查 Glider 和脚本是否存在 (在 __main__ 块做似乎更合适)# required_files = [glider_path, config_path, collector_script_path, parser_script_path]# for f_path in required_files:# if not f_path.exists():# print(f"[{datetime.now()}] main: Error: Required file not found at {f_path}", file=sys.stderr)# sys.exit(1)glider_process = None# --- 清理函数 ---def cleanup(signum, frame):print(f"\n[{datetime.now()}] scheduler.py: Received signal {signal.Signals(signum).name}. Cleaning up...", file=sys.stderr)kill_glider(glider_process)print(f"[{datetime.now()}] scheduler.py: Exiting.", file=sys.stderr)sys.exit(0)signal.signal(signal.SIGTERM, cleanup)4 unmodified linesupdate_cycle_count = 0while True:update_cycle_count += 1print(f"\n===== [{datetime.now()}] Starting Update Cycle #{update_cycle_count} =====", file=sys.stderr)# 1. 运行收集器collector_success = run_collector(collector_script_path)6 unmodified linesforwarders_conf_path)# 3. 无论解析是否成功,都尝试重启 Gliderprint(f"[{datetime.now()}] main: Restarting glider process after update cycle...", file=sys.stderr)kill_glider(glider_process) # 先停止旧的glider_process = run_glider_with_includes( # 启动新的glider_path,1 unmodified lineforwarders_conf_path # 传入包含 forward 规则的文件路径)if not glider_process:print(f"[{datetime.now()}] main: !!! ERROR - Failed to restart glider process!", file=sys.stderr)else:print(f"[{datetime.now()}] main: Glider process restarted successfully.", file=sys.stderr)else:# 收集器失败,保留当前运行的 Glider 进程(如果有的话)print(f"[{datetime.now()}] main: Collector failed. Keeping current glider process running (if any).", file=sys.stderr)# 检查 Glider 是否意外退出了,如果退出了尝试重启if glider_process and glider_process.poll() is not None:print(f"[{datetime.now()}] main: Detected that glider process was not running. Attempting restart...", file=sys.stderr)glider_process = run_glider_with_includes(glider_path,config_path,3 unmodified lines# 等待下一次更新wait_time = 1800 # 30分钟print(f"[{datetime.now()}] main: Update cycle finished. Waiting {wait_time / 60:.1f} minutes until next cycle...", file=sys.stderr)time.sleep(wait_time)except KeyboardInterrupt:# 用户按 Ctrl+C 时也会触发 SIGINT,由 cleanup 处理print(f"\n[{datetime.now()}] scheduler.py: KeyboardInterrupt detected.", file=sys.stderr)except Exception as e:print(f"\n[{datetime.now()}] scheduler.py: !!! UNEXPECTED ERROR in the main loop: {e}", file=sys.stderr)traceback.print_exc(file=sys.stderr)kill_glider(glider_process) # 尝试清理sys.exit(1) # 异常退出if __name__ == "__main__":print(f"[{datetime.now()}] scheduler.py: Entering __main__ block.", file=sys.stderr)# 检查基本文件是否存在_current_dir = Path(__file__).parent.absolute()_required_paths = {"glider": _current_dir / "glider" / "glider","glider_config": _current_dir / "glider.conf","collector_script": _current_dir / "run_collector.py","parser_script": _current_dir / "parse.py"}missing_files = []for name, path in _required_paths.items():if not path.exists():missing_files.append(str(path))if missing_files:print(f"[{datetime.now()}] scheduler.py: !!! FATAL ERROR - Required file(s) not found:", file=sys.stderr)for mf in missing_files:print(f" - {mf}", file=sys.stderr)sys.exit(1)else:print(f"[{datetime.now()}] scheduler.py: All required files checked.", file=sys.stderr)# --- 初始运行 ---print(f"[{datetime.now()}] scheduler.py: Starting initial run...", file=sys.stderr)initial_collector_success = False # 初始化标志try:# 明确打印调用 Collectorprint(f"[{datetime.now()}] scheduler.py: Calling initial run_collector...", file=sys.stderr)collector_script = _required_paths["collector_script"]initial_collector_success = run_collector(collector_script) # 调用函数# 明确打印 Collector 调用结束print(f"[{datetime.now()}] scheduler.py: Initial run_collector finished. Success: {initial_collector_success}", file=sys.stderr)if initial_collector_success:# 明确打印调用 Parserprint(f"[{datetime.now()}] scheduler.py: Calling initial run_parser_and_save_output...", file=sys.stderr)parser_script = _required_paths["parser_script"]clash_yaml = _current_dir / "aggregator" / "data" / "clash.yaml"forwarders_conf = _current_dir / "forwarders.conf"parser_success = run_parser_and_save_output(parser_script, clash_yaml, forwarders_conf)# 明确打印 Parser 调用结束print(f"[{datetime.now()}] scheduler.py: Initial run_parser finished. Success: {parser_success}", file=sys.stderr)else:print(f"[{datetime.now()}] scheduler.py: Skipping initial parser run due to collector failure.", file=sys.stderr)except Exception as e:# 捕获初始运行中的任何意外错误print(f"[{datetime.now()}] scheduler.py: !!! UNEXPECTED ERROR during initial run: {e}", file=sys.stderr)traceback.print_exc(file=sys.stderr)# 明确打印初始运行逻辑结束,即将调用 main()print(f"[{datetime.now()}] scheduler.py: Initial run section finished. Proceeding to call main().", file=sys.stderr)# --- 启动主逻辑 ---main()
scheduler.py+144-78