Class: Fluent::Plugin::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.



9
10
11
12
13
14
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 9

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

Instance Method Details

#add_hash_table_buffer(setting_name, id, hash) ⇒ Object



234
235
236
237
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 234

def add_hash_table_buffer(setting_name, id, hash)
  @hash_table_bulk_insert << "('#{setting_name}','#{id}','#{hash}')"
  flush_hash_table if @hash_table_bulk_insert.size >= @bulk_insert_count
end

#collect_gap_ids(config, current_id, previous_id) ⇒ Object



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 188

def collect_gap_ids(config, current_id, previous_id)
  setting_name = config['name']
  if (current_id - previous_id) > 1 && config['enable_loose_delete'] == 0
    query = "SELECT SQL_NO_CACHE 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 (current_id - previous_id) > 1 && config['enable_loose_delete'] == 1
    return [*previous_id...current_id] - [current_id,previous_id]
  elsif previous_id > current_id
    query = "SELECT SQL_NO_CACHE 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 SQL_NO_CACHE 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



26
27
28
29
30
31
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 26

def configure(conf)
  super
  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



175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 175

def detect_delete(config, current_id, previous_id)
  return if config['enable_delete'] != 1 || previous_id.nil?
  deleted_ids = collect_gap_ids(config, 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



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 150

def detect_insert_update(config, row)
  primary_key = config['primary_key']
  current_id = row[primary_key]
  stored_hash = config['enable_loose_insert'] == 1 ? "" : 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, :id => current_id, :setting_name => config['name'], :hash => current_hash})
  end
end

#emit_record(tag, record) ⇒ Object



288
289
290
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 288

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

#flush_hash_tableObject



262
263
264
265
266
267
268
269
270
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 262

def flush_hash_table
  return if @hash_table_bulk_insert.empty?
  query = "INSERT INTO hash_tables (setting_name,setting_query_pk,setting_query_hash)
    VALUES #{@hash_table_bulk_insert.join(',')}
    ON DUPLICATE KEY UPDATE setting_query_hash = VALUES(setting_query_hash)"
  @manager_db.query(query)
  @hash_table_bulk_insert.clear
  @hash_table_bulk_insert_last_time = Time.now
end

#format_tag(tag, param) ⇒ Object



226
227
228
229
230
231
232
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 226

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

#get_manager_connectionObject



292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 292

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 Mysql2::Error => e
    raise "mysql_replicator_multi: #{e}"
  end
end

#get_origin_connection(config) ⇒ Object



310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 310

def get_origin_connection(config)
  begin
    return Mysql2::Client.new(
      :host => config['host'],
      :port => config['port'],
      :username => config['username'],
      :password => config['password'],
      :database => config['database'],
      :encoding => 'utf8',
      :reconnect => true,
      :stream => true,
      :cache_rows => false
    )
  rescue Mysql2::Error => e
    if config['enable_retry'] == 1
      raise e
    else
      raise "mysql_replicator_multi: #{e}"
    end
  end
end

#get_settingsObject



68
69
70
71
72
73
74
75
76
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 68

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



169
170
171
172
173
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 169

def get_stored_hash(setting_name, id)
  query = "SELECT SQL_NO_CACHE setting_query_hash FROM hash_tables WHERE setting_query_pk = #{id.to_i} AND setting_name = '#{setting_name}'"
  row = @manager_db.query(query).first
  return row.nil? ? "" : row['setting_query_hash']
end

#hash_table_flusherObject



239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 239

def hash_table_flusher
  begin
    while @running
      if @hash_table_bulk_insert.empty? || @bulk_insert_timeout > (Time.now - @hash_table_bulk_insert_last_time)
        sleep @bulk_insert_timeout
        next
      end
      @mutex.synchronize {
        flush_hash_table
      }
    end
    @mutex.synchronize {
      flush_hash_table
    }
  rescue StandardError => e
    @mutex.synchronize {
      log.error "mysql_replicator_multi: failed to flush buffered query. :config=>#{masked_config}"
      log.error "error: #{e.message}"
      log.error e.backtrace.join("\n")
    }
  end
end

#parse_json_columns!(row, columns) ⇒ Object

