serverengine 2.0.0pre1-x86-mingw32

Sign up to get free protection for your applications and to get access to all the features.
Files changed (48) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +5 -0
  3. data/.rspec +2 -0
  4. data/.travis.yml +20 -0
  5. data/Changelog +122 -0
  6. data/Gemfile +2 -0
  7. data/LICENSE +202 -0
  8. data/NOTICE +3 -0
  9. data/README.md +514 -0
  10. data/Rakefile +26 -0
  11. data/appveyor.yml +24 -0
  12. data/examples/server.rb +138 -0
  13. data/examples/spawn_worker_script.rb +38 -0
  14. data/lib/serverengine.rb +46 -0
  15. data/lib/serverengine/blocking_flag.rb +77 -0
  16. data/lib/serverengine/command_sender.rb +89 -0
  17. data/lib/serverengine/config_loader.rb +82 -0
  18. data/lib/serverengine/daemon.rb +233 -0
  19. data/lib/serverengine/daemon_logger.rb +135 -0
  20. data/lib/serverengine/embedded_server.rb +67 -0
  21. data/lib/serverengine/multi_process_server.rb +155 -0
  22. data/lib/serverengine/multi_spawn_server.rb +95 -0
  23. data/lib/serverengine/multi_thread_server.rb +80 -0
  24. data/lib/serverengine/multi_worker_server.rb +150 -0
  25. data/lib/serverengine/privilege.rb +57 -0
  26. data/lib/serverengine/process_manager.rb +508 -0
  27. data/lib/serverengine/server.rb +178 -0
  28. data/lib/serverengine/signal_thread.rb +116 -0
  29. data/lib/serverengine/signals.rb +31 -0
  30. data/lib/serverengine/socket_manager.rb +171 -0
  31. data/lib/serverengine/socket_manager_unix.rb +98 -0
  32. data/lib/serverengine/socket_manager_win.rb +154 -0
  33. data/lib/serverengine/supervisor.rb +313 -0
  34. data/lib/serverengine/utils.rb +62 -0
  35. data/lib/serverengine/version.rb +3 -0
  36. data/lib/serverengine/winsock.rb +128 -0
  37. data/lib/serverengine/worker.rb +81 -0
  38. data/serverengine.gemspec +37 -0
  39. data/spec/blocking_flag_spec.rb +59 -0
  40. data/spec/daemon_logger_spec.rb +175 -0
  41. data/spec/daemon_spec.rb +169 -0
  42. data/spec/multi_process_server_spec.rb +113 -0
  43. data/spec/server_worker_context.rb +232 -0
  44. data/spec/signal_thread_spec.rb +94 -0
  45. data/spec/socket_manager_spec.rb +119 -0
  46. data/spec/spec_helper.rb +19 -0
  47. data/spec/supervisor_spec.rb +215 -0
  48. metadata +184 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: bb740fe7e9ba44533ad55afa79c34feb0521931e
