forked from brightroll/rq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.rb
1914 lines (1625 loc) · 59.2 KB
/
queue.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
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
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
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
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
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
376
377
378
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require 'socket'
require 'json'
require 'fcntl'
require 'digest'
require 'fileutils'
require 'code/hashdir'
require 'code/adminoper'
require 'code/queueclient'
require 'code/protocol'
require 'pathname'
require 'parse-cron'
module RQ
class Worker < Struct.new(
:qc,
:name,
:status,
:child_write_pipe,
:pid,
:options
)
end
class QueueConfig < Struct.new(
:name,
:script,
:num_workers,
:exec_prefix,
:env_vars,
:coalesce_params,
:blocking_params,
:schedule
)
def to_json
{
'name' => name,
'script' => script,
'num_workers' => num_workers,
'exec_prefix' => exec_prefix,
'env_vars' => env_vars,
'coalesce_params' => coalesce_params,
'blocking_params' => blocking_params,
'schedule' => schedule.map do |s|
{
'cron' => s['cron'],
'params' => {
'param1' => s['param1'],
'param2' => s['param2'],
'param3' => s['param3'],
'param4' => s['param4'],
}
}
end
}.to_json
end
end
class Queue
include Protocol
def initialize(options, parent_pipe)
@start_time = Time.now
@last_sched = nil
# Read config
@name = options['name']
@queue_path = "queue/#{@name}"
@rq_config_path = "./config/"
@parent_pipe = parent_pipe
init_socket
@prep = [] # should be small
@que = [] # could be large
@run = [] # should be small
@completed = [] # Messages that have properly set their status and exited properly
@wait_time = 1
@status = RQ::AdminOper.new(@rq_config_path, @name)
@temp_que_dups = {}
@signal_hup_rd, @signal_hup_wr = IO.pipe
@signal_chld_rd, @signal_chld_wr = IO.pipe
Signal.trap("TERM") do
shutdown!
end
Signal.trap("CHLD") do
@signal_chld_wr.syswrite('.')
end
Signal.trap("HUP") do
@signal_hup_wr.syswrite('.')
end
unless load_rq_config
sleep 5
$log.error("Invalid main rq config for #{@name}. Exiting." )
exit! 1
end
unless load_config
sleep 5
$log.error("Invalid config for #{@name}. Exiting." )
exit! 1
end
load_messages
@status.update!
end
def self.delete(name)
queue_path = "queue/#{name}"
stat = File.stat(queue_path)
# Throw in the inode for uniqueness
new_queue_path = "queue/#{name}.deleted.#{stat.ino}"
FileUtils.mv(queue_path, new_queue_path)
end
def self.create(options, config_path=nil)
# Validate the options
config = sublimate_config(options)
# Create a directories and config
queue_path = "queue/#{config['name']}"
FileUtils.mkdir_p(queue_path)
FileUtils.mkdir_p(queue_path + '/prep')
FileUtils.mkdir_p(queue_path + '/que')
FileUtils.mkdir_p(queue_path + '/run')
RQ::HashDir.make(queue_path + '/done')
RQ::HashDir.make(queue_path + '/relayed')
FileUtils.mkdir_p(queue_path + '/err')
if config_path
old_path = Pathname.new(config_path).realpath.to_s
File.symlink(old_path, queue_path + '/config.json')
else
# Write config to dir
File.open(queue_path + '/config.json', "w") do |f|
f.write(config.to_json)
end
end
RQ::Queue.start_process(config)
end
def self.start_process(options)
# nice pipes writeup
# http://www.cim.mcgill.ca/~franco/OpSys-304-427/lecture-notes/node28.html
child_rd, parent_wr = IO.pipe
child_pid = fork do
# Restore default signal handlers from those inherited from queuemgr
Signal.trap('TERM', 'DEFAULT')
Signal.trap('CHLD', 'DEFAULT')
Signal.trap('HUP', 'DEFAULT')
$0 = $log.progname = "[rq-que] [#{options['name']}]"
begin
parent_wr.close
#child only code block
$log.debug('post fork')
q = RQ::Queue.new(options, child_rd)
# This should never return, it should Kernel.exit!
# but we may wrap this instead
$log.debug('post new')
q.run_loop
rescue Exception
$log.error("Exception!")
$log.error($!)
$log.error($!.backtrace)
raise
end
end
#parent only code block
child_rd.close
if child_pid == nil
parent_wr.close
return nil
end
worker = Worker.new
worker.qc = QueueClient.new(options['name'])
worker.name = options['name']
worker.status = 'RUNNING'
worker.child_write_pipe = parent_wr
worker.pid = child_pid
worker.options = options
# Wait up to a second for the worker to start up
20.times do
sleep 0.05
break if worker.qc.ping == 'pong' rescue false
end
worker
# If anything went wrong at all log it and return nil.
rescue Exception
$log.error("Failed to start worker #{options.inspect}: #{$!}")
nil
end
def self.validate_options(options)
err = false
if not err
if options.include?('name')
if (1..128).include?(options['name'].size)
if options['name'].class != String
resp = "json config has invalid name (not String)"
err = true
end
else
resp = "json config has invalid name (size)"
err = true
end
else
resp = 'json config is missing name field'
err = true
end
end
if not err
if options.include?('num_workers')
if not ( (1..128).include?(options['num_workers'].to_i) )
resp = "json config has invalid num_workers field (out of range 1..128)"
err = true
end
else
resp = 'json config is missing num_workers field'
err = true
end
end
if not err
if options.include?('script')
if (1..1024).include?(options['script'].size)
if options['script'].class != String
resp = "json config has invalid script (not String)"
err = true
end
else
resp = "json config has invalid script (size)"
err = true
end
else
resp = 'json config is missing script field'
err = true
end
end
[err, resp]
end
def run_queue_script!(msg)
msg_id = msg['msg_id']
basename = File.join(@queue_path, 'run', msg_id)
job_path = File.expand_path(File.join(basename, 'job'))
Dir.mkdir(job_path) unless File.exist?(job_path)
# Identify executable to run, if there is no script, go oper down
# Also, fix an old issue where we didn't deref the symlink when executing a script
# This meant that a script would see a new directory on a code deploy if that
# script lived under a symlinked path
script_path = Pathname.new(@config.script).realpath.to_s rescue @config.script
if (!File.executable?(script_path) rescue false)
$log.warn("ERROR - QUEUE SCRIPT - not there or runnable #{script_path}")
if @status.oper_status != 'SCRIPTERROR'
@status.set_oper_status('SCRIPTERROR')
$log.warn("SCRIPTERROR - DAEMON STATUS is set to SCRIPTERROR")
$log.warn("OPER STATUS is now: #{@status.oper_status}")
end
return
end
if @status.oper_status == 'SCRIPTERROR'
@status.set_oper_status('UP')
$log.info("SCRIPTERROR FIXED - DAEMON STATUS is set to UP")
$log.info("OPER STATUS is now: #{@status.oper_status}")
end
parent_rd, child_wr = IO.pipe
child_rd, parent_wr = IO.pipe
$log.debug("1 child process prep step for runnable #{script_path}")
child_pid = fork do
# Setup env
$0 = $log.progname = "[rq-msg] [#{@name}] [#{msg_id}]"
begin
#child only code block
Dir.chdir(job_path) # Chdir to child path
$log.debug("child process prep step for runnable #{script_path}")
$log.debug("post fork - parent rd pipe fd: #{parent_rd.fileno}")
$log.debug("post fork - child wr pipe fd: #{child_wr.fileno}")
$log.debug("post fork - child rd pipe fd: #{child_rd.fileno}")
$log.debug("post fork - parent wr pipe fd: #{parent_wr.fileno}")
# WE MUST DO THIS BECAUSE WE MAY GET PIPE FDs IN THE 3-4 RANGE
# THIS GIVES US HIGHER # FDs SO WE CAN SAFELY CLOSE
child_wr_fd = child_wr.fcntl(Fcntl::F_DUPFD)
child_rd_fd = child_rd.fcntl(Fcntl::F_DUPFD)
$log.debug("post fork - child_wr_fd pipe fd: #{child_wr_fd}")
$log.debug("post fork - child_rd_fd pipe fd: #{child_rd_fd}")
parent_rd.close
parent_wr.close
#... the pipe fd will get closed on exec
# child_wr
IO.for_fd(3).close rescue nil
fd = IO.for_fd(child_wr_fd).fcntl(Fcntl::F_DUPFD, 3)
$log.warn("Error duping fd for 3 - got #{fd}") unless fd == 3
IO.for_fd(child_wr_fd).close rescue nil
# child_rd
IO.for_fd(4).close rescue nil
fd = IO.for_fd(child_rd_fd).fcntl(Fcntl::F_DUPFD, 4)
$log.warn("Error duping fd for 4 - got #{fd}") unless fd == 4
IO.for_fd(child_rd_fd).close rescue nil
f = File.open(job_path + "/stdio.log", "a")
f.sync = true
pfx = "#{Process.pid} - #{Time.now} -"
f.write("\n#{pfx} RQ START - #{script_path}\n")
$stdin.close
$stdout.reopen f
$stderr.reopen f
# Ruby 2.0 sets CLOEXEC by default, turn it off explicitly
fd_3 = IO.for_fd(3)
fd_4 = IO.for_fd(4)
fd_3.fcntl(Fcntl::F_SETFD, fd_3.fcntl(Fcntl::F_GETFD, 0) & ~Fcntl::FD_CLOEXEC) rescue nil
fd_4.fcntl(Fcntl::F_SETFD, fd_4.fcntl(Fcntl::F_GETFD, 0) & ~Fcntl::FD_CLOEXEC) rescue nil
# Turn CLOEXEC explicitly on for all other likely open fds
(5..32).each do |io|
io = IO.for_fd(io) rescue nil
next unless io
io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
end
$log.debug('post FD_CLOEXEC') unless fd == 2
$log.debug("running #{script_path}")
ENV["RQ_VER"] = RQ_VER
ENV["RQ_SCRIPT"] = @config.script
ENV["RQ_REALSCRIPT"] = script_path
ENV["RQ_HOST"] = "http://#{@host}:#{@port}#{@root}"
ENV["RQ_DEST"] = gen_full_dest(msg)['dest']
ENV["RQ_DEST_QUEUE"] = gen_full_dest(msg)['queue']
ENV["RQ_MSG_ID"] = msg_id
ENV["RQ_FULL_MSG_ID"] = gen_full_msg_id(msg)
ENV["RQ_MSG_DIR"] = job_path
ENV["RQ_PIPE"] = "3" # DEPRECATED
ENV["RQ_WRITE"] = "3" # USE THESE INSTEAD
ENV["RQ_READ"] = "4"
ENV["RQ_COUNT"] = msg['count'].to_s
ENV["RQ_PARAM1"] = msg['param1'].to_s
ENV["RQ_PARAM2"] = msg['param2'].to_s
ENV["RQ_PARAM3"] = msg['param3'].to_s
ENV["RQ_PARAM4"] = msg['param4'].to_s
ENV["RQ_ORIG_MSG_ID"] = msg['orig_msg_id'].to_s
ENV["RQ_FORCE_REMOTE"] = "1" if msg['force_remote']
# Set env vars specified in queue config file
@config.env_vars.each do |varname, value|
ENV[varname] = value unless varname.match(/^RQ_/) # Don't let the config override RQ-specific env vars though
end
# unset RUBYOPT so it doesn't reinitialize the client ruby's GEM_HOME, etc.
ENV.delete("RUBYOPT")
$log.debug("set ENV now executing #{msg.inspect}")
# Setting priority to BATCH mode
Process.setpriority(Process::PRIO_PROCESS, 0, 19)
$log.debug("set ENV, now executing #{script_path}")
# bash -lc will execute the command but first re-initializing like a new login (reading .bashrc, etc.)
exec_prefix = @config.exec_prefix || "bash -lc"
exec_path = "#{exec_prefix} #{script_path}".strip
$log.debug("exec path: #{exec_path}")
exec("#{exec_path}") if RUBY_VERSION < '2.0'
exec("#{exec_path}", :close_others => false)
rescue
$log.warn($!)
$log.warn($!.backtrace)
raise
end
end
#parent only code block
child_wr.close
child_rd.close
if child_pid == nil
parent_rd.close
$log.warn("ERROR failed to run child script: queue_path, $!")
return nil
end
msg['child_pid'] = child_pid
msg['child_read_pipe'] = parent_rd
msg['child_write_pipe'] = parent_wr
write_msg_process_id(msg_id, child_pid)
end
def init_socket
# Show pid
File.unlink(@queue_path + '/queue.pid') rescue nil
File.open(@queue_path + '/queue.pid', "w") do |f|
f.write("#{Process.pid}\n")
end
# Setup IPC
File.unlink(@queue_path + '/queue.sock') rescue nil
@sock = UNIXServer.open(@queue_path + '/queue.sock')
end
def load_rq_config
begin
data = File.read(@rq_config_path + 'config.json')
js_data = JSON.parse(data)
@host = js_data['host']
@port = js_data['port']
@root = js_data.fetch('relative_root', '/').chomp('/') + '/'
true
rescue
false
end
end
def load_config
data = File.read(File.join(@queue_path, 'config.json'))
@config = self.class.sublimate_config(JSON.parse(data))
end
# There are a variety of ways we used to specify truth.
# Going forward, javascript true / false are preferred.
def self.so_truthy? fudge
!!([true, 'true', 'yes', '1', 1].include? fudge)
end
def self.sublimate_config(conf)
# TODO config validation
new_config = QueueConfig.new
new_config.name = conf['name']
new_config.script = conf['script']
new_config.num_workers = conf['num_workers'].to_i
new_config.exec_prefix = conf['exec_prefix']
if conf['env_vars'].is_a? Hash
new_config.env_vars = conf['env_vars']
else
new_config.env_vars = {}
end
if so_truthy?(conf['coalesce'])
# Convert from old style coalesce / coalesce_paramN
new_config.coalesce_params = (1..4).map{ |x| x if so_truthy?(conf["coalesce_param#{x}"]) }.compact
elsif conf['coalesce_params'].is_a? Array
new_config.coalesce_params = conf['coalesce_params'].map(&:to_i)
else
new_config.coalesce_params = []
end
if conf['blocking_params'].is_a? Array
new_config.blocking_params = conf['blocking_params'].map(&:to_i)
else
new_config.blocking_params = []
end
new_config.schedule = (conf['schedule'] || []).map do |s|
begin
{
'cron' => s['cron'],
'cron_obj' => CronParser.new(s['cron']),
'params' => {
'param1' => s['param1'],
'param2' => s['param2'],
'param3' => s['param3'],
'param4' => s['param4'],
}
}
rescue
$log.warn("Invalid cron spec: #{s['cron']}: [ #{$!} ]")
end
end.compact
new_config
end
# It is called right before check_msg
def alloc_id(msg)
# Simple time insertion system - should work since single threaded
times = 0
z = Time.now.getutc
name = z.strftime('_%Y%m%d.%H%M.%S.') + sprintf('%03d', (z.tv_usec / 1000))
prep_name = File.join(@queue_path, 'prep', name)
Dir.mkdir(prep_name)
stat = File.stat(prep_name)
new_name = z.strftime('%Y%m%d.%H%M.%S.') + sprintf('%03d.%d', (z.tv_usec / 1000), stat.ino)
File.rename(prep_name, File.join(@queue_path, 'prep', new_name))
@prep << new_name
msg['msg_id'] = new_name
rescue
times += 1
$log.warn("couldn't ALLOC ID times: #{times} [ #{$!} ]")
if times > 10
$log.warn("FAILED TO ALLOC ID")
raise
end
sleep 0.001
retry
else
msg
end
# This copies certain fields over and insures consistency in a new
# message
# It is called right after alloc_id
def check_msg(msg, input)
raise 'input missing required "dest" parameter' unless input.has_key?('dest')
msg['dest'] = input['dest']
# If orig_msg_id is set already, then use it
# otherwise we initialize it with this msg
msg['orig_msg_id'] = input['orig_msg_id'] || gen_full_msg_id(msg)
msg['count'] = (input['count'] || 0).to_i
msg['max_count'] = (input['max_count'] || 15).to_i
# Copy only these keys from input message
keys = %w(src param1 param2 param3 param4 post_run_webhook due force_remote)
keys.each do |key|
next unless input.has_key?(key)
msg[key] = input[key]
end
end
def store_msg(msg, new_state='prep')
# Write message to disk
msg['due'] ||= Time.now.to_i
clean = msg.reject { |k, v| k == 'child_read_pipe' || k == 'child_pid' || k == 'child_write_pipe' }
basename = File.join(@queue_path, new_state, msg['msg_id'])
File.open(basename + '/tmp', 'w') { |f| f.write(clean.to_json) }
File.rename(basename + '/tmp', basename + '/msg')
true
rescue
File.unlink(basename + '/tmp') rescue nil
$log.error("couldn't write message")
false
end
def que(msg, from_state = 'prep')
msg_id = msg['msg_id']
begin
# Read in full message
msg = get_message(msg, from_state)
basename = msg['path']
return false unless File.exist? basename
newname = File.join(@queue_path, 'que', msg_id)
File.rename(basename, newname)
msg['state'] = 'que'
msg['status'] = 'que'
rescue
$log.error("couldn't commit message #{msg_id}: #{$!}")
return false
end
# Put in queue
@prep.delete(msg['msg_id'])
@que.unshift(msg)
# This may execute the new message immediately
run_scheduler!
true
end
# required: dest
# options: src param1 param2 param3 param4 post_run_webhook due force_remote
def make_message(options, que=true)
msg = { }
alloc_id(msg)
check_msg(msg, options)
store_msg(msg)
que(msg) if que
msg
end
def is_duplicate?(msg1, msg2)
return false if @config.coalesce_params.empty?
@config.coalesce_params.all? do |p|
msg1["param#{p}"] == msg2["param#{p}"]
end
end
# Handle a message that does succeed
# Put all of its dups into the done state
def handle_dups_done(msg, new_state)
if msg['dups']
msg['dups'].each do |i|
h = @temp_que_dups.delete(i)
new_status = "duplicate #{gen_full_msg_id(msg)}"
write_msg_status(i, new_status, 'que')
h['status'] = new_state + " - " + new_status
h['state'] = new_state
store_msg(h, 'que')
# TODO: refactor this
basename = File.join(@queue_path, 'que', i)
RQ::HashDir.inject(basename, File.join(@queue_path, new_state), i)
end
msg['dups'] = msg['dups'].map { |i| gen_full_msg_id({'msg_id' => i}) }
end
end
# Handle a message that doesn't succeed
def handle_dups_fail(msg)
if msg['dups']
msg['dups'].each do |i|
h = @temp_que_dups.delete(i)
h.delete('dup')
@que.unshift(h)
end
msg.delete('dups')
end
end
def handle_dups(msg)
return unless @config.coalesce_params
duplicates = @que.select { |i| is_duplicate?(msg, i) }
return if duplicates.empty?
$log.info("#{msg['msg_id']} - found #{duplicates.length} dups ")
# Collect all the dups into the msg and remove from the @que
# also show parent in each dup
msg['dups'] = []
duplicates.each { |i|
msg['dups'] << i['msg_id']
@temp_que_dups[i['msg_id']] = i
r = @que.delete(i) # ordering here is important
$log.info("#{r['msg_id']} - removed from @que as dup")
i['dup'] = gen_full_msg_id(msg)
}
end
# This is similar to check_msg, but it works with a message that is already
# in the system
def copy_and_clean_msg(input, new_dest = nil)
msg = {}
msg['dest'] = new_dest || input['dest']
# If orig_msg_id is set already, then use it
# otherwise we initialize it with this msg
msg['orig_msg_id'] = input['orig_msg_id']
msg['count'] = 0
msg['max_count'] = (input['max_count'] || 15).to_i
# Copy only these keys from input message
keys = %w(src param1 param2 param3 param4 post_run_webhook due)
keys.each do |key|
next unless input.has_key?(key)
msg[key] = input[key]
end
return msg
end
def run_job(msg, from_state = 'que')
msg_id = msg['msg_id']
begin
basename = File.join(@queue_path, from_state, msg_id)
newname = File.join(@queue_path, 'run', msg_id)
File.rename(basename, newname)
rescue
$log.warn("couldn't run message #{msg_id} [ #{$!} ]")
# Remove the job from the queue. This may leave things in que state that
# will be attempted again after a restart, but avoids the job jamming
# the top of the queue. TODO: move the job to the err queue?
@que.delete(msg)
return false
end
# Put in run queue
@que.delete(msg)
@run.unshift(msg)
handle_dups(msg)
run_queue_script!(msg)
end
def msg_state_prep?(msg)
msg_id = msg['msg_id']
return false unless @prep.include?(msg_id)
basename = File.join(@queue_path, 'prep', msg_id)
unless File.exist?(basename)
$log.warn("WARNING - serious queue inconsistency #{msg_id}")
$log.warn("WARNING - #{msg_id} in memory but not on disk")
return false
end
true
end
def msg_state(msg, options={:consistency => true})
msg_id = msg['msg_id']
state = \
if @prep.include?(msg_id)
'prep'
elsif not Dir.glob(File.join(@queue_path, 'que', msg_id)).empty?
'que'
elsif @run.find { |o| o['msg_id'] == msg_id }
'run'
elsif RQ::HashDir.exist(@queue_path, 'done', msg_id)
basename = RQ::HashDir.path_for(@queue_path, 'done', msg_id)
'done'
elsif RQ::HashDir.exist(@queue_path, 'relayed', msg_id)
basename = RQ::HashDir.path_for(@queue_path, 'relayed', msg_id)
'relayed'
elsif not Dir.glob(File.join(@queue_path, 'err', msg_id)).empty?
'err'
end
return false unless state
basename ||= File.join(@queue_path, state, msg_id)
if options[:consistency]
unless File.exist?(basename)
$log.warn("WARNING - serious queue inconsistency #{msg_id}")
$log.warn("WARNING - #{msg_id} in memory but not on disk")
return false
end
end
state
end
def delete_msg!(msg)
state = msg_state(msg)
return nil unless state
return nil unless msg['msg_id']
basename = File.join(@queue_path, state, msg['msg_id'])
# N.B. do not delete a message in 'run' state,
# first kill the process and force the message to err state,
# then delete it from err state.
case state
when 'prep'
FileUtils.rm_rf(basename)
@prep.delete(msg['msg_id'])
when 'que'
FileUtils.rm_rf(basename)
@que.delete_if { |o| o['msg_id'] == msg['msg_id'] }
when 'done'
FileUtils.rm_rf(basename)
when 'err'
FileUtils.rm_rf(basename)
end
end
def clone_msg(msg)
state = msg_state(msg)
return nil unless state
return nil unless ['err', 'relayed', 'done'].include? state
old_msg = get_message(msg, state)
old_basename = old_msg['path']
new_msg = { }
alloc_id(new_msg)
check_msg(new_msg, old_msg)
# check_msg copies only required fields, but still copies count
# so we delete that as well
new_msg['count'] = 0
new_msg['cloned_from'] = old_msg['msg_id']
# Now check for, and copy attachments
# Assumes that original message guaranteed attachment integrity
new_basename = File.join(@queue_path, 'prep', new_msg['msg_id'])
if File.directory?(old_basename + '/attach/')
ents = Dir.entries(old_basename + '/attach/').reject {|i| i.start_with?('.') }
if not ents.empty?
# simple check for attachment dir
old_attach_path = old_basename + '/attach/'
new_attach_path = new_basename + '/attach/'
Dir.mkdir(new_attach_path)
ents.each do |ent|
# Now clone attachments by hard_linking to them in new message
new_path = new_attach_path + ent
old_path = old_attach_path + ent
File.link(old_path, new_path)
end
end
end
store_msg(new_msg)
que(new_msg)
msg_id = gen_full_msg_id(new_msg)
rescue Exception => e
["fail", e.message].to_json
else
msg_id
end
def get_message(params, state,
options={ :read_message => true,
:check_attachments => true})
if ['done', 'relayed'].include? state
basename = RQ::HashDir.path_for(@queue_path, state, params['msg_id'])
else
basename = File.join(@queue_path, state, params['msg_id'])
end
msg = nil
begin
if options[:read_message]
data = File.read(basename + "/msg")
msg = JSON.parse(data)
else
msg = {}
end
msg['path'] = basename
msg['status'] = state
msg['state'] = state
if File.exist?(basename + "/status")
xtra_data = File.read(basename + "/status")
xtra_status = JSON.parse(xtra_data)
msg['status'] += " - #{xtra_status['job_status']}"
end
# Now check for attachments
if options[:read_message] && options[:check_attachments] && File.directory?(basename + "/attach/")
cwd = Dir.pwd
ents = Dir.entries(basename + "/attach/").reject { |i| i.start_with?('.') }
if not ents.empty?
msg['_attachments'] = { }
ents.each do |ent|
msg['_attachments'][ent] = { }
path = File.join(basename, 'attach', ent)
md5, size = file_md5(path)
msg['_attachments'][ent]['md5'] = md5
msg['_attachments'][ent]['size'] = size
msg['_attachments'][ent]['path'] = File.join(cwd, path)
end
end
end
rescue
msg = nil
$log.warn("Bad message in queue: #{basename} [ #{$!} ]")
end
return msg
end
def gen_full_msg_id(msg)
"http://#{@host}:#{@port}#{@root}q/#{@name}/#{msg['msg_id']}"
end
def gen_full_dest(msg)
case msg['dest']
when /^http:/
# If message already has dest url...
{
'dest' => msg['dest'],
'queue' => msg['dest'][%r{/q/([^\/]+)}, 1],
}
when %r{^/q/}
# If message already has dest path...
{
'dest' => "http://#{@host}:#{@port}#{msg['dest']}",
'queue' => msg['dest'][%r{/q/([^\/]+)}, 1],
}
else
# Bare queue name
{
'dest' => "http://#{@host}:#{@port}/q/#{msg['dest']}",
'queue' => msg['dest'],
}
end
end
def attach_msg(msg)
msg_id = msg['msg_id']
# validate attachment
result = [false, 'Unknown error']
begin
basename = File.join(@queue_path, 'prep', msg_id)
return [false, "No message on disk"] unless File.exist? basename
#TODO: deal with symlinks
# simple early check, ok, now check for pathname
return [false, "Invalid pathname, must be normalized #{msg['pathname']} (ie. must start with /"] unless msg['pathname'].start_with?("/")
return [false, "No such file #{msg['pathname']} to attach to message"] unless File.exist?(msg['pathname'])
return [false, "Attachment currently cannot be a directory #{msg['pathname']}"] if File.directory?(msg['pathname'])
return [false, "Attachment currently cannot be read: #{msg['pathname']}"] unless File.readable?(msg['pathname'])
return [false, "Attachment currently not of supported type: #{msg['pathname']}"] unless File.file?(msg['pathname'])
# simple check for attachment dir
attach_path = basename + '/attach/'
Dir.mkdir(attach_path) unless File.exist?(attach_path)
# OK do we have a name?
# Try that first, else use basename
name = msg['name'] || File.basename(msg['pathname'])
# Validate - that it does not have any '/' chars or a '.' prefix
if name.start_with?(".")
return [false, "Attachment name as a dot-file not allowed: #{name}"]
end
# Unsafe char removal
name_test = name.tr('~?[]%|$&<>', '*')
if name_test.index("*")
return [false, "Attachment name has invalid character. not allowed: #{name}"]
end
# TODO: support directory moves
# OK is path on same filesystem?
# stat of basename
if File.stat(attach_path).dev != File.stat(msg['pathname']).dev
return [false, "Attachment must be on same filesystem as que: #{msg['pathname']}"]
end
# No - is local_fs_only set, then error out
# FOR NOW: error out (tough Shit!), blocking would take too long MF
# TODO: else, make a copy in
# ELSE, lock, fork, do copy, return status updates, complex yada yada
# SCREW THIS: let the client do the prep on the cmd line
# Yes - good - just do a link, then rename
# First hardlink to temp file that doesn't exist (link will fail
# if new name already exists in dir
new_path = attach_path + name
tmp_new_path = attach_path + name + '.tmp'
File.unlink(tmp_new_path) rescue nil # Insure tmp_new_path is clear
File.link(msg['pathname'], tmp_new_path)
# Second, do a rename, that will overwrite
md5, size = file_md5(tmp_new_path)
File.rename(tmp_new_path, new_path)
# DONE
result = [true, "#{md5}-Attached successfully"]
rescue
$log.warn("couldn't add attachment to message #{msg_id} [ #{$!} ]")
return false
end
return result
end
def del_attach_msg(msg)
msg_id = msg['msg_id']
attach_name = msg['attachment_name']
# validate attachment
result = [false, 'Unknown error']
begin
basename = File.join(@queue_path, 'prep', msg_id)
return [false, "No message on disk"] unless File.exist? basename
# simple check for attachment dir
attach_path = basename + '/attach/'
return [false, "No attach directory for msg"] unless File.exist?(attach_path)
new_path = attach_path + attach_name
return [false, "No attachment with that named for msg"] unless File.exist?(new_path)