Send a ping request to a lambda function.

    :param awsclient:
    :param function_name:
    :param alias_name:
    :param version:
    :return: ping response payload
497326
def ping(awsclient, function_name, alias_name=ALIAS_NAME, version=None):
    
    log.debug('sending ping to lambda function: %s', function_name)
    payload = '{"ramuda_action": "ping"}'  # default to ping event
    # reuse invoke
    return invoke(awsclient, function_name, payload, invocation_type=None,
                  alias_name=alias_name, version=version)
660769
def send_http_request(self, app: str, service: str, version: str, method: str, entity: str, params: dict):
        
        host, port, node_id, service_type = self._registry_client.resolve(service, version, entity, HTTP)

        url = 'http://{}:{}{}'.format(host, port, params.pop('path'))

        http_keys = ['data', 'headers', 'cookies', 'auth', 'allow_redirects', 'compress', 'chunked']
        kwargs = {k: params[k] for k in http_keys if k in params}

        query_params = params.pop('params', {})

        if app is not None:
            query_params['app'] = app

        query_params['version'] = version
        query_params['service'] = service

        response = yield from aiohttp.request(method, url, params=query_params, **kwargs)
        return response
957239
def _send(self, message):
        
        message['command'] = 'zappa.asynchronous.route_sns_task'
        payload = json.dumps(message).encode('utf-8')
        if len(payload) > LAMBDA_ASYNC_PAYLOAD_LIMIT: # pragma: no cover
            raise AsyncException("Payload too large for SNS")
        self.response = self.client.publish(
                                TargetArn=self.arn,
                                Message=payload
                            )
        self.sent = self.response.get('MessageId')
974819
def _request(self, func, url, version=1, *args, **kwargs):
        
        return_json = kwargs.pop('return_json', False)
        url = self.api_url[version] + url
        response = func(url, *args, **kwargs)

        if 'proxies' not in kwargs:
            kwargs['proxies'] = self.proxydict

        # Check for error, raising an exception if appropriate.
        response.raise_for_status()

        try:
            json_response = response.json()
        except ValueError:
            json_response = None
        if isinstance(json_response, dict):
            error = json_response.get('error')
            if error:
                raise BitstampError(error)
            elif json_response.get('status') == "error":
                raise BitstampError(json_response.get('reason'))

        if return_json:
            if json_response is None:
                raise BitstampError(
                    "Could not decode json for: " + response.text)
            return json_response

        return response
1017839
def update_alias(self):
        """"""
        LOG.info('Updating alias %s to point to $LATEST', self.env)

        try:
            self.lambda_client.update_alias(FunctionName=self.app_name, Name=self.env, FunctionVersion='$LATEST')
        except boto3.exceptions.botocore.exceptions.ClientError as error:
            LOG.debug('Update alias error: %s', error)
            LOG.info("Alias update failed. Retrying...")
            raise
68070
def wrap_httplib_request(request_func):
    

    def call(self, method, url, body, headers, *args, **kwargs):
        _tracer = execution_context.get_opencensus_tracer()
        blacklist_hostnames = execution_context.get_opencensus_attr(
            'blacklist_hostnames')
        dest_url = '{}:{}'.format(self._dns_host, self.port)
        if utils.disable_tracing_hostname(dest_url, blacklist_hostnames):
            return request_func(self, method, url, body,
                                headers, *args, **kwargs)
        _span = _tracer.start_span()
        _span.span_kind = span_module.SpanKind.CLIENT
        _span.name = '[httplib]{}'.format(request_func.__name__)

        # Add the request url to attributes
        _tracer.add_attribute_to_current_span(HTTP_URL, url)

        # Add the request method to attributes
        _tracer.add_attribute_to_current_span(HTTP_METHOD, method)

        # Store the current span id to thread local.
        execution_context.set_opencensus_attr(
            'httplib/current_span_id', _span.span_id)
        try:
            headers = headers.copy()
            headers.update(_tracer.propagator.to_headers(
                _span.context_tracer.span_context))
        except Exception:  # pragma: NO COVER
            pass
        return request_func(self, method, url, body, headers, *args, **kwargs)

    return call
