-
Notifications
You must be signed in to change notification settings - Fork 237
Serverless instrumentation #716
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
34 commits
Select commit
Hold shift + click to select a range
3163616
Add skeleton for serverless transport and decorator
basepi 76a0ed5
Remove references to Client.send()
basepi 4e5bcc1
Add ServerlessClient class
basepi eee211e
Use kwargs for all transport __init__ parameters
basepi 342e31f
Make sure `self.name` is present
basepi f5aa82c
Explicitly set the logLevel
basepi 6b67194
Just use print to avoid logging formatter issues
basepi a6bffda
Add capture_serverless to top level import
basepi da19168
Add processing
basepi c0356a5
Add a prefix to our logs for identification
basepi 237c51d
Move capture_serverless to contrib/serverless
basepi baeb403
Collect API Gateway request information + response
basepi c6233eb
Always include the port
basepi f7ca651
Add requestContext to context dictionary
basepi 4f3fcf5
Fix up URL generation
basepi abdf639
Merge remote-tracking branch 'upstream/master' into serverless
basepi 3c14f8f
Remove TODO -- I did it!
basepi ed69fdd
Move capture_serverless into aws.py
basepi a44d96e
Set the transaction type dynamically
basepi 782302e
Minimize processing if capture_body is False
basepi ed17b78
Merge remote-tracking branch 'upstream/master' into serverless
basepi cb57a3b
Add additional context and naming from AWS env vars
basepi 1c0cf99
Remove service.version
basepi 3aef83d
Fix framework_name
basepi 53b6ca2
Use empty dict for missing headers
basepi 7d8cb43
Still no framework info in event
basepi 25ed35a
Print metadata for serverless
basepi 15ee8f6
Just pass framework info inline
basepi ea47280
Remove framework_version
basepi 7e81a27
Add serverless tests
basepi cddc51c
Merge remote-tracking branch 'upstream/master' into serverless
basepi ca542aa
Don't collect requestContext
basepi 904e25f
Remove requestContext refs from tests
basepi eaa12bc
Merge remote-tracking branch 'upstream/master' into serverless
basepi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| # BSD 3-Clause License | ||
basepi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| # | ||
| # Copyright (c) 2019, Elasticsearch BV | ||
| # All rights reserved. | ||
| # | ||
| # Redistribution and use in source and binary forms, with or without | ||
| # modification, are permitted provided that the following conditions are met: | ||
| # | ||
| # * Redistributions of source code must retain the above copyright notice, this | ||
| # list of conditions and the following disclaimer. | ||
| # | ||
| # * Redistributions in binary form must reproduce the above copyright notice, | ||
| # this list of conditions and the following disclaimer in the documentation | ||
| # and/or other materials provided with the distribution. | ||
| # | ||
| # * Neither the name of the copyright holder nor the names of its | ||
| # contributors may be used to endorse or promote products derived from | ||
| # this software without specific prior written permission. | ||
| # | ||
| # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | ||
| # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | ||
| # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | ||
| # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE | ||
| # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | ||
| # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | ||
| # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | ||
| # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, | ||
| # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | ||
| # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ||
|
|
||
| import os | ||
|
|
||
| # Future providers such as GCP and Azure will be added to this if/elif block | ||
| # This way you can use the same syntax for each of the providers from a user | ||
| # perspective | ||
| if os.environ.get("AWS_REGION"): | ||
| from elasticapm.contrib.serverless.aws import capture_serverless | ||
| else: | ||
| from elasticapm.contrib.serverless.aws import capture_serverless | ||
|
|
||
| __all__ = ("capture_serverless",) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,200 @@ | ||
| # BSD 3-Clause License | ||
| # | ||
| # Copyright (c) 2019, Elasticsearch BV | ||
| # All rights reserved. | ||
| # | ||
| # Redistribution and use in source and binary forms, with or without | ||
| # modification, are permitted provided that the following conditions are met: | ||
| # | ||
| # * Redistributions of source code must retain the above copyright notice, this | ||
| # list of conditions and the following disclaimer. | ||
| # | ||
| # * Redistributions in binary form must reproduce the above copyright notice, | ||
| # this list of conditions and the following disclaimer in the documentation | ||
| # and/or other materials provided with the distribution. | ||
| # | ||
| # * Neither the name of the copyright holder nor the names of its | ||
| # contributors may be used to endorse or promote products derived from | ||
| # this software without specific prior written permission. | ||
| # | ||
| # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | ||
| # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | ||
| # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | ||
| # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE | ||
| # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | ||
| # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | ||
| # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | ||
| # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, | ||
| # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | ||
| # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ||
|
|
||
| import base64 | ||
| import functools | ||
| import json | ||
| import os | ||
|
|
||
| import elasticapm | ||
| from elasticapm.base import ServerlessClient | ||
| from elasticapm.conf import constants | ||
| from elasticapm.utils import compat, encoding, get_name_from_func | ||
| from elasticapm.utils.disttracing import TraceParent | ||
|
|
||
|
|
||
| class capture_serverless(object): | ||
| """ | ||
| Context manager and decorator designed for instrumenting serverless | ||
| functions. | ||
|
|
||
| Uses a logging-only version of the transport, and no background threads. | ||
| Begins and ends a single transaction. | ||
| """ | ||
|
|
||
| def __init__(self, **kwargs): | ||
| self.name = kwargs.get("name") | ||
| self.event = {} | ||
| self.context = {} | ||
| self.response = None | ||
|
|
||
| if "framework_name" not in kwargs: | ||
| kwargs["framework_name"] = os.environ.get("AWS_EXECUTION_ENV", "AWS_Lambda_python") | ||
|
|
||
| self.client = ServerlessClient(**kwargs) | ||
| if not self.client.config.debug and self.client.config.instrument: | ||
| elasticapm.instrument() | ||
|
|
||
| def __call__(self, func): | ||
| self.name = self.name or get_name_from_func(func) | ||
|
|
||
| @functools.wraps(func) | ||
| def decorated(*args, **kwds): | ||
| if len(args) == 2: | ||
| # Saving these for request context later | ||
| self.event, self.context = args | ||
| else: | ||
| self.event, self.context = {}, {} | ||
| if not self.client.config.debug and self.client.config.instrument: | ||
| with self: | ||
| self.response = func(*args, **kwds) | ||
| return self.response | ||
| else: | ||
| return func(*args, **kwds) | ||
|
|
||
| return decorated | ||
|
|
||
| def __enter__(self): | ||
| """ | ||
| Transaction setup | ||
| """ | ||
| trace_parent = TraceParent.from_headers(self.event.get("headers", {})) | ||
| if "httpMethod" in self.event: | ||
| self.transaction = self.client.begin_transaction("request", trace_parent=trace_parent) | ||
| elasticapm.set_context( | ||
| lambda: get_data_from_request( | ||
| self.event, | ||
| capture_body=self.client.config.capture_body in ("transactions", "all"), | ||
| capture_headers=self.client.config.capture_headers, | ||
| ), | ||
| "request", | ||
| ) | ||
| if os.environ.get("AWS_LAMBDA_FUNCTION_NAME"): | ||
| elasticapm.set_transaction_name( | ||
| "{} {}".format(self.event["httpMethod"], os.environ["AWS_LAMBDA_FUNCTION_NAME"]) | ||
| ) | ||
| else: | ||
| elasticapm.set_transaction_name(self.name, override=False) | ||
| else: | ||
| self.transaction = self.client.begin_transaction("function", trace_parent=trace_parent) | ||
| elasticapm.set_transaction_name(os.environ.get("AWS_LAMBDA_FUNCTION_NAME", self.name), override=False) | ||
|
|
||
| def __exit__(self, exc_type, exc_val, exc_tb): | ||
| """ | ||
| Transaction teardown | ||
| """ | ||
| if exc_val: | ||
| self.client.capture_exception(exc_info=(exc_type, exc_val, exc_tb), handled=False) | ||
|
|
||
| if self.response and isinstance(self.response, dict): | ||
| elasticapm.set_context( | ||
| lambda: get_data_from_response(self.response, capture_headers=self.client.config.capture_headers), | ||
| "response", | ||
| ) | ||
| if "statusCode" in self.response: | ||
| result = "HTTP {}xx".format(int(self.response["statusCode"]) // 100) | ||
| elasticapm.set_transaction_result(result, override=False) | ||
| self.client.end_transaction() | ||
|
|
||
|
|
||
| def get_data_from_request(event, capture_body=False, capture_headers=True): | ||
| """ | ||
| Capture context data from API gateway event | ||
| """ | ||
| result = {} | ||
| if capture_headers and "headers" in event: | ||
| result["headers"] = event["headers"] | ||
| if "httpMethod" not in event: | ||
| # Not API Gateway | ||
| return result | ||
|
|
||
| result["method"] = event["httpMethod"] | ||
| if event["httpMethod"] in constants.HTTP_WITH_BODY and "body" in event: | ||
| body = event["body"] | ||
| if capture_body: | ||
| if event.get("isBase64Encoded"): | ||
| body = base64.b64decode(body) | ||
| else: | ||
| try: | ||
| jsonbody = json.loads(body) | ||
| body = jsonbody | ||
| except Exception: | ||
| pass | ||
|
|
||
| if body is not None: | ||
| result["body"] = body if capture_body else "[REDACTED]" | ||
|
|
||
| result["url"] = get_url_dict(event) | ||
| return result | ||
|
|
||
|
|
||
| def get_data_from_response(response, capture_headers=True): | ||
| """ | ||
| Capture response data from lambda return | ||
| """ | ||
| result = {} | ||
|
|
||
| if "statusCode" in response: | ||
| result["status_code"] = response["statusCode"] | ||
|
|
||
| if capture_headers and "headers" in response: | ||
| result["headers"] = response["headers"] | ||
| return result | ||
|
|
||
|
|
||
| def get_url_dict(event): | ||
| """ | ||
| Reconstruct URL from API Gateway | ||
| """ | ||
| headers = event.get("headers", {}) | ||
| proto = headers.get("X-Forwarded-Proto", "https") | ||
| host = headers.get("Host", "") | ||
| path = event.get("path", "") | ||
| port = headers.get("X-Forwarded-Port") | ||
| stage = "/" + event.get("requestContext", {}).get("stage", "") | ||
| query = "" | ||
| if event.get("queryStringParameters"): | ||
| query = "?" | ||
| for k, v in compat.iteritems(event["queryStringParameters"]): | ||
| query += "{}={}".format(k, v) | ||
| url = proto + "://" + host + stage + path + query | ||
|
|
||
| url_dict = { | ||
| "full": encoding.keyword_field(url), | ||
| "protocol": proto, | ||
| "hostname": encoding.keyword_field(host), | ||
| "pathname": encoding.keyword_field(stage + path), | ||
| } | ||
|
|
||
| if port: | ||
| url_dict["port"] = port | ||
| if query: | ||
| url_dict["search"] = encoding.keyword_field(query) | ||
| return url_dict |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
IIRC, last time I did this, all our linters got into a kerfuffle. I think it was black and flake8 duking it out
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
As far as I can tell, both are running on that file in my IDE and both are happy. Took some experimentation as to the location of the
# noqa: F401line (which is why I know both were running).Could you try checking it out and see if your IDE gives you problems?