Skip to content

Instantly share code, notes, and snippets.

Created December 28, 2013 20:47
Show Gist options
  • Save anonymous/d0eb6f09b3192765c84d to your computer and use it in GitHub Desktop.
Save anonymous/d0eb6f09b3192765c84d to your computer and use it in GitHub Desktop.
module Puppet::Parser::Functions
newfunction(:multicraft_get_daemon_id, :type => :rvalue) do
user = lookupvar('username')
url = lookupvar('api_url')
key = lookupvar('api_key')
api = MultiCraftApi.new(url, user, key)
connections = api.findConnections :ip, lookupvar('ipaddress')
if connections[:data][:Daemons].count == 0
connections = api.listConnections
if connections[:data][:Daemons].count == 0
1
end
else
connections[:data][:Daemons].keys.max + 1
end
end
end
require 'json'
require 'net/http'
require 'uri'
require 'digest/md5'
class MultiCraftApi
attr_accessor :last_response
@@methods = {
:listUsers => {},
:listConnections => {},
:findConnections => [{:name => :field, :type => :array}, {:name => :value, :type => :array}],
}
def initialize(url, user, key)
@url = url
@user = user
@key = key
end
def method_missing(method, *arguments)
if (!@@methods.has_key? method)
puts method.class.name
return {:success => false, :errors => ['Unknown API method "#{method.class.name}"'], :data => {}};
end
callargs = {}
argnames = @@methods[method]
argnames.each_index { |index|
if argnames[index].kind_of?(Hash)
name = arg[:name]
else
name = argnames[index].to_s
end
if index < arguments.count
value = arguments[index]
elsif argnames[index].kind_of?(Hash) && argnames[index].has_key?(:default)
if index >= arguments.count
value = arg[:default]
else
value = arguments[index]
end
else
return {:success => false, :errors => ['#{method.to_s}()": Not enough arguments (#{arguments.count})'], :data => {}};
end
if argnames[index].kind_of?(Hash) && argnames[index].has_key?(:type)
if arg[:type] == :array
value = JSON.generate(value)
end
callargs[name] = value;
end
call(method.to_s, callargs)
}
end
def call(method, params = {})
if @url.empty?
return {:success => false, :errors => ['Invalid target URL']};
end
if @key.empty?
return {:success => false, :errors => ['Invalid API key']};
end
if !params.kind_of?(Hash)
params = {params => params}
end
params[:'_MulticraftAPIMethod'] = method;
params[:'_MulticraftAPIUser'] = @user;
str = ''
params.each_value { |param|
str << param
}
params[:'_MulticraftAPIKey'] = Digest::MD5.digest(@key+str);
send(@url, params)
end
def send(url, query)
uri = URI.parse(url)
response = Net::HTTP.post_form(uri, query)
if (!response.kind_of?(Net::HTTPSuccess))
error = 'Empty response (wrong API URL or connection problem)'
return {:success => false, :errors => [error], :data => ''}
end
@last_response = response
ret = JSON.parse(response.body, :symbolize_names => true)
if !ret.kind_of?(Hash)
return {:success => false, :errors => [ret], :data => {}};
end
ret
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment