Class: Fluent::Mixin::RewriteTagName::PlaceholderExpander

Inherits:
Object
  • Object
show all
Defined in:
lib/fluent/mixin/rewrite_tag_name.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize ⇒ PlaceholderExpander

Returns a new instance of PlaceholderExpander.



37
38
39
40
# File 'lib/fluent/mixin/rewrite_tag_name.rb', line 37

def initialize
  @tag = ''
  @placeholders = {}
end

Instance Attribute Details

#placeholders ⇒ Object (readonly)



35
36
37
# File 'lib/fluent/mixin/rewrite_tag_name.rb', line 35

def placeholders
  @placeholders
end

Instance Method Details

#expand(str) ⇒ Object



42
43
44
45
46
47
48
49
50
# File 'lib/fluent/mixin/rewrite_tag_name.rb', line 42

def expand(str)
  str = str.gsub(/(\${(tag|hostname)}|__(TAG|HOSTNAME)__)/) do |name|
    $log.warn "RewriteTagNameMixin: unknown placeholder `#{name}` found" unless @placeholders.include?(name)
    @placeholders[name]
  end
  str = str.gsub(/__TAG_PARTS\[-?[0-9]+(?:\.\.\.?-?[0-9]+)?\]__|\$\{tag_parts\[-?[0-9]+(?:\.\.\.?-?[0-9]+)?\]\}/) do |tag_parts_offset|
    expand_tag_parts(tag_parts_offset)
  end
end

#expand_tag_parts(tag_parts_offset) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/fluent/mixin/rewrite_tag_name.rb', line 52

def expand_tag_parts(tag_parts_offset)
  begin
    position = /\[(?<first>-?[0-9]+)(?<range_part>(?<range_type>\.\.\.?)(?<last>-?[0-9]+))?\]/.match(tag_parts_offset)
    raise "failed to parse offset even though matching tag_parts" unless position
    tag_parts = @tag.split('.')
    if position[:range_part]
      extract_tag_part_range(tag_parts, position)
    else
      extract_tag_part_index(tag_parts, position)
    end
  rescue StandardError => e
    $log.warn "RewriteTagNameMixin: failed to expand tag_parts. :message=>#{e.message} tag:#{@tag} placeholder:#{tag_parts_matched}"
    nil
  end
end

#extract_tag_part_index(tag_parts, position) ⇒ Object



68
69
70
71
72
# File 'lib/fluent/mixin/rewrite_tag_name.rb', line 68

def extract_tag_part_index(tag_parts, position)
  index = position[:first].to_i
  raise "missing placeholder." unless tag_parts[index]
  tag_parts[index]
end

#extract_tag_part_range(tag_parts, position) ⇒ Object



74
75
76
77
78
79
# File 'lib/fluent/mixin/rewrite_tag_name.rb', line 74

def extract_tag_part_range(tag_parts, position)
  exclude_end = (position[:range_type] == '...')
  range = Range.new(position[:first].to_i, position[:last].to_i, exclude_end)
  raise "missing placeholder." unless tag_parts[range]
  tag_parts[range].join('.')
end

#set_hostname(value) ⇒ Object



86
87
88
# File 'lib/fluent/mixin/rewrite_tag_name.rb', line 86

def set_hostname(value)
  set_placeholder('hostname', value)
end

#set_tag(value) ⇒ Object



81
82
83
84
# File 'lib/fluent/mixin/rewrite_tag_name.rb', line 81

def set_tag(value)
  @tag = value
  set_placeholder('tag', value)
end