4
+ data.tar.gz: f5959aca75bcc3a340de1d91caac0da9a0905e10
5
+ SHA512:
6
+ metadata.gz: 14e11560b295c04880c29987fde26649e5c98d3f2c44c956f8666fb0e80766f88e850d6871f736c376fbd652e0f1d74a249f4a0813dcccb53c7fe0b58d5b0c27
7
+ data.tar.gz: 3f1a342b7cc25e9b18798bb389027dde8a3d2a6d8fd1a5ca71d7ed726c09d7df1b3540bf795a2c090188057a42e059ed187dc51c80659cb246e5d9136617c9f5
data/.gitignore ADDED
@@ -0,0 +1,5 @@
1
+ Gemfile.lock
2
+ tmp/*
3
+ pkg/*
4
+ myserver.log
5
+ myserver.pid
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --require spec_helper
2
+
data/.travis.yml ADDED
@@ -0,0 +1,20 @@
1
+ language: ruby
2
+
3
+ rvm:
4
+ - 2.1.10
5
+ - 2.2.4
6
+ - 2.3.0
7
+ - ruby-head
8
+
9
+ branches:
10
+ only:
11
+ - master
12
+
13
+ script: bundle exec rake spec
14
+
15
+ before_install:
16
+ - gem update bundler
17
+
18
+ matrix:
19
+ allow_failures:
20
+ - rvm: ruby-head
data/Changelog ADDED
@@ -0,0 +1,122 @@
1
+ 2016-08-23 version 2.0.0:
2
+
3
+ * Add windows-pr gem dependency to get ruby_bin_path correctly
4
+ * Add command sender feature to use pipe to control workers for Windows
5
+ * Delete MultiprocessLogDevice implementation to use Ruby's one always. This
6
+ means removal of backward workaround code for Ruby < 2.1.
7
+ * Refactor modules and methods to clean internal file dependency Internal
8
+ symbol `ServerEngine::Daemon::Signals` is moved to `ServerEngine::Signals`
9
+ * Add example script to run servers
10
+ * Fix required Ruby version to 2.1 or later
11
+
12
+ 2016-05-19 version 1.6.4:
13
+
14
+ * Refactor to delete some warnings
15
+ * Fix infinite self call bug in SignalTread
16
+ * Add ruby 2.1 support for TravisCI
17
+
18
+ 2016-04-27 version 1.6.3:
19
+
20
+ * Fix Socket Manager for UDP to adapt to ipv6
21
+ * Fix Socket Manager not to join thread in Ruby 2.1
22
+ * Fix Socket Manager to identify all localhost address
23
+ * Fix ruby dll path on Ruby x64
24
+
25
+ 2016-04-14 version 1.6.2:
26
+
27
+ * Fix to use Etc instead of id command in change_privilege for windows
28
+ * Fix signal handler on Server class to be configurable
29
+ * Fix to use spawn when damonize on windows
30
+
31
+ 2016-03-04 version 1.6.1:
32
+
33
+ * Fix CloseHandle definition in winsock
34
+
35
+
36
+ 2015-01-07 version 1.6.0:
37
+
38
+ * Added SocketManager, a utility class for multiprocess servers to listen on
39
+ the same TCP or UDP port dynamically.
40
+ * Added a new attr_reader accessor at Daemon#server and Supervisor#server
41
+ * Added ServerEngine.windows? method to check Windows platform
42
+ * ProcessManager now considers Windows platform
43
+
44
+
45
+ 2015-09-28 version 1.5.11:
46
+
47
+ * Fix unexpected logger option handling [#22]
48
+ * Fix gem homepage link
49
+
50
+
51
+ 2014-10-27 version 1.5.10:
52
+
53
+ * Added worker_type=spawn (experimental)
54
+ * Fixed Worker#config to reference Server#config so that Worker#reload reads
55
+ the new config reloaded by Server#reload (=ConfigLoader#reload_config) in
56
+ worker_type=thread and embedded
57
+ * Server#stop, #restart and #reload show a debug log message
58
+
59
+
60
+ 2014-07-24 version 1.5.9:
61
+
62
+ * Fixed DaemonLogger#reoepen! on Ruby >= 2.1.0
63
+
64
+
65
+ 2014-06-27 version 1.5.8:
66
+
67
+ * Use standard LogDevice on Ruby >= 2.1.0 imporoved at https://github.com/ruby/ruby/pull/428
68
+
69
+
70
+ 2013-10-31 version 1.5.7:
71
+
72
+ * Fixed :log parameter handling
73
+
74
+
75
+ 2013-10-20 version 1.5.6:
76
+
77
+ * Fixed log rotation in worker_type=process mode [#9]
78
+ * DaemonLogger supports 'trace' level
79
+
80
+
81
+ 2013-09-17 version 1.5.5:
82
+
83
+ * worker_type=thread and embedded show uncaught errors caused in Worker#stop
84
+ and Worker#reload interface
85
+ * ProcessManager: enables child process heartbeat only if enable_heartbeat
86
+ option is true
87
+ * ProcessManager: doesn't call fcntl on pipe pairs if F_SETFD or FD_CLOEXEC
88
+ is not defined
89
+ * ProcessManager: added #spawn(*args) method
90
+
91
+
92
+ 2013-09-10 version 1.5.4:
93
+
94
+ * SignalThread: fixed "Unexpected error can't be called from trap context"
95
+ error in Ruby 2.0 (Thanks to @jondot and @sonots)
96
+
97
+
98
+ 2013-06-30 version 1.5.3:
99
+
100
+ * Daemon: uses Process::UID.from_name and Process::GID.from_name
101
+ instead of running id command
102
+ * worker_type=thread calls before_fork
103
+ * Added MultiWorkerServer#join_workers
104
+ * DaemonLogger: fixed #initialize to use config[:log_level]
105
+
106
+
107
+ 2013-06-11 version 1.5.2:
108
+
109
+ * Updated default parameters of ProcessManager to be more conservative
110
+ * Daemon: added :daemonize_error_exit_code option
111
+ * Fixed ServerEngine.create
112
+
113
+
114
+ 2013-06-04 version 1.5.1:
115
+
116
+ * Changed #close callback to #after_start
117
+
118
+
119
+ 2013-06-01 version 1.5.0:
120
+
121
+ * First release
122
+
data/Gemfile ADDED
@@ -0,0 +1,2 @@
1
+ source 'https://rubygems.org/'
2
+ gemspec
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.
data/NOTICE ADDED
@@ -0,0 +1,3 @@
1
+ ServerEngine
2
+ https://github.com/frsyuki/serverengine
3
+ Copyright (C) 2012-2013 Sadayuki Furuhashi
data/README.md ADDED
@@ -0,0 +1,514 @@
1
+ # ServerEngine
2
+
3
+ ServerEngine is a framework to implement robust multiprocess servers like Unicorn.
4
+
5
+ **Main features:**
6
+
7
+ ```
8
+ Heartbeat via pipe
9
+ & auto-restart
10
+ / \ ---+
11
+ +------------+ / +----------+ \ +--------+ |
12
+ | Supervisor |------| Server |------| Worker | |
13
+ +------------+ +----------+\ +--------+ | Multi-process
14
+ / \ | or multi-thread
15
+ / \ +--------+ |
16
+ Dynamic reconfiguration | Worker | |
17
+ and live restart support +--------+ |
18
+ ---+
19
+ ```
20
+
21
+ ServerEngine also provides useful options and utilities such as **logging**, **signal handlers**, **changing process names** shown by `ps` command, chuser, **stacktrace** and **heap dump on signal**.
22
+
23
+ * [Examples](#examples)
24
+ * [Simplest server](#simplest-server)
25
+ * [Multiprocess server](#multiprocess-server)
26
+ * [Multiprocess TCP server](#multiprocess-tcp-server)
27
+ * [Multiprocess server on Windows and JRuby platforms](#multiprocess-server-on-windows-and-jruby-platforms)
28
+ * [Logging](#logging)
29
+ * [Supervisor auto restart](#supervisor-auto-restart)
30
+ * [Live restart](#live-restart)
31
+ * [Dynamic config reloading](#dynamic-config-reloading)
32
+ * [Signals](#signals)
33
+ * [Utilities](#utilities)
34
+ * [BlockingFlag](#blockingflag)
35
+ * [SocketManager](#socketmanager)
36
+ * [Module API](#module-api)
37
+ * [Worker module](#worker-module)
38
+ * [Server module](#server-module)
39
+ * [List of all configurations](#list-of-all-configurations)
40
+
41
+ ## Examples
42
+
43
+ ### Simplest server
44
+
45
+ What you need to implement at least is a worker module which has `run` and `stop` methods.
46
+
47
+ ```ruby
48
+ require 'serverengine'
49
+
50
+ module MyWorker
51
+ def run
52
+ until @stop
53
+ logger.info "Awesome work!"
54
+ sleep 1
55
+ end
56
+ end
57
+
58
+ def stop
59
+ @stop = true
60
+ end
61
+ end
62
+
63
+ se = ServerEngine.create(nil, MyWorker, {
64
+ daemonize: true,
65
+ log: 'myserver.log',
66
+ pid_path: 'myserver.pid',
67
+ })
68
+ se.run
69
+ ```
70
+
71
+ Send `TERM` signal (or `KILL` on Windows) to kill the daemon. See also **Signals** section bellow for details.
72
+
73
+
74
+ ### Multiprocess server
75
+
76
+ Simply set **worker_type: "process"** or **worker_type: "thread"** parameter, and set number of workers to `workers` parameter.
77
+
78
+ ```ruby
79
+ se = ServerEngine.create(nil, MyWorker, {
80
+ daemonize: true,
81
+ log: 'myserver.log',
82
+ pid_path: 'myserver.pid',
83
+ worker_type: 'process',
84
+ workers: 4,
85
+ })
86
+ se.run
87
+ ```
88
+
89
+ See also **Worker types** section bellow.
90
+
91
+
92
+ ### Multiprocess TCP server
93
+
94
+ One of the typical implementation styles of TCP servers is that a parent process listens socket and child processes accept connections from clients.
95
+
96
+ ServerEngine allows you to optionally implement a server module to control the parent process:
97
+
98
+ ```ruby
99
+ # Server module controls the parent process
100
+ module MyServer
101
+ def before_run
102
+ @sock = TCPServer.new(config[:bind], config[:port])
103
+ end
104
+
105
+ attr_reader :sock
106
+ end
107
+
108
+ # Worker module controls child processes
109
+ module MyWorker
110
+ def run
111
+ until @stop
112
+ # you should use Cool.io or EventMachine actually
113
+ c = server.sock.accept
114
+ c.write "Awesome work!"
115
+ c.close
116
+ end
117
+ end
118
+
119
+ def stop
120
+ @stop = true
121
+ end
122
+ end
123
+
124
+ se = ServerEngine.create(MyServer, MyWorker, {
125
+ daemonize: true,
126
+ log: 'myserver.log',
127
+ pid_path: 'myserver.pid',
128
+ worker_type: 'process',
129
+ workers: 4,
130
+ bind: '0.0.0.0',
131
+ port: 9071,
132
+ })
133
+ se.run
134
+ ```
135
+
136
+
137
+ ### Multiprocess server on Windows and JRuby platforms
138
+
139
+ Above **worker_type: "process"** depends on `fork` system call, which doesn't work on Windows or JRuby platform.
140
+ ServerEngine provides **worker_type: "spawn"** for those platforms (This is still EXPERIMENTAL). However, unfortunately, you need to implement different worker module because `worker_type: "spawn"` is not compatible with **worker_type: "process"** in terms of API.
141
+
142
+ What you need to implement at least to use worker_type: "spawn" is `def spawn(process_manager)` method. You will call `process_manager.spawn` at the method, where `spawn` is same with `Process.spawn` excepting return value.
143
+
144
+ In addition, Windows does not support signals. ServerEngine provides **command_sender: "pipe"** for Windows (and for other platforms, if you want to use it).
145
+ When using **command_sender: "pipe"**, the child process have to handle commands sent from parent process via STDIN.
146
+ On Windows, **command_sender: "pipe"** is default.
147
+
148
+ You can call `Server#stop(stop_graceful)` and `Server#restart(stop_graceful)` instead of sending signals.
149
+
150
+ ```ruby
151
+ module MyWorker
152
+ def spawn(process_manager)
153
+ env = {
154
+ 'SERVER_ENGINE_CONFIG' => config.to_json
155
+ }
156
+ script = %[
157
+ require 'serverengine'
158
+ require 'json'
159
+
160
+ conf = JSON.parse(ENV['SERVER_ENGINE_CONFIG'], symbolize_names: true)
161
+ logger = ServerEngine::DaemonLogger.new(conf[:log] || STDOUT, conf)
162
+
163
+ @stop = false
164
+ command_pipe = STDIN.dup
165
+ STDIN.reopen(File::NULL)
166
+ Thread.new do
167
+ until @stop
168
+ case command_pipe.gets.chomp
169
+ when "GRACEFUL_STOP"
170
+ @stop = true
171
+ when "IMMEDIATE_STOP"
172
+ @stop = true
173
+ when "GRACEFUL_RESTART", "IMMEDIATE_RESTART"
174
+ # do something...
175
+ end
176
+ end
177
+ end
178
+
179
+ until @stop
180
+ logger.info 'Awesome work!'
181
+ sleep 1
182
+ end
183
+ ]
184
+ process_manager.spawn(env, "ruby", "-e", script)
185
+ end
186
+ end
187
+
188
+ se = ServerEngine.create(nil, MyWorker, {
189
+ worker_type: 'spawn',
190
+ command_sender: 'pipe',
191
+ log: 'myserver.log',
192
+ })
193
+ se.run
194
+ ```
195
+
196
+
197
+ ## Logging
198
+
199
+ ServerEngine logger rotates logs by 1MB and keeps 5 generations by default.
200
+
201
+ ```ruby
202
+ se = ServerEngine.create(MyServer, MyWorker, {
203
+ log: 'myserver.log',
204
+ log_level: 'debug',
205
+ log_rotate_age: 5,
206
+ log_rotate_size: 1*1024*1024,
207
+ })
208
+ se.run
209
+ ```
210
+
211
+ ServerEngine's default logger extends from Ruby's standard Logger library to:
212
+
213
+ * support multiprocess aware log rotation
214
+ * support reopening of log file
215
+ * support 'trace' level, which is lower level than 'debug'
216
+
217
+ See also **Configuration** section bellow.
218
+
219
+
220
+ ## Supervisor auto restart
221
+
222
+ Server programs running 24x7 hours need to survive even if a process stalled because of unexpected memory swapping or network errors.
223
+
224
+ Supervisor process runs as the parent process of the server process and monitor it to restart automatically. You can enable supervisor process by setting `supervisor: true` parameter:
225
+
226
+ ```ruby
227
+ se = ServerEngine.create(nil, MyWorker, {
228
+ daemonize: true,
229
+ pid_path: 'myserver.pid',
230
+ supervisor: true, # enables supervisor process
231
+ })
232
+ se.run
233
+ ```
234
+
235
+ This auto restart reature will be suppressed for workers which exits with exit code specified by `unrecoverable_exit_codes`. At this case, whole process will exit without error (exit code 0).
236
+
237
+ ## Live restart
238
+
239
+ You can restart a server process without waiting for completion of all workers using `INT` signal (`supervisor: true` and `enable_detach: true` parameters must be enabled).
240
+ This feature allows you to minimize downtime where workers take long time to complete a task.
241
+
242
+ ```
243
+ # 1. starts server
244
+ +------------+ +----------+ +-----------+
245
+ | Supervisor |----| Server |----| Worker(s) |
246
+ +------------+ +----------+ +-----------+
247
+
248
+ # 2. receives SIGINT and waits for shutdown of the server for server_detach_wait
249
+ +------------+ +----------+ +-----------+
250
+ | Supervisor | | Server |----| Worker(s) |
251
+ +------------+ +----------+ +-----------+
252
+
253
+ # 3. starts new server if the server doesn't exit in server_detach_wait time
254
+ +------------+ +----------+ +-----------+
255
+ | Supervisor |\ | Server |----| Worker(s) |
256
+ +------------+ | +----------+ +-----------+
257
+ |
258
+ | +----------+ +-----------+
259
+ \--| Server |----| Worker(s) |
260
+ +----------+ +-----------+
261
+
262
+ # 4. old server exits eventually
263
+ +------------+
264
+ | Supervisor |\
265
+ +------------+ |
266
+ |
267
+ | +----------+ +-----------+
268
+ \--| Server |----| Worker(s) |
269
+ +----------+ +-----------+
270
+ ```
271
+
272
+ Note that network servers (which listen sockets) shouldn't use live restart because it causes "Address already in use" error at the server process. Instead, simply use `worker_type: "process"` configuration and send `USR1` to restart workers instead of the server. It restarts a worker without waiting for shutdown of the other workers. This way doesn't cause downtime because server process doesn't close listening sockets and keeps accepting new clients (See also `restart_server_process` parameter if necessary).
273
+
274
+
275
+ ## Dynamic config reloading
276
+
277
+ Robust servers should not restart only to update configuration parameters.
278
+
279
+ ```ruby
280
+ module MyWorker
281
+ def initialize
282
+ reload
283
+ end
284
+
285
+ def reload
286
+ @message = config[:message] || "Awesome work!"
287
+ @sleep = config[:sleep] || 1
288
+ end
289
+
290
+ def run
291
+ until @stop
292
+ logger.info @message
293
+ sleep @sleep
294
+ end
295
+ end
296
+
297
+ def stop
298
+ @stop = true
299
+ end
300
+ end
301
+
302
+ se = ServerEngine.create(nil, MyWorker) do
303
+ YAML.load_file("config.yml").merge({
304
+ daemonize: true,
305
+ worker_type: 'process',
306
+ })
307
+ end
308
+ se.run
309
+ ```
310
+
311
+ Send `USR2` signal to reload configuration file.
312
+
313
+
314
+ ## Signals
315
+
316
+ - **TERM:** graceful shutdown
317
+ - **QUIT:** immediate shutdown (available only when `worker_type` is "process")
318
+ - **USR1:** graceful restart
319
+ - **HUP:** immediate restart (available only when `worker_type` is "process")
320
+ - **USR2:** reload config file and reopen log file
321
+ - **INT:** detach process for live restarting (available only when `supervisor` and `enable_detach` parameters are true. otherwise graceful shutdown)
322
+ - **CONT:** dump stacktrace and memory information to /tmp/sigdump-<pid>.log file
323
+
324
+ Immediate shutdown and restart send SIGQUIT signal to worker processes which kills the processes.
325
+ Graceful shutdown and restart call `Worker#stop` method and wait for completion of `Worker#run` method.
326
+
327
+ Note that signals are not supported on Windows.
328
+ You have to use piped command instead of signals on Windows.
329
+ See also **Multiprocess server on Windows and JRuby platforms** section.
330
+
331
+
332
+ ## Utilities
333
+
334
+ ### BlockingFlag
335
+
336
+ `ServerEngine::BlockingFlag` is recommended to stop workers because `stop` method is called by a different thread from the `run` thread.
337
+
338
+ ```ruby
339
+ module MyWorker
340
+ def initialize
341
+ @stop_flag = ServerEngine::BlockingFlag.new
342
+ end
343
+
344
+ def run
345
+ until @stop_flag.wait_for_set(1.0) # or @stop_flag.set?
346
+ logger.info @message
347
+ end
348
+ end
349
+
350
+ def stop
351
+ @stop_flag.set!
352
+ end
353
+ end
354
+
355
+ se = ServerEngine.create(nil, MyWorker) do
356
+ YAML.load_file(config).merge({
357
+ daemonize: true,
358
+ worker_type: 'process'
359
+ })
360
+ end
361
+ se.run
362
+ ```
363
+
364
+
365
+ ### SocketManager
366
+
367
+ `ServerEngine::SocketManager` is a powerful library to listen on the same port across multiple worker processes dynamically.
368
+
369
+ ```ruby
370
+ module MyServer
371
+ def before_run
372
+ @socket_manager_path = ServerEngine::SocketManager::Server.generate_path
373
+ @socket_manager_server = ServerEngine::SocketManager::Server.open(@socket_manager_path)
374
+ end
375
+
376
+ def after_run
377
+ @socket_manager_server.close
378
+ end
379
+
380
+ attr_reader :socket_manager_path
381
+ end
382
+
383
+ module MyWorker
384
+ def initialize
385
+ @stop_flag = ServerEngine::BlockingFlag.new
386
+ @socket_manager = ServerEngine::SocketManager::Client.new(server.socket_manager_path)
387
+ end
388
+
389
+ def run
390
+ lsock = @socket_manager.listen_tcp('0.0.0.0', 12345)
391
+ until @stop
392
+ c = lsock.accept
393
+ c.write "Awesome work!"
394
+ c.close
395
+ end
396
+ end
397
+
398
+ def stop
399
+ @stop = true
400
+ end
401
+ end
402
+
403
+ se = ServerEngine.create(MyServer, MyWorker, {
404
+ daemonize: true,
405
+ log: 'myserver.log',
406
+ pid_path: 'myserver.pid',
407
+ worker_type: 'process',
408
+ workers: 4,
409
+ bind: '0.0.0.0',
410
+ port: 9071,
411
+ })
412
+ se.run
413
+ ```
414
+
415
+ See also [examples](https://github.com/fluent/serverengine/tree/master/examples).
416
+
417
+
418
+ ## Module API
419
+
420
+ Available methods are different depending on `worker_type`. ServerEngine supports 3 worker types:
421
+
422
+ - **embedded**: uses a thread to run worker module (default). This type doesn't support immediate shutdown or immediate restart.
423
+ - **thread**: uses threads to run worker modules. This type doesn't support immediate shutdown or immediate restart.
424
+ - **process**: uses processes to run worker modules. This type doesn't work on Windows or JRuby platform.
425
+ - **spawn**: uses processes to run worker modules. This type works on Windows and JRuby platform but available interface of worker module is limited (See also Worker module section).
426
+
427
+ ### Worker module
428
+
429
+ - interface
430
+ - `initialize` is called in the parent process (or thread) in contrast to the other methods
431
+ - `before_fork` is called before fork for each worker process [`worker_type` = "thread", "process"]
432
+ - `run` is the required method for `worker_type` = "embedded", "thread", "process"
433
+ - `spawn(process_manager)` is the required method for `worker_type` = "spawn". Should call `process_manager.spawn([env,] command... [,options])`.
434
+ - `stop` is called when TERM signal is received [`worker_type` = "embedded", "thread", "process"]
435
+ - `reload` is called when USR2 signal is received [`worker_type` = "embedded", "thread", "process"]
436
+ - `after_start` is called after starting the worker process in the parent process (or thread) [`worker_type` = "thread", "process", "spawn"]
437
+ - api
438
+ - `server` server instance
439
+ - `config` configuration
440
+ - `logger` logger
441
+ - `worker_id` serial id of workers beginning from 0
442
+
443
+
444
+ ### Server module
445
+
446
+ - interface
447
+ - `initialize` is called in the parent process in contrast to the other methods
448
+ - `before_run` is called before starting workers
449
+ - `after_run` is called before shutting down
450
+ - `after_start` is called after starting the server process in the parent process (available if `supervisor` parameter is true)
451
+ - hook points (call `super` in these methods)
452
+ - `reload_config`
453
+ - `stop(stop_graceful)`
454
+ - `restart(stop_graceful)`
455
+ - api
456
+ - `config` configuration
457
+ - `logger` logger
458
+
459
+
460
+ ## List of all configurations
461
+
462
+ - Daemon
463
+ - **daemonize** enables daemonize (default: false)
464
+ - **pid_path** sets the path to pid file (default: don't create pid file)
465
+ - **supervisor** enables supervisor if it's true (default: false)
466
+ - **daemon_process_name** changes process name ($0) of server or supervisor process
467
+ - **chuser** changes execution user
468
+ - **chgroup** changes execution group
469
+ - **chumask** changes umask
470
+ - **daemonize_error_exit_code** exit code when daemonize, changing user or changing group fails (default: 1)
471
+ - Supervisor: available only when `supervisor` parameters is true
472
+ - **server_process_name** changes process name ($0) of server process
473
+ - **restart_server_process** restarts server process when it receives USR1 or HUP signal. (default: false)
474
+ - **enable_detach** enables INT signal (default: true)
475
+ - **exit_on_detach** exits supervisor after detaching server process instead of restarting it (default: false)
476
+ - **disable_reload** disables USR2 signal (default: false)
477
+ - **server_restart_wait** sets wait time before restarting server after last restarting (default: 1.0) [dynamic reloadable]
478
+ - **server_detach_wait** sets wait time before starting live restart (default: 10.0) [dynamic reloadable]
479
+ - Multithread server and multiprocess server: available only when `worker_type` is thread or process
480
+ - **workers** sets number of workers (default: 1) [dynamic reloadable]
481
+ - **start_worker_delay** sets wait time before starting a new worker (default: 0) [dynamic reloadable]
482
+ - **start_worker_delay_rand** randomizes start_worker_delay at this ratio (default: 0.2) [dynamic reloadable]
483
+ - Multiprocess server: available only when `worker_type` is "process"
484
+ - **worker_process_name** changes process name ($0) of workers [dynamic reloadable]
485
+ - **worker_heartbeat_interval** sets interval of heartbeats in seconds (default: 1.0) [dynamic reloadable]
486
+ - **worker_heartbeat_timeout** sets timeout of heartbeat in seconds (default: 180) [dynamic reloadable]
487
+ - **worker_graceful_kill_interval** sets the first interval of TERM signals in seconds (default: 15) [dynamic reloadable]
488
+ - **worker_graceful_kill_interval_increment** sets increment of TERM signal interval in seconds (default: 10) [dynamic reloadable]
489
+ - **worker_graceful_kill_timeout** sets promotion timeout from TERM to QUIT signal in seconds. -1 means no timeout (default: 600) [dynamic reloadable]
490
+ - **worker_immediate_kill_interval** sets the first interval of QUIT signals in seconds (default: 10) [dynamic reloadable]
491
+ - **worker_immediate_kill_interval_increment** sets increment of QUIT signal interval in seconds (default: 10) [dynamic reloadable]
492
+ - **worker_immediate_kill_timeout** sets promotion timeout from QUIT to KILL signal in seconds. -1 means no timeout (default: 600) [dynamic reloadable]
493
+ - **unrecoverable_exit_codes** handles worker processes, which exits with code included in this value, as unrecoverable (not to restart) (default: [])
494
+ - **stop_immediately_at_unrecoverable_exit** stops server immediately if a worker exits with unrecoverable exit status (default: false)
495
+ - Multiprocess spawn server: available only when `worker_type` is "spawn"
496
+ - all parameters of multiprocess server excepting worker_process_name
497
+ - **worker_reload_signal** sets the signal to notice configuration reload to a spawned process. Set nil to disable (default: nil)
498
+ - Logger
499
+ - **log** sets path to log file. Set "-" for STDOUT (default: STDERR) [dynamic reloadable]
500
+ - **log_level** log level: trace, debug, info, warn, error or fatal. (default: debug) [dynamic reloadable]
501
+ - **log_rotate_age** generations to keep rotated log files (default: 5)
502
+ - **log_rotate_size** sets the size to rotate log files (default: 1048576)
503
+ - **log_stdout** hooks STDOUT to log file (default: true)
504
+ - **log_stderr** hooks STDERR to log file (default: true)
505
+ - **logger_class** class of the logger instance (default: ServerEngine::DaemonLogger)
506
+
507
+ ---
508
+
509
+ ```
510
+ Author: Sadayuki Furuhashi
511
+ Copyright: Copyright (c) 2012-2013 Sadayuki Furuhashi
512
+ License: Apache License, Version 2.0
513
+ ```
514
+