Class: LogStash::Outputs::LMLogs

Inherits:
Base
  • Object
show all
Defined in:
lib/logstash/outputs/lmlogs.rb

Overview

An example output that does nothing.

Defined Under Namespace

Classes: InvalidHTTPConfigError

Constant Summary collapse

ALLOWED_DOMAINS =
["logicmonitor.com", "lmgov.us", "qa-lmgov.us"]
@@MAX_PAYLOAD_SIZE =
8*1024*1024
@@CONSOLE_LOGS =

For developer debugging.

false

Instance Method Summary collapse

Instance Method Details

#clientObject



184
185
186
# File 'lib/logstash/outputs/lmlogs.rb', line 184

def client
  @client ||= make_client
end

#client_configObject

def register



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/logstash/outputs/lmlogs.rb', line 152

def client_config
  c = {
      connect_timeout: @connect_timeout,
      socket_timeout: @socket_timeout,
      request_timeout: @request_timeout,
      follow_redirects: @follow_redirects,
      automatic_retries: @automatic_retries,
      retry_non_idempotent: @retry_non_idempotent,
      check_connection_timeout: @validate_after_inactivity,
      pool_max: @pool_max,
      pool_max_per_route: @pool_max_per_route,
      cookies: @cookies,
      keepalive: @keepalive
  }

  if @proxy
    # Symbolize keys if necessary
    c[:proxy] = @proxy.is_a?(Hash) ?
                    @proxy.reduce({}) {|memo,(k,v)| memo[k.to_sym] = v; memo} :
                    @proxy
  end

  log_debug("manticore client config: ", :client => c)
  return c
end

#closeObject



189
190
191
# File 'lib/logstash/outputs/lmlogs.rb', line 189

def close
  @client.close
end

#configure_authObject



193
194
195
196
197
198
199
200
201
202
203
# File 'lib/logstash/outputs/lmlogs.rb', line 193

def configure_auth
  @use_bearer_instead_of_lmv1 = false
  if @access_id == nil || @access_key.value == nil
    @logger.info "Access Id or access key null. Using bearer token for authentication."
    @use_bearer_instead_of_lmv1 = true
  end
  if @use_bearer_instead_of_lmv1 && @bearer_token.value == nil
    @logger.error "Bearer token not specified. Either access_id and access_key both or bearer_token must be specified for authentication with Logicmonitor."
    raise LogStash::ConfigurationError, 'No valid authentication specified. Either access_id and access_key both or bearer_token must be specified for authentication with Logicmonitor.'
  end
end

#generate_auth_string(body) ⇒ Object



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

def generate_auth_string(body)
  if @use_bearer_instead_of_lmv1
    return "Bearer #{@bearer_token.value}"
  else
    timestamp = DateTime.now.strftime('%Q')
    hash_this = "POST#{timestamp}#{body}/log/ingest"
    sign_this = OpenSSL::HMAC.hexdigest(
                  OpenSSL::Digest.new('sha256'),
                  "#{@access_key.value}",
                  hash_this
                )
    signature = Base64.strict_encode64(sign_this)
    return "LMv1 #{@access_id}:#{signature}:#{timestamp}"
  end
end

#isValidPayloadSize(documents, lmlogs_event, max_payload_size) ⇒ Object



356
357
358
359
360
361
362
363
364
# File 'lib/logstash/outputs/lmlogs.rb', line 356

def isValidPayloadSize(documents,lmlogs_event,max_payload_size)
  if (documents.to_json.bytesize + lmlogs_event.to_json.bytesize) >  max_payload_size
        send_batch(documents)
        documents = []

  end
  documents.push(lmlogs_event)
  return documents
end

#log_debug(message, *opts) ⇒ Object



282
283
284
285
286
287
288
# File 'lib/logstash/outputs/lmlogs.rb', line 282

def log_debug(message, *opts)
  if @@CONSOLE_LOGS
    puts "[#{DateTime::now}] [logstash.outputs.lmlogs] [DEBUG] #{message} #{opts.to_s}"
  elsif debug
    @logger.debug(message, *opts)
  end
end

#log_failure(message, opts) ⇒ Object



352
353
354
# File 'lib/logstash/outputs/lmlogs.rb', line 352

def log_failure(message, opts)
  @logger.error("[HTTP Output Failure] #{message}", opts)
end

#multi_receive(events) ⇒ Object



291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/logstash/outputs/lmlogs.rb', line 291

