api.rb
1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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: