Class: Fluent::MysqlBinlogFlydataInput

Inherits:
MysqlBinlogInput
  • Object
show all
Includes:
FlydataSync, MysqlBinlogFlydataInputPreference
Defined in:
lib/flydata/fluent-plugins/in_mysql_binlog_flydata.rb

Constant Summary collapse

SOURCE_POSITION_FILE_CLASS =
Flydata::SourceMysql::PluginSupport::SourcePositionFile

Instance Method Summary collapse

Methods included from FlydataSync

#build_data_entry, included

Methods included from MysqlBinlogFlydataInputPreference

included

Instance Method Details

#configure(conf) ⇒ Object


55
56
57
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
# File 'lib/flydata/fluent-plugins/in_mysql_binlog_flydata.rb', line 55

def configure(conf)
  super
  Flydata::RollbarHookSetup.new($log).setup

  # SSL configuration
  unless @ssl_ca_content.to_s.strip.empty?
    @ssl_ca_path = @sync_fm.ssl_ca_path(@source_position_file.path)
    @sync_fm.save_ssl_ca(FlydataCore::Fluent::ConfigHelper.unescape_conf(@ssl_ca_content), @ssl_ca_path)
  end

  # Db access opts
  @db_opts = { host: @host, port: @port, username: @username, password: @password, database: @database, ssl_ca: @ssl_ca_path, ssl_cipher: @ssl_cipher }

  $log.info "mysql host:\"#{@host}\" port:\"#{@port}\" username:\"#{@username}\" database:\"#{@database}\" tables:\"#{@tables}\" tables_append_only:\"#{tables_append_only}\""
  $log.info "mysql client version: #{`mysql -V`}"
  server_msg = `echo 'select version();' | #{FlydataCore::Mysql::CommandGenerator.generate_mysql_cmd(@db_opts)} 2>&1`
  if ($? && $?.exitstatus == 0)
    $log.info "mysql server version: #{server_msg.strip}"
  else
    err_msg = "Failed to access mysql server... #{server_msg.strip}"
    $log.error err_msg
    $stderr.puts err_msg
    #exit 1   # causes retry loop
  end

  table_meta = Flydata::SourceMysql::TableMeta.new(@db_opts.merge(tables: @tables))

  # Set context
  @context = Flydata::SourceMysql::PluginSupport::Context.new(
    database: @database, tables: @tables,
    tag: @tag, sync_fm: @sync_fm, omit_events: @omit_events,
    table_meta: table_meta, table_revs: @table_revs, dbconf: @db_opts
  )
  @record_dispatcher = Flydata::SourceMysql::PluginSupport::FlydataBinlogRecordDispatcher.new(@context)
  @idle_event_detector = IdleEventDetector.new(@initial_idle_interval, @continuous_idle_interval, @check_interval, @idle_timeout)
end

#event_listener(event) ⇒ Object


208
209
210
211
212
213
214
215
# File 'lib/flydata/fluent-plugins/in_mysql_binlog_flydata.rb', line 208

def event_listener(event)
  @idle_event_detector.notify
  @record_dispatcher.dispatch(event)
rescue Exception => e
  position = @source_position_file.read
  $log.error "error occurred while processing #{event.event_type} event at #{position}, event_class:#{event.class.to_s}\n#{e.message}\n#{$!.backtrace.join("\n")}"
  raise
end

#runObject


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
151
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/flydata/fluent-plugins/in_mysql_binlog_flydata.rb', line 125

def run
  return if process_aborted?

  @context.table_meta.reload
  Flydata::SourceMysql::TableDdl.migrate_tables(@context.tables, @db_opts,
                                          @context.sync_fm, @source_position_file.path,
                                          @context) do |event|
    @record_dispatcher.dispatch(event)
  end

  current_ssl_cipher = @ssl_cipher
  retried = false

  do_transaction do |transaction_context|
    begin
      begin
        start_kodama(mysql_url) do |c|
          c.binlog_position_file = @source_position_file.path
          if @ssl_ca_path.to_s != '' && c.respond_to?(:ssl_ca=)
            $log.info "SSL is enabled. (ssl_ca: #{@ssl_ca_path})"
            c.ssl_ca = @ssl_ca_path
            unless current_ssl_cipher.to_s.empty?
              $log.info "SSL cipher is set. (ssl_cipher: #{current_ssl_cipher})"
              c.ssl_cipher = current_ssl_cipher
            end
          end

          if c.respond_to?(:sent_binlog_position_file=)
            $log.info "Sent position feature is enabled. sent_position_file:#{@sent_position_file.path}"
            c.sent_binlog_position_file = @sent_position_file.path
          end

          c.connection_retry_limit = @retry_limit
          c.connection_retry_wait = @retry_wait
          c.log_level = @log_level.to_sym
          @listen_events.each do |event_type|
            $log.trace { "registered binlog event listener '#{event_type}'" }
            c.send("on_#{event_type}", &method(:event_listener))
          end
        end
      rescue Kodama::TransactionError
        $log.debug "TransactionError"
        transaction_context.set_transaction_broken
        raise
      end
    rescue Binlog::Error => e
      if /dh key too small/.match(e.to_s) && !retried && !@secondary_ssl_cipher.to_s.empty?
        retried = true
        current_ssl_cipher = @secondary_ssl_cipher
        $log.warn("Retry with secondary ssl cipher list due to '#{e}' - secondary_ssl_cipher: '#{@secondary_ssl_cipher}'")
        retry
      elsif /binlog file.*does not exist/.match(e.to_s)
        $log.error("#{e.to_s}.  Sync must be reset.  Terminating the agent.")
        Process.kill(:TERM, Process.ppid)
      elsif e.kind_of?(Kodama::ConnectionEstablishError)
        $log.error("#{e.to_s}.  Connection to MySQL server could not be established.  Terminating the agent.")
        Process.kill(:TERM, Process.ppid)
      else
        raise e
      end
    end
  end
