|
4 | 4 | import os
|
5 | 5 | import sys
|
6 | 6 | import tempfile
|
| 7 | +import psycopg2 |
7 | 8 | from pathlib import Path
|
| 9 | +from psycopg2 import sql |
8 | 10 |
|
9 | 11 | import requests
|
10 | 12 | from github import Github, Auth
|
|
13 | 15 | from workflow_rerun.log_analyzer import LogAnalyzer
|
14 | 16 | from workflow_rerun.log_collector import collect_logs_for_run
|
15 | 17 |
|
| 18 | +def record_rerun_to_db(repository_full_name: str, run_id: int, ticket_number: int): |
| 19 | + """Record the rerun event to the PostgreSQL database.""" |
| 20 | + |
| 21 | + db_username = os.environ.get('PGUSER') |
| 22 | + db_password = os.environ.get('PGPASSWORD') |
| 23 | + db_host = os.environ.get('PGHOST') |
| 24 | + db_database = os.environ.get('PGDATABASE') |
| 25 | + db_port = os.environ.get('PGPORT') |
| 26 | + conn = psycopg2.connect(host=db_host, |
| 27 | + port=db_port, |
| 28 | + user=db_username, |
| 29 | + password=db_password, |
| 30 | + database=db_database) |
| 31 | + |
| 32 | + cursor = None |
| 33 | + try: |
| 34 | + cursor = conn.cursor() |
| 35 | + |
| 36 | + insert_query = sql.SQL(""" |
| 37 | + INSERT INTO rerunner_stats (repository_full_name, run_id, ticket_number, rerun_at) |
| 38 | + VALUES (%s, %s, %s, NOW() AT TIME ZONE 'UTC') |
| 39 | + """) |
| 40 | + |
| 41 | + cursor.execute(insert_query, (repository_full_name, run_id, ticket_number)) |
| 42 | + conn.commit() |
| 43 | + |
| 44 | + LOGGER.info(f'Successfully recorded rerun to database: repo={repository_full_name}, ' |
| 45 | + f'run_id={run_id}, ticket={ticket_number}') |
| 46 | + |
| 47 | + except psycopg2.Error as e: |
| 48 | + LOGGER.error(f'Failed to record rerun to database: {e}') |
| 49 | + conn.rollback() |
| 50 | + raise |
| 51 | + finally: |
| 52 | + if cursor: |
| 53 | + cursor.close() |
| 54 | + conn.close() |
| 55 | + |
| 56 | + |
16 | 57 |
|
17 | 58 | if __name__ == '__main__':
|
18 | 59 |
|
|
60 | 101 | response = requests.post(url=f'https://api.github.com/repos/{repository_name}/actions/runs/{run_id}/rerun-failed-jobs',
|
61 | 102 | headers={'Authorization': f'Bearer {GITHUB_TOKEN}'})
|
62 | 103 | status = response.status_code == 201
|
63 |
| - |
| 104 | + |
64 | 105 | if status:
|
65 | 106 | LOGGER.info(f'RUN RETRIGGERED SUCCESSFULLY: {run.html_url}')
|
| 107 | + record_rerun_to_db(repository_name, run_id, |
| 108 | + log_analyzer.found_error_ticket) |
66 | 109 | else:
|
67 | 110 | LOGGER.info(f'RUN WAS NOT RETRIGGERED, SEE ABOVE')
|
68 | 111 |
|
69 |
| - # Needed to run a step after for statistics |
70 |
| - with open(file=os.environ['GITHUB_ENV'], |
71 |
| - mode='a') as fh: |
72 |
| - fh.write('PIPELINE_RETRIGGERED=true\n') |
73 |
| - fh.write(f'FOUND_ERROR_TICKET={log_analyzer.found_error_ticket}\n') |
74 |
| - |
75 | 112 | # "status" is True (which is 1) if everything is ok, False (which is 0) otherwise
|
76 | 113 | sys.exit(not status)
|
77 | 114 | else:
|
|
0 commit comments