Class: LogStash::Outputs::Percy

Inherits:
Base
  • Object
show all
Includes:
Edge
Defined in:
lib/logstash/outputs/percy.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Edge

#to_ns

Instance Attribute Details

#batchObject (readonly)

Returns the value of attribute batch.



76
77
78
# File 'lib/logstash/outputs/percy.rb', line 76

def batch
  @batch
end

Instance Method Details

#add_entry_to_batch(e) ⇒ Object

Add an entry to the current batch returns false if the batch is full and the entry can’t be added.



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/logstash/outputs/percy.rb', line 203

def add_entry_to_batch(e)
  line = e.entry['line']
  # we don't want to send empty lines.
  return true if line.to_s.strip.empty?

  if @batch.nil?
    @batch = Batch.new(e)
    return true
  end

  if @batch.size_bytes_after(line) > @batch_size
    return false
  end
  @batch.add(e)
  return true
end

#batch_sizeObject

‘Maximum batch size to accrue before pushing to loki. Defaults to 102400 bytes’



56
# File 'lib/logstash/outputs/percy.rb', line 56

config :batch_size, :validate => :number, :default => 102400, :required => false

#batch_waitObject

‘Interval in seconds to wait before pushing a batch of records to loki. Defaults to 1 second’



59
# File 'lib/logstash/outputs/percy.rb', line 59

config :batch_wait, :validate => :number, :default => 1, :required => false

#ca_certObject

‘TLS’



53
# File 'lib/logstash/outputs/percy.rb', line 53

config :ca_cert, :validate => :path, :required => false

#certObject

‘Client certificate’



49
# File 'lib/logstash/outputs/percy.rb', line 49

config :cert, :validate => :path, :required => false

#client_idObject

‘BasicAuth credentials’



30
# File 'lib/logstash/outputs/percy.rb', line 30

config :client_id, :validate => :string, :required => true

#closeObject



230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/logstash/outputs/percy.rb', line 230

def close
  @entries.close
  @mutex.synchronize do 
    @stop = true 
  end
  @batch_wait_thread.join
  @batch_size_thread.join

  # if by any chance we still have a forming batch, we need to send it.
  send(@batch) if !@batch.nil?
  @batch = nil
end

#createClientObject



308
309
310
311
312
# File 'lib/logstash/outputs/percy.rb', line 308

def createClient()
  @logger.info("createClient: started method")
  client = OAuth2::Client.new(@client_id, @client_secret, auth_scheme: "basic_auth", site: @tokenurl_domain,:token_url => @tokenurl_endpoint)
  return client
end

#createClientwithProxyObject



314
315
316
317
318
319
320
321
# File 'lib/logstash/outputs/percy.rb', line 314

def createClientwithProxy()
  #@logger.info("createClient: started method")
 conn_opts = {}
 conn_opts = conn_opts.merge('ssl' => {verify: false})
 conn_opts = conn_opts.merge('proxy' => @proxy_url)
 client = OAuth2::Client.new(@client_id, @client_secret, auth_scheme: "basic_auth", site: @tokenurl_domain,:token_url => @tokenurl_endpoint, :connection_opts => conn_opts)
  return client
end

#edge_http_request(token, payload) ⇒ Object



331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# File 'lib/logstash/outputs/percy.rb', line 331

def edge_http_request(token, payload)
  @logger.info("edge_http_request: started method")
  cntLines = JSON.parse(payload)["streams"][0]["values"].size
  @logger.info("processing #{cntLines} lines to edge-prom")
  retry_count = 0
  delay = @min_delay
  begin      
    res = token.post(@uri, {:body => payload1, :headers => params})
    status_code = "#{res.status}"
    @logger.info("send: status_code", :status_code => status_code)
    begin
      @logger.info("send: res_body", :res_body => res)
      #JSON.parse(res.body)
      #@logger.info("send res parsed", :res.parsed => res.parsed)
    rescue StandardError => err
      @logger.warn("Failed to send batch, attempt: ", :error_inspect => err.inspect, :error => err)
    end
    return status_code if !status_code.nil? && status_code.to_i != 429 && status_code.to_i.div(100) != 5
    return res
    raise StandardError.new res
  rescue StandardError => e
    retry_count += 1
    @logger.warn("Failed to send batch, attempt: #{retry_count}/#{@retries}", :error_inspect => e.inspect, :error => e)
    if retry_count < @retries
      sleep delay
      if delay * 2 <= @max_delay
        delay = delay * 2
      else
        delay = @max_delay
      end
      retry
    else
      @logger.error("Failed to send batch", :error_inspect => e.inspect, :error => e)
      return res
    end
  end
end

#getToken(client) ⇒ Object



323
324
325
326
327
328
329
# File 'lib/logstash/outputs/percy.rb', line 323

def getToken(client)
  params = {}
  opts = {}
  params = params.merge('scope' => @scopes)
  access = client.client_credentials.get_token(params, opts)
  return access
end

#include_fieldsObject

‘An array of fields to map to labels, if defined only fields in this list will be mapped.’



68
# File 'lib/logstash/outputs/percy.rb', line 68

config :include_fields, :validate => :array, :default => [], :required => false

#insecure_skip_verifyObject

‘Disable server certificate verification’



46
# File 'lib/logstash/outputs/percy.rb', line 46

config :insecure_skip_verify, :validate => :boolean, :default => false, :required => false

#is_batch_expiredObject



220
221
222
# File 'lib/logstash/outputs/percy.rb', line 220

def is_batch_expired
  return !@batch.nil? && @batch.age() >= @batch_wait
end

#label_set_for(labels) ⇒ Object



262
263
264
265
# File 'lib/logstash/outputs/percy.rb', line 262

def label_set_for(labels)
  #@logger.info("label_set_for: started method")
  return stringify_values(labels) if !labels.empty?
end

#load_sslObject



163
164
165
166
# File 'lib/logstash/outputs/percy.rb', line 163

def load_ssl
  @cert = OpenSSL::X509::Certificate.new(File.read(@cert)) if @cert
  @key = OpenSSL::PKey.read(File.read(@key)) if @key
end

#max_batch_sizeObject



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/logstash/outputs/percy.rb', line 115

def max_batch_size
  @logger.info("max_batch_size: started method")
  loop do
    @mutex.synchronize do
      return if @stop
    end

    e = @entries.deq
    return if e.nil?

    @mutex.synchronize do
      if !add_entry_to_batch(e)
        @logger.debug("Max batch_size is reached. Sending batch to edge-loki")
        send(@batch)
        @batch = Batch.new(e)
      end
    end
  end
end

#max_batch_waitObject



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/logstash/outputs/percy.rb', line 135

def max_batch_wait
  # minimum wait frequency is 10 milliseconds
 min_wait_checkfrequency = 1/100
 max_wait_checkfrequency = @batch_wait
 if max_wait_checkfrequency < min_wait_checkfrequency
  max_wait_checkfrequency = min_wait_checkfrequency
  end

  loop do
    @mutex.synchronize do
      return if @stop
    end

    sleep(max_wait_checkfrequency)
    if is_batch_expired
      @mutex.synchronize do
        @logger.debug("Max batch_wait time is reached. Sending batch to loki")
        send(@batch)
        @batch = nil
      end
    end
  end
end

#max_delayObject

‘Backoff configuration. Maximum backoff time between retries. Default 300s’



71
# File 'lib/logstash/outputs/percy.rb', line 71

config :max_delay, :validate => :number, :default => 300, :required => false

#message_fieldObject

‘Log line field to pick from logstash. Defaults to “message”’



62
# File 'lib/logstash/outputs/percy.rb', line 62

config :message_field, :validate => :string, :default => "message", :required => false

#min_delayObject

‘Backoff configuration. Initial backoff time between retries. Default 1s’



65
# File 'lib/logstash/outputs/percy.rb', line 65

config :min_delay, :validate => :number, :default => 1, :required => false

#proxy_urlObject

‘Proxy URL’



43
# File 'lib/logstash/outputs/percy.rb', line 43

config :proxy_url, :validate => :string, :required => false

#receive(event) ⇒ Object



226
227
228
# File 'lib/logstash/outputs/percy.rb', line 226

def receive(event)
  @entries << Entry.new(event, @message_field, @include_fields)
end

#registerObject



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/logstash/outputs/percy.rb', line 78

def register
  puts "1"
  @uri = URI.parse(@url)
  
  @registry = Prometheus::Client.registry
  @http_requests = Prometheus::Client::Gauge.new(:commandsAborted_summation, docstring: 'prometheus', labels: [:app, :env, :product_id, :provider, :region, :site_code])
  @registry.register(@http_requests)

  unless @uri.is_a?(URI::HTTP) || @uri.is_a?(URI::HTTPS)
    raise LogStash::ConfigurationError, "url parameter must be valid HTTP, currently '#{@url}'"
  end

  if @min_delay > @max_delay
    raise LogStash::ConfigurationError, "Min delay should be less than Max delay, currently 'Min delay is #{@min_delay} and Max delay is #{@max_delay}'"
  end

  @logger.info("Prom output plugin", :class => self.class.name)

  # initialize Queue and Mutex
  @entries = Queue.new 
  @mutex = Mutex.new
  @stop = false

  # create nil batch object.
  @batch = nil

  # validate certs
  if ssl_cert?
    load_ssl
    validate_ssl_key
  end

  # start batch_max_wait and batch_max_size threads
  @batch_wait_thread = Thread.new{max_batch_wait()}
  @batch_size_thread = Thread.new{max_batch_size()}
end

#retriesObject

‘Backoff configuration. Maximum number of retries to do’



74
# File 'lib/logstash/outputs/percy.rb', line 74

config :retries, :validate => :number, :default => 10, :required => false

#scopesObject

‘Scopes’



40
# File 'lib/logstash/outputs/percy.rb', line 40

config :scopes, :validate => :string, :required => true

#send(batch) ⇒ Object



243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/logstash/outputs/percy.rb', line 243

