-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrigger_release.py
More file actions
executable file
·483 lines (404 loc) · 16.9 KB
/
trigger_release.py
File metadata and controls
executable file
·483 lines (404 loc) · 16.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
#!/usr/bin/env python3
"""
Script to trigger and monitor the GitHub release workflow.
Requires GH_TOKEN environment variable with permissions to trigger workflows.
"""
import os
import sys
import time
import logging
from datetime import datetime, timedelta, timezone
from typing import Optional, Dict, Any
import requests
class GitHubWorkflowMonitor:
"""Monitor and control GitHub Actions workflow runs."""
def __init__(self, token: str, owner: str, repo: str, logger: logging.Logger):
self.token = token
self.owner = owner
self.repo = repo
self.logger = logger
self.base_url = f"https://api.github.com/repos/{owner}/{repo}"
self.headers = {
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {token}",
"X-GitHub-Api-Version": "2022-11-28"
}
self.run_id: Optional[int] = None
self.run_url: Optional[str] = None
self.version_tag: Optional[str] = None
self.jobs_requiring_approval = [
"release_ref",
"release_qa",
"release_int"
]
self.approved_jobs = set()
self.completed_jobs = set()
self.last_status_time = time.time()
def trigger_workflow(
self, workflow_file: str, branch: str = "main"
) -> bool:
"""Trigger the workflow dispatch event."""
url = f"{self.base_url}/actions/workflows/{workflow_file}/dispatches"
data = {
"ref": branch
}
self.logger.info(
f"🚀 Triggering workflow '{workflow_file}' on branch '{branch}' "
f"for repo '{self.owner}/{self.repo}'..."
)
response = requests.post(url, headers=self.headers, json=data)
if response.status_code == 204:
self.logger.info("✅ Workflow triggered successfully")
return True
else:
self.logger.error(f"❌ Failed to trigger workflow: {response.status_code}")
self.logger.error(f"Response: {response.text}")
return False
def get_latest_run(
self, workflow_file: str, minutes: int = 2
) -> Optional[Dict[Any, Any]]:
"""Get the most recent workflow run started within the last N
minutes."""
url = f"{self.base_url}/actions/workflows/{workflow_file}/runs"
params = {
"per_page": 10,
"status": "in_progress"
}
response = requests.get(url, headers=self.headers, params=params)
if response.status_code != 200:
self.logger.error(f"❌ Failed to get workflow runs: {response.status_code}")
return None
data = response.json()
cutoff_time = datetime.now(timezone.utc) - timedelta(minutes=minutes)
for run in data.get("workflow_runs", []):
run_created = datetime.strptime(
run["created_at"], "%Y-%m-%dT%H:%M:%SZ"
).replace(tzinfo=timezone.utc)
if run_created >= cutoff_time:
return run
return None
def get_run_details(self, run_id: int) -> Optional[Dict[Any, Any]]:
"""Get details of a specific workflow run."""
url = f"{self.base_url}/actions/runs/{run_id}"
response = requests.get(url, headers=self.headers)
if response.status_code == 200:
return response.json()
return None
def get_run_jobs(self, run_id: int) -> Optional[Dict[Any, Any]]:
"""Get all jobs for a specific workflow run."""
url = f"{self.base_url}/actions/runs/{run_id}/jobs"
response = requests.get(url, headers=self.headers)
if response.status_code == 200:
return response.json()
return None
def get_pending_deployments(self, run_id: int) -> Optional[list]:
"""Get pending deployment reviews for a workflow run."""
url = f"{self.base_url}/actions/runs/{run_id}/pending_deployments"
response = requests.get(url, headers=self.headers)
if response.status_code == 200:
return response.json()
return None
def approve_deployment(self, run_id: int, environment_ids: list) -> bool:
"""Approve a pending deployment."""
url = f"{self.base_url}/actions/runs/{run_id}/pending_deployments"
data = {
"environment_ids": environment_ids,
"state": "approved",
"comment": "Auto-approved by trigger_release.py script"
}
response = requests.post(url, headers=self.headers, json=data)
if response.status_code == 200:
return True
else:
self.logger.warning(f"⚠️ Failed to approve deployment: {response.status_code}")
self.logger.warning(f"Response: {response.text}")
return False
def check_for_errors(
self, run_details: Dict[Any, Any], jobs_data: Dict[Any, Any]
) -> Optional[str]:
"""Check if any job has failed."""
if run_details.get("conclusion") == "failure":
return "Workflow run failed"
for job in jobs_data.get("jobs", []):
if job["conclusion"] == "failure":
return f"Job '{job['name']}' failed"
if job["conclusion"] == "cancelled":
return f"Job '{job['name']}' was cancelled"
return None
def monitor_and_approve(self) -> bool:
"""Main monitoring loop."""
self.logger.info(f"\n📊 Monitoring workflow run: {self.run_url}\n")
tag_release_completed = False
while True:
# Get current run details
run_details = self.get_run_details(self.run_id)
if not run_details:
self.logger.error("❌ Failed to get run details")
return False
jobs_data = self.get_run_jobs(self.run_id)
if not jobs_data:
self.logger.error("❌ Failed to get jobs data")
return False
# Check for errors
error = self.check_for_errors(run_details, jobs_data)
if error:
self.logger.error(f"\n❌ ERROR: {error}")
self.print_summary(error)
return False
# Track job statuses and detect changes
current_job_status = {}
for job in jobs_data.get("jobs", []):
job_name = job["name"]
job_status = job["status"]
job_conclusion = job.get("conclusion")
current_job_status[job_name] = (job_status, job_conclusion)
# Detect newly completed jobs
if (job_conclusion == "success" and
job_name not in self.completed_jobs):
self.completed_jobs.add(job_name)
self.logger.info(f"✅ Job completed: {job_name}")
# Check if tag_release completed
if job_name == "tag_release / tag_release" and not tag_release_completed:
tag_release_completed = True
# Try to extract version from subsequent
# jobs that use it
self._extract_version_from_jobs(jobs_data)
if self.version_tag:
self.logger.info(f"🏷️ Version tag: {self.version_tag}")
# Check for pending deployments
pending = self.get_pending_deployments(self.run_id)
if pending:
for deployment in pending:
env_name = deployment["environment"]["name"]
env_id = deployment["environment"]["id"]
# Check if this is release_prod
if env_name == "prod":
self.logger.info(
f"\n🛑 Reached production deployment for "
f"environment '{env_name}'"
)
self.print_summary(
"Stopped at production deployment"
)
return True
# Auto-approve other environments
job_name = f"release_{env_name}"
if (job_name in self.jobs_requiring_approval and
job_name not in self.approved_jobs):
self.logger.info(
f"✓ Approving deployment to environment "
f"'{env_name}'..."
)
if self.approve_deployment(self.run_id, [env_id]):
self.approved_jobs.add(job_name)
self.logger.info(f"✅ Approved: {job_name}")
else:
self.logger.warning(f"⚠️ Failed to approve: {job_name}")
# Check if workflow is complete
if run_details.get("status") == "completed":
if run_details.get("conclusion") == "success":
self.logger.info("\n✅ Workflow completed successfully")
self.print_summary("Completed successfully")
return True
else:
conclusion = run_details.get("conclusion", "unknown")
self.logger.warning(
f"\n⚠️ Workflow completed with conclusion: "
f"{conclusion}"
)
self.print_summary(
f"Completed with conclusion: {conclusion}"
)
return False
# Print status update every 30 seconds
current_time = time.time()
if current_time - self.last_status_time >= 30:
self.print_status_update(run_details, jobs_data)
self.last_status_time = current_time
# Sleep before next check
time.sleep(10)
def _extract_version_from_jobs(self, jobs_data: Dict[Any, Any]) -> None:
"""Try to extract version tag using GitHub CLI."""
if self.version_tag:
return # Already have it
try:
import subprocess
# Use gh CLI to get workflow run details with outputs
result = subprocess.run(
[
"gh", "run", "view", str(self.run_id),
"--repo", f"{self.owner}/{self.repo}",
"--json", "jobs"
],
capture_output=True,
text=True,
timeout=10
)
if result.returncode == 0:
import json
data = json.loads(result.stdout)
# Look through jobs for tag_release and
# find jobs that depend on it
for job in data.get("jobs", []):
# Look for jobs that use VERSION_NUMBER input
if "package_code" in job.get("name", ""):
# Try to extract from job name or check if
# we can get it from logs
# The version will be in the inputs but
# not directly available
pass
# Try alternative: check recent tags
tag_result = subprocess.run(
[
"gh", "api",
f"/repos/{self.owner}/{self.repo}/tags",
"--jq", ".[0].name"
],
capture_output=True,
text=True,
timeout=10
)
if tag_result.returncode == 0:
latest_tag = tag_result.stdout.strip()
if latest_tag:
self.version_tag = latest_tag
except Exception:
# If gh CLI fails, we'll just skip version extraction
pass
def print_status_update(
self, run_details: Dict[Any, Any], jobs_data: Dict[Any, Any]
) -> None:
"""Print a status update."""
status = run_details.get("status", "unknown")
# Count jobs by status
in_progress = sum(
1 for j in jobs_data.get("jobs", [])
if j["status"] == "in_progress"
)
completed = sum(
1 for j in jobs_data.get("jobs", [])
if j["status"] == "completed"
)
queued = sum(
1 for j in jobs_data.get("jobs", [])
if j["status"] == "queued"
)
self.logger.info(
f"⏳ Workflow still running... [Status: {status}, "
f"Jobs: {completed} completed, {in_progress} in progress, "
f"{queued} queued]"
)
def print_summary(self, outcome: str) -> None:
"""Print final summary."""
self.logger.info("\n" + "="*70)
self.logger.info(f"📋 RELEASE WORKFLOW SUMMARY {self.repo}")
self.logger.info("="*70)
self.logger.info(f"Workflow URL: {self.run_url}")
self.logger.info(f"Version Tag: {self.version_tag or 'N/A'}")
self.logger.info(f"Outcome: {outcome}")
approved = ', '.join(sorted(self.approved_jobs)) or 'None'
self.logger.info(f"Approved: {approved}")
self.logger.info("="*70 + "\n")
def setup_logger(repo_name: str) -> logging.Logger:
"""Set up logger to write to file and console."""
# Create logs directory if it doesn't exist
log_dir = "logs"
os.makedirs(log_dir, exist_ok=True)
# Create timestamp for log filename
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
# Sanitize repo name for filename (replace / with _)
safe_repo_name = repo_name.replace("/", "_")
# Create log filename
log_file = os.path.join(log_dir, f"release_{safe_repo_name}_{timestamp}.log")
# Create logger
logger = logging.getLogger("trigger_release")
logger.setLevel(logging.INFO)
# Remove any existing handlers
logger.handlers.clear()
# Create file handler
file_handler = logging.FileHandler(log_file, encoding='utf-8')
file_handler.setLevel(logging.INFO)
# Create console handler
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.INFO)
# Create formatters - console includes repo name, file doesn't need it
file_formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
console_formatter = logging.Formatter(
f'%(asctime)s - [{repo_name}] - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
# Add formatter to handlers
file_handler.setFormatter(file_formatter)
console_handler.setFormatter(console_formatter)
# Add handlers to logger
logger.addHandler(file_handler)
logger.addHandler(console_handler)
logger.info(f"Logging to file: {log_file}")
return logger
def main():
"""Main entry point."""
import argparse
parser = argparse.ArgumentParser(
description='Trigger and monitor GitHub release workflow'
)
parser.add_argument(
'repo',
help='Repository in format owner/repo '
'(e.g., NHSDigital/eps-vpc-resources)'
)
parser.add_argument(
'--workflow',
default='release.yml',
help='Workflow file name (default: release.yml)'
)
parser.add_argument(
'--branch',
default='main',
help='Branch to trigger workflow on (default: main)'
)
args = parser.parse_args()
# Parse repository
try:
owner, repo = args.repo.split('/')
except ValueError:
# Use basic print here since logger isn't set up yet
print(
"❌ Error: Repository must be in format owner/repo "
"(e.g., NHSDigital/eps-vpc-resources)"
)
sys.exit(1)
# Set up logger
logger = setup_logger(args.repo)
# Get GitHub token
token = os.environ.get("GH_TOKEN")
if not token:
logger.error("❌ Error: GH_TOKEN environment variable not set")
sys.exit(1)
workflow_file = args.workflow
branch = args.branch
# Create monitor instance
monitor = GitHubWorkflowMonitor(token, owner, repo, logger)
# Trigger the workflow
if not monitor.trigger_workflow(workflow_file, branch):
sys.exit(1)
# Wait a moment for the run to be created
logger.info("⏳ Waiting for workflow run to start...")
for attempt in range(12): # Try for up to 2 minutes
time.sleep(10)
run = monitor.get_latest_run(workflow_file, minutes=3)
if run:
monitor.run_id = run["id"]
monitor.run_url = run["html_url"]
logger.info(f"✅ Found workflow run: {monitor.run_url}")
break
if not monitor.run_id:
logger.error("❌ Failed to find the triggered workflow run")
sys.exit(1)
# Monitor and approve deployments
success = monitor.monitor_and_approve()
sys.exit(0 if success else 1)
if __name__ == "__main__":
main()