Skip to content

Commit 9c5019c

Browse files
committed
Use one connection for all communication with extension.
1 parent 8d38aa9 commit 9c5019c

File tree

1 file changed

+15
-13
lines changed

1 file changed

+15
-13
lines changed

datadog_lambda/extension.py

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,29 @@
11
import logging
22
from os import path
33

4-
try:
5-
# only available in python 3
6-
# not an issue since the extension is not compatible with python 2.x runtime
7-
# https://docs.aws.amazon.com/lambda/latest/dg/using-extensions.html
8-
import urllib.request
9-
except ImportError:
10-
# safe since both calls to urllib are protected with try/expect and will return false
11-
urllib = None
12-
13-
AGENT_URL = "http://127.0.0.1:8124"
144
HELLO_PATH = "/lambda/hello"
155
FLUSH_PATH = "/lambda/flush"
166
EXTENSION_PATH = "/opt/extensions/datadog-agent"
177

188
logger = logging.getLogger(__name__)
199

2010

11+
try:
12+
import http.client
13+
14+
conn = http.client.HTTPConnection("127.0.0.1", 8124)
15+
except Exception as e:
16+
logger.debug("unable to create http connection to extension: ", e)
17+
conn = None
18+
19+
2120
def is_extension_running():
2221
if not path.exists(EXTENSION_PATH):
2322
return False
2423
try:
25-
urllib.request.urlopen(AGENT_URL + HELLO_PATH)
24+
conn.request("GET", HELLO_PATH)
25+
resp = conn.getresponse()
26+
return resp.status == 200
2627
except Exception as e:
2728
logger.debug("Extension is not running, returned with error %s", e)
2829
return False
@@ -31,8 +32,9 @@ def is_extension_running():
3132

3233
def flush_extension():
3334
try:
34-
req = urllib.request.Request(AGENT_URL + FLUSH_PATH, "".encode("ascii"))
35-
urllib.request.urlopen(req)
35+
conn.request("POST", FLUSH_PATH, b"")
36+
resp = conn.getresponse()
37+
return resp.status == 200
3638
except Exception as e:
3739
logger.debug("Failed to flush extension, returned with error %s", e)
3840
return False

0 commit comments

Comments
 (0)