Class: PerfectQueue::Backend::RDBCompatBackend

Inherits:
Object
  • Object
show all
Includes:
PerfectQueue::BackendHelper
Defined in:
lib/perfectqueue/backend/rdb_compat.rb

Defined Under Namespace

Classes: Token

Constant Summary collapse

DELETE_OFFSET =

timeout model

0 —- now-1Bs —- retention —|—– now – alive ——- FUTURE

~~~~~~~^  to be deleted ^      |~~~^~~~       ^ running or in-queue
 DELETE          13_0000_0000->|   to be acquired

NOTE: this architecture introduces Year 2042 problem.

10_0000_0000
EVENT_HORIZON =

2011-03-13 07:06:40 UTC

13_0000_0000
KEEPALIVE =
10
MAX_RETRY =
10
LOCK_WAIT_TIMEOUT =
60
DEFAULT_DELETE_INTERVAL =
20

Instance Attribute Summary collapse

Attributes included from PerfectQueue::BackendHelper

#client

Instance Method Summary collapse

Methods included from PerfectQueue::BackendHelper

#close

Constructor Details

#initialize(client, config) ⇒ RDBCompatBackend

Returns a new instance of RDBCompatBackend.



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
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
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 39

def initialize(client, config)
  super

  @pq_connect_timeout = config.fetch(:pq_connect_timeout, 20)
  url = config[:url]
  @table = config[:table]
  unless @table
    raise ConfigError, ":table option is required"
  end

  if /\Amysql2:/i =~ url
    options = {max_connections: 1, sslca: config[:sslca]}
    options[:connect_timeout] = config.fetch(:connect_timeout, 3)
    @db = Sequel.connect(url, options)
    if config.fetch(:use_connection_pooling, nil) != nil
      @use_connection_pooling = !!config[:use_connection_pooling]
    else
      @use_connection_pooling = !!config[:sslca]
    end
    @table_lock = lambda {
      locked = nil
      loop do
        @db.fetch("SELECT GET_LOCK('#{@table}', #{LOCK_WAIT_TIMEOUT}) locked") do |row|
          locked = true if row[:locked] == 1
        end
        break if locked
      end
    }
    @table_unlock = lambda {
      @db.run("DO RELEASE_LOCK('#{@table}')")
    }
  else
    raise ConfigError, "only 'mysql' is supported"
  end

  @last_time = Time.now.to_i
  @mutex = Mutex.new

  connect {
    # connection test
  }

  # MySQL's CONNECTION_ID() is a 64bit unsigned integer from the
  # server's internal thread ID counter. It is unique while the MySQL
  # server is running.
  # https://bugs.mysql.com/bug.php?id=19806
  #
  # An acquired task is marked with next_timeout and CONNECTION_ID().
  # Therefore while alive_time is not changed and we don't restart
  # the server in 1 second, they won't conflict.
  if config[:disable_resource_limit]
    @update_sql = "UPDATE `\#{@table}`\n  JOIN (\n  SELECT id\n    FROM `\#{@table}` FORCE INDEX (`index_\#{@table}_on_timeout`)\n   WHERE \#{EVENT_HORIZON} < timeout AND timeout <= :now\n   ORDER BY timeout ASC\nLIMIT :max_acquire) AS t1 USING(id)\n   SET timeout=:next_timeout, owner=CONNECTION_ID()\n"
    @sql = "SELECT id, timeout, data, created_at, resource\n  FROM `\#{@table}`\n WHERE timeout = ? AND owner = CONNECTION_ID()\n"
  else
    @update_sql = "UPDATE `\#{@table}`\n  JOIN (\n    SELECT id, IFNULL(max_running, 1) / (IFNULL(running, 0) + 1) AS weight\n    FROM `\#{@table}`\n    LEFT JOIN (\nSELECT resource, COUNT(1) AS running\nFROM `\#{@table}` AS t1\nWHERE timeout > :now AND resource IS NOT NULL\nGROUP BY resource\n    ) AS t2 USING(resource)\n    WHERE \#{EVENT_HORIZON} < timeout AND timeout <= :now AND IFNULL(max_running - running, 1) > 0\n    ORDER BY weight DESC, timeout ASC\n    LIMIT :max_acquire\n  ) AS t3 USING (id)\nSET timeout = :next_timeout, owner = CONNECTION_ID()\n"
    @sql = "SELECT id, timeout, data, created_at, resource, max_running\n  FROM `\#{@table}`\n WHERE timeout = ? AND owner = CONNECTION_ID()\n"
  end

  @cleanup_interval = config[:cleanup_interval] || DEFAULT_DELETE_INTERVAL
  # If cleanup_interval > max_request_per_child / max_acquire,
  # some processes won't run DELETE query.
  # (it's not an issue when there are enough workers)
  @cleanup_interval_count = @cleanup_interval > 0 ? rand(@cleanup_interval) : 0
