sqeduler 0.1.4

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: a64cee1c9810e71e1f579df8e1a6a57b2f6b3f63
4
+ data.tar.gz: d1b27b846003b95fbc8d46cca571ea84f4924e1a
5
+ SHA512:
6
+ metadata.gz: 68767817edc816cbe2f72cc09b1df71e6df7700be3c9de3946d4cc39a47cef0d2b9f7b0bfb7fae1708dd653deb9d94ca287aadd2b294e5159fedc010d9f40bb6
7
+ data.tar.gz: 7c2980641c62840d39711f9a98c09aa60f81aa8ab43357ae3ae6c9a4fa7e39e168ddef7602cde5ede14d1e10b231fb512096b367c2f4b4eb640bda103fe9f682
data/.document ADDED
@@ -0,0 +1,3 @@
1
+ lib/**/*.rb
2
+ README.md
3
+ CHANGES.md
data/.gitignore ADDED
@@ -0,0 +1,6 @@
1
+ /.bundle
2
+ /.yardoc/
3
+ /Gemfile.lock
4
+ /doc/
5
+ /pkg/
6
+ /vendor/cache/*.gem
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --color
2
+ --format documentation
3
+ --warnings
data/.rubocop.yml ADDED
@@ -0,0 +1,26 @@
1
+ AllCops:
2
+ RunRailsCops: true
3
+ DisplayCopNames: true
4
+
5
+ Lint/EndAlignment:
6
+ AlignWith: variable
7
+
8
+ Metrics/ClassLength:
9
+ Max: 150
10
+
11
+ # just a really annoying check, especially when logging
12
+ Metrics/LineLength:
13
+ Max: 120
14
+
15
+ Metrics/MethodLength:
16
+ Max: 20
17
+
18
+ Style/HashSyntax:
19
+ EnforcedStyle: hash_rockets
20
+
21
+ Style/StringLiterals:
22
+ EnforcedStyle: double_quotes
23
+
24
+ Style/Documentation:
25
+ Exclude:
26
+ - 'lib/sqeduler/version.rb'
data/.travis.yml ADDED
@@ -0,0 +1,6 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.1
4
+ - 2.2
5
+ services:
6
+ - redis-server
data/.yardopts ADDED
@@ -0,0 +1 @@
1
+ --markup markdown --title "sqeduler Documentation" --protected
data/CHANGES.md ADDED
@@ -0,0 +1,4 @@
1
+ ### 0.1.0 / 2015-01-11
2
+
3
+ * Initial release:
4
+
data/CONTRIBUTING.md ADDED
@@ -0,0 +1,13 @@
1
+ Contributing
2
+ ============
3
+
4
+ If you would like to contribute code to Sqeduler you can do so through GitHub by
5
+ forking the repository and sending a pull request.
6
+
7
+ When submitting code, please make every effort to follow existing conventions
8
+ and style in order to keep the code as readable as possible `bundle exec rubocop`.
9
+
10
+ Before your code can be accepted into the project you must also sign the
11
+ [Individual Contributor License Agreement (CLA)][1].
12
+
13
+ [1]: https://spreadsheets.google.com/spreadsheet/viewform?formkey=dDViT2xzUHAwRkI3X3k5Z0lQM091OGc6MQ&ndplr=1
data/Gemfile ADDED
@@ -0,0 +1,10 @@
1
+ # encoding: utf-8
2
+ source "https://www.rubygems.org"
3
+
4
+ gem "sidekiq-scheduler", :github => "ecin/sidekiq-scheduler", :branch => "ecin/redis-lock" # https://github.com/Moove-it/sidekiq-scheduler/pull/38
5
+
6
+ gemspec
7
+
8
+ group :development do
9
+ gem "kramdown"
10
+ end
data/LICENSE.txt ADDED
@@ -0,0 +1,54 @@
1
+ Apache License
2
+
3
+ Version 2.0, January 2004
4
+
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
16
+
17
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
18
+
19
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
20
+
21
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
22
+
23
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
24
+
25
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
26
+
27
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
28
+
29
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
30
+
31
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32
+
33
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
34
+
35
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
36
+
37
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
38
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
39
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
41
+
42
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
43
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
44
+
45
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
46
+
47
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
48
+
49
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
50
+
51
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
52
+
53
+ END OF TERMS AND CONDITIONS
54
+
data/README.md ADDED
@@ -0,0 +1,161 @@
1
+ # sqeduler
2
+
3
+ [![Build Status](https://travis-ci.org/square/sqeduler.svg?branch=master)](https://travis-ci.org/square/sqeduler)
4
+
5
+ ## Description
6
+
7
+ Provides loosely-coupled helpers for Sidekiq workers. Provides highly available scheduling across multiple hosts.
8
+
9
+ ## Features
10
+
11
+ * Centralizes configuration for Sidekiq and Sidekiq::Scheduler
12
+ * Provides composable modules for Sidekiq jobs.
13
+ * Simple callbacks for `before_start`, `on_success`, `on_failure`
14
+ * Synchronization across multiple hosts:
15
+ * Provides global level scheduler locks through a thread-safe redis lock
16
+ * `synchronize_jobs_mode` for if a job should run exclusively. Currently only supports `:one_at_a_time`.
17
+ * Callbacks for `on_schedule_collision` and `on_lock_timeout`
18
+ * Crosshost worker killswitches. `enabled` and `disable` methods to enable and disable workers. Enabled by default.
19
+
20
+ ## Examples
21
+
22
+ To install this gem with necessary forks:
23
+
24
+ ```ruby
25
+ gem 'sqeduler'
26
+ gem 'sidekiq-scheduler', :github => 'ecin/sidekiq-scheduler', :branch => 'ecin/redis-lock' # https://github.com/Moove-it/sidekiq-scheduler/pull/38
27
+ ```
28
+
29
+ ### Scheduling
30
+
31
+ To use this gem for initializing `Sidekiq` and `Sidekiq::Scheduler`:
32
+
33
+ In an initializer:
34
+
35
+ ```ruby
36
+ require 'sqeduler'
37
+ config = Sqeduler::Config.new(
38
+ # configuration for connecting to redis client. Must be a hash, not a `ConnectionPool`.
39
+ :redis_hash => SIDEKIQ_REDIS,
40
+ :logger => logger, # defaults to Rails.logger if nil
41
+ )
42
+
43
+ # OPTIONAL PARAMETERS
44
+ # Additional configuration for Sidekiq.
45
+ # Optional server config for sidekiq. Allows you to hook into `Sidekiq.configure_server`
46
+ config.on_server_start = proc {|config| ... }
47
+ # optional client config for sidekiq. Allows you to hook into `Sidekiq.configure_client`
48
+ config.on_client_start = proc {|config| ... }
49
+ # required if you want to start the Sidekiq::Scheduler
50
+ config.schedule_path = Rails.root.join('config').join('sidekiq_schedule.yml')
51
+
52
+ Sqeduler::Service.config = config
53
+ # Starts Sidekiq and Sidekiq::Scheduler
54
+ Sqeduler::Service.start
55
+ ```
56
+
57
+ See documentation for [Sidekiq::Scheduler](https://github.com/Moove-it/sidekiq-scheduler#scheduled-jobs-recurring-jobs)
58
+ for specifics on how to construct your schedule YAML file.
59
+
60
+ ### Worker Helpers
61
+
62
+ To use `Sqeduler::Worker` modules:
63
+ * You **DO NOT need** to use this gem for starting Sidekiq or Sidekiq::Scheduler (i.e: `Sqeduler::Service.start`)
64
+ * You **DO need** to provide at `config.redis_hash`, and `config.logger` if you don't want to log to `Rails.logger`.
65
+ * This gem creates a separate `ConnectionPool` so that it can create locks for synchronization and store state for disabling/enabling workers.
66
+
67
+ The modules:
68
+
69
+ * `Sqeduler::Worker::Callbacks`: simple callbacks for `before_start`, `on_success`, `on_failure`
70
+ * `Sqeduler::Worker::Synchronization`: synchronize workers across multiple hosts:
71
+ * `synchronize_jobs_mode` for if a job should run exclusively. Currently only supports `:one_at_a_time`.
72
+ * Callbacks for `on_schedule_collision` and `on_lock_timeout`
73
+ * `Sqeduler::Worker::KillSwitch`: cross-host worker disabling/enabling.
74
+ * `enabled` and `disable` class methods to enable and disable workers.
75
+ * Workers are enabled by default.
76
+
77
+ You can either include everything`include Sqeduler::Worker::Everything`) or prepend à la carte, but make sure to
78
+ use [prepend](http://ruby-doc.org/core-2.0.0/Module.html#method-i-prepend), not `include`.
79
+
80
+ Sample code and callback docs below.
81
+
82
+ ```ruby
83
+ class MyWorker
84
+ include Sidekiq::Worker
85
+
86
+ # include everything
87
+ include Sqeduler::Worker::Everything
88
+ # or cherry pick the modules that you want
89
+
90
+ # optionally synchronize jobs across hosts
91
+ prepend Sqeduler::Worker::Synchronization
92
+ # then define how the job should be synchronized
93
+ # :timeout in seconds, how long should we poll for a lock, default is 5
94
+ # :expiration in seconds, how long should the lock be held for
95
+ synchronize :one_at_a_time, :expiration => 1.hour, :timeout => 1.second
96
+
97
+ # cross-host methods for enabling and disabling workers
98
+ # MyWorker.disable and MyWorker.enable
99
+ prepend Sqeduler::Worker::KillSwitch
100
+
101
+
102
+ # Simple callbacks for `before_start`, `on_success`, `on_failure`
103
+ # must be the last worker to be prepended
104
+ prepend Sqeduler::Worker::Callbacks
105
+
106
+ def perform(*args)
107
+ # Your typical sidekiq worker code
108
+ end
109
+
110
+ private
111
+
112
+ # callbacks for Sqeduler::Worker::Callbacks
113
+
114
+ def before_start
115
+ # before perform is called
116
+ end
117
+
118
+ def on_success(total_time)
119
+ # It worked! Save this status or enqueue other jobs.
120
+ end
121
+
122
+ def on_failure(e)
123
+ # Bugsnag can already be notified with config.exception_notifier,
124
+ # but maybe you need to log this differently.
125
+ end
126
+
127
+ # callbacks for Sqeduler::Worker::Synchronization
128
+
129
+ # NOTE: Even if `on_schedule_collision` or `on_lock_timeout` occur your job will still
130
+ # receive on_success if you prepend Sqeduler::Worker::Callbacks. These events do not
131
+ # equate to failures.
132
+
133
+ def on_schedule_collision(duration)
134
+ # Called when your worker uses synchronization and :expiration is too low, i.e. it took longer
135
+ # to carry out `perform` then your lock's expiration period. In this situation, it's possible for
136
+ # the job to get scheduled again even though you expected the job to run exclusively.
137
+ end
138
+
139
+ def on_lock_timeout(key)
140
+ # Called when your worker cannot obtain the lock.
141
+ end
142
+ end
143
+ ```
144
+
145
+ ## License
146
+
147
+ Copyright 2015 Square Inc.
148
+
149
+ Licensed under the Apache License, Version 2.0 (the "License");
150
+ you may not use this file except in compliance with the License.
151
+ You may obtain a copy of the License at
152
+
153
+ http://www.apache.org/licenses/LICENSE-2.0
154
+
155
+ Unless required by applicable law or agreed to in writing, software
156
+ distributed under the License is distributed on an "AS IS" BASIS,
157
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
158
+ See the License for the specific language governing permissions and
159
+ limitations under the License.
160
+
161
+
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # encoding: utf-8
2
+
3
+ require "rspec/core/rake_task"
4
+ RSpec::Core::RakeTask.new
5
+
6
+ require "rubocop/rake_task"
7
+ RuboCop::RakeTask.new
8
+
9
+ require "yard"
10
+ task :doc => :yard
11
+
12
+ task :default => [:spec, :rubocop]
@@ -0,0 +1,16 @@
1
+ # encoding: utf-8
2
+ module Sqeduler
3
+ # Simple config for Sqeduler::Service
4
+ class Config
5
+ attr_accessor :logger, :redis_hash, :schedule_path,
6
+ :on_server_start, :on_client_start
7
+
8
+ def initialize(opts = {})
9
+ self.redis_hash = opts[:redis_hash]
10
+ self.schedule_path = opts[:schedule_path]
11
+ self.on_server_start = opts[:on_server_start]
12
+ self.on_client_start = opts[:on_client_start]
13
+ self.logger = opts[:logger]
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,23 @@
1
+ # encoding: utf-8
2
+ module Sqeduler
3
+ # A unique lock value for reserving a lock across multiple hosts
4
+ class LockValue
5
+ def value
6
+ @value ||= [hostname, process_id, thread_id].join(":")
7
+ end
8
+
9
+ private
10
+
11
+ def hostname
12
+ Socket.gethostname
13
+ end
14
+
15
+ def process_id
16
+ Process.pid
17
+ end
18
+
19
+ def thread_id
20
+ Thread.current.object_id
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,112 @@
1
+ # encoding: utf-8
2
+ module Sqeduler
3
+ # Uses eval_sha to execute server-side scripts on redis.
4
+ # Avoids some of the potentially racey and brittle dependencies on Time-based
5
+ # redis locks in other locking libraries.
6
+ class RedisLock
7
+ include RedisScripts
8
+
9
+ class LockTimeoutError < StandardError; end
10
+ SLEEP_TIME = 0.1
11
+ attr_reader :key, :timeout
12
+
13
+ def initialize(key, options = {})
14
+ @key = key
15
+ @expiration = options[:expiration]
16
+ fail ArgumentError, "Expiration must be provided!" unless @expiration
17
+ @timeout = options[:timeout] || 5
18
+ end
19
+
20
+ def lock
21
+ Service.logger.info(
22
+ "Try to acquire lock with #{key}, expiration: #{@expiration} sec, timeout: #{timeout} sec"
23
+ )
24
+ return true if locked?
25
+ if poll_for_lock
26
+ Service.logger.info "Acquired lock #{key} with value #{lock_value}"
27
+ true
28
+ else
29
+ Service.logger.info "Failed to acquire lock #{key} with value #{lock_value}"
30
+ false
31
+ end
32
+ end
33
+
34
+ def unlock
35
+ if release_lock
36
+ Service.logger.info "Released lock #{key} with value #{lock_value}"
37
+ true
38
+ else
39
+ Service.logger.info "Cannot release lock #{key} with value #{lock_value}"
40
+ false
41
+ end
42
+ end
43
+
44
+ def refresh
45
+ if refresh_lock
46
+ Service.logger.info "Refreshed lock #{key} with value #{lock_value}"
47
+ true
48
+ else
49
+ Service.logger.info "Cannot refresh lock #{key} with value #{lock_value}"
50
+ false
51
+ end
52
+ end
53
+
54
+ def locked?
55
+ redis_pool.with do |redis|
56
+ if redis.get(key) == lock_value
57
+ Service.logger.info "Lock #{key} with value #{lock_value} is valid"
58
+ true
59
+ else
60
+ Service.logger.info "Lock #{key} with value #{lock_value} has expired or is not present"
61
+ false
62
+ end
63
+ end
64
+ end
65
+
66
+ def self.with_lock(key, options)
67
+ fail "Block is required" unless block_given?
68
+ mutex = new(key, options)
69
+ unless mutex.lock
70
+ fail LockTimeoutError, "Timed out trying to get #{key} lock. Exceeded #{mutex.timeout} sec"
71
+ end
72
+ begin
73
+ yield
74
+ ensure
75
+ mutex.unlock
76
+ end
77
+ end
78
+
79
+ def expiration_milliseconds
80
+ # expiration needs to be an integer
81
+ @expiration ? (@expiration * 1000).to_i : 0
82
+ end
83
+
84
+ private
85
+
86
+ def lock_value
87
+ @lock_value ||= LockValue.new.value
88
+ end
89
+
90
+ def poll_for_lock
91
+ start = Time.now
92
+ ran_at_least_once = false
93
+ while Time.now - start < timeout || !ran_at_least_once
94
+ locked = take_lock
95
+ break if locked
96
+ ran_at_least_once = true
97
+ sleep SLEEP_TIME
98
+ end
99
+ locked
100
+ end
101
+
102
+ def take_lock
103
+ redis_pool.with do |redis|
104
+ redis.set(key, lock_value, :nx => true, :px => expiration_milliseconds)
105
+ end
106
+ end
107
+
108
+ def redis_pool
109
+ Service.redis_pool
110
+ end
111
+ end
112
+ end
@@ -0,0 +1,63 @@
1
+ # encoding: utf-8
2
+ module Sqeduler
3
+ # Extracts atomic Lua scripts for Redis.
4
+ module RedisScripts
5
+ def release_lock
6
+ sha_and_evaluate(:release, key, lock_value)
7
+ end
8
+
9
+ def refresh_lock
10
+ sha_and_evaluate(:refresh, key, lock_value)
11
+ end
12
+
13
+ private
14
+
15
+ def sha_and_evaluate(script_name, key, value)
16
+ redis_pool.with do |redis|
17
+ sha = load_sha(redis, script_name)
18
+ # all scripts return 0 or 1
19
+ redis.evalsha(sha, :keys => [key], :argv => [value]) == 1
20
+ end
21
+ end
22
+
23
+ def load_sha(redis, script_name)
24
+ @redis_sha_cache ||= {}
25
+ @redis_sha_cache[script_name] ||= begin
26
+ script = if script_name == :refresh
27
+ refresh_lock_script
28
+ elsif script_name == :release
29
+ release_lock_script
30
+ else
31
+ fail "No script for #{script_name}"
32
+ end
33
+ # strip leading whitespace of 8 characters
34
+ redis.script(:load, script.gsub(/^ {8}/, ""))
35
+ end
36
+ end
37
+
38
+ def refresh_lock_script
39
+ <<-EOF
40
+ if redis.call('GET', KEYS[1]) == false then
41
+ return redis.call('SET', KEYS[1], ARGV[1], 'NX', 'PX', #{expiration_milliseconds}) and 1 or 0
42
+ elseif redis.call('GET', KEYS[1]) == ARGV[1] then
43
+ redis.call('PEXPIRE', KEYS[1], #{expiration_milliseconds})
44
+ if redis.call('GET', KEYS[1]) == ARGV[1] then
45
+ return 1
46
+ end
47
+ end
48
+ return 0
49
+ EOF
50
+ end
51
+
52
+ def release_lock_script
53
+ <<-EOF
54
+ if redis.call('GET', KEYS[1]) == ARGV[1] then
55
+ redis.call('DEL', KEYS[1])
56
+ return 1
57
+ else
58
+ return 0
59
+ end
60
+ EOF
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,100 @@
1
+ # encoding: utf-8
2
+ require "sidekiq"
3
+ require "sidekiq-scheduler"
4
+ module Sqeduler
5
+ # Singleton class for configuring this Gem.
6
+ class Service
7
+ SCHEDULER_TIMEOUT = 60
8
+ MINIMUM_REDIS_VERSION = "2.6.12"
9
+
10
+ class << self
11
+ attr_accessor :config
12
+
13
+ def start
14
+ fail "No config provided" unless config
15
+ config_sidekiq_server
16
+ config_sidekiq_client
17
+ config_scheduler
18
+ end
19
+
20
+ def verify_redis_pool(redis_pool)
21
+ return @verified if defined?(@verified)
22
+ redis_pool.with do |redis|
23
+ version = redis.info["redis_version"]
24
+ unless Gem::Version.new(version) >= Gem::Version.new(MINIMUM_REDIS_VERSION)
25
+ fail "Must be using redis >= #{MINIMUM_REDIS_VERSION}"
26
+ end
27
+ @verified = true
28
+ end
29
+ end
30
+
31
+ def config_sidekiq_server
32
+ logger.info "Initializing Sidekiq server"
33
+ ::Sidekiq.configure_server do |config|
34
+ setup_sidekiq_redis(config)
35
+ if Service.scheduling?
36
+ config.on(:shutdown) do
37
+ # Make sure any scheduling locks are released on shutdown.
38
+ Sidekiq::Scheduler.rufus_scheduler.stop
39
+ end
40
+ end
41
+
42
+ Service.config.on_server_start.call(config) if Service.config.on_server_start
43
+ end
44
+ end
45
+
46
+ def config_sidekiq_client
47
+ logger.info "Initializing Sidekiq client"
48
+ ::Sidekiq.configure_client do |config|
49
+ setup_sidekiq_redis(config)
50
+ if Service.config.on_client_start
51
+ Service.config.on_client_start.call(config)
52
+ end
53
+ end
54
+ end
55
+
56
+ def setup_sidekiq_redis(config)
57
+ return if Service.config.redis_hash.nil? || Service.config.redis_hash.empty?
58
+ config.redis = Service.config.redis_hash
59
+ end
60
+
61
+ def config_scheduler
62
+ if scheduling?
63
+ logger.info "Initializing Sidekiq::Scheduler with schedule #{config.schedule_path}"
64
+ ::Sidekiq::Scheduler.rufus_scheduler_options = {
65
+ :trigger_lock => TriggerLock.new
66
+ }
67
+ ::Sidekiq.schedule = YAML.load_file(config.schedule_path)
68
+ else
69
+ logger.warn "No schedule_path provided. Not starting Sidekiq::Scheduler."
70
+ end
71
+ end
72
+
73
+ def scheduling?
74
+ !config.schedule_path.to_s.empty?
75
+ end
76
+
77
+ # A singleton redis ConnectionPool for Sidekiq::Scheduler,
78
+ # Sqeduler::Worker::Synchronization, Sqeduler::Worker::KillSwitch. Should be
79
+ # separate from Sidekiq's so that we don't saturate the client and server connection
80
+ # pools.
81
+ def redis_pool
82
+ @redis_pool ||= begin
83
+ redis = { :namespace => "sqeduler" }.merge(config.redis_hash)
84
+ ::Sidekiq::RedisConnection.create(redis).tap do |redis_pool|
85
+ verify_redis_pool(redis_pool)
86
+ end
87
+ end
88
+ end
89
+
90
+ def logger
91
+ return config.logger if config.logger
92
+ if defined?(Rails)
93
+ Rails.logger
94
+ else
95
+ fail ArgumentError, "No logger provided and Rails.logger cannot be inferred"
96
+ end
97
+ end
98
+ end
99
+ end
100
+ end
@@ -0,0 +1,20 @@
1
+ # encoding: utf-8
2
+ module Sqeduler
3
+ # Super simple facade to match RufusScheduler's expectations of how
4
+ # a trigger_lock behaves.
5
+ class TriggerLock < RedisLock
6
+ SCHEDULER_LOCK_KEY = "sidekiq_scheduler_lock".freeze
7
+
8
+ def initialize
9
+ super(SCHEDULER_LOCK_KEY, :expiration => 60, :timeout => 0)
10
+ end
11
+
12
+ def lock
13
+ # Locking should:
14
+ # - not block
15
+ # - return true if already acquired
16
+ # - refresh the lock if already acquired
17
+ refresh || super
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,4 @@
1
+ # encoding: utf-8
2
+ module Sqeduler
3
+ VERSION = "0.1.4"
4
+ end