dogstatsd-ruby 5.1.0 → 5.3.2

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 264d78a169508453151e7a5c3260c2299ad05c727dc9c72cfa52f8be721809d0
4
- data.tar.gz: 8e0726168a20f7efcb2bdcf72ab3d748184cd652de4fd25871f9fdf676020baf
3
+ metadata.gz: cfde2027b6fb73eee85ed0c612db51df707c2b01bec2266a3f2049acc34990f1
4
+ data.tar.gz: 5b1bb3263af1cbdde2bb84cf4d92f2e84ad7e0a0b3eaa5ad67f048750c062c46
5
5
  SHA512:
6
- metadata.gz: 1875c615a043db68c69d855af2b454e45ef41af1d7e1f726a6067c35e260eb0dbc9b706a0588608e31bd5087e500b1b77b1b604f3dc22750f1376b6583b78c9a
7
- data.tar.gz: 36f60d62312f6844efa9ce1b53a86cde380140582e009b5e5bf07d3a4a859e4d762e92a2ebcfe38a668145255f82f72c84504caabb93f25475e895a5166a9969
6
+ metadata.gz: 2b563e322f2eaff18eeb07f786d6277290c032e94859d89d856a7bc2512a278424ab5ec9f94f8bf477a222e9ef00075ad2e0293b29dbb0021a5b6551f836b3c9
7
+ data.tar.gz: 787b04cc62a139289784a9b1992a152ca74fafa3d97afa68944dea95121ff6d3af80164b551b5430d50b263f0d0c8f702d22c1450faaaebdbc4bc69f09c331fe
data/README.md CHANGED
@@ -22,9 +22,9 @@ To instantiate a DogStatsd client:
22
22
  # Import the library
23
23
  require 'datadog/statsd'
24
24
 
25
- # Create a DogStatsD client instance.
25
+ # Create a DogStatsD client instance
26
26
  statsd = Datadog::Statsd.new('localhost', 8125)
27
- ...
27
+ # ...
28
28
  # release resources used by the client instance
29
29
  statsd.close()
30
30
  ```
@@ -32,46 +32,73 @@ Or if you want to connect over Unix Domain Socket:
32
32
  ```ruby
33
33
  # Connection over Unix Domain Socket
34
34
  statsd = Datadog::Statsd.new(socket_path: '/path/to/socket/file')
35
- ...
35
+ # ...
36
36
  # release resources used by the client instance
37
37
  statsd.close()
38
38
  ```
39
39
 
40
- Find a list of all the available options for your DogStatsD Client in the [DogStatsD-ruby rubydoc](https://www.rubydoc.info/github/DataDog/dogstatsd-ruby/master/Datadog/Statsd) or in the [Datadog public DogStatsD documentation](https://docs.datadoghq.com/developers/dogstatsd/?tab=ruby#client-instantiation-parameters).
40
+ Find a list of all the available options for your DogStatsD Client in the [DogStatsD-ruby rubydoc](https://www.rubydoc.info/github/DataDog/dogstatsd-ruby/master/Datadog/Statsd) or in the [Datadog public DogStatsD documentation](https://docs.datadoghq.com/developers/dogstatsd/?code-lang=ruby#client-instantiation-parameters).
41
41
 
42
42
  ### Migrating from v4.x to v5.x
43
43
 
44
44
  If you are already using DogStatsD-ruby v4.x and you want to migrate to a version v5.x, the major
45
- change concerning you is the new threading model (please see section Threading model):
45
+ change concerning you is the new [threading model](#threading-model):
46
46
 
47
47
  In practice, it means two things:
48
48
 
49
- 1. Now that the client is buffering metrics before sending them, you have to manually
50
- call the method `Datadog::Statsd#flush` if you want to force the sending of metrics. Note that the companion thread will automatically flush the buffered metrics if the buffer gets full or when you are closing the instance.
49
+ 1. Now that the client is buffering metrics before sending them, you have to call `Datadog::Statsd#flush(sync: true)` if you want synchronous behavior. In most cases, this is not needed, as the sender thread will automatically flush the buffered metrics if the buffer gets full or when you are closing the instance.
51
50
 
52
51
  2. You have to make sure you are either:
53
52
 
54
- * using singletons instances of the DogStatsD client and not allocating one each time you need one, letting the buffering mechanism flush metrics, or,
55
- * properly closing your DogStatsD client instance when it is not needed anymore using the method `Datadog::Statsd#close` to release the resources used by the instance and to close the socket
53
+ * Using a singleton instance of the DogStatsD client instead of creating a new instance whenever you need one; this will let the buffering mechanism flush metrics regularly
54
+ * Or properly disposing of the DogStatsD client instance when it is not needed anymore using the method `Datadog::Statsd#close`
55
+
56
+ If you have issues with the sender thread or the buffering mode, you can instantiate a client that behaves exactly as in v4.x (i.e. no sender thread and flush on every metric submission):
57
+
58
+ ```ruby
59
+ # Create a DogStatsD client instance using UDP
60
+ statsd = Datadog::Statsd.new('localhost', 8125, single_thread: true, buffer_max_pool_size: 1)
61
+ # ...
62
+ statsd.close()
63
+ ```
64
+
65
+ or
66
+
67
+ ```ruby
68
+ # Create a DogStatsD client instance using UDS
69
+ statsd = Datadog::Statsd.new(socket_path: '/path/to/socket/file', single_thread: true, buffer_max_pool_size: 1)
70
+ # ...
71
+ statsd.close()
72
+ ```
56
73
 
