blob: 0fdff80ba4c108feaeffa1330d99e631cbb924d5 [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 Arhipovae1f0b472020-01-03 17:38:11 +020014def 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 Tyzhnenko5a5d8da2017-12-14 14:14:42 +020045class JenkinsClient(object):
46
Dennis Dmitriev27a96792018-07-30 07:52:03 +030047 def __init__(self, host=None, username='admin', password='r00tme'):
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +020048 host = host or 'http://172.16.44.33:8081'
obutenkoca858402019-07-04 18:31:39 +030049 self.__client = jenkins.Jenkins(
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +020050 host,
51 username=username,
52 password=password)
obutenkoca858402019-07-04 18:31:39 +030053 self.__client._session.verify = False
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +020054
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):
Hanna Arhipovae1f8b242020-03-31 13:37:11 +030062 max_count = 6
63 for count in range(max_count):
64 try:
65 return self.__client.get_job_info(name)
66 except jenkins.JenkinsException as err:
67 print("caught JenkinsException: {err}. \
68 repeat {count}/{max_count}".
69 format(err=err,
70 count=count,
71 max_count=max_count))
72 time.sleep(10)
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +020073
74 def list_builds(self, name):
75 return self.job_info(name).get('builds')
76
77 def build_info(self, name, build_id):
78 return self.__client.get_build_info(name, build_id)
79
80 def job_params(self, name):
81 job = self.job_info(name)
82 job_params = next(
83 p for p in job['property'] if
84 'hudson.model.ParametersDefinitionProperty' == p['_class'])
85 job_params = job_params['parameterDefinitions']
86 return job_params
87
88 def make_defults_params(self, name):
89 job_params = self.job_params(name)
90 def_params = dict(
91 [(j['name'], j['defaultParameterValue']['value'])
92 for j in job_params])
93 return def_params
94
Dennis Dmitrieva5bd1652018-05-31 20:57:19 +030095 def run_build(self, name, params=None, timeout=600, verbose=False):
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +020096 params = params or self.make_defults_params(name)
Dennis Dmitrieva5bd1652018-05-31 20:57:19 +030097 num = self.__client.build_job(name, params)
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +030098 time.sleep(2) # wait while job is started
Dennis Dmitrieva5bd1652018-05-31 20:57:19 +030099
Dmitry Tyzhnenkob39de052019-03-21 17:05:07 +0200100 def is_build_queued():
101 try:
102 item = self.__client.get_queue_item(num)
103 ts = item['inQueueSince'] / 1000
104 since_time = datetime.datetime.fromtimestamp(ts)
105 print("Build in the queue since {}".format(since_time))
106 return True
107 except jenkins.JenkinsException:
108 if verbose:
109 print("Build have not been queued {} yet".format(num))
110
111 helpers.wait(
112 is_build_queued,
113 timeout=timeout,
114 interval=30,
115 timeout_msg='Timeout waiting to queue the build '
116 'for {} job'.format(name))
117
Dennis Dmitrieva5bd1652018-05-31 20:57:19 +0300118 def is_blocked():
119 queued = self.__client.get_queue_item(num)
120 status = not queued['blocked']
121 if not status and verbose:
122 print("pending the job [{}] : {}".format(name, queued['why']))
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300123 return (status and
124 'executable' in (queued or {}) and
125 'number' in (queued['executable'] or {}))
Dennis Dmitrieva5bd1652018-05-31 20:57:19 +0300126
127 helpers.wait(
128 is_blocked,
129 timeout=timeout,
130 interval=30,
131 timeout_msg='Timeout waiting to run the job [{}]'.format(name))
Dennis Dmitrieva5bd1652018-05-31 20:57:19 +0300132 build_id = self.__client.get_queue_item(num)['executable']['number']
Dmitry Tyzhnenkob39de052019-03-21 17:05:07 +0200133
134 def is_build_started():
135 try:
136 build = self.__client.get_build_info(name, build_id)
137 ts = float(build['timestamp']) / 1000
138 start_time = datetime.datetime.fromtimestamp(ts)
139 print("the build {} in {} have started at {} UTC".format(
140 build_id, name, start_time))
141 return True
142 except jenkins.JenkinsException:
143 if verbose:
144 print("the build {} in {} have not strated yet".format(
145 build_id, name))
146 helpers.wait(
147 is_build_started,
148 timeout=timeout,
149 interval=30,
150 timeout_msg='Timeout waiting to run build of '
151 'the job [{}]'.format(name))
152
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +0200153 return name, build_id
154
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300155 def wait_end_of_build(self, name, build_id, timeout=600, interval=5,
156 verbose=False, job_output_prefix=''):
157 '''Wait until the specified build is finished
158
159 :param name: ``str``, job name
160 :param build_id: ``int``, build id
161 :param timeout: ``int``, timeout waiting the job, sec
162 :param interval: ``int``, interval of polling the job result, sec
163 :param verbose: ``bool``, print the job console updates during waiting
164 :param job_output_prefix: ``str``, print the prefix for each console
165 output line, with the pre-defined
166 substitution keys:
167 - '{name}' : the current job name
168 - '{build_id}' : the current build-id
169 - '{time}' : the current time
170 :returns: requests object with headers and console output, ``obj``
171 '''
Dennis Dmitriev61115112018-05-31 06:48:43 +0300172 start = [0]
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300173 time_str = time.strftime("%H:%M:%S")
174 prefix = "\n" + job_output_prefix.format(job_name=name,
175 build_number=build_id,
176 time=time_str)
177 if verbose:
178 print(prefix, end='')
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +0200179
180 def building():
Dmitry Tyzhnenko80ce0202019-02-07 13:27:19 +0200181 try:
182 status = not self.build_info(name, build_id)['building']
183 except ConnectionError:
184 status = False
185
Dennis Dmitrieva5bd1652018-05-31 20:57:19 +0300186 if verbose:
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300187 time_str = time.strftime("%H:%M:%S")
188 prefix = "\n" + job_output_prefix.format(
189 job_name=name, build_number=build_id, time=time_str)
Dennis Dmitriev61115112018-05-31 06:48:43 +0300190 res = self.get_progressive_build_output(name,
191 build_id,
192 start=start[0])
193 if 'X-Text-Size' in res.headers:
194 text_size = int(res.headers['X-Text-Size'])
195 if start[0] < text_size:
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300196 text = res.content.decode('utf-8',
197 errors='backslashreplace')
198 print(text.replace("\n", prefix), end='')
Dennis Dmitriev61115112018-05-31 06:48:43 +0300199 start[0] = text_size
200 return status
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +0200201
202 helpers.wait(
203 building,
204 timeout=timeout,
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300205 interval=interval,
Dennis Dmitriev13e804b2018-10-09 19:25:14 +0300206 timeout_msg=('Timeout waiting the job {0}:{1} in {2} sec.'
207 .format(name, build_id, timeout)))
Dmitry Tyzhnenkob610afd2018-02-19 15:43:45 +0200208
209 def get_build_output(self, name, build_id):
210 return self.__client.get_build_console_output(name, build_id)
Dennis Dmitriev61115112018-05-31 06:48:43 +0300211
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300212 def get_progressive_build_output(self, name, build_id, start=0):
Dennis Dmitriev61115112018-05-31 06:48:43 +0300213 '''Get build console text.
214
215 :param name: Job name, ``str``
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300216 :param build_id: Build id, ``int``
217 :param start: Start offset, ``int``
Dennis Dmitriev61115112018-05-31 06:48:43 +0300218 :returns: requests object with headers and console output, ``obj``
219 '''
220 folder_url, short_name = self.__client._get_job_folder(name)
221
222 PROGRESSIVE_CONSOLE_OUTPUT = (
223 '%(folder_url)sjob/%(short_name)s/%(build_id)d/'
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300224 'logText/progressiveText?start=%(start)d')
Hanna Arhipovae1f0b472020-01-03 17:38:11 +0200225 req = send_request(
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300226 'GET',
227 self.__client._build_url(PROGRESSIVE_CONSOLE_OUTPUT, locals()))
228 return(self.__client.jenkins_request(req))
Dennis Dmitriev27a96792018-07-30 07:52:03 +0300229
230 def get_workflow(self, name, build_id, enode=None, mode='describe'):
231 '''Get workflow results from pipeline job
232
233 :param name: job name
234 :param build_id: str, build number or 'lastBuild'
235 :param enode: int, execution node in the workflow
236 :param mode: the stage or execution node description if 'describe',
237 the execution node log if 'log'
238 '''
239 folder_url, short_name = self.__client._get_job_folder(name)
240
241 if enode:
242 WORKFLOW_DESCRIPTION = (
243 '%(folder_url)sjob/%(short_name)s/%(build_id)s/'
244 'execution/node/%(enode)d/wfapi/%(mode)s')
245 else:
246 WORKFLOW_DESCRIPTION = (
247 '%(folder_url)sjob/%(short_name)s/%(build_id)s/wfapi/%(mode)s')
Hanna Arhipovae1f0b472020-01-03 17:38:11 +0200248 req = send_request(
Dennis Dmitriev27a96792018-07-30 07:52:03 +0300249 'GET',
250 self.__client._build_url(WORKFLOW_DESCRIPTION, locals()))
251 response = self.__client.jenkins_open(req)
252 return json.loads(response)
Dennis Dmitriev8565c342019-02-11 23:45:03 +0200253
254 def get_artifact(self, name, build_id, artifact_path, destination_name):
255 '''Wait until the specified build is finished
256
257 :param name: ``str``, job name
258 :param build_id: ``str``, build id or "lastBuild"
259 :param artifact_path: ``str``, path and filename of the artifact
260 relative to the job URL
261 :param artifact_path: ``str``, destination path and filename
262 on the local filesystem where to save
263 the artifact content
264 :returns: requests object with headers and console output, ``obj``
265 '''
266 folder_url, short_name = self.__client._get_job_folder(name)
267
268 DOWNLOAD_URL = ('%(folder_url)sjob/%(short_name)s/%(build_id)s/'
269 'artifact/%(artifact_path)s')
Hanna Arhipovae1f0b472020-01-03 17:38:11 +0200270 req = send_request(
Dennis Dmitriev8565c342019-02-11 23:45:03 +0200271 'GET',
272 self.__client._build_url(DOWNLOAD_URL, locals()))
273
274 response = self.__client.jenkins_request(req)
275 return response.content