lib/onering/api.rb in onering-client-0.0.16 vs lib/onering/api.rb in onering-client-0.0.17
- old
+ new
@@ -1,42 +1,74 @@
-require 'net/http'
+require 'net/https'
require 'uri'
require 'json'
require 'yaml'
require 'addressable/uri'
+require 'deep_merge'
module Onering
module API
module Errors
class NotConnected < Exception; end
class ClientError < Exception; end
class ServerError < Exception; end
end
class Base
- DEFAULT_BASE="http://onering"
+ DEFAULT_BASE="https://onering"
DEFAULT_PATH="/api"
- DEFAULT_OPTIONS={}
+ DEFAULT_OPTIONS_FILE=[
+ "./cli.yml",
+ "~/.onering/cli.yml",
+ "/etc/onering/cli.yml"
+ ]
+ DEFAULT_CLIENT_PEM=[
+ "./client.pem",
+ "~/.onering/client.pem",
+ "/etc/onering/client.pem"
+ ]
+
class<<self
+ def connect(options={})
+ # list all existing config files from least specific to most
+ @_configfiles = ([options[:config]] + DEFAULT_OPTIONS_FILE).compact.select{|i|
+ File.exists?(File.expand_path(i))
+ }.reverse
- def connect(host=nil)
- if host.is_a?(URI)
- @_uri = host
- elsif host.is_a?(String)
- @_uri = Addressable::URI.parse("#{host}/#{DEFAULT_PATH}")
+ # merge all config files with more-specific values overriding less-specific ones
+ @_config = {}
+ @_configfiles.each do |i|
+ c = YAML.load(File.read(File.expand_path(i))) rescue {}
+ @_config.deep_merge!(c)
+ end
+
+ if options[:host].is_a?(URI)
+ @_uri = options[:host]
+ elsif options[:host].is_a?(String)
+ @_uri = Addressable::URI.parse("#{options[:host]}/#{DEFAULT_PATH}")
else
- @_uri = Addressable::URI.parse("#{DEFAULT_BASE}/#{DEFAULT_PATH}")
+ @_uri = Addressable::URI.parse("#{@_config['url'] || DEFAULT_BASE}/#{@_config['apiroot'] || DEFAULT_PATH}")
end
-
if @_uri
- @_http = Net::HTTP.new(@_uri.host, @_uri.port)
+ @_pemfile = ([options[:pemfile], @_config['pemfile']]+DEFAULT_CLIENT_PEM).compact.select{|i|
+ File.exists?(File.expand_path(i))
+ }.first
+
+ if @_pemfile
+ @_pem = File.read(File.expand_path(@_pemfile))
+ @_http = Net::HTTP.new(@_uri.host, (@_uri.port || 443))
+ @_http.use_ssl = true
+ @_http.cert = OpenSSL::X509::Certificate.new(@_pem)
+ @_http.key = OpenSSL::PKey::RSA.new(@_pem)
+ @_http.verify_mode = OpenSSL::SSL::VERIFY_PEER
+ end
end
end
def request(endpoint, options={})
- options = DEFAULT_OPTIONS.merge(options)
+ options = @_config.merge(options)
request = nil
uri = Addressable::URI.parse("#{@_uri.to_s}/#{endpoint}")
uri.query_values = options[:fields] if options[:fields]