Skip to content

Commit 71daae4

Browse files
committed
AMLII-2173 - Add DD_DOGSTATSD_URL support to datadogpy
Adds support for the unix:// and udp:// variants of DD_DOGSTATSD_URL. Will only be applied if the host and port are their default values and no socket_path has been provided.
1 parent 4e8b412 commit 71daae4

4 files changed

Lines changed: 154 additions & 19 deletions

File tree

README.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,11 @@ options = {
9494
initialize(**options)
9595
```
9696

97+
Alternatively, the environment variable `DD_DOGSTATSD_URL` can be used to define a udp connection:
98+
`DD_DOGSTATSD_URL=udp://localhost:8125`
99+
100+
Manually supplying a host/port will take precedence over using this environment variable.
101+
97102
See the full list of available [DogStatsD client instantiation parameters](https://docs.datadoghq.com/developers/dogstatsd/?code-lang=python#client-instantiation-parameters).
98103

99104
#### Instantiate the DogStatsd client with UDS
@@ -110,6 +115,12 @@ options = {
110115
initialize(**options)
111116
```
112117

118+
Alternatively, the environment variable `DD_DOGSTATSD_URL` can be used to define a UDS connection:
119+
`DD_DOGSTATSD_URL=unix:///var/run/datadog/dsd.socket`
120+
121+
As with the udp variant, manually supplying a statsd_socket_path will take precedence over the environment variable.
122+
123+
113124
#### Origin detection over UDP and UDS
114125

115126
Origin detection is a method to detect which pod `DogStatsD` packets are coming from in order to add the pod's tags to the tag list.

datadog/dogstatsd/base.py

Lines changed: 84 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,11 @@
2525
# pypy has the same module, but capitalized.
2626
import Queue as queue # type: ignore[no-redef]
2727

28+
try:
29+
from urllib.parse import urlparse # type: ignore
30+
except ImportError:
31+
# Python 2 has the same functionality stored under a different module.
32+
from urlparse import urlparse # type: ignore
2833

2934
# pylint: disable=unused-import
3035
from typing import Optional, List, Text, Union
@@ -54,6 +59,7 @@
5459
UNIX_ADDRESS_SCHEME = "unix://"
5560
UNIX_ADDRESS_DATAGRAM_SCHEME = "unixgram://"
5661
UNIX_ADDRESS_STREAM_SCHEME = "unixstream://"
62+
WINDOWS_NAMEDPIPE_SCHEME = "\\\\.\\pipe\\"
5763

5864
# Buffering-related values (in seconds)
5965
DEFAULT_BUFFERING_FLUSH_INTERVAL = 0.3
@@ -180,12 +186,19 @@ def __init__(
180186
181187
>>> statsd = DogStatsd()
182188
189+
:envvar DD_DOGSTATSD_URL: the connection information for the dogstatsd server.
190+
If set, it overrides the default values.
191+
Example for UDP url: `DD_DOGSTATSD_URL=udp://localhost:8125`
192+
Example for UDS: `DD_DOGSTATSD_URL=unix:///var/run/datadog/dsd.socket`
193+
Windows named pipes are currently unsupported.
194+
:type DD_DOGSTATSD_URL: string
195+
183196
:envvar DD_AGENT_HOST: the host of the DogStatsd server.
184-
If set, it overrides default value.
197+
If set, it overrides default value. DD_DOGSTATSD_URL takes precedence over this value.
185198
:type DD_AGENT_HOST: string
186199
187200
:envvar DD_DOGSTATSD_PORT: the port of the DogStatsd server.
188-
If set, it overrides default value.
201+
If set, it overrides default value. DD_DOGSTATSD_URL takes precedence over this value.
189202
:type DD_DOGSTATSD_PORT: integer
190203
191204
:envvar DATADOG_TAGS: Tags to attach to every metric reported by dogstatsd client.
@@ -353,22 +366,8 @@ def __init__(
353366
# Check for deprecated option
354367
if max_buffer_size is not None:
355368
log.warning("The parameter max_buffer_size is now deprecated and is not used anymore")
356-
# Check host and port env vars
357-
agent_host = os.environ.get("DD_AGENT_HOST")
358-
if agent_host and host == DEFAULT_HOST:
359-
host = agent_host
360369

361-
dogstatsd_port = os.environ.get("DD_DOGSTATSD_PORT")
362-
if dogstatsd_port and port == DEFAULT_PORT:
363-
try:
364-
port = int(dogstatsd_port)
365-
except ValueError:
366-
log.warning(
367-
"Port number provided in DD_DOGSTATSD_PORT env var is not an integer: \
368-
%s, using %s as port number",
369-
dogstatsd_port,
370-
port,
371-
)
370+
host, port, socket_path = self._parse_env_connection_overrides(host, port, socket_path)
372371

373372
# Assuming environment variables always override
374373
telemetry_host = os.environ.get("DD_TELEMETRY_HOST", telemetry_host)
@@ -574,6 +573,74 @@ def disable_telemetry(self):
574573
def enable_telemetry(self):
575574
self._telemetry = True
576575

576+
def _parse_env_connection_overrides(self, host, port, socket_path):
577+
dogstatsd_url = os.environ.get("DD_DOGSTATSD_URL")
578+
579+
if (
580+
host == DEFAULT_HOST
581+
and port == DEFAULT_PORT
582+
and socket_path is None
583+
and dogstatsd_url is not None
584+
):
585+
parsed = urlparse(dogstatsd_url)
586+
# If all values are defaults, prefer DD_DOGSTATSD_URL if present.
587+
if parsed.scheme == "unix":
588+
log.debug(
589+
"Found a DD_DOGSTATSD_URL matching the uds syntax, "
590+
"setting socket path %s.", dogstatsd_url
591+
)
592+
return host, port, dogstatsd_url
593+
594+
elif dogstatsd_url.startswith(WINDOWS_NAMEDPIPE_SCHEME):
595+
log.debug(
596+
"DD_DOGSTATSD_URL is configured to utilize a windows named pipe, "
597+
"which is not currently supported by datadogpy. Falling back to "
598+
"alternate connection identifiers."
599+
)
600+
601+
elif parsed.scheme == "udp":
602+
try:
603+
p_port = parsed.port
604+
# Python 2 doesn't automatically perform bounds checking on the port
605+
if p_port is None or p_port < 0 or p_port > 65535:
606+
log.debug("Invalid port number provided, reverting to default port")
607+
p_port = DEFAULT_PORT
608+
except ValueError:
609+
log.debug("Invalid port number provided, reverting to default port")
610+
p_port = DEFAULT_PORT
611+
612+
log.debug(
613+
"Found a DD_DOGSTATSD_URL matching the udp sytnax, "
614+
"setting host and port %s:%d.", parsed.hostname, p_port
615+
)
616+
617+
return parsed.hostname, p_port, socket_path
618+
else:
619+
log.debug(
620+
"Unable to parse DD_DOGSTATSD_URL, did you remember to prefix the url "
621+
"with 'unix://' or 'udp://'? Falling back to alternate "
622+
"connection identifiers."
623+
)
624+
625+
# We either have some non-default values or no DD_DOGSTATSD_URL
626+
# Check host and port env vars
627+
agent_host = os.environ.get("DD_AGENT_HOST")
628+
if agent_host and host == DEFAULT_HOST:
629+
host = agent_host
630+
631+
dogstatsd_port = os.environ.get("DD_DOGSTATSD_PORT")
632+
if dogstatsd_port and port == DEFAULT_PORT:
633+
try:
634+
port = int(dogstatsd_port)
635+
except ValueError:
636+
log.warning(
637+
"Port number provided in DD_DOGSTATSD_PORT env var is not an integer: \
638+
%s, using %s as port number",
639+
dogstatsd_port,
640+
port,
641+
)
642+
return host, port, socket_path
643+
577644
# Note: Invocations of this method should be thread-safe
578645
def _start_flush_thread(self):
579646
if self._disable_aggregation and self.disable_buffering:

doc/source/index.rst

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,15 @@ Here's an example where the statsd host and port are configured as well::
4040
)
4141

4242

43+
If statsd_host and statsd_port are left at their default values and no socket_path alternative is supplied,
44+
the DD_DOGSTATSD_URL environment variable, if it exists, will be used to determine the connection
45+
information. This must be a URL that start with either `udp://` (to connect using UDP) or with `unix://`
46+
(to use a Unix Domain Socket).
47+
48+
* Example for UDP url: `DD_DOGSTATSD_URL=udp://localhost:8125`
49+
* Example for UDS: `DD_DOGSTATSD_URL=unix:///var/run/datadog/dsd.socket`
50+
51+
4352
.. autofunction:: datadog.initialize
4453

4554

tests/unit/dogstatsd/test_statsd.py

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
# Datadog libraries
3131
from datadog import initialize, statsd
3232
from datadog import __version__ as version
33-
from datadog.dogstatsd.base import DEFAULT_BUFFERING_FLUSH_INTERVAL, DogStatsd, MIN_SEND_BUFFER_SIZE, UDP_OPTIMAL_PAYLOAD_LENGTH, UDS_OPTIMAL_PAYLOAD_LENGTH
33+
from datadog.dogstatsd.base import DEFAULT_BUFFERING_FLUSH_INTERVAL, DEFAULT_HOST, DEFAULT_PORT, DogStatsd, MIN_SEND_BUFFER_SIZE, UDP_OPTIMAL_PAYLOAD_LENGTH, UDS_OPTIMAL_PAYLOAD_LENGTH
3434
from datadog.dogstatsd.context import TimedContextManagerDecorator
3535
from datadog.util.compat import is_higher_py35, is_p3k
3636
from tests.util.contextmanagers import preserve_environment_variable, EnvVars
@@ -286,7 +286,7 @@ def test_initialization(self):
286286
self.assertIsNone(statsd.host)
287287
self.assertIsNone(statsd.port)
288288

289-
def test_dogstatsd_initialization_with_env_vars(self):
289+
def test_dogstatsd_initialization_with_env_vars_agent_host(self):
290290
"""
291291
Dogstatsd can retrieve its config from env vars when
292292
not provided in constructor.
@@ -302,6 +302,54 @@ def test_dogstatsd_initialization_with_env_vars(self):
302302
self.assertEqual(dogstatsd.host, "myenvvarhost")
303303
self.assertEqual(dogstatsd.port, 4321)
304304

305+
306+
def test_dogstatsd_initialization_with_env_vars_dogstatsd_url(self):
307+
"""
308+
Dogstatsd can retrieve its config from env vars when
309+
not provided in constructor.
310+
"""
311+
# Setup UDP
312+
with preserve_environment_variable('DD_DOGSTATSD_URL'):
313+
os.environ['DD_DOGSTATSD_URL'] = 'udp://myenvvarhost:4321'
314+
dogstatsd = DogStatsd()
315+
316+
# Assert
317+
self.assertEqual(dogstatsd.host, "myenvvarhost")
318+
self.assertEqual(dogstatsd.port, 4321)
319+
self.assertEqual(dogstatsd.socket_path, None)
320+
321+
# Test UDS
322+
with preserve_environment_variable('DD_DOGSTATSD_URL'):
323+
os.environ['DD_DOGSTATSD_URL'] = 'unix:///hello/world.sock'
324+
dogstatsd = DogStatsd()
325+
self.assertEqual(dogstatsd.socket_path, 'unix:///hello/world.sock')
326+
self.assertEqual(dogstatsd.host, None)
327+
self.assertEqual(dogstatsd.port, None)
328+
329+
# Test non-default host
330+
with preserve_environment_variable('DD_DOGSTATSD_URL'):
331+
os.environ['DD_DOGSTATSD_URL'] = 'unix:///hello/world.sock'
332+
dogstatsd = DogStatsd(host="myhost")
333+
self.assertEqual(dogstatsd.socket_path, None)
334+
self.assertEqual(dogstatsd.host, 'myhost')
335+
self.assertEqual(dogstatsd.port, DEFAULT_PORT)
336+
337+
# Test non-default port
338+
with preserve_environment_variable('DD_DOGSTATSD_URL'):
339+
os.environ['DD_DOGSTATSD_URL'] = 'unix:///hello/world.sock'
340+
dogstatsd = DogStatsd(port=8240)
341+
self.assertEqual(dogstatsd.socket_path, None)
342+
self.assertEqual(dogstatsd.host, DEFAULT_HOST)
343+
self.assertEqual(dogstatsd.port, 8240)
344+
345+
# Test non-default socket_path
346+
with preserve_environment_variable('DD_DOGSTATSD_URL'):
347+
os.environ['DD_DOGSTATSD_URL'] = 'unix:///hello/world.sock'
348+
dogstatsd = DogStatsd(socket_path='unix:///var/run/datadog/dsd.sock')
349+
self.assertEqual(dogstatsd.socket_path, 'unix:///var/run/datadog/dsd.sock')
350+
self.assertEqual(dogstatsd.host, None)
351+
self.assertEqual(dogstatsd.port, None)
352+
305353
def test_initialization_closes_socket(self):
306354
statsd.socket = FakeSocket()
307355
self.assertIsNotNone(statsd.socket)

0 commit comments

Comments
 (0)