Class: Delayed::Backend::Es::Job

Inherits:
Object
  • Object
show all
Includes:
Base
Defined in:
lib/delayed/backend/es.rb

Constant Summary collapse

INDEX_NAME =
"delayed-jobs"
DOCUMENT_TYPE =
"job"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ Job

Returns a new instance of Job.



114
115
116
117
118
119
# File 'lib/delayed/backend/es.rb', line 114

def initialize(hash = {})
  self.attempts = 0
  self.priority = 0
  self.id = SecureRandom.hex(5)
  hash.each { |k, v| send(:"#{k}=", v) }
end

Instance Attribute Details

#attemptsObject

Returns the value of attribute attempts.



14
15
16
# File 'lib/delayed/backend/es.rb', line 14

def attempts
  @attempts
end

#failed_atObject

Returns the value of attribute failed_at.



20
21
22
# File 'lib/delayed/backend/es.rb', line 20

def failed_at
  @failed_at
end

#handlerObject

Returns the value of attribute handler.



15
16
17
# File 'lib/delayed/backend/es.rb', line 15

def handler
  @handler
end

#idObject

Returns the value of attribute id.



11
12
13
# File 'lib/delayed/backend/es.rb', line 11

def id
  @id
end

#last_errorObject

Returns the value of attribute last_error.



16
17
18
# File 'lib/delayed/backend/es.rb', line 16

def last_error
  @last_error
end

#locked_atObject

Returns the value of attribute locked_at.



18
19
20
# File 'lib/delayed/backend/es.rb', line 18

def locked_at
  @locked_at
end

#locked_byObject

Returns the value of attribute locked_by.



19
20
21
# File 'lib/delayed/backend/es.rb', line 19

def locked_by
  @locked_by
end

#priorityObject

Returns the value of attribute priority.



13
14
15
# File 'lib/delayed/backend/es.rb', line 13

def priority
  @priority
end

#queueObject

Returns the value of attribute queue.



21
22
23
# File 'lib/delayed/backend/es.rb', line 21

def queue
  @queue
end

#run_atObject

Returns the value of attribute run_at.



17
18
19
# File 'lib/delayed/backend/es.rb', line 17

def run_at
  @run_at
end

#versionObject

Returns the value of attribute version.



12
13
14
# File 'lib/delayed/backend/es.rb', line 12

def version
  @version
end

Class Method Details

.allObject

CALLING ‘ALL’ IS NEVER A GOOD IDEA MEMORY LEAKS ALWAYS BEGIN LIKE THIS!!! stub to call 10 jobs.



124
125
126
127
128
129
# File 'lib/delayed/backend/es.rb', line 124

def self.all
  search_response = get_client.search :index =>INDEX_NAME, :type => DOCUMENT_TYPE, :body => {:size => 10, :query => {match_all: {}}}
  search_response["hits"]["hits"].map{|c|
  	new(c["_source"].merge("id" => c["_id"]))
  }
end

.clear_locks!(worker_name) ⇒ Object

USES ES SCROLL API



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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/delayed/backend/es.rb', line 156

def self.clear_locks!(worker_name)
	scroll_id = nil
	execution_count = 0
	while true
		begin
 		response = nil
							# Display the initial results
							#puts "--- BATCH 0 -------------------------------------------------"
							#puts r['hits']['hits'].map { |d| d['_source']['title'] }.inspect
							if scroll_id.blank?
								response = get_client.search index: INDEX_NAME, scroll: '4m', body: {_source: false, query: {term: {locked_by: worker_name}}}
							else
								response = get_client.scroll scroll_id: scroll_id, scroll: '4m'
							end
							
							scroll_id = response['_scroll_id']

							job_ids = response['hits']['hits'].map{|c| c['_id']}
						 	
						  	break if job_ids.blank?

						  	bulk_array = []
						  	
						  	script = 
							{
								:lang => "painless",
								:params => {
									
								},
								:source => '''
									ctx._source.locked_at = null;
									ctx._source.locked_by = null;
								'''
							}

						  	job_ids.each do |jid|

bulk_array << {
	_update: {
		_index: INDEX_NAME,
		_type: DOCUMENT_TYPE,
		_id: jid,
		data: {
			script: script, 
			scripted_upsert: false,
			upsert: {}
		}
	}
}

						  	end

						  	bulk_response = get_client.bulk body: bulk_array

						  	execution_count +=1	

						  	break if execution_count > 10
					  	rescue => e
					  		puts "error clearing locks--->"
					  		puts e.to_s
					  		break
					  	end
	end
end

.countObject



131
132
133
# File 'lib/delayed/backend/es.rb', line 131

