Class: Fluent::MysqlReplicatorMultiInput

Inherits:
Input
  • Object
show all
Defined in:
lib/fluent/plugin/in_mysql_replicator_multi.rb

Instance Method Summary collapse

Constructor Details

#initializeMysqlReplicatorMultiInput

Returns a new instance of MysqlReplicatorMultiInput.



5
6
7
8
9
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 5

def initialize
  require 'mysql2'
  require 'digest/sha1'
  super
end

Instance Method Details

#collect_gap_ids(setting_name, current_id, previous_id) ⇒ Object



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 137

def collect_gap_ids(setting_name, current_id, previous_id)
  if (current_id - previous_id) > 1
    query = "SELECT setting_query_pk FROM hash_tables
      WHERE setting_name = '#{setting_name}' 
      AND setting_query_pk > #{previous_id.to_i} AND setting_query_pk < #{current_id.to_i}"
  elsif previous_id > current_id
    query = "SELECT setting_query_pk FROM hash_tables
      WHERE setting_name = '#{setting_name}' 
      AND setting_query_pk > #{previous_id.to_i}"
  elsif previous_id == current_id
    query = "SELECT setting_query_pk FROM hash_tables
      WHERE setting_name = '#{setting_name}' 
      AND (setting_query_pk > #{current_id.to_i} OR setting_query_pk < #{current_id.to_i})"
  end
  ids = Array.new
  unless query.nil?
    @manager_db.query(query).each do |row|
      ids << row['setting_query_pk']
    end
  end
  return ids
end

#configure(conf) ⇒ Object



18
19
20
21
22
23
24
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 18

def configure(conf)
  super
  @reconnect_interval = Config.time_value('10sec')
  if @tag.nil?
    raise Fluent::ConfigError, "mysql_replicator_multi: missing 'tag' parameter. Please add following line into config like 'tag replicator.${name}.${event}.${primary_key}'"
  end
end

#detect_delete(config, current_id, previous_id) ⇒ Object



124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 124

def detect_delete(config, current_id, previous_id)
  return unless config['enable_delete'] == 1
  deleted_ids = collect_gap_ids(config['name'], current_id, previous_id)
  unless deleted_ids.empty?
    event = :delete
    deleted_ids.each do |id|
      tag = format_tag(@tag, {:name => config['name'], :event => event, :primary_key => config['primary_key']})
      emit_record(tag, {config['primary_key'] => id})
    end
    update_hashtable({:event =>  event, :ids => deleted_ids, :setting_name => config['name']})
  end
end

#detect_insert_update(config, row) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 98

def detect_insert_update(config, row)
  primary_key = config['primary_key']
  current_id = row[primary_key]
  stored_hash = get_stored_hash(config['name'], current_id)
  current_hash = Digest::SHA1.hexdigest(row.flatten.join)

  event = nil
  if stored_hash.empty?
    event = :insert
  elsif stored_hash != current_hash
    event = :update
  end
  unless event.nil?
    tag = format_tag(@tag, {:name => config['name'], :event => event, :primary_key => config['primary_key']})
    emit_record(tag, row)
    update_hashtable({:event => event, :ids => current_id, :setting_name => config['name'], :hash => current_hash})
  end
end

#emit_record(tag, record) ⇒ Object



183
184
185
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 183

def emit_record(tag, record)
  Engine.emit(tag, Engine.now, record)
end

#format_tag(tag, param) ⇒ Object



175
176
177
178
179
180
181
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 175

def format_tag(tag, param)
  pattern = {'${name}' => param[:name], '${event}' => param[:event].to_s, '${primary_key}' => param[:primary_key]}
  tag.gsub(/\${[a-z_]+(\[[0-9]+\])?}/, pattern) do
    $log.warn "mysql_replicator_multi: missing placeholder. :tag=>#{tag} :placeholder=>#{$1}" unless pattern.include?($1)
    pattern[$1]
  end
end

#get_manager_connectionObject



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 187

def get_manager_connection
  begin
    return Mysql2::Client.new(
      :host => @manager_host,
      :port => @manager_port,
      :username => @manager_username,
      :password => @manager_password,
      :database => @manager_database,
      :encoding => 'utf8',
      :reconnect => true,
      :stream => false,
      :cache_rows => false
    )
  rescue Exception => e
    $log.warn "mysql_replicator_multi: #{e}"
    sleep @reconnect_interval
    retry
  end
end

#get_origin_connection(config) ⇒ Object



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 207

def get_origin_connection(config)
  begin
    return Mysql2::Client.new(
      :host => config['host'],
      :port => config['manager_port'],
      :username => config['username'],
      :password => config['password'],
      :database => config['database'],
      :encoding => 'utf8',
      :reconnect => true,
      :stream => true,
      :cache_rows => false
    )
  rescue Exception => e
    $log.warn "mysql_replicator_multi: #{e}"
    sleep @reconnect_interval
    retry
  end
end

#get_settingsObject



48
49
50
51
52
53
54
55
56
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 48

def get_settings
  manager_db = get_manager_connection
  settings = []
  query = "SELECT * FROM settings WHERE is_active = 1;"
  manager_db.query(query).each do |row|
    settings << row
  end
  return settings
end

#get_stored_hash(setting_name, id) ⇒ Object



117
118
119
120
121
122
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 117

def get_stored_hash(setting_name, id)
  query = "SELECT setting_query_hash FROM hash_tables WHERE setting_query_pk = #{id.to_i} AND setting_name = '#{setting_name}'"
  @manager_db.query(query).each do |row|
    return row['setting_query_hash']
  end
end

#poll(config) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 58

def poll(config)
  begin
    @manager_db = get_manager_connection
    masked_config = Hash[config.map {|k,v| (k == 'password') ? [k, v.to_s.gsub(/./, '*')] : [k,v]}]
    @mutex.synchronize {
      $log.info "mysql_replicator_multi: polling start. :config=>#{masked_config}"
    }
    primary_key = config['primary_key']
    previous_id = current_id = 0
    loop do
      start_time = Time.now
      db = get_origin_connection(config)
      db.query(config['query']).each do |row|
        @mutex.lock
        row.each {|k, v| row[k] = v.to_s if v.is_a?(Time) || v.is_a?(Date)}
        current_id = row[primary_key]
        if row[primary_key].nil?
          $log.error "mysql_replicator_multi: missing primary_key. :setting_name=>#{config['name']} :primary_key=>#{primary_key}"
          @mutex.unlock
          break
        end
        detect_insert_update(config, row)
        detect_delete(config, current_id, previous_id)
        previous_id = current_id
        @mutex.unlock
      end
      db.close
      elapsed_time = sprintf("%0.02f", Time.now - start_time)
      $log.info "mysql_replicator_multi: finished execution :setting_name=>#{config['name']} :elapsed_time=>#{elapsed_time} sec"
      sleep config['interval']
    end
  rescue StandardError => e
    @mutex.synchronize {
      $log.error "mysql_replicator_multi: failed to execute query. :config=>#{masked_config}"
      $log.error "error: #{e.message}"
      $log.error e.backtrace.join("\n")
    }
  end
end

#shutdownObject



42
43
44
45
46
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 42

def shutdown
  @threads.each do |thread|
    Thread.kill(thread)
  end
end

#startObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 26

def start
  begin
    @threads = []
    @mutex = Mutex.new
    get_settings.each do |config|
      @threads << Thread.new {
        poll(config)
      }
    end
    $log.error "mysql_replicator_multi: stop working due to empty configuration" if @threads.empty?
  rescue StandardError => e
    $log.error "error: #{e.message}"
    $log.error e.backtrace.join("\n")
  end
end

#update_hashtable(opts) ⇒ Object



160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 160

def update_hashtable(opts)
  ids = opts[:ids].is_a?(Integer) ? [opts[:ids]] : opts[:ids]
  ids.each do |id|
    case opts[:event]
    when :insert
      query = "insert into hash_tables (setting_name,setting_query_pk,setting_query_hash) values('#{opts[:setting_name]}','#{id}','#{opts[:hash]}')"
    when :update
      query = "update hash_tables set setting_query_hash = '#{opts[:hash]}' WHERE setting_name = '#{opts[:setting_name]}' AND setting_query_pk = '#{id}'"
    when :delete
      query = "delete from hash_tables WHERE setting_name = '#{opts[:setting_name]}' AND setting_query_pk = '#{id}'"
    end
    @manager_db.query(query) unless query.nil?
  end
end