lib/prometheus/client/push.rb in prometheus-client-0.7.1 vs lib/prometheus/client/push.rb in prometheus-client-0.8.0

- old
+ new

@@ -1,7 +1,8 @@ # encoding: UTF-8 +require 'thread' require 'net/http' require 'uri' require 'prometheus/client' require 'prometheus/client/formats/text' @@ -13,35 +14,42 @@ # Pushgateway. class Push DEFAULT_GATEWAY = 'http://localhost:9091'.freeze PATH = '/metrics/jobs/%s'.freeze INSTANCE_PATH = '/metrics/jobs/%s/instances/%s'.freeze - HEADER = { 'Content-Type' => Formats::Text::CONTENT_TYPE }.freeze SUPPORTED_SCHEMES = %w(http https).freeze attr_reader :job, :instance, :gateway, :path def initialize(job, instance = nil, gateway = nil) + @mutex = Mutex.new @job = job @instance = instance @gateway = gateway || DEFAULT_GATEWAY - @uri = parse(@gateway) @path = build_path(job, instance) + @uri = parse("#{@gateway}#{@path}") + @http = Net::HTTP.new(@uri.host, @uri.port) - @http.use_ssl = @uri.scheme == 'https' + @http.use_ssl = (@uri.scheme == 'https') end def add(registry) - request('POST', registry) + synchronize do + request(Net::HTTP::Post, registry) + end end def replace(registry) - request('PUT', registry) + synchronize do + request(Net::HTTP::Put, registry) + end end def delete - @http.send_request('DELETE', path) + synchronize do + request(Net::HTTP::Delete) + end end private def parse(url) @@ -62,13 +70,20 @@ else format(PATH, URI.escape(job)) end end - def request(method, registry) - data = Formats::Text.marshal(registry) + def request(req_class, registry = nil) + req = req_class.new(@uri) + req.content_type = Formats::Text::CONTENT_TYPE + req.basic_auth(@uri.user, @uri.password) if @uri.user + req.body = Formats::Text.marshal(registry) if registry - @http.send_request(method, path, data, HEADER) + @http.request(req) + end + + def synchronize + @mutex.synchronize { yield } end end end end