rescue => e
  # HACK: mysql-replication-listener has a network connection leak bug which doesn't release a connection
  # to MySQL.  Rather than fixing the bug, restarting the fluentd process for now.
  $log.warn "kodama died with an error.  Restart the process after #{@retry_wait} seconds.  error: #{e.class.to_s} '#{e.to_s}'\n#{e.backtrace.join("\n")}"
  sleep @retry_wait
  Process.kill(:HUP, Process.ppid) # Send SIGHUP to the supervisor to restart fluentd
rescue SignalException
  $log.debug "signal exception. exception: #{$!.class.to_s}, error: #{$!.to_s}"
  raise
rescue Exception
  $log.error "unexpected fatal error. exception: #{$!.class.to_s}, error: #{$!.to_s}\n#{$!.backtrace.join("\n")}"
  raise
end

#shutdownObject


217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/flydata/fluent-plugins/in_mysql_binlog_flydata.rb', line 217

def shutdown
  return if process_aborted?

  @idle_event_detector.stop
  if @thread and @thread.alive?
    $log.info "Requesting stop Kodama"
    begin
      @kodama_client.stop_request if @kodama_client
      if wait_till_safe_to_stop
        @thread.join
        $log.info "Kodama has stopped successfully"
      else
        $log.error "Unable to stop Kodama"
      end
    rescue => e
       $log.warn "an error occurred during Kodama shutdown.  error:'#{e.to_s}'\n#{e.backtrace.join("\n")}"
    end
  end

  @sync_fm.close
end

#startObject


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
# File 'lib/flydata/fluent-plugins/in_mysql_binlog_flydata.rb', line 92

def start
  super

  @idle_event_detector.start do |reason, timestamp|
    case reason
    when :event_not_coming
      $log.warn "No binary log event since #{timestamp}"
    when :event_still_not_coming
      $log.warn "No binary log event since #{timestamp}"
    when :event_arrived_finally
      $log.info "Binary log event has come at #{timestamp}"
    when :event_idle_timeout
      $log.warn "No binary log event since #{timestamp}. Restarting the process."
      Process.kill(:HUP, Process.ppid)
    end
  end

rescue Binlog::Error
  if (/basic_string::_M_replace_aux/ === $!.to_s)
    # TODO Fix the root cause in mysql-replication-listener
    $log.error <<EOS
a mysql-replication-listener error.  This could have been caused by one of the following reasons.
- Failed on connect: Your host is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts'
EOS
  else
    $log.error "unexpected mysql-replication-listener error. exception: #{$!.class.to_s}, error: #{$!.to_s}\n#{$!.backtrace.join("\n")}"
  end
  raise
rescue Exception
  $log.error "unexpected fatal error. exception: #{$!.class.to_s}, error: #{$!.to_s}\n#{$!.backtrace.join("\n")}"
  raise
end

#start_kodama(options, &block) ⇒ Object


201
202
203
204
205
206
# File 'lib/flydata/fluent-plugins/in_mysql_binlog_flydata.rb', line 201

def start_kodama(options, &block)
  @kodama_client = Kodama::Client.new(Kodama::Client.mysql_url(options))
  @kodama_client.logger = $log
  block.call(@kodama_client)
  @kodama_client.start
end

#wait_till_safe_to_stopObject


239
240
241
242
243
244
245
246
# File 'lib/flydata/fluent-plugins/in_mysql_binlog_flydata.rb', line 239

def wait_till_safe_to_stop
  retry_count = 5
  1.upto(retry_count) do |i|
    return true if @kodama_client.safe_to_stop?
    sleep 3
  end
  false
end