def self.count
  get_client.count index: INDEX_NAME
end

.create(attrs = {}) ⇒ Object



139
140
141
142
143
# File 'lib/delayed/backend/es.rb', line 139

def self.create(attrs = {})
  new(attrs).tap do |o|
    o.save
  end
end

.create!(*args) ⇒ Object



145
146
147
# File 'lib/delayed/backend/es.rb', line 145

def self.create!(*args)
  create(*args)
end

.create_indexObject



89
90
91
92
93
94
95
# File 'lib/delayed/backend/es.rb', line 89

def self.create_index
	response = get_client.indices.create :index => INDEX_NAME, :body => {
		mappings: {DOCUMENT_TYPE => { :properties =>  mappings}}
	}
	puts "Created delayed job index with response."
	puts response.to_s
end

.create_indexesObject



109
110
111
112
# File 'lib/delayed/backend/es.rb', line 109

def self.create_indexes
	delete_index
	create_index
end

.db_time_nowObject



421
422
423
# File 'lib/delayed/backend/es.rb', line 421

def self.db_time_now
  Time.current
end

.delete_allObject



135
136
137
# File 'lib/delayed/backend/es.rb', line 135

def self.delete_all
  create_indexes
end

.delete_indexObject



97
98
99
100
101
102
103
104
105
106
107
# File 'lib/delayed/backend/es.rb', line 97

def self.delete_index
	if Elasticsearch::Persistence.client.indices.exists? index: INDEX_NAME
		
		puts "delayed job index exists."
		response = get_client.indices.delete :index => INDEX_NAME
		puts "delete response:"
		puts response.to_s
	else
		puts "delayed job index does not exist."
	end
end

.find_available(worker_name, limit = 5, max_run_time = Worker.max_run_time) ⇒ Object

Find a few candidate jobs to run (in case some immediately get locked by others).



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
256
257
258
259
260
261
262
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
305
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
# File 'lib/delayed/backend/es.rb', line 222

def self.find_available(worker_name, limit = 5, max_run_time = Worker.max_run_time) 
	#puts "max run time is:"
	#puts Worker.max_run_time
	right_now = Time.now
	#####################################################
					##
					##
					## THE BASE QUERY
					## translated into human terms
					## any job where
					## 1. run_at is less than the current time
					## AND
					## 2. locked_by : current_worker OR locked_At : nil OR locked_at < (time_now - max_run_time)
					## AND
					## 3. failed_at : nil
					## AND
					## OPTIONAL ->
					## priority queries
					## OPTIONAL ->
					## queue name.
					##
					##
					#####################################################

					query = {
						bool: {
							must: [
								{
									range: {
run_at: {
	lte: right_now.strftime("%Y-%m-%d %H:%M:%S")
}
									}
								},
								{
									bool: {
should: [
	{
		term: {
			locked_by: Worker.name
		}
	},
	{
		bool: {
			must_not: [
				{
					exists: {
						field: "locked_at"
					}
				}
			]
		}
	},
	{
		range: {
			locked_at: {
				lte: (right_now - max_run_time).strftime("%Y-%m-%d %H:%M:%S")
			}
		}
	}
]
									}
								}
							],
							must_not: [
								{
									exists: {
field: "failed_at"
									}
								}
							]
						}
					}

					################################################
					##
					##
					## ADD PRIORITY CLAUSES
					##
					##
					################################################
					if Worker.min_priority
						query[:bool][:must] << {
							range: {
								priority: {
									gte: Worker.min_priority.to_i
								}
							}
						}
					end

					if Worker.max_priority
						query[:bool][:must] << {
							range: {
								priority: {
									lte: Worker.max_priority.to_i
								}
							}
						}
					end


					##############################################
					##
					##
					## QUEUES IF SPECIFIED.
					##
					##
					##############################################
					if Worker.queues.any?
						query[:bool][:must] << {
							terms: {
								queue: Worker.queues
							}
						}
					end


					#############################################
					##
					##
					## SORT
					##
					##
					############################################
					sort = [
						{"locked_by" => "desc"},
						{"priority" => "asc"},
						{"run_at" => "asc"}
					]

					##puts "find available jobs query is:"
					##puts JSON.pretty_generate(query)

					search_response = get_client.search :index => INDEX_NAME, :type => DOCUMENT_TYPE,
						:body => {
							version: true,
							size: limit,
							sort: sort,
							query: query
						}
					

					puts "search_response is"
					puts search_response["hits"]["hits"]
					## it would return the first hit.
					search_response["hits"]["hits"].map{|c|
						k = new(c["_source"])
						k.id = c["_id"]
						k.version = c["_version"]
						k
					}

