Sha256: e1feb7d898d416775fc3374751cea9fb20d4a6fe911e3a63ac7cda7a2574b812

Contents?: true

Size: 1.46 KB

Versions: 5

Compression:

Stored size: 1.46 KB

Contents

require 'socket'

module Fozzie
  module Socket

    RESERVED_CHARS_REGEX = /[\:\|\@]/

    private

    # Send the statistic to the server
    #
    # Creates the Statsd key from the given values, and sends to socket (depending on sample rate)
    #
    def send(stat, delta, type, sample_rate)
      stat = [stat].flatten.compact.collect(&:to_s).join('.').downcase
      stat = stat.gsub('::', '.').gsub(RESERVED_CHARS_REGEX, '_')

      k =  [Fozzie.c.data_prefix, stat].compact.join('.')
      k << ":"
      k << [delta, type].join('|')
      k << '@%s' % sample_rate.to_s if sample_rate < 1

      sampled(sample_rate) { send_to_socket(k.strip) }
    end

    # If the statistic is sampled, generate a condition to check if it's good to send
    def sampled(sample_rate)
      yield unless sample_rate < 1 and rand > sample_rate
    end

    # Send data to the server via the socket
    def send_to_socket(message)
      begin
        Fozzie.logger.debug {"Statsd: #{message}"} if Fozzie.logger
        Timeout.timeout(Fozzie.c.timeout) {
          res = socket.send(message, 0, Fozzie.c.host, Fozzie.c.port)
          Fozzie.logger.debug {"Statsd sent: #{res}"} if Fozzie.logger
          (res.to_i == message.length)
        }
      rescue => exc
        Fozzie.logger.debug {"Statsd Failure: #{exc.message}\n#{exc.backtrace}"} if Fozzie.logger
        false
      end
    end

    # The Socket we want to use to send data
    def socket
      @socket ||= ::UDPSocket.new
    end

  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
fozzie-0.0.25 lib/fozzie/socket.rb
fozzie-0.0.24 lib/fozzie/socket.rb
fozzie-0.0.23 lib/fozzie/socket.rb
fozzie-0.0.22 lib/fozzie/socket.rb
fozzie-0.0.21 lib/fozzie/socket.rb