require 'httparty' require 'json' module GTAPI class GaptoolServer include HTTParty default_timeout 600 DEFAULT_AWS_AZ = 'us-west-2c' attr_reader :version def initialize(user, apikey, uri, default_aws_az=DEFAULT_AWS_AZ) @auth = { 'X-GAPTOOL-USER' => user, 'X-GAPTOOL-KEY' => apikey} default_aws_az = default_aws_az || DEFAULT_AWS_AZ @default_aws_az = default_aws_az @default_aws_region = default_aws_az[0..-2] @version = File.read(File.realpath(File.join(File.dirname(__FILE__), "..", 'VERSION'))).strip GaptoolServer.base_uri uri end def call(verb, url, opts={}) options = opts || {} options[:headers] ||= {} options[:headers].merge!(@auth) options[:headers]['Accept'] = 'application/json' options[:headers]['Content-Type'] = 'application/json' options[:headers]['X-GAPTOOL-VERSION'] = @version case verb when :post options[:body] ||= '' end JSON.parse(self.class.send(verb, url, options).body) end def get(url, opts={}) call(:get, url, opts) end def post(url, opts={}) call(:post, url, opts) end def patch(url, opts={}) call(:patch, url, opts) end def rehash() post("/rehash") end def getonenode(id) get("/instance/#{id}") end def getenvroles(role, environment, params={}) get("/hosts/#{role}/#{environment}", {query: params}) end def addnode(zone, itype, role, environment, mirror=nil, security_group=nil, ami=nil, chef_repo=nil, chef_branch=nil, chef_runlist=nil, no_terminate=nil, tags=nil) body = { 'zone' => zone || @default_aws_az, 'itype' => itype, 'role' => role, 'environment' => environment, 'ami' => ami, 'chef_repo' => chef_repo, 'chef_branch' => chef_branch } unless security_group.nil? body['security_group'] = security_group end unless chef_runlist.nil? || chef_runlist.empty? body['chef_runlist'] = [*chef_runlist] end if no_terminate body['terminate'] = false end unless tags.nil? || tags.empty? body['tags'] = [*tags] end post('/init', {body: body.to_json}) end def terminatenode(id, zone) post('/terminate', {body: {'id' => id, 'zone' => zone || @default_aws_region}.to_json}) end def setparameters(instance, params={}) patch("/instance/#{instance}", {body: params.to_json}) end def getappnodes(app, environment, params={}) get("/app/#{app}/#{environment}/hosts", {query: params}) end def apps(params={}) get("/apps", {query: params}) end def ssh(role, environment, id) get("/ssh/#{role}/#{environment}/#{id}") end def getrolenodes(role, params={}) get("/hosts/#{role}", {query: params}) end def getenvnodes(environment, params={}) get("/hosts/ALL/#{environment}", {query: params}) end def getallnodes(params) get("/hosts", {query: params}) end def api_version() get("/version") end end end