129102
def create_async_sns_topic(self, lambda_name, lambda_arn):
        
        topic_name = get_topic_name(lambda_name)
        # Create SNS topic
        topic_arn = self.sns_client.create_topic(
            Name=topic_name)['TopicArn']
        # Create subscription
        self.sns_client.subscribe(
            TopicArn=topic_arn,
            Protocol='lambda',
            Endpoint=lambda_arn
        )
        # Add Lambda permission for SNS to invoke function
        self.create_event_permission(
            lambda_name=lambda_name,
            principal='sns.amazonaws.com',
            source_arn=topic_arn
        )
        # Add rule for SNS topic as a event source
        add_event_source(
            event_source={
                "arn": topic_arn,
                "events": ["sns:Publish"]
            },
            lambda_arn=lambda_arn,
            target_function="zappa.asynchronous.route_task",
            boto_session=self.boto_session
        )
        return topic_arn
364333
def create_alias(self):
        """"""
        LOG.info('Creating alias %s', self.env)

        try:
            self.lambda_client.create_alias(
                FunctionName=self.app_name,
                Name=self.env,
                FunctionVersion='$LATEST',
                Description='Alias for {}'.format(self.env))
        except boto3.exceptions.botocore.exceptions.ClientError as error:
            LOG.debug('Create alias error: %s', error)
            LOG.info("Alias creation failed. Retrying...")
            raise
643200
def lambda_handler(event, context):
    # incoming token value
    token = event['authorizationToken']
    print("Method ARN: " + event['methodArn'])

    '''
    
    '''
    principalId = 'user|a1b2c3d4'

    '''
    You can send a 401 Unauthorized response to the client by failing like so:

      raise Exception('Unauthorized')

    If the token is valid, a policy must be generated which will allow or deny
    access to the client. If access is denied, the client will receive a 403
    Access Denied response. If access is allowed, API Gateway will proceed with
    the backend integration configured on the method that was called.

    This function must generate a policy that is associated with the recognized
    principal user identifier. Depending on your use case, you might store
    policies in a DB, or generate them on the fly.

    Keep in mind, the policy is cached for 5 minutes by default (TTL is
    configurable in the authorizer) and will apply to subsequent calls to any
    method/resource in the RestApi made with the same token.

    The example policy below denies access to all resources in the RestApi.
    '''
    tmp = event['methodArn'].split(':')
    apiGatewayArnTmp = tmp[5].split('/')
    awsAccountId = tmp[4]

    policy = AuthPolicy(principalId, awsAccountId)
    policy.restApiId = apiGatewayArnTmp[0]
    policy.region = tmp[3]
    policy.stage = apiGatewayArnTmp[1]
    policy.denyAllMethods()
    #policy.allowMethod(HttpVerb.GET, '/pets/*')

    # Finally, build the policy
    authResponse = policy.build()

    # new! -- add additional key-value pairs associated with the authenticated principal
    # these are made available by APIGW like so: $context.authorizer.<key>
    # additional context is cached
    context = {
        'key': 'value',  # $context.authorizer.key -> value
        'number': 1,
        'bool': True
    }
    # context['arr'] = ['foo'] <- this is invalid, APIGW will not accept it
    # context['obj'] = {'foo':'bar'} <- also invalid

    authResponse['context'] = context

    return authResponse
12646
def lambda_handler(event, context):
    print("Client token: " + event['authorizationToken'])
    print("Method ARN: " + event['methodArn'])
    """and produce the principal user identifier associated with the tokenthis could be accomplished in a number of ways:1. Call out to OAuth provider2. Decode a JWT token inline3. Lookup in a self-managed DB"""
    principalId = "user|a1b2c3d4"

    """you can send a 401 Unauthorized response to the client by failing like so:raise Exception('Unauthorized')if the token is valid, a policy must be generated which will allow or deny access to the clientif access is denied, the client will receive a 403 Access Denied responseif access is allowed, API Gateway will proceed with the backend integration configured on the method that was calledthis function must generate a policy that is associated with the recognized principal user identifier.depending on your use case, you might store policies in a DB, or generate them on the flykeep in mind, the policy is cached for 5 minutes by default (TTL is configurable in the authorizer)and will apply to subsequent calls to any method/resource in the RestApimade with the same tokenthe example policy below denies access to all resources in the RestApi"""
    tmp = event['methodArn'].split(':')
    apiGatewayArnTmp = tmp[5].split('/')
    awsAccountId = tmp[4]

    policy = AuthPolicy(principalId, awsAccountId)
    policy.restApiId = apiGatewayArnTmp[0]
    policy.region = tmp[3]
    policy.stage = apiGatewayArnTmp[1]

    # Blueprint denies all methods by default
    # policy.denyAllMethods()

    # Example allows all methods
    policy.allowAllMethods()

    """policy.allowMethod(HttpVerb.GET, "/pets/*")finally, build the policy and exit the function using return"""
    return policy.build()
