75 lines
2.1 KiB
Ruby
75 lines
2.1 KiB
Ruby
require 'rest_client'
|
|
require 'json'
|
|
require_relative 'exceptions'
|
|
require_relative 'module'
|
|
|
|
module Proxmox::RestConnection
|
|
def __response__ resp
|
|
case resp.code
|
|
when 200
|
|
JSON.parse( resp.body, symbolize_names: true)[:data]
|
|
when 500
|
|
nil
|
|
else
|
|
raise "Request failed of #{req.url} [#{resp.code}]: #{resp.body.inspect}"
|
|
end
|
|
end
|
|
|
|
def __headers__ **hdrs
|
|
Proxmox.api_ticket.merge( 'Accept' => 'application/json').merge( hdrs)
|
|
end
|
|
|
|
def __data__ **data
|
|
case data
|
|
when String
|
|
data
|
|
else
|
|
data.to_json
|
|
end
|
|
end
|
|
|
|
private :__response__, :__headers__, :__data__
|
|
|
|
def bench path
|
|
#t = Time.now
|
|
r = yield
|
|
#p path => Time.now-t
|
|
r
|
|
end
|
|
|
|
def rest_get path, **data, &exe
|
|
data = data.delete_if {|k,v|v.nil?}
|
|
path += "#{path.include?( ??) ? ?& : ??}#{data.map{|k,v|"#{CGI.escape k.to_s}=#{CGI.escape v.to_s}"}.join '&'}" unless data.empty?
|
|
STDERR.puts "GET #{path} <= #{data}" if $DEBUG
|
|
__response__ Proxmox.connection[path].get( __headers__( :'Content-Type' => 'application/json'))
|
|
rescue RestClient::Exception
|
|
$!.instance_variable_set :@request, "GET #{path}"
|
|
raise
|
|
end
|
|
|
|
def rest_put path, **data, &exe
|
|
data = __data__( **data)
|
|
STDERR.puts "PUT #{path} <= #{data}" if $DEBUG
|
|
__response__ Proxmox.connection[path].put( data, __headers__( :'Content-Type' => 'application/json'))
|
|
rescue RestClient::Exception
|
|
$!.instance_variable_set :@request, "PUT #{path}"
|
|
raise
|
|
end
|
|
|
|
def rest_del path, &exe
|
|
STDERR.puts "DELETE #{path}" if $DEBUG
|
|
__response__ Proxmox.connection[path].delete( __headers__( :'Content-Type' => 'application/json'))
|
|
rescue RestClient::Exception
|
|
$!.instance_variable_set :@request, "DELETE #{path}"
|
|
raise
|
|
end
|
|
|
|
def rest_post path, **data, &exe
|
|
data = __data__( **data)
|
|
STDERR.puts "POST #{path} <= #{data}" if $DEBUG
|
|
__response__ Proxmox.connection[path].post( data, __headers__( :'Content-Type' => 'application/json'))
|
|
rescue RestClient::Exception
|
|
$!.instance_variable_set :@request, "POST #{path}"
|
|
raise
|
|
end
|
|
end
|