blob: d07a58d82c4ed4519766a42a2d7cd95d45a98067 [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/*
Fathi Boudrac10378c2021-01-21 18:25:19 +010012 * Copyright (c) 2018-2021, 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
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +010028
29class LAVA_RPC_connector(xmlrpc.client.ServerProxy, object):
30
31 def __init__(self,
32 username,
33 token,
34 hostname,
35 rest_prefix="RPC2",
36 https=False):
37
38 # If user provides hostname with http/s prefix
39 if "://" in hostname:
40 htp_pre, hostname = hostname.split("://")
41 server_addr = "%s://%s:%s@%s/%s" % (htp_pre,
42 username,
43 token,
44 hostname,
45 rest_prefix)
46 self.server_url = "%s://%s" % (htp_pre, hostname)
47 else:
48 server_addr = "%s://%s:%s@%s/%s" % ("https" if https else "http",
49 username,
50 token,
51 hostname,
52 rest_prefix)
53 self.server_url = "%s://%s" % ("https" if https else "http",
54 hostname)
55
56 self.server_job_prefix = "%s/scheduler/job/%%s" % self.server_url
Milosz Wasilewski4c4190d2020-12-15 12:56:22 +000057 self.server_api = "%s/api/v0.2/" % self.server_url
Matthew Hart4a4f1202020-06-12 15:52:46 +010058 self.server_results_prefix = "%s/results/%%s" % self.server_url
Matthew Hartc6bbbf92020-08-19 14:12:07 +010059 self.token = token
60 self.username = username
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +010061 super(LAVA_RPC_connector, self).__init__(server_addr)
62
63 def _rpc_cmd_raw(self, cmd, params=None):
64 """ Run a remote comand and return the result. There is no constrain
65 check on the syntax of the command. """
66
67 cmd = "self.%s(%s)" % (cmd, params if params else "")
68 return eval(cmd)
69
70 def ls_cmd(self):
71 """ Return a list of supported commands """
72
73 print("\n".join(self.system.listMethods()))
74
Matthew Hart4a4f1202020-06-12 15:52:46 +010075 def fetch_file(self, url, out_file):
Matthew Hartc6bbbf92020-08-19 14:12:07 +010076 auth_params = {
77 'user': self.username,
78 'token': self.token
79 }
Matthew Hart4a4f1202020-06-12 15:52:46 +010080 try:
Matthew Hartc6bbbf92020-08-19 14:12:07 +010081 with requests.get(url, stream=True, params=auth_params) as r:
Matthew Hart4a4f1202020-06-12 15:52:46 +010082 with open(out_file, 'wb') as f:
83 shutil.copyfileobj(r.raw, f)
84 return(out_file)
85 except:
86 return(False)
87
88 def get_job_results(self, job_id, yaml_out_file):
89 results_url = "{}/yaml".format(self.server_results_prefix % job_id)
90 return(self.fetch_file(results_url, yaml_out_file))
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +010091
Matthew Hartfb6fd362020-03-04 21:03:59 +000092 def get_job_definition(self, job_id, yaml_out_file=None):
93 job_def = self.scheduler.jobs.definition(job_id)
94 if yaml_out_file:
95 with open(yaml_out_file, "w") as F:
96 F.write(str(job_def))
Paul Sokolovskyf2f385d2022-01-11 00:36:31 +030097 def_o = yaml.safe_load(job_def)
Matthew Hartfb6fd362020-03-04 21:03:59 +000098 return job_def, def_o.get('metadata', [])
99
Matthew Hart4a4f1202020-06-12 15:52:46 +0100100 def get_job_log(self, job_id, target_out_file):
Milosz Wasilewski4c4190d2020-12-15 12:56:22 +0000101 auth_headers = {"Authorization": "Token %s" % self.token}
102 log_url = "{server_url}/jobs/{job_id}/logs/".format(
103 server_url=self.server_api, job_id=job_id
104 )
Fathi Boudrac10378c2021-01-21 18:25:19 +0100105 with requests.get(log_url, stream=True, headers=auth_headers) as r:
106 if r.status_code != 200:
107 print("{} - {}".format(log_url, r.status_code))
108 return
109 log_list = yaml.load(r.content, Loader=yaml.SafeLoader)
110 with open(target_out_file, "w") as target_out:
111 for line in log_list:
112 level = line["lvl"]
113 if (level == "target") or (level == "feedback"):
114 try:
115 target_out.write("{}\n".format(line["msg"]))
116 except UnicodeEncodeError:
117 msg = (
118 line["msg"]
119 .encode("ascii", errors="replace")
120 .decode("ascii")
121 )
122 target_out.write("{}\n".format(msg))
Matthew Hartfb6fd362020-03-04 21:03:59 +0000123
Matthew Hart4a4f1202020-06-12 15:52:46 +0100124 def get_job_config(self, job_id, config_out_file):
125 config_url = "{}/configuration".format(self.server_job_prefix % job_id)
126 self.fetch_file(config_url, config_out_file)
Matthew Hartfb6fd362020-03-04 21:03:59 +0000127
128 def get_job_info(self, job_id, yaml_out_file=None):
129 job_info = self.scheduler.jobs.show(job_id)
130 if yaml_out_file:
131 with open(yaml_out_file, "w") as F:
132 F.write(str(job_info))
133 return job_info
134
135 def get_error_reason(self, job_id):
Matthew Hart2c2688f2020-05-26 13:09:20 +0100136 try:
137 lava_res = self.results.get_testsuite_results_yaml(job_id, 'lava')
Paul Sokolovskyf2f385d2022-01-11 00:36:31 +0300138 results = yaml.safe_load(lava_res)
Matthew Hart2c2688f2020-05-26 13:09:20 +0100139 for test in results:
140 if test['name'] == 'job':
141 return(test.get('metadata', {}).get('error_type', ''))
142 except Exception:
143 return("Unknown")
Matthew Hartfb6fd362020-03-04 21:03:59 +0000144
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100145 def get_job_state(self, job_id):
146 return self.scheduler.job_state(job_id)["job_state"]
147
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100148 def cancel_job(self, job_id):
149 """ Cancell job with id=job_id. Returns True if successfull """
150
151 return self.scheduler.jobs.cancel(job_id)
152
153 def validate_job_yaml(self, job_definition, print_err=False):
154 """ Validate a job definition syntax. Returns true is server considers
155 the syntax valid """
156
157 try:
158 with open(job_definition) as F:
159 input_yaml = F.read()
160 self.scheduler.validate_yaml(input_yaml)
161 return True
162 except Exception as E:
163 if print_err:
164 print(E)
165 return False
166
Matthew Hart110e1dc2020-05-27 17:18:55 +0100167 def device_type_from_def(self, job_data):
Paul Sokolovskyf2f385d2022-01-11 00:36:31 +0300168 def_yaml = yaml.safe_load(job_data)
Matthew Hart110e1dc2020-05-27 17:18:55 +0100169 return(def_yaml['device_type'])
170
171 def has_device_type(self, job_data):
172 d_type = self.device_type_from_def(job_data)
173 all_d = self.scheduler.devices.list()
174 for device in all_d:
175 if device['type'] == d_type:
176 if device['health'] in ['Good', 'Unknown']:
177 return(True)
178 return(False)
179
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100180 def submit_job(self, job_definition):
181 """ Will submit a yaml definition pointed by job_definition after
182 validating it againist the remote backend. Returns resulting job id,
183 and server url for job"""
184
185 try:
186 if not self.validate_job_yaml(job_definition):
187 print("Served rejected job's syntax")
188 raise Exception("Invalid job")
189 with open(job_definition, "r") as F:
190 job_data = F.read()
191 except Exception as e:
192 print("Cannot submit invalid job. Check %s's content" %
193 job_definition)
194 print(e)
195 return None, None
Dean Bircha6ede7e2020-03-13 14:00:33 +0000196 try:
Dean Birch1d545c02020-05-29 14:09:21 +0100197 if self.has_device_type(job_data):
198 job_id = self.scheduler.submit_job(job_data)
199 job_url = self.server_job_prefix % job_id
200 return(job_id, job_url)
201 else:
202 raise Exception("No devices online with required device_type")
Dean Bircha6ede7e2020-03-13 14:00:33 +0000203 except Exception as e:
204 print(e)
205 return(None, None)
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100206
207 def resubmit_job(self, job_id):
208 """ Re-submit job with provided id. Returns resulting job id,
209 and server url for job"""
210
211 job_id = self.scheduler.resubmit_job(job_id)
212 job_url = self.server_job_prefix % job_id
213 return(job_id, job_url)
214
215 def block_wait_for_job(self, job_id, timeout, poll_freq=1):
216 """ Will block code execution and wait for the job to submit.
217 Returns job status on completion """
218
219 start_t = int(time.time())
220 while(True):
221 cur_t = int(time.time())
222 if cur_t - start_t >= timeout:
223 print("Breaking because of timeout")
224 break
225 # Check if the job is not running
Dean Arnoldf1169b92020-03-11 10:14:14 +0000226 cur_status = self.get_job_state(job_id)
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100227 # If in queue or running wait
Dean Arnoldc1d81b42020-03-11 15:56:36 +0000228 if cur_status not in ["Canceling","Finished"]:
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100229 time.sleep(poll_freq)
230 else:
231 break
Dean Arnoldc1d81b42020-03-11 15:56:36 +0000232 return self.scheduler.job_health(job_id)["job_health"]
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100233
Matthew Hartfb6fd362020-03-04 21:03:59 +0000234 def block_wait_for_jobs(self, job_ids, timeout, poll_freq=10):
235 """ Wait for multiple LAVA job ids to finish and return finished list """
236
237 start_t = int(time.time())
238 finished_jobs = {}
239 while(True):
240 cur_t = int(time.time())
241 if cur_t - start_t >= timeout:
242 print("Breaking because of timeout")
243 break
244 for job_id in job_ids:
245 # Check if the job is not running
246 cur_status = self.get_job_info(job_id)
247 # If in queue or running wait
248 if cur_status['state'] in ["Canceling","Finished"]:
249 cur_status['error_reason'] = self.get_error_reason(job_id)
250 finished_jobs[job_id] = cur_status
251 if len(job_ids) == len(finished_jobs):
252 break
253 else:
254 time.sleep(poll_freq)
255 if len(job_ids) == len(finished_jobs):
256 break
257 return finished_jobs
258
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100259 def test_credentials(self):
260 """ Attempt to querry the back-end and verify that the user provided
261 authentication is valid """
262
263 try:
264 self._rpc_cmd_raw("system.listMethods")
265 return True
266 except Exception as e:
267 print(e)
268 print("Credential validation failed")
269 return False
270
271
272if __name__ == "__main__":
273 pass