api.rb 1.92 KB
module Lxd::API
  def self.get host, certificate = nil
    certificate ||= host.certificate

    uri = URI.parse host.uri
    con = Net::HTTP.new uri.host, uri.port ? uri.port : 8443
    con.use_ssl = true
    con.cert = OpenSSL::X509::Certificate.new certificate.cert
    con.key = OpenSSL::PKey::RSA.new certificate.key
    con.verify_mode = OpenSSL::SSL::VERIFY_NONE

    resp = call con, Net::HTTP::Get.new('/')
    api = Lxd::API::V1_0.new con if resp['metadata'].include? '/1.0'
    raise Lxd::API::Exception 'unsupported api version' unless api
    return api unless block_given?
    yield api
  rescue Lxd::API::Exception => e
    Rails.logger.error { "#{e.message} #{e.backtrace.join("\n")}" }
    nil
  rescue => e
    Rails.logger.error {
      format(
        'Error connecting: %s, %s %s',
        host.uri, e.message, e.backtrace.join("\n")
      )
    }
    nil
  ensure
    con.close if block_given?
  end

  def self.call con, req
    resp = con.request req
    unless resp.code != 200
      raise Lxd::API::Exception(
        "request failure: (#{resp.code}) #{resp.message}"
      )
    end
    JSON.parse resp.body
  end

  def initialize con
    @con = con
  end

  def call req
    handle_response(Lxd::API.call @con, req)
  rescue Lxd::API::Exception => e
    Rails.logger.error { "#{e.message} #{e.backtrace.join("\n")}" }
    nil
  rescue => e
    Rails.logger.error {
      format(
        'Error connecting: %s, %s %s',
        host.uri, e.message, e.backtrace.join("\n")
      )
    }
    nil
  end

  def get uri
    call Net::HTTP::Get.new uri
  end

  def put uri, data={}
    request = Net::HTTP::Put.new uri
    request.body = data.to_json
    call request
  end

  def post uri, data={}
    request = Net::HTTP::Post.new uri
    request.body = data.to_json
    call request
  end

  def delete uri, data={}
    request = Net::HTTP::Delete.new uri
    request.body = data.to_json
    call request
  end
end
# vim: set et ts=2 sw=2: