-
Notifications
You must be signed in to change notification settings - Fork 4
/
JenkinsHelper.py
executable file
·310 lines (274 loc) · 11.7 KB
/
JenkinsHelper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
#!/usr/bin/env python
"""Jenkins Helper functions
It contains jenkins helper
Run JenkinsHelper --help or JenkinsHelper --help <command> for
detail help."""
from __future__ import (
absolute_import, division, print_function, unicode_literals)
import ast
import logging
import os
import os.path
import re
import sys
try:
# We need to import 'List' and 'Any' for mypy to work
from typing import List, Any # noqa: F401 # pylint: disable=unused-import
except ImportError:
sys.stderr.write("python typing module is not installed" + os.linesep)
from ZanataFunctions import UrlHelper
from ZanataArgParser import ZanataArgParser # pylint: disable=E0401
class JenkinsServer(object):
"""JenkinsServer can connect to a Jenkins server"""
def __init__(self, server_url, user, token):
# type: (str, str,str) -> None
self.url_helper = UrlHelper(
server_url, user, token)
self.server_url = server_url
self.user = user
self.token = token
@classmethod
def add_parser(cls, arg_parser=None, env_sub_commands=None):
# type: (ZanataArgParser) -> ZanataArgParser
"""Add JenkinsServer parameters to a parser"""
if not arg_parser:
arg_parser = ZanataArgParser(description=__doc__)
# Add env
arg_parser.add_env(
'JENKINS_URL', dest='server_url', required=True,
sub_commands=env_sub_commands)
arg_parser.add_env(
'ZANATA_JENKINS_USER', dest='user', required=True,
sub_commands=env_sub_commands)
arg_parser.add_env(
'ZANATA_JENKINS_TOKEN', dest='token', required=True,
sub_commands=env_sub_commands)
return arg_parser
@classmethod
def init_from_parsed_args(cls, args):
"""New an instance from parsed args"""
return cls(args.server_url, args.user, args.token)
class JenkinsJob(object):
"""JenkinsJob object can access a Jenkins Job"""
@staticmethod
def dict_get_elem_by_path(dic, path):
# type (dict, str) -> object
"""Return the elem in python dictionary given path
for example: you can use a/b to retrieve answer from following
dict:
{ 'a': { 'b': 'answer' }}"""
obj = dic
for key in path.split('/'):
if obj[key]:
obj = obj[key]
else:
return None
return obj
@staticmethod
def print_key_value(key, value):
# type (str, str) -> None
"""Pretty print the key and value"""
return "%30s : %s" % (key, value)
def get_elem(self, path):
# type: (str) -> object
"""Get element from the job object"""
return JenkinsJob.dict_get_elem_by_path(self.content, path)
def __repr__(self):
# type: () -> str
result = "\n".join([
JenkinsJob.print_key_value(tup[0], tup[1]) for tup in [
['job_name', self.job_name],
['folder', self.folder],
['branch', self.branch]]])
if self.content:
result += "\n\n%s" % "\n".join([
JenkinsJob.print_key_value(
key, self.get_elem(key)) for key in [
'displayName',
'fullName',
'lastBuild/number',
'lastCompletedBuild/number',
'lastFailedBuild/number',
'lastSuccessfulBuild/number']])
return result
def __init__(self, server, job_name, folder='', branch=''):
# type (JenkinsServer, str, str, str) -> None
self.server = server
self.job_name = job_name
self.folder = folder
self.branch = branch
self.content = None
job_path = "job/%s" % self.job_name
if folder:
job_path = "job/%s/%s" % (folder, job_path)
if branch:
job_path += "/job/%s" % branch
self.url = "%s%s" % (self.server.server_url, job_path)
@classmethod
def add_parser(
cls, arg_parser=None,
only_options=False, env_sub_commands=None):
# type: (ZanataArgParser, bool) -> ZanataArgParser
"""Add JenkinsJob parameters to parser
arg_parser: existing parser to be appended to
only_options: Add only options and JenkinsServer env"""
if not arg_parser or not arg_parser.has_env('JENKINS_URL'):
arg_parser = JenkinsServer.add_parser(
arg_parser, env_sub_commands)
arg_parser.add_common_argument(
'-b', '--branch', type=str,
help='branch or PR name')
arg_parser.add_common_argument(
'-F', '--folder', type=str,
help='GitHub Organization Folder')
if not only_options:
arg_parser.add_common_argument(
'job_name', type=str, help='job name')
# Add sub commands
arg_parser.add_sub_command(
'get-job', None,
help='Show job objects')
arg_parser.add_sub_command(
'get-last-successful-build', None,
help=cls.get_last_successful_build.__doc__)
arg_parser.add_sub_command(
'get-last-successful-artifacts',
{
'-p --artifact-path-patterns': {
'type': str, 'default': '.*',
'help': 'comma split artifact path regex pattern'}}, # noqa: E501, #pylint: disable=line-too-long
help='Get matching last-successful artifacts. Default: .*')
arg_parser.add_sub_command(
'download-last-successful-artifacts',
{
'-p --artifact-path-patterns': {
'type': str, 'default': '.*',
'help': 'comma split artifact path regex'
},
'-d --download-dir': {
'type': str, 'default': '.',
'help': 'Download directory'}
},
help='Get matching last-successful artifacts. Default: .*')
return arg_parser
@classmethod
def init_from_parsed_args(cls, args):
"""New an instance from parsed args"""
server = JenkinsServer.init_from_parsed_args(args)
kwargs = {'job_name': args.job_name}
for k in ['folder', 'branch']:
if hasattr(args, k):
kwargs[k] = getattr(args, k)
return cls(server, **kwargs)
def load(self):
# type: () -> None
"""Load the build object from Jenkins server"""
logging.debug("Loading job from %s/api/python", self.url)
self.content = ast.literal_eval(UrlHelper.read(
"%s/api/python" % self.url))
def get_last_successful_build(self):
# type: () -> JenkinsJobBuild
"""Get last successful build"""
if not self.content:
self.load()
if not self.content:
raise AssertionError("Failed to load job from %s" % self.url)
return JenkinsJobBuild(
self,
int(self.get_elem('lastSuccessfulBuild/number')),
self.get_elem('lastSuccessfulBuild/url'))
def get_last_successful_artifacts(
self, artifact_path_patterns=None):
# type: (List[str]) -> List[str]
"""Get last successful artifacts that matches patterns"""
build = self.get_last_successful_build()
return build.list_artifacts_related_paths(artifact_path_patterns)
def download_last_successful_artifacts(
self, artifact_path_patterns=None, download_dir='.'):
# type: (List[str])-> List[str]
"""Download last successful artifacts that matches patterns.
Returns related path of artifacts
Note the directory structure will be flattern."""
if not artifact_path_patterns:
artifact_path_patterns = ['.*']
build = self.get_last_successful_build()
artifact_path_list = build.list_artifacts_related_paths(
artifact_path_patterns)
for artifact_path in artifact_path_list:
UrlHelper.download_file(
build.url + 'artifact/' + artifact_path,
download_dir=download_dir)
return artifact_path_list
class JenkinsJobBuild(object):
"""Build object for Jenkins job"""
def __init__(self, parent_job, build_number, build_url):
# type (object, int, str) -> None
self.parent_job = parent_job
self.number = build_number
self.url = build_url
self.content = None
def get_elem(self, path):
# type: (str) -> object
"""Get element from the build object"""
return JenkinsJob.dict_get_elem_by_path(self.content, path)
def load(self):
"""Load the build object from Jenkins server"""
logging.debug("Loading build from %sapi/python", self.url)
self.content = ast.literal_eval(UrlHelper.read(
"%s/api/python" % self.url))
def list_artifacts_related_paths(self, artifact_path_patterns=None):
# type: (str) -> List[str]
"""Return a List of relativePaths of artifacts
that matches the path patterns"""
if not artifact_path_patterns:
artifact_path_patterns = ['.*']
if not self.content:
self.load()
if not self.content:
raise AssertionError("Failed to load build from %s" % self.url)
result = []
for artifact in self.content['artifacts']:
for pattern in artifact_path_patterns:
if re.search(pattern, artifact['relativePath']):
result.append(artifact['relativePath'])
break # Only append once
return result
def __repr__(self):
# type: () -> str
result = "\n".join([
JenkinsJob.print_key_value(
tup[0], str(tup[1])) for tup in [
['number', self.number],
['url', self.url]]])
if self.content:
result += "\n\n%s" % "\n".join([
JenkinsJob.print_key_value(
key, self.get_elem(key)) for key in [
'nextBuild/number',
'previousBuild/number']])
result += "\n\nArtifacts:\n%s" % "\n ".join(
self.list_artifacts_related_paths())
return result
def run_sub_command(args):
# type (ZanataArgParser.Namespace) -> None
"""Run the sub command"""
job = JenkinsJob.init_from_parsed_args(args)
job.load()
if args.sub_command == 'get-job':
print(job)
elif args.sub_command == 'get-last-successful-build':
build = job.get_last_successful_build()
build.load()
print(build)
elif args.sub_command == 'get-last-successful-artifacts':
print('\n'.join(
job.get_last_successful_artifacts(
args.artifact_path_patterns.split(','))
))
elif args.sub_command == 'download-last-successful-artifacts':
artifact_path_list = job.download_last_successful_artifacts(
args.artifact_path_patterns.split(','),
args.download_dir)
print("Downloaded files %s" % '\n'.join(artifact_path_list))
if __name__ == '__main__':
run_sub_command(JenkinsJob.add_parser().parse_all())