blob: 063d4007f762f13938d39d4b893b8fdd8b09d168 [file] [log] [blame]
Dennis Dmitriev61115112018-05-31 06:48:43 +03001from __future__ import print_function
Dmitry Tyzhnenkob39de052019-03-21 17:05:07 +02002import datetime
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +03003import time
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +02004
5import jenkins
Dennis Dmitriev27a96792018-07-30 07:52:03 +03006import json
Dennis Dmitriev61115112018-05-31 06:48:43 +03007import requests
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +02008
9from devops.helpers import helpers
10
Dmitry Tyzhnenko80ce0202019-02-07 13:27:19 +020011from requests.exceptions import ConnectionError
12
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +020013
Hanna Arhipovab2522692020-09-23 15:25:11 +030014def 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 Arhipovae1f0b472020-01-03 17:38:11 +020052def send_request(action, endpoint):
53 """
Hanna Arhipovab2522692020-09-23 15:25:11 +030054 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 Arhipovae1f0b472020-01-03 17:38:11 +020058 """
Hanna Arhipovab2522692020-09-23 15:25:11 +030059 response = requests.Request(action, endpoint)
60 return response
Hanna Arhipovae1f0b472020-01-03 17:38:11 +020061
62
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +020063class JenkinsClient(object):
64
Dennis Dmitriev27a96792018-07-30 07:52:03 +030065 def __init__(self, host=None, username='admin', password='r00tme'):
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +020066 host = host or 'http://172.16.44.33:8081'
obutenkoca858402019-07-04 18:31:39 +030067 self.__client = jenkins.Jenkins(
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +020068 host,
69 username=username,
70 password=password)
obutenkoca858402019-07-04 18:31:39 +030071 self.__client._session.verify = False
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +020072
Hanna Arhipovab2522692020-09-23 15:25:11 +030073 @retry()
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +020074 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 Arhipovab2522692020-09-23 15:25:11 +030080 @retry()
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +020081 def job_info(self, name):
Hanna Arhipovab2522692020-09-23 15:25:11 +030082 return self.__client.get_job_info(name)
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +020083
84 def list_builds(self, name):
85 return self.job_info(name).get('builds')
86
Hanna Arhipovab2522692020-09-23 15:25:11 +030087 @retry()
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +020088 def build_info(self, name, build_id):
Hanna Arhipovab2522692020-09-23 15:25:11 +030089 return self.__client.get_build_info(name, build_id)
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +020090
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 Arhipovab2522692020-09-23 15:25:11 +0300106 @retry()
Dennis Dmitrieva5bd1652018-05-31 20:57:19 +0300107 def run_build(self, name, params=None, timeout=600, verbose=False):
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +0200108 params = params or self.make_defults_params(name)
Dennis Dmitrieva5bd1652018-05-31 20:57:19 +0300109 num = self.__client.build_job(name, params)
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300110 time.sleep(2) # wait while job is started
Dennis Dmitrieva5bd1652018-05-31 20:57:19 +0300111
Dmitry Tyzhnenkob39de052019-03-21 17:05:07 +0200112 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 Dmitrieva5bd1652018-05-31 20:57:19 +0300130 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 Dmitriev3ec2e532018-06-08 04:33:34 +0300135 return (status and
136 'executable' in (queued or {}) and
137 'number' in (queued['executable'] or {}))
Dennis Dmitrieva5bd1652018-05-31 20:57:19 +0300138
139 helpers.wait(
140 is_blocked,
141 timeout=timeout,
142 interval=30,
143 timeout_msg='Timeout waiting to run the job [{}]'.format(name))
Dennis Dmitrieva5bd1652018-05-31 20:57:19 +0300144 build_id = self.__client.get_queue_item(num)['executable']['number']
Dmitry Tyzhnenkob39de052019-03-21 17:05:07 +0200145
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 Tyzhnenko5a5d8da2017-12-14 14:14:42 +0200165 return name, build_id
166
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300167 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 Dmitriev61115112018-05-31 06:48:43 +0300184 start = [0]
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300185 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 Tyzhnenko5a5d8da2017-12-14 14:14:42 +0200191
192 def building():
Dmitry Tyzhnenko80ce0202019-02-07 13:27:19 +0200193 try:
194 status = not self.build_info(name, build_id)['building']
195 except ConnectionError:
196 status = False
197
Dennis Dmitrieva5bd1652018-05-31 20:57:19 +0300198 if verbose:
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300199 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 Dmitriev61115112018-05-31 06:48:43 +0300202 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 Dmitriev3ec2e532018-06-08 04:33:34 +0300208 text = res.content.decode('utf-8',
209 errors='backslashreplace')
210 print(text.replace("\n", prefix), end='')
Dennis Dmitriev61115112018-05-31 06:48:43 +0300211 start[0] = text_size
212 return status
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +0200213
214 helpers.wait(
215 building,
216 timeout=timeout,
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300217 interval=interval,
Dennis Dmitriev13e804b2018-10-09 19:25:14 +0300218 timeout_msg=('Timeout waiting the job {0}:{1} in {2} sec.'
219 .format(name, build_id, timeout)))
Dmitry Tyzhnenkob610afd2018-02-19 15:43:45 +0200220
Hanna Arhipovab2522692020-09-23 15:25:11 +0300221 @retry()
Dmitry Tyzhnenkob610afd2018-02-19 15:43:45 +0200222 def get_build_output(self, name, build_id):
223 return self.__client.get_build_console_output(name, build_id)
Dennis Dmitriev61115112018-05-31 06:48:43 +0300224
Hanna Arhipovab2522692020-09-23 15:25:11 +0300225 @retry(max_count=12)
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300226 def get_progressive_build_output(self, name, build_id, start=0):
Dennis Dmitriev61115112018-05-31 06:48:43 +0300227 '''Get build console text.
228
229 :param name: Job name, ``str``
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300230 :param build_id: Build id, ``int``
231 :param start: Start offset, ``int``
Dennis Dmitriev61115112018-05-31 06:48:43 +0300232 :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 Dmitriev3ec2e532018-06-08 04:33:34 +0300238 'logText/progressiveText?start=%(start)d')
Hanna Arhipovae1f0b472020-01-03 17:38:11 +0200239 req = send_request(
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300240 'GET',
241 self.__client._build_url(PROGRESSIVE_CONSOLE_OUTPUT, locals()))
242 return(self.__client.jenkins_request(req))
Dennis Dmitriev27a96792018-07-30 07:52:03 +0300243
Hanna Arhipovab2522692020-09-23 15:25:11 +0300244 @retry(max_count=12)
Dennis Dmitriev27a96792018-07-30 07:52:03 +0300245 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 Arhipovae1f0b472020-01-03 17:38:11 +0200263 req = send_request(
Dennis Dmitriev27a96792018-07-30 07:52:03 +0300264 'GET',
265 self.__client._build_url(WORKFLOW_DESCRIPTION, locals()))
266 response = self.__client.jenkins_open(req)
267 return json.loads(response)
Dennis Dmitriev8565c342019-02-11 23:45:03 +0200268
Hanna Arhipovab2522692020-09-23 15:25:11 +0300269 @retry(max_count=12)
Dennis Dmitriev8565c342019-02-11 23:45:03 +0200270 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 Arhipovae1f0b472020-01-03 17:38:11 +0200286 req = send_request(
Dennis Dmitriev8565c342019-02-11 23:45:03 +0200287 'GET',
288 self.__client._build_url(DOWNLOAD_URL, locals()))
289
290 response = self.__client.jenkins_request(req)
291 return response.content