-
Notifications
You must be signed in to change notification settings - Fork 94
/
udp_sink.rb
80 lines (69 loc) · 1.9 KB
/
udp_sink.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# frozen_string_literal: true
module StatsD
module Instrument
# @note This class is part of the new Client implementation that is intended
# to become the new default in the next major release of this library.
class UDPSink
class << self
def for_addr(addr)
host, port_as_string = addr.split(":", 2)
new(host, Integer(port_as_string))
end
end
attr_reader :host, :port
FINALIZER = ->(object_id) do
Thread.list.each do |thread|
if (store = thread["StatsD::UDPSink"])
store.delete(object_id)&.close
end
end
end
def initialize(host, port)
ObjectSpace.define_finalizer(self, FINALIZER)
@host = host
@port = port
end
def sample?(sample_rate)
sample_rate == 1.0 || rand < sample_rate
end
def <<(datagram)
retried = false
begin
socket.send(datagram, 0)
rescue SocketError, IOError, SystemCallError => error
StatsD.logger.debug do
"[StatsD::Instrument::UDPSink] Resetting connection because of #{error.class}: #{error.message}"
end
invalidate_socket
if retried
StatsD.logger.warn do
"[#{self.class.name}] Events were dropped because of #{error.class}: #{error.message}"
end
else
retried = true
retry
end
end
self
end
def flush(blocking:)
# noop
end
private
def invalidate_socket
socket = thread_store.delete(object_id)
socket&.close
end
def socket
thread_store[object_id] ||= begin
socket = UDPSocket.new
socket.connect(@host, @port)
socket
end
end
def thread_store
Thread.current["StatsD::UDPSink"] ||= {}
end
end
end
end