defmacro-unicorn 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,387 @@
1
+ # -*- encoding: binary -*-
2
+
3
+ require 'socket'
4
+ require 'logger'
5
+
6
+ module Unicorn
7
+
8
+ # Implements a simple DSL for configuring a Unicorn server.
9
+ #
10
+ # See http://unicorn.bogomips.org/examples/unicorn.conf.rb for an
11
+ # example config file.
12
+ class Configurator < Struct.new(:set, :config_file, :after_reload)
13
+
14
+ # Default settings for Unicorn
15
+ DEFAULTS = {
16
+ :timeout => 60,
17
+ :logger => Logger.new($stderr),
18
+ :worker_processes => 1,
19
+ :after_fork => lambda { |server, worker|
20
+ server.logger.info("worker=#{worker.nr} spawned pid=#{$$}")
21
+ },
22
+ :before_fork => lambda { |server, worker|
23
+ server.logger.info("worker=#{worker.nr} spawning...")
24
+ },
25
+ :before_exec => lambda { |server|
26
+ server.logger.info("forked child re-executing...")
27
+ },
28
+ :pid => nil,
29
+ :preload_app => false,
30
+ }
31
+
32
+ def initialize(defaults = {}) #:nodoc:
33
+ self.set = Hash.new(:unset)
34
+ use_defaults = defaults.delete(:use_defaults)
35
+ self.config_file = defaults.delete(:config_file)
36
+
37
+ # after_reload is only used by unicorn_rails, unsupported otherwise
38
+ self.after_reload = defaults.delete(:after_reload)
39
+
40
+ set.merge!(DEFAULTS) if use_defaults
41
+ defaults.each { |key, value| self.send(key, value) }
42
+ Hash === set[:listener_opts] or
43
+ set[:listener_opts] = Hash.new { |hash,key| hash[key] = {} }
44
+ Array === set[:listeners] or set[:listeners] = []
45
+ reload
46
+ end
47
+
48
+ def reload #:nodoc:
49
+ instance_eval(File.read(config_file), config_file) if config_file
50
+
51
+ # working_directory binds immediately (easier error checking that way),
52
+ # now ensure any paths we changed are correctly set.
53
+ [ :pid, :stderr_path, :stdout_path ].each do |var|
54
+ String === (path = set[var]) or next
55
+ path = File.expand_path(path)
56
+ test(?w, path) || test(?w, File.dirname(path)) or \
57
+ raise ArgumentError, "directory for #{var}=#{path} not writable"
58
+ end
59
+
60
+ # unicorn_rails creates dirs here after working_directory is bound
61
+ after_reload.call if after_reload
62
+ end
63
+
64
+ def commit!(server, options = {}) #:nodoc:
65
+ skip = options[:skip] || []
66
+ set.each do |key, value|
67
+ value == :unset and next
68
+ skip.include?(key) and next
69
+ server.__send__("#{key}=", value)
70
+ end
71
+ end
72
+
73
+ def [](key) # :nodoc:
74
+ set[key]
75
+ end
76
+
77
+ # sets object to the +new+ Logger-like object. The new logger-like
78
+ # object must respond to the following methods:
79
+ # +debug+, +info+, +warn+, +error+, +fatal+, +close+
80
+ def logger(new)
81
+ %w(debug info warn error fatal close).each do |m|
82
+ new.respond_to?(m) and next
83
+ raise ArgumentError, "logger=#{new} does not respond to method=#{m}"
84
+ end
85
+
86
+ set[:logger] = new
87
+ end
88
+
89
+ # sets after_fork hook to a given block. This block will be called by
90
+ # the worker after forking. The following is an example hook which adds
91
+ # a per-process listener to every worker:
92
+ #
93
+ # after_fork do |server,worker|
94
+ # # per-process listener ports for debugging/admin:
95
+ # addr = "127.0.0.1:#{9293 + worker.nr}"
96
+ #
97
+ # # the negative :tries parameter indicates we will retry forever
98
+ # # waiting on the existing process to exit with a 5 second :delay
99
+ # # Existing options for Unicorn::Configurator#listen such as
100
+ # # :backlog, :rcvbuf, :sndbuf are available here as well.
101
+ # server.listen(addr, :tries => -1, :delay => 5, :backlog => 128)
102
+ #
103
+ # # drop permissions to "www-data" in the worker
104
+ # # generally there's no reason to start Unicorn as a priviledged user
105
+ # # as it is not recommended to expose Unicorn to public clients.
106
+ # worker.user('www-data', 'www-data') if Process.euid == 0
107
+ # end
108
+ def after_fork(*args, &block)
109
+ set_hook(:after_fork, block_given? ? block : args[0])
110
+ end
111
+
112
+ # sets before_fork got be a given Proc object. This Proc
113
+ # object will be called by the master process before forking
114
+ # each worker.
115
+ def before_fork(*args, &block)
116
+ set_hook(:before_fork, block_given? ? block : args[0])
117
+ end
118
+
119
+ def app(&block)
120
+ set_hook(:app, block, 0)
121
+ end
122
+
123
+ # sets the before_exec hook to a given Proc object. This
124
+ # Proc object will be called by the master process right
125
+ # before exec()-ing the new unicorn binary. This is useful
126
+ # for freeing certain OS resources that you do NOT wish to
127
+ # share with the reexeced child process.
128
+ # There is no corresponding after_exec hook (for obvious reasons).
129
+ def before_exec(*args, &block)
130
+ set_hook(:before_exec, block_given? ? block : args[0], 1)
131
+ end
132
+
133
+ # sets the timeout of worker processes to +seconds+. Workers
134
+ # handling the request/app.call/response cycle taking longer than
135
+ # this time period will be forcibly killed (via SIGKILL). This
136
+ # timeout is enforced by the master process itself and not subject
137
+ # to the scheduling limitations by the worker process. Due the
138
+ # low-complexity, low-overhead implementation, timeouts of less
139
+ # than 3.0 seconds can be considered inaccurate and unsafe.
140
+ def timeout(seconds)
141
+ Numeric === seconds or raise ArgumentError,
142
+ "not numeric: timeout=#{seconds.inspect}"
143
+ seconds >= 3 or raise ArgumentError,
144
+ "too low: timeout=#{seconds.inspect}"
145
+ set[:timeout] = seconds
146
+ end
147
+
148
+ # sets the current number of worker_processes to +nr+. Each worker
149
+ # process will serve exactly one client at a time. You can
150
+ # increment or decrement this value at runtime by sending SIGTTIN
151
+ # or SIGTTOU respectively to the master process without reloading
152
+ # the rest of your Unicorn configuration. See the SIGNALS document
153
+ # for more information.
154
+ def worker_processes(nr)
155
+ Integer === nr or raise ArgumentError,
156
+ "not an integer: worker_processes=#{nr.inspect}"
157
+ nr >= 0 or raise ArgumentError,
158
+ "not non-negative: worker_processes=#{nr.inspect}"
159
+ set[:worker_processes] = nr
160
+ end
161
+
162
+ # sets listeners to the given +addresses+, replacing or augmenting the
163
+ # current set. This is for the global listener pool shared by all
164
+ # worker processes. For per-worker listeners, see the after_fork example
165
+ # This is for internal API use only, do not use it in your Unicorn
166
+ # config file. Use listen instead.
167
+ def listeners(addresses) # :nodoc:
168
+ Array === addresses or addresses = Array(addresses)
169
+ addresses.map! { |addr| expand_addr(addr) }
170
+ set[:listeners] = addresses
171
+ end
172
+
173
+ # adds an +address+ to the existing listener set.
174
+ #
175
+ # The following options may be specified (but are generally not needed):
176
+ #
177
+ # +:backlog+: this is the backlog of the listen() syscall.
178
+ #
179
+ # Some operating systems allow negative values here to specify the
180
+ # maximum allowable value. In most cases, this number is only
181
+ # recommendation and there are other OS-specific tunables and
182
+ # variables that can affect this number. See the listen(2)
183
+ # syscall documentation of your OS for the exact semantics of
184
+ # this.
185
+ #
186
+ # If you are running unicorn on multiple machines, lowering this number
187
+ # can help your load balancer detect when a machine is overloaded
188
+ # and give requests to a different machine.
189
+ #
190
+ # Default: 1024
191
+ #
192
+ # +:rcvbuf+, +:sndbuf+: maximum receive and send buffer sizes of sockets
193
+ #
194
+ # These correspond to the SO_RCVBUF and SO_SNDBUF settings which
195
+ # can be set via the setsockopt(2) syscall. Some kernels
196
+ # (e.g. Linux 2.4+) have intelligent auto-tuning mechanisms and
197
+ # there is no need (and it is sometimes detrimental) to specify them.
198
+ #
199
+ # See the socket API documentation of your operating system
200
+ # to determine the exact semantics of these settings and
201
+ # other operating system-specific knobs where they can be
202
+ # specified.
203
+ #
204
+ # Defaults: operating system defaults
205
+ #
206
+ # +:tcp_nodelay+: disables Nagle's algorithm on TCP sockets
207
+ #
208
+ # This has no effect on UNIX sockets.
209
+ #
210
+ # Default: operating system defaults (usually Nagle's algorithm enabled)
211
+ #
212
+ # +:tcp_nopush+: enables TCP_CORK in Linux or TCP_NOPUSH in FreeBSD
213
+ #
214
+ # This will prevent partial TCP frames from being sent out.
215
+ # Enabling +tcp_nopush+ is generally not needed or recommended as
216
+ # controlling +tcp_nodelay+ already provides sufficient latency
217
+ # reduction whereas Unicorn does not know when the best times are
218
+ # for flushing corked sockets.
219
+ #
220
+ # This has no effect on UNIX sockets.
221
+ #
222
+ # +:tries+: times to retry binding a socket if it is already in use
223
+ #
224
+ # A negative number indicates we will retry indefinitely, this is
225
+ # useful for migrations and upgrades when individual workers
226
+ # are binding to different ports.
227
+ #
228
+ # Default: 5
229
+ #
230
+ # +:delay+: seconds to wait between successive +tries+
231
+ #
232
+ # Default: 0.5 seconds
233
+ #
234
+ # +:umask+: sets the file mode creation mask for UNIX sockets
235
+ #
236
+ # Typically UNIX domain sockets are created with more liberal
237
+ # file permissions than the rest of the application. By default,
238
+ # we create UNIX domain sockets to be readable and writable by
239
+ # all local users to give them the same accessibility as
240
+ # locally-bound TCP listeners.
241
+ #
242
+ # This has no effect on TCP listeners.
243
+ #
244
+ # Default: 0 (world read/writable)
245
+ def listen(address, opt = {})
246
+ address = expand_addr(address)
247
+ if String === address
248
+ [ :umask, :backlog, :sndbuf, :rcvbuf, :tries ].each do |key|
249
+ value = opt[key] or next
250
+ Integer === value or
251
+ raise ArgumentError, "not an integer: #{key}=#{value.inspect}"
252
+ end
253
+ [ :tcp_nodelay, :tcp_nopush ].each do |key|
254
+ (value = opt[key]).nil? and next
255
+ TrueClass === value || FalseClass === value or
256
+ raise ArgumentError, "not boolean: #{key}=#{value.inspect}"
257
+ end
258
+ unless (value = opt[:delay]).nil?
259
+ Numeric === value or
260
+ raise ArgumentError, "not numeric: delay=#{value.inspect}"
261
+ end
262
+ set[:listener_opts][address].merge!(opt)
263
+ end
264
+
265
+ set[:listeners] << address
266
+ end
267
+
268
+ # sets the +path+ for the PID file of the unicorn master process
269
+ def pid(path); set_path(:pid, path); end
270
+
271
+ # Enabling this preloads an application before forking worker
272
+ # processes. This allows memory savings when using a
273
+ # copy-on-write-friendly GC but can cause bad things to happen when
274
+ # resources like sockets are opened at load time by the master
275
+ # process and shared by multiple children. People enabling this are
276
+ # highly encouraged to look at the before_fork/after_fork hooks to
277
+ # properly close/reopen sockets. Files opened for logging do not
278
+ # have to be reopened as (unbuffered-in-userspace) files opened with
279
+ # the File::APPEND flag are written to atomically on UNIX.
280
+ #
281
+ # In addition to reloading the unicorn-specific config settings,
282
+ # SIGHUP will reload application code in the working
283
+ # directory/symlink when workers are gracefully restarted.
284
+ def preload_app(bool)
285
+ case bool
286
+ when TrueClass, FalseClass
287
+ set[:preload_app] = bool
288
+ else
289
+ raise ArgumentError, "preload_app=#{bool.inspect} not a boolean"
290
+ end
291
+ end
292
+
293
+ # Allow redirecting $stderr to a given path. Unlike doing this from
294
+ # the shell, this allows the unicorn process to know the path its
295
+ # writing to and rotate the file if it is used for logging. The
296
+ # file will be opened with the File::APPEND flag and writes
297
+ # synchronized to the kernel (but not necessarily to _disk_) so
298
+ # multiple processes can safely append to it.
299
+ def stderr_path(path)
300
+ set_path(:stderr_path, path)
301
+ end
302
+
303
+ # Same as stderr_path, except for $stdout
304
+ def stdout_path(path)
305
+ set_path(:stdout_path, path)
306
+ end
307
+
308
+ # sets the working directory for Unicorn. This ensures USR2 will
309
+ # start a new instance of Unicorn in this directory. This may be
310
+ # a symlink.
311
+ def working_directory(path)
312
+ # just let chdir raise errors
313
+ path = File.expand_path(path)
314
+ if config_file &&
315
+ config_file[0] != ?/ &&
316
+ ! test(?r, "#{path}/#{config_file}")
317
+ raise ArgumentError,
318
+ "config_file=#{config_file} would not be accessible in" \
319
+ " working_directory=#{path}"
320
+ end
321
+ Dir.chdir(path)
322
+ Server::START_CTX[:cwd] = ENV["PWD"] = path
323
+ end
324
+
325
+ # Runs worker processes as the specified +user+ and +group+.
326
+ # The master process always stays running as the user who started it.
327
+ # This switch will occur after calling the after_fork hook, and only
328
+ # if the Worker#user method is not called in the after_fork hook
329
+ def user(user, group = nil)
330
+ # raises ArgumentError on invalid user/group
331
+ Etc.getpwnam(user)
332
+ Etc.getgrnam(group) if group
333
+ set[:user] = [ user, group ]
334
+ end
335
+
336
+ # expands "unix:path/to/foo" to a socket relative to the current path
337
+ # expands pathnames of sockets if relative to "~" or "~username"
338
+ # expands "*:port and ":port" to "0.0.0.0:port"
339
+ def expand_addr(address) #:nodoc
340
+ return "0.0.0.0:#{address}" if Integer === address
341
+ return address unless String === address
342
+
343
+ case address
344
+ when %r{\Aunix:(.*)\z}
345
+ File.expand_path($1)
346
+ when %r{\A~}
347
+ File.expand_path(address)
348
+ when %r{\A(?:\*:)?(\d+)\z}
349
+ "0.0.0.0:#$1"
350
+ when %r{\A(.*):(\d+)\z}
351
+ # canonicalize the name
352
+ packed = Socket.pack_sockaddr_in($2.to_i, $1)
353
+ Socket.unpack_sockaddr_in(packed).reverse!.join(':')
354
+ else
355
+ address
356
+ end
357
+ end
358
+
359
+ private
360
+
361
+ def set_path(var, path) #:nodoc:
362
+ case path
363
+ when NilClass, String
364
+ set[var] = path
365
+ else
366
+ raise ArgumentError
367
+ end
368
+ end
369
+
370
+ def set_hook(var, my_proc, req_arity = 2) #:nodoc:
371
+ case my_proc
372
+ when Proc
373
+ arity = my_proc.arity
374
+ (arity == req_arity) or \
375
+ raise ArgumentError,
376
+ "#{var}=#{my_proc.inspect} has invalid arity: " \
377
+ "#{arity} (need #{req_arity})"
378
+ when NilClass
379
+ my_proc = DEFAULTS[var]
380
+ else
381
+ raise ArgumentError, "invalid type: #{var}=#{my_proc.inspect}"
382
+ end
383
+ set[var] = my_proc
384
+ end
385
+
386
+ end
387
+ end
@@ -0,0 +1,20 @@
1
+ # -*- encoding: binary -*-
2
+
3
+ module Unicorn
4
+
5
+ # Frequently used constants when constructing requests or responses. Many times
6
+ # the constant just refers to a string with the same contents. Using these constants
7
+ # gave about a 3% to 10% performance improvement over using the strings directly.
8
+ # Symbols did not really improve things much compared to constants.
9
+ module Const
10
+ UNICORN_VERSION="0.97.0"
11
+
12
+ DEFAULT_HOST = "0.0.0.0" # default TCP listen host address
13
+ DEFAULT_PORT = 8080 # default TCP listen port
14
+ DEFAULT_LISTEN = "#{DEFAULT_HOST}:#{DEFAULT_PORT}"
15
+
16
+ # The basic max request size we'll try to read.
17
+ CHUNK_SIZE=(16 * 1024)
18
+ end
19
+
20
+ end
@@ -0,0 +1,65 @@
1
+ # -*- encoding: binary -*-
2
+
3
+ $stdout.sync = $stderr.sync = true
4
+ $stdin.binmode
5
+ $stdout.binmode
6
+ $stderr.binmode
7
+
8
+ require 'unicorn'
9
+
10
+ class Unicorn::Launcher
11
+
12
+ # We don't do a lot of standard daemonization stuff:
13
+ # * umask is whatever was set by the parent process at startup
14
+ # and can be set in config.ru and config_file, so making it
15
+ # 0000 and potentially exposing sensitive log data can be bad
16
+ # policy.
17
+ # * don't bother to chdir("/") here since unicorn is designed to
18
+ # run inside APP_ROOT. Unicorn will also re-chdir() to
19
+ # the directory it was started in when being re-executed
20
+ # to pickup code changes if the original deployment directory
21
+ # is a symlink or otherwise got replaced.
22
+ def self.daemonize!(options = nil)
23
+ $stdin.reopen("/dev/null")
24
+
25
+ # We only start a new process group if we're not being reexecuted
26
+ # and inheriting file descriptors from our parent
27
+ unless ENV['UNICORN_FD']
28
+ if options
29
+ # grandparent - reads pipe, exits when master is ready
30
+ # \_ parent - exits immediately ASAP
31
+ # \_ unicorn master - writes to pipe when ready
32
+
33
+ rd, wr = IO.pipe
34
+ grandparent = $$
35
+ if fork
36
+ wr.close # grandparent does not write
37
+ else
38
+ rd.close # unicorn master does not read
39
+ Process.setsid
40
+ exit if fork # parent dies now
41
+ end
42
+
43
+ if grandparent == $$
44
+ # this will block until Server#join runs (or it dies)
45
+ master_pid = (rd.readpartial(16) rescue nil).to_i
46
+ unless master_pid > 1
47
+ warn "master failed to start, check stderr log for details"
48
+ exit!(1)
49
+ end
50
+ exit 0
51
+ else # unicorn master process
52
+ options[:ready_pipe] = wr
53
+ end
54
+ else # backwards compat
55
+ exit if fork
56
+ Process.setsid
57
+ exit if fork
58
+ end
59
+ # $stderr/$stderr can/will be redirected separately in the Unicorn config
60
+ Unicorn::Configurator::DEFAULTS[:stderr_path] = "/dev/null"
61
+ Unicorn::Configurator::DEFAULTS[:stdout_path] = "/dev/null"
62
+ end
63
+ end
64
+
65
+ end
@@ -0,0 +1,150 @@
1
+ # -*- encoding: binary -*-
2
+
3
+ require 'socket'
4
+
5
+ module Unicorn
6
+ module SocketHelper
7
+ include Socket::Constants
8
+
9
+ # configure platform-specific options (only tested on Linux 2.6 so far)
10
+ case RUBY_PLATFORM
11
+ when /linux/
12
+ # from /usr/include/linux/tcp.h
13
+ TCP_DEFER_ACCEPT = 9 unless defined?(TCP_DEFER_ACCEPT)
14
+
15
+ # do not send out partial frames (Linux)
16
+ TCP_CORK = 3 unless defined?(TCP_CORK)
17
+ when /freebsd(([1-4]\..{1,2})|5\.[0-4])/
18
+ # Do nothing for httpready, just closing a bug when freebsd <= 5.4
19
+ TCP_NOPUSH = 4 unless defined?(TCP_NOPUSH) # :nodoc:
20
+ when /freebsd/
21
+ # do not send out partial frames (FreeBSD)
22
+ TCP_NOPUSH = 4 unless defined?(TCP_NOPUSH)
23
+
24
+ # Use the HTTP accept filter if available.
25
+ # The struct made by pack() is defined in /usr/include/sys/socket.h
26
+ # as accept_filter_arg
27
+ unless `/sbin/sysctl -nq net.inet.accf.http`.empty?
28
+ # set set the "httpready" accept filter in FreeBSD if available
29
+ # if other protocols are to be supported, this may be
30
+ # String#replace-d with "dataready" arguments instead
31
+ FILTER_ARG = ['httpready', nil].pack('a16a240')
32
+ end
33
+ end
34
+
35
+ def set_tcp_sockopt(sock, opt)
36
+
37
+ # highly portable, but off by default because we don't do keepalive
38
+ if defined?(TCP_NODELAY) && ! (val = opt[:tcp_nodelay]).nil?
39
+ sock.setsockopt(IPPROTO_TCP, TCP_NODELAY, val ? 1 : 0)
40
+ end
41
+
42
+ unless (val = opt[:tcp_nopush]).nil?
43
+ val = val ? 1 : 0
44
+ if defined?(TCP_CORK) # Linux
45
+ sock.setsockopt(IPPROTO_TCP, TCP_CORK, val)
46
+ elsif defined?(TCP_NOPUSH) # TCP_NOPUSH is untested (FreeBSD)
47
+ sock.setsockopt(IPPROTO_TCP, TCP_NOPUSH, val)
48
+ end
49
+ end
50
+
51
+ # No good reason to ever have deferred accepts off
52
+ if defined?(TCP_DEFER_ACCEPT)
53
+ sock.setsockopt(SOL_TCP, TCP_DEFER_ACCEPT, 1)
54
+ elsif defined?(SO_ACCEPTFILTER) && defined?(FILTER_ARG)
55
+ sock.setsockopt(SOL_SOCKET, SO_ACCEPTFILTER, FILTER_ARG)
56
+ end
57
+ end
58
+
59
+ def set_server_sockopt(sock, opt)
60
+ opt ||= {}
61
+
62
+ TCPSocket === sock and set_tcp_sockopt(sock, opt)
63
+
64
+ if opt[:rcvbuf] || opt[:sndbuf]
65
+ log_buffer_sizes(sock, "before: ")
66
+ sock.setsockopt(SOL_SOCKET, SO_RCVBUF, opt[:rcvbuf]) if opt[:rcvbuf]
67
+ sock.setsockopt(SOL_SOCKET, SO_SNDBUF, opt[:sndbuf]) if opt[:sndbuf]
68
+ log_buffer_sizes(sock, " after: ")
69
+ end
70
+ sock.listen(opt[:backlog] || 1024)
71
+ rescue => e
72
+ if respond_to?(:logger)
73
+ logger.error "error setting socket options: #{e.inspect}"
74
+ logger.error e.backtrace.join("\n")
75
+ end
76
+ end
77
+
78
+ def log_buffer_sizes(sock, pfx = '')
79
+ respond_to?(:logger) or return
80
+ rcvbuf = sock.getsockopt(SOL_SOCKET, SO_RCVBUF).unpack('i')
81
+ sndbuf = sock.getsockopt(SOL_SOCKET, SO_SNDBUF).unpack('i')
82
+ logger.info "#{pfx}#{sock_name(sock)} rcvbuf=#{rcvbuf} sndbuf=#{sndbuf}"
83
+ end
84
+
85
+ # creates a new server, socket. address may be a HOST:PORT or
86
+ # an absolute path to a UNIX socket. address can even be a Socket
87
+ # object in which case it is immediately returned
88
+ def bind_listen(address = '0.0.0.0:8080', opt = {})
89
+ return address unless String === address
90
+
91
+ sock = if address[0] == ?/
92
+ if File.exist?(address)
93
+ if File.socket?(address)
94
+ if self.respond_to?(:logger)
95
+ logger.info "unlinking existing socket=#{address}"
96
+ end
97
+ File.unlink(address)
98
+ else
99
+ raise ArgumentError,
100
+ "socket=#{address} specified but it is not a socket!"
101
+ end
102
+ end
103
+ old_umask = File.umask(opt[:umask] || 0)
104
+ begin
105
+ UNIXServer.new(address)
106
+ ensure
107
+ File.umask(old_umask)
108
+ end
109
+ elsif address =~ /^(\d+\.\d+\.\d+\.\d+):(\d+)$/
110
+ TCPServer.new($1, $2.to_i)
111
+ else
112
+ raise ArgumentError, "Don't know how to bind: #{address}"
113
+ end
114
+ set_server_sockopt(sock, opt)
115
+ sock
116
+ end
117
+
118
+ # Returns the configuration name of a socket as a string. sock may
119
+ # be a string value, in which case it is returned as-is
120
+ # Warning: TCP sockets may not always return the name given to it.
121
+ def sock_name(sock)
122
+ case sock
123
+ when String then sock
124
+ when UNIXServer
125
+ Socket.unpack_sockaddr_un(sock.getsockname)
126
+ when TCPServer
127
+ Socket.unpack_sockaddr_in(sock.getsockname).reverse!.join(':')
128
+ when Socket
129
+ begin
130
+ Socket.unpack_sockaddr_in(sock.getsockname).reverse!.join(':')
131
+ rescue ArgumentError
132
+ Socket.unpack_sockaddr_un(sock.getsockname)
133
+ end
134
+ else
135
+ raise ArgumentError, "Unhandled class #{sock.class}: #{sock.inspect}"
136
+ end
137
+ end
138
+
139
+ # casts a given Socket to be a TCPServer or UNIXServer
140
+ def server_cast(sock)
141
+ begin
142
+ Socket.unpack_sockaddr_in(sock.getsockname)
143
+ TCPServer.for_fd(sock.fileno)
144
+ rescue ArgumentError
145
+ UNIXServer.for_fd(sock.fileno)
146
+ end
147
+ end
148
+
149
+ end # module SocketHelper
150
+ end # module Unicorn