Class: Ridc::Sender

Inherits:
Object
  • Object
show all
Defined in:
lib/sender.rb

Instance Method Summary collapse

Constructor Details

#initialize(customer_key, secret_key, host, port, application_id) ⇒ Sender

Returns a new instance of Sender.



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/sender.rb', line 33

def initialize(customer_key, secret_key, host, port, application_id)
  @queue = Queue.new
  @worker_mutex = Mutex.new
  @application_id = application_id
  @customer_key = customer_key
  @secret_key = secret_key
  @host = host
  @port = port.to_s.to_i
  @my_public_ip = my_first_public_ipv4
  @my_private_ip = my_first_private_ipv4
  @my_hostname = Socket.gethostname
  @environment = Rails.env.to_s
  @sender_started = false
  @sender_thread = nil
end

Instance Method Details

#add_to_queue(event) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/sender.rb', line 49

def add_to_queue(event)
#  Rails.logger.original.debug("RIDC: Loading event.")
  event[:event_session_id] = Thread.current["session_id"]
  event[:event_session_content] = Thread.current["session_content"]
  event[:time] = Time.now.utc.to_i
  body = {  
  "customerKey" => @customer_key,
  "signature" => sign_with_secret_key(event.to_json),
  "event" => event,
  "hostname" => @my_hostname,
  "public_ip_v4" => @my_public_ip,
  "private_ip_v4" => @my_private_ip,
  "environment" => @environment
  }
  
  @queue << body
  @worker_mutex.synchronize do
    if @sender_started
      check_sender_thread
    else
      start_sender_thread
    end
  end
end

#check_sender_threadObject



74
75
76
# File 'lib/sender.rb', line 74

def check_sender_thread
  start_sender_thread unless (@sender_thread && @sender_thread.alive?)
end

#send_all_eventsObject



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/sender.rb', line 84

def send_all_events
#  Rails.logger.original.info("RIDC: Sending all events")
  loop do 
    begin
      if @queue.empty? 
        sleep(SEND_LOOP_DELAY_S)
      else
         body = @queue.pop(true)
        unless body.nil?
          send_request(body)
        end
      end
    rescue Exception => e
      Rails.logger.original.error(e)
    end
  end
end

#send_request(body) ⇒ Object



102
103
104
105
106
107
108
109
110
111
# File 'lib/sender.rb', line 102

def send_request(body)
    
    req = Net::HTTP::Post.new("/events", initheader = {'Content-Type' => 'application/json'})
    req.body = body.to_json
    Ridc.logger.debug("RIDC: Sending event: " + req.body)
    response = Net::HTTP.new(@host, @port).start { |http| http.request(req) }
    return response
rescue Exception => e 
    Rails.logger.original.error(e)
end

#start_sender_threadObject



78
79
80
81
82
# File 'lib/sender.rb', line 78

def start_sender_thread
  #    Rails.logger.original.info("RIDC: Starting sender thread.")
  @sender_thread = Thread.new { send_all_events() }
  @sender_started = true
end