Skip to content

Commit 7a4ec25

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 9220c5e commit 7a4ec25

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)
@@ -568,6 +567,74 @@ def disable_telemetry(self):
568567
def enable_telemetry(self):
569568
self._telemetry = True
570569

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

286-
def test_dogstatsd_initialization_with_env_vars(self):
286+
def test_dogstatsd_initialization_with_env_vars_agent_host(self):
287287
"""
288288
Dogstatsd can retrieve its config from env vars when
289289
not provided in constructor.
@@ -299,6 +299,54 @@ def test_dogstatsd_initialization_with_env_vars(self):
299299
self.assertEqual(dogstatsd.host, "myenvvarhost")
300300
self.assertEqual(dogstatsd.port, 4321)
301301

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

0 commit comments

Comments
 (0)