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