Skip to content
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

[statsd] fix socket creation thread safeness #60

Merged
merged 1 commit into from
Jun 25, 2015
Merged
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
18 changes: 11 additions & 7 deletions datadog/dogstatsd/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,17 +47,21 @@ def __exit__(self, type, value, traceback):
self.close_buffer()

def get_socket(self):
'''
Return a connected socket
'''
"""
Return a connected socket.

Note: connect the socket before assigning it to the class instance to
avoid bad thread race conditions.
"""
if not self.socket:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socket.connect((self.host, self.port))
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.connect((self.host, self.port))
self.socket = sock
return self.socket

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm seeing these races in a newer version of this module. Pretty sure there is still a race in this code. If another thread closes the socket between line 59 and 60, get_socket could return None or a closed socket. Similar race in close_socket itself.


def open_buffer(self, max_buffer_size=50):
"""
Open a buffer to send a batch of metrics in one packet
Open a buffer to send a batch of metrics in one packet.

You can also use this as a context manager.

Expand All @@ -71,7 +75,7 @@ def open_buffer(self, max_buffer_size=50):

def close_buffer(self):
"""
Flush the buffer and switch back to single metric packets
Flush the buffer and switch back to single metric packets.
"""
self._send = self._send_to_server
self._flush_buffer()
Expand Down
8 changes: 8 additions & 0 deletions tests/performance/test_statsd_thread_safety.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,11 @@ def test_send_batch_metrics(self):
payload = map(lambda x: x.split("\n"), self.recv())
payload = reduce(lambda prev, ele: prev + ele, payload, [])
t.assert_equal(10001, len(payload), len(payload))

def test_socket_creation(self):
"""
Assess thread safeness in socket creation.
"""
statsd = DogstatsdTest()
for _ in range(10000):
threading.Thread(target=statsd.send_metrics).start()