workety 2.0.3

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: 0cdc2a8236499e0f1432599a7ffd985425899a97
4
+ data.tar.gz: eb666d1d2b5a04b82e275d783fd286045b7fec20
5
+ SHA512:
6
+ metadata.gz: b458440966ec540a29aa11d0f1dce85ead941384739bb82be63c9622126fe726026e3efb75fc8fb663787281e8d886e1a4340f04f62e988bd28e6c7af3c880c3
7
+ data.tar.gz: f429d67217ae6563b41211e40935b4e458034284df73343c4bf931018b7502e3e84bbcc715da6959e105ed4e0a3cfda497bc8a36242db519675a5aa73218a5ee
data/CONTRIBUTING.md ADDED
@@ -0,0 +1,5 @@
1
+
2
+ We require our contributors to sign a Contributor License Agreement before
3
+ any contribution can be considered, reviewed, or accepted.
4
+
5
+ Please see https://contributors.senotrusov.com/ for details.
data/ISSUE_TEMPLATE.md ADDED
@@ -0,0 +1,5 @@
1
+ <!--
2
+ Please use the "x" character to declare that you agree with the statement below. Otherwise, remove the said statement and mark your submission as "Not a Contribution.".
3
+ -->
4
+
5
+ [ ] I agree that this is the Contribution as defined in Apache License, Version 2.0 (the "License") and I am submitting this Contribution in compliance with the License. A copy of the License can be obtained at http://www.apache.org/licenses/LICENSE-2
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,5 @@
1
+ <!--
2
+ Please note that we require our contributors to sign a Contributor License Agreement before any contribution can be considered, reviewed, or accepted.
3
+
4
+ Please see our Contributing Guidelines for details.
5
+ -->
data/README.md ADDED
@@ -0,0 +1,120 @@
1
+ # Workety
2
+
3
+ A library to run Ruby classes as daemons.
4
+
5
+ * process start
6
+ * terminal detach
7
+ * run as a user/group (root privileges drop)
8
+ * signal handling
9
+ * logfile
10
+ * pidfile, check for already running daemon
11
+ * may restart in a case of failure, by forking from watchdog
12
+ * may send exceptions to Airbrake and Exceptional
13
+ * Rails environment load at a late stage
14
+ * support for mutithreaded workers
15
+ * command-line argument parsing by use of the [trollop](http://trollop.rubyforge.org) library
16
+ * simple API for an application code
17
+
18
+
19
+ ### Command-line invocation
20
+
21
+ ```sh
22
+ # run a daemon
23
+ workety -e development start Workety::SimpleThread --foo=bar
24
+ # ^^^^^ Start as a daemon
25
+ # ^^^^^^^^^^^^^^ Options for Workety ^^^^^^^^^ Options for the class
26
+
27
+ # run a thread in the console
28
+ workety Workety::SimpleThread
29
+ ```
30
+
31
+ ### SimpleThread example
32
+
33
+ ```ruby
34
+ class SimpleThread
35
+ # Before dropping privileges
36
+ def initialize
37
+ end
38
+
39
+ # After changing privileges to some user/group
40
+ def start
41
+ @t = Thread.workety do
42
+ until Workety.must_stop? do
43
+ sleep 1
44
+ end
45
+ end
46
+
47
+ Thread.workety do
48
+ sleep 10
49
+ Workety.stop
50
+ end
51
+ end
52
+
53
+ def join
54
+ @t.join
55
+ end
56
+
57
+ def stop
58
+ @t.kill
59
+ end
60
+ end
61
+ ```
62
+
63
+ ### GracefulStopThread example
64
+
65
+ ```ruby
66
+ class GracefulStopThread
67
+ # Before dropping privileges
68
+ def initialize
69
+ @mutex = Mutex.new
70
+ @wakeup = ConditionVariable.new
71
+ end
72
+
73
+ # After changing privileges to some user/group
74
+ def start
75
+ @worker = Thread.workety do
76
+ @mutex.synchronize do
77
+ until Workety.must_stop? do
78
+
79
+ puts "Hello"
80
+
81
+ @wakeup.wait(@mutex, 10)
82
+ end
83
+ end
84
+ end
85
+ end
86
+
87
+ def join
88
+ @worker.join
89
+ end
90
+
91
+ def stop
92
+ @mutex.synchronize do
93
+ @wakeup.signal
94
+ end
95
+ end
96
+ end
97
+ ```
98
+
99
+
100
+ ## Copyright and License
101
+
102
+ ```
103
+ Copyright 2006-2011 Stanislav Senotrusov
104
+
105
+ Licensed under the Apache License, Version 2.0 (the "License");
106
+ you may not use this file except in compliance with the License.
107
+ You may obtain a copy of the License at
108
+
109
+ http://www.apache.org/licenses/LICENSE-2.0
110
+
111
+ Unless required by applicable law or agreed to in writing, software
112
+ distributed under the License is distributed on an "AS IS" BASIS,
113
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
114
+ See the License for the specific language governing permissions and
115
+ limitations under the License.
116
+ ```
117
+
118
+ ## Contributing
119
+
120
+ Please see our [Contributing Guidelines](CONTRIBUTING.md) for details.
data/Rakefile ADDED
@@ -0,0 +1,35 @@
1
+
2
+ # Copyright 2006-2011 Stanislav Senotrusov <stan@senotrusov.com>
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+
17
+ begin
18
+ require 'jeweler'
19
+
20
+ Jeweler::Tasks.new do |gemspec|
21
+ gemspec.name = "workety"
22
+ gemspec.licenses = ['Apache-2.0']
23
+ gemspec.summary = "Run Ruby/Rails code as a worker: detach, signals, watchdog, threads, reporting"
24
+ gemspec.authors = ["Stanislav Senotrusov"]
25
+ gemspec.email = "stan@senotrusov.com"
26
+ gemspec.homepage = "https://github.com/senotrusov/workety"
27
+
28
+ gemspec.add_dependency 'trollop'
29
+ end
30
+
31
+ Jeweler::GemcutterTasks.new
32
+
33
+ rescue LoadError
34
+ puts "Jeweler not available. Install it with: gem install jeweler"
35
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 2.0.3
data/bin/workety ADDED
@@ -0,0 +1,359 @@
1
+ #!/usr/bin/env ruby
2
+ #
3
+ # Copyright 2006-2011 Stanislav Senotrusov <stan@senotrusov.com>
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+
18
+ # I encountered functions and classes once. They look strange.
19
+
20
+
21
+ # Parse command-line arguments
22
+ #
23
+ # workety -e development start Workety::TestThread --foo=bar
24
+ # ^^^^^ Start as daemon
25
+ # ^^^^^^^^^^^^^^ Options for Workety ^^^^^^^^^ Options for class (parsed by class)
26
+ #
27
+ #
28
+ # workety Workety::TestThread
29
+ # Runs test thread in console
30
+ #
31
+ require 'trollop'
32
+
33
+ options = Trollop::options do
34
+ opt :environment, "Run in environment (development/production/testing)", :type => :string
35
+
36
+ opt :user, "Run as user", :type => :string
37
+ opt :group, "Run as group", :type => :string
38
+
39
+ opt :name, "Logfile and pidfile name", :type => :string
40
+ opt :log, "Logfile name (default to class_name)", :type => :string
41
+ opt :log_level, "Log level (debug, info, warn, error, fatal)", :type => :string
42
+ opt :pid, "Pidfile name (default to class_name)", :type => :string
43
+
44
+ opt :no_watchdog, "Do not watch and restart daemon", :type => :boolean
45
+
46
+ stop_on_unknown
47
+ end
48
+
49
+ action = case ARGV.first
50
+ when /start/i
51
+ ARGV.shift
52
+ options[:environment] ||= "production"
53
+ :start
54
+ when /stop/i
55
+ ARGV.shift
56
+ options[:environment] ||= "production"
57
+ :stop
58
+ else
59
+ options[:environment] ||= "development"
60
+ :console
61
+ end
62
+
63
+ ENV['RAILS_ENV'] ||= options[:environment]
64
+
65
+ class_name = ARGV.shift
66
+
67
+ unless class_name || action == :stop && (options[:name] || options[:pid])
68
+ STDERR.puts "ERROR: class name required"
69
+ Process.exit false
70
+ end
71
+
72
+
73
+ # Define pid and log file name
74
+ #
75
+ pidfile = "tmp/pids/#{options[:name] || options[:pid] || class_name}.pid"
76
+ logfile = "log/#{options[:name] || options[:log] || class_name}.log"
77
+
78
+
79
+ # Do stop action and exit
80
+ #
81
+ WORKETY_STOP_TICK = 0.05
82
+ WORKETY_STOP_NOTICE = 5
83
+ WORKETY_STOP_WARNING = 55
84
+ WORKETY_STOP_KILL = 60
85
+ # There is also a Workety::STOP_SELF_WATCHDOG_TIMEOUT == 65 defined in Workety module
86
+
87
+ if action == :stop
88
+ begin
89
+ pid = File.read(pidfile).to_i
90
+ Process.kill(:TERM, pid)
91
+
92
+ begin
93
+ noticd = false
94
+ warned = false
95
+ killed = false
96
+ forced = false
97
+
98
+ slept = 0
99
+
100
+ while Process.getpgid(pid) # Raise Errno::ESRCH if process not found
101
+
102
+ sleep WORKETY_STOP_TICK
103
+ slept += WORKETY_STOP_TICK
104
+
105
+ # Notice the operator and send USR1 signal to log running threads
106
+ if !noticd && slept >= WORKETY_STOP_NOTICE
107
+ STDOUT.puts "\n#{WORKETY_STOP_NOTICE} seconds notice timeout reached"
108
+
109
+ STDOUT.puts "\nSending USR1 signal to log list of running threads"
110
+ Process.kill(:USR1, pid)
111
+
112
+ STDOUT.puts "USR2 as a warning signal will be sent after #{WORKETY_STOP_WARNING} seconds from the first TERM"
113
+ STDOUT.puts "KILL signal will be sent after #{WORKETY_STOP_KILL} seconds from the first TERM"
114
+
115
+ STDOUT.puts "\nPress <Ctrl>c to cancel or <Ctrl>d to force USR2 signal and the following KILL signal within #{WORKETY_STOP_KILL - WORKETY_STOP_WARNING} seconds"
116
+
117
+ noticd = true
118
+ end
119
+
120
+ # Send USR2 as a warning
121
+ if !warned && slept >= WORKETY_STOP_WARNING
122
+ STDOUT.puts "\nSending USR2 signal as a warning before KILL"
123
+ Process.kill(:USR2, pid)
124
+ warned = true
125
+ end
126
+
127
+ # Send KILL
128
+ if !killed && slept >= WORKETY_STOP_KILL
129
+ STDOUT.puts "\nSending KILL signal"
130
+ Process.kill(:KILL, pid)
131
+ killed = true
132
+ end
133
+
134
+ # Check for <Ctrl>d
135
+ if !forced && slept < WORKETY_STOP_WARNING
136
+ begin
137
+ STDIN.read_nonblock(100)
138
+ rescue Errno::EAGAIN
139
+ # Resource temporarily unavailable - it's ok, retrying
140
+ rescue EOFError
141
+ # Operator pressed <Ctrl>d
142
+ forced = true
143
+ slept = WORKETY_STOP_WARNING
144
+ end
145
+ end
146
+
147
+ end # while
148
+
149
+ # Process is no longer alive
150
+ rescue Errno::ESRCH
151
+ STDOUT.puts "Shutdown successfull"
152
+ Process.exit true
153
+
154
+ # Operator pressed <Ctrl>c and cancels force shutdown
155
+ rescue Interrupt
156
+ Process.exit false
157
+ end
158
+
159
+ rescue Errno::ENOENT
160
+ STDERR.puts "ERROR: Pidfile #{pidfile} does not exists"
161
+ Process.exit false
162
+
163
+ rescue Errno::ESRCH
164
+ STDERR.puts "ERROR: Process with pid #{pid} does not running"
165
+ Process.exit false
166
+ end
167
+ end
168
+
169
+
170
+ # Below that line prefer STDOUT.write "foo\n" instead of puts
171
+ #
172
+ # Current ruby puts implementation make two write syscals - one for string and one (if needed) for record separator (a newline).
173
+ # When writing to file (logfile on our case) concurrently it may intermix strings with separators like "ab\n\n".
174
+
175
+
176
+ # Detach from terminal when running as a daemon (start action)
177
+ #
178
+ if action == :start
179
+ # based on Reimer Behrends notes
180
+ # http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/87467
181
+ Process.exit!(true) if fork # Parent exits, child continues.
182
+ Process.setsid # Become session leader.
183
+ Process.exit!(true) if fork # Zap session leader. See http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
184
+
185
+ # Is there any point to set umask here?
186
+ # File.umask 022 # Default permissions will be 644 for files and 755 for directories
187
+
188
+ STDIN.reopen "/dev/null"
189
+
190
+ STDOUT.reopen(logfile, "a")
191
+ STDOUT.sync = true
192
+
193
+ STDERR.reopen STDOUT
194
+ end
195
+
196
+
197
+ # Check - are process is already running?
198
+ #
199
+ if File.exists?(pidfile)
200
+ begin
201
+ Process.getpgid(pid = File.read(pidfile).to_i)
202
+ # STDERR.write "ERROR: Process is already running with pid #{pid}\n"
203
+ # Process.exit false
204
+ STDERR.write "WARNING: Found pidfile #{pidfile} with pid #{pid} and a process running with that pid\n"
205
+ rescue Errno::ENOENT
206
+ # Do nothing
207
+ rescue Errno::ESRCH
208
+ STDERR.write "WARNING: Found pidfile #{pidfile} with pid #{pid}, it may be the result of an unclean shutdown\n"
209
+ end
210
+ end
211
+
212
+
213
+ # Write pid to file and define at_exit handler for pidfile deletion
214
+ #
215
+ File.open(pidfile, 'w') do |file|
216
+ file.write Process.pid
217
+ end
218
+
219
+ delete_pidfile = true
220
+ at_exit { File.delete(pidfile) if delete_pidfile }
221
+
222
+
223
+ # Watchdog process if needed
224
+ #
225
+ WORKETY_RESTART_DELAY = 60
226
+
227
+ module Signal
228
+ # Signal received by watchdog is propogated to child by this helper method
229
+ def self.propagate(pid, signal, out_signal = nil)
230
+ out_signal ||= signal
231
+ trap(signal) do
232
+ begin
233
+ yield if block_given?
234
+ Process.kill(out_signal, pid)
235
+ rescue Errno::ESRCH
236
+ # Process with pid #{pid} does not running
237
+ end
238
+ end
239
+ end
240
+ end
241
+
242
+ if action == :start && !options[:no_watchdog]
243
+
244
+ must_stop = false
245
+
246
+ loop do
247
+ # There is a need to reseed random number generators after each fork.
248
+ # Fortunately, ruby developers already do this for us, as I get from http://redmine.ruby-lang.org/issues/4579
249
+ if (child_pid = fork)
250
+ # Parent restarts child and propagate signals to him.
251
+
252
+ Signal.propagate(child_pid, :INT) { must_stop = true }
253
+ Signal.propagate(child_pid, :TERM) { must_stop = true }
254
+ Signal.propagate(child_pid, :USR1)
255
+ Signal.propagate(child_pid, :USR2, :KILL) { must_stop = true }
256
+
257
+ Process.wait(child_pid)
258
+
259
+ STDOUT.write "Child #{child_pid} exited " +
260
+ ($?.exited? ? "normally with status #{$?.exitstatus}" : "abnormally") +
261
+ ($?.signaled? ? " because of an uncaught signal #{$?.termsig}" : "") +
262
+ ($?.coredump? ? " and coredump" : "") + "\n"
263
+
264
+ if must_stop || $?.exitstatus == 0
265
+ STDOUT.write "Terminating\n"
266
+ Process.exit(true)
267
+ end
268
+
269
+ # Clear signal handlers in order that newly forked children did not inherit watchdog handlers
270
+ Signal.trap(:INT, "DEFAULT")
271
+ Signal.trap(:TERM, "DEFAULT")
272
+ Signal.trap(:USR1, "IGNORE")
273
+ Signal.trap(:USR2, "DEFAULT")
274
+
275
+ else
276
+ # Children breaks to initialize and run
277
+ delete_pidfile = false
278
+ break
279
+ end
280
+
281
+ STDOUT.write "Restarting after #{WORKETY_RESTART_DELAY} seconds\n"
282
+ sleep WORKETY_RESTART_DELAY
283
+ end
284
+ end
285
+
286
+
287
+ # Load bundler, rails framework, rails application, initialize logger
288
+ #
289
+ # This will load bundler, rails framework and define application configuration class
290
+ require File.expand_path('config/application')
291
+
292
+ Rails.configuration.autoload_paths.push "#{Rails.configuration.root}/app/workety"
293
+
294
+ class Workety::Railtie < Rails::Railtie
295
+ initializer :workety, :after => :load_environment_config, :before => :load_active_support do |app|
296
+ Rails.configuration.threadsafe!
297
+ end
298
+ end
299
+
300
+ if action == :console
301
+ Rails.logger = ActiveSupport::BufferedLogger.new(STDOUT)
302
+ Rails.logger.level = ActiveSupport::BufferedLogger.const_get(options[:log_level].upcase) if options[:log_level]
303
+ else
304
+ Rails.configuration.paths.log logfile
305
+ Rails.configuration.log_level = options[:log_level].downcase.to_sym if options[:log_level]
306
+ end
307
+
308
+ ActiveSupport::BufferedLogger.class_eval do
309
+ def chown_logfile(user_uid, group_gid)
310
+ @log.chown(user_uid, group_gid) if @log.respond_to?(:chown)
311
+ end
312
+ end
313
+
314
+ # This will initialize Rails application, load all the application classes
315
+ require File.expand_path('config/environment')
316
+
317
+ Rails.logger.auto_flushing = true
318
+ Rails.logger.flush
319
+
320
+ at_exit { Rails.logger.flush }
321
+
322
+
323
+ # Handling stop signals
324
+ #
325
+ # If signal handler was called second time while the first is still running,
326
+ # then mutex inside that handler will lead to deadlock (recursive locking, ThreadError)
327
+ # as all handling occurs in main thread. To avoid that signal handler spawns new thread
328
+ # which take care of stopping the process
329
+ #
330
+ Signal.threaded_trap(:INT) { Workety.stop } # Ctrl+C
331
+ Signal.threaded_trap(:TERM) { Workety.stop } # kill
332
+ Signal.threaded_trap(:USR1) { Thread.log } # USR1 signal to display list of running thread and their backtraces
333
+ Signal.trap(:USR2, "IGNORE") # USR2 signal used as a warning before KILL signal
334
+
335
+
336
+ # Watchdog thread will shutdown process if parent process is gone
337
+ #
338
+ if action == :start && !options[:no_watchdog]
339
+ Thread.rescue_exit do
340
+ sleep 30 until Process.ppid == 1
341
+ Rails.logger.fatal "Parent process is missing, terminating"
342
+ Workety.stop
343
+ end
344
+ end
345
+
346
+
347
+ # TODO: proper test environment
348
+ # require "workety/test/test_thread.rb" if class_name == "Workety::TestThread"
349
+
350
+
351
+ # Start the worker
352
+ #
353
+ Workety.start class_name, options[:user], options[:group]
354
+ Workety.join
355
+
356
+ Rails.logger.debug { "Exiting with exitstatus #{(!Workety.aborted?) ? 0 : 1}" }
357
+
358
+ Process.exit(!Workety.aborted?)
359
+