def send(batch)
  @logger.info("send: started method")
  payload = batch.to_json
  client = createClient()
  access = getToken(client)
  @http_requests.set(21.534, labels: label_set_for({ app: 'apmt_metric_test', env: 'test', product_id: 'apmt_test', provider: 'onprem', region: 'westeurope', site_code: 'USTIS01'}))
  #puts "token"
  #puts token
  #JSON.parse(token.ac)
  #puts access.token
  #puts access.headers
  push = Prometheus::Client::Push.new('prometheus').edge_add(access.token, @uri, @registry)
  #Prometheus::Client::Push.new('my-batch-job').add(@registry)
  #push = Prometheus::Client::Push.new('prom_batch', 'edge_prom', 'https://telemetry.pensieve.maersk-digital.net/api/v1/push').add(@registry)
  #push.basic_auth("user", "password")
  #push.add_field 'Authorization', 'Bearer ' + access.token
  #WriteRequest(access)
end

#setLabels(labels_param) ⇒ Object



275
276
277
278
279
280
# File 'lib/logstash/outputs/percy.rb', line 275

def setLabels(labels_param)
  stringified = []
  labels_param.each { |k,v| stringified.append(Label.new(k, v)) }

  stringified
end

#setSamples(sample_ts_param, sample_val_param) ⇒ Object



282
283
284
# File 'lib/logstash/outputs/percy.rb', line 282

def setSamples(sample_ts_param, sample_val_param)
    return Sample.new(sample_ts_param, sample_val_param)
end

#singleObject

‘A single instance of the Output will be shared among the pipeline worker threads’



24
# File 'lib/logstash/outputs/percy.rb', line 24

concurrency :single

#ssl_cert?Boolean

Returns:

  • (Boolean)


159
160
161
# File 'lib/logstash/outputs/percy.rb', line 159

def ssl_cert?
  !@key.nil? && !@cert.nil?
end

#ssl_opts(uri) ⇒ Object



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/logstash/outputs/percy.rb', line 174

def ssl_opts(uri)
  opts = {
    use_ssl: uri.scheme == 'https'
  }

   # disable server certificate verification
  if @insecure_skip_verify
    opts = opts.merge(
      verify_mode: OpenSSL::SSL::VERIFY_NONE
    )
  end

  if !@cert.nil? && !@key.nil?
    opts = opts.merge(
      verify_mode: OpenSSL::SSL::VERIFY_PEER,
      cert: @cert,
      key: @key
    )
  end

  unless @ca_cert.nil?
    opts = opts.merge(
      ca_file: @ca_cert
    )
  end
  opts
end

#stringify_values(labels) ⇒ Object



267
268
269
270
271
272
273
# File 'lib/logstash/outputs/percy.rb', line 267

def stringify_values(labels)
    #@logger.info("stringify_values: started method")
    stringified = {}
    labels.each { |k,v| stringified[k] = v.to_s }

    stringified
end

#tokenurl_domainObject

‘Prom Token URL Domain’



34
# File 'lib/logstash/outputs/percy.rb', line 34

config :tokenurl_domain, :validate => :string, :required => true

#tokenurl_endpointObject

‘Prom Token URL Endpoint’



37
# File 'lib/logstash/outputs/percy.rb', line 37

config :tokenurl_endpoint, :validate => :string, :default => "oauth2/v2.0/token", :required => false

#urlObject

‘Prom URL’



27
# File 'lib/logstash/outputs/percy.rb', line 27

config :url, :validate => :string, :required => true

#validate_ssl_keyObject



168
169
170
171
172
# File 'lib/logstash/outputs/percy.rb', line 168

def validate_ssl_key
  if !@key.is_a?(OpenSSL::PKey::RSA) && !@key.is_a?(OpenSSL::PKey::DSA)
    raise LogStash::ConfigurationError, "Unsupported private key type '#{@key.class}''"
  end
end

#WriteRequest(token) ⇒ Object



286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/logstash/outputs/percy.rb', line 286

def WriteRequest(token)
    #labels = setLabels(label_set_for({ '__name__':'vsphere_vm', app: 'apmt_metric_test', env: 'test', product_id: 'apmt_test', provider: 'onprem', region: 'westeurope', site_code: 'USTIS01'}))
    #puts labels
    #samples = setSamples(Time.now.to_f(), 10.785)
    #puts samples
    #ts = Edge::TimeSeries.new(labels, samples)
    puts "TimeSeries"
    payload1 = {"TimeSeries": {Labels: label_set_for({ '__name__':'vsphere_vm', app: 'apmt_logs_test', env: 'test', product_id: 'apmt_test', provider: 'onprem', region: 'westeurope', site_code: 'USTIS01'}), Samples: [Timestamp: Time.now.to_f(), Value: 10.5 ]}}.to_json
    puts payload1
    #payload1 = {Labels: labels, Samples: samples}
    #payload = Marshal.dump(ts)
    payload = Marshal.dump(payload1)
    source = Snappy.deflate(payload)

    puts "Payload"
    puts payload
    puts "Snappy"
    puts source
    response = token.post(@uri, {:body => source, :headers => {'Content-Type' => 'application/x-protobuf', 'Content-Encoding' => 'snappy', 'User-Agent' => 'mop-edge-1.0.0', 'X-Prometheus-Remote-Write-Version' => '0.1.0'}})
    return response
end