Parse the given columns’ JSON string values into nested objects in place. Non-string values, missing columns, and malformed JSON are left untouched so enabling this never corrupts non-JSON data.



275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 275

def parse_json_columns!(row, columns)
  return if columns.empty?
  columns.each do |col|
    v = row[col]
    next unless v.is_a?(String)
    begin
      row[col] = JSON.parse(v)
    rescue JSON::ParserError
      # leave the original string as-is on malformed JSON
    end
  end
end

#poll(config) ⇒ Object



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
114
115
116
117
118
119
120
121
122
123
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
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 78

def poll(config)
  begin
    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']
    json_columns = (config['json_columns'] || '').split(',').map(&:strip).reject(&:empty?)
    previous_id = current_id = nil
    while @running
      rows_count = 0
      start_time = Time.now
      db = nil
      nest_db = nil
      begin
        unless config['prepared_query'].nil?
          nest_db = get_origin_connection(config)
          config['prepared_query'].strip.split(/;/).each do |query|
            nest_db.query(query)
          end
        end
        db = get_origin_connection(config)
        db.query(config['query']).each do |row|
          row.each {|k, v| row[k] = v.to_s if v.is_a?(Time) || v.is_a?(Date) || v.is_a?(BigDecimal)}
          parse_json_columns!(row, json_columns)
          row.select {|k, v| v.to_s.strip.match(/^SELECT[^\$]+\$\{[^\}]+\}/i) }.each do |k, v|
            row[k] = [] unless row[k].is_a?(Array)
            nest_db.query(v.gsub(/\$\{([^\}]+)\}/) {|matched| row[$1].to_s}).each do |nest_row|
              nest_row.each {|k, v| nest_row[k] = v.to_s if v.is_a?(Time) || v.is_a?(Date) || v.is_a?(BigDecimal)}
              row[k] << nest_row
            end
          end
          current_id = row[primary_key]
          @mutex.synchronize {
            if row[primary_key].nil?
              log.error "mysql_replicator_multi: missing primary_key. :setting_name=>#{config['name']} :primary_key=>#{primary_key}"
              break
            end
            detect_insert_update(config, row)
            detect_delete(config, current_id, previous_id)
          }
          previous_id = current_id
          rows_count += 1
        end
      rescue Mysql2::Error => e
        raise e unless config['enable_retry'] == 1

        @mutex.synchronize {
          log.error "mysql_replicator_multi: failed due to an error caused by the database. :setting_name=>#{config['name']}"
          log.error "error: #{e.message}"
          log.error e.backtrace.join("\n")
        }
        sleep config['retry_interval']
      ensure
        db.close if db
        nest_db.close if nest_db && !config['prepared_query'].nil?
      end
      elapsed_time = sprintf("%0.02f", Time.now - start_time)
      @mutex.synchronize {
        log.info "mysql_replicator_multi: execution finished. :setting_name=>#{config['name']} :rows_count=>#{rows_count} :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



63
64
65
66
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 63

def shutdown
  @threads.each(&:join)
  super
end

#startObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 33

def start
  super
  begin
    @threads = []
    @mutex = Mutex.new
    @manager_db = get_manager_connection
    @manager_db.query("SET SESSION wait_timeout=1800;")
    @running = true
    @threads << thread_create(:in_mysql_replicator_flusher) {
      @hash_table_bulk_insert = []
      @hash_table_bulk_insert_last_time = Time.now
      hash_table_flusher
    }
    get_settings.each_with_index do |config, idx|
      @threads << thread_create(:"in_mysql_replicator_pollers_#{idx}") {
        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

#stopObject



58
59
60
61
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 58

def stop
  @running = false
  super
end

#update_hashtable(opts) ⇒ Object



214
215
216
217
218
219
220
221
222
223
224
# File 'lib/fluent/plugin/in_mysql_replicator_multi.rb', line 214

def update_hashtable(opts)
  case opts[:event]
  when :insert
    add_hash_table_buffer(opts[:setting_name], opts[: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 = '#{opts[:id]}'"
  when :delete
    query = "DELETE FROM hash_tables WHERE setting_name = '#{opts[:setting_name]}' AND setting_query_pk IN(#{opts[:ids].join(',')})"
  end
  @manager_db.query(query) unless query.nil?
end