Skip to content

Commit ddfc66e

Browse files
author
David Bouchare
committed
Handle more socket exceptions (DataDog#349)
* Handle all exceptions * Change log levels and increase max line for tests * Add lock to address threading issues * Remove conversion to str Co-Authored-By: dabcoder <david.bouchare@datadoghq.com>
1 parent 9363229 commit ddfc66e

File tree

2 files changed

+20
-13
lines changed

2 files changed

+20
-13
lines changed

datadog/dogstatsd/base.py

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import logging
88
import os
99
import socket
10+
from threading import Lock
1011

1112
# datadog
1213
from datadog.dogstatsd.context import TimedContextManagerDecorator
@@ -59,6 +60,8 @@ def __init__(self, host='localhost', port=8125, max_buffer_size=50, namespace=No
5960
:type socket_path: string
6061
"""
6162

63+
self.lock = Lock()
64+
6265
# Connection
6366
if socket_path is not None:
6467
self.socket_path = socket_path
@@ -114,16 +117,17 @@ def get_socket(self):
114117
Note: connect the socket before assigning it to the class instance to
115118
avoid bad thread race conditions.
116119
"""
117-
if not self.socket:
118-
if self.socket_path is not None:
119-
sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
120-
sock.connect(self.socket_path)
121-
sock.setblocking(0)
122-
self.socket = sock
123-
else:
124-
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
125-
sock.connect((self.host, self.port))
126-
self.socket = sock
120+
with self.lock:
121+
if not self.socket:
122+
if self.socket_path is not None:
123+
sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
124+
sock.connect(self.socket_path)
125+
sock.setblocking(0)
126+
self.socket = sock
127+
else:
128+
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
129+
sock.connect((self.host, self.port))
130+
self.socket = sock
127131

128132
return self.socket
129133

@@ -289,9 +293,12 @@ def _send_to_server(self, packet):
289293
except socket.timeout:
290294
# dogstatsd is overflowing, drop the packets (mimicks the UDP behaviour)
291295
return
292-
except socket.error:
293-
log.info("Error submitting packet, dropping the packet and closing the socket")
296+
except (socket.error, socket.herror, socket.gaierror) as se:
297+
log.warning("Error submitting packet: {}, dropping the packet and closing the socket".format(se))
294298
self.close_socket()
299+
except Exception as e:
300+
log.error("Unexpected error: %s", str(e))
301+
return
295302

296303
def _send_to_buffer(self, packet):
297304
self.buffer.append(packet)

tox.ini

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,4 @@ deps =
2222
commands = flake8 datadog
2323

2424
[flake8]
25-
max-line-length = 100
25+
max-line-length = 120

0 commit comments

Comments
 (0)