Skip to content

Instantly share code, notes, and snippets.

@mikehale
Last active December 27, 2015 00:39
Show Gist options
  • Save mikehale/7239367 to your computer and use it in GitHub Desktop.
Save mikehale/7239367 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'optparse'
require 'excon'
require 'json'
require 'uri'
require 'netrc'
class LibratoLogsUriFetcher
attr_reader :name, :user, :secret
def initialize(name, user, secret)
@name = name
@user = user
@secret = secret
end
def basic_auth(user, pass)
'Basic ' << ['' << user << ':' << pass].pack('m').delete(Excon::CR_NL)
end
def headers
{
'Authorization' => basic_auth(user, secret),
'Content-Type' => 'application/json'
}
end
def find_token(offset=0, length=100)
response = Excon.get("https://metrics-api.librato.com/v1/api_tokens",
:headers => headers,
:expects => [200],
:query => {'offset' => offset, 'length' => length})
token = JSON.parse(response.body)["api_tokens"].detect{|t| t["name"] == name }
return token if token
query = JSON.parse(response.body)["query"]
offset = query["offset"]
total = query["total"]
if offset + length < total
find_token(offset + length, length)
end
end
def create_token
response = Excon.post("https://metrics-api.librato.com/v1/api_tokens",
:headers => headers,
:expects => [200, 201],
:body => {:name => name, :role => "recorder"}.to_json)
JSON.parse(response.body)
end
def get_logs_uri(token_uri)
response = Excon.get(token_uri,
:headers => headers,
:expects => [200],
:query => {'logs_uri' => 1})
JSON.parse(response.body)["logs_uri"]
end
def run
if token = find_token
token_uri = token['href']
puts "Found an existing token named: #{name}"
else
puts "Creating a token named: #{name}"
token = create_token
token_uri = token['href']
end
puts get_logs_uri(token_uri)
end
end
ARGV.options do |o|
name = ""
user, secret = Netrc.read["metrics-api.librato.com"] || ["", ""]
o.set_summary_indent(" ")
o.banner = "Usage: #{$0} [OPTIONS]"
o.on("-u", "--user USER", String, "Librato account email") { |e| user = e }
o.on("-s", "--secret SECRET", String, "Librato api key with full access used to create the record only scoped api key") { |e| secret = e }
o.on("-n", "--name NAME", String, "Name to give the recorder api key (should include the app name)") { |e| name = e }
o.parse!
o.abort(o) if [user, name, secret].any?(&:empty?)
LibratoLogsUriFetcher.new(name, user, secret).run
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment