blob: c88d1da527db0b3a84d7154828be0183dbc9c87f [file] [log] [blame]
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +01001#!/usr/bin/env python3
2
3""" lava_rpc_connector.py:
4
5 class that extends xmlrpc in order to add LAVA specific functionality.
6 Used in managing communication with the back-end. """
7
8from __future__ import print_function
9
10__copyright__ = """
11/*
Xinyu Zhang82dab282022-10-09 16:33:19 +080012 * Copyright (c) 2018-2022, Arm Limited. All rights reserved.
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +010013 *
14 * SPDX-License-Identifier: BSD-3-Clause
15 *
16 */
17 """
Karl Zhang08681e62020-10-30 13:56:03 +080018
19__author__ = "tf-m@lists.trustedfirmware.org"
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +010020__project__ = "Trusted Firmware-M Open CI"
Xinyu Zhang06286a92021-07-22 14:00:51 +080021__version__ = "1.4.0"
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +010022
23import xmlrpc.client
24import time
Matthew Hartfb6fd362020-03-04 21:03:59 +000025import yaml
Matthew Hart4a4f1202020-06-12 15:52:46 +010026import requests
27import shutil
Paul Sokolovskyb06bf6f2022-12-27 13:46:24 +030028import logging
29
30
31_log = logging.getLogger("lavaci")
32
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +010033
34class LAVA_RPC_connector(xmlrpc.client.ServerProxy, object):
35
36 def __init__(self,
37 username,
38 token,
39 hostname,
40 rest_prefix="RPC2",
41 https=False):
42
43 # If user provides hostname with http/s prefix
44 if "://" in hostname:
45 htp_pre, hostname = hostname.split("://")
46 server_addr = "%s://%s:%s@%s/%s" % (htp_pre,
47 username,
48 token,
49 hostname,
50 rest_prefix)
51 self.server_url = "%s://%s" % (htp_pre, hostname)
52 else:
53 server_addr = "%s://%s:%s@%s/%s" % ("https" if https else "http",
54 username,
55 token,
56 hostname,
57 rest_prefix)
58 self.server_url = "%s://%s" % ("https" if https else "http",
59 hostname)
60
61 self.server_job_prefix = "%s/scheduler/job/%%s" % self.server_url
Milosz Wasilewski4c4190d2020-12-15 12:56:22 +000062 self.server_api = "%s/api/v0.2/" % self.server_url
Matthew Hart4a4f1202020-06-12 15:52:46 +010063 self.server_results_prefix = "%s/results/%%s" % self.server_url
Matthew Hartc6bbbf92020-08-19 14:12:07 +010064 self.token = token
65 self.username = username
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +010066 super(LAVA_RPC_connector, self).__init__(server_addr)
67
68 def _rpc_cmd_raw(self, cmd, params=None):
69 """ Run a remote comand and return the result. There is no constrain
70 check on the syntax of the command. """
71
72 cmd = "self.%s(%s)" % (cmd, params if params else "")
73 return eval(cmd)
74
75 def ls_cmd(self):
76 """ Return a list of supported commands """
77
78 print("\n".join(self.system.listMethods()))
79
Matthew Hart4a4f1202020-06-12 15:52:46 +010080 def fetch_file(self, url, out_file):
Matthew Hartc6bbbf92020-08-19 14:12:07 +010081 auth_params = {
82 'user': self.username,
83 'token': self.token
84 }
Matthew Hart4a4f1202020-06-12 15:52:46 +010085 try:
Matthew Hartc6bbbf92020-08-19 14:12:07 +010086 with requests.get(url, stream=True, params=auth_params) as r:
Matthew Hart4a4f1202020-06-12 15:52:46 +010087 with open(out_file, 'wb') as f:
88 shutil.copyfileobj(r.raw, f)
89 return(out_file)
90 except:
91 return(False)
92
93 def get_job_results(self, job_id, yaml_out_file):
94 results_url = "{}/yaml".format(self.server_results_prefix % job_id)
95 return(self.fetch_file(results_url, yaml_out_file))
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +010096
Matthew Hartfb6fd362020-03-04 21:03:59 +000097 def get_job_definition(self, job_id, yaml_out_file=None):
98 job_def = self.scheduler.jobs.definition(job_id)
99 if yaml_out_file:
100 with open(yaml_out_file, "w") as F:
101 F.write(str(job_def))
Paul Sokolovskyf2f385d2022-01-11 00:36:31 +0300102 def_o = yaml.safe_load(job_def)
Xinyu Zhang82dab282022-10-09 16:33:19 +0800103 return def_o
Matthew Hartfb6fd362020-03-04 21:03:59 +0000104
Matthew Hart4a4f1202020-06-12 15:52:46 +0100105 def get_job_log(self, job_id, target_out_file):
Milosz Wasilewski4c4190d2020-12-15 12:56:22 +0000106 auth_headers = {"Authorization": "Token %s" % self.token}
107 log_url = "{server_url}/jobs/{job_id}/logs/".format(
108 server_url=self.server_api, job_id=job_id
109 )
Fathi Boudrac10378c2021-01-21 18:25:19 +0100110 with requests.get(log_url, stream=True, headers=auth_headers) as r:
111 if r.status_code != 200:
112 print("{} - {}".format(log_url, r.status_code))
113 return
114 log_list = yaml.load(r.content, Loader=yaml.SafeLoader)
115 with open(target_out_file, "w") as target_out:
116 for line in log_list:
117 level = line["lvl"]
118 if (level == "target") or (level == "feedback"):
119 try:
120 target_out.write("{}\n".format(line["msg"]))
121 except UnicodeEncodeError:
122 msg = (
123 line["msg"]
124 .encode("ascii", errors="replace")
125 .decode("ascii")
126 )
127 target_out.write("{}\n".format(msg))
Matthew Hartfb6fd362020-03-04 21:03:59 +0000128
Matthew Hart4a4f1202020-06-12 15:52:46 +0100129 def get_job_config(self, job_id, config_out_file):
130 config_url = "{}/configuration".format(self.server_job_prefix % job_id)
131 self.fetch_file(config_url, config_out_file)
Matthew Hartfb6fd362020-03-04 21:03:59 +0000132
133 def get_job_info(self, job_id, yaml_out_file=None):
134 job_info = self.scheduler.jobs.show(job_id)
135 if yaml_out_file:
136 with open(yaml_out_file, "w") as F:
137 F.write(str(job_info))
138 return job_info
139
140 def get_error_reason(self, job_id):
Matthew Hart2c2688f2020-05-26 13:09:20 +0100141 try:
142 lava_res = self.results.get_testsuite_results_yaml(job_id, 'lava')
Paul Sokolovskyf2f385d2022-01-11 00:36:31 +0300143 results = yaml.safe_load(lava_res)
Matthew Hart2c2688f2020-05-26 13:09:20 +0100144 for test in results:
145 if test['name'] == 'job':
146 return(test.get('metadata', {}).get('error_type', ''))
147 except Exception:
148 return("Unknown")
Matthew Hartfb6fd362020-03-04 21:03:59 +0000149
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100150 def get_job_state(self, job_id):
151 return self.scheduler.job_state(job_id)["job_state"]
152
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100153 def cancel_job(self, job_id):
154 """ Cancell job with id=job_id. Returns True if successfull """
155
156 return self.scheduler.jobs.cancel(job_id)
157
158 def validate_job_yaml(self, job_definition, print_err=False):
159 """ Validate a job definition syntax. Returns true is server considers
160 the syntax valid """
161
162 try:
163 with open(job_definition) as F:
164 input_yaml = F.read()
165 self.scheduler.validate_yaml(input_yaml)
166 return True
167 except Exception as E:
168 if print_err:
169 print(E)
170 return False
171
Matthew Hart110e1dc2020-05-27 17:18:55 +0100172 def device_type_from_def(self, job_data):
Paul Sokolovskyf2f385d2022-01-11 00:36:31 +0300173 def_yaml = yaml.safe_load(job_data)
Matthew Hart110e1dc2020-05-27 17:18:55 +0100174 return(def_yaml['device_type'])
175
176 def has_device_type(self, job_data):
177 d_type = self.device_type_from_def(job_data)
178 all_d = self.scheduler.devices.list()
179 for device in all_d:
180 if device['type'] == d_type:
181 if device['health'] in ['Good', 'Unknown']:
182 return(True)
183 return(False)
184
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100185 def submit_job(self, job_definition):
186 """ Will submit a yaml definition pointed by job_definition after
187 validating it againist the remote backend. Returns resulting job id,
188 and server url for job"""
189
190 try:
191 if not self.validate_job_yaml(job_definition):
192 print("Served rejected job's syntax")
193 raise Exception("Invalid job")
194 with open(job_definition, "r") as F:
195 job_data = F.read()
196 except Exception as e:
197 print("Cannot submit invalid job. Check %s's content" %
198 job_definition)
199 print(e)
200 return None, None
Dean Bircha6ede7e2020-03-13 14:00:33 +0000201 try:
Dean Birch1d545c02020-05-29 14:09:21 +0100202 if self.has_device_type(job_data):
203 job_id = self.scheduler.submit_job(job_data)
204 job_url = self.server_job_prefix % job_id
205 return(job_id, job_url)
206 else:
207 raise Exception("No devices online with required device_type")
Dean Bircha6ede7e2020-03-13 14:00:33 +0000208 except Exception as e:
209 print(e)
210 return(None, None)
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100211
212 def resubmit_job(self, job_id):
213 """ Re-submit job with provided id. Returns resulting job id,
214 and server url for job"""
215
216 job_id = self.scheduler.resubmit_job(job_id)
217 job_url = self.server_job_prefix % job_id
218 return(job_id, job_url)
219
220 def block_wait_for_job(self, job_id, timeout, poll_freq=1):
221 """ Will block code execution and wait for the job to submit.
222 Returns job status on completion """
223
224 start_t = int(time.time())
225 while(True):
226 cur_t = int(time.time())
227 if cur_t - start_t >= timeout:
228 print("Breaking because of timeout")
229 break
230 # Check if the job is not running
Dean Arnoldf1169b92020-03-11 10:14:14 +0000231 cur_status = self.get_job_state(job_id)
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100232 # If in queue or running wait
Dean Arnoldc1d81b42020-03-11 15:56:36 +0000233 if cur_status not in ["Canceling","Finished"]:
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100234 time.sleep(poll_freq)
235 else:
236 break
Dean Arnoldc1d81b42020-03-11 15:56:36 +0000237 return self.scheduler.job_health(job_id)["job_health"]
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100238
Matthew Hartfb6fd362020-03-04 21:03:59 +0000239 def block_wait_for_jobs(self, job_ids, timeout, poll_freq=10):
240 """ Wait for multiple LAVA job ids to finish and return finished list """
241
242 start_t = int(time.time())
243 finished_jobs = {}
244 while(True):
245 cur_t = int(time.time())
246 if cur_t - start_t >= timeout:
247 print("Breaking because of timeout")
248 break
249 for job_id in job_ids:
Paul Sokolovskyfb298c62022-04-29 23:15:17 +0300250 if job_id in finished_jobs:
251 continue
Matthew Hartfb6fd362020-03-04 21:03:59 +0000252 # Check if the job is not running
253 cur_status = self.get_job_info(job_id)
254 # If in queue or running wait
255 if cur_status['state'] in ["Canceling","Finished"]:
256 cur_status['error_reason'] = self.get_error_reason(job_id)
257 finished_jobs[job_id] = cur_status
Paul Sokolovskyb06bf6f2022-12-27 13:46:24 +0300258 _log.info(
259 "Job %d finished in %ds with status: %s. Remaining: %d",
260 job_id, time.time() - start_t, cur_status['state'],
261 len(job_ids) - len(finished_jobs)
262 )
Matthew Hartfb6fd362020-03-04 21:03:59 +0000263 if len(job_ids) == len(finished_jobs):
264 break
265 else:
266 time.sleep(poll_freq)
267 if len(job_ids) == len(finished_jobs):
268 break
269 return finished_jobs
270
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100271 def test_credentials(self):
272 """ Attempt to querry the back-end and verify that the user provided
273 authentication is valid """
274
275 try:
276 self._rpc_cmd_raw("system.listMethods")
277 return True
278 except Exception as e:
279 print(e)
280 print("Credential validation failed")
281 return False
282
283
284if __name__ == "__main__":
285 pass