Class: Puma::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/puma/cli.rb

Overview

Handles invoke a Puma::Server in a command line style.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(argv, events = Events.stdio) ⇒ CLI

Create a new CLI object using argv as the command line arguments.

stdout and stderr can be set to IO-like objects which this object will report status on.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/puma/cli.rb', line 27

def initialize(argv, events=Events.stdio)
  @debug = false
  @argv = argv

  @events = events

  @status = nil
  @runner = nil

  @config = nil

  ENV['NEWRELIC_DISPATCHER'] ||= "puma"

  setup_options
  generate_restart_data

  @binder = Binder.new(@events)
  @binder.import_from_env
end

Instance Attribute Details

#binderObject (readonly)

The Binder object containing the sockets bound to.



48
49
50
# File 'lib/puma/cli.rb', line 48

def binder
  @binder
end

#configObject (readonly)

The Configuration object used.



51
52
53
# File 'lib/puma/cli.rb', line 51

def config
  @config
end

#eventsObject (readonly)

The Events object used to output information.



57
58
59
# File 'lib/puma/cli.rb', line 57

def events
  @events
end

#optionsObject (readonly)

The Hash of options used to configure puma.



54
55
56
# File 'lib/puma/cli.rb', line 54

def options
  @options
end

Instance Method Details

#clustered?Boolean

Returns:

  • (Boolean)


285
286
287
# File 'lib/puma/cli.rb', line 285

def clustered?
  @options[:workers] > 0
end

#debug(str) ⇒ Object



71
72
73
74
75
# File 'lib/puma/cli.rb', line 71

def debug(str)
  if @options[:debug]
    @events.log "- #{str}"
  end
end

#delete_pidfileObject



254
255
256
257
258
# File 'lib/puma/cli.rb', line 254

def delete_pidfile
  if path = @options[:pidfile]
    File.unlink path if File.exists? path
  end
end

#error(str) ⇒ Object

Delegate error to @events



67
68
69
# File 'lib/puma/cli.rb', line 67

def error(str)
  @events.error str
end

#generate_restart_dataObject



295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/puma/cli.rb', line 295

def generate_restart_data
  # Use the same trick as unicorn, namely favor PWD because
  # it will contain an unresolved symlink, useful for when
  # the pwd is /data/releases/current.
  if dir = ENV['PWD']
    s_env = File.stat(dir)
    s_pwd = File.stat(Dir.pwd)

    if s_env.ino == s_pwd.ino and s_env.dev == s_pwd.dev
      @restart_dir = dir
      @options[:worker_directory] = dir
    end
  end

  @restart_dir ||= Dir.pwd

  @original_argv = ARGV.dup

  if defined? Rubinius::OS_ARGV
    @restart_argv = Rubinius::OS_ARGV
  else
    require 'rubygems'

    # if $0 is a file in the current directory, then restart
    # it the same, otherwise add -S on there because it was
    # picked up in PATH.
    #
    if File.exists?($0)
      arg0 = [Gem.ruby, $0]
    else
      arg0 = [Gem.ruby, "-S", $0]
    end

    # Detect and reinject -Ilib from the command line
    lib = File.expand_path "lib"
    arg0[1,0] = ["-I", lib] if $:[0] == lib

    @restart_argv = arg0 + ARGV
  end
end

#graceful_stopObject



289
290
291
292
293
# File 'lib/puma/cli.rb', line 289

def graceful_stop
  @control.stop(true) if @control
  @runner.stop_blocked
  log "- Goodbye!"
end

#haltObject



507
508
509
510
# File 'lib/puma/cli.rb', line 507

def halt
  @status = :halt
  @runner.halt
end

#jruby?Boolean

Returns:

  • (Boolean)


77
78
79
# File 'lib/puma/cli.rb', line 77

def jruby?
  IS_JRUBY
end

#jruby_daemon_startObject



344
345
346
347
# File 'lib/puma/cli.rb', line 344

def jruby_daemon_start
  require 'puma/jruby_restart'
  JRubyRestart.daemon_start(@restart_dir, restart_args)
end

#log(str) ⇒ Object

Delegate log to @events



61
62
63
# File 'lib/puma/cli.rb', line 61

def log(str)
  @events.log str
end

#parse_optionsObject

:nodoc:



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/puma/cli.rb', line 261

def parse_options
  @parser.parse! @argv

  if @argv.last
    @options[:rackup] = @argv.shift
  end

  @config = Puma::Configuration.new @options

  # Advertise the Configuration
  Puma.cli_config = @config

  @config.load

  if clustered?
    unsupported "worker mode not supported on JRuby and Windows",
                jruby? || windows?
  end

  if @options[:daemon] and windows?
    unsupported "daemon mode not supported on Windows"
  end
