Class: MysqlWarmer::EventedMysql

Inherits:
EM::Connection
  • Object
show all
Defined in:
lib/mysql_warmer/em/mysql.rb,
lib/mysql_warmer/em/mysql.rb

Constant Summary collapse

DisconnectErrors =
[
'query: not connected',
'MySQL server has gone away',
'Lost connection to MySQL server during query'
]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(mysql, opts) ⇒ EventedMysql

Returns a new instance of EventedMysql.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/mysql_warmer/em/mysql.rb', line 19

def initialize mysql, opts
  @mysql = mysql
  @fd = mysql.socket
  @opts = opts
  @current = nil
  @@queue ||= []
  @processing = false
  @connected = true

  log 'mysql connected'

  self.notify_readable = true
  EM.add_timer(0){ next_query }
end

Instance Attribute Details

#connectedObject (readonly)

Returns the value of attribute connected.



33
34
35
# File 'lib/mysql_warmer/em/mysql.rb', line 33

def connected
  @connected
end

#optsObject (readonly) Also known as: settings

Returns the value of attribute opts.



33
34
35
# File 'lib/mysql_warmer/em/mysql.rb', line 33

def opts
  @opts
end

#processingObject (readonly)

Returns the value of attribute processing.



33
34
35
# File 'lib/mysql_warmer/em/mysql.rb', line 33

def processing
  @processing
end

Class Method Details

._connect(opts) ⇒ Object

stolen from sequel



204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/mysql_warmer/em/mysql.rb', line 204

def self._connect opts
  opts = settings.merge(opts)

  conn = Mysql.init

  # set encoding _before_ connecting
  if charset = opts[:charset] || opts[:encoding]
    conn.options(Mysql::SET_CHARSET_NAME, charset)
  end

  conn.options(Mysql::OPT_LOCAL_INFILE, 'client')

  conn.real_connect(
    opts[:host] || 'localhost',
    opts[:user] || 'root',
    opts[:password],
    opts[:database],
    opts[:port],
    opts[:socket],
    0 +
    # XXX multi results require multiple callbacks to parse
    # Mysql::CLIENT_MULTI_RESULTS +
    # Mysql::CLIENT_MULTI_STATEMENTS +
    (opts[:compress] == false ? 0 : Mysql::CLIENT_COMPRESS)
  )

  # increase timeout so mysql server doesn't disconnect us
  # this is especially bad if we're disconnected while EM.attach is
  # still in progress, because by the time it gets to EM, the FD is
  # no longer valid, and it throws a c++ 'bad file descriptor' error
  # (do not use a timeout of -1 for unlimited, it does not work on mysqld > 5.0.60)
  conn.query("set @@wait_timeout = #{opts[:timeout] || 2592000}")

  # we handle reconnecting (and reattaching the new fd to EM)
  conn.reconnect = false

  # By default, MySQL 'where id is null' selects the last inserted id
  # Turn this off. http://dev.rubyonrails.org/ticket/6778
  conn.query("set SQL_AUTO_IS_NULL=0")

  # get results for queries
  conn.query_with_result = true

  conn
rescue Mysql::Error => e
  if cb = opts[:on_error]
    cb.call(e)
    nil
  else
    raise e
  end
end

.all(query, type = nil, &blk) ⇒ Object



281
282
283
284
285
286
287
288
289
# File 'lib/mysql_warmer/em/mysql.rb', line 281

def self.all query, type = nil, &blk
  responses = 0
  connection_pool.each do |c|
    c.execute(query, type) do
      responses += 1
      blk.call if blk and responses == @connection_pool.size
    end
  end
end

.connect(opts) ⇒ Object



188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/mysql_warmer/em/mysql.rb', line 188

def self.connect opts
  puts EM.respond_to?(:watch)
  unless EM.respond_to?(:watch) and Mysql.method_defined?(:socket)
    raise RuntimeError, 'mysqlplus and EM.watch are required for EventedMysql'
  end

  if conn = _connect(opts)
    EM.watch conn.socket, self, conn, opts
  else
    EM.add_timer(5){ connect opts }
  end
end

.connection_poolObject



291
292
293
294
295
296
297
298
# File 'lib/mysql_warmer/em/mysql.rb', line 291

def self.connection_pool
  @connection_pool ||= (1..settings[:connections]).map{ EventedMysql.connect(settings) }
  # p ['connpool', settings[:connections], @connection_pool.size]
  # (1..(settings[:connections]-@connection_pool.size)).each do
  #   @connection_pool << EventedMysql.connect(settings)
  # end unless settings[:connections] == @connection_pool.size
  # @connection_pool
end

.execute(query, type = nil, cblk = nil, eblk = nil, &blk) ⇒ Object



