# frozen_string_literal: true require 'json' class MetricsParser def initialize(metric_prefix, router, tag) @metric_prefix = metric_prefix @router = router @tag = tag end def normalise_data(data_to_normalize = []) normalized_data = [] if data_to_normalize.length == 1 data_to_normalize.each do |interim_data| normalized_data = interim_data.split(/\\n+|\\r+/).reject(&:empty?) end else data_to_normalize.each_line do |interim_data| normalized_data << interim_data.strip unless interim_data == "\n" end end normalized_data end def clean_data(data_to_clean = []) cleaned_data = [] data_to_clean.each do |interim_data| cleaned_data << interim_data unless interim_data.include? '#' end cleaned_data end def extract_metrics_in_hash(cleaned_data = [], prefix = '', separator = '') hash_data_array = [] cleaned_data.each do |interim_data| hash_data_array << generate_hash_from_data(interim_data, prefix, separator) end hash_data_array end def generate_hash_from_data(data = '', prefix = '', separator = '') metrics_hash = {} if data =~ /{/ && data =~ /}/ metric_name, additional_dims, metric_val_and_time = data.match(/(.*){(.*)}(.*)/i).captures if metric_val_and_time =~ / / metrics_hash['metric_name'] = prefix + separator + metric_name metrics_hash['value'] = metric_val_and_time.strip.split[0] =~ /^\S*\.\S*$/ ? metric_val_and_time.strip.split[0].to_f : metric_val_and_time.strip.split[0].to_i metrics_hash['time'] = metric_val_and_time.strip.split[1].to_i if additional_dims =~ /,/ additional_dims.split(/,/).map do |interim_data| metrics_hash[interim_data.split(/=/)[0]] = interim_data.split(/=/)[1].gsub(/"/, '') if interim_data =~ /=/ end end end else metrics_hash['metric_name'], metrics_hash['value'], metrics_hash['time'] = data.split metrics_hash['metric_name'] = prefix + separator + metrics_hash['metric_name'] metrics_hash['value'] = metrics_hash['value'] =~ /^\S*\.\S*$/ ? metrics_hash['value'].to_f : metrics_hash['value'].to_i metrics_hash['time'] = metrics_hash['time'].to_i end metrics_hash end def serialize_data(hashed_data_array = []) serialised_data = [] hashed_data_array.each do |interim_data| serialised_data << JSON.parse(interim_data.to_json) end serialised_data end def emit_parsed_metrics(platform_metrics) normalized_data = normalise_data(platform_metrics) cleaned_data = clean_data(normalized_data) hash_data_array = extract_metrics_in_hash(cleaned_data, @metric_prefix, '.') serialized_data = serialize_data(hash_data_array) serialized_data.each do |interim_data| @router.emit(@tag, Fluent::Engine.now, interim_data) end end end