blob: 80e0ff68e31404f3693cfeac3ac3e06930dd6c9b [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/*
Dean Arnoldf1169b92020-03-11 10:14:14 +000012 * Copyright (c) 2018-2020, 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"
Karl Zhang08681e62020-10-30 13:56:03 +080021__version__ = "1.2.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))
97 def_o = yaml.load(job_def)
98 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 )
105 r = requests.get(log_url, stream=True, headers=auth_headers)
106 if r.status_code != 200:
107 print("{} - {}".format(log_url, r.status_code))
Matthew Hart4a4f1202020-06-12 15:52:46 +0100108 return
109 with open(target_out_file, "w") as target_out:
110 try:
111 for line in r.iter_lines():
112 line = line.decode('utf-8')
113 try:
114 if ('target' in line) or ('feedback' in line):
115 line_yaml = yaml.load(line)[0]
116 if line_yaml['lvl'] in ['target', 'feedback']:
117 target_out.write("{}\n".format(line_yaml['msg']))
118 except yaml.parser.ParserError as e:
119 continue
120 except yaml.scanner.ScannerError as e:
121 continue
122 except Exception as e:
123 pass
Matthew Hartfb6fd362020-03-04 21:03:59 +0000124
Matthew Hart4a4f1202020-06-12 15:52:46 +0100125 def get_job_config(self, job_id, config_out_file):
126 config_url = "{}/configuration".format(self.server_job_prefix % job_id)
127 self.fetch_file(config_url, config_out_file)
Matthew Hartfb6fd362020-03-04 21:03:59 +0000128
129 def get_job_info(self, job_id, yaml_out_file=None):
130 job_info = self.scheduler.jobs.show(job_id)
131 if yaml_out_file:
132 with open(yaml_out_file, "w") as F:
133 F.write(str(job_info))
134 return job_info
135
136 def get_error_reason(self, job_id):
Matthew Hart2c2688f2020-05-26 13:09:20 +0100137 try:
138 lava_res = self.results.get_testsuite_results_yaml(job_id, 'lava')
139 results = yaml.load(lava_res)
140 for test in results:
141 if test['name'] == 'job':
142 return(test.get('metadata', {}).get('error_type', ''))
143 except Exception:
144 return("Unknown")
Matthew Hartfb6fd362020-03-04 21:03:59 +0000145
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100146 def get_job_state(self, job_id):
147 return self.scheduler.job_state(job_id)["job_state"]
148
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100149 def cancel_job(self, job_id):
150 """ Cancell job with id=job_id. Returns True if successfull """
151
152 return self.scheduler.jobs.cancel(job_id)
153
154 def validate_job_yaml(self, job_definition, print_err=False):
155 """ Validate a job definition syntax. Returns true is server considers
156 the syntax valid """
157
158 try:
159 with open(job_definition) as F:
160 input_yaml = F.read()
161 self.scheduler.validate_yaml(input_yaml)
162 return True
163 except Exception as E:
164 if print_err:
165 print(E)
166 return False
167
Matthew Hart110e1dc2020-05-27 17:18:55 +0100168 def device_type_from_def(self, job_data):
169 def_yaml = yaml.load(job_data)
170 return(def_yaml['device_type'])
171
172 def has_device_type(self, job_data):
173 d_type = self.device_type_from_def(job_data)
174 all_d = self.scheduler.devices.list()
175 for device in all_d:
176 if device['type'] == d_type:
177 if device['health'] in ['Good', 'Unknown']:
178 return(True)
179 return(False)
180
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100181 def submit_job(self, job_definition):
182 """ Will submit a yaml definition pointed by job_definition after
183 validating it againist the remote backend. Returns resulting job id,
184 and server url for job"""
185
186 try:
187 if not self.validate_job_yaml(job_definition):
188 print("Served rejected job's syntax")
189 raise Exception("Invalid job")
190 with open(job_definition, "r") as F:
191 job_data = F.read()
192 except Exception as e:
193 print("Cannot submit invalid job. Check %s's content" %
194 job_definition)
195 print(e)
196 return None, None
Dean Bircha6ede7e2020-03-13 14:00:33 +0000197 try:
Dean Birch1d545c02020-05-29 14:09:21 +0100198 if self.has_device_type(job_data):
199 job_id = self.scheduler.submit_job(job_data)
200 job_url = self.server_job_prefix % job_id
201 return(job_id, job_url)
202 else:
203 raise Exception("No devices online with required device_type")
Dean Bircha6ede7e2020-03-13 14:00:33 +0000204 except Exception as e:
205 print(e)
206 return(None, None)
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100207
208 def resubmit_job(self, job_id):
209 """ Re-submit job with provided id. Returns resulting job id,
210 and server url for job"""
211
212 job_id = self.scheduler.resubmit_job(job_id)
213 job_url = self.server_job_prefix % job_id
214 return(job_id, job_url)
215
216 def block_wait_for_job(self, job_id, timeout, poll_freq=1):
217 """ Will block code execution and wait for the job to submit.
218 Returns job status on completion """
219
220 start_t = int(time.time())
221 while(True):
222 cur_t = int(time.time())
223 if cur_t - start_t >= timeout:
224 print("Breaking because of timeout")
225 break
226 # Check if the job is not running
Dean Arnoldf1169b92020-03-11 10:14:14 +0000227 cur_status = self.get_job_state(job_id)
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100228 # If in queue or running wait
Dean Arnoldc1d81b42020-03-11 15:56:36 +0000229 if cur_status not in ["Canceling","Finished"]:
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100230 time.sleep(poll_freq)
231 else:
232 break
Dean Arnoldc1d81b42020-03-11 15:56:36 +0000233 return self.scheduler.job_health(job_id)["job_health"]
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100234
Matthew Hartfb6fd362020-03-04 21:03:59 +0000235 def block_wait_for_jobs(self, job_ids, timeout, poll_freq=10):
236 """ Wait for multiple LAVA job ids to finish and return finished list """
237
238 start_t = int(time.time())
239 finished_jobs = {}
240 while(True):
241 cur_t = int(time.time())
242 if cur_t - start_t >= timeout:
243 print("Breaking because of timeout")
244 break
245 for job_id in job_ids:
246 # Check if the job is not running
247 cur_status = self.get_job_info(job_id)
248 # If in queue or running wait
249 if cur_status['state'] in ["Canceling","Finished"]:
250 cur_status['error_reason'] = self.get_error_reason(job_id)
251 finished_jobs[job_id] = cur_status
252 if len(job_ids) == len(finished_jobs):
253 break
254 else:
255 time.sleep(poll_freq)
256 if len(job_ids) == len(finished_jobs):
257 break
258 return finished_jobs
259
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100260 def test_credentials(self):
261 """ Attempt to querry the back-end and verify that the user provided
262 authentication is valid """
263
264 try:
265 self._rpc_cmd_raw("system.listMethods")
266 return True
267 except Exception as e:
268 print(e)
269 print("Credential validation failed")
270 return False
271
272
273if __name__ == "__main__":
274 pass