def multi_receive(events)
  if events.length() > 0
    log_debug(events.to_json)
 end

  events.each_slice(@batch_size) do |chunk|
    documents = []
    chunk.each do |event|

      documents = isValidPayloadSize(documents, processEvent(event), @@MAX_PAYLOAD_SIZE)
    end
    send_batch(documents)
  end
end

#processEvent(event) ⇒ Object



307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/logstash/outputs/lmlogs.rb', line 307

def processEvent(event)
  event_json = JSON.parse(event.to_json)
  lmlogs_event = {}

  if 
    lmlogs_event = event_json
    lmlogs_event.delete("@timestamp")  # remove redundant timestamp field
    unless @resource_type.to_s.strip.empty?
      lmlogs_event["_resource.type"] = @resource_type
    end

    if lmlogs_event.dig("event", "original") != nil
      lmlogs_event["event"].delete("original") # remove redundant log field
    end
  elsif 
    .each do | key, value |
      nestedVal = event_json
      value.each do |x|
        if nestedVal == nil
          break
        end
        nestedVal = nestedVal[x]
      end
      if nestedVal != nil
        lmlogs_event[key] = nestedVal
      end
    end
  end

  lmlogs_event["message"] = event.get(@message_key).to_s
  lmlogs_event["_lm.resourceId"] = {}
  lmlogs_event["_lm.resourceId"]["#{@lm_property}"] = event.get(@property_key.to_s)

  if @keep_timestamp
    lmlogs_event["timestamp"] = event.get("@timestamp")
  end

  if @timestamp_is_key
    lmlogs_event["timestamp"] = event.get(@timestamp_key.to_s)
  end

  return lmlogs_event

end

#registerObject



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/logstash/outputs/lmlogs.rb', line 124

def register
  @total = 0
  @total_failed = 0
  logger.info("Initialized LogicMonitor output plugin with configuration",
              :host => @host)
  logger.info("Max Payload Size: ",
              :size => @@MAX_PAYLOAD_SIZE)
  configure_auth

  # Check if `portal_domain` is an empty string and set the default value
  if @portal_domain.nil? || @portal_domain.strip.empty?
    @portal_domain = "logicmonitor.com"
  end

   unless ALLOWED_DOMAINS.include?(@portal_domain)
        raise LogStash::ConfigurationError, "Invalid portal_domain: #{@portal_domain}. Allowed values are: #{ALLOWED_DOMAINS.join(', ')}"
   end
   log_debug("Setting LM portal domain ", :portal_domain => portal_domain)

   = Hash.new
  if .any?
    .each do | nested_key |
      [nested_key] = nested_key.to_s.split('.')
    end
  end

end

#send_batch(events) ⇒ Object



220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/logstash/outputs/lmlogs.rb', line 220

def send_batch(events)
  log_debug("Started sending logs to LM: ",
                :time => Time::now.utc)
  url = "https://" + @portal_name + "." + @portal_domain +"/rest/log/ingest"
  body = events.to_json
  auth_string = generate_auth_string(body)
  request = client.post(url, {
      :body => body,
      :headers => {
              "Content-Type" => "application/json",
              "User-Agent" => "lm-logs-logstash/" + LmLogsLogstashPlugin::VERSION,
              "Authorization" => "#{auth_string}"
      }
  })

  request.on_success do |response|
    if response.code == 202
      @total += events.length
      log_debug("Successfully sent ",
                    :response_code => response.code,
                    :batch_size => events.length,
                    :total_sent => @total,
                    :time => Time::now.utc)
    elsif response.code == 207
      log_failure(
        "207 HTTP code - some of the events successfully parsed, some not. ",
        :response_code => response.code,
        :url => url,
        :response_body => response.body,
        :total_failed => @total_failed)
    else
      @total_failed += 1
      log_failure(
          "Encountered non-202/207 HTTP code #{response.code}",
          :response_code => response.code,
          :url => url,
          :response_body => response.body,
          :total_failed => @total_failed)
    end
  end

  request.on_failure do |exception|
    @total_failed += 1
    log_failure("The request failed. ",
                :url => url,
                :method => @http_method,
                :message => exception.message,
                :class => exception.class.name,
                :backtrace => exception.backtrace,
                :total_failed => @total_failed
    )
  end

  log_debug("Completed sending logs to LM",
                :total => @total,
                :time => Time::now.utc)
  request.call

rescue Exception => e
  @logger.error("[Exception=] #{e.message} #{e.backtrace}")
end