Class: Thin::Server

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Daemonizable, Logging
Defined in:
lib/thin/server.rb

Overview

The utterly famous Thin HTTP server. It listens for incoming requests through a given backend and forwards all requests to app.

TCP server

Create a new TCP server bound to host:port by specifiying host and port as the first 2 arguments.

Thin::Server.start('0.0.0.0', 3000, app)

UNIX domain server

Create a new UNIX domain socket bound to socket file by specifiying a filename as the first argument. Eg.: /tmp/thin.sock. If the first argument contains a / it will be assumed to be a UNIX socket.

Thin::Server.start('/tmp/thin.sock', app)

Using a custom backend

You can implement your own way to connect the server to its client by creating your own Backend class and passing it as the :backend option.

Thin::Server.start('galaxy://faraway', 1345, app, :backend => Thin::Backends::MyFancyBackend)

Rack application (app)

All requests will be processed through app, which must be a valid Rack adapter. A valid Rack adapter (application) must respond to call(env#Hash) and return an array of [status, headers, body].

Building an app in place

If a block is passed, a Rack::Builder instance will be passed to build the app. So you can do cool stuff like this:

Thin::Server.start('0.0.0.0', 3000) do
  use Rack::CommonLogger
  use Rack::ShowExceptions
  map "/lobster" do
    use Rack::Lint
    run Rack::Lobster.new
  end
end

Controlling with signals

  • INT and TERM: Force shutdown (see Server#stop!)

  • TERM & QUIT calls stop to shutdown gracefully.

  • HUP calls restart to … surprise, restart!

  • USR1 reopen log files.

Signals are processed at one second intervals. Disable signals by passing :signals => false.

Constant Summary collapse

DEFAULT_TIMEOUT =

Default values

30
DEFAULT_HOST =

sec

'0.0.0.0'
DEFAULT_PORT =
3000
DEFAULT_MAXIMUM_CONNECTIONS =
1024
DEFAULT_MAXIMUM_PERSISTENT_CONNECTIONS =
100

Instance Attribute Summary collapse

Attributes included from Daemonizable

#log_file, #pid_file

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Daemonizable

#change_privilege, #daemonize, included, #on_restart, #pid, #restart

Methods included from Logging

debug=, debug?, level, level=, #log, log_debug, #log_debug, log_error, #log_error, #log_info, log_info, log_msg, #silent, #silent=, silent=, silent?, #trace, trace, trace=, trace?, trace_msg

Constructor Details

#initialize(*args, &block) ⇒ Server

Returns a new instance of Server.



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/thin/server.rb', line 100

def initialize(*args, &block)
  host, port, options = DEFAULT_HOST, DEFAULT_PORT, {}
  
  # Guess each parameter by its type so they can be
  # received in any order.
  args.each do |arg|
    case arg
    when Fixnum, /^\d+$/ then port    = arg.to_i
    when String          then host    = arg
    when Hash            then options = arg
    else
      @app = arg if arg.respond_to?(:call)
    end
  end
  
  # Set tag if needed
  self.tag = options[:tag]

  # Try to intelligently select which backend to use.
  @backend = select_backend(host, port, options)
  
  load_cgi_multipart_eof_fix
  
  @backend.server = self
  
  # Set defaults
  @backend.maximum_connections            = DEFAULT_MAXIMUM_CONNECTIONS
  @backend.maximum_persistent_connections = DEFAULT_MAXIMUM_PERSISTENT_CONNECTIONS
  @backend.timeout                        = options[:timeout] || DEFAULT_TIMEOUT
  
  # Allow using Rack builder as a block
  @app = Rack::Builder.new(&block).to_app if block
  
  # If in debug mode, wrap in logger adapter
  @app = Rack::CommonLogger.new(@app) if Logging.debug?
  
  @setup_signals = options[:signals] != false
end

Instance Attribute Details

#appObject

Application (Rack adapter) called with the request that produces the response.



64
65
66
# File 'lib/thin/server.rb', line 64

def app
  @app
end

#backendObject

Backend handling the connections to the clients.



70
71
72
# File 'lib/thin/server.rb', line 70

def backend
  @backend
end

#tagObject

A tag that will show in the process listing



67
68
69
# File 'lib/thin/server.rb', line 67

def tag
  @tag
end

Class Method Details

.start(*args, &block) ⇒ Object

Lil’ shortcut to turn this:

Server.new(...).start

into this:

Server.start(...)


147
148
149
# File 'lib/thin/server.rb', line 147

def self.start(*args, &block)
  new(*args, &block).start!
end

Instance Method Details

#configObject

Configure the server

The process might need to have superuser privilege to configure server with optimal options.



211
212
213
# File 'lib/thin/server.rb', line 211

def config
  @backend.config
end

#nameObject Also known as: to_s

Name of the server and type of backend used. This is also the name of the process in which Thin is running as a daemon.



217
218
219
# File 'lib/thin/server.rb', line 217

def name
  "thin server (#{@backend})" + (tag ? " [#{tag}]" : "")
end

#reopen_logObject

Reopen log file.

Reopen the log file and redirect STDOUT and STDERR to it.



201
202
203
204
205
206
# File 'lib/thin/server.rb', line 201

def reopen_log
  return unless log_file
  file = File.expand_path(log_file)
  log_info "Reopening log file: #{file}"
  Daemonize.redirect_io(file)
end

#running?Boolean

Return true if the server is running and ready to receive requests. Note that the server might still be running and return false when shuting down and waiting for active connections to complete.

Returns:

  • (Boolean)


225
226
227
# File 'lib/thin/server.rb', line 225

def running?
  @backend.running?
end

#startObject Also known as: start!

Start the server and listen for connections.

Raises:

  • (ArgumentError)


152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/thin/server.rb', line 152

def start
  raise ArgumentError, 'app required' unless @app
  
  log_info  "Thin web server (v#{VERSION::STRING} codename #{VERSION::CODENAME})"
  log_debug "Debugging ON"
  trace     "Tracing ON"
  
  log_info "Maximum connections set to #{@backend.maximum_connections}"
  log_info "Listening on #{@backend}, CTRL+C to stop"

  @backend.start { setup_signals if @setup_signals }
end

#stopObject

Gracefull shutdown

Stops the server after processing all current connections. As soon as this method is called, the server stops accepting new requests and waits for all current connections to finish. Calling twice is the equivalent of calling stop!.



171
172
173
174
175
176
177
178
179
180
181
# File 'lib/thin/server.rb', line 171

def stop
  if running?
    @backend.stop
    unless @backend.empty?
      log_info "Waiting for #{@backend.size} connection(s) to finish, "\
               "can take up to #{timeout} sec, CTRL+C to stop now"
    end
  else
    stop!
  end
end

#stop!Object

Force shutdown

Stops the server closing all current connections right away. This doesn’t wait for connection to finish their work and send data. All current requests will be dropped.



187
188
189
190
191
192
193
194
195
196
197
# File 'lib/thin/server.rb', line 187

def stop!
  if @backend.started_reactor?
    log_info "Stopping ..."
  else
    log_info "Stopping Thin ..."
    log_info "Thin was started inside an existing EventMachine.run block."
    log_info "Call `EventMachine.stop` to stop the reactor and quit the process."
  end

  @backend.stop!
end