683068
def wire_deprecated(awsclient, function_name, s3_event_sources=None,
                    time_event_sources=None,
                    alias_name=ALIAS_NAME):
    
    if not lambda_exists(awsclient, function_name):
        log.error(colored.red('The function you try to wire up doesn\'t ' +
                          'exist... Bailing out...'))
        return 1
    client_lambda = awsclient.get_client('lambda')
    lambda_function = client_lambda.get_function(FunctionName=function_name)
    lambda_arn = client_lambda.get_alias(FunctionName=function_name,
                                         Name=alias_name)['AliasArn']
    log.info('wiring lambda_arn %s ...' % lambda_arn)

    if lambda_function is not None:
        s3_events_ensure_exists, s3_events_ensure_absent = filter_events_ensure(
            s3_event_sources)
        cloudwatch_events_ensure_exists, cloudwatch_events_ensure_absent = \
            filter_events_ensure(time_event_sources)

        for s3_event_source in s3_events_ensure_absent:
            _ensure_s3_event(awsclient, s3_event_source, function_name,
                             alias_name, lambda_arn, s3_event_source['ensure'])
        for s3_event_source in s3_events_ensure_exists:
            _ensure_s3_event(awsclient, s3_event_source, function_name,
                             alias_name, lambda_arn, s3_event_source['ensure'])

        for time_event in cloudwatch_events_ensure_absent:
            _ensure_cloudwatch_event(awsclient, time_event, function_name,
                                     alias_name, lambda_arn,
                                     time_event['ensure'])
        for time_event in cloudwatch_events_ensure_exists:
            _ensure_cloudwatch_event(awsclient, time_event, function_name,
                                     alias_name, lambda_arn,
                                     time_event['ensure'])
    return 0
1324239
def ping(self):
        
        d = self.replyQueue.get_ping()
        packet = RequestPing(self.charset, self.errors)
        self.transport.write(bytes(packet))
        return d.addCallback(self.handle_reply, self.charset, self.errors, None)
679042
def update_lambda_function(self, bucket, function_name, s3_key=None, publish=True, local_zip=None, num_revisions=None):
        
        print("Updating Lambda function code..")

        kwargs = dict(
            FunctionName=function_name,
            Publish=publish
        )
        if local_zip:
            kwargs['ZipFile'] = local_zip
        else:
            kwargs['S3Bucket'] = bucket
            kwargs['S3Key'] = s3_key

        response = self.lambda_client.update_function_code(**kwargs)
        resource_arn = response['FunctionArn']
        version = response['Version']

        # If the lambda has an ALB alias, let's update the alias
        # to point to the newest version of the function. We have to use a GET
        # here, as there's no HEAD-esque call to retrieve metadata about a
        # function alias.
        # Related: https://github.com/Miserlou/Zappa/pull/1730
        #          https://github.com/Miserlou/Zappa/issues/1823
        try:
            response = self.lambda_client.get_alias(
                FunctionName=function_name,
                Name=ALB_LAMBDA_ALIAS,
            )
            alias_exists = True
        except botocore.exceptions.ClientError as e:  # pragma: no cover
            if "ResourceNotFoundException" not in e.response["Error"]["Code"]:
                raise e
            alias_exists = False

        if alias_exists:
            self.lambda_client.update_alias(
                FunctionName=function_name,
                FunctionVersion=version,
                Name=ALB_LAMBDA_ALIAS,
            )

        if num_revisions:
            # Find the existing revision IDs for the given function
            # Related: https://github.com/Miserlou/Zappa/issues/1402
            versions_in_lambda = []
            versions = self.lambda_client.list_versions_by_function(FunctionName=function_name)
            for version in versions['Versions']:
                versions_in_lambda.append(version['Version'])
            while 'NextMarker' in versions:
                versions = self.lambda_client.list_versions_by_function(FunctionName=function_name,Marker=versions['NextMarker'])
                for version in versions['Versions']:
                    versions_in_lambda.append(version['Version'])
            versions_in_lambda.remove('$LATEST')
            # Delete older revisions if their number exceeds the specified limit
            for version in versions_in_lambda[::-1][num_revisions:]:
                self.lambda_client.delete_function(FunctionName=function_name,Qualifier=version)

        return resource_arn
