blob: ec1191a3bd9c7589fa928294801b5a9b087e2170 [file] [log] [blame]
Matthew Hartfb6fd362020-03-04 21:03:59 +00001#!/usr/bin/env python3
2
3from __future__ import print_function
4
5__copyright__ = """
6/*
Xinyu Zhangaf63f902023-01-05 15:09:28 +08007 * Copyright (c) 2020-2023, Arm Limited. All rights reserved.
Matthew Hartfb6fd362020-03-04 21:03:59 +00008 *
9 * SPDX-License-Identifier: BSD-3-Clause
10 *
11 */
12 """
13
14"""
15Script for waiting for LAVA jobs and parsing the results
16"""
17
18import os
Matthew Hartfb6fd362020-03-04 21:03:59 +000019import time
20import yaml
21import argparse
Xinyu Zhangc8a670c2021-05-18 20:20:53 +080022import shutil
Paul Sokolovskya95abd92022-12-27 13:48:11 +030023import logging
Jianliang Shen418051d2023-08-21 12:01:11 +080024import json
Paul Sokolovsky7fd1bc52023-01-11 20:14:37 +030025from xmlrpc.client import ProtocolError
Matthew Hartfb6fd362020-03-04 21:03:59 +000026from jinja2 import Environment, FileSystemLoader
Matthew Hartfb6fd362020-03-04 21:03:59 +000027from lava_helper import test_lava_dispatch_credentials
Xinyu Zhangc918b6e2022-10-08 17:13:17 +080028from lava_submit_jobs import submit_lava_jobs
Paul Sokolovsky2512ec52022-03-04 00:15:39 +030029import codecov_helper
30
Matthew Hartfb6fd362020-03-04 21:03:59 +000031
Paul Sokolovskya95abd92022-12-27 13:48:11 +030032_log = logging.getLogger("lavaci")
33
34
Matthew Hartfb6fd362020-03-04 21:03:59 +000035def wait_for_jobs(user_args):
36 job_list = user_args.job_ids.split(",")
37 job_list = [int(x) for x in job_list if x != '']
38 lava = test_lava_dispatch_credentials(user_args)
Xinyu Zhangf2b7cbf2021-05-18 20:17:34 +080039 finished_jobs = get_finished_jobs(job_list, user_args, lava)
Xinyu Zhangc8a670c2021-05-18 20:20:53 +080040 resubmit_jobs = resubmit_failed_jobs(finished_jobs, user_args)
Paul Sokolovskyc87beee2022-04-30 08:50:47 +030041 if resubmit_jobs:
Paul Sokolovskyf3674562022-12-27 22:20:01 +030042 _log.info("Waiting for resubmitted jobs: %s", resubmit_jobs)
Paul Sokolovskyc87beee2022-04-30 08:50:47 +030043 finished_resubmit_jobs = get_finished_jobs(resubmit_jobs, user_args, lava)
44 finished_jobs.update(finished_resubmit_jobs)
Paul Sokolovsky451f67b2022-03-08 19:44:41 +030045 return finished_jobs
46
Paul Sokolovsky451f67b2022-03-08 19:44:41 +030047def process_finished_jobs(finished_jobs, user_args):
Xinyu Zhangf2b7cbf2021-05-18 20:17:34 +080048 print_lava_urls(finished_jobs, user_args)
Paul Sokolovsky451f67b2022-03-08 19:44:41 +030049 test_report(finished_jobs, user_args)
Xinyu Zhang82dab282022-10-09 16:33:19 +080050 job_links(finished_jobs, user_args)
Paul Sokolovsky2512ec52022-03-04 00:15:39 +030051 codecov_helper.coverage_reports(finished_jobs, user_args)
Xinyu Zhangf2b7cbf2021-05-18 20:17:34 +080052
53def get_finished_jobs(job_list, user_args, lava):
Paul Sokolovskya95abd92022-12-27 13:48:11 +030054 _log.info("Waiting for %d LAVA jobs", len(job_list))
Paul Sokolovsky697f9552022-05-05 10:44:27 +030055 finished_jobs = lava.block_wait_for_jobs(job_list, user_args.dispatch_timeout, 5)
Matthew Hartfb6fd362020-03-04 21:03:59 +000056 unfinished_jobs = [item for item in job_list if item not in finished_jobs]
57 for job in unfinished_jobs:
Xinyu Zhang7fefe5b2023-02-08 11:35:49 +080058 _log.info("Cancelling unfinished job %d because of timeout.", job)
Matthew Hartfb6fd362020-03-04 21:03:59 +000059 lava.cancel_job(job)
Xinyu Zhang7fefe5b2023-02-08 11:35:49 +080060 if len(unfinished_jobs) > 0:
61 _log.info("Job fails because some test jobs have been cancelled.")
Matthew Hartfb6fd362020-03-04 21:03:59 +000062 if user_args.artifacts_path:
63 for job, info in finished_jobs.items():
64 info['job_dir'] = os.path.join(user_args.artifacts_path, "{}_{}".format(str(job), info['description']))
65 finished_jobs[job] = info
66 finished_jobs = fetch_artifacts(finished_jobs, user_args, lava)
Xinyu Zhangf2b7cbf2021-05-18 20:17:34 +080067 return finished_jobs
Matthew Hartfb6fd362020-03-04 21:03:59 +000068
Xinyu Zhangc8a670c2021-05-18 20:20:53 +080069def resubmit_failed_jobs(jobs, user_args):
70 if not jobs:
71 return []
Xinyu Zhang4aca6d02021-05-31 11:43:32 +080072 time.sleep(2) # be friendly to LAVA
Xinyu Zhangc8a670c2021-05-18 20:20:53 +080073 failed_job = []
74 os.makedirs('failed_jobs', exist_ok=True)
75 for job_id, info in jobs.items():
76 if not (info['health'] == "Complete" and info['state'] == "Finished"):
Paul Sokolovskyb7a41a92022-12-28 18:06:45 +030077 _log.warning(
78 "Will resubmit job %d because of its state: %s, health: %s",
Paul Sokolovsky7fa6c9e2022-12-30 15:01:49 +030079 job_id, info["state"], info["health"]
Paul Sokolovskyb7a41a92022-12-28 18:06:45 +030080 )
Xinyu Zhangc8a670c2021-05-18 20:20:53 +080081 job_dir = info['job_dir']
82 def_path = os.path.join(job_dir, 'definition.yaml')
83 os.rename(def_path, 'failed_jobs/{}_definition.yaml'.format(job_id))
84 shutil.rmtree(job_dir)
85 failed_job.append(job_id)
86 for failed_job_id in failed_job:
87 jobs.pop(failed_job_id)
Xinyu Zhangc918b6e2022-10-08 17:13:17 +080088 resubmitted_jobs = submit_lava_jobs(user_args, job_dir='failed_jobs')
Xinyu Zhangc8a670c2021-05-18 20:20:53 +080089 resubmitted_jobs = [int(x) for x in resubmitted_jobs if x != '']
90 return resubmitted_jobs
91
Matthew Hartfb6fd362020-03-04 21:03:59 +000092def fetch_artifacts(jobs, user_args, lava):
93 if not user_args.artifacts_path:
94 return
95 for job_id, info in jobs.items():
96 job_dir = info['job_dir']
Paul Sokolovskydc8281a2022-12-27 21:54:42 +030097 t = time.time()
Paul Sokolovskyce546192023-01-03 21:28:08 +030098
Paul Sokolovsky970c4cc2023-06-05 22:13:29 +030099 retry_delay = 3
Paul Sokolovskyce546192023-01-03 21:28:08 +0300100 for retry in range(3, 0, -1):
101 try:
102 os.makedirs(job_dir, exist_ok=True)
103 def_path = os.path.join(job_dir, 'definition.yaml')
104 target_log = os.path.join(job_dir, 'target_log.txt')
105 config = os.path.join(job_dir, 'config.tar.bz2')
106 results_file = os.path.join(job_dir, 'results.yaml')
107 definition = lava.get_job_definition(job_id, def_path)
108 jobs[job_id]['metadata'] = definition.get('metadata', [])
109 time.sleep(0.2) # be friendly to LAVA
110 lava.get_job_log(job_id, target_log)
111 time.sleep(0.2)
112 lava.get_job_config(job_id, config)
113 time.sleep(0.2)
114 lava.get_job_results(job_id, results_file)
115 break
Paul Sokolovskyd5c8c812023-04-20 22:23:17 +0300116 except (ProtocolError, IOError, yaml.error.YAMLError) as e:
Paul Sokolovskyce546192023-01-03 21:28:08 +0300117 if retry == 1:
118 raise
119 else:
Paul Sokolovskyd615c932024-03-25 12:01:07 +0700120 _log.warning("fetch_artifacts(%s): Error %r occurred, retrying", job_id, e)
Paul Sokolovsky970c4cc2023-06-05 22:13:29 +0300121 time.sleep(retry_delay)
122 retry_delay *= 2
Paul Sokolovskyce546192023-01-03 21:28:08 +0300123
Paul Sokolovskyd615c932024-03-25 12:01:07 +0700124 _log.info("Fetched artifacts for job %s in %ds", job_id, time.time() - t)
Paul Sokolovskyc2d6d882022-02-25 19:11:18 +0300125 codecov_helper.extract_trace_data(target_log, job_dir)
Matthew Hartfb6fd362020-03-04 21:03:59 +0000126 return(jobs)
127
128
129def lava_id_to_url(id, user_args):
130 return "{}/scheduler/job/{}".format(user_args.lava_url, id)
131
Xinyu Zhang97ee3fd2020-12-14 14:45:06 +0800132def job_links(jobs, user_args):
133 job_links = ""
134 for job, info in jobs.items():
Xinyu Zhang82dab282022-10-09 16:33:19 +0800135 job_links += "\nLAVA Test Config:\n"
136 job_links += "Config Name: {}\n".format(info['metadata']['build_name'])
137 job_links += "Test Result: {}\n".format(info['result'])
138 job_links += "Device Type: {}\n".format(info['metadata']['device_type'])
Xinyu Zhang97ee3fd2020-12-14 14:45:06 +0800139 job_links += "Build link: {}\n".format(info['metadata']['build_job_url'])
Xinyu Zhang78c146a2022-09-05 19:06:40 +0800140 job_links += "LAVA link: {}\n".format(lava_id_to_url(job, user_args))
Xinyu Zhang82dab282022-10-09 16:33:19 +0800141 job_links += "TFM LOG: {}artifact/{}/target_log.txt\n".format(os.getenv("BUILD_URL"), info['job_dir'])
Jianliang Shen48704152023-10-17 17:06:00 +0800142
143 # Save job information to share folder.
144 if os.getenv('JOB_NAME') == 'tf-m-nightly-performance':
145 with open(os.path.join(os.getenv('SHARE_FOLDER'), 'performance_config.txt'), 'a') as f:
146 f.write(info['metadata']['build_name'] + ' ' + info['job_dir'] + '\n')
147
Xinyu Zhang97ee3fd2020-12-14 14:45:06 +0800148 print(job_links)
149
Matthew Hartfb6fd362020-03-04 21:03:59 +0000150def remove_lava_dupes(results):
151 for result in results:
152 if result['result'] != 'pass':
153 if result['suite'] == "lava":
154 for other in [x for x in results if x != result]:
155 if other['name'] == result['name']:
156 if other['result'] == 'pass':
157 results.remove(result)
158 return(results)
159
Paul Sokolovsky451f67b2022-03-08 19:44:41 +0300160def test_report(jobs, user_args):
Matthew Hartfb6fd362020-03-04 21:03:59 +0000161 # parsing of test results is WIP
162 fail_j = []
163 jinja_data = []
164 for job, info in jobs.items():
Xinyu Zhang0f78e7a2022-10-17 13:55:52 +0800165 info['result'] = 'SUCCESS'
Xinyu Zhang82dab282022-10-09 16:33:19 +0800166 if info['health'] != 'Complete':
Xinyu Zhang0f78e7a2022-10-17 13:55:52 +0800167 info['result'] = 'FAILURE'
Xinyu Zhang82dab282022-10-09 16:33:19 +0800168 fail_j.append(job)
169 continue
Matthew Hart4a4f1202020-06-12 15:52:46 +0100170 results_file = os.path.join(info['job_dir'], 'results.yaml')
171 if not os.path.exists(results_file) or (os.path.getsize(results_file) == 0):
Xinyu Zhang0f78e7a2022-10-17 13:55:52 +0800172 info['result'] = 'FAILURE'
Matthew Hart4a4f1202020-06-12 15:52:46 +0100173 fail_j.append(job)
174 continue
175 with open(results_file, "r") as F:
176 res_data = F.read()
Paul Sokolovskyf2f385d2022-01-11 00:36:31 +0300177 results = yaml.safe_load(res_data)
Paul Sokolovsky07f6dfb2022-07-15 12:26:24 +0300178 non_lava_results = [x for x in results if x['suite'] != 'lava' or x['name'] == 'lava-test-monitor']
Matthew Hartfb6fd362020-03-04 21:03:59 +0000179 info['lava_url'] = lava_id_to_url(job, user_args)
Arthur She38d5f5a2022-09-02 17:32:14 -0700180 info['artifacts_dir'] = info['job_dir']
Matthew Hartfb6fd362020-03-04 21:03:59 +0000181 jinja_data.append({job: [info, non_lava_results]})
182 for result in non_lava_results:
Paul Sokolovsky58f00de2022-02-01 00:26:32 +0300183 if result['result'] == 'fail':
Xinyu Zhang0f78e7a2022-10-17 13:55:52 +0800184 info['result'] = 'FAILURE'
Matthew Hartfb6fd362020-03-04 21:03:59 +0000185 fail_j.append(job) if job not in fail_j else fail_j
186 time.sleep(0.5) # be friendly to LAVA
Matthew Hartfb6fd362020-03-04 21:03:59 +0000187 data = {}
188 data['jobs'] = jinja_data
189 render_jinja(data)
190
191def render_jinja(data):
192 work_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), "jinja2_templates")
193 template_loader = FileSystemLoader(searchpath=work_dir)
194 template_env = Environment(loader=template_loader)
195 html = template_env.get_template("test_summary.jinja2").render(data)
196 csv = template_env.get_template("test_summary_csv.jinja2").render(data)
197 with open('test_summary.html', "w") as F:
198 F.write(html)
199 with open('test_summary.csv', "w") as F:
200 F.write(csv)
201
202def print_lava_urls(jobs, user_args):
203 output = [lava_id_to_url(x, user_args) for x in jobs]
Xinyu Zhang78c146a2022-09-05 19:06:40 +0800204 info_print("LAVA jobs triggered for this build: {}".format(output))
Matthew Hartfb6fd362020-03-04 21:03:59 +0000205
206
Xinyu Zhang78c146a2022-09-05 19:06:40 +0800207def info_print(line, silent=True):
208 if not silent:
209 print("INFO: {}".format(line))
Matthew Hartfb6fd362020-03-04 21:03:59 +0000210
Paul Sokolovskyde25e1f2023-01-02 14:29:21 +0300211# WARNING: Setting this to >1 is a last resort, temporary stop-gap measure,
212# which will overload LAVA and jeopardize stability of the entire TF CI.
213INEFFICIENT_RETRIES = 1
214
215
Matthew Hartfb6fd362020-03-04 21:03:59 +0000216def main(user_args):
217 """ Main logic """
Paul Sokolovskyde25e1f2023-01-02 14:29:21 +0300218 for try_time in range(INEFFICIENT_RETRIES):
Xinyu Zhang3e8f6602021-04-28 10:57:32 +0800219 try:
Paul Sokolovsky451f67b2022-03-08 19:44:41 +0300220 finished_jobs = wait_for_jobs(user_args)
Xinyu Zhang3e8f6602021-04-28 10:57:32 +0800221 break
222 except Exception as e:
Paul Sokolovskyde25e1f2023-01-02 14:29:21 +0300223 if try_time < INEFFICIENT_RETRIES - 1:
Paul Sokolovskyf3674562022-12-27 22:20:01 +0300224 _log.exception("Exception in wait_for_jobs")
225 _log.info("Will try to get LAVA jobs again, this was try: %d", try_time)
Xinyu Zhang3e8f6602021-04-28 10:57:32 +0800226 else:
227 raise e
Paul Sokolovsky451f67b2022-03-08 19:44:41 +0300228 process_finished_jobs(finished_jobs, user_args)
Xinyu Zhangaf63f902023-01-05 15:09:28 +0800229 if len(finished_jobs) < len(user_args.job_ids.split(",")):
230 raise Exception("Some LAVA jobs cancelled.")
Matthew Hartfb6fd362020-03-04 21:03:59 +0000231
232def get_cmd_args():
233 """ Parse command line arguments """
234
235 # Parse command line arguments to override config
236 parser = argparse.ArgumentParser(description="Lava Wait Jobs")
237 cmdargs = parser.add_argument_group("Lava Wait Jobs")
238
239 # Configuration control
240 cmdargs.add_argument(
241 "--lava-url", dest="lava_url", action="store", help="LAVA lab URL (without RPC2)"
242 )
243 cmdargs.add_argument(
244 "--job-ids", dest="job_ids", action="store", required=True, help="Comma separated list of job IDS"
245 )
246 cmdargs.add_argument(
Xinyu Zhangf2b7cbf2021-05-18 20:17:34 +0800247 "--lava-token", dest="lava_token", action="store", help="LAVA auth token"
Matthew Hartfb6fd362020-03-04 21:03:59 +0000248 )
249 cmdargs.add_argument(
Xinyu Zhangf2b7cbf2021-05-18 20:17:34 +0800250 "--lava-user", dest="lava_user", action="store", help="LAVA username"
Matthew Hartfb6fd362020-03-04 21:03:59 +0000251 )
252 cmdargs.add_argument(
253 "--use-env", dest="token_from_env", action="store_true", default=False, help="Use LAVA auth info from environment"
254 )
255 cmdargs.add_argument(
256 "--lava-timeout", dest="dispatch_timeout", action="store", type=int, default=3600, help="Time in seconds to wait for all jobs"
257 )
258 cmdargs.add_argument(
259 "--artifacts-path", dest="artifacts_path", action="store", help="Download LAVA artifacts to this directory"
260 )
261 return parser.parse_args()
262
263
264if __name__ == "__main__":
Paul Sokolovskya95abd92022-12-27 13:48:11 +0300265 logging.basicConfig(level=logging.INFO)
Matthew Hartfb6fd362020-03-04 21:03:59 +0000266 main(get_cmd_args())