Exemple #1
0
def reset_timeout(event, context):
    """
    A lambda resetting its timeout by calling lambda_runtime.report_done
    """

    print "Remaining time: ", context.get_remaining_time_in_millis()
    time.sleep(10)
    print "Remaining time: ", context.get_remaining_time_in_millis()

    lambda_runtime.report_done(context.aws_request_id, None, 'Success', 0)
    time.sleep(0.1)
    print "Remaining time: ", context.get_remaining_time_in_millis()
Exemple #2
0
def handle_http_request(request_handler, invokeid, sockfd):
    try:
        request_handler(sockfd)
    except wsgi.FaultException as e:
        lambda_runtime.report_fault(invokeid, e.msg, e.except_value, e.trace)
    finally:
        try:
            os.close(sockfd)
        except Exception as e:
            print("Error closing original data connection descriptor",
                  file=sys.stderr)
            traceback.print_exc()
        finally:
            lambda_runtime.report_done(invokeid, None, None)
Exemple #3
0
 def handle(self, event, context):
     try:
         runtime.report_running()
         ret = self.real_handler(event, context)
         if type(ret) == Decimal:
             ret = str(ret)
         ret = json.dumps(ret)
         if len(ret) > max_ret_msg_len:
             runtime.report_fail(max_ret_msg_len_exceed_error, 0, 1)
         else:
             runtime.report_done(ret, 0)
     except Exception as ex:
         stack_trace = traceback.format_exc().splitlines()
         # erase current frame
         del stack_trace[1]
         del stack_trace[1]
         runtime.report_fail('\n'.join(stack_trace), 0, 2)
Exemple #4
0
def send_report_end(event, context):
    """
    A Lambda that calls report_done from within the code
    """
    print "Beginning"
    lambda_runtime.report_done(context.aws_request_id, None, 'Success', 0)
    time.sleep(1)

    print "After first done"
    lambda_runtime.report_done(context.aws_request_id, None, 'Success', 0)
    time.sleep(1)

    print "After second done"
    lambda_runtime.report_done(context.aws_request_id, None, 'Success', 0)
    time.sleep(1)

    print "Now really done"
    return 'Success'
Exemple #5
0
def main():
    if sys.version_info[0] < 3:
        reload(sys)
        sys.setdefaultencoding('utf-8')

    sys.stdout = CustomFile(sys.stdout)
    sys.stderr = CustomFile(sys.stderr)

    logging.Formatter.converter = time.gmtime
    logger = logging.getLogger()
    logger_handler = LambdaLoggerHandler()
    logger_handler.setFormatter(
        logging.Formatter(
            '[%(levelname)s]\t%(asctime)s.%(msecs)dZ\t%(aws_request_id)s\t%(message)s\n',
            '%Y-%m-%dT%H:%M:%S'))
    logger_handler.addFilter(LambdaLoggerFilter())
    logger.addHandler(logger_handler)

    global _GLOBAL_AWS_REQUEST_ID

    # Remove lambda internal environment variables
    for env in [
            "_LAMBDA_CONTROL_SOCKET", "_LAMBDA_SHARED_MEM_FD",
            "_LAMBDA_LOG_FD", "_LAMBDA_CONSOLE_SOCKET",
            "_LAMBDA_RUNTIME_LOAD_TIME"
    ]:
        del os.environ[env]

    (invokeid, mode, handler, suppress_init, credentials) = wait_for_start()

    sys.path.insert(0, os.environ['LAMBDA_TASK_ROOT'])

    # Set /var/task as site directory so we are able to load all customer pth files
    if sys.version_info[0] >= 3:
        site.addsitedir(os.environ["LAMBDA_TASK_ROOT"])

    if suppress_init:
        init_handler, request_handler = lambda: None, None
    else:
        init_handler, request_handler = _get_handlers(handler, mode)
    run_init_handler(init_handler, invokeid)
    lambda_runtime.report_done(invokeid, None, None)
    log_info("init complete at epoch {0}".format(int(round(time.time() *
                                                           1000))))

    while True:
        (invokeid, x_amzn_trace_id, sockfd, credentials, event_body,
         context_objs, invoked_function_arn) = wait_for_invoke()
        _GLOBAL_AWS_REQUEST_ID = invokeid

        if x_amzn_trace_id != None:
            os.environ['_X_AMZN_TRACE_ID'] = x_amzn_trace_id
        elif '_X_AMZN_TRACE_ID' in os.environ:
            del os.environ['_X_AMZN_TRACE_ID']

        # If the handler hasn't been loaded yet, due to init suppression, load it now.
        if request_handler is None:
            init_handler, request_handler = _get_handlers(handler, mode)
            run_init_handler(init_handler, invokeid)

        if mode == "http":
            handle_http_request(request_handler, invokeid, sockfd)
        elif mode == "event":
            handle_event_request(request_handler, invokeid, event_body,
                                 context_objs, invoked_function_arn)
