function.py
17.2 KB
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
# Copyright (c) 2014, 2015 Mitch Garnaat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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 logging
import os
import zipfile
import time
import shutil
import hashlib
import uuid
from botocore.exceptions import ClientError
import kappa.awsclient
import kappa.log
LOG = logging.getLogger(__name__)
class Function(object):
excluded_dirs = ['boto3', 'botocore', 'concurrent', 'dateutil',
'docutils', 'futures', 'jmespath', 'python_dateutil']
excluded_files = ['.gitignore']
def __init__(self, context, config):
self._context = context
self._config = config
self._lambda_client = kappa.awsclient.create_client(
'lambda', context.session)
self._response = None
self._log = None
@property
def name(self):
return self._context.name
@property
def runtime(self):
return self._config['runtime']
@property
def handler(self):
return self._config['handler']
@property
def dependencies(self):
return self._config.get('dependencies', list())
@property
def description(self):
return self._config['description']
@property
def timeout(self):
return self._config['timeout']
@property
def memory_size(self):
return self._config['memory_size']
@property
def zipfile_name(self):
return '{}.zip'.format(self._context.name)
@property
def tests(self):
return self._config.get('tests', '_tests')
@property
def permissions(self):
return self._config.get('permissions', list())
@property
def log(self):
if self._log is None:
log_group_name = '/aws/lambda/%s' % self.name
self._log = kappa.log.Log(self._context, log_group_name)
return self._log
@property
def code_sha_256(self):
return self._get_response_configuration('CodeSha256')
@property
def arn(self):
return self._get_response_configuration('FunctionArn')
@property
def alias_arn(self):
return self.arn + ':{}'.format(self._context.environment)
@property
def repository_type(self):
return self._get_response_code('RepositoryType')
@property
def location(self):
return self._get_response_code('Location')
@property
def version(self):
return self._get_response_configuration('Version')
@property
def deployment_uri(self):
return 'https://{}.execute-api.{}.amazonaws.com/{}'.format(
self.api_id, self._apigateway_client.region_name,
self._context.environment)
def _get_response(self):
if self._response is None:
try:
self._response = self._lambda_client.call(
'get_function',
FunctionName=self.name)
LOG.debug(self._response)
except Exception:
LOG.debug('Unable to find ARN for function: %s', self.name)
return self._response
def _get_response_configuration(self, key, default=None):
value = None
response = self._get_response()
if response:
if 'Configuration' in response:
value = response['Configuration'].get(key, default)
return value
def _get_response_code(self, key, default=None):
value = None
response = self._get_response
if response:
if 'Configuration' in response:
value = response['Configuration'].get(key, default)
return value
def _check_function_md5(self):
# Zip up the source code and then compute the MD5 of that.
# If the MD5 does not match the cached MD5, the function has
# changed and needs to be updated so return True.
changed = True
self._copy_config_file()
files = [] + self.dependencies + [self._context.source_dir]
self.zip_lambda_function(self.zipfile_name, files)
m = hashlib.md5()
with open(self.zipfile_name, 'rb') as fp:
m.update(fp.read())
zip_md5 = m.hexdigest()
cached_md5 = self._context.get_cache_value('zip_md5')
LOG.debug('zip_md5: %s', zip_md5)
LOG.debug('cached md5: %s', cached_md5)
if zip_md5 != cached_md5:
self._context.set_cache_value('zip_md5', zip_md5)
else:
changed = False
LOG.info('function unchanged')
return changed
def _check_config_md5(self):
# Compute the MD5 of all of the components of the configuration.
# If the MD5 does not match the cached MD5, the configuration has
# changed and needs to be updated so return True.
m = hashlib.md5()
m.update(self.description.encode('utf-8'))
m.update(self.handler.encode('utf-8'))
m.update(str(self.memory_size).encode('utf-8'))
m.update(self._context.exec_role_arn.encode('utf-8'))
m.update(str(self.timeout).encode('utf-8'))
config_md5 = m.hexdigest()
cached_md5 = self._context.get_cache_value('config_md5')
LOG.debug('config_md5: %s', config_md5)
LOG.debug('cached_md5: %s', cached_md5)
if config_md5 != cached_md5:
self._context.set_cache_value('config_md5', config_md5)
changed = True
else:
changed = False
return changed
def _copy_config_file(self):
config_name = '{}_config.json'.format(self._context.environment)
config_path = os.path.join(self._context.source_dir, config_name)
if os.path.exists(config_path):
dest_path = os.path.join(self._context.source_dir, 'config.json')
LOG.debug('copy %s to %s', config_path, dest_path)
shutil.copy2(config_path, dest_path)
def _zip_lambda_dir(self, zipfile_name, lambda_dir):
LOG.debug('_zip_lambda_dir: lambda_dir=%s', lambda_dir)
LOG.debug('zipfile_name=%s', zipfile_name)
relroot = os.path.abspath(lambda_dir)
with zipfile.ZipFile(zipfile_name, 'a',
compression=zipfile.ZIP_DEFLATED) as zf:
for root, subdirs, files in os.walk(lambda_dir):
excluded_dirs = []
for subdir in subdirs:
for excluded in self.excluded_dirs:
if subdir.startswith(excluded):
excluded_dirs.append(subdir)
for excluded in excluded_dirs:
subdirs.remove(excluded)
try:
dir_path = os.path.relpath(root, relroot)
dir_path = os.path.normpath(os.path.splitdrive(dir_path)[1])
while dir_path[0] in (os.sep, os.altsep):
dir_path = dir_path[1:]
dir_path += '/'
zf.getinfo(dir_path)
except KeyError:
zf.write(root, dir_path)
for filename in files:
if filename not in self.excluded_files:
filepath = os.path.join(root, filename)
if os.path.isfile(filepath):
arcname = os.path.join(
os.path.relpath(root, relroot), filename)
try:
zf.getinfo(arcname)
except KeyError:
zf.write(filepath, arcname)
def _zip_lambda_file(self, zipfile_name, lambda_file):
LOG.debug('_zip_lambda_file: lambda_file=%s', lambda_file)
LOG.debug('zipfile_name=%s', zipfile_name)
with zipfile.ZipFile(zipfile_name, 'a',
compression=zipfile.ZIP_DEFLATED) as zf:
try:
zf.getinfo(lambda_file)
except KeyError:
zf.write(lambda_file)
def zip_lambda_function(self, zipfile_name, files):
try:
os.remove(zipfile_name)
except OSError:
pass
for f in files:
LOG.debug('adding file %s', f)
if os.path.isdir(f):
self._zip_lambda_dir(zipfile_name, f)
else:
self._zip_lambda_file(zipfile_name, f)
def exists(self):
return self._get_response()
def tail(self):
LOG.info('tailing function: %s', self.name)
return self.log.tail()
def list_aliases(self):
LOG.info('listing aliases of %s', self.name)
try:
response = self._lambda_client.call(
'list_aliases',
FunctionName=self.name)
LOG.debug(response)
except Exception:
LOG.exception('Unable to list aliases')
return response.get('Versions', list())
def find_latest_version(self):
# Find the current (latest) version by version number
# First find the SHA256 of $LATEST
versions = self.list_versions()
for v in versions:
if v['Version'] == '$LATEST':
latest_sha256 = v['CodeSha256']
break
for v in versions:
if v['Version'] != '$LATEST':
if v['CodeSha256'] == latest_sha256:
version = v['Version']
break
return version
def create_alias(self, name, description, version=None):
if not version:
version = self.find_latest_version()
try:
LOG.debug('creating alias %s=%s', name, version)
response = self._lambda_client.call(
'create_alias',
FunctionName=self.name,
Description=description,
FunctionVersion=version,
Name=name)
LOG.debug(response)
except Exception:
LOG.exception('Unable to create alias')
def update_alias(self, name, description, version=None):
# Find the current (latest) version by version number
# First find the SHA256 of $LATEST
if not version:
version = self.find_latest_version()
try:
LOG.debug('updating alias %s=%s', name, version)
response = self._lambda_client.call(
'update_alias',
FunctionName=self.name,
Description=description,
FunctionVersion=version,
Name=name)
LOG.debug(response)
except Exception:
LOG.exception('Unable to update alias')
def add_permission(self, action, principal,
source_arn=None, source_account=None):
try:
kwargs = {
'FunctionName': self.name,
'Qualifier': self._context.environment,
'StatementId': str(uuid.uuid4()),
'Action': action,
'Principal': principal}
if source_arn:
kwargs['SourceArn'] = source_arn
if source_account:
kwargs['SourceAccount'] = source_account
response = self._lambda_client.call(
'add_permission', **kwargs)
LOG.debug(response)
except Exception:
LOG.exception('Unable to add permission')
def add_permissions(self):
if self.permissions:
time.sleep(5)
for permission in self.permissions:
self.add_permission(
permission['action'],
permission['principal'],
permission.get('source_arn'),
permission.get('source_account'))
def create(self):
LOG.info('creating function %s', self.name)
self._check_function_md5()
self._check_config_md5()
# There is a consistency problem here.
# Sometimes the role is not ready to be used by the function.
ready = False
while not ready:
with open(self.zipfile_name, 'rb') as fp:
exec_role = self._context.exec_role_arn
LOG.debug('exec_role=%s', exec_role)
try:
zipdata = fp.read()
response = self._lambda_client.call(
'create_function',
FunctionName=self.name,
Code={'ZipFile': zipdata},
Runtime=self.runtime,
Role=exec_role,
Handler=self.handler,
Description=self.description,
Timeout=self.timeout,
MemorySize=self.memory_size,
Publish=True)
LOG.debug(response)
description = 'For stage {}'.format(
self._context.environment)
self.create_alias(self._context.environment, description)
ready = True
except ClientError as e:
if 'InvalidParameterValueException' in str(e):
LOG.debug('Role is not ready, waiting')
time.sleep(2)
except Exception:
LOG.exception('Unable to upload zip file')
ready = True
self.add_permissions()
def update(self):
LOG.info('updating function %s', self.name)
if self._check_function_md5():
self._response = None
with open(self.zipfile_name, 'rb') as fp:
try:
LOG.info('uploading new function zipfile %s',
self.zipfile_name)
zipdata = fp.read()
response = self._lambda_client.call(
'update_function_code',
FunctionName=self.name,
ZipFile=zipdata,
Publish=True)
LOG.debug(response)
self.update_alias(
self._context.environment,
'For the {} stage'.format(self._context.environment))
except Exception:
LOG.exception('unable to update zip file')
def update_configuration(self):
if self._check_config_md5():
self._response = None
LOG.info('updating configuration for %s', self.name)
exec_role = self._context.exec_role_arn
LOG.debug('exec_role=%s', exec_role)
try:
response = self._lambda_client.call(
'update_function_configuration',
FunctionName=self.name,
Role=exec_role,
Handler=self.handler,
Description=self.description,
Timeout=self.timeout,
MemorySize=self.memory_size)
LOG.debug(response)
except Exception:
LOG.exception('unable to update function configuration')
else:
LOG.info('function configuration has not changed')
def deploy(self):
if self.exists():
self.update_configuration()
return self.update()
return self.create()
def list_versions(self):
try:
response = self._lambda_client.call(
'list_versions_by_function',
FunctionName=self.name)
LOG.debug(response)
except Exception:
LOG.exception('Unable to list versions')
return response['Versions']
def tag(self, name, description):
self.create_alias(name, description)
def delete(self):
LOG.info('deleting function %s', self.name)
response = None
try:
response = self._lambda_client.call(
'delete_function',
FunctionName=self.name)
LOG.debug(response)
except ClientError:
LOG.debug('function %s: not found', self.name)
return response
def status(self):
try:
response = self._lambda_client.call(
'get_function',
FunctionName=self.name)
LOG.debug(response)
except ClientError:
LOG.debug('function %s not found', self.name)
response = None
return response
def _invoke(self, data, invocation_type):
LOG.debug('invoke %s as %s', self.name, invocation_type)
response = self._lambda_client.call(
'invoke',
FunctionName=self.name,
InvocationType=invocation_type,
LogType='Tail',
Payload=data)
LOG.debug(response)
return response
def invoke(self, test_data=None):
return self._invoke(test_data, 'RequestResponse')
def invoke_async(self, test_data=None):
return self._invoke(test_data, 'Event')
def dryrun(self, test_data=None):
return self._invoke(test_data, 'DryRun')