end

#phased_restartObject



498
499
500
501
# File 'lib/puma/cli.rb', line 498

def phased_restart
  return false unless @runner.respond_to? :phased_restart
  @runner.phased_restart
end

#restartObject



493
494
495
496
# File 'lib/puma/cli.rb', line 493

def restart
  @status = :restart
  @runner.restart
end

#restart!Object



349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
# File 'lib/puma/cli.rb', line 349

def restart!
  @options[:on_restart].each do |block|
    block.call self
  end

  if jruby?
    @binder.listeners.each_with_index do |(str,io),i|
      io.close

      # We have to unlink a unix socket path that's not being used
      uri = URI.parse str
      if uri.scheme == "unix"
        path = "#{uri.host}#{uri.path}"
        File.unlink path
      end
    end

    require 'puma/jruby_restart'
    JRubyRestart.chdir_exec(@restart_dir, restart_args)
  else
    redirects = {:close_others => true}
    @binder.listeners.each_with_index do |(l,io),i|
      ENV["PUMA_INHERIT_#{i}"] = "#{io.to_i}:#{l}"
      redirects[io.to_i] = io.to_i
    end

    argv = restart_args

    Dir.chdir @restart_dir

    argv += [redirects] unless RUBY_VERSION < '1.9'
    Kernel.exec(*argv)
  end
end

#restart_argsObject



336
337
338
339
340
341
342
# File 'lib/puma/cli.rb', line 336

def restart_args
  if cmd = @options[:restart_cmd]
    cmd.split(' ') + @original_argv
  else
    @restart_argv
  end
end

#runObject

Parse the options, load the rackup, start the server and wait for it to finish.



387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# File 'lib/puma/cli.rb', line 387

def run
  begin
    parse_options
  rescue UnsupportedOption
    exit 1
  end

  if dir = @options[:directory]
    Dir.chdir dir
  end

  set_rack_environment

  if clustered?
    @events = PidEvents.new STDOUT, STDERR
    @options[:logger] = @events

    @runner = Cluster.new(self)
  else
    @runner = Single.new(self)
  end

  setup_signals

  if cont = @options[:control_url]
    start_control cont
  end

  @status = :run

  @runner.run

  case @status
  when :halt
    log "* Stopping immediately!"
  when :run, :stop
    graceful_stop
  when :restart
    log "* Restarting..."
    @control.stop true if @control
    restart!
  end
end

#set_rack_environmentObject



242
243
244
245
246
247
248
249
250
251
252
# File 'lib/puma/cli.rb', line 242

def set_rack_environment
  # Try the user option first, then the environment variable,
  # finally default to development

  env = @options[:environment] ||
               ENV['RACK_ENV'] ||
                 'development'

  @options[:environment] = env
  ENV['RACK_ENV'] = env
end

#setup_optionsObject

Build the OptionParser object to handle the available options.



93
94
95
96
97
98
99
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/puma/cli.rb', line 93