end

.get_clientObject



37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/delayed/backend/es.rb', line 37

def self.get_client
	if Elasticsearch::Persistence.client
		puts "got persistence client, using it."
		puts "its settings are/"
		puts Elasticsearch::Persistence.client
		Elasticsearch::Persistence.client
	else
		puts "----- returning the default client --------- "
		client ||= Elasticsearch::Client.new
		client
	end
end

.mappingsObject



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
# File 'lib/delayed/backend/es.rb', line 50

def self.mappings
	{
		payload_object: {
			type: 'object'
		},
		locked_at: {
			type: 'date',
			format: 'yyyy-MM-dd HH:mm:ss'
		},
		failed_at: {
			type: 'date',
			format: 'yyyy-MM-dd HH:mm:ss'
		},
		priority: {
			type: 'integer'
		},
		attempts: {
			type: 'integer'
		},
		queue: {
			type: 'keyword'
		},
		handler: {
			type: 'text',
			index: false
		},
		locked_by: {
			type: 'keyword'
		},
		last_error: {
			type: 'keyword'
		},
		run_at: {
			type: 'date',
			format: 'yyyy-MM-dd HH:mm:ss'
		}
	}
end

Instance Method Details

#destroyObject



430
431
432
433
434
# File 'lib/delayed/backend/es.rb', line 430

def destroy
  # gotta do this.
  #puts "Calling destroy"
  self.class.get_client.delete :index => INDEX_NAME, :type => DOCUMENT_TYPE, :id => self.id.to_s
end

#json_representationObject



436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
# File 'lib/delayed/backend/es.rb', line 436

def json_representation
	if self.respond_to? "as_json"
		as_json.except("payload_object").except(:payload_object)
	else
		puts "payload object is ----------->"
		puts self.payload_object
		attributes = {}
		self.class.mappings.keys.each do |attr|
			if attr.to_s == "payload_object"
				## this object has to be serialized.
				## 
			else
				attributes[attr] = self.send(attr)
			end
		end
		JSON.generate(attributes)
	end
end

#lock_exclusively!(_max_run_time, worker) ⇒ Object

Lock this job for this worker. Returns true if we have the lock, false otherwise.



379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
# File 'lib/delayed/backend/es.rb', line 379

def lock_exclusively!(_max_run_time, worker)
  #puts "called lock exclusively ------------------------>"
  
  script = 
					{
						:lang => "painless",
						:params => {
							:locked_at => self.class.db_time_now.strftime("%Y-%m-%d %H:%M:%S"),
							:locked_by => worker,
							:version => self.version
						},
						:source => '''
							if(ctx._version == params.version){
								ctx._source.locked_at = params.locked_at;
								ctx._source.locked_by = params.locked_by;
							}
							else{
								ctx.op = "none";
							}
						'''
					}

					puts "Script is"
					puts JSON.pretty_generate(script)


					#begin
					response = self.class.get_client.update(index: INDEX_NAME, type: DOCUMENT_TYPE, id: self.id.to_s, body: {
						:script => script,
						:scripted_upsert => false,
						:upsert => {}	
					})

					## if this returns no-op chec,
					puts "lock response:"
					puts response.to_s
					

					return response["result"] == "updated"
  
end

#reloadObject



472
473
474
475
476
477
478
# File 'lib/delayed/backend/es.rb', line 472

def reload
  #puts "called reload job---------------->"
  object = self.class.get_client.get :id => self.id, :index => INDEX_NAME, :type => DOCUMENT_TYPE
  k = self.class.new(object["_source"])
  k.id = object["_id"]
  k
end

#saveObject



455
456
457
458
459
460
461
462
463
464
465
466
# File 'lib/delayed/backend/es.rb', line 455

def save
  #puts "Came to save --------------->"
  self.run_at ||= Time.current.strftime("%Y-%m-%d %H:%M:%S")
  ## so here you do the actual saving.
  #Elasticsearch::Client.gateway.
  #puts "object as json -------------->"
  #puts json_representation
  save_response = self.class.get_client.index :index => INDEX_NAME, :type => DOCUMENT_TYPE, :body => json_representation, :id => self.id.to_s
  #puts "save response is: #{save_response}"
  self.class.all << self unless self.class.all.include?(self)
  true
end

#save!Object



468
469
470
# File 'lib/delayed/backend/es.rb', line 468

def save!
  save
end

#update_attributes(attrs = {}) ⇒ Object



425
426
427
428
# File 'lib/delayed/backend/es.rb', line 425

def update_attributes(attrs = {})
  attrs.each { |k, v| send(:"#{k}=", v) }
  save
end