end

Instance Attribute Details

#dbObject (readonly)

Returns the value of attribute db.



137
138
139
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 137

def db
  @db
end

Instance Method Details

#acquire(alive_time, max_acquire, options) ⇒ Object

> [AcquiredTask]



240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 240

def acquire(alive_time, max_acquire, options)
  now = (options[:now] || Time.now).to_i
  next_timeout = now + alive_time
  tasks = nil
  t0 = nil

  if @cleanup_interval_count <= 0
    connect {
      t0=Process.clock_gettime(Process::CLOCK_MONOTONIC)
      @db["DELETE FROM `#{@table}` WHERE timeout <= ?", now-DELETE_OFFSET].delete
      @cleanup_interval_count = @cleanup_interval
      STDERR.puts"PQ:delete from #{@table}:%6f sec" % [Process.clock_gettime(Process::CLOCK_MONOTONIC)-t0]
    }
  end

  connect_locked {
    t0=Process.clock_gettime(Process::CLOCK_MONOTONIC)
    n = @db[@update_sql, next_timeout: next_timeout, now: now, max_acquire: max_acquire].update
    if n <= 0
      return nil
    end
    @table_unlock.call

    tasks = []
    @db.fetch(@sql, next_timeout) {|row|
      attributes = create_attributes(nil, row)
      task_token = Token.new(row[:id])
      task = AcquiredTask.new(@client, row[:id], attributes, task_token)
      tasks.push task
    }
    @cleanup_interval_count -= 1

    return tasks
  }
ensure
  STDERR.puts "PQ:acquire from #{@table}:%6f sec (%d tasks)" % [Process.clock_gettime(Process::CLOCK_MONOTONIC)-t0,tasks.size] if tasks
end

#compress_data(data, compression) ⇒ Object



198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 198

def compress_data(data, compression)
  if compression == 'gzip'
    io = StringIO.new
    io.set_encoding(Encoding::ASCII_8BIT)
    gz = Zlib::GzipWriter.new(io)
    begin
      gz.write(data)
    ensure
      gz.close
    end
    data = io.string
    data = Sequel::SQL::Blob.new(data)
  end
  data
end

#finish(task_token, retention_time, options) ⇒ Object

> nil



283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 283

def finish(task_token, retention_time, options)
  now = (options[:now] || Time.now).to_i
  delete_timeout = now - DELETE_OFFSET + retention_time
  key = task_token.key

  connect {
    n = @db["UPDATE `#{@table}` SET timeout=?, created_at=NULL, resource=NULL WHERE id=? AND created_at IS NOT NULL", delete_timeout, key].update
    if n <= 0
      raise IdempotentAlreadyFinishedError, "task key=#{key} does not exist or already finished."
    end
  }
  nil
end

#force_finish(key, retention_time, options) ⇒ Object



278
279
280
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 278

def force_finish(key, retention_time, options)
  finish(Token.new(key), retention_time, options)
end

#get_task_metadata(key, options) ⇒ Object

> TaskStatus



167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 167

