| 1 |
import errno |
| 2 |
import socket |
| 3 |
import struct |
| 4 |
import threading |
| 5 |
import time |
| 6 |
import traceback |
| 7 |
|
| 8 |
import msgpack |
| 9 |
|
| 10 |
_global_sender = None |
| 11 |
|
| 12 |
|
| 13 |
def _set_global_sender(sender): # pragma: no cover |
| 14 |
"""[For testing] Function to set global sender directly""" |
| 15 |
global _global_sender |
| 16 |
_global_sender = sender |
| 17 |
|
| 18 |
|
| 19 |
def setup(tag, **kwargs): # pragma: no cover |
| 20 |
global _global_sender |
| 21 |
_global_sender = FluentSender(tag, **kwargs) |
| 22 |
|
| 23 |
|
| 24 |
def get_global_sender(): # pragma: no cover |
| 25 |
return _global_sender |
| 26 |
|
| 27 |
|
| 28 |
def close(): # pragma: no cover |
| 29 |
get_global_sender().close() |
| 30 |
|
| 31 |
|
| 32 |
class EventTime(msgpack.ExtType): |
| 33 |
def __new__(cls, timestamp, nanoseconds=None): |
| 34 |
seconds = int(timestamp) |
| 35 |
if nanoseconds is None: |
| 36 |
nanoseconds = int(timestamp % 1 * 10**9) |
| 37 |
return super().__new__( |
| 38 |
cls, |
| 39 |
code=0, |
| 40 |
data=struct.pack(">II", seconds, nanoseconds), |
| 41 |
) |
| 42 |
|
| 43 |
@classmethod |
| 44 |
def from_unix_nano(cls, unix_nano): |
| 45 |
seconds, nanos = divmod(unix_nano, 10**9) |
| 46 |
return cls(seconds, nanos) |
| 47 |
|
| 48 |
|
| 49 |
class FluentSender: |
| 50 |
def __init__( |
| 51 |
self, |
| 52 |
tag, |
| 53 |
host="localhost", |
| 54 |
port=24224, |
| 55 |
bufmax=1 * 1024 * 1024, |
| 56 |
timeout=3.0, |
| 57 |
verbose=False, |
| 58 |
buffer_overflow_handler=None, |
| 59 |
nanosecond_precision=False, |
| 60 |
msgpack_kwargs=None, |
| 61 |
*, |
| 62 |
forward_packet_error=True, |
| 63 |
**kwargs, |
| 64 |
): |
| 65 |
""" |
| 66 |
:param kwargs: This kwargs argument is not used in __init__. This will be removed in the next major version. |
| 67 |
""" |
| 68 |
self.tag = tag |
| 69 |
self.host = host |
| 70 |
self.port = port |
| 71 |
self.bufmax = bufmax |
| 72 |
self.timeout = timeout |
| 73 |
self.verbose = verbose |
| 74 |
self.buffer_overflow_handler = buffer_overflow_handler |
| 75 |
self.nanosecond_precision = nanosecond_precision |
| 76 |
self.forward_packet_error = forward_packet_error |
| 77 |
self.msgpack_kwargs = {} if msgpack_kwargs is None else msgpack_kwargs |
| 78 |
|
| 79 |
self.socket = None |
| 80 |
self.pendings = None |
| 81 |
self.lock = threading.Lock() |
| 82 |
self._closed = False |
| 83 |
self._last_error_threadlocal = threading.local() |
| 84 |
|
| 85 |
def emit(self, label, data): |
| 86 |
if self.nanosecond_precision: |
| 87 |
cur_time = EventTime.from_unix_nano(time.time_ns()) |
| 88 |
else: |
| 89 |
cur_time = int(time.time()) |
| 90 |
return self.emit_with_time(label, cur_time, data) |
| 91 |
|
| 92 |
def emit_with_time(self, label, timestamp, data): |
| 93 |
try: |
| 94 |
bytes_ = self._make_packet(label, timestamp, data) |
| 95 |
except Exception as e: |
| 96 |
if not self.forward_packet_error: |
| 97 |
raise |
| 98 |
self.last_error = e |
| 99 |
bytes_ = self._make_packet( |
| 100 |
label, |
| 101 |
timestamp, |
| 102 |
{ |
| 103 |
"level": "CRITICAL", |
| 104 |
"message": "Can't output to log", |
| 105 |
"traceback": traceback.format_exc(), |
| 106 |
}, |
| 107 |
) |
| 108 |
return self._send(bytes_) |
| 109 |
|
| 110 |
@property |
| 111 |
def last_error(self): |
| 112 |
return getattr(self._last_error_threadlocal, "exception", None) |
| 113 |
|
| 114 |
@last_error.setter |
| 115 |
def last_error(self, err): |
| 116 |
self._last_error_threadlocal.exception = err |
| 117 |
|
| 118 |
def clear_last_error(self, _thread_id=None): |
| 119 |
if hasattr(self._last_error_threadlocal, "exception"): |
| 120 |
delattr(self._last_error_threadlocal, "exception") |
| 121 |
|
| 122 |
def close(self): |
| 123 |
with self.lock: |
| 124 |
if self._closed: |
| 125 |
return |
| 126 |
self._closed = True |
| 127 |
if self.pendings: |
| 128 |
try: |
| 129 |
self._send_data(self.pendings) |
| 130 |
except Exception: |
| 131 |
self._call_buffer_overflow_handler(self.pendings) |
| 132 |
|
| 133 |
self._close() |
| 134 |
self.pendings = None |
| 135 |
|
| 136 |
def _make_packet(self, label, timestamp, data): |
| 137 |
if label: |
| 138 |
tag = f"{self.tag}.{label}" if self.tag else label |
| 139 |
else: |
| 140 |
tag = self.tag |
| 141 |
if self.nanosecond_precision and isinstance(timestamp, float): |
| 142 |
timestamp = EventTime(timestamp) |
| 143 |
packet = (tag, timestamp, data) |
| 144 |
if self.verbose: |
| 145 |
print(packet) |
| 146 |
return msgpack.packb(packet, **self.msgpack_kwargs) |
| 147 |
|
| 148 |
def _send(self, bytes_): |
| 149 |
with self.lock: |
| 150 |
if self._closed: |
| 151 |
return False |
| 152 |
return self._send_internal(bytes_) |
| 153 |
|
| 154 |
def _send_internal(self, bytes_): |
| 155 |
# buffering |
| 156 |
if self.pendings: |
| 157 |
self.pendings += bytes_ |
| 158 |
bytes_ = self.pendings |
| 159 |
|
| 160 |
try: |
| 161 |
self._send_data(bytes_) |
| 162 |
|
| 163 |
# send finished |
| 164 |
self.pendings = None |
| 165 |
|
| 166 |
return True |
| 167 |
except OSError as e: |
| 168 |
self.last_error = e |
| 169 |
|
| 170 |
# close socket |
| 171 |
self._close() |
| 172 |
|
| 173 |
# clear buffer if it exceeds max buffer size |
| 174 |
if self.pendings and (len(self.pendings) > self.bufmax): |
| 175 |
self._call_buffer_overflow_handler(self.pendings) |
| 176 |
self.pendings = None |
| 177 |
else: |
| 178 |
self.pendings = bytes_ |
| 179 |
|
| 180 |
return False |
| 181 |
|
| 182 |
def _check_recv_side(self): |
| 183 |
try: |
| 184 |
self.socket.settimeout(0.0) |
| 185 |
try: |
| 186 |
recvd = self.socket.recv(4096) |
| 187 |
except OSError as recv_e: |
| 188 |
if recv_e.errno != errno.EWOULDBLOCK: |
| 189 |
raise |
| 190 |
return |
| 191 |
|
| 192 |
if recvd == b"": |
| 193 |
raise OSError(errno.EPIPE, "Broken pipe") |
| 194 |
finally: |
| 195 |
self.socket.settimeout(self.timeout) |
| 196 |
|
| 197 |
def _send_data(self, bytes_): |
| 198 |
# reconnect if possible |
| 199 |
self._reconnect() |
| 200 |
# send message |
| 201 |
bytes_to_send = len(bytes_) |
| 202 |
bytes_sent = 0 |
| 203 |
self._check_recv_side() |
| 204 |
while bytes_sent < bytes_to_send: |
| 205 |
sent = self.socket.send(bytes_[bytes_sent:]) |
| 206 |
if sent == 0: |
| 207 |
raise OSError(errno.EPIPE, "Broken pipe") |
| 208 |
bytes_sent += sent |
| 209 |
self._check_recv_side() |
| 210 |
|
| 211 |
def _reconnect(self): |
| 212 |
if not self.socket: |
| 213 |
try: |
| 214 |
if self.host.startswith("unix://"): |
| 215 |
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 216 |
sock.settimeout(self.timeout) |
| 217 |
sock.connect(self.host[len("unix://") :]) |
| 218 |
else: |
| 219 |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 220 |
sock.settimeout(self.timeout) |
| 221 |
# This might be controversial and may need to be removed |
| 222 |
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) |
| 223 |
sock.connect((self.host, self.port)) |
| 224 |
except Exception as e: |
| 225 |
try: |
| 226 |
sock.close() |
| 227 |
except Exception: # pragma: no cover |
| 228 |
pass |
| 229 |
raise e |
| 230 |
else: |
| 231 |
self.socket = sock |
| 232 |
|
| 233 |
def _call_buffer_overflow_handler(self, pending_events): |
| 234 |
try: |
| 235 |
if self.buffer_overflow_handler: |
| 236 |
self.buffer_overflow_handler(pending_events) |
| 237 |
except Exception: |
| 238 |
# User should care any exception in handler |
| 239 |
pass |
| 240 |
|
| 241 |
def _close(self): |
| 242 |
try: |
| 243 |
sock = self.socket |
| 244 |
if sock: |
| 245 |
try: |
| 246 |
try: |
| 247 |
sock.shutdown(socket.SHUT_RDWR) |
| 248 |
except OSError: # pragma: no cover |
| 249 |
pass |
| 250 |
finally: |
| 251 |
try: |
| 252 |
sock.close() |
| 253 |
except OSError: # pragma: no cover |
| 254 |
pass |
| 255 |
finally: |
| 256 |
self.socket = None |
| 257 |
|
| 258 |
def __enter__(self): |
| 259 |
return self |
| 260 |
|
| 261 |
def __exit__(self, typ, value, traceback): |
| 262 |
try: |
| 263 |
self.close() |
| 264 |
except Exception as e: # pragma: no cover |
| 265 |
self.last_error = e |