diff --git a/.github/workflows/delete_old_runs.yml b/.github/workflows/delete_old_runs.yml new file mode 100644 index 0000000..c2436a7 --- /dev/null +++ b/.github/workflows/delete_old_runs.yml @@ -0,0 +1,82 @@ +# 工作流的名称 +name: DeleteOldRuns + +# 工作流运行的名称 +run-name: DeleteOldRuns + +# 指定此工作流的触发器 +on: + schedule: + - cron: '0 16 * * *' # 每天0点触发工作流(基于北京时间) + workflow_dispatch: # 可以手动执行 + +jobs: + # 检查成绩 + DeleteOldRuns: + name: DeleteOldRuns + + # 在最新版的Ubuntu系统上运行 + runs-on: ubuntu-latest + + steps: + # 使用GitHub Actions提供的动作来检出代码库 + - name: Checkout Repository + uses: actions/checkout@main + + # 配置Python环境 + - name: Set up Python + uses: actions/setup-python@main + with: + python-version: "*" + + - name: Install dependencies + run: | + # 使用pip安装项目的依赖项 + pip install requests + + - name: Get Connection + run: | + # 获取连接信息 + url="https://ifconfig.me/all" + response=$(curl -s -X GET "$url") + echo "$response" + + - name: Run main program + id: run_main_program + env: + GITHUB_ACTIONS: ${{github.actions}} + URL: ${{ secrets.URL }} + USERNAME: ${{ secrets.USERNAME }} + PASSWORD: ${{ secrets.PASSWORD }} + TOKEN: ${{ secrets.TOKEN }} + GITHUB_TOKEN: ${{ secrets.GHTOKEN }} + GITHUB_EVENT_NAME: ${{ github.event_name }} + GITHUB_TRIGGERING_ACTOR: ${{ github.triggering_actor }} + REPOSITORY_NAME: ${{ github.repository }} + GITHUB_SHA: ${{ github.sha }} + GITHUB_WORKFLOW: ${{ github.workflow }} + GITHUB_RUN_NUMBER: ${{ github.run_number }} + GITHUB_RUN_ID: ${{ github.run_id }} + run: | + # 运行主程序 + if [ -n "$GHTOKEN" ]; then + python delete_old_runs.py + export BEIJING_TIME="$(TZ='Asia/Shanghai' date +'%Y-%m-%d %H:%M:%S:%3N')" + echo "BEIJING_TIME=$BEIJING_TIME" >> $GITHUB_OUTPUT + echo "------" + fi + + # 方便通过截图快速定位到用户 + echo "Triggered By: $GITHUB_EVENT_NAME" + echo "Run By: $GITHUB_TRIGGERING_ACTOR" + echo "Repository Name: $REPOSITORY_NAME" + echo "Commit SHA: $GITHUB_SHA" + echo "Workflow Name: $GITHUB_WORKFLOW" + echo "Workflow Number: $GITHUB_RUN_NUMBER" + echo "Workflow ID: $GITHUB_RUN_ID" + echo "Beijing Time: $BEIJING_TIME" + + - name: Delete __pycache__ folder + run: | + # 删除__pycache__文件夹 + rm -rf __pycache__ \ No newline at end of file diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 90113de..ad69549 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -28,9 +28,6 @@ jobs: # 在最新版的Ubuntu系统上运行 runs-on: ubuntu-latest - outputs: - BEIJING_TIME: ${{ steps.run_main_program.outputs.BEIJING_TIME }} - steps: # 使用GitHub Actions提供的动作来检出代码库 - name: Checkout Repository diff --git a/delete_old_runs.py b/delete_old_runs.py new file mode 100644 index 0000000..a7befbd --- /dev/null +++ b/delete_old_runs.py @@ -0,0 +1,81 @@ +# 必要的依赖库 +import requests +from datetime import datetime, timedelta, timezone +from concurrent.futures import ThreadPoolExecutor +import os + + +class GitHubActionsManager: + def __init__(self, repo_url, token): + self.repo_url = repo_url # GitHub仓库URL + self.token = token # GitHub个人访问令牌 + self.runs_url = f"{self.repo_url}/actions/runs" # 获取运行记录的URL + self.current_time = datetime.now(timezone.utc) # 获取当前时间 + + def get_workflow_runs(self, url): + # 发送GET请求获取工作流运行记录 + response = requests.get(url, headers={"Authorization": f"token {self.token}"}) + if response.status_code == 200: # 如果请求成功 + return response.json()["workflow_runs"] # 返回运行记录列表 + else: # 如果请求失败 + print( + f"Failed to fetch runs from {url}. Status code: {response.status_code}" + ) # 打印错误信息 + return [] # 返回空列表 + + def delete_run(self, run_id): + delete_url = f"{self.runs_url}/{run_id}" # 构建删除运行记录的URL + # 发送DELETE请求删除指定ID的运行记录 + response = requests.delete( + delete_url, headers={"Authorization": f"token {self.token}"} + ) + if response.status_code == 204: # 如果删除成功 + print(f"Deleted run with ID {run_id}") # 打印删除成功的消息 + else: # 如果删除失败 + print( + f"Failed to delete run with ID {run_id}. Status code: {response.status_code}" + ) # 打印错误信息 + + def delete_old_runs(self, max_workers=10): + next_page = self.runs_url # 初始化下一页的URL为第一页 + while next_page: # 循环直到没有下一页 + print(beijing_time) # 打印时间 + # 发送GET请求获取一页工作流运行记录 + response = requests.get( + next_page, headers={"Authorization": f"token {self.token}"} + ) + if response.status_code == 200: # 如果请求成功 + data = response.json() # 将响应数据转换为JSON格式 + runs = data["workflow_runs"] # 获取运行记录列表 + next_page = response.links.get("next", {}).get("url") # 获取下一页的URL + + with ThreadPoolExecutor( + max_workers=max_workers + ) as executor: # 创建线程池 + for run in runs: # 遍历每条运行记录 + # 将运行记录的创建时间转换为UTC时间 + run_time = datetime.strptime( + run["created_at"], "%Y-%m-%dT%H:%M:%SZ" + ).replace(tzinfo=timezone.utc) + # 计算当前时间与运行记录创建时间的差值 + time_difference = self.current_time - run_time + if time_difference > timedelta(hours=24): # 如果差值超过24小时 + executor.submit( + self.delete_run, run["id"] + ) # 提交删除运行记录的任务 + else: # 如果请求失败 + print( + f"Failed to fetch runs. Status code: {response.status_code}" + ) # 打印错误信息 + break # 退出循环 + + +if __name__ == "__main__": + repository_name = os.environ.get("REPOSITORY_NAME") + github_token = os.environ.get("GITHUB_TOKEN") + beijing_time = os.environ.get("BEIJING_TIME") + repo_url = f"https://api.github.com/repos/{repository_name}" # GitHub仓库URL + token = f"{github_token}" # GitHub个人访问令牌 + + manager = GitHubActionsManager(repo_url, token) # 创建GitHubActionsManager实例 + manager.delete_old_runs() # 删除24小时前的运行记录