def setup_options
  @options = {
    :min_threads => 0,
    :max_threads => 16,
    :quiet => false,
    :debug => false,
    :binds => [],
    :workers => 0,
    :daemon => false,
    :worker_boot => []
  }

  @parser = OptionParser.new do |o|
    o.on "-b", "--bind URI", "URI to bind to (tcp://, unix://, ssl://)" do |arg|
      @options[:binds] << arg
    end

    o.on "-C", "--config PATH", "Load PATH as a config file" do |arg|
      @options[:config_file] = arg
    end

    o.on "--control URL", "The bind url to use for the control server",
                          "Use 'auto' to use temp unix server" do |arg|
      if arg
        @options[:control_url] = arg
      elsif jruby?
        unsupported "No default url available on JRuby"
      end
    end

    o.on "--control-token TOKEN",
         "The token to use as authentication for the control server" do |arg|
      @options[:control_auth_token] = arg
    end

    o.on "-d", "--daemon", "Daemonize the server into the background" do
      @options[:daemon] = true
      @options[:quiet] = true
    end

    o.on "--debug", "Log lowlevel debugging information" do
      @options[:debug] = true
    end

    o.on "--dir DIR", "Change to DIR before starting" do |d|
      @options[:directory] = d.to_s
      @options[:worker_directory] = d.to_s
    end

    o.on "-e", "--environment ENVIRONMENT",
         "The environment to run the Rack app on (default development)" do |arg|
      @options[:environment] = arg
    end

    o.on "-I", "--include PATH", "Specify $LOAD_PATH directories" do |arg|
      $LOAD_PATH.unshift(*arg.split(':'))
    end

    o.on "-p", "--port PORT", "Define what port TCP port to bind to",
                              "Use -b for more advanced options" do |arg|
      @options[:binds] << "tcp://#{Configuration::DefaultTCPHost}:#{arg}"
    end

    o.on "--pidfile PATH", "Use PATH as a pidfile" do |arg|
      @options[:pidfile] = arg
    end

    o.on "--preload", "Preload the app. Cluster mode only" do
      @options[:preload_app] = true
    end

    o.on "-q", "--quiet", "Quiet down the output" do
      @options[:quiet] = true
    end

    o.on "-R", "--restart-cmd CMD",
         "The puma command to run during a hot restart",
         "Default: inferred" do |cmd|
      @options[:restart_cmd] = cmd
    end

    o.on "-S", "--state PATH", "Where to store the state details" do |arg|
      @options[:state] = arg
    end

    o.on '-t', '--threads INT', "min:max threads to use (default 0:16)" do |arg|
      min, max = arg.split(":")
      if max
        @options[:min_threads] = min.to_i
        @options[:max_threads] = max.to_i
      else
        @options[:min_threads] = 0
        @options[:max_threads] = arg.to_i
      end
    end

    o.on "-V", "--version", "Print the version information" do
      puts "puma version #{Puma::Const::VERSION}"
      exit 1
    end

    o.on "-w", "--workers COUNT",
               "Activate cluster mode: How many worker processes to create" do |arg|
      @options[:workers] = arg.to_i
    end

  end

  @parser.banner = "puma <options> <rackup file>"

  @parser.on_tail "-h", "--help", "Show help" do
    log @parser
    exit 1
  end
end

#setup_signalsObject



431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
# File 'lib/puma/cli.rb', line 431

def setup_signals
  begin
    Signal.trap "SIGUSR2" do
      restart
    end
  rescue Exception
    log "*** SIGUSR2 not implemented, signal based restart unavailable!"
  end

  begin
    Signal.trap "SIGTERM" do
      stop
    end
  rescue Exception
    log "*** SIGTERM not implemented, signal based gracefully stopping unavailable!"
  end

  if jruby?
    Signal.trap("INT") do
      graceful_stop
      exit
    end
  end
end

#start_control(str) ⇒ Object



456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
# File 'lib/puma/cli.rb', line 456

def start_control(str)
  require 'puma/app/status'

  uri = URI.parse str

  app = Puma::App::Status.new self

  if token = @options[:control_auth_token]
    app.auth_token = token unless token.empty? or token == :none
  end

  control = Puma::Server.new app, @events
  control.min_threads = 0
  control.max_threads = 1

  case uri.scheme
  when "tcp"
    log "* Starting control server on #{str}"
    control.add_tcp_listener uri.host, uri.port
  when "unix"
    log "* Starting control server on #{str}"
    path = "#{uri.host}#{uri.path}"

    control.add_unix_listener path
  else
    error "Invalid control URI: #{str}"
  end

  control.run
  @control = control
end

#statsObject



503
504
505
# File 'lib/puma/cli.rb', line 503

def stats
  @runner.stats
end

#stopObject



488
489
490
491
# File 'lib/puma/cli.rb', line 488

def stop
  @status = :stop
  @runner.stop
end

#unsupported(str, cond = true) ⇒ Object

Raises:



85
86
87
88
89
# File 'lib/puma/cli.rb', line 85

def unsupported(str, cond=true)
  return unless cond
  @events.error str
  raise UnsupportedOption
end

#windows?Boolean

Returns:

  • (Boolean)


81
82
83
# File 'lib/puma/cli.rb', line 81

def windows?
  RUBY_PLATFORM =~ /mswin32|ming32/
end

#write_pidObject

If configured, write the pid of the current process out to a file.



232
233
234
235
236
237
238
239
240
# File 'lib/puma/cli.rb', line 232

def write_pid
  if path = @options[:pidfile]
    File.open(path, "w") do |f|
      f.puts Process.pid
    end

    at_exit { delete_pidfile }
  end
end

#write_stateObject



209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/puma/cli.rb', line 209

def write_state
  write_pid

  require 'yaml'

  if path = @options[:state]
    state = { "pid" => Process.pid }

    cfg = @config.dup

    [ :logger, :worker_boot, :on_restart ].each { |o| cfg.options.delete o }

    state["config"] = cfg

    File.open(path, "w") do |f|
      f.write state.to_yaml
    end
  end
end