blob: 9bab0e564426ed11ca617357c9dfd8d506606082 [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 """
18__author__ = "Minos Galanakis"
19__email__ = "minos.galanakis@linaro.org"
20__project__ = "Trusted Firmware-M Open CI"
21__status__ = "stable"
Minos Galanakisea421232019-06-20 17:11:28 +010022__version__ = "1.1"
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +010023
24import xmlrpc.client
25import time
Matthew Hartfb6fd362020-03-04 21:03:59 +000026import yaml
Matthew Hart4a4f1202020-06-12 15:52:46 +010027import requests
28import shutil
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +010029
30class LAVA_RPC_connector(xmlrpc.client.ServerProxy, object):
31
32 def __init__(self,
33 username,
34 token,
35 hostname,
36 rest_prefix="RPC2",
37 https=False):
38
39 # If user provides hostname with http/s prefix
40 if "://" in hostname:
41 htp_pre, hostname = hostname.split("://")
42 server_addr = "%s://%s:%s@%s/%s" % (htp_pre,
43 username,
44 token,
45 hostname,
46 rest_prefix)
47 self.server_url = "%s://%s" % (htp_pre, hostname)
48 else:
49 server_addr = "%s://%s:%s@%s/%s" % ("https" if https else "http",
50 username,
51 token,
52 hostname,
53 rest_prefix)
54 self.server_url = "%s://%s" % ("https" if https else "http",
55 hostname)
56
57 self.server_job_prefix = "%s/scheduler/job/%%s" % 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):
101 log_url = "{}/log_file/plain".format(self.server_job_prefix % job_id)
102 r = requests.get(log_url, stream=True)
103 if not r:
104 return
105 with open(target_out_file, "w") as target_out:
106 try:
107 for line in r.iter_lines():
108 line = line.decode('utf-8')
109 try:
110 if ('target' in line) or ('feedback' in line):
111 line_yaml = yaml.load(line)[0]
112 if line_yaml['lvl'] in ['target', 'feedback']:
113 target_out.write("{}\n".format(line_yaml['msg']))
114 except yaml.parser.ParserError as e:
115 continue
116 except yaml.scanner.ScannerError as e:
117 continue
118 except Exception as e:
119 pass
Matthew Hartfb6fd362020-03-04 21:03:59 +0000120
Matthew Hart4a4f1202020-06-12 15:52:46 +0100121 def get_job_config(self, job_id, config_out_file):
122 config_url = "{}/configuration".format(self.server_job_prefix % job_id)
123 self.fetch_file(config_url, config_out_file)
Matthew Hartfb6fd362020-03-04 21:03:59 +0000124
125 def get_job_info(self, job_id, yaml_out_file=None):
126 job_info = self.scheduler.jobs.show(job_id)
127 if yaml_out_file:
128 with open(yaml_out_file, "w") as F:
129 F.write(str(job_info))
130 return job_info
131
132 def get_error_reason(self, job_id):
Matthew Hart2c2688f2020-05-26 13:09:20 +0100133 try:
134 lava_res = self.results.get_testsuite_results_yaml(job_id, 'lava')
135 results = yaml.load(lava_res)
136 for test in results:
137 if test['name'] == 'job':
138 return(test.get('metadata', {}).get('error_type', ''))
139 except Exception:
140 return("Unknown")
Matthew Hartfb6fd362020-03-04 21:03:59 +0000141
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100142 def get_job_state(self, job_id):
143 return self.scheduler.job_state(job_id)["job_state"]
144
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100145 def cancel_job(self, job_id):
146 """ Cancell job with id=job_id. Returns True if successfull """
147
148 return self.scheduler.jobs.cancel(job_id)
149
150 def validate_job_yaml(self, job_definition, print_err=False):
151 """ Validate a job definition syntax. Returns true is server considers
152 the syntax valid """
153
154 try:
155 with open(job_definition) as F:
156 input_yaml = F.read()
157 self.scheduler.validate_yaml(input_yaml)
158 return True
159 except Exception as E:
160 if print_err:
161 print(E)
162 return False
163
Matthew Hart110e1dc2020-05-27 17:18:55 +0100164 def device_type_from_def(self, job_data):
165 def_yaml = yaml.load(job_data)
166 return(def_yaml['device_type'])
167
168 def has_device_type(self, job_data):
169 d_type = self.device_type_from_def(job_data)
170 all_d = self.scheduler.devices.list()
171 for device in all_d:
172 if device['type'] == d_type:
173 if device['health'] in ['Good', 'Unknown']:
174 return(True)
175 return(False)
176
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100177 def submit_job(self, job_definition):
178 """ Will submit a yaml definition pointed by job_definition after
179 validating it againist the remote backend. Returns resulting job id,
180 and server url for job"""
181
182 try:
183 if not self.validate_job_yaml(job_definition):
184 print("Served rejected job's syntax")
185 raise Exception("Invalid job")
186 with open(job_definition, "r") as F:
187 job_data = F.read()
188 except Exception as e:
189 print("Cannot submit invalid job. Check %s's content" %
190 job_definition)
191 print(e)
192 return None, None
Dean Bircha6ede7e2020-03-13 14:00:33 +0000193 try:
Dean Birch1d545c02020-05-29 14:09:21 +0100194 if self.has_device_type(job_data):
195 job_id = self.scheduler.submit_job(job_data)
196 job_url = self.server_job_prefix % job_id
197 return(job_id, job_url)
198 else:
199 raise Exception("No devices online with required device_type")
Dean Bircha6ede7e2020-03-13 14:00:33 +0000200 except Exception as e:
201 print(e)
202 return(None, None)
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100203
204 def resubmit_job(self, job_id):
205 """ Re-submit job with provided id. Returns resulting job id,
206 and server url for job"""
207
208 job_id = self.scheduler.resubmit_job(job_id)
209 job_url = self.server_job_prefix % job_id
210 return(job_id, job_url)
211
212 def block_wait_for_job(self, job_id, timeout, poll_freq=1):
213 """ Will block code execution and wait for the job to submit.
214 Returns job status on completion """
215
216 start_t = int(time.time())
217 while(True):
218 cur_t = int(time.time())
219 if cur_t - start_t >= timeout:
220 print("Breaking because of timeout")
221 break
222 # Check if the job is not running
Dean Arnoldf1169b92020-03-11 10:14:14 +0000223 cur_status = self.get_job_state(job_id)
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100224 # If in queue or running wait
Dean Arnoldc1d81b42020-03-11 15:56:36 +0000225 if cur_status not in ["Canceling","Finished"]:
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100226 time.sleep(poll_freq)
227 else:
228 break
Dean Arnoldc1d81b42020-03-11 15:56:36 +0000229 return self.scheduler.job_health(job_id)["job_health"]
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100230
Matthew Hartfb6fd362020-03-04 21:03:59 +0000231 def block_wait_for_jobs(self, job_ids, timeout, poll_freq=10):
232 """ Wait for multiple LAVA job ids to finish and return finished list """
233
234 start_t = int(time.time())
235 finished_jobs = {}
236 while(True):
237 cur_t = int(time.time())
238 if cur_t - start_t >= timeout:
239 print("Breaking because of timeout")
240 break
241 for job_id in job_ids:
242 # Check if the job is not running
243 cur_status = self.get_job_info(job_id)
244 # If in queue or running wait
245 if cur_status['state'] in ["Canceling","Finished"]:
246 cur_status['error_reason'] = self.get_error_reason(job_id)
247 finished_jobs[job_id] = cur_status
248 if len(job_ids) == len(finished_jobs):
249 break
250 else:
251 time.sleep(poll_freq)
252 if len(job_ids) == len(finished_jobs):
253 break
254 return finished_jobs
255
Minos Galanakisf4ca6ac2017-12-11 02:39:21 +0100256 def test_credentials(self):
257 """ Attempt to querry the back-end and verify that the user provided
258 authentication is valid """
259
260 try:
261 self._rpc_cmd_raw("system.listMethods")
262 return True
263 except Exception as e:
264 print(e)
265 print("Credential validation failed")
266 return False
267
268
269if __name__ == "__main__":
270 pass