-
Notifications
You must be signed in to change notification settings - Fork 20
/
npm_job_worker.py
267 lines (233 loc) · 10.4 KB
/
npm_job_worker.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
#!/usr/bin/env python
#
# Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
#
import argparse
import ast
import base64
import boto3
import botocore
import errno
import os
import requests
import shutil
import subprocess
import sys
import tempfile
import time
import zipfile
from botocore.exceptions import ClientError
from boto3.session import Session
import boto.utils
parser = argparse.ArgumentParser(description='Custom action AWS CodePipeline worker to publish Node.js artifacts to an Artifactory NPM repository')
parser.add_argument("--version", help="Set the custom action version the worker will use. Default is '1'")
args = parser.parse_args()
if len(sys.argv) < 2:
print('Setting Custom Action version to 1')
sys.argv.append('1')
CA_VERSION = sys.argv[-1]
instance_info = boto.utils.get_instance_identity()
worker_region = instance_info['document']['region']
codepipeline = boto3.client('codepipeline', region_name=worker_region)
def action_type():
ActionType = {
'category': 'Deploy',
'owner': 'Custom',
'provider': 'Artifactory',
'version': CA_VERSION }
return(ActionType)
def poll_for_jobs():
try:
artifactory_action_type = action_type()
print(artifactory_action_type)
jobs = codepipeline.poll_for_jobs(actionTypeId=artifactory_action_type)
while not jobs['jobs']:
time.sleep(10)
jobs = codepipeline.poll_for_jobs(actionTypeId=artifactory_action_type)
if jobs['jobs']:
print('Job found')
return jobs['jobs'][0]
except ClientError as e:
print("Received an error: %s" % str(e))
raise
def get_job_info(job):
nonce = job['nonce']
jobId = job['id']
inputBucketName = job['data']['inputArtifacts'][0]['location']['s3Location']['bucketName']
inputObjectKey = job['data']['inputArtifacts'][0]['location']['s3Location']['objectKey']
try:
outputBucketName = job['data']['outputArtifacts'][0]['location']['s3Location']['bucketName']
outputObjectKey = job['data']['outputArtifacts'][0]['location']['s3Location']['objectKey']
except IndexError as e:
print('Error getting output Bucket: %s' % str(e))
print('No output artifacts defined, setting outputBucketName and outputObjectKey to []')
outputBucketName = []
outputObjectKey = []
access_token = job['data']['artifactCredentials']['accessKeyId']
sa_key = job['data']['artifactCredentials']['secretAccessKey']
s_Token = job['data']['artifactCredentials']['sessionToken']
configuration = job['data']['actionConfiguration']['configuration']
return(nonce, jobId, inputBucketName, inputObjectKey, outputBucketName, outputObjectKey, access_token, sa_key, s_Token, configuration)
def job_acknowledge(jobId, nonce):
try:
print('Acknowledging job for jobId %s' % jobId)
result = codepipeline.acknowledge_job(jobId=jobId, nonce=nonce)
return(result)
except Exception as e:
print("Received an error when trying to acknowledge the job: %s" % str(e))
raise
def get_bucket_location(bucketName, init_client):
region = init_client.get_bucket_location(Bucket=bucketName)['LocationConstraint']
if not region:
region = 'us-east-1'
return(region)
def get_s3_artifact(bucketName, objectKey, ak, sk, st):
init_s3 = boto3.client('s3')
region = get_bucket_location(bucketName, init_s3)
session = Session(aws_access_key_id=ak,
aws_secret_access_key=sk,
aws_session_token=st)
s3 = session.resource('s3',
region_name=region,
config=botocore.client.Config(signature_version='s3v4'))
try:
tempdirname = tempfile.mkdtemp()
except OSError as e:
print('Could not write temp directory %s' % tempdirname)
raise
bucket = s3.Bucket(bucketName)
obj = bucket.Object(objectKey)
filename = tempdirname + '/' + objectKey
try:
if os.path.dirname(objectKey):
directory = os.path.dirname(filename)
os.makedirs(directory)
print('Downloading the %s object and writing it to disk in %s location' % (objectKey, tempdirname))
with open(filename, 'wb') as data:
obj.download_fileobj(data)
except ClientError as e:
print('Downloading the object and writing the file to disk raised this error: ' + str(e))
raise
return(filename, tempdirname)
def unzip_codepipeline_artifact(artifact, origtmpdir):
# create a new temp directory
# Unzip artifact into new directory
try:
newtempdir = tempfile.mkdtemp()
print('Extracting artifact %s into temporary directory %s' % (artifact, newtempdir))
zip_ref = zipfile.ZipFile(artifact, 'r')
zip_ref.extractall(newtempdir)
zip_ref.close()
shutil.rmtree(origtmpdir)
return(os.listdir(newtempdir), newtempdir)
except OSError as e:
if e.errno != errno.EEXIST:
shutil.rmtree(newtempdir)
raise
def gen_artifactory_auth_token(configuration):
hostname = configuration['ArtifactoryHost']
username = configuration['UserName']
pwd = configuration['Password']
# We want to get a token from Artifactory so we don't save the Username and Password in the .npmrc file: curl -uUSERNAME:PASSWORD -XPOST "http://ARTIFACTORY_HOST/artifactory/api/security/token" -d "username=config['UserName']" -d "scope=member-of-groups:*"
data = {'username': username, 'scope': 'member-of-groups:*'}
token_url = hostname + '/artifactory/api/security/token'
get_token = requests.post(token_url, data=data, auth=(username, pwd))
token = ast.literal_eval(get_token.text)['access_token']
return(token, hostname, username)
def create_npmconfig_file(configuration, username, token):
up = username + ':' + token
enc_up = base64.b64encode(up)
email = configuration['EmailAddress']
print("Get the home dir for the user running")
homedir = os.path.expanduser('~')
npmconfigfile = homedir + '/.npmrc'
print("Writing npm config file to homedir: " + homedir)
print("npmconfig file: " + npmconfigfile)
with open(npmconfigfile, 'w') as config:
try:
config.write("_auth = " + enc_up + "\n")
config.write("email = " + email + "\n")
config.write("always-auth = true")
return(npmconfigfile)
except Exception as e:
print("Received error when trying to write the NPM config file %s: %s" % (str(npmconfigfile), str(e)))
def push_to_npm(configuration, artifact_list, temp_dir, jobId):
reponame = configuration['RepoKey']
art_type = configuration['TypeOfArtifact']
print("Putting artifact into NPM repository " + reponame)
token, hostname, username = gen_artifactory_auth_token(configuration)
npmconfigfile = create_npmconfig_file(configuration, username, token)
url = hostname + '/artifactory/api/' + art_type + '/' + reponame
print("Changing directory to " + str(temp_dir))
os.chdir(temp_dir)
try:
print("Publishing following files to the repository: %s " % os.listdir(temp_dir))
print("Sending artifact to Artifactory NPM registry URL: " + url)
subprocess.call(["npm", "config", "set", "registry", url])
req = subprocess.call(["npm", "publish", "--registry", url])
print("Return code from npm publish: " + str(req))
if req != 0:
err_msg = "npm ERR! Recieved non OK response while sending response to Artifactory. Return code from npm publish: " + str(req)
signal_failure(jobId, err_msg)
else:
signal_success(jobId)
except requests.exceptions.RequestException as e:
print("Received an error when trying to commit artifact %s to repository %s: " % (str(art_type), str(configuration['RepoKey']), str(e)))
raise
return(req, npmconfigfile)
def signal_failure(jobId, msg):
print("Signaling failure, reason: %s" % msg)
try:
failure = codepipeline.put_job_failure_result(jobId=jobId, failureDetails={'type': 'JobFailed', 'message': msg})
return failure
except Exception as e:
print("Received an error when attempting to put job failure result: %s" % str(e))
def signal_success(jobId):
print("Signaling success to CodePipeline")
try:
success = codepipeline.put_job_success_result(jobId=jobId, currentRevision={'revision': jobId, 'changeIdentifier': jobId}, executionDetails={'summary': 'Job completed successfully', 'percentComplete': 100})
return success
except Exception as e:
print("Received this error when attempting to put job success result: %s" % str(e))
raise
def cleanup(npmconfigfile, tempdir):
try:
os.remove(npmconfigfile)
shutil.rmtree(tempdir)
subprocess.call(["npm", "cache", "clean"])
homedir = os.path.expanduser('~')
npmcache = homedir + '/.npm'
shutil.rmtree(npmcache)
except Exception as e:
print("Received error when attempting to clean up: %s" % str(e))
raise
def main():
while True:
try:
job = poll_for_jobs()
nonce, jobId, inputS3, inputObject, outputS3, outputObject, ak, sk, st, config = get_job_info(job)
acknowledge = job_acknowledge(jobId, nonce)
print('Acknowledge job returned: ' + str(acknowledge))
artifact, tempdirname = get_s3_artifact(inputS3, inputObject, ak, sk, st)
artifact_list, newtempdir = unzip_codepipeline_artifact(artifact, tempdirname)
pkg = config['TypeOfArtifact']
if pkg == 'npm':
publish_stat, npmconfigname = push_to_npm(config, artifact_list, newtempdir, jobId)
print('Publishing to repository resulted in the status code: %s' % str(publish_stat))
cleanup(npmconfigname, newtempdir)
except Exception as e:
print(" Received an error: %s" % e)
raise
if __name__ == '__main__':
sys.exit(main())