690995
def get_lambdas(awsclient, config, add_arn=False):
    
    if 'lambda' in config:
        client_lambda = awsclient.get_client('lambda')
        lambda_entries = config['lambda'].get('entries', [])
        lmbdas = []
        for lambda_entry in lambda_entries:
            lmbda = {
                'name': lambda_entry.get('name', None),
                'alias': lambda_entry.get('alias', None),
                'swagger_ref': lambda_entry.get('swaggerRef', None)
            }
            if add_arn:
                _sleep()
                response_lambda = client_lambda.get_function(
                    FunctionName=lmbda['name'])
                lmbda['arn'] = response_lambda['Configuration']['FunctionArn']
            lmbdas.append(lmbda)
        return lmbdas
    else:
        return []
634414
def get_lambda_arn(app, account, region):
    
    session = boto3.Session(profile_name=account, region_name=region)
    lambda_client = session.client('lambda')

    lambda_arn = None
    paginator = lambda_client.get_paginator('list_functions')

    for lambda_functions in paginator.paginate():
        for lambda_function in lambda_functions['Functions']:
            if lambda_function['FunctionName'] == app:
                lambda_arn = lambda_function['FunctionArn']
                LOG.debug("Lambda ARN for lambda function %s is %s.", app, lambda_arn)
                break
        if lambda_arn:
            break

    if not lambda_arn:
        LOG.fatal('Lambda function with name %s not found in %s %s', app, account, region)
        raise LambdaFunctionDoesNotExist(
            'Lambda function with name {0} not found in {1} {2}'.format(app, account, region))

    return lambda_arn
1354978
def _lambda_uri(self, lambda_name, lambda_region):
        '''
        
        '''
        profile = self._common_aws_args.get('profile')
        region = self._common_aws_args.get('region')

        lambda_region = __utils__['boto3.get_region']('lambda', lambda_region, profile)
        apigw_region = __utils__['boto3.get_region']('apigateway', region, profile)

        lambda_desc = __salt__['boto_lambda.describe_function'](lambda_name, **self._common_aws_args)

        if lambda_region != apigw_region:
            if not lambda_desc.get('function'):
                # try look up in the same region as the apigateway as well if previous lookup failed
                lambda_desc = __salt__['boto_lambda.describe_function'](lambda_name, **self._common_aws_args)

        if not lambda_desc.get('function'):
            raise ValueError('Could not find lambda function {0} in '
                             'regions [{1}, {2}].'.format(lambda_name, lambda_region, apigw_region))

        lambda_arn = lambda_desc.get('function').get('FunctionArn')
        lambda_uri = ('arn:aws:apigateway:{0}:lambda:path/2015-03-31'
                      '/functions/{1}/invocations'.format(apigw_region, lambda_arn))
        return lambda_uri
312091
def update_lambda_configuration(    self,
                                        lambda_arn,
                                        function_name,
                                        handler,
                                        description='Zappa Deployment',
                                        timeout=30,
                                        memory_size=512,
                                        publish=True,
                                        vpc_config=None,
                                        runtime='python2.7',
                                        aws_environment_variables=None,
                                        aws_kms_key_arn=None
                                    ):
        
        print("Updating Lambda function configuration..")

        if not vpc_config:
            vpc_config = {}
        if not self.credentials_arn:
            self.get_credentials_arn()
        if not aws_kms_key_arn:
            aws_kms_key_arn = ''
        if not aws_environment_variables:
            aws_environment_variables = {}

        # Check if there are any remote aws lambda env vars so they don't get trashed.
        # https://github.com/Miserlou/Zappa/issues/987,  Related: https://github.com/Miserlou/Zappa/issues/765
        lambda_aws_config = self.lambda_client.get_function_configuration(FunctionName=function_name)
        if "Environment" in lambda_aws_config:
            lambda_aws_environment_variables = lambda_aws_config["Environment"].get("Variables", {})
            # Append keys that are remote but not in settings file
            for key, value in lambda_aws_environment_variables.items():
                if key not in aws_environment_variables:
                    aws_environment_variables[key] = value

        response = self.lambda_client.update_function_configuration(
            FunctionName=function_name,
            Runtime=runtime,
            Role=self.credentials_arn,
            Handler=handler,
            Description=description,
            Timeout=timeout,
            MemorySize=memory_size,
            VpcConfig=vpc_config,
            Environment={'Variables': aws_environment_variables},
            KMSKeyArn=aws_kms_key_arn,
            TracingConfig={
                'Mode': 'Active' if self.xray_tracing else 'PassThrough'
            }
        )

        resource_arn = response['FunctionArn']

        if self.tags:
            self.lambda_client.tag_resource(Resource=resource_arn, Tags=self.tags)

        return resource_arn