Skip to content

Commit

Permalink
Delay lock creation
Browse files Browse the repository at this point in the history
  • Loading branch information
therve committed Feb 24, 2021
1 parent d2fc46c commit e84dff9
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
3 changes: 3 additions & 0 deletions datadog/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import os
import os.path
from typing import Any, List, Optional
from threading import Lock

# datadog
from datadog import api
Expand Down Expand Up @@ -122,6 +123,8 @@ def initialize(
if statsd_constant_tags:
statsd.constant_tags += statsd_constant_tags

statsd.lock = Lock()

api._return_raw_response = return_raw_response

# HTTP client and API options
Expand Down
26 changes: 22 additions & 4 deletions datadog/dogstatsd/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
import socket
import errno
import time
from threading import Lock

# datadog
from datadog.dogstatsd.context import (
Expand Down Expand Up @@ -52,6 +51,18 @@
DEFAULT_TELEMETRY_MIN_FLUSH_INTERVAL = 10


class _NullContextManager(object):

def __init__(self):
pass

def __enter__(self):
pass

def __exit__(self, *args):
pass


class DogStatsd(object):
OK, WARNING, CRITICAL, UNKNOWN = (0, 1, 2, 3)

Expand Down Expand Up @@ -170,7 +181,8 @@ def __init__(
:type telemetry_socket_path: string
"""

self.lock = Lock()
# Create the lock later in initialize
self.lock = None

# Check for deprecated option
if max_buffer_size is not None:
Expand Down Expand Up @@ -298,7 +310,10 @@ def get_socket(self, telemetry=False):
Note: connect the socket before assigning it to the class instance to
avoid bad thread race conditions.
"""
with self.lock:
lock = self.lock
if lock is None:
lock = _NullContextManager()
with lock:
if telemetry and self._dedicated_telemetry_destination():
if not self.telemetry_socket:
if self.telemetry_socket_path is not None:
Expand Down Expand Up @@ -493,7 +508,10 @@ def close_socket(self):
"""
Closes connected socket if connected.
"""
with self.lock:
lock = self.lock
if lock is None:
lock = _NullContextManager()
with lock:
if self.socket:
try:
self.socket.close()
Expand Down

0 comments on commit e84dff9

Please sign in to comment.