Class: EventedMysql

Inherits:
EM::Connection
  • Object
show all
Defined in:
lib/em/mysql.rb,
lib/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.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/em/mysql.rb', line 15

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.



29
30
31
# File 'lib/em/mysql.rb', line 29

def connected
  @connected
end

#optsObject (readonly) Also known as: settings

Returns the value of attribute opts.



29
30
31
# File 'lib/em/mysql.rb', line 29

def opts
  @opts
end

#processingObject (readonly)

Returns the value of attribute processing.



29
30
31
# File 'lib/em/mysql.rb', line 29

def processing
  @processing
end

Class Method Details

._connect(opts) ⇒ Object

stolen from sequel



199
200
201
202
203
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
# File 'lib/em/mysql.rb', line 199

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



276
277
278
279
280
281
282
283
284
# File 'lib/em/mysql.rb', line 276

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



184
185
186
187
188
189
190
191
192
193
194
# File 'lib/em/mysql.rb', line 184

def self.connect opts
  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



286
287
288
289
290
291
292
293
# File 'lib/em/mysql.rb', line 286

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



258
259
260
261
262
263
264
265
266
# File 'lib/em/mysql.rb', line 258

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

.reset!Object



295
296
297
298
299
300
# File 'lib/em/mysql.rb', line 295

def self.reset!
  @connection_pool.each do |c|
    c.close
  end
  @connection_pool = nil
end

.settingsObject



254
255
256
# File 'lib/em/mysql.rb', line 254

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

Instance Method Details

#closeObject



162
163
164
165
166
# File 'lib/em/mysql.rb', line 162

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

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



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

def execute sql, response = nil, cblk = nil, eblk = nil, retries = 0, &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, retries]
      return
    end
  rescue Mysql::Error => e
    log 'mysql error', e.message
    if DisconnectErrors.include? e.message
      @@queue << [response, sql, cblk, eblk, retries]
      return close
    else
      raise e
    end
  end

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

#notify_readableObject



38
39
40
41
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
# File 'lib/em/mysql.rb', line 38

def notify_readable
  log 'readable'
  if item = @current
    @current = nil
    start, response, sql, cblk, eblk, retries = 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/ and retries < MAX_RETRIES_ON_DEADLOCKS
    @@queue << [response, sql, cblk, eblk, retries + 1]
    @processing = false
    next_query
  elsif DisconnectErrors.include? e.message
    @@queue << [response, sql, cblk, eblk, retries + 1]
    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



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/em/mysql.rb', line 97

def unbind
  log 'mysql disconnect', $!, *($! ? $!.backtrace[0..5] : [])
  # 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