57
74
  ### v5.x Common Pitfalls
58
75
 
59
- Version v5.x of `dogstatsd-ruby` is using a companion thread for preemptive flushing, it brings better performances for application having a high-throughput of statsd metrics, but it comes with new pitfalls:
76
+ Version v5.x of `dogstatsd-ruby` is using a sender thread for flushing. This provides better performance, but you need to consider the following pitfalls:
60
77
 
61
- * Applications forking after having created the dogstatsd instance: forking a process can't duplicate the existing threads, meaning that one of the processes won't have a companion thread to flush the metrics and will lead to missing metrics.
62
- * Applications creating a lot of different instances of the client without closing them: it is important to close the instance to free the thread and the socket it is using or it will lead to thread leaks.
78
+ 1. Applications that use `fork` after having created the dogstatsd instance: the child process will automatically spawn a new sender thread to flush metrics.
79
+
80
+ 2. Applications that create multiple instances of the client without closing them: it is important to `#close` all instances to free the thread and the socket they are using otherwise you will leak those resources.
63
81
 
64
82
  If you are using [Sidekiq](https://github.com/mperham/sidekiq), please make sure to close the client instances that are instantiated. [See this example on using DogStatsD-ruby v5.x with Sidekiq](https://github.com/DataDog/dogstatsd-ruby/blob/master/examples/sidekiq_example.rb).
65
83
 
66
84
  If you are using [Puma](https://github.com/puma/puma) or [Unicorn](https://yhbt.net/unicorn.git), please make sure to create the instance of DogStatsD in the workers, not in the main process before it forks to create its workers. See [this comment for more details](https://github.com/DataDog/dogstatsd-ruby/issues/179#issuecomment-845570345).
67
85
 
68
- Applications that are in these situations and can't apply these recommendations should pin dogstatsd-ruby v4.x using `gem 'dogstatsd-ruby', '~> 4.0'`. Note that v4.x will continue to be maintained until a future v5.x version can more easily fit these use cases.
86
+ Applications that run into issues but can't apply these recommendations should use the `single_thread` mode which disables the use of the sender thread.
87
+ Here is how to instantiate a client in this mode:
88
+
89
+ ```ruby
90
+ statsd = Datadog::Statsd.new('localhost', 8125, single_thread: true)
91
+ # ...
92
+ # release resources used by the client instance and flush last metrics
93
+ statsd.close()
94
+ ```
69
95
 
70
96
  ### Origin detection over UDP
71
97
 
72
- Origin detection is a method to detect which pod DogStatsD packets are coming from in order to add the pod's tags to the tag list.
98
+ Origin detection is a method to detect which pod DogStatsD packets are coming from, in order to add the pod's tags to the tag list.
99
+
100
+ To enable origin detection over UDP, add the following lines to your application manifest:
73
101
 
74
- To enable origin detection over UDP, add the following lines to your application manifest
75
102
  ```yaml
76
103
  env:
77
104
  - name: DD_ENTITY_ID
@@ -79,56 +106,57 @@ env:
79
106
  fieldRef:
80
107
  fieldPath: metadata.uid
81
108
  ```
109
+
82
110
  The DogStatsD client attaches an internal tag, `entity_id`. The value of this tag is the content of the `DD_ENTITY_ID` environment variable, which is the pod’s UID.
83
111
 
84
112
  ## Usage
85
113
 
86
- In order to use DogStatsD metrics, events, and Service Checks the Agent must be [running and available](https://docs.datadoghq.com/developers/dogstatsd/?tab=ruby).
114
+ In order to use DogStatsD metrics, events, and Service Checks the Datadog Agent must be [running and available](https://docs.datadoghq.com/developers/dogstatsd/?tab=ruby).
87
115
 
88
116
  ### Metrics
89
117
 
90
- After the client is created, you can start sending custom metrics to Datadog. See the dedicated [Metric Submission: DogStatsD documentation](https://docs.datadoghq.com/developers/metrics/dogstatsd_metrics_submission/?tab=ruby) to see how to submit all supported metric types to Datadog with working code examples:
118
+ After the client is created, you can start sending custom metrics to Datadog. See the dedicated [Metric Submission: DogStatsD documentation](https://docs.datadoghq.com/metrics/dogstatsd_metrics_submission/?tab=ruby) to see how to submit all supported metric types to Datadog with working code examples:
91
119
 
92
- * [Submit a COUNT metric](https://docs.datadoghq.com/developers/metrics/dogstatsd_metrics_submission/?tab=ruby#count).
93
- * [Submit a GAUGE metric](https://docs.datadoghq.com/developers/metrics/dogstatsd_metrics_submission/?tab=ruby#gauge).
94
- * [Submit a SET metric](https://docs.datadoghq.com/developers/metrics/dogstatsd_metrics_submission/?tab=ruby#set)
95
- * [Submit a HISTOGRAM metric](https://docs.datadoghq.com/developers/metrics/dogstatsd_metrics_submission/?tab=ruby#histogram)
96
- * [Submit a DISTRIBUTION metric](https://docs.datadoghq.com/developers/metrics/dogstatsd_metrics_submission/?tab=ruby#distribution)
120
+ * [Submit a COUNT metric](https://docs.datadoghq.com/metrics/dogstatsd_metrics_submission/?code-lang=ruby#count).
121
+ * [Submit a GAUGE metric](https://docs.datadoghq.com/metrics/dogstatsd_metrics_submission/?code-lang=ruby#gauge).
122
+ * [Submit a SET metric](https://docs.datadoghq.com/metrics/dogstatsd_metrics_submission/?code-lang=ruby#set)
123
+ * [Submit a HISTOGRAM metric](https://docs.datadoghq.com/metrics/dogstatsd_metrics_submission/?code-lang=ruby#histogram)
124
+ * [Submit a DISTRIBUTION metric](https://docs.datadoghq.com/metrics/dogstatsd_metrics_submission/?code-lang=ruby#distribution)
97
125
 
98
- Some options are suppported when submitting metrics, like [applying a Sample Rate to your metrics](https://docs.datadoghq.com/developers/metrics/dogstatsd_metrics_submission/?tab=ruby#metric-submission-options) or [tagging your metrics with your custom tags](https://docs.datadoghq.com/developers/metrics/dogstatsd_metrics_submission/?tab=ruby#metric-tagging). Find all the available functions to report metrics in the [DogStatsD-ruby rubydoc](https://www.rubydoc.info/github/DataDog/dogstatsd-ruby/master/Datadog/Statsd).
126
+ Some options are suppported when submitting metrics, like [applying a Sample Rate to your metrics](https://docs.datadoghq.com/metrics/dogstatsd_metrics_submission/?tab=ruby#metric-submission-options) or [tagging your metrics with your custom tags](https://docs.datadoghq.com/metrics/dogstatsd_metrics_submission/?tab=ruby#metric-tagging). Find all the available functions to report metrics in the [DogStatsD-ruby rubydoc](https://www.rubydoc.info/github/DataDog/dogstatsd-ruby/master/Datadog/Statsd).
99
127
 
100
128
  ### Events
101
129
 
102
- After the client is created, you can start sending events to your Datadog Event Stream. See the dedicated [Event Submission: DogStatsD documentation](https://docs.datadoghq.com/developers/events/dogstatsd/?tab=ruby) to see how to submit an event to Datadog your Event Stream.
130
+ After the client is created, you can start sending events to your Datadog Event Stream. See the dedicated [Event Submission: DogStatsD documentation](https://docs.datadoghq.com/events/guides/dogstatsd/?code-lang=ruby) to see how to submit an event to Datadog your Event Stream.
103
131
 
104
132
  ### Service Checks
105
133
 
106
134
  After the client is created, you can start sending Service Checks to Datadog. See the dedicated [Service Check Submission: DogStatsD documentation](https://docs.datadoghq.com/developers/service_checks/dogstatsd_service_checks_submission/?tab=ruby) to see how to submit a Service Check to Datadog.
107
135
 
108
- ### Maximum packets size in high-throughput scenarios
136
+ ### Maximum packet size in high-throughput scenarios
109
137
 
110
138
  In order to have the most efficient use of this library in high-throughput scenarios,
111
- default values for the maximum packets size have already been set for both UDS (8192 bytes)
112
- and UDP (1432 bytes) in order to have the best usage of the underlying network.
113
- However, if you perfectly know your network and you know that a different value for the maximum packets
114
- size should be used, you can set it with the parameter `buffer_max_payload_size`. Example:
139
+ recommended values for the maximum packet size have already been set for both UDS (8192 bytes)
140
+ and UDP (1432 bytes).
141
+
142
+ However, if are in control of your network and want to use a different value for the maximum packet
143
+ size, you can do it by setting the `buffer_max_payload_size` parameter:
115
144
 
116
145
  ```ruby
117
- # Create a DogStatsD client instance.
118
146
  statsd = Datadog::Statsd.new('localhost', 8125, buffer_max_payload_size: 4096)
147
+ # ...
148
+ statsd.close()
119
149
  ```
120
150
 
121
151
  ## Threading model
122
152
 
123
- On versions greater than 5.0, we changed the threading model of the library so that one instance of `Datadog::Statsd` could be shared between threads and so that the writes in the socket are non blocking.
153
+ Starting with version 5.0, `dogstatsd-ruby` employs a new threading model where one instance of `Datadog::Statsd` can be shared between threads and where data sending is non-blocking (asynchronous).
124
154
 
125
- When you instantiate a `Datadog::Statsd`, a companion thread is spawned. This thread will be called the Sender thread, as it is modeled by the [Sender](../lib/datadog/statsd/sender.rb) class.
155
+ When you instantiate a `Datadog::Statsd`, a sender thread is spawned. This thread will be called the Sender thread, as it is modeled by the [Sender](../lib/datadog/statsd/sender.rb) class. You can make use of `single_thread: true` to disable this behavior.
126
156
 
127
- This thread is stopped when you close the statsd client (`Datadog::Statsd#close`). It also means that allocating a lot of statsd clients without closing them properly when not used anymore
128
- could lead to a thread leak (even though they will be sleeping, blocked on IO).
129
- The communication between the current thread is managed through a standard Ruby Queue.
157
+ This thread is stopped when you close the statsd client (`Datadog::Statsd#close`). Instantiating a lot of statsd clients without calling `#close` after they are not needed anymore will most likely lead to threads being leaked.
130
158
 
131
- The sender thread has the following logic (Code present in the method `Datadog::Statsd::Sender#send_loop`):
159
+ The sender thread has the following logic (from `Datadog::Statsd::Sender#send_loop`):
132
160
 
133
161
  ```
134
162
  while the sender message queue is not closed do
@@ -144,15 +172,13 @@ while the sender message queue is not closed do
144
172
  end while
145
173
  ```
146
174
 
147
- Most of the time, the sender thread is blocked and sleeping when doing a blocking read from the sender message queue.
175
+ There are three different kinds of messages:
148
176
 
149
- We can see that there is 3 different kind of messages:
177
+ 1. a control message to flush the buffer in the connection
178
+ 2. a control message to synchronize any thread with the sender thread
179
+ 3. a message to append to the buffer
150
180
 
151
- * a control message to flush the buffer in the connection
152
- * a control message to synchronize any thread with the sender thread
153
- * a message to append to the buffer
154
-
155
- There is also an implicit message which is closing the queue as it will stop blocking read from the message queue (if happening) and thus, stop the sender thread.
181
+ There is also an implicit message which closes the queue which will cause the sender thread to finish processing and exit.
156
182
 
157
183
  ### Usual workflow
158
184
 
@@ -160,20 +186,29 @@ You push metrics to the statsd client which writes them quickly to the sender me
160
186
 
161
187
  ### Flushing
162
188
 
163
- When calling a flush, a specific control message (the `:flush` symbol) is sent to the sender thread. When finding it, it flushes its internal buffer into the connection.
189
+ When calling `Datadog::Statsd#flush`, a specific control message (`:flush`) is sent to the sender thread. When the sender thread receives it, it flushes its internal buffer into the connection.
164
190
 
165
191
  ### Rendez-vous
166
192
 
167
- It is possible to ensure a message has been consumed by the sender thread and written to the buffer by simply calling a rendez-vous right after. This is done when you are doing a synchronized flush (calling `Datadog::Statsd#flush` with the `sync: true` option).
193
+ It is possible to ensure a message has been consumed by the sender thread and written to the buffer by simply calling a rendez-vous right after. This is done when you are doing a synchronous flush using `Datadog::Statsd#flush(sync: true)`.
194
+
195
+ Doing so means the caller thread is blocked and waiting until the data has been flushed by the sender thread.
196
+
197
+ This is useful when preparing to exit the application or when checking unit tests.
198
+
199
+ ### Thread-safety
200
+
201
+ By default, instances of `Datadog::Statsd` are thread-safe and we recommend that a single instance be reused by all application threads (even in applications that employ forking). The sole exception is the `#close` method — this method is not yet thread safe (work in progress here [#209](https://github.com/DataDog/dogstatsd-ruby/pull/209)).
202
+
203
+ When using the `single_thread: true` mode, instances of `Datadog::Statsd` are still thread-safe, but you may run into contention on heavily-threaded applications, so we don’t recommend (for performance reasons) reusing these instances.
168
204
 
169
- This means the current thread is going to sleep and wait for a Queue which is given to the sender thread. When the sender thread reads this queue from its own message queue, it puts a placeholder message in it so that it wakes up the calling thread.
205
+ ## Versioning
170
206
 
171
- This is useful when closing the application or when checking unit tests.
207
+ This Ruby gem is using [Semantic Versioning](https://guides.rubygems.org/patterns/#semantic-versioning) but please note that supported Ruby versions can change in a minor release of this library. As much as possible, we will add a "future deprecation" message in the minor release preceding the one dropping the support.
172
208
 
173
209
  ## Credits
174
210
 
175
- dogstatsd-ruby is forked from Rein Henrichs [original Statsd
176
- client](https://github.com/reinh/statsd).
211
+ dogstatsd-ruby is forked from Rein Henrichs' [original Statsd client](https://github.com/reinh/statsd).
177
212
 
178
213
  Copyright (c) 2011 Rein Henrichs. See LICENSE.txt for
179
214
  further details.
@@ -8,16 +8,11 @@ module Datadog
8
8
  @logger = logger
9
9
  end
10
10
 
11
- # Close the underlying socket
12
- def close
13
- begin
14
- @socket && @socket.close if instance_variable_defined?(:@socket)
15
- rescue StandardError => boom
16
- logger.error { "Statsd: #{boom.class} #{boom}" } if logger
17
- end
18
- @socket = nil
11
+ def reset_telemetry
12
+ telemetry.reset
19
13
  end
20
14
 
15
+ # not thread safe: `Sender` instances that use this are required to properly synchronize or sequence calls to this method
21
16
  def write(payload)
22
17
  logger.debug { "Statsd: #{payload}" } if logger
23
18
 
@@ -36,6 +31,7 @@ module Datadog
36
31
  retries += 1
37
32
  begin
38
33
  close
34
+ connect
39
35
  retry
40
36
  rescue StandardError => e
41
37
  boom = e
@@ -48,11 +44,16 @@ module Datadog
48
44
  end
49
45
 
50
46
  private
47
+
51
48
  attr_reader :telemetry
52
49
  attr_reader :logger
53
50
 
54
- def socket
55
- @socket ||= connect
51
+ def connect
52
+ raise 'Should be implemented by subclass'
53
+ end
54
+
55
+ def close
56
+ raise 'Should be implemented by subclass'
56
57
  end
57
58
  end
58
59
  end
@@ -18,6 +18,8 @@ module Datadog
18
18
  telemetry_flush_interval: nil,
19
19
  global_tags: [],
20
20
 
21
+ single_thread: false,
22
+
21
23
  logger: nil
22
24
  )
23
25
  @transport_type = socket_path.nil? ? :udp : :uds
@@ -47,13 +49,12 @@ module Datadog
47
49
  raise ArgumentError, "buffer_max_payload_size is not high enough to use telemetry (tags=(#{global_tags.inspect}))"
48
50
  end
49
51
 
50
- @buffer = MessageBuffer.new(@connection,
52
+ buffer = MessageBuffer.new(@connection,
51
53
  max_payload_size: buffer_max_payload_size,
52
54
  max_pool_size: buffer_max_pool_size || DEFAULT_BUFFER_POOL_SIZE,
53
55
  overflowing_stategy: buffer_overflowing_stategy,
54
56
  )
55
-
56
- @sender = Sender.new(buffer)
57
+ @sender = (single_thread ? SingleThreadSender : Sender).new(buffer, logger: logger)
57
58
  @sender.start
58
59
  end
59
60
 
@@ -97,7 +98,6 @@ module Datadog
97
98
  end
98
99
 
99
100
  private
100
- attr_reader :buffer
101
101
  attr_reader :sender
102
102
  attr_reader :connection
103
103
 
@@ -19,7 +19,7 @@ module Datadog
19
19
  @overflowing_stategy = overflowing_stategy
20
20
 
21
21
  @buffer = String.new
22
- @message_count = 0
22
+ clear_buffer
23
23
  end
24
24
 
25
25
  def add(message)
@@ -42,16 +42,20 @@ module Datadog
42
42
  true
43
43
  end
44
44
 
45
+ def reset
46
+ clear_buffer
47
+ connection.reset_telemetry
48
+ end
49
+
45
50
  def flush
46
51
  return if buffer.empty?
47
52
 
48
53
  connection.write(buffer)
49
-
50
- buffer.clear
51
- @message_count = 0
54
+ clear_buffer
52
55
  end
53
56
 
54
57
  private
58
+
55
59
  attr :max_payload_size
56
60
  attr :max_pool_size
57
61
 
@@ -66,6 +70,11 @@ module Datadog
66
70
  false
67
71
  end
68
72
 
73
+ def clear_buffer
74
+ buffer.clear
75
+ @message_count = 0
76
+ end
77
+
69
78
  def preemptive_flush?
70
79
  @message_count == max_pool_size || buffer.bytesize > bytesize_threshold
71
80
  end
@@ -2,23 +2,45 @@
2
2
 
3
3
  module Datadog
4
4
  class Statsd
5
+ # Sender is using a companion thread to flush and pack messages
6
+ # in a `MessageBuffer`.
7
+ # The communication with this thread is done using a `Queue`.
8
+ # If the thread is dead, it is starting a new one to avoid having a blocked
9
+ # Sender with no companion thread to communicate with (most of the time, having
10
+ # a dead companion thread means that a fork just happened and that we are
11
+ # running in the child process).
5
12
  class Sender
6
13
  CLOSEABLE_QUEUES = Queue.instance_methods.include?(:close)
7
14
 
8
- def initialize(message_buffer)
15
+ def initialize(message_buffer, logger: nil)
9
16
  @message_buffer = message_buffer
17
+ @logger = logger
18
+ @mx = Mutex.new
10
19
  end
11
20
 
12
21
  def flush(sync: false)
13
- # don't try to flush if there is no message_queue instantiated
14
- return unless message_queue
15
-
16
- message_queue.push(:flush)
22
+ # keep a copy around in case another thread is calling #stop while this method is running
23
+ current_message_queue = message_queue
24
+
25
+ # don't try to flush if there is no message_queue instantiated or
26
+ # no companion thread running
27
+ if !current_message_queue
28
+ @logger.debug { "Statsd: can't flush: no message queue ready" } if @logger
29
+ return
30
+ end
31
+ if !sender_thread.alive?
32
+ @logger.debug { "Statsd: can't flush: no sender_thread alive" } if @logger
33
+ return
34
+ end
17
35
 
36
+ current_message_queue.push(:flush)
18
37
  rendez_vous if sync
19
38
  end
20
39
 
21
40
  def rendez_vous
41
+ # could happen if #start hasn't be called
42
+ return unless message_queue
43
+
22
44
  # Initialize and get the thread's sync queue
23
45
  queue = (Thread.current[:statsd_sync_queue] ||= Queue.new)
24
46
  # tell sender-thread to notify us in the current
@@ -32,19 +54,39 @@ module Datadog
32
54
  def add(message)
33
55
  raise ArgumentError, 'Start sender first' unless message_queue
34
56
 
57
+ # if the thread does not exist, we assume we are running in a forked process,
58
+ # empty the message queue and message buffers (these messages belong to
59
+ # the parent process) and spawn a new companion thread.
60
+ if !sender_thread.alive?
61
+ @mx.synchronize {
62
+ # a call from another thread has already re-created
63
+ # the companion thread before this one acquired the lock
64
+ break if sender_thread.alive?
65
+ @logger.debug { "Statsd: companion thread is dead, re-creating one" } if @logger
66
+
67
+ message_queue.close if CLOSEABLE_QUEUES
68
+ @message_queue = nil
69
+ message_buffer.reset
70
+ start
71
+ }
72
+ end
73
+
35
74
  message_queue << message
36
75
  end
37
76
 
38
77
  def start
39
78
  raise ArgumentError, 'Sender already started' if message_queue
40
79
 
41
- # initialize message queue for background thread
80
+ # initialize a new message queue for the background thread
42
81
  @message_queue = Queue.new
43
82
  # start background thread
44
83
  @sender_thread = Thread.new(&method(:send_loop))
45
84
  end
46
85
 
47
86
  if CLOSEABLE_QUEUES
87
+ # when calling stop, make sure that no other threads is trying
88
+ # to close the sender nor trying to continue to `#add` more message
89
+ # into the sender.
48
90
  def stop(join_worker: true)
49
91
  message_queue = @message_queue
50
92
  message_queue.close if message_queue
@@ -53,6 +95,9 @@ module Datadog
53
95
  sender_thread.join if sender_thread && join_worker
54
96
  end
55
97
  else
98
+ # when calling stop, make sure that no other threads is trying
99
+ # to close the sender nor trying to continue to `#add` more message
100
+ # into the sender.
56
101
  def stop(join_worker: true)
57
102
  message_queue = @message_queue
58
103
  message_queue << :close if message_queue
@@ -65,7 +110,6 @@ module Datadog
65
110
  private
66
111
 
67
112
  attr_reader :message_buffer
68
-
69
113
  attr_reader :message_queue
70
114
  attr_reader :sender_thread
71
115
 
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Datadog
4
+ class Statsd
5
+ # The SingleThreadSender is a sender synchronously buffering messages
6
+ # in a `MessageBuffer`.
7
+ # It is using current Process.PID to check it is the result of a recent fork
8
+ # and it is reseting the MessageBuffer if that's the case.
9
+ class SingleThreadSender
10
+ def initialize(message_buffer, logger: nil)
11
+ @message_buffer = message_buffer
12
+ @logger = logger
13
+ @mx = Mutex.new
14
+ # store the pid for which this sender has been created
15
+ update_fork_pid
16
+ end
17
+
18
+ def add(message)
19
+ @mx.synchronize {
20
+ # we have just forked, meaning we have messages in the buffer that we should
21
+ # not send, they belong to the parent process, let's clear the buffer.
22
+ if forked?
23
+ @message_buffer.reset
24
+ update_fork_pid
25
+ end
26
+ @message_buffer.add(message)
27
+ }
28
+ end
29
+
30
+ def flush(*)
31
+ @mx.synchronize {
32
+ @message_buffer.flush()
33
+ }
34
+ end
35
+
36
+ # Compatibility with `Sender`
37
+ def start()
38
+ end
39
+
40
+ # Compatibility with `Sender`
41
+ def stop()
42
+ end
43
+
44
+ # Compatibility with `Sender`
45
+ def rendez_vous()
46
+ end
47
+
48
+ private
49
+
50
+ # below are "fork management" methods to be able to clean the MessageBuffer
51
+ # if it detects that it is running in a unknown PID.
52
+
53
+ def forked?
54
+ Process.pid != @fork_pid
55
+ end
56
+
57
+ def update_fork_pid
58
+ @fork_pid = Process.pid
59
+ end
60
+ end
61
+ end
62
+ end
@@ -19,18 +19,30 @@ module Datadog
19
19
 
20
20
  @host = host || ENV.fetch('DD_AGENT_HOST', DEFAULT_HOST)
21
21
  @port = port || ENV.fetch('DD_DOGSTATSD_PORT', DEFAULT_PORT).to_i
22
+ @socket = nil
23
+ end
24
+
25
+ def close
26
+ @socket.close if @socket
27
+ @socket = nil
22
28
  end
23
29
 
24
30
  private
25
31
 
26
32
  def connect
27
- UDPSocket.new.tap do |socket|
28
- socket.connect(host, port)
29
- end
33
+ close if @socket
34
+
35
+ @socket = UDPSocket.new
36
+ @socket.connect(host, port)
30
37
  end
31
38
 
39
+ # send_message is writing the message in the socket, it may create the socket if nil
40
+ # It is not thread-safe but since it is called by either the Sender bg thread or the
41
+ # SingleThreadSender (which is using a mutex while Flushing), only one thread must call
42
+ # it at a time.
32
43
  def send_message(message)
33
- socket.send(message, 0)
44
+ connect unless @socket
45
+ @socket.send(message, 0)
34
46
  end
35
47
  end
36
48
  end
@@ -14,20 +14,31 @@ module Datadog
14
14
  super(**kwargs)
15
15
 
16
16
  @socket_path = socket_path
17
+ @socket = nil
18
+ end
19
+
20
+ def close
21
+ @socket.close if @socket
22
+ @socket = nil
17
23
  end
18
24
 
19
25
  private
20
26
 
21
27
  def connect
22
- socket = Socket.new(Socket::AF_UNIX, Socket::SOCK_DGRAM)
23
- socket.connect(Socket.pack_sockaddr_un(@socket_path))
24
- socket
28
+ close if @socket
29
+
30
+ @socket = Socket.new(Socket::AF_UNIX, Socket::SOCK_DGRAM)
31
+ @socket.connect(Socket.pack_sockaddr_un(@socket_path))
25
32
  end
26
33
 
34
+ # send_message is writing the message in the socket, it may create the socket if nil
35
+ # It is not thread-safe but since it is called by either the Sender bg thread or the
36
+ # SingleThreadSender (which is using a mutex while Flushing), only one thread must call
37
+ # it at a time.
27
38
  def send_message(message)
28
- socket.sendmsg_nonblock(message)
39
+ connect unless @socket
40
+ @socket.sendmsg_nonblock(message)
29
41
  rescue Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::ENOENT => e
30
- @socket = nil
31
42
  # TODO: FIXME: This error should be considered as a retryable error in the
32
43
  # Connection class. An even better solution would be to make BadSocketError inherit
33
44
  # from a specific retryable error class in the Connection class.
@@ -4,6 +4,6 @@ require_relative 'connection'
4
4
 
5
5
  module Datadog
6
6
  class Statsd
7
- VERSION = '5.1.0'
7
+ VERSION = '5.3.2'
8
8
  end
9
9
  end
@@ -8,8 +8,12 @@ require_relative 'statsd/uds_connection'
8
8
  require_relative 'statsd/message_buffer'
9
9
  require_relative 'statsd/serialization'
10
10
  require_relative 'statsd/sender'
11
+ require_relative 'statsd/single_thread_sender'
11
12
  require_relative 'statsd/forwarder'
12
13
 
14
+ $deprecation_message_mutex = Mutex.new
15
+ $deprecation_message_done = false
16
+
13
17
  # = Datadog::Statsd: A DogStatsd client (https://www.datadoghq.com)
14
18
  #
15
19
  # @example Set up a global Statsd client for a server on localhost:8125
@@ -70,6 +74,7 @@ module Datadog
70
74
  # @option [Integer] buffer_max_pool_size max messages to buffer
71
75
  # @option [String] socket_path unix socket path
72
76
  # @option [Float] default sample rate if not overridden
77
+ # @option [Boolean] single_thread flushes the metrics on the main thread instead of in a companion thread
73
78
  def initialize(
74
79
  host = nil,
75
80
  port = nil,
@@ -85,6 +90,8 @@ module Datadog
85
90
 
86
91
  logger: nil,
87
92
 
93
+ single_thread: false,
94
+
88
95
  telemetry_enable: true,
89
96
  telemetry_flush_interval: DEFAULT_TELEMETRY_FLUSH_INTERVAL
90
97
  )
@@ -97,6 +104,19 @@ module Datadog
97
104
  @serializer = Serialization::Serializer.new(prefix: @prefix, global_tags: tags)
98
105
  @sample_rate = sample_rate
99
106
 
107
+ # deprecation message for ruby < 2.1.0 users as we will drop support for ruby 2.0
108
+ # in dogstatsd-ruby 5.4.0
109
+ # TODO(remy): remove this message and the two global vars used in dogstatd-ruby 5.4.0
110
+ if RUBY_VERSION < '2.1.0' && $deprecation_message_mutex.try_lock && !$deprecation_message_done
111
+ if logger != nil
112
+ logger.warn { "deprecation: dogstatsd-ruby will drop support of Ruby < 2.1.0 in a next minor release" }
113
+ else
114
+ puts("warning: deprecation: dogstatsd-ruby will drop support of Ruby < 2.1.0 in a next minor release")
115
+ end
116
+ $deprecation_message_done = true
117
+ $deprecation_message_mutex.unlock
118
+ end
119
+
100
120
  @forwarder = Forwarder.new(
101
121
  host: host,
102
122
  port: port,
@@ -105,6 +125,8 @@ module Datadog
105
125
  global_tags: tags,
106
126
  logger: logger,
107
127
 
128
+ single_thread: single_thread,
129
+
108
130
  buffer_max_payload_size: buffer_max_payload_size,
109
131
  buffer_max_pool_size: buffer_max_pool_size,
110
132
  buffer_overflowing_stategy: buffer_overflowing_stategy,
metadata CHANGED
@@ -1,15 +1,15 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: dogstatsd-ruby
3
3
  version: !ruby/object:Gem::Version
4
- version: 5.1.0
4
+ version: 5.3.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Rein Henrichs
8
8
  - Karim Bogtob
9
- autorequire:
9
+ autorequire:
10
10
  bindir: bin
11
11
  cert_chain: []
12
- date: 2021-06-17 00:00:00.000000000 Z
12
+ date: 2021-11-03 00:00:00.000000000 Z
13
13
  dependencies: []
14
14
  description: A Ruby DogStatsd client
15
15
  email: code@datadoghq.com
@@ -32,6 +32,7 @@ files:
32
32
  - lib/datadog/statsd/serialization/service_check_serializer.rb
33
33
  - lib/datadog/statsd/serialization/stat_serializer.rb
34
34
  - lib/datadog/statsd/serialization/tag_serializer.rb
35
+ - lib/datadog/statsd/single_thread_sender.rb
35
36
  - lib/datadog/statsd/telemetry.rb
36
37
  - lib/datadog/statsd/udp_connection.rb
37
38
  - lib/datadog/statsd/uds_connection.rb
@@ -41,10 +42,14 @@ licenses:
41
42
  - MIT
42
43
  metadata:
43
44
  bug_tracker_uri: https://github.com/DataDog/dogstatsd-ruby/issues
44
- changelog_uri: https://github.com/DataDog/dogstatsd-ruby/blob/v5.1.0/CHANGELOG.md
45
- documentation_uri: https://www.rubydoc.info/gems/dogstatsd-ruby/5.1.0
46
- source_code_uri: https://github.com/DataDog/dogstatsd-ruby/tree/v5.1.0
47
- post_install_message:
45
+ changelog_uri: https://github.com/DataDog/dogstatsd-ruby/blob/v5.3.2/CHANGELOG.md
46
+ documentation_uri: https://www.rubydoc.info/gems/dogstatsd-ruby/5.3.2
47
+ source_code_uri: https://github.com/DataDog/dogstatsd-ruby/tree/v5.3.2
48
+ post_install_message: |2+
49
+
50
+ If you are upgrading from v4.x of the dogstatsd-ruby library, note the major change to the threading model:
51
+ https://github.com/DataDog/dogstatsd-ruby#migrating-from-v4x-to-v5x
52
+
48
53
  rdoc_options: []
49
54
  require_paths:
50
55
  - lib
@@ -59,9 +64,8 @@ required_rubygems_version: !ruby/object:Gem::Requirement
59
64
  - !ruby/object:Gem::Version
60
65
  version: '0'
61
66
  requirements: []
62
- rubyforge_project:
63
- rubygems_version: 2.7.10
64
- signing_key:
67
+ rubygems_version: 3.2.22
68
+ signing_key:
65
69
  specification_version: 4
66
70
  summary: A Ruby DogStatsd client
67
71
  test_files: []