Class: EventQ::RabbitMq::QueueWorker

Inherits:
Object
  • Object
show all
Includes:
WorkerId
Defined in:
lib/eventq_rabbitmq/rabbitmq_queue_worker.rb,
lib/eventq_rabbitmq/jruby/rabbitmq_queue_worker.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeQueueWorker

Returns a new instance of QueueWorker.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker.rb', line 8

def initialize
  @threads = []
  @forks = []
  @is_running = false

  @retry_exceeded_block = nil
  @on_retry_block = nil
  @on_error_block = nil
  @hash_helper = HashKit::Helper.new
  @serialization_provider_manager = EventQ::SerializationProviders::Manager.new
  @signature_provider_manager = EventQ::SignatureProviders::Manager.new
  @last_gc_flush = Time.now
  @gc_flush_interval = 10
end

Instance Attribute Details

#is_runningObject

Returns the value of attribute is_running.



6
7
8
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker.rb', line 6

def is_running
  @is_running
end

Instance Method Details

#call_on_error_block(error:, message: nil) ⇒ Object



137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker.rb', line 137

def call_on_error_block(error:, message: nil)
  if @on_error_block
    EventQ.logger.debug { "[#{self.class}] - Executing on_error block." }
    begin
      @on_error_block.call(error, message)
    rescue => e
      EventQ.logger.error("[#{self.class}] - An error occurred executing the on_error block. Error: #{e}")
    end
  else
    EventQ.logger.debug { "[#{self.class}] - No on_error block specified to execute." }
  end
end

#call_on_retry_block(message) ⇒ Object



250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker.rb', line 250

def call_on_retry_block(message)
  if @on_retry_block
    EventQ.logger.debug { "[#{self.class}] - Executing on_retry block." }
    begin
      @on_retry_block.call(message, abort)
    rescue => e
      EventQ.logger.error("[#{self.class}] - An error occurred executing the on_retry block. Error: #{e}")
    end
  else
    EventQ.logger.debug { "[#{self.class}] - No on_retry block specified." }
  end
end

#call_on_retry_exceeded_block(message) ⇒ Object



237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker.rb', line 237

def call_on_retry_exceeded_block(message)
  if @retry_exceeded_block != nil
    EventQ.logger.debug { "[#{self.class}] - Executing on_retry_exceeded block." }
    begin
      @retry_exceeded_block.call(message)
    rescue => e
      EventQ.logger.error("[#{self.class}] - An error occurred executing the on_retry_exceeded block. Error: #{e}")
    end
  else
    EventQ.logger.debug { "[#{self.class}] - No on_retry_exceeded block specified." }
  end
end

#configure(queue, options = {}) ⇒ Object



306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker.rb', line 306

def configure(queue, options = {})

  @queue = queue

  #default thread count
  @thread_count = 4
  if options.key?(:thread_count)
    @thread_count = options[:thread_count]
  end

  #default sleep time in seconds
  @sleep = 15
  if options.key?(:sleep)
    @sleep = options[:sleep]
  end

  @fork_count = 1
  if options.key?(:fork_count)
    @fork_count = options[:fork_count]
  end

  @gc_flush_interval = 10
  if options.key?(:gc_flush_interval)
    @gc_flush_interval = options[:gc_flush_interval]
  end

  EventQ.logger.info("[#{self.class}] - Configuring. Process Count: #{@fork_count} | Thread Count: #{@thread_count} | Interval Sleep: #{@sleep}.")

  return true

end

#deserialize_message(payload) ⇒ Object



227
228
229
230
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker.rb', line 227

def deserialize_message(payload)
  provider = @serialization_provider_manager.get_provider(EventQ::Configuration.serialization_provider)
  return provider.deserialize(payload)
end

#gc_flushObject



150
151
152
153
154
155
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker.rb', line 150

def gc_flush
  if Time.now - last_gc_flush > @gc_flush_interval
    GC.start
    @last_gc_flush = Time.now
  end
end

#last_gc_flushObject



157
158
159
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker.rb', line 157

def last_gc_flush
  @last_gc_flush
end

#on_error(&block) ⇒ Object



218
219
220
221
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker.rb', line 218

def on_error(&block)
  @on_error_block = block
  return nil
end

#on_retry(&block) ⇒ Object



213
214
215
216
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker.rb', line 213

def on_retry(&block)
  @on_retry_block = block
  return nil
end

#on_retry_exceeded(&block) ⇒ Object



208
209
210
211
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker.rb', line 208

def on_retry_exceeded(&block)
  @retry_exceeded_block = block
  return nil
end

#reject_message(channel, message, delivery_tag, retry_exchange, queue, abort) ⇒ Object



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker.rb', line 263

