Dennis Dmitriev | 6111511 | 2018-05-31 06:48:43 +0300 | [diff] [blame] | 1 | from __future__ import print_function |
Dmitry Tyzhnenko | b39de05 | 2019-03-21 17:05:07 +0200 | [diff] [blame] | 2 | import datetime |
Dennis Dmitriev | 3ec2e53 | 2018-06-08 04:33:34 +0300 | [diff] [blame] | 3 | import time |
Dmitry Tyzhnenko | 5a5d8da | 2017-12-14 14:14:42 +0200 | [diff] [blame] | 4 | |
| 5 | import jenkins |
Dennis Dmitriev | 27a9679 | 2018-07-30 07:52:03 +0300 | [diff] [blame] | 6 | import json |
Dennis Dmitriev | 6111511 | 2018-05-31 06:48:43 +0300 | [diff] [blame] | 7 | import requests |
Dmitry Tyzhnenko | 5a5d8da | 2017-12-14 14:14:42 +0200 | [diff] [blame] | 8 | |
| 9 | from devops.helpers import helpers |
| 10 | |
Dmitry Tyzhnenko | 80ce020 | 2019-02-07 13:27:19 +0200 | [diff] [blame] | 11 | from requests.exceptions import ConnectionError |
| 12 | |
Dmitry Tyzhnenko | 5a5d8da | 2017-12-14 14:14:42 +0200 | [diff] [blame] | 13 | |
Hanna Arhipova | b252269 | 2020-09-23 15:25:11 +0300 | [diff] [blame] | 14 | def retry(max_count=6, |
| 15 | sleep_before_retry=10): |
| 16 | def _retry(func): |
| 17 | def __retry(*args, **kwargs): |
| 18 | """ |
| 19 | Waits some time and retries the requests if it fails with |
| 20 | with any error |
| 21 | Raises Exceptions after all unsuccessful tries |
| 22 | |
| 23 | :param func: callable |
| 24 | :param args, kwargs: parameters of decorated functions |
| 25 | :param max_count: times of retries |
| 26 | :param sleep_before_retry: how many seconds needs to wait before |
| 27 | the next retry |
| 28 | :return: response |
| 29 | :raise ConnectionError after several unsuccessful connections |
| 30 | """ |
| 31 | err = None |
| 32 | for count in range(max_count): |
| 33 | try: |
| 34 | return func(*args, **kwargs) |
| 35 | except Exception as err: |
| 36 | print("Try {count}/{max_count} caught Exception: {err}. \ |
| 37 | \n... repeat after {secs} secs". |
| 38 | format(err=err, |
| 39 | count=count+1, |
| 40 | max_count=max_count, |
| 41 | secs=sleep_before_retry)) |
| 42 | time.sleep(sleep_before_retry) |
| 43 | print("Function failed in {total_time} seconds".format( |
| 44 | total_time=max_count*sleep_before_retry) |
| 45 | ) |
| 46 | raise err |
| 47 | return __retry |
| 48 | return _retry |
| 49 | |
| 50 | |
| 51 | @retry(max_count=5, sleep_before_retry=2) |
Hanna Arhipova | e1f0b47 | 2020-01-03 17:38:11 +0200 | [diff] [blame] | 52 | def send_request(action, endpoint): |
| 53 | """ |
Hanna Arhipova | b252269 | 2020-09-23 15:25:11 +0300 | [diff] [blame] | 54 | Makes request with described operation to endpoint |
| 55 | :param action: string, type of operation GET, POST, DELETE and so on |
| 56 | :param endpoint: string, url to send request |
| 57 | :return: response |
Hanna Arhipova | e1f0b47 | 2020-01-03 17:38:11 +0200 | [diff] [blame] | 58 | """ |
Hanna Arhipova | b252269 | 2020-09-23 15:25:11 +0300 | [diff] [blame] | 59 | response = requests.Request(action, endpoint) |
| 60 | return response |
Hanna Arhipova | e1f0b47 | 2020-01-03 17:38:11 +0200 | [diff] [blame] | 61 | |
| 62 | |
Dmitry Tyzhnenko | 5a5d8da | 2017-12-14 14:14:42 +0200 | [diff] [blame] | 63 | class JenkinsClient(object): |
| 64 | |
Dennis Dmitriev | 27a9679 | 2018-07-30 07:52:03 +0300 | [diff] [blame] | 65 | def __init__(self, host=None, username='admin', password='r00tme'): |
Dmitry Tyzhnenko | 5a5d8da | 2017-12-14 14:14:42 +0200 | [diff] [blame] | 66 | host = host or 'http://172.16.44.33:8081' |
obutenko | ca85840 | 2019-07-04 18:31:39 +0300 | [diff] [blame] | 67 | self.__client = jenkins.Jenkins( |
Dmitry Tyzhnenko | 5a5d8da | 2017-12-14 14:14:42 +0200 | [diff] [blame] | 68 | host, |
| 69 | username=username, |
| 70 | password=password) |
obutenko | ca85840 | 2019-07-04 18:31:39 +0300 | [diff] [blame] | 71 | self.__client._session.verify = False |
Dmitry Tyzhnenko | 5a5d8da | 2017-12-14 14:14:42 +0200 | [diff] [blame] | 72 | |
Hanna Arhipova | b252269 | 2020-09-23 15:25:11 +0300 | [diff] [blame] | 73 | @retry() |
Dmitry Tyzhnenko | 5a5d8da | 2017-12-14 14:14:42 +0200 | [diff] [blame] | 74 | def jobs(self): |
| 75 | return self.__client.get_jobs() |
| 76 | |
| 77 | def find_jobs(self, name): |
| 78 | return filter(lambda x: name in x['fullname'], self.jobs()) |
| 79 | |
Hanna Arhipova | b252269 | 2020-09-23 15:25:11 +0300 | [diff] [blame] | 80 | @retry() |
Dmitry Tyzhnenko | 5a5d8da | 2017-12-14 14:14:42 +0200 | [diff] [blame] | 81 | def job_info(self, name): |
Hanna Arhipova | b252269 | 2020-09-23 15:25:11 +0300 | [diff] [blame] | 82 | return self.__client.get_job_info(name) |
Dmitry Tyzhnenko | 5a5d8da | 2017-12-14 14:14:42 +0200 | [diff] [blame] | 83 | |
| 84 | def list_builds(self, name): |
| 85 | return self.job_info(name).get('builds') |
| 86 | |
Hanna Arhipova | b252269 | 2020-09-23 15:25:11 +0300 | [diff] [blame] | 87 | @retry() |
Dmitry Tyzhnenko | 5a5d8da | 2017-12-14 14:14:42 +0200 | [diff] [blame] | 88 | def build_info(self, name, build_id): |
Hanna Arhipova | b252269 | 2020-09-23 15:25:11 +0300 | [diff] [blame] | 89 | return self.__client.get_build_info(name, build_id) |
Dmitry Tyzhnenko | 5a5d8da | 2017-12-14 14:14:42 +0200 | [diff] [blame] | 90 | |
| 91 | def job_params(self, name): |
| 92 | job = self.job_info(name) |
| 93 | job_params = next( |
| 94 | p for p in job['property'] if |
| 95 | 'hudson.model.ParametersDefinitionProperty' == p['_class']) |
| 96 | job_params = job_params['parameterDefinitions'] |
| 97 | return job_params |
| 98 | |
| 99 | def make_defults_params(self, name): |
| 100 | job_params = self.job_params(name) |
| 101 | def_params = dict( |
| 102 | [(j['name'], j['defaultParameterValue']['value']) |
| 103 | for j in job_params]) |
| 104 | return def_params |
| 105 | |
Hanna Arhipova | b252269 | 2020-09-23 15:25:11 +0300 | [diff] [blame] | 106 | @retry() |
Dennis Dmitriev | a5bd165 | 2018-05-31 20:57:19 +0300 | [diff] [blame] | 107 | def run_build(self, name, params=None, timeout=600, verbose=False): |
Dmitry Tyzhnenko | 5a5d8da | 2017-12-14 14:14:42 +0200 | [diff] [blame] | 108 | params = params or self.make_defults_params(name) |
Dennis Dmitriev | a5bd165 | 2018-05-31 20:57:19 +0300 | [diff] [blame] | 109 | num = self.__client.build_job(name, params) |
Dennis Dmitriev | 3ec2e53 | 2018-06-08 04:33:34 +0300 | [diff] [blame] | 110 | time.sleep(2) # wait while job is started |
Dennis Dmitriev | a5bd165 | 2018-05-31 20:57:19 +0300 | [diff] [blame] | 111 | |
Dmitry Tyzhnenko | b39de05 | 2019-03-21 17:05:07 +0200 | [diff] [blame] | 112 | def is_build_queued(): |
| 113 | try: |
| 114 | item = self.__client.get_queue_item(num) |
| 115 | ts = item['inQueueSince'] / 1000 |
| 116 | since_time = datetime.datetime.fromtimestamp(ts) |
| 117 | print("Build in the queue since {}".format(since_time)) |
| 118 | return True |
| 119 | except jenkins.JenkinsException: |
| 120 | if verbose: |
| 121 | print("Build have not been queued {} yet".format(num)) |
| 122 | |
| 123 | helpers.wait( |
| 124 | is_build_queued, |
| 125 | timeout=timeout, |
| 126 | interval=30, |
| 127 | timeout_msg='Timeout waiting to queue the build ' |
| 128 | 'for {} job'.format(name)) |
| 129 | |
Dennis Dmitriev | a5bd165 | 2018-05-31 20:57:19 +0300 | [diff] [blame] | 130 | def is_blocked(): |
| 131 | queued = self.__client.get_queue_item(num) |
| 132 | status = not queued['blocked'] |
| 133 | if not status and verbose: |
| 134 | print("pending the job [{}] : {}".format(name, queued['why'])) |
Dennis Dmitriev | 3ec2e53 | 2018-06-08 04:33:34 +0300 | [diff] [blame] | 135 | return (status and |
| 136 | 'executable' in (queued or {}) and |
| 137 | 'number' in (queued['executable'] or {})) |
Dennis Dmitriev | a5bd165 | 2018-05-31 20:57:19 +0300 | [diff] [blame] | 138 | |
| 139 | helpers.wait( |
| 140 | is_blocked, |
| 141 | timeout=timeout, |
| 142 | interval=30, |
| 143 | timeout_msg='Timeout waiting to run the job [{}]'.format(name)) |
Dennis Dmitriev | a5bd165 | 2018-05-31 20:57:19 +0300 | [diff] [blame] | 144 | build_id = self.__client.get_queue_item(num)['executable']['number'] |
Dmitry Tyzhnenko | b39de05 | 2019-03-21 17:05:07 +0200 | [diff] [blame] | 145 | |
| 146 | def is_build_started(): |
| 147 | try: |
| 148 | build = self.__client.get_build_info(name, build_id) |
| 149 | ts = float(build['timestamp']) / 1000 |
| 150 | start_time = datetime.datetime.fromtimestamp(ts) |
| 151 | print("the build {} in {} have started at {} UTC".format( |
| 152 | build_id, name, start_time)) |
| 153 | return True |
| 154 | except jenkins.JenkinsException: |
| 155 | if verbose: |
| 156 | print("the build {} in {} have not strated yet".format( |
| 157 | build_id, name)) |
| 158 | helpers.wait( |
| 159 | is_build_started, |
| 160 | timeout=timeout, |
| 161 | interval=30, |
| 162 | timeout_msg='Timeout waiting to run build of ' |
| 163 | 'the job [{}]'.format(name)) |
| 164 | |
Dmitry Tyzhnenko | 5a5d8da | 2017-12-14 14:14:42 +0200 | [diff] [blame] | 165 | return name, build_id |
| 166 | |
Dennis Dmitriev | 3ec2e53 | 2018-06-08 04:33:34 +0300 | [diff] [blame] | 167 | def wait_end_of_build(self, name, build_id, timeout=600, interval=5, |
| 168 | verbose=False, job_output_prefix=''): |
| 169 | '''Wait until the specified build is finished |
| 170 | |
| 171 | :param name: ``str``, job name |
| 172 | :param build_id: ``int``, build id |
| 173 | :param timeout: ``int``, timeout waiting the job, sec |
| 174 | :param interval: ``int``, interval of polling the job result, sec |
| 175 | :param verbose: ``bool``, print the job console updates during waiting |
| 176 | :param job_output_prefix: ``str``, print the prefix for each console |
| 177 | output line, with the pre-defined |
| 178 | substitution keys: |
| 179 | - '{name}' : the current job name |
| 180 | - '{build_id}' : the current build-id |
| 181 | - '{time}' : the current time |
| 182 | :returns: requests object with headers and console output, ``obj`` |
| 183 | ''' |
Dennis Dmitriev | 6111511 | 2018-05-31 06:48:43 +0300 | [diff] [blame] | 184 | start = [0] |
Dennis Dmitriev | 3ec2e53 | 2018-06-08 04:33:34 +0300 | [diff] [blame] | 185 | time_str = time.strftime("%H:%M:%S") |
| 186 | prefix = "\n" + job_output_prefix.format(job_name=name, |
| 187 | build_number=build_id, |
| 188 | time=time_str) |
| 189 | if verbose: |
| 190 | print(prefix, end='') |
Dmitry Tyzhnenko | 5a5d8da | 2017-12-14 14:14:42 +0200 | [diff] [blame] | 191 | |
| 192 | def building(): |
Dmitry Tyzhnenko | 80ce020 | 2019-02-07 13:27:19 +0200 | [diff] [blame] | 193 | try: |
| 194 | status = not self.build_info(name, build_id)['building'] |
| 195 | except ConnectionError: |
| 196 | status = False |
| 197 | |
Dennis Dmitriev | a5bd165 | 2018-05-31 20:57:19 +0300 | [diff] [blame] | 198 | if verbose: |
Dennis Dmitriev | 3ec2e53 | 2018-06-08 04:33:34 +0300 | [diff] [blame] | 199 | time_str = time.strftime("%H:%M:%S") |
| 200 | prefix = "\n" + job_output_prefix.format( |
| 201 | job_name=name, build_number=build_id, time=time_str) |
Dennis Dmitriev | 6111511 | 2018-05-31 06:48:43 +0300 | [diff] [blame] | 202 | res = self.get_progressive_build_output(name, |
| 203 | build_id, |
| 204 | start=start[0]) |
| 205 | if 'X-Text-Size' in res.headers: |
| 206 | text_size = int(res.headers['X-Text-Size']) |
| 207 | if start[0] < text_size: |
Dennis Dmitriev | 3ec2e53 | 2018-06-08 04:33:34 +0300 | [diff] [blame] | 208 | text = res.content.decode('utf-8', |
| 209 | errors='backslashreplace') |
| 210 | print(text.replace("\n", prefix), end='') |
Dennis Dmitriev | 6111511 | 2018-05-31 06:48:43 +0300 | [diff] [blame] | 211 | start[0] = text_size |
| 212 | return status |
Dmitry Tyzhnenko | 5a5d8da | 2017-12-14 14:14:42 +0200 | [diff] [blame] | 213 | |
| 214 | helpers.wait( |
| 215 | building, |
| 216 | timeout=timeout, |
Dennis Dmitriev | 3ec2e53 | 2018-06-08 04:33:34 +0300 | [diff] [blame] | 217 | interval=interval, |
Dennis Dmitriev | 13e804b | 2018-10-09 19:25:14 +0300 | [diff] [blame] | 218 | timeout_msg=('Timeout waiting the job {0}:{1} in {2} sec.' |
| 219 | .format(name, build_id, timeout))) |
Dmitry Tyzhnenko | b610afd | 2018-02-19 15:43:45 +0200 | [diff] [blame] | 220 | |
Hanna Arhipova | b252269 | 2020-09-23 15:25:11 +0300 | [diff] [blame] | 221 | @retry() |
Dmitry Tyzhnenko | b610afd | 2018-02-19 15:43:45 +0200 | [diff] [blame] | 222 | def get_build_output(self, name, build_id): |
| 223 | return self.__client.get_build_console_output(name, build_id) |
Dennis Dmitriev | 6111511 | 2018-05-31 06:48:43 +0300 | [diff] [blame] | 224 | |
Hanna Arhipova | b252269 | 2020-09-23 15:25:11 +0300 | [diff] [blame] | 225 | @retry(max_count=12) |
Dennis Dmitriev | 3ec2e53 | 2018-06-08 04:33:34 +0300 | [diff] [blame] | 226 | def get_progressive_build_output(self, name, build_id, start=0): |
Dennis Dmitriev | 6111511 | 2018-05-31 06:48:43 +0300 | [diff] [blame] | 227 | '''Get build console text. |
| 228 | |
| 229 | :param name: Job name, ``str`` |
Dennis Dmitriev | 3ec2e53 | 2018-06-08 04:33:34 +0300 | [diff] [blame] | 230 | :param build_id: Build id, ``int`` |
| 231 | :param start: Start offset, ``int`` |
Dennis Dmitriev | 6111511 | 2018-05-31 06:48:43 +0300 | [diff] [blame] | 232 | :returns: requests object with headers and console output, ``obj`` |
| 233 | ''' |
| 234 | folder_url, short_name = self.__client._get_job_folder(name) |
| 235 | |
| 236 | PROGRESSIVE_CONSOLE_OUTPUT = ( |
| 237 | '%(folder_url)sjob/%(short_name)s/%(build_id)d/' |
Dennis Dmitriev | 3ec2e53 | 2018-06-08 04:33:34 +0300 | [diff] [blame] | 238 | 'logText/progressiveText?start=%(start)d') |
Hanna Arhipova | e1f0b47 | 2020-01-03 17:38:11 +0200 | [diff] [blame] | 239 | req = send_request( |
Dennis Dmitriev | 3ec2e53 | 2018-06-08 04:33:34 +0300 | [diff] [blame] | 240 | 'GET', |
| 241 | self.__client._build_url(PROGRESSIVE_CONSOLE_OUTPUT, locals())) |
| 242 | return(self.__client.jenkins_request(req)) |
Dennis Dmitriev | 27a9679 | 2018-07-30 07:52:03 +0300 | [diff] [blame] | 243 | |
Hanna Arhipova | b252269 | 2020-09-23 15:25:11 +0300 | [diff] [blame] | 244 | @retry(max_count=12) |
Dennis Dmitriev | 27a9679 | 2018-07-30 07:52:03 +0300 | [diff] [blame] | 245 | def get_workflow(self, name, build_id, enode=None, mode='describe'): |
| 246 | '''Get workflow results from pipeline job |
| 247 | |
| 248 | :param name: job name |
| 249 | :param build_id: str, build number or 'lastBuild' |
| 250 | :param enode: int, execution node in the workflow |
| 251 | :param mode: the stage or execution node description if 'describe', |
| 252 | the execution node log if 'log' |
| 253 | ''' |
| 254 | folder_url, short_name = self.__client._get_job_folder(name) |
| 255 | |
| 256 | if enode: |
| 257 | WORKFLOW_DESCRIPTION = ( |
| 258 | '%(folder_url)sjob/%(short_name)s/%(build_id)s/' |
| 259 | 'execution/node/%(enode)d/wfapi/%(mode)s') |
| 260 | else: |
| 261 | WORKFLOW_DESCRIPTION = ( |
| 262 | '%(folder_url)sjob/%(short_name)s/%(build_id)s/wfapi/%(mode)s') |
Hanna Arhipova | e1f0b47 | 2020-01-03 17:38:11 +0200 | [diff] [blame] | 263 | req = send_request( |
Dennis Dmitriev | 27a9679 | 2018-07-30 07:52:03 +0300 | [diff] [blame] | 264 | 'GET', |
| 265 | self.__client._build_url(WORKFLOW_DESCRIPTION, locals())) |
| 266 | response = self.__client.jenkins_open(req) |
| 267 | return json.loads(response) |
Dennis Dmitriev | 8565c34 | 2019-02-11 23:45:03 +0200 | [diff] [blame] | 268 | |
Hanna Arhipova | b252269 | 2020-09-23 15:25:11 +0300 | [diff] [blame] | 269 | @retry(max_count=12) |
Dennis Dmitriev | 8565c34 | 2019-02-11 23:45:03 +0200 | [diff] [blame] | 270 | def get_artifact(self, name, build_id, artifact_path, destination_name): |
| 271 | '''Wait until the specified build is finished |
| 272 | |
| 273 | :param name: ``str``, job name |
| 274 | :param build_id: ``str``, build id or "lastBuild" |
| 275 | :param artifact_path: ``str``, path and filename of the artifact |
| 276 | relative to the job URL |
| 277 | :param artifact_path: ``str``, destination path and filename |
| 278 | on the local filesystem where to save |
| 279 | the artifact content |
| 280 | :returns: requests object with headers and console output, ``obj`` |
| 281 | ''' |
| 282 | folder_url, short_name = self.__client._get_job_folder(name) |
| 283 | |
| 284 | DOWNLOAD_URL = ('%(folder_url)sjob/%(short_name)s/%(build_id)s/' |
| 285 | 'artifact/%(artifact_path)s') |
Hanna Arhipova | e1f0b47 | 2020-01-03 17:38:11 +0200 | [diff] [blame] | 286 | req = send_request( |
Dennis Dmitriev | 8565c34 | 2019-02-11 23:45:03 +0200 | [diff] [blame] | 287 | 'GET', |
| 288 | self.__client._build_url(DOWNLOAD_URL, locals())) |
| 289 | |
| 290 | response = self.__client.jenkins_request(req) |
| 291 | return response.content |