wait_for_workflows.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. #!/usr/bin/env python3
  2. import os
  3. import json
  4. import requests
  5. import time
  6. import sys
  7. from datetime import datetime, timezone
  8. def wait_for_workflows_to_appear(github_token, repo, workflow_names, start_time, max_wait=300):
  9. """等待工作流出现在API中"""
  10. headers = {
  11. "Authorization": f"token {github_token}",
  12. "Accept": "application/vnd.github.v3+json"
  13. }
  14. print(f"Waiting for {len(workflow_names)} workflows to appear...")
  15. print(f"Start time: {start_time}")
  16. print(f"Max wait time: {max_wait} seconds")
  17. found_workflows = set()
  18. start_timestamp = time.time()
  19. while time.time() - start_timestamp < max_wait:
  20. all_found = True
  21. for workflow_name in workflow_names:
  22. if workflow_name in found_workflows:
  23. continue
  24. workflow_id = get_workflow_id(github_token, repo, workflow_name)
  25. if not workflow_id:
  26. print(f"Workflow {workflow_name} not found, skipping")
  27. found_workflows.add(workflow_name)
  28. continue
  29. # 检查是否有新的运行
  30. runs = get_recent_runs(github_token, repo, workflow_id, start_time)
  31. if runs:
  32. print(f"✓ Found new run for {workflow_name}: {runs[0]['id']}")
  33. found_workflows.add(workflow_name)
  34. else:
  35. print(f"⏳ Waiting for {workflow_name}...")
  36. all_found = False
  37. if all_found:
  38. print("✓ All workflows have started!")
  39. return True
  40. time.sleep(10) # 每10秒检查一次
  41. print("⚠️ Timeout waiting for workflows to appear")
  42. print(f"Found {len(found_workflows)} out of {len(workflow_names)} workflows")
  43. return False
  44. def get_workflow_id(github_token, repo, workflow_name):
  45. """获取工作流ID"""
  46. headers = {
  47. "Authorization": f"token {github_token}",
  48. "Accept": "application/vnd.github.v3+json"
  49. }
  50. url = f"https://api.github.com/repos/{repo}/actions/workflows"
  51. response = requests.get(url, headers=headers)
  52. if response.status_code == 200:
  53. workflows = response.json()["workflows"]
  54. for workflow in workflows:
  55. if workflow["name"] == workflow_name:
  56. return workflow["id"]
  57. return None
  58. def get_recent_runs(github_token, repo, workflow_id, start_time):
  59. """获取开始时间后的运行"""
  60. headers = {
  61. "Authorization": f"token {github_token}",
  62. "Accept": "application/vnd.github.v3+json"
  63. }
  64. url = f"https://api.github.com/repos/{repo}/actions/workflows/{workflow_id}/runs"
  65. params = {"per_page": 5}
  66. response = requests.get(url, headers=headers, params=params)
  67. if response.status_code != 200:
  68. return []
  69. runs = response.json()["workflow_runs"]
  70. start_time_dt = datetime.fromisoformat(start_time.replace('Z', '+00:00'))
  71. recent_runs = []
  72. for run in runs:
  73. run_time = datetime.fromisoformat(run["created_at"].replace('Z', '+00:00'))
  74. if run_time >= start_time_dt:
  75. recent_runs.append(run)
  76. return recent_runs
  77. def main():
  78. github_token = os.getenv("GITHUB_TOKEN")
  79. repo = os.getenv("GITHUB_REPOSITORY")
  80. workflows_json = os.getenv("TARGET_WORKFLOWS")
  81. start_time = sys.argv[1] if len(sys.argv) > 1 else datetime.now(timezone.utc).isoformat()
  82. if not all([github_token, repo, workflows_json]):
  83. raise ValueError("Missing required environment variables")
  84. workflows = json.loads(workflows_json)
  85. success = wait_for_workflows_to_appear(github_token, repo, workflows, start_time)
  86. if not success:
  87. print("Proceeding anyway, some workflows may not be detected...")
  88. if __name__ == "__main__":
  89. main()