def reject_message(channel, message, delivery_tag, retry_exchange, queue, abort)

  EventQ.logger.info("[#{self.class}] - Message rejected removing from queue.")
  #reject the message to remove from queue
  channel.reject(delivery_tag, false)

  #check if the message retry limit has been exceeded
  if message.retry_attempts >= queue.max_retry_attempts

    EventQ.logger.info("[#{self.class}] - Message retry attempt limit exceeded. Msg: #{serialize_message(message)}")

    call_on_retry_exceeded_block(message)

  #check if the message is allowed to be retried
  elsif queue.allow_retry

    EventQ.logger.debug { "[#{self.class}] - Incrementing retry attempts count." }
    message.retry_attempts += 1

    if queue.allow_retry_back_off == true
      EventQ.logger.debug { "[#{self.class}] - Calculating message back off retry delay. Attempts: #{message.retry_attempts} * Retry Delay: #{queue.retry_delay}" }
      message_ttl = message.retry_attempts * queue.retry_delay
      if (message.retry_attempts * queue.retry_delay) > queue.max_retry_delay
        EventQ.logger.debug { "[#{self.class}] - Max message back off retry delay reached." }
        message_ttl = queue.max_retry_delay
      end
    else
      EventQ.logger.debug { "[#{self.class}] - Setting fixed retry delay for message." }
      message_ttl = queue.retry_delay
    end

    EventQ.logger.debug { "[#{self.class}] - Sending message for retry. Message TTL: #{message_ttl}" }
    retry_exchange.publish(serialize_message(message), :expiration => message_ttl)
    EventQ.logger.debug { "[#{self.class}] - Published message to retry exchange." }

    call_on_retry_block(message)

  end

  return true

end

#running?Boolean

Returns:

  • (Boolean)


223
224
225
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker.rb', line 223

def running?
  return @is_running
end

#serialize_message(msg) ⇒ Object



232
233
234
235
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker.rb', line 232

def serialize_message(msg)
  provider = @serialization_provider_manager.get_provider(EventQ::Configuration.serialization_provider)
  return provider.serialize(msg)
end

#start(queue, options = {}, &block) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker.rb', line 23

def start(queue, options = {}, &block)

  EventQ.logger.info("[#{self.class}] - Preparing to start listening for messages.")

  configure(queue, options)

  raise "[#{self.class}] - Worker is already running." if running?

  if options[:client] == nil
    raise "[#{self.class}] - :client (QueueClient) must be specified."
  end

  EventQ.logger.info("[#{self.class}] - Listening for messages.")
  EventQ.logger.debug do
    "[#{self.class} #start] - Listening for messages on queue: #{EventQ.create_queue_name(queue.name)}"
  end

  @forks = []

  if @fork_count > 1
    @fork_count.times do
      pid = fork do
        start_process(options, queue, block)
      end
      @forks.push(pid)
    end

    if options.key?(:wait) && options[:wait] == true
      @forks.each { |pid| Process.wait(pid) }
    end

  else
    start_process(options, queue, block)
  end

end

#start_process(options, queue, block) ⇒ Object



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/eventq_rabbitmq/rabbitmq_queue_worker.rb', line 60

def start_process(options, queue, block)

  @is_running = true

  %w'INT TERM'.each do |sig|
    Signal.trap(sig) {
      stop
      exit
    }
  end

  if !options.key?(:durable)
    options[:durable] = true
  end

  client = options[:client]
  manager = EventQ::RabbitMq::QueueManager.new
  manager.durable = options[:durable]
  @connection = client.get_connection

  @threads = []

  #loop through each thread count
  @thread_count.times do
    thr = Thread.new do

      #begin the queue loop for this thread
      while true do

        #check if the worker is still allowed to run and break out of thread loop if not
        unless running?
          break
        end

        has_received_message = false

        begin

          channel = @connection.create_channel

          has_received_message = thread_process_iteration(channel, manager, queue, block)

        rescue => e
          EventQ.logger.error("An unhandled error occurred. Error: #{e} | Backtrace: #{e.backtrace}")
          call_on_error_block(error: e)
        end

        if channel != nil && channel.open?
          channel.close
        end

        gc_flush

        if !has_received_message
          EventQ.logger.debug { "[#{self.class}] - No message received." }
          if @sleep > 0
            EventQ.logger.debug { "[#{self.class}] - Sleeping for #{@sleep} seconds" }
            sleep(@sleep)
          end
        end

      end

    end
    @threads.push(thr)

  end

  if options.key?(:wait) && options[:wait] == true
    @threads.each { |thr| thr.join }
    @connection.close if @connection.open?
  end

  return true

end

#stopObject



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker.rb', line 192

def stop
  EventQ.logger.info { "[#{self.class}] - Stopping..." }
  @is_running = false
  Thread.list.each do |thread|
    thread.exit unless thread == Thread.current
  end
  if @connection != nil
    begin
      @connection.close if @connection.open?
    rescue Timeout::Error
      EventQ.logger.error { 'Timeout occurred closing connection.' }
    end
  end
  return true
end

#thread_process_iteration(channel, manager, queue, block) ⇒ Object



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
# File 'lib/eventq_rabbitmq/rabbitmq_queue_worker.rb', line 161

def thread_process_iteration(channel, manager, queue, block)

  #get the queue
  q = manager.get_queue(channel, queue)
  retry_exchange = manager.get_retry_exchange(channel, queue)

  received = false

  begin
    delivery_info, payload = manager.pop_message(queue: q)

    #check that message was received
    if payload != nil
      received = true
      begin
        tag_processing_thread
        process_message(payload, queue, channel, retry_exchange, delivery_info, block)
      ensure
        untag_processing_thread
      end

    end

  rescue => e
    EventQ.logger.error("[#{self.class}] - An error occurred attempting to process a message. Error: #{e} | Backtrace: #{e.backtrace}")
    call_on_error_block(error: e)
  end

  return received
end