class CloudflareAccess

Constants

DEFAULT_FIELDS

Attributes

auth_email[RW]
auth_key[RW]
domain[RW]
fields[RW]
logger[RW]
metadata_file[RW]

Public Class Methods

new(arguments) click to toggle source
# File lib/logstash/inputs/cloudflare_logs.rb, line 14
def initialize(arguments)
  @auth_email = arguments[:auth_email]
  @auth_key = arguments[:auth_key]
  @domain = arguments[:domain]
  @fields = arguments[:fields] || DEFAULT_FIELDS
  @metadata_file = arguments[:metadata_file]
  @logger = arguments[:logger]
end

Public Instance Methods

end_time() click to toggle source
# File lib/logstash/inputs/cloudflare_logs.rb, line 36
def end_time
  @end_time ||= (Time.now - (5 * 60)).to_datetime.rfc3339.to_s.gsub(/[-+]00:00/, 'Z')
end
logs() click to toggle source
# File lib/logstash/inputs/cloudflare_logs.rb, line 56
def logs
  begin
    results = RestClient.get("https://api.cloudflare.com/client/v4/zones/#{domain}/logs/received?start=#{start_time}&end=#{end_time}&fields=#{fields.join(',')}", 'X-Auth-Email' => auth_email, 'X-Auth-Key' => auth_key)
    results.body.split("\n").collect { |raw_log| JSON.parse(raw_log) }
  rescue RestClient::BadRequest => error
    @logger.error(error.response.strip)
    @logger.error("https://api.cloudflare.com/client/v4/zones/#{domain}/logs/received?start=#{start_time}&end=#{end_time}&fields=#{fields.join(',')}")
    @logger.error({'X-Auth-Email' => auth_email, 'X-Auth-Key' => auth_key}.inspect)

    raise error
  end
end
start_time() click to toggle source
# File lib/logstash/inputs/cloudflare_logs.rb, line 23
def start_time
  if File.exist?(metadata_file)
    begin
      start_time = Time.parse(JSON.parse(File.read(metadata_file))['start_time']).to_datetime.rfc3339.to_s.gsub(/[-+]00:00/, 'Z')
    rescue JSON::ParserError
      start_time = (Time.now - (15 * 60)).to_datetime.rfc3339.to_s.gsub(/[-+]00:00/, 'Z')
    end
  else
    start_time = (Time.now - (15 * 60)).to_datetime.rfc3339.to_s.gsub(/[-+]00:00/, 'Z')
  end
  start_time
end
update_metadata_file(key, value) click to toggle source
# File lib/logstash/inputs/cloudflare_logs.rb, line 40
def update_metadata_file(key, value)
  key = key.to_s
  meta_data = {}

  if File.exist?(metadata_file)
    begin
      meta_data = JSON.parse(File.read(metadata_file))
    rescue JSON::ParserError
    end
  end

  meta_data[key] = value

  File.open(metadata_file, 'w+') { |file| file.write(meta_data.to_json) }
end