module AppRb::Util::Consul def self.register_service(host, id, name, port, url, tags = []) AppRb::Util.do_it %(curl -s -X PUT #{host}:8500/v1/agent/service/register -d'{ "Id": "#{id}", "Name": "#{name}", "Port": #{port}, "Tags": #{JSON.dump(tags)}, "Check": { "DeregisterCriticalServiceAfter": "20m", "Interval": "7s", "HTTP": "http://#{host}:#{port}#{url}" } }') end def self.remove_services(consul, tags = [], except = nil) JSON.load(AppRb::Util.just_cmd("curl -s #{consul}/v1/catalog/services")).select { |k, v| (v & tags) == tags }.keys.each do |service| JSON.load(AppRb::Util.just_cmd("curl -s #{consul}/v1/catalog/service/#{service}")).each do |s| if except && s["ServiceTags"].index(except) # keep this service else AppRb::Util.do_it %(curl -s -X DELETE #{s["Address"]}:8500/v1/agent/service/deregister/#{s["ServiceID"]}) end end end end def self.consul_wait(consul, service) loop do url = "curl -s #{consul}/v1/health/service/#{service}" statuses = JSON.load(AppRb::Util.just_cmd(url)).flat_map { |s| s["Checks"] }.reject { |c| c["CheckID"] == "serfHealth" }.map { |c| c["Status"] } puts "statuses: #{statuses.inspect}" break if statuses.uniq == ["passing"] || statuses.uniq == [] sleep 3 end end CONSUL_DIR = "apps" def self.kv_get(consul, relative_path, k) AppRb::Util.just_cmd "curl -s #{consul}/v1/kv/#{CONSUL_DIR}/#{relative_path}/#{k}?raw" end def self.kv_set(consul, relative_path, k, v) AppRb::Util.do_it "curl -s -X PUT #{consul}/v1/kv/#{CONSUL_DIR}/#{relative_path}/#{k} -d#{v}" puts "" end def self.kv_unset(consul, relative_path) AppRb::Util.do_it "curl -s -X DELETE #{consul}/v1/kv/#{CONSUL_DIR}/#{relative_path}?recurse" puts "" end def self.kv_keys(consul, relative_path) (JSON.load(AppRb::Util.just_cmd "curl -s #{consul}/v1/kv/#{CONSUL_DIR}/#{relative_path}?recurse") || []).map { |v| v["Key"].sub("#{CONSUL_DIR}/#{relative_path}/", "") } end end