Exemple #6
0
def _get_handlers(handler, mode, invokeid, throttled=False):
    lambda_runtime.report_user_init_start()
    init_handler = lambda: None
    """
    This is the old way we were loading modules.
    It was causing intermittent build failures for unknown reasons.
    Using the imp module seems to remove these failures.
    The imp module appears to be more extreme in that it reloads
    the module if it is already loaded, and it likely doesn't use any caches when
    searching for the module but does a full directory search, which is what we want.
    """
    # m = imp.load_module(modname, globals(), locals(), [])

    try:
        (modname, fname) = handler.rsplit('.', 1)
    except ValueError as e:
        fault = wsgi.FaultException("Bad handler '{}'".format(handler), str(e),
                                    None)
        request_handler = make_fault_handler(fault)
        lambda_runtime.report_user_init_end()
        return init_handler, request_handler

    file_handle, pathname, desc = None, None, None
    try:
        # Recursively loading handler in nested directories
        for segment in modname.split('.'):
            if pathname is not None:
                pathname = [pathname]
            file_handle, pathname, desc = imp.find_module(segment, pathname)
        if file_handle is None:
            module_type = desc[2]
            if module_type == imp.C_BUILTIN:
                request_handler = make_fault_handler(
                    wsgi.FaultException(
                        "Cannot use built-in module {} as a handler module".
                        format(modname), None, None))
                lambda_runtime.report_user_init_end()
                return init_handler, request_handler
        m = imp.load_module(modname, file_handle, pathname, desc)
    except Exception as e:
        request_handler = load_handler_failed_handler(e, modname)
        lambda_runtime.report_user_init_end()
        # if the module load failed, usually we'd defer the error to the first INVOKE
        # if the throttled flag is set, there's another service tracking error states,
        # so we'll report the fault and exit to fail the INIT.
        #
        # request_handler constructed by load_handler_failed handler should always throw wsgi.FaultException.
        # This exception type has a .fatal field which signals if the runtime believes the error is not rety-able.
        # the report_fault helper returns this as it's 3rd return value.
        if throttled:
            try:
                request_handler()
            except Exception as e:
                errortype, result, fatal = report_fault(invokeid, e)
                if fatal:
                    lambda_runtime.report_done(invokeid, errortype, result, 1)
                    sys.exit(1)
        return init_handler, request_handler
    finally:
        if file_handle is not None:
            file_handle.close()

    try:
        init_handler = getattr(m, 'init')
    except AttributeError as e:
        pass

    try:
        request_handler = make_final_handler(getattr(m, fname), mode)
    except AttributeError as e:
        fault = wsgi.FaultException(
            "Handler '{}' missing on module '{}'".format(fname, modname),
            str(e), None)
        request_handler = make_fault_handler(fault)
    lambda_runtime.report_user_init_end()
    return init_handler, request_handler