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

In the MessageBuffer, detect if we've just been called by a fork child. #199

Closed
wants to merge 3 commits into from
Closed
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
35 changes: 32 additions & 3 deletions lib/datadog/statsd/message_buffer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,20 @@ def initialize(connection,

@buffer = String.new
@message_count = 0

# store the pid for which this message buffer has been created
update_fork_pid
end

def add(message)
# we are in a new PID, which means the parent process has just forked and
# we are currently running in the child: we have to clean the buffer since
# we don't want to process/flush the metrics buffered by the parent process.
if forked?
reset
update_fork_pid
end

message_size = message.bytesize

return nil unless message_size > 0 # to avoid adding empty messages to the buffer
Expand All @@ -42,13 +53,16 @@ def add(message)
true
end

def reset
buffer.clear
@message_count = 0
end

def flush
return if buffer.empty?

connection.write(buffer)

buffer.clear
@message_count = 0
reset
end

private
Expand Down Expand Up @@ -83,6 +97,21 @@ def ensure_sendable!(message_size)
def bytesize_threshold
@bytesize_threshold ||= (max_payload_size - PAYLOAD_SIZE_TOLERANCE * max_payload_size).to_i
end

# below are "fork management" methods to be able to clean the MessageBuffer
# if it detects that it is running in a unknown PID.

def forked?
Process.pid != fork_pid
end

def update_fork_pid
@fork_pid = Process.pid
end

def fork_pid
@fork_pid ||= Process.pid
end
remeh marked this conversation as resolved.
Show resolved Hide resolved
end
end
end