def (key, options)
  now = (options[:now] || Time.now).to_i

  connect {
    row = @db.fetch("SELECT timeout, data, created_at, resource, max_running FROM `#{@table}` WHERE id=? LIMIT 1", key).first
    unless row
      raise NotFoundError, "task key=#{key} does no exist"
    end
    attributes = create_attributes(now, row)
    return .new(@client, key, attributes)
  }
end

#heartbeat(task_token, alive_time, options) ⇒ Object

> nil



298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 298

def heartbeat(task_token, alive_time, options)
  now = (options[:now] || Time.now).to_i
  next_timeout = now + alive_time
  key = task_token.key
  data = options[:data]

  sql = "UPDATE `#{@table}` SET timeout=?"
  params = [sql, next_timeout]
  if data
    sql << ", data=?"
    params << compress_data(data.to_json, options[:compression])
  end
  sql << " WHERE id=? AND created_at IS NOT NULL"
  params << key

  connect {
    n = @db[*params].update
    if n <= 0
      row = @db.fetch("SELECT id, timeout, created_at FROM `#{@table}` WHERE id=? LIMIT 1", key).first
      if row == nil
        raise PreemptedError, "task key=#{key} does not exist or preempted."
      elsif row[:created_at] == nil
        raise PreemptedError, "task key=#{key} preempted."
      else # row[:timeout] == next_timeout
        # ok
      end
    end
  }
  nil
end

#init_database(options) ⇒ Object



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 144

def init_database(options)
  sql = []
  sql << "DROP TABLE IF EXISTS `#{@table}`" if options[:force]
  sql << "    CREATE TABLE IF NOT EXISTS `\#{@table}` (\n      id VARCHAR(255) NOT NULL,\n      timeout INT NOT NULL,\n      data LONGBLOB NOT NULL,\n      created_at INT,\n      resource VARCHAR(255),\n      max_running INT,\n      /* CONNECTION_ID() can be 64bit: https://bugs.mysql.com/bug.php?id=19806 */\n      owner BIGINT(21) UNSIGNED NOT NULL DEFAULT 0,\n      PRIMARY KEY (id)\n    )\n    SQL\n  sql << \"CREATE INDEX `index_\#{@table}_on_timeout` ON `\#{@table}` (`timeout`)\"\n  connect {\n    sql.each(&@db.method(:run))\n  }\nend\n"

#list(options, &block) ⇒ Object

yield [TaskWithMetadata]



186
187
188
189
190
191
192
193
194
195
196
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 186

def list(options, &block)
  now = (options[:now] || Time.now).to_i

  connect {
    @db.fetch("SELECT id, timeout, data, created_at, resource, max_running FROM `#{@table}` ORDER BY timeout ASC") {|row|
      attributes = create_attributes(now, row)
      task = .new(@client, row[:id], attributes)
      yield task
    }
  }
end

#preempt(key, alive_time, options) ⇒ Object

> AcquiredTask

Raises:



181
182
183
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 181

def preempt(key, alive_time, options)
  raise NotSupportedError.new("preempt is not supported by rdb_compat backend")
end

#release(task_token, alive_time, options) ⇒ Object



329
330
331
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 329

def release(task_token, alive_time, options)
  heartbeat(task_token, alive_time, options)
end

#submit(key, type, data, options) ⇒ Object

> Task



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 215

def submit(key, type, data, options)
  now = (options[:now] || Time.now).to_i
  now = 1 if now < 1  # 0 means cancel requested
  run_at = (options[:run_at] || now).to_i
  user = options[:user]
  user = user.to_s if user
  max_running = options[:max_running]
  data = data ? data.dup : {}
  data['type'] = type
  d = compress_data(data.to_json, options[:compression])

  connect {
    begin
      @db[
        "INSERT INTO `#{@table}` (id, timeout, data, created_at, resource, max_running) VALUES (?, ?, ?, ?, ?, ?)",
        key, run_at, d, now, user, max_running
      ].insert
      return Task.new(@client, key)
    rescue Sequel::UniqueConstraintViolation
      raise IdempotentAlreadyExistsError, "task key=#{key} already exists"
    end
  }
end