-
Notifications
You must be signed in to change notification settings - Fork 43
/
newrelic_lambda_wrapper.py
94 lines (73 loc) · 2.81 KB
/
newrelic_lambda_wrapper.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
# -*- coding: utf-8 -*-
import imp
import os
import warnings
os.environ.setdefault("NEW_RELIC_APP_NAME", os.getenv("AWS_LAMBDA_FUNCTION_NAME", ""))
os.environ.setdefault("NEW_RELIC_NO_CONFIG_FILE", "true")
os.environ.setdefault("NEW_RELIC_DISTRIBUTED_TRACING_ENABLED", "true")
os.environ.setdefault("NEW_RELIC_SERVERLESS_MODE_ENABLED", "true")
os.environ.setdefault(
"NEW_RELIC_TRUSTED_ACCOUNT_KEY", os.getenv("NEW_RELIC_ACCOUNT_ID", "")
)
# The agent will load some environment variables on module import so we need
# to perform the import after setting the necessary environment variables.
import newrelic.agent # noqa
from newrelic_lambda.lambda_handler import lambda_handler # noqa
newrelic.agent.initialize()
class IOpipeNoOp(object):
def __call__(self, *args, **kwargs):
warnings.warn(
"Use of context.iopipe.* is no longer supported. "
"Please see New Relic Python agent documentation here: "
"https://docs.newrelic.com/docs/agents/python-agent"
)
def __getattr__(self, name):
return IOpipeNoOp()
def get_handler():
if (
"NEW_RELIC_LAMBDA_HANDLER" not in os.environ
or not os.environ["NEW_RELIC_LAMBDA_HANDLER"]
):
raise ValueError(
"No value specified in NEW_RELIC_LAMBDA_HANDLER environment variable"
)
try:
module_path, handler_name = os.environ["NEW_RELIC_LAMBDA_HANDLER"].rsplit(
".", 1
)
except ValueError:
raise ValueError(
"Improperly formated handler value: %s"
% os.environ["NEW_RELIC_LAMBDA_HANDLER"]
)
file_handle, pathname, desc = None, None, None
try:
for segment in module_path.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:
raise ImportError(
"Cannot use built-in module %s as a handler module" % module_path
)
module = imp.load_module(module_path, file_handle, pathname, desc)
except Exception as e:
raise ImportError("Failed to import module '%s': %s" % (module_path, e))
finally:
if file_handle is not None:
file_handle.close()
try:
handler = getattr(module, handler_name)
except AttributeError:
raise AttributeError(
"No handler '%s' in module '%s'" % (handler_name, module_path)
)
return handler
# Greedily load the handler during cold start, so we don't pay for it on first invoke
wrapped_handler = get_handler()
@lambda_handler()
def handler(event, context):
context.iopipe = IOpipeNoOp()
return wrapped_handler(event, context)