PageRenderTime 46ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/unicorn/configurator.rb

https://github.com/flipstone/unicorn
Ruby | 629 lines | 245 code | 48 blank | 336 comment | 24 complexity | 3e4c5ab319c39575d61421195b785c18 MD5 | raw file
Possible License(s): GPL-3.0
  1. # -*- encoding: binary -*-
  2. require 'logger'
  3. require 'unicorn/ssl_configurator'
  4. # Implements a simple DSL for configuring a \Unicorn server.
  5. #
  6. # See http://unicorn.bogomips.org/examples/unicorn.conf.rb and
  7. # http://unicorn.bogomips.org/examples/unicorn.conf.minimal.rb
  8. # example configuration files. An example config file for use with
  9. # nginx is also available at
  10. # http://unicorn.bogomips.org/examples/nginx.conf
  11. #
  12. # See the link:/TUNING.html document for more information on tuning unicorn.
  13. class Unicorn::Configurator
  14. include Unicorn
  15. include Unicorn::SSLConfigurator
  16. # :stopdoc:
  17. attr_accessor :set, :config_file, :after_reload
  18. # used to stash stuff for deferred processing of cli options in
  19. # config.ru after "working_directory" is bound. Do not rely on
  20. # this being around later on...
  21. RACKUP = {
  22. :daemonize => false,
  23. :host => Unicorn::Const::DEFAULT_HOST,
  24. :port => Unicorn::Const::DEFAULT_PORT,
  25. :set_listener => false,
  26. :options => { :listeners => [] }
  27. }
  28. # Default settings for Unicorn
  29. DEFAULTS = {
  30. :timeout => 60,
  31. :logger => Logger.new($stderr),
  32. :worker_processes => 1,
  33. :after_fork => lambda { |server, worker|
  34. server.logger.info("worker=#{worker.nr} spawned pid=#{$$}")
  35. },
  36. :before_fork => lambda { |server, worker|
  37. server.logger.info("worker=#{worker.nr} spawning...")
  38. },
  39. :before_exec => lambda { |server|
  40. server.logger.info("forked child re-executing...")
  41. },
  42. :pid => nil,
  43. :preload_app => false,
  44. :rewindable_input => true, # for Rack 2.x: (Rack::VERSION[0] <= 1),
  45. :client_body_buffer_size => Unicorn::Const::MAX_BODY,
  46. :trust_x_forwarded => true,
  47. }
  48. #:startdoc:
  49. def initialize(defaults = {}) #:nodoc:
  50. self.set = Hash.new(:unset)
  51. @use_defaults = defaults.delete(:use_defaults)
  52. self.config_file = defaults.delete(:config_file)
  53. # after_reload is only used by unicorn_rails, unsupported otherwise
  54. self.after_reload = defaults.delete(:after_reload)
  55. set.merge!(DEFAULTS) if @use_defaults
  56. defaults.each { |key, value| self.__send__(key, value) }
  57. Hash === set[:listener_opts] or
  58. set[:listener_opts] = Hash.new { |hash,key| hash[key] = {} }
  59. Array === set[:listeners] or set[:listeners] = []
  60. reload(false)
  61. end
  62. def reload(merge_defaults = true) #:nodoc:
  63. if merge_defaults && @use_defaults
  64. set.merge!(DEFAULTS) if @use_defaults
  65. end
  66. instance_eval(File.read(config_file), config_file) if config_file
  67. parse_rackup_file
  68. RACKUP[:set_listener] and
  69. set[:listeners] << "#{RACKUP[:host]}:#{RACKUP[:port]}"
  70. # unicorn_rails creates dirs here after working_directory is bound
  71. after_reload.call if after_reload
  72. # working_directory binds immediately (easier error checking that way),
  73. # now ensure any paths we changed are correctly set.
  74. [ :pid, :stderr_path, :stdout_path ].each do |var|
  75. String === (path = set[var]) or next
  76. path = File.expand_path(path)
  77. File.writable?(path) || File.writable?(File.dirname(path)) or \
  78. raise ArgumentError, "directory for #{var}=#{path} not writable"
  79. end
  80. end
  81. def commit!(server, options = {}) #:nodoc:
  82. skip = options[:skip] || []
  83. if ready_pipe = RACKUP.delete(:ready_pipe)
  84. server.ready_pipe = ready_pipe
  85. end
  86. set.each do |key, value|
  87. value == :unset and next
  88. skip.include?(key) and next
  89. server.__send__("#{key}=", value)
  90. end
  91. end
  92. def [](key) # :nodoc:
  93. set[key]
  94. end
  95. # sets object to the +obj+ Logger-like object. The new Logger-like
  96. # object must respond to the following methods:
  97. # * debug
  98. # * info
  99. # * warn
  100. # * error
  101. # * fatal
  102. # The default Logger will log its output to the path specified
  103. # by +stderr_path+. If you're running Unicorn daemonized, then
  104. # you must specify a path to prevent error messages from going
  105. # to /dev/null.
  106. def logger(obj)
  107. %w(debug info warn error fatal).each do |m|
  108. obj.respond_to?(m) and next
  109. raise ArgumentError, "logger=#{obj} does not respond to method=#{m}"
  110. end
  111. set[:logger] = obj
  112. end
  113. # sets after_fork hook to a given block. This block will be called by
  114. # the worker after forking. The following is an example hook which adds
  115. # a per-process listener to every worker:
  116. #
  117. # after_fork do |server,worker|
  118. # # per-process listener ports for debugging/admin:
  119. # addr = "127.0.0.1:#{9293 + worker.nr}"
  120. #
  121. # # the negative :tries parameter indicates we will retry forever
  122. # # waiting on the existing process to exit with a 5 second :delay
  123. # # Existing options for Unicorn::Configurator#listen such as
  124. # # :backlog, :rcvbuf, :sndbuf are available here as well.
  125. # server.listen(addr, :tries => -1, :delay => 5, :backlog => 128)
  126. # end
  127. def after_fork(*args, &block)
  128. set_hook(:after_fork, block_given? ? block : args[0])
  129. end
  130. # sets before_fork got be a given Proc object. This Proc
  131. # object will be called by the master process before forking
  132. # each worker.
  133. def before_fork(*args, &block)
  134. set_hook(:before_fork, block_given? ? block : args[0])
  135. end
  136. # sets the before_exec hook to a given Proc object. This
  137. # Proc object will be called by the master process right
  138. # before exec()-ing the new unicorn binary. This is useful
  139. # for freeing certain OS resources that you do NOT wish to
  140. # share with the reexeced child process.
  141. # There is no corresponding after_exec hook (for obvious reasons).
  142. def before_exec(*args, &block)
  143. set_hook(:before_exec, block_given? ? block : args[0], 1)
  144. end
  145. # sets the timeout of worker processes to +seconds+. Workers
  146. # handling the request/app.call/response cycle taking longer than
  147. # this time period will be forcibly killed (via SIGKILL). This
  148. # timeout is enforced by the master process itself and not subject
  149. # to the scheduling limitations by the worker process. Due the
  150. # low-complexity, low-overhead implementation, timeouts of less
  151. # than 3.0 seconds can be considered inaccurate and unsafe.
  152. #
  153. # For running Unicorn behind nginx, it is recommended to set
  154. # "fail_timeout=0" for in your nginx configuration like this
  155. # to have nginx always retry backends that may have had workers
  156. # SIGKILL-ed due to timeouts.
  157. #
  158. # # See http://wiki.nginx.org/NginxHttpUpstreamModule for more details
  159. # # on nginx upstream configuration:
  160. # upstream unicorn_backend {
  161. # # for UNIX domain socket setups:
  162. # server unix:/path/to/unicorn.sock fail_timeout=0;
  163. #
  164. # # for TCP setups
  165. # server 192.168.0.7:8080 fail_timeout=0;
  166. # server 192.168.0.8:8080 fail_timeout=0;
  167. # server 192.168.0.9:8080 fail_timeout=0;
  168. # }
  169. def timeout(seconds)
  170. set_int(:timeout, seconds, 3)
  171. max = 0x7ffffffe # Rainbows! adds one second to this for safety
  172. set[:timeout] = seconds > max ? max : seconds
  173. end
  174. # sets the current number of worker_processes to +nr+. Each worker
  175. # process will serve exactly one client at a time. You can
  176. # increment or decrement this value at runtime by sending SIGTTIN
  177. # or SIGTTOU respectively to the master process without reloading
  178. # the rest of your Unicorn configuration. See the SIGNALS document
  179. # for more information.
  180. def worker_processes(nr)
  181. set_int(:worker_processes, nr, 1)
  182. end
  183. # sets listeners to the given +addresses+, replacing or augmenting the
  184. # current set. This is for the global listener pool shared by all
  185. # worker processes. For per-worker listeners, see the after_fork example
  186. # This is for internal API use only, do not use it in your Unicorn
  187. # config file. Use listen instead.
  188. def listeners(addresses) # :nodoc:
  189. Array === addresses or addresses = Array(addresses)
  190. addresses.map! { |addr| expand_addr(addr) }
  191. set[:listeners] = addresses
  192. end
  193. # Adds an +address+ to the existing listener set. May be specified more
  194. # than once. +address+ may be an Integer port number for a TCP port, an
  195. # "IP_ADDRESS:PORT" for TCP listeners or a pathname for UNIX domain sockets.
  196. #
  197. # listen 3000 # listen to port 3000 on all TCP interfaces
  198. # listen "127.0.0.1:3000" # listen to port 3000 on the loopback interface
  199. # listen "/tmp/.unicorn.sock" # listen on the given Unix domain socket
  200. # listen "[::1]:3000" # listen to port 3000 on the IPv6 loopback interface
  201. #
  202. # The following options may be specified (but are generally not needed):
  203. #
  204. # [:backlog => number of clients]
  205. #
  206. # This is the backlog of the listen() syscall.
  207. #
  208. # Some operating systems allow negative values here to specify the
  209. # maximum allowable value. In most cases, this number is only
  210. # recommendation and there are other OS-specific tunables and
  211. # variables that can affect this number. See the listen(2)
  212. # syscall documentation of your OS for the exact semantics of
  213. # this.
  214. #
  215. # If you are running unicorn on multiple machines, lowering this number
  216. # can help your load balancer detect when a machine is overloaded
  217. # and give requests to a different machine.
  218. #
  219. # Default: 1024
  220. #
  221. # [:rcvbuf => bytes, :sndbuf => bytes]
  222. #
  223. # Maximum receive and send buffer sizes (in bytes) of sockets.
  224. #
  225. # These correspond to the SO_RCVBUF and SO_SNDBUF settings which
  226. # can be set via the setsockopt(2) syscall. Some kernels
  227. # (e.g. Linux 2.4+) have intelligent auto-tuning mechanisms and
  228. # there is no need (and it is sometimes detrimental) to specify them.
  229. #
  230. # See the socket API documentation of your operating system
  231. # to determine the exact semantics of these settings and
  232. # other operating system-specific knobs where they can be
  233. # specified.
  234. #
  235. # Defaults: operating system defaults
  236. #
  237. # [:tcp_nodelay => true or false]
  238. #
  239. # Disables Nagle's algorithm on TCP sockets if +true+.
  240. #
  241. # Setting this to +true+ can make streaming responses in Rails 3.1
  242. # appear more quickly at the cost of slightly higher bandwidth usage.
  243. # The effect of this option is most visible if nginx is not used,
  244. # but nginx remains highly recommended with \Unicorn.
  245. #
  246. # This has no effect on UNIX sockets.
  247. #
  248. # Default: +true+ (Nagle's algorithm disabled) in \Unicorn,
  249. # +true+ in Rainbows! This defaulted to +false+ in \Unicorn
  250. # 3.x
  251. #
  252. # [:tcp_nopush => true or false]
  253. #
  254. # Enables/disables TCP_CORK in Linux or TCP_NOPUSH in FreeBSD
  255. #
  256. # This prevents partial TCP frames from being sent out and reduces
  257. # wakeups in nginx if it is on a different machine. Since \Unicorn
  258. # is only designed for applications that send the response body
  259. # quickly without keepalive, sockets will always be flushed on close
  260. # to prevent delays.
  261. #
  262. # This has no effect on UNIX sockets.
  263. #
  264. # Default: +false+
  265. # This defaulted to +true+ in \Unicorn 3.4 - 3.7
  266. #
  267. # [:ipv6only => true or false]
  268. #
  269. # This option makes IPv6-capable TCP listeners IPv6-only and unable
  270. # to receive IPv4 queries on dual-stack systems. A separate IPv4-only
  271. # listener is required if this is true.
  272. #
  273. # This option is only available for Ruby 1.9.2 and later.
  274. #
  275. # Enabling this option for the IPv6-only listener and having a
  276. # separate IPv4 listener is recommended if you wish to support IPv6
  277. # on the same TCP port. Otherwise, the value of \env[\"REMOTE_ADDR\"]
  278. # will appear as an ugly IPv4-mapped-IPv6 address for IPv4 clients
  279. # (e.g ":ffff:10.0.0.1" instead of just "10.0.0.1").
  280. #
  281. # Default: Operating-system dependent
  282. #
  283. # [:tries => Integer]
  284. #
  285. # Times to retry binding a socket if it is already in use
  286. #
  287. # A negative number indicates we will retry indefinitely, this is
  288. # useful for migrations and upgrades when individual workers
  289. # are binding to different ports.
  290. #
  291. # Default: 5
  292. #
  293. # [:delay => seconds]
  294. #
  295. # Seconds to wait between successive +tries+
  296. #
  297. # Default: 0.5 seconds
  298. #
  299. # [:umask => mode]
  300. #
  301. # Sets the file mode creation mask for UNIX sockets. If specified,
  302. # this is usually in octal notation.
  303. #
  304. # Typically UNIX domain sockets are created with more liberal
  305. # file permissions than the rest of the application. By default,
  306. # we create UNIX domain sockets to be readable and writable by
  307. # all local users to give them the same accessibility as
  308. # locally-bound TCP listeners.
  309. #
  310. # This has no effect on TCP listeners.
  311. #
  312. # Default: 0000 (world-read/writable)
  313. #
  314. # [:tcp_defer_accept => Integer]
  315. #
  316. # Defer accept() until data is ready (Linux-only)
  317. #
  318. # For Linux 2.6.32 and later, this is the number of retransmits to
  319. # defer an accept() for if no data arrives, but the client will
  320. # eventually be accepted after the specified number of retransmits
  321. # regardless of whether data is ready.
  322. #
  323. # For Linux before 2.6.32, this is a boolean option, and
  324. # accepts are _always_ deferred indefinitely if no data arrives.
  325. # This is similar to <code>:accept_filter => "dataready"</code>
  326. # under FreeBSD.
  327. #
  328. # Specifying +true+ is synonymous for the default value(s) below,
  329. # and +false+ or +nil+ is synonymous for a value of zero.
  330. #
  331. # A value of +1+ is a good optimization for local networks
  332. # and trusted clients. For Rainbows! and Zbatery users, a higher
  333. # value (e.g. +60+) provides more protection against some
  334. # denial-of-service attacks. There is no good reason to ever
  335. # disable this with a +zero+ value when serving HTTP.
  336. #
  337. # Default: 1 retransmit for \Unicorn, 60 for Rainbows! 0.95.0\+
  338. #
  339. # [:accept_filter => String]
  340. #
  341. # defer accept() until data is ready (FreeBSD-only)
  342. #
  343. # This enables either the "dataready" or (default) "httpready"
  344. # accept() filter under FreeBSD. This is intended as an
  345. # optimization to reduce context switches with common GET/HEAD
  346. # requests. For Rainbows! and Zbatery users, this provides
  347. # some protection against certain denial-of-service attacks, too.
  348. #
  349. # There is no good reason to change from the default.
  350. #
  351. # Default: "httpready"
  352. def listen(address, options = {})
  353. address = expand_addr(address)
  354. if String === address
  355. [ :umask, :backlog, :sndbuf, :rcvbuf, :tries ].each do |key|
  356. value = options[key] or next
  357. Integer === value or
  358. raise ArgumentError, "not an integer: #{key}=#{value.inspect}"
  359. end
  360. [ :tcp_nodelay, :tcp_nopush, :ipv6only ].each do |key|
  361. (value = options[key]).nil? and next
  362. TrueClass === value || FalseClass === value or
  363. raise ArgumentError, "not boolean: #{key}=#{value.inspect}"
  364. end
  365. unless (value = options[:delay]).nil?
  366. Numeric === value or
  367. raise ArgumentError, "not numeric: delay=#{value.inspect}"
  368. end
  369. set[:listener_opts][address].merge!(options)
  370. end
  371. set[:listeners] << address
  372. end
  373. # sets the +path+ for the PID file of the unicorn master process
  374. def pid(path); set_path(:pid, path); end
  375. # Enabling this preloads an application before forking worker
  376. # processes. This allows memory savings when using a
  377. # copy-on-write-friendly GC but can cause bad things to happen when
  378. # resources like sockets are opened at load time by the master
  379. # process and shared by multiple children. People enabling this are
  380. # highly encouraged to look at the before_fork/after_fork hooks to
  381. # properly close/reopen sockets. Files opened for logging do not
  382. # have to be reopened as (unbuffered-in-userspace) files opened with
  383. # the File::APPEND flag are written to atomically on UNIX.
  384. #
  385. # In addition to reloading the unicorn-specific config settings,
  386. # SIGHUP will reload application code in the working
  387. # directory/symlink when workers are gracefully restarted when
  388. # preload_app=false (the default). As reloading the application
  389. # sometimes requires RubyGems updates, +Gem.refresh+ is always
  390. # called before the application is loaded (for RubyGems users).
  391. #
  392. # During deployments, care should _always_ be taken to ensure your
  393. # applications are properly deployed and running. Using
  394. # preload_app=false (the default) means you _must_ check if
  395. # your application is responding properly after a deployment.
  396. # Improperly deployed applications can go into a spawn loop
  397. # if the application fails to load. While your children are
  398. # in a spawn loop, it is is possible to fix an application
  399. # by properly deploying all required code and dependencies.
  400. # Using preload_app=true means any application load error will
  401. # cause the master process to exit with an error.
  402. def preload_app(bool)
  403. set_bool(:preload_app, bool)
  404. end
  405. # Toggles making \env[\"rack.input\"] rewindable.
  406. # Disabling rewindability can improve performance by lowering
  407. # I/O and memory usage for applications that accept uploads.
  408. # Keep in mind that the Rack 1.x spec requires
  409. # \env[\"rack.input\"] to be rewindable, so this allows
  410. # intentionally violating the current Rack 1.x spec.
  411. #
  412. # +rewindable_input+ defaults to +true+ when used with Rack 1.x for
  413. # Rack conformance. When Rack 2.x is finalized, this will most
  414. # likely default to +false+ while still conforming to the newer
  415. # (less demanding) spec.
  416. def rewindable_input(bool)
  417. set_bool(:rewindable_input, bool)
  418. end
  419. # The maximum size (in +bytes+) to buffer in memory before
  420. # resorting to a temporary file. Default is 112 kilobytes.
  421. # This option has no effect if "rewindable_input" is set to
  422. # +false+.
  423. def client_body_buffer_size(bytes)
  424. set_int(:client_body_buffer_size, bytes, 0)
  425. end
  426. # Allow redirecting $stderr to a given path. Unlike doing this from
  427. # the shell, this allows the unicorn process to know the path its
  428. # writing to and rotate the file if it is used for logging. The
  429. # file will be opened with the File::APPEND flag and writes
  430. # synchronized to the kernel (but not necessarily to _disk_) so
  431. # multiple processes can safely append to it.
  432. #
  433. # If you are daemonizing and using the default +logger+, it is important
  434. # to specify this as errors will otherwise be lost to /dev/null.
  435. # Some applications/libraries may also triggering warnings that go to
  436. # stderr, and they will end up here.
  437. def stderr_path(path)
  438. set_path(:stderr_path, path)
  439. end
  440. # Same as stderr_path, except for $stdout. Not many Rack applications
  441. # write to $stdout, but any that do will have their output written here.
  442. # It is safe to point this to the same location a stderr_path.
  443. # Like stderr_path, this defaults to /dev/null when daemonized.
  444. def stdout_path(path)
  445. set_path(:stdout_path, path)
  446. end
  447. # sets the working directory for Unicorn. This ensures SIGUSR2 will
  448. # start a new instance of Unicorn in this directory. This may be
  449. # a symlink, a common scenario for Capistrano users. Unlike
  450. # all other Unicorn configuration directives, this binds immediately
  451. # for error checking and cannot be undone by unsetting it in the
  452. # configuration file and reloading.
  453. def working_directory(path)
  454. # just let chdir raise errors
  455. path = File.expand_path(path)
  456. if config_file &&
  457. config_file[0] != ?/ &&
  458. ! File.readable?("#{path}/#{config_file}")
  459. raise ArgumentError,
  460. "config_file=#{config_file} would not be accessible in" \
  461. " working_directory=#{path}"
  462. end
  463. Dir.chdir(path)
  464. Unicorn::HttpServer::START_CTX[:cwd] = ENV["PWD"] = path
  465. end
  466. # Runs worker processes as the specified +user+ and +group+.
  467. # The master process always stays running as the user who started it.
  468. # This switch will occur after calling the after_fork hook, and only
  469. # if the Worker#user method is not called in the after_fork hook
  470. # +group+ is optional and will not change if unspecified.
  471. def user(user, group = nil)
  472. # raises ArgumentError on invalid user/group
  473. Etc.getpwnam(user)
  474. Etc.getgrnam(group) if group
  475. set[:user] = [ user, group ]
  476. end
  477. # Sets whether or not the parser will trust X-Forwarded-Proto and
  478. # X-Forwarded-SSL headers and set "rack.url_scheme" to "https" accordingly.
  479. # Rainbows!/Zbatery installations facing untrusted clients directly
  480. # should set this to +false+. This is +true+ by default as Unicorn
  481. # is designed to only sit behind trusted nginx proxies.
  482. #
  483. # This has never been publically documented and is subject to removal
  484. # in future releases.
  485. def trust_x_forwarded(bool) # :nodoc:
  486. set_bool(:trust_x_forwarded, bool)
  487. end
  488. # expands "unix:path/to/foo" to a socket relative to the current path
  489. # expands pathnames of sockets if relative to "~" or "~username"
  490. # expands "*:port and ":port" to "0.0.0.0:port"
  491. def expand_addr(address) #:nodoc:
  492. return "0.0.0.0:#{address}" if Integer === address
  493. return address unless String === address
  494. case address
  495. when %r{\Aunix:(.*)\z}
  496. File.expand_path($1)
  497. when %r{\A~}
  498. File.expand_path(address)
  499. when %r{\A(?:\*:)?(\d+)\z}
  500. "0.0.0.0:#$1"
  501. when %r{\A\[([a-fA-F0-9:]+)\]\z}, %r/\A((?:\d+\.){3}\d+)\z/
  502. canonicalize_tcp($1, 80)
  503. when %r{\A\[([a-fA-F0-9:]+)\]:(\d+)\z}, %r{\A(.*):(\d+)\z}
  504. canonicalize_tcp($1, $2.to_i)
  505. else
  506. address
  507. end
  508. end
  509. private
  510. def set_int(var, n, min) #:nodoc:
  511. Integer === n or raise ArgumentError, "not an integer: #{var}=#{n.inspect}"
  512. n >= min or raise ArgumentError, "too low (< #{min}): #{var}=#{n.inspect}"
  513. set[var] = n
  514. end
  515. def canonicalize_tcp(addr, port)
  516. packed = Socket.pack_sockaddr_in(port, addr)
  517. port, addr = Socket.unpack_sockaddr_in(packed)
  518. /:/ =~ addr ? "[#{addr}]:#{port}" : "#{addr}:#{port}"
  519. end
  520. def set_path(var, path) #:nodoc:
  521. case path
  522. when NilClass, String
  523. set[var] = path
  524. else
  525. raise ArgumentError
  526. end
  527. end
  528. def check_bool(var, bool) # :nodoc:
  529. case bool
  530. when true, false
  531. return bool
  532. end
  533. raise ArgumentError, "#{var}=#{bool.inspect} not a boolean"
  534. end
  535. def set_bool(var, bool) #:nodoc:
  536. set[var] = check_bool(var, bool)
  537. end
  538. def set_hook(var, my_proc, req_arity = 2) #:nodoc:
  539. case my_proc
  540. when Proc
  541. arity = my_proc.arity
  542. (arity == req_arity) or \
  543. raise ArgumentError,
  544. "#{var}=#{my_proc.inspect} has invalid arity: " \
  545. "#{arity} (need #{req_arity})"
  546. when NilClass
  547. my_proc = DEFAULTS[var]
  548. else
  549. raise ArgumentError, "invalid type: #{var}=#{my_proc.inspect}"
  550. end
  551. set[var] = my_proc
  552. end
  553. # this is called _after_ working_directory is bound. This only
  554. # parses the embedded switches in .ru files
  555. # (for "rackup" compatibility)
  556. def parse_rackup_file # :nodoc:
  557. ru = RACKUP[:file] or return # we only return here in unit tests
  558. # :rails means use (old) Rails autodetect
  559. if ru == :rails
  560. File.readable?('config.ru') or return
  561. ru = 'config.ru'
  562. end
  563. File.readable?(ru) or
  564. raise ArgumentError, "rackup file (#{ru}) not readable"
  565. # it could be a .rb file, too, we don't parse those manually
  566. ru =~ /\.ru\z/ or return
  567. /^#\\(.*)/ =~ File.read(ru) or return
  568. RACKUP[:optparse].parse!($1.split(/\s+/))
  569. if RACKUP[:daemonize]
  570. # unicorn_rails wants a default pid path, (not plain 'unicorn')
  571. if after_reload
  572. spid = set[:pid]
  573. pid('tmp/pids/unicorn.pid') if spid.nil? || spid == :unset
  574. end
  575. unless RACKUP[:daemonized]
  576. Unicorn::Launcher.daemonize!(RACKUP[:options])
  577. RACKUP[:ready_pipe] = RACKUP[:options].delete(:ready_pipe)
  578. end
  579. end
  580. end
  581. end