-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathnexus
396 lines (324 loc) · 12.1 KB
/
nexus
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
#!/usr/bin/env python
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'metadata_version': '1.0'}
DOCUMENTATION = '''
---
module: nexus
short_description: Download and install an artifact from storage.
See https://github.com/mihxil/ansible-nexus
author: Michiel Meeuwissen, Marc Bosserhoff, Rostyslav Fridman, Giles Westwood
options:
nexus:
required: true
description:
- Base url of the nexus
artifactory:
required: true
description:
- Base url of the artifactory
repository:
required: false
description:
- Optional the used repository
- Defaults to 'public'
destdir:
required: false
description:
- The destination dir of the downloaded artifacts
- Defaults to '/tmp/downloaded_artifacts'
artifactId:
required:: true
description:
- The artifact to download. The format is separated by ':' and
will be connected like so: groupId:artifactId:version
extension:
required: false
description:
- The artifact extension (Defaults to 'war')
force:
required: false
description:
- Forces the download of the artifacts if they are present
in the target destination
http_user:
required: false
description:
- If the storage need a basic authentication, the user name
can be provided here
http_pass:
required: false
description:
- If the storage need a basic authentication, the password
can be provided here
'''
EXAMPLES = '''
- name: get statistics jar
nexus:
nexus=http://nexus.vpro.nl
artifactId=nl.vpro.stats:stats-backend:0.3-SNAPSHOT
extension=jar
- name: get statistics jar
nexus:
artifactory=http://artifactory.vpro.nl
artifactId=nl.vpro.stats:stats-backend:0.3-SNAPSHOT
extension=jar
'''
from ansible.module_utils.basic import *
from ansible.module_utils.parsing.convert_bool import *
import urllib2
import base64
from datetime import datetime
from wsgiref.handlers import format_date_time
import xml.etree.ElementTree as ET
# download an artifact from nexus or artifactory
def loadArtifact(url, dest, http_user, http_pass, force, remote_md5_different):
result = dict(url=url, http_user=http_user, force=force)
try:
headers = {}
# Support if modified header if not using 'force' flag or if md5 is detected as different from remote
# to always download artifacts
if os.path.isfile(dest) and not force and not remote_md5_different:
headers['IF-Modified-Since'] = \
format_date_time(time.mktime(datetime.fromtimestamp(
os.path.getmtime(dest)).timetuple()))
if http_user and http_pass:
headers['Authorization'] = "Basic %s" % \
base64.encodestring('%s:%s' %
(http_user, http_pass)).replace('\n', '')
request = urllib2.Request(url, None, headers)
response = urllib2.urlopen(request)
if response.code == 200:
handle = open(dest, 'wb')
handle.write(response.read())
handle.close()
# Everything went ok, set result set accordingly
result['failed'] = False
result['code'] = response.code
result['msg'] = "OK"
result['changed'] = True
return result
except Exception as e:
# In case of error, let ansible stop the playbook
result['failed'] = True
result['changed'] = False
result['msg'] = "Unknown error"
if hasattr(e, "code"):
result['code'] = e.code
if hasattr(e, "reason"):
result['msg'] = e.reason
else:
result['msg'] = "The server couldn\'t fulfill the request."
# In case of 304 the resource is still in place and not updated
if e.code == 304:
result['failed'] = False
return result
raise e
# query nexus for the md5sum of an artifact
def get_remote_md5(nexus, artifactory, url, http_user, http_pass):
if artifactory:
result = 'unsupported'
return result
try:
headers = {}
if http_user and http_pass:
headers['Authorization'] = "Basic %s" % \
base64.encodestring('%s:%s' %
(http_user, http_pass)).replace('\n', '')
md5_url = url + '.md5'
request = urllib2.Request(url, None, headers)
response = urllib2.urlopen(request)
result = response.read()
return result
except Exception as e:
# In case of error, let ansible stop the playbook
result['failed'] = True
result['msg'] = "Unknown error"
if hasattr(e, "code"):
result['code'] = e.code
if hasattr(e, "reason"):
result['msg'] = e.reason
else:
result['msg'] = "The server couldn\'t fulfill the request."
return result
raise e
# query nexus or artifactory for version number of an artifact
# if latest is specified return the latest version of an artifact
def get_version(nexus, artifactory, url, version_to_find, http_user, http_pass):
result = dict(url=url, http_user=http_user)
if "SNAPSHOT" in version_to_find:
url = url + "/" + version_to_find
try:
headers = {}
if http_user and http_pass:
headers['Authorization'] = "Basic %s" % \
base64.encodestring('%s:%s' %
(http_user, http_pass)).replace('\n', '')
request = urllib2.Request(url + "/maven-metadata.xml", None, headers)
response = urllib2.urlopen(request)
xml = response.read()
root = ET.fromstring(xml)
if artifactory:
if any(x in version_to_find.lower() for x in ["latest", "release"]):
for version in root.findall('versioning'):
return version.find(version_to_find.lower()).text
if "SNAPSHOT" in version_to_find:
return root.find(
'versioning/snapshotVersions/snapshotVersion/value').text
# http://articles.javatalks.ru/articles/32
if nexus:
for latest in root.findall('./versioning/versions/version[last()]'):
return latest.text
except Exception as e:
# In case of error, let ansible stop the playbook
result['failed'] = True
result['msg'] = "Unknown error"
if hasattr(e, "code"):
result['code'] = e.code
if hasattr(e, "reason"):
result['msg'] = e.reason
else:
result['msg'] = "The server couldn\'t fulfill the request."
return result
raise e
import hashlib
import os.path
def md5(fname):
hash_md5 = hashlib.md5()
if os.path.isfile(fname):
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
else:
md5_result = 'no file'
return md5_result
def main():
module = AnsibleModule(
argument_spec=dict(
nexus=dict(required=False),
artifactory=dict(required=False),
repository=dict(required=False, default="public"),
destdir=dict(required=False, default="/tmp/downloaded_artifacts"),
filename=dict(required=False, default=None),
artifactId=dict(required=True),
extension=dict(required=False, default="war"),
force=dict(required=False, default=False, type='bool'),
http_user=dict(required=False),
http_pass=dict(required=False, no_log=True)
),
supports_check_mode=False
)
nexus = module.params['nexus']
artifactory = module.params['artifactory']
repository = module.params['repository']
destdir = module.params['destdir']
artifactId = module.params['artifactId']
filename = module.params['filename']
extension = module.params['extension']
force = module.boolean(module.params['force'])
http_user = module.params['http_user']
http_pass = module.params['http_pass']
# Prepare strings and urls before the storage call
split = artifactId.split(":")
(groupId, artifactId, version) = split[0:3]
classifier = split[3] if len(split) >= 4 else ""
urlAppendClassifier = "&c=" + classifier if classifier else ""
postfix = "-" + classifier if classifier else ""
if repository == "":
repository = "snapshots" if "SNAPSHOT" in version else "releases"
original_version = version
group_version = version
# Retrieve latest artifact API functionality is available only in
# Artifactory Pro. We will have to use a workaround
if re.search('(release|latest|snapshot)', version.lower()):
if artifactory:
artifact_url = artifactory + "/" + repository + "/" + \
groupId.replace(".", "/") + "/" + artifactId
if nexus:
artifact_url = nexus + "/service/local/repositories/" + repository + "/content/" + groupId.replace(".", "/") + "/" + artifactId
version = get_version(
nexus,
artifactory,
artifact_url,
original_version,
http_user,
http_pass
)
if "failed" in version:
module.fail_json(
artifactId=artifactId,
url=artifact_url,
repository=repository,
msg=version['msg'],
result=version
)
if any(x in original_version.lower() for x in ["latest", "release"]):
group_version = version
# Create generic filename if filename is not set
if filename is None:
filename = artifactId + "-" + version + postfix + "." + extension
if nexus:
url = nexus + "/service/local/artifact/maven/redirect?r=" + \
repository + "&g=" + groupId + "&a=" + artifactId + "&v=" + \
version + "&e=" + extension + urlAppendClassifier
storage = nexus
if artifactory:
url = artifactory + "/" + repository + "/" + \
groupId.replace(".", "/") + "/" + artifactId + "/" + group_version + \
"/" + filename
storage = artifactory
if not os.path.exists(destdir):
os.mkdir(destdir)
dest = destdir + "/" + filename
if artifactory:
md5_url = 'unknown'
if nexus:
md5_url = nexus + "/service/local/repositories/" + repository + "/content/" + groupId.replace(".", "/") + "/" \
+ artifactId + "/" + version + "/" + artifactId + '-' + version + "." + extension + ".md5"
local_md5 = md5(dest)
remote_md5 = get_remote_md5(
nexus,
artifactory,
md5_url,
http_user,
http_pass
)
remote_md5_different = False
if str(remote_md5) == str(local_md5):
module.exit_json(
dest=dest,
remote_md5=remote_md5,
local_md5=local_md5,
md5match=True,
filename=filename,
artifactId=artifactId,
changed=False
)
else:
remote_md5_different = True
# Try to download an artifact from nexus or artifactory
result = loadArtifact(url, dest, http_user, http_pass, force, remote_md5_different)
if result['failed']:
module.fail_json(
artifactId=artifactId,
storage=storage,
url=url,
filename=filename,
dest=dest,
repository=repository,
remote_md5_different=remote_md5_different,
changed=result['changed'],
msg=result['msg'],
result=result
)
module.exit_json(
dest=dest,
filename=filename,
remote_md5=remote_md5,
local_md5=local_md5,
remote_md5_different=remote_md5_different,
artifactId=artifactId,
changed=result['changed']
)
main()