sidekiq 0.5.0

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of sidekiq might be problematic. Click here for more details.

Files changed (62) hide show
  1. data/.rvmrc +3 -0
  2. data/COMM-LICENSE +75 -0
  3. data/Changes.md +4 -0
  4. data/Gemfile +4 -0
  5. data/Gemfile.lock +32 -0
  6. data/LICENSE +9 -0
  7. data/README.md +64 -0
  8. data/Rakefile +8 -0
  9. data/TODO.md +4 -0
  10. data/bin/client +7 -0
  11. data/bin/sidekiq +19 -0
  12. data/lib/sidekiq.rb +4 -0
  13. data/lib/sidekiq/cli.rb +100 -0
  14. data/lib/sidekiq/client.rb +47 -0
  15. data/lib/sidekiq/manager.rb +131 -0
  16. data/lib/sidekiq/middleware.rb +89 -0
  17. data/lib/sidekiq/processor.rb +37 -0
  18. data/lib/sidekiq/rails.rb +5 -0
  19. data/lib/sidekiq/util.rb +36 -0
  20. data/lib/sidekiq/version.rb +3 -0
  21. data/lib/sidekiq/worker.rb +42 -0
  22. data/myapp/.gitignore +15 -0
  23. data/myapp/Gemfile +5 -0
  24. data/myapp/Gemfile.lock +100 -0
  25. data/myapp/Rakefile +7 -0
  26. data/myapp/app/controllers/application_controller.rb +3 -0
  27. data/myapp/app/helpers/application_helper.rb +2 -0
  28. data/myapp/app/mailers/.gitkeep +0 -0
  29. data/myapp/app/models/.gitkeep +0 -0
  30. data/myapp/app/models/post.rb +2 -0
  31. data/myapp/app/views/layouts/application.html.erb +14 -0
  32. data/myapp/app/workers/hard_worker.rb +6 -0
  33. data/myapp/config.ru +4 -0
  34. data/myapp/config/application.rb +59 -0
  35. data/myapp/config/boot.rb +6 -0
  36. data/myapp/config/database.yml +25 -0
  37. data/myapp/config/environment.rb +5 -0
  38. data/myapp/config/environments/development.rb +37 -0
  39. data/myapp/config/environments/production.rb +67 -0
  40. data/myapp/config/environments/test.rb +37 -0
  41. data/myapp/config/initializers/backtrace_silencers.rb +7 -0
  42. data/myapp/config/initializers/inflections.rb +15 -0
  43. data/myapp/config/initializers/mime_types.rb +5 -0
  44. data/myapp/config/initializers/secret_token.rb +7 -0
  45. data/myapp/config/initializers/session_store.rb +8 -0
  46. data/myapp/config/initializers/wrap_parameters.rb +14 -0
  47. data/myapp/config/locales/en.yml +5 -0
  48. data/myapp/config/routes.rb +58 -0
  49. data/myapp/db/migrate/20120123214055_create_posts.rb +10 -0
  50. data/myapp/db/seeds.rb +7 -0
  51. data/myapp/lib/assets/.gitkeep +0 -0
  52. data/myapp/lib/tasks/.gitkeep +0 -0
  53. data/myapp/log/.gitkeep +0 -0
  54. data/myapp/script/rails +6 -0
  55. data/sidekiq.gemspec +22 -0
  56. data/test/helper.rb +9 -0
  57. data/test/test_client.rb +50 -0
  58. data/test/test_manager.rb +38 -0
  59. data/test/test_middleware.rb +62 -0
  60. data/test/test_processor.rb +52 -0
  61. data/test/timed_queue.rb +42 -0
  62. metadata +179 -0
data/.rvmrc ADDED
@@ -0,0 +1,3 @@
1
+ export RUBYOPT="-Ilib"
2
+ export JRUBY_OPTS="--1.9"
3
+ rvm use 1.9.3@sidekiq --create
@@ -0,0 +1,75 @@
1
+ THIS LICENSE AGREEMENT DESCRIBES YOUR RIGHTS WITH RESPECT TO THE SOFTWARE AND ITS COMPONENTS.
2
+
3
+ 1. OWNERSHIP, LICENSE GRANT
4
+
5
+ This is a license agreement and not an agreement for sale. We reserve ownership of all intellectual property rights inherent in or relating to the Software, which include, but are not limited to, all copyright, patent rights, all rights in relation to registered and unregistered trademarks (including service marks), confidential information (including trade secrets and know-how) and all rights other than those expressly granted by this License Agreement.
6
+
7
+ Subject to the payment of the fee required and subject to the terms and conditions of this License Agreement, We grant to You a revocable, non- transferable and non-exclusive license (i) for Designated User(s) (as defined below) within Your organization to install and use the Software on any workstations used exclusively by such Designated User and (ii) for You to install and use the Software in connection with unlimited domains and sub-domains on unlimited servers, solely in connection with distribution of the Software in accordance with sections 3 and 4 below. This license is not sublicensable except as explicitly set forth herein. “Designated User(s)” shall mean Your employee(s) acting within the scope of their employment or Your consultant(s) or contractor(s) acting within the scope of the services they provide for You or on Your behalf for whom You have purchased a license to use the Software.
8
+
9
+ In addition to the other terms contained herein, We grant to You a revocable, non- transferable and non-exclusive license to install and use the Software on a single computer (the “Trial License”) strictly for Your internal evaluation and review purposes and not for production purposes. This Trial License applies only if You have registered with Us for a Trial License of the Software and shall be effective for forty-five (45) consecutive days following the date of registration (“the Trial Period”). You may only register for a Trial License once in any eighteen month period. You agree not to use a Trial License for any purpose other than determining whether to purchase a license to the Software. You are explicitly not permitted to distribute the Software to any user outside the Organization on whose behalf you have undertaken this license. Your rights to use the Trial License will immediately terminate upon the earlier of (i) the expiration of the Trial Period, or (ii) such time that You purchase a license to the Software. We reserve the right to terminate Your Trial License at any time in Our absolute and sole discretion.
10
+
11
+ 2. PERMITTED USES, SOURCE CODE, MODIFICATIONS
12
+
13
+ We provide You with source code so that You can create Modifications of the original Software, where Modification means: a) any addition to or deletion from the contents of a file included in the original Software or previous Modifications created by You, or b) any new file that contains any part of the original Software or previous Modifications. While You retain all rights to any original work authored by You as part of the Modifications, We continue to own all copyright and other intellectual property rights in the Software.
14
+
15
+ 3. DISTRIBUTION
16
+
17
+ You may distribute the Software in any applications, frameworks, or elements (collectively referred to as an “Application” or “Applications”) that you develop using the Software in accordance with this License Agreement, provided that such distribution does not violate the restrictions set forth in section 4 of this License Agreement. You must not remove, obscure or interfere with any copyright, acknowledgment, attribution, trademark, warning or disclaimer statement affixed to, incorporated in or otherwise applied in connection with the Software.
18
+
19
+ You are required to ensure that the Software is not reused by or with any applications other than those with which You distribute it as permitted herein. For example, if You install the Software on a customer’s server, that customer is not permitted to use the Software independently of Your application, and must be informed as such.
20
+
21
+ You will not owe Us any royalties for Your distribution of the Software in accordance with this License Agreement.
22
+
23
+ 4. PROHIBITED USES
24
+
25
+ You may not, without Our prior written consent, redistribute the Software or Modifications other than by including the Software or a portion thereof within Your own product, which must have substantially different functionality than the Software or Modifications and must not allow any third party to use the Software or Modifications, or any portions thereof, for software development or application development purposes. You are explicitly not allowed to redistribute the Software or Modifications as part of any product that can be described as a development toolkit or library, an application builder, a website builder or any product that is intended for use by software, application, or website developers or designers. You are not allowed to redistribute any part of the Software documentation. You may not change or remove the copyright notice from any of the files included in the Software or Modifications.
26
+
27
+ UNDER NO CIRCUMSTANCES MAY YOU USE THE SOFTWARE FOR A PRODUCT THAT IS INTENDED FOR SOFTWARE OR APPLICATION DEVELOPMENT PURPOSES.
28
+
29
+ The Open Source version of the Software (“GPL Version”) is licensed under the terms of the GNU General Public License versions 3.0 (“GPL”) and not under this License Agreement. If You, or another third party, has, at any time, developed all (or any portions of) the Application(s) using the GPL Version, You may not combine such development work with the Software and must license such Application(s) (or any portions derived there from) under the terms of the GNU General Public License version 3, a copy of which is located at http://www.gnu.org/copyleft/gpl.html.
30
+
31
+ 5. TERMINATION
32
+
33
+ This License Agreement and Your right to use the Software and Modifications will terminate immediately without notice if You fail to comply with the terms and conditions of this License Agreement. Upon termination, You agree to immediately cease using and destroy the Software or Modifications, including all accompanying documents. The provisions of sections 4, 5, 6, 7, 8, 9, 10 and 12 will survive any termination of this License Agreement.
34
+
35
+ 6. DISCLAIMER OF WARRANTIES
36
+
37
+ TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, WE AND OUR SUPPLIERS DISCLAIM ALL WARRANTIES AND CONDITIONS, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT, WITH REGARD TO THE SOFTWARE. WE DO NOT GUARANTEE THAT THE OPERATION OF THE SOFTWARE WILL BE UNINTERRUPTED OR ERROR-FREE, AND YOU ACKNOWLEDGE THAT IT IS NOT TECHNICALLY PRACTICABLE FOR US TO DO SO.
38
+
39
+ 7. LIMITATION OF LIABILITIES
40
+
41
+ TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL WE OR OUR SUPPLIERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION OR ANY OTHER PECUNIARY LAW) ARISING OUT OF THE USE OF OR INABILITY TO USE THE SOFTWARE, EVEN IF WE HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. IN ANY CASE, OUR ENTIRE LIABILITY UNDER ANY PROVISION OF THIS LICENSE AGREEMENT SHALL BE LIMITED TO THE AMOUNT ACTUALLY PAID BY YOU FOR THE SOFTWARE.
42
+
43
+ 8. VERIFICATION
44
+
45
+ We or a certified auditor acting on Our behalf, may, upon its reasonable request and at its expense, audit You with respect to the use of the Software. Such audit may be conducted by mail, electronic means or through an in-person visit to Your place of business. Any such in-person audit shall be conducted during regular business hours at Your facilities and shall not unreasonably interfere with Your business activities. We shall not remove, copy, or redistribute any electronic material during the course of an audit. If an audit reveals that You are using the Software in a way that is in material violation of the terms of the License Agreement, then You shall pay Our reasonable costs of conducting the audit. In the case of a material violation, You agree to pay Us any amounts owing that are attributable to the unauthorized use. In the alternative, We reserve the right, at Our sole option, to terminate the licenses for the Software.
46
+
47
+ 9. THIRD PARTY SOFTWARE
48
+
49
+ Examples included in Software may provide links to third party libraries or code (collectively “Third Party Software”) to implement various functions. Third Party Software does not comprise part of the Software. In some cases, access to Third Party Software may be included along with the Software delivery as a convenience for demonstration purposes. Such source code and libraries may be included in the “…/examples” source tree delivered with the Software and do not comprise the Software. Licensee acknowledges (1) that some part of Third Party Software may require additional licensing of copyright and patents from the owners of such, and (2) that distribution of any of the Software referencing or including any portion of a Third Party Software may require appropriate licensing from such third parties.
50
+
51
+ 10. PAYMENT AND TAXES
52
+
53
+ If credit has been extended to You by Us, all payments under this License Agreement are due within thirty (30) days of the date We mail an invoice to You. If We have not extended credit to You, You shall be required to make payment concurrent with the delivery of the Software by Us. All amounts payable are gross amounts but exclusive of any value added tax, use tax, sales tax or similar tax. You shall be entitled to withhold from payments any applicable withholding taxes and comply with all applicable tax and employment legislation. Each party shall pay all taxes (including, but not limited to, taxes based upon its income) or levies imposed on it under applicable laws, regulations and tax treaties as a result of this Agreement and any payments made hereunder (including those required to be withheld or deducted from payments). Each party shall furnish evidence of such paid taxes as is sufficient to enable the other party to obtain any credits available to it, including original withholding tax certificates.
54
+
55
+ 11. MISCELLANEOUS
56
+
57
+ The license granted herein applies only to the version of the Software available when purchased in connection with the terms of this License Agreement. Any previous or subsequent license granted to You for use of the Software shall be governed by the terms and conditions of the agreement entered in connection with purchase of that version of the Software. You agree that you will comply with all applicable laws and regulations with respect to the Software, including without limitation all export and re-export control laws and regulations.
58
+
59
+ While redistributing the Software or Modifications thereof, You may choose to offer acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License Agreement. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on our behalf. You agree to indemnify, defend, and hold Us harmless from and against any liability incurred by, or claims asserted against, Us (i) by reason of Your accepting any such support, warranty, indemnity or additional liability; or (ii) arising out of the use, reproduction or distribution of Your Application, except to the extent such claim is solely based on the inclusion of the Software therein.
60
+
61
+ You agree to be identified as a customer of ours and You agree that We may refer to You by name, trade name and trademark, if applicable, and may briefly describe Your business in our marketing materials and web site.
62
+
63
+ You may not assign this License Agreement without Our prior written consent, which will not be unreasonably withheld. This License Agreement will inure to the benefit of Our successors and assigns.
64
+
65
+ You acknowledge that this License Agreement is complete and is the exclusive representation of our agreement. No oral or written information given by Us or on our behalf shall create a warranty or collateral contract, or in any way increase the scope of this License Agreement in any way, and You may not rely on any such oral or written information. No term or condition contained in any purchase order shall apply unless expressly accepted by Us in writing,
66
+
67
+ There are no implied licenses or other implied rights granted under this License Agreement, and all rights, save for those expressly granted hereunder, shall remain with Us and our licensors. In addition, no licenses or immunities are granted to the combination of the Software and/or Modifications, as applicable, with any other software or hardware not delivered by Us to You under this License Agreement.
68
+
69
+ If any provision in this License Agreement shall be determined to be invalid, such provision shall be deemed omitted; the remainder of this License Agreement shall continue in full force and effect. If any remedy provided is determined to have failed for its essential purpose, all limitations of liability and exclusions of damages set forth in this License Agreement shall remain in effect.
70
+
71
+ This License Agreement may be modified only by a written instrument signed by an authorized representative of each party.
72
+
73
+ This License Agreement is governed by the law of the State of Oregon, United States (notwithstanding conflicts of laws provisions), and all parties irrevocably submit to the jurisdiction of the courts of the State of Oregon and further agree to commence any litigation which may arise hereunder in the state or federal courts located in the judicial district of Multnomah County, Oregon, US.
74
+
75
+ If the Software or any related documentation is licensed to the U.S. government or any agency thereof, it will be deemed to be “commercial computer software” or “commercial computer software documentation,” pursuant to DFAR Section 227.7202 and FAR Section 12.212. Any use of the Software or related documentation by the U.S. government will be governed solely by the terms of this License Agreement.
@@ -0,0 +1,4 @@
1
+ 0.5.0
2
+ -----------
3
+
4
+ - Initial release!
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'http://rubygems.org'
2
+ gemspec
3
+
4
+ gem 'simplecov', :require => false, :group => :test
@@ -0,0 +1,32 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ sidekiq (0.1.0)
5
+ celluloid
6
+ connection_pool
7
+ multi_json
8
+ redis
9
+
10
+ GEM
11
+ remote: http://rubygems.org/
12
+ specs:
13
+ celluloid (0.8.0)
14
+ connection_pool (0.1.0)
15
+ minitest (2.10.0)
16
+ multi_json (1.0.4)
17
+ rake (0.9.2.2)
18
+ redis (2.2.2)
19
+ simplecov (0.5.4)
20
+ multi_json (~> 1.0.3)
21
+ simplecov-html (~> 0.5.3)
22
+ simplecov-html (0.5.3)
23
+
24
+ PLATFORMS
25
+ java
26
+ ruby
27
+
28
+ DEPENDENCIES
29
+ minitest
30
+ rake
31
+ sidekiq!
32
+ simplecov
data/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ Copyright (c) Mike Perham
2
+
3
+ Sidekiq is open source licensed under the GPLv3 for non-commerical use:
4
+
5
+ Please see <http://www.gnu.org/licenses/gpl-3.0.html> for license text.
6
+
7
+ To purchase a commercial license, you must pledge $50 to my Pledgie
8
+ fund at http://www.pledgie.com/campaigns/16623. The commercial license can
9
+ be found in COMM-LICENSE.
@@ -0,0 +1,64 @@
1
+ Sidekiq
2
+ ==============
3
+
4
+ Simple, efficient message processing for Ruby.
5
+
6
+ Sidekiq aims to be compatible with Resque. It uses the exact same
7
+ message format as Resque so it can integrate into an existing Resque processing farm.
8
+ You can have Sidekiq and Resque run side-by-side at the same time and
9
+ use the Resque client to enqueue messages in Redis to be processed by Sidekiq.
10
+
11
+ Sidekiq is different from Resque in how it processes messages: it
12
+ processes many messages concurrently per process. Resque only processes
13
+ one message at a time per process so it is far less memory efficient.
14
+ You'll find that you might need 50 200MB resque processes to peg your CPU
15
+ whereas one 300MB Sidekiq process will peg the same CPU and perform the
16
+ same amount of work. Please see [my blog post on Resque's memory
17
+ efficiency](http://blog.carbonfive.com/2011/09/16/improving-resques-memory-efficiency/)
18
+ and how I was able to shrink a Carbon Five client's resque processing farm
19
+ from 9 machines to 1 machine.
20
+
21
+
22
+ Requirements
23
+ -----------------
24
+
25
+ I test on Ruby 1.9.3 and JRuby 1.6.5 in 1.9 mode. Other versions/VMs are
26
+ untested.
27
+
28
+
29
+ Installation
30
+ -----------------
31
+
32
+ gem install sidekiq
33
+
34
+
35
+ Getting Started
36
+ -----------------
37
+
38
+ See the [sidekiq home page](http://mperham.github.com/sidekiq) for the simple 4-step process.
39
+
40
+
41
+ More Information
42
+ -----------------
43
+
44
+ Please see the [sidekiq wiki](https://github.com/mperham/sidekiq/wiki) for more information.
45
+
46
+
47
+ License
48
+ -----------------
49
+
50
+ sidekiq is GPLv3 licensed for **non-commercial use only**. For a commercial
51
+ license, you must give $50 to my [Pledgie campaign](http://www.pledgie.com/campaigns/16623).
52
+ Considering the hundreds of hours I've spent writing OSS, I hope you
53
+ think this is a reasonable price. BTW, the commercial license is in
54
+ COMM-LICENSE and is the [Sencha commercial license v1.10](http://www.sencha.com/legal/sencha-commercial-software-license-agreement/) with the Support (section 11) terms removed.
55
+ Support is provided through GitHub Issues. You are welcome to try the
56
+ software for 2 weeks.
57
+
58
+ <a href='http://www.pledgie.com/campaigns/16623'><img alt='Click here to lend your support to Open Source and make a donation at www.pledgie.com !' src='http://www.pledgie.com/campaigns/16623.png?skin_name=chrome' border='0' /></a>
59
+
60
+ Author
61
+ -----------------
62
+
63
+ Mike Perham, [@mperham](https://twitter.com/mperham), [http://mikeperham.com](http://mikeperham.com)
64
+
@@ -0,0 +1,8 @@
1
+ require 'rake/testtask'
2
+ Rake::TestTask.new(:test) do |test|
3
+ test.libs << 'test'
4
+ test.warning = true
5
+ test.pattern = 'test/**/test_*.rb'
6
+ end
7
+
8
+ task :default => :test
data/TODO.md ADDED
@@ -0,0 +1,4 @@
1
+ - monitoring stats
2
+ - resque-ui-esque web ui
3
+ - graceful shutdown (ideally Celluloid will provide this)
4
+ - monit/god/etc example scripts
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'sidekiq'
4
+
5
+ 10.times do
6
+ Sidekiq::Client.push('class' => 'HardWorker', 'args' => ['bob', 1])
7
+ end
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ begin
4
+ require 'sidekiq/cli'
5
+ rescue LoadError
6
+ # Better way to do this in dev?
7
+ dir = File.expand_path(File.dirname(__FILE__) + '/../lib')
8
+ $LOAD_PATH << dir if File.exist?("#{dir}/sidekiq.rb")
9
+ require 'sidekiq/cli'
10
+ end
11
+
12
+ begin
13
+ cli = Sidekiq::CLI.new
14
+ cli.run
15
+ rescue => e
16
+ raise e if $DEBUG
17
+ STDERR.puts e.message
18
+ exit 1
19
+ end
@@ -0,0 +1,4 @@
1
+ require 'sidekiq/version'
2
+ require 'sidekiq/client'
3
+ require 'sidekiq/worker'
4
+ require 'sidekiq/rails' if defined?(Rails)
@@ -0,0 +1,100 @@
1
+ require 'optparse'
2
+ require 'sidekiq/version'
3
+ require 'sidekiq/util'
4
+ require 'sidekiq/client'
5
+ require 'sidekiq/manager'
6
+ require 'connection_pool'
7
+
8
+ module Sidekiq
9
+ class CLI
10
+ include Util
11
+
12
+ def initialize
13
+ parse_options
14
+ validate!
15
+ boot_rails
16
+ end
17
+
18
+ FOREVER = 2_000_000_000
19
+
20
+ def run
21
+ ::Sidekiq::Client.redis = ConnectionPool.new { Redis.connect(:url => @options[:server]) }
22
+ manager = Sidekiq::Manager.new(@options[:server], @options)
23
+ begin
24
+ log 'Starting processing, hit Ctrl-C to stop'
25
+ manager.start!
26
+ sleep FOREVER
27
+ rescue Interrupt
28
+ log 'Shutting down...'
29
+ manager.stop!
30
+ manager.wait(:shutdown)
31
+ end
32
+ end
33
+
34
+ private
35
+
36
+ def boot_rails
37
+ ENV['RAILS_ENV'] = @options[:environment]
38
+ require File.expand_path("#{@options[:rails]}/config/environment.rb")
39
+ ::Rails.application.eager_load!
40
+ end
41
+
42
+ def validate!
43
+ $DEBUG = @options[:verbose]
44
+
45
+ if !File.exist?("#{@options[:rails]}/config/boot.rb")
46
+ log "========== Please point sidekiq to a Rails 3 application =========="
47
+ log @parser
48
+ exit(1)
49
+ end
50
+ end
51
+
52
+ def parse_options(argv=ARGV)
53
+ @options = {
54
+ :verbose => false,
55
+ :queues => ['default'],
56
+ :processor_count => 25,
57
+ :server => ENV['REDISTOGO_URL'] || 'redis://localhost:6379/0',
58
+ :rails => '.',
59
+ :environment => 'production',
60
+ }
61
+
62
+ @parser = OptionParser.new do |o|
63
+ o.on "-q", "--queue QUEUE,WEIGHT", "Queue to process, with optional weight" do |arg|
64
+ (q, weight) = arg.split(",")
65
+ (weight || 1).times do
66
+ @options[:queues] << q
67
+ end
68
+ end
69
+
70
+ o.on "-v", "--verbose", "Print more verbose output" do
71
+ @options[:verbose] = true
72
+ end
73
+
74
+ o.on "-s", "--server LOCATION", "Where to find Redis" do |arg|
75
+ @options[:server] = arg
76
+ end
77
+
78
+ o.on '-e', '--environment ENV', "Rails application environment" do |arg|
79
+ @options[:environment] = arg
80
+ end
81
+
82
+ o.on '-r', '--rails PATH', "Location of Rails application with workers" do |arg|
83
+ @options[:rails] = arg
84
+ end
85
+
86
+ o.on '-c', '--concurrency INT', "processor threads to use" do |arg|
87
+ @options[:processor_count] = arg.to_i
88
+ end
89
+ end
90
+
91
+ @parser.banner = "sidekiq [options]"
92
+ @parser.on_tail "-h", "--help", "Show help" do
93
+ log @parser
94
+ exit 1
95
+ end
96
+ @parser.parse!(argv)
97
+ end
98
+
99
+ end
100
+ end
@@ -0,0 +1,47 @@
1
+ require 'multi_json'
2
+ require 'redis'
3
+
4
+ module Sidekiq
5
+ class Client
6
+
7
+ def self.redis
8
+ @redis ||= begin
9
+ # autoconfig for Heroku
10
+ hash = { :url => ENV['REDISTOGO_URL'] } if ENV['REDISTOGO_URL']
11
+ Redis.connect(hash)
12
+ end
13
+ end
14
+
15
+ def self.redis=(redis)
16
+ @redis = redis
17
+ end
18
+
19
+ # Example usage:
20
+ # Sidekiq::Client.push('my_queue', 'class' => MyWorker, 'args' => ['foo', 1, :bat => 'bar'])
21
+ def self.push(queue='default', item)
22
+ raise(ArgumentError, "Message must be a Hash of the form: { 'class' => SomeClass, 'args' => ['bob', 1, :foo => 'bar'] }") unless item.is_a?(Hash)
23
+ raise(ArgumentError, "Message must include a class and set of arguments: #{item.inspect}") if !item['class'] || !item['args']
24
+
25
+ item['class'] = item['class'].to_s if !item['class'].is_a?(String)
26
+ redis.rpush("queue:#{queue}", MultiJson.encode(item))
27
+ end
28
+
29
+ # Please use .push if possible instead.
30
+ #
31
+ # Example usage:
32
+ #
33
+ # Sidekiq::Client.enqueue(MyWorker, 'foo', 1, :bat => 'bar')
34
+ #
35
+ # Messages are enqueued to the 'default' queue. Optionally,
36
+ # MyWorker can define a queue class method:
37
+ #
38
+ # def self.queue
39
+ # 'my_queue'
40
+ # end
41
+ #
42
+ def self.enqueue(klass, *args)
43
+ queue = (klass.respond_to?(:queue) && klass.queue) || 'default'
44
+ push(queue, { 'class' => klass.name, 'args' => args })
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,131 @@
1
+ require 'celluloid'
2
+ require 'redis'
3
+ require 'multi_json'
4
+
5
+ require 'sidekiq/util'
6
+ require 'sidekiq/processor'
7
+
8
+ module Sidekiq
9
+
10
+ ##
11
+ # The main router in the system. This
12
+ # manages the processor state and fetches messages
13
+ # from Redis to be dispatched to an idle processor.
14
+ #
15
+ class Manager
16
+ include Util
17
+ include Celluloid
18
+
19
+ trap_exit :processor_died
20
+
21
+ def initialize(location, options={})
22
+ log "Booting sidekiq #{Sidekiq::VERSION} with Redis at #{location}"
23
+ verbose options.inspect
24
+ @count = options[:processor_count] || 25
25
+ @queues = options[:queues]
26
+ @queue_idx = 0
27
+ @queues_size = @queues.size
28
+ @redis = Redis.connect(:url => location)
29
+
30
+ @done = false
31
+ @busy = []
32
+ @ready = []
33
+ @count.times do
34
+ @ready << Processor.new_link(current_actor)
35
+ end
36
+ end
37
+
38
+ def stop
39
+ @done = true
40
+ @ready.each(&:terminate)
41
+ @ready.clear
42
+
43
+ after(5) do
44
+ signal(:shutdown)
45
+ end
46
+ end
47
+
48
+ def start
49
+ dispatch(true)
50
+ end
51
+
52
+ def when_done
53
+ @done_callback = Proc.new
54
+ end
55
+
56
+ def processor_done(processor)
57
+ @done_callback.call(processor)
58
+ @busy.delete(processor)
59
+ if stopped?
60
+ processor.terminate
61
+ else
62
+ @ready << processor
63
+ end
64
+ dispatch
65
+ end
66
+
67
+ def processor_died(processor, reason)
68
+ @busy.delete(processor)
69
+
70
+ if reason
71
+ log "Processor death: #{reason}"
72
+ log reason.backtrace.join("\n")
73
+ end
74
+
75
+ unless stopped?
76
+ @ready << Processor.new_link(current_actor)
77
+ dispatch
78
+ end
79
+ end
80
+
81
+ private
82
+
83
+ def find_work(queue_idx)
84
+ current_queue = @queues[queue_idx]
85
+ msg = @redis.lpop("queue:#{current_queue}")
86
+ if msg
87
+ processor = @ready.pop
88
+ @busy << processor
89
+ processor.process! MultiJson.decode(msg)
90
+ end
91
+ !!msg
92
+ end
93
+
94
+ def dispatch(schedule = false)
95
+ watchdog("Fatal error in sidekiq, dispatch loop died") do
96
+ return if stopped?
97
+
98
+ # Our dispatch loop
99
+ # Loop through the queues, looking for a message in each.
100
+ queue_idx = 0
101
+ found = false
102
+ loop do
103
+ # return so that we don't dispatch again until processor_done
104
+ break verbose('no processors') if @ready.size == 0
105
+
106
+ found ||= find_work(queue_idx)
107
+ queue_idx += 1
108
+
109
+ # if we find no messages in any of the queues, we can break
110
+ # out of the loop. Otherwise we loop again.
111
+ lastq = (queue_idx % @queues.size == 0)
112
+ if lastq && !found
113
+ verbose('nothing to process'); break
114
+ elsif lastq
115
+ queue_idx = 0
116
+ found = false
117
+ end
118
+ end
119
+
120
+ # This is the polling loop that ensures we check Redis every
121
+ # second for work, even if there was nothing to do this time
122
+ # around.
123
+ after(1) { verbose('ping'); dispatch(schedule) } if schedule
124
+ end
125
+ end
126
+
127
+ def stopped?
128
+ @done
129
+ end
130
+ end
131
+ end