Class: Corn::Post

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

Instance Method Summary collapse

Constructor Details

#initializePost

Returns a new instance of Post.



7
8
9
10
# File 'lib/corn/post.rb', line 7

def initialize
  @queue = Queue.new
  @thread = start_post_thread
end

Instance Method Details

#enqueue(data, name) ⇒ Object



29
30
31
# File 'lib/corn/post.rb', line 29

def enqueue(data, name)
  @queue << [data, name]
end

#http_post(data, name) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/corn/post.rb', line 33

def http_post(data, name)
  uri = URI.parse(submit_url)
  req = Net::HTTP::Post.new(uri.path)
  req.set_form_data("data" => data, 'client_id' => Corn.client_id, 'name' => name)

  http = Net::HTTP.new(uri.host, uri.port)
  if uri.scheme == 'https'
    http.use_ssl = true
    if Corn.ssl_verify_peer?
      http.verify_mode = OpenSSL::SSL::VERIFY_PEER
      http.ca_file = Corn.ssl_ca_file if Corn.ssl_ca_file
      http.ca_path = Corn.ssl_ca_path if Corn.ssl_ca_path
    else
      http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    end
  end
  res = http.request(req)
  Corn.logger.info("Corn report submitted to #{submit_url}")
  unless res.is_a?(Net::HTTPSuccess)
    Corn.logger.error("Post failed: #{res.message}(#{res.code}), response body: \n#{res.body}")
  end
rescue Exception => e
  Corn.logger.error("post to #{submit_url} failed: #{e.message}\n#{e.backtrace.join("\n")}")
end

#start_post_threadObject



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/corn/post.rb', line 16

def start_post_thread
  Thread.start do
    begin
      loop do
        http_post(*@queue.pop)
        sleep 1
      end
    rescue => e
      Corn.logger.error("Corn post thread stopped by error #{e.message}\n#{e.backtrace.join("\n")}")
    end
  end
end

#submit_urlObject



58
59
60
# File 'lib/corn/post.rb', line 58

def submit_url
  Corn.submit_url
end

#terminateObject



12
13
14
# File 'lib/corn/post.rb', line 12

def terminate
  @thread.terminate rescue nil
end