blob: b9f6a02d2920949a6a61737e6915035777f8f7b1 [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):
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 Dmitrieva5bd1652018-05-31 20:57:19 +030085 def run_build(self, name, params=None, timeout=600, verbose=False):
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +020086 params = params or self.make_defults_params(name)
Dennis Dmitrieva5bd1652018-05-31 20:57:19 +030087 num = self.__client.build_job(name, params)
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +030088 time.sleep(2) # wait while job is started
Dennis Dmitrieva5bd1652018-05-31 20:57:19 +030089
Dmitry Tyzhnenkob39de052019-03-21 17:05:07 +020090 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 Dmitrieva5bd1652018-05-31 20:57:19 +0300108 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 Dmitriev3ec2e532018-06-08 04:33:34 +0300113 return (status and
114 'executable' in (queued or {}) and
115 'number' in (queued['executable'] or {}))
Dennis Dmitrieva5bd1652018-05-31 20:57:19 +0300116
117 helpers.wait(
118 is_blocked,
119 timeout=timeout,
120 interval=30,
121 timeout_msg='Timeout waiting to run the job [{}]'.format(name))
Dennis Dmitrieva5bd1652018-05-31 20:57:19 +0300122 build_id = self.__client.get_queue_item(num)['executable']['number']
Dmitry Tyzhnenkob39de052019-03-21 17:05:07 +0200123
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 Tyzhnenko5a5d8da2017-12-14 14:14:42 +0200143 return name, build_id
144
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300145 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 Dmitriev61115112018-05-31 06:48:43 +0300162 start = [0]
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300163 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 Tyzhnenko5a5d8da2017-12-14 14:14:42 +0200169
170 def building():
Dmitry Tyzhnenko80ce0202019-02-07 13:27:19 +0200171 try:
172 status = not self.build_info(name, build_id)['building']
173 except ConnectionError:
174 status = False
175
Dennis Dmitrieva5bd1652018-05-31 20:57:19 +0300176 if verbose:
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300177 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 Dmitriev61115112018-05-31 06:48:43 +0300180 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 Dmitriev3ec2e532018-06-08 04:33:34 +0300186 text = res.content.decode('utf-8',
187 errors='backslashreplace')
188 print(text.replace("\n", prefix), end='')
Dennis Dmitriev61115112018-05-31 06:48:43 +0300189 start[0] = text_size
190 return status
Dmitry Tyzhnenko5a5d8da2017-12-14 14:14:42 +0200191
192 helpers.wait(
193 building,
194 timeout=timeout,
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300195 interval=interval,
Dennis Dmitriev13e804b2018-10-09 19:25:14 +0300196 timeout_msg=('Timeout waiting the job {0}:{1} in {2} sec.'
197 .format(name, build_id, timeout)))
Dmitry Tyzhnenkob610afd2018-02-19 15:43:45 +0200198
199 def get_build_output(self, name, build_id):
200 return self.__client.get_build_console_output(name, build_id)
Dennis Dmitriev61115112018-05-31 06:48:43 +0300201
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300202 def get_progressive_build_output(self, name, build_id, start=0):
Dennis Dmitriev61115112018-05-31 06:48:43 +0300203 '''Get build console text.
204
205 :param name: Job name, ``str``
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300206 :param build_id: Build id, ``int``
207 :param start: Start offset, ``int``
Dennis Dmitriev61115112018-05-31 06:48:43 +0300208 :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 Dmitriev3ec2e532018-06-08 04:33:34 +0300214 'logText/progressiveText?start=%(start)d')
Hanna Arhipovae1f0b472020-01-03 17:38:11 +0200215 req = send_request(
Dennis Dmitriev3ec2e532018-06-08 04:33:34 +0300216 'GET',
217 self.__client._build_url(PROGRESSIVE_CONSOLE_OUTPUT, locals()))
218 return(self.__client.jenkins_request(req))
Dennis Dmitriev27a96792018-07-30 07:52:03 +0300219
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 Arhipovae1f0b472020-01-03 17:38:11 +0200238 req = send_request(
Dennis Dmitriev27a96792018-07-30 07:52:03 +0300239 'GET',
240 self.__client._build_url(WORKFLOW_DESCRIPTION, locals()))
241 response = self.__client.jenkins_open(req)
242 return json.loads(response)
Dennis Dmitriev8565c342019-02-11 23:45:03 +0200243
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 Arhipovae1f0b472020-01-03 17:38:11 +0200260 req = send_request(
Dennis Dmitriev8565c342019-02-11 23:45:03 +0200261 'GET',
262 self.__client._build_url(DOWNLOAD_URL, locals()))
263
264 response = self.__client.jenkins_request(req)
265 return response.content