Skip to content

Use one connection for all communication with extension. #405

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
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 15 additions & 13 deletions datadog_lambda/extension.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,29 @@
import logging
from os import path

try:
# only available in python 3
# not an issue since the extension is not compatible with python 2.x runtime
# https://docs.aws.amazon.com/lambda/latest/dg/using-extensions.html
import urllib.request
except ImportError:
# safe since both calls to urllib are protected with try/expect and will return false
urllib = None

AGENT_URL = "http://127.0.0.1:8124"
HELLO_PATH = "/lambda/hello"
FLUSH_PATH = "/lambda/flush"
EXTENSION_PATH = "/opt/extensions/datadog-agent"

logger = logging.getLogger(__name__)


try:
import http.client

conn = http.client.HTTPConnection("127.0.0.1", 8124)
except Exception as e:
logger.debug("unable to create http connection to extension: ", e)
conn = None


def is_extension_running():
if not path.exists(EXTENSION_PATH):
return False
try:
urllib.request.urlopen(AGENT_URL + HELLO_PATH)
conn.request("GET", HELLO_PATH)
resp = conn.getresponse()
return resp.status == 200
except Exception as e:
logger.debug("Extension is not running, returned with error %s", e)
return False
Expand All @@ -31,8 +32,9 @@ def is_extension_running():

def flush_extension():
try:
req = urllib.request.Request(AGENT_URL + FLUSH_PATH, "".encode("ascii"))
urllib.request.urlopen(req)
conn.request("POST", FLUSH_PATH, b"")
resp = conn.getresponse()
return resp.status == 200
except Exception as e:
logger.debug("Failed to flush extension, returned with error %s", e)
return False
Expand Down
4 changes: 1 addition & 3 deletions datadog_lambda/wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import json
from time import time_ns

from datadog_lambda.extension import should_use_extension, flush_extension
from datadog_lambda.extension import should_use_extension
from datadog_lambda.cold_start import (
set_cold_start,
is_cold_start,
Expand Down Expand Up @@ -367,8 +367,6 @@ def _after(self, event, context):

if not self.flush_to_log or should_use_extension:
flush_stats()
if should_use_extension:
flush_extension()

if self.encode_authorizer_context and is_authorizer_response(self.response):
self._inject_authorizer_span_headers(
Expand Down