"""Image validation lambda function module.""" import config from src import image_validator from src.common import buffers_utils from src.common import lambda_exceptions from src.common import s3 from src.common import status from src.common import util from src.common.constants import errors from src.constants import general def _log_error(err, filename, bucket): status.send_general_status( function=config.LAMBDA_NAME, status_name=general.IMAGE_VALIDATION_ERROR_STATUS, filename=filename, bucket=bucket, errors=err) def handler(event, context): """Lambda entry point.""" try: buffers = None bucket, key, asset_config, file_type = util.extract_event(event) input_params = { 'key': key, 'bucket': bucket, 'file_type': file_type, 'transcoding_type': event.get('transcoding_type'), 'config': asset_config } buffers = buffers_utils.allocate_buffers(1) buffer = buffers[0] buffer = s3.download_file_object(bucket, key, buffer) buffers[0] = buffer image_validator.validate_image(buffer) status.send_general_status( function=config.LAMBDA_NAME, status_name=general.IMAGE_VALIDATION_COMPLETE_STATUS, filename=key, bucket=bucket) return input_params except lambda_exceptions.LambdaStatusError as error: config.logger.exception(str(error)) # if this is a malformed event but we have the key, we can send the error to the microserivce. # if the key is missing, then we cant post the status if 'key' in event: _log_error(error.errors, event.get('key'), event.get('bucket', None)) raise except lambda_exceptions.LambdaError as error: config.logger.exception(str(error)) raise except Exception as error: config.logger.exception(str(error)) e = dict() e[errors.IMAGE_VALIDATION_ERROR_CODE] = errors.ERROR_MESSAGES[errors.IMAGE_VALIDATION_ERROR_CODE].format( message=str(error)) _log_error(e, key, bucket) raise finally: if buffers: buffers_utils.release_allocated_buffers(buffers)