263
264
265
266
267
268
269
270
271
# File 'lib/mysql_warmer/em/mysql.rb', line 263

def self.execute query, type = nil, cblk = nil, eblk = nil, &blk
  unless nil#connection = connection_pool.find{|c| not c.processing and c.connected }
    @n ||= 0
    connection = connection_pool[@n]
    @n = 0 if (@n+=1) >= connection_pool.size
  end

  connection.execute(query, type, cblk, eblk, &blk)
end

.settingsObject



259
260
261
# File 'lib/mysql_warmer/em/mysql.rb', line 259

def self.settings
  @settings ||= { :connections => 4, :logging => false }
end

Instance Method Details

#closeObject



166
167
168
169
170
# File 'lib/mysql_warmer/em/mysql.rb', line 166

def close
  @connected = false
  fd = detach
  log 'detached fd', fd
end

#execute(sql, response = nil, cblk = nil, eblk = nil, &blk) ⇒ Object



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
# File 'lib/mysql_warmer/em/mysql.rb', line 129

def execute sql, response = nil, cblk = nil, eblk = nil, &blk
  cblk ||= blk

  begin
    unless @processing or !@connected
      # begin
      #   log 'mysql ping', @mysql.ping
      #   # log 'mysql stat', @mysql.stat
      #   # log 'mysql errno', @mysql.errno
      # rescue
      #   log 'mysql ping failed'
      #   @@queue << [response, sql, blk]
      #   return close
      # end

      @processing = true

      log 'mysql sending', sql
      @mysql.send_query(sql)
    else
      @@queue << [response, sql, cblk, eblk]
      return
    end
  rescue Mysql::Error => e
    log 'mysql error', e.message
    if DisconnectErrors.include? e.message
      @@queue << [response, sql, cblk, eblk]
      return close
    else
      raise e
    end
  end

  log 'queuing', response, sql
  @current = [Time.now, response, sql, cblk, eblk]
end

#notify_readableObject



42
43
44
45
46
47
48
49
50
51
52
53
54
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
91
92
93
94
95
96
97
98
99
# File 'lib/mysql_warmer/em/mysql.rb', line 42

def notify_readable
  log 'readable'
  if item = @current
    @current = nil
    start, response, sql, cblk, eblk = item
    log 'mysql response', Time.now-start, sql
    arg = case response
          when :raw
            result = @mysql.get_result
            @mysql.instance_variable_set('@cur_result', result)
            @mysql
          when :select
            ret = []
            result = @mysql.get_result
            result.each_hash{|h| ret << h }
            log 'mysql result', ret
            ret
          when :update
            result = @mysql.get_result
            @mysql.affected_rows
          when :insert
            result = @mysql.get_result
            @mysql.insert_id
          else
            result = @mysql.get_result
            log 'got a result??', result if result
            nil
          end

    @processing = false
    # result.free if result.is_a? Mysql::Result
    next_query
    cblk.call(arg) if cblk
  else
    log 'readable, but nothing queued?! probably an ERROR state'
    return close
  end
rescue Mysql::Error => e
  log 'mysql error', e.message
  if e.message =~ /Deadlock/
    @@queue << [response, sql, cblk, eblk]
    @processing = false
    next_query
  elsif DisconnectErrors.include? e.message
    @@queue << [response, sql, cblk, eblk]
    return close
  elsif cb = (eblk || @opts[:on_error])
    cb.call(e)
    @processing = false
    next_query
  else
    raise e
  end
  # ensure
  #   res.free if res.is_a? Mysql::Result
  #   @processing = false
  #   next_query
end

#unbindObject



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
# File 'lib/mysql_warmer/em/mysql.rb', line 101

def unbind
  log 'mysql disconnect', $!
  # cp = EventedMysql.instance_variable_get('@connection_pool') and cp.delete(self)
  @connected = false

  # XXX wait for the next tick until the current fd is removed completely from the reactor
  #
  # XXX in certain cases the new FD# (@mysql.socket) is the same as the old, since FDs are re-used
  # XXX without next_tick in these cases, unbind will get fired on the newly attached signature as well
  #
  # XXX do _NOT_ use EM.next_tick here. if a bunch of sockets disconnect at the same time, we want
  # XXX reconnects to happen after all the unbinds have been processed
  EM.add_timer(0) do
    log 'mysql reconnecting'
    @processing = false
    @mysql = EventedMysql._connect @opts
    @fd = @mysql.socket

    @signature = EM.attach_fd @mysql.socket, true
    EM.set_notify_readable @signature, true
    log 'mysql connected'
    EM.instance_variable_get('@conns')[@signature] = self
    @connected = true
    # make_socket_blocking
    next_query
  end
end