-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathdsl.rb
1438 lines (1322 loc) · 46 KB
/
dsl.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
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
383
384
385
386
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# frozen_string_literal: true
require_relative 'const'
require_relative 'util'
module Puma
# The methods that are available for use inside the configuration file.
# These same methods are used in Puma cli and the rack handler
# internally.
#
# Used manually (via CLI class):
#
# config = Configuration.new({}) do |user_config|
# user_config.port 3001
# end
# config.load
#
# puts config.options[:binds] # => "tcp://127.0.0.1:3001"
#
# Used to load file:
#
# $ cat puma_config.rb
# port 3002
#
# Resulting configuration:
#
# config = Configuration.new(config_file: "puma_config.rb")
# config.load
#
# puts config.options[:binds] # => "tcp://127.0.0.1:3002"
#
# You can also find many examples being used by the test suite in
# +test/config+.
#
# Puma v6 adds the option to specify a key name (String or Symbol) to the
# hooks that run inside the forked workers. All the hooks run inside the
# {Puma::Cluster::Worker#run} method.
#
# Previously, the worker index and the LogWriter instance were passed to the
# hook blocks/procs. If a key name is specified, a hash is passed as the last
# parameter. This allows storage of data, typically objects that are created
# before the worker that need to be passed to the hook when the worker is shutdown.
#
# The following hooks have been updated:
#
# | DSL Method | Options Key | Fork Block Location |
# | on_worker_boot | :before_worker_boot | inside, before |
# | on_worker_shutdown | :before_worker_shutdown | inside, after |
# | on_refork | :before_refork | inside |
# | after_refork | :after_refork | inside |
#
class DSL
ON_WORKER_KEY = [String, Symbol].freeze
# Convenience method so logic can be used in CI.
#
# @see ssl_bind
#
def self.ssl_bind_str(host, port, opts)
verify = opts.fetch(:verify_mode, 'none').to_s
tls_str =
if opts[:no_tlsv1_1] then '&no_tlsv1_1=true'
elsif opts[:no_tlsv1] then '&no_tlsv1=true'
else ''
end
ca_additions = "&ca=#{Puma::Util.escape(opts[:ca])}" if ['peer', 'force_peer'].include?(verify)
low_latency_str = opts.key?(:low_latency) ? "&low_latency=#{opts[:low_latency]}" : ''
backlog_str = opts[:backlog] ? "&backlog=#{Integer(opts[:backlog])}" : ''
if defined?(JRUBY_VERSION)
cipher_suites = opts[:ssl_cipher_list] ? "&ssl_cipher_list=#{opts[:ssl_cipher_list]}" : nil # old name
cipher_suites = "#{cipher_suites}&cipher_suites=#{opts[:cipher_suites]}" if opts[:cipher_suites]
protocols = opts[:protocols] ? "&protocols=#{opts[:protocols]}" : nil
keystore_additions = "keystore=#{opts[:keystore]}&keystore-pass=#{opts[:keystore_pass]}"
keystore_additions = "#{keystore_additions}&keystore-type=#{opts[:keystore_type]}" if opts[:keystore_type]
if opts[:truststore]
truststore_additions = "&truststore=#{opts[:truststore]}"
truststore_additions = "#{truststore_additions}&truststore-pass=#{opts[:truststore_pass]}" if opts[:truststore_pass]
truststore_additions = "#{truststore_additions}&truststore-type=#{opts[:truststore_type]}" if opts[:truststore_type]
end
"ssl://#{host}:#{port}?#{keystore_additions}#{truststore_additions}#{cipher_suites}#{protocols}" \
"&verify_mode=#{verify}#{tls_str}#{ca_additions}#{backlog_str}"
else
ssl_cipher_filter = opts[:ssl_cipher_filter] ? "&ssl_cipher_filter=#{opts[:ssl_cipher_filter]}" : nil
ssl_ciphersuites = opts[:ssl_ciphersuites] ? "&ssl_ciphersuites=#{opts[:ssl_ciphersuites]}" : nil
v_flags = (ary = opts[:verification_flags]) ? "&verification_flags=#{Array(ary).join ','}" : nil
cert_flags = (cert = opts[:cert]) ? "cert=#{Puma::Util.escape(cert)}" : nil
key_flags = (key = opts[:key]) ? "&key=#{Puma::Util.escape(key)}" : nil
password_flags = (password_command = opts[:key_password_command]) ? "&key_password_command=#{Puma::Util.escape(password_command)}" : nil
reuse_flag =
if (reuse = opts[:reuse])
if reuse == true
'&reuse=dflt'
elsif reuse.is_a?(Hash) && (reuse.key?(:size) || reuse.key?(:timeout))
val = +''
if (size = reuse[:size]) && Integer === size
val << size.to_s
end
if (timeout = reuse[:timeout]) && Integer === timeout
val << ",#{timeout}"
end
if val.empty?
nil
else
"&reuse=#{val}"
end
else
nil
end
else
nil
end
"ssl://#{host}:#{port}?#{cert_flags}#{key_flags}#{password_flags}#{ssl_cipher_filter}#{ssl_ciphersuites}" \
"#{reuse_flag}&verify_mode=#{verify}#{tls_str}#{ca_additions}#{v_flags}#{backlog_str}#{low_latency_str}"
end
end
def initialize(options, config)
@config = config
@options = options
@plugins = []
end
def _load_from(path)
if path
@path = path
instance_eval(File.read(path), path, 1)
end
ensure
_offer_plugins
end
def _offer_plugins
@plugins.each do |o|
if o.respond_to? :config
@options.shift
o.config self
end
end
@plugins.clear
end
def set_default_host(host)
@options[:default_host] = host
end
def default_host
@options[:default_host] || Configuration::DEFAULTS[:tcp_host]
end
def inject(&blk)
instance_eval(&blk)
end
def get(key,default=nil)
@options[key.to_sym] || default
end
# Load the named plugin for use by this configuration.
#
# @example
# plugin :tmp_restart
#
def plugin(name)
@plugins << @config.load_plugin(name)
end
# Use an object or block as the rack application. This allows the
# configuration file to be the application itself.
#
# @example
# app do |env|
# body = 'Hello, World!'
#
# [
# 200,
# {
# 'Content-Type' => 'text/plain',
# 'Content-Length' => body.length.to_s
# },
# [body]
# ]
# end
#
# @see Puma::Configuration#app
#
def app(obj=nil, &block)
obj ||= block
raise "Provide either a #call'able or a block" unless obj
@options[:app] = obj
end
# Start the Puma control rack application on +url+. This application can
# be communicated with to control the main server. Additionally, you can
# provide an authentication token, so all requests to the control server
# will need to include that token as a query parameter. This allows for
# simple authentication.
#
# Check out {Puma::App::Status} to see what the app has available.
#
# @example
# activate_control_app 'unix:///var/run/pumactl.sock'
# @example
# activate_control_app 'unix:///var/run/pumactl.sock', { auth_token: '12345' }
# @example
# activate_control_app 'unix:///var/run/pumactl.sock', { no_token: true }
#
def activate_control_app(url="auto", opts={})
if url == "auto"
path = Configuration.temp_path
@options[:control_url] = "unix://#{path}"
@options[:control_url_temp] = path
else
@options[:control_url] = url
end
if opts[:no_token]
# We need to use 'none' rather than :none because this value will be
# passed on to an instance of OptionParser, which doesn't support
# symbols as option values.
#
# See: https://github.com/puma/puma/issues/1193#issuecomment-305995488
auth_token = 'none'
else
auth_token = opts[:auth_token]
auth_token ||= Configuration.random_token
end
@options[:control_auth_token] = auth_token
@options[:control_url_umask] = opts[:umask] if opts[:umask]
end
# Load additional configuration from a file.
# Files get loaded later via Configuration#load.
#
# @example
# load 'config/puma/production.rb'
#
def load(file)
@options[:config_files] ||= []
@options[:config_files] << file
end
# Bind the server to +url+. "tcp://", "unix://" and "ssl://" are the only
# accepted protocols. Multiple urls can be bound to, calling +bind+ does
# not overwrite previous bindings.
#
# The default is "tcp://0.0.0.0:9292".
#
# You can use query parameters within the url to specify options:
#
# * Set the socket backlog depth with +backlog+, default is 1024.
# * Set up an SSL certificate with +key+ & +cert+.
# * Set up an SSL certificate for mTLS with +key+, +cert+, +ca+ and +verify_mode+.
# * Set whether to optimize for low latency instead of throughput with
# +low_latency+, default is to not optimize for low latency. This is done
# via +Socket::TCP_NODELAY+.
# * Set socket permissions with +umask+.
#
# @example Backlog depth
# bind 'unix:///var/run/puma.sock?backlog=512'
# @example SSL cert
# bind 'ssl://127.0.0.1:9292?key=key.key&cert=cert.pem'
# @example SSL cert for mutual TLS (mTLS)
# bind 'ssl://127.0.0.1:9292?key=key.key&cert=cert.pem&ca=ca.pem&verify_mode=force_peer'
# @example Disable optimization for low latency
# bind 'tcp://0.0.0.0:9292?low_latency=false'
# @example Socket permissions
# bind 'unix:///var/run/puma.sock?umask=0111'
#
# @see Puma::Runner#load_and_bind
# @see Puma::Cluster#run
#
def bind(url)
@options[:binds] ||= []
@options[:binds] << url
end
def clear_binds!
@options[:binds] = []
end
# Bind to (systemd) activated sockets, regardless of configured binds.
#
# Systemd can present sockets as file descriptors that are already opened.
# By default Puma will use these but only if it was explicitly told to bind
# to the socket. If not, it will close the activated sockets. This means
# all configuration is duplicated.
#
# Binds can contain additional configuration, but only SSL config is really
# relevant since the unix and TCP socket options are ignored.
#
# This means there is a lot of duplicated configuration for no additional
# value in most setups. This method tells the launcher to bind to all
# activated sockets, regardless of existing bind.
#
# To clear configured binds, the value only can be passed. This will clear
# out any binds that may have been configured.
#
# @example Use any systemd activated sockets as well as configured binds
# bind_to_activated_sockets
#
# @example Only bind to systemd activated sockets, ignoring other binds
# bind_to_activated_sockets 'only'
#
def bind_to_activated_sockets(bind=true)
@options[:bind_to_activated_sockets] = bind
end
# Define the TCP port to bind to. Use `bind` for more advanced options.
#
# The default is +9292+.
#
# @example
# port 3000
#
def port(port, host=nil)
host ||= default_host
bind URI::Generic.build(scheme: 'tcp', host: host, port: Integer(port)).to_s
end
# Define how long the tcp socket stays open, if no data has been received.
#
# The default is 30 seconds.
#
# @example
# first_data_timeout 40
#
# @see Puma::Server.new
#
def first_data_timeout(seconds)
@options[:first_data_timeout] = Integer(seconds)
end
# Define how long persistent connections can be idle before Puma closes them.
#
# The default is 20 seconds.
#
# @example
# persistent_timeout 30
#
# @see Puma::Server.new
#
def persistent_timeout(seconds)
@options[:persistent_timeout] = Integer(seconds)
end
# If a new request is not received within this number of seconds, begin shutting down.
#
# The default is +nil+.
#
# @example
# idle_timeout 60
#
# @see Puma::Server.new
#
def idle_timeout(seconds)
@options[:idle_timeout] = Integer(seconds)
end
# Work around leaky apps that leave garbage in Thread locals
# across requests.
#
# The default is +false+.
#
# @example
# clean_thread_locals
#
def clean_thread_locals(which=true)
@options[:clean_thread_locals] = which
end
# When shutting down, drain the accept socket of pending connections and
# process them. This loops over the accept socket until there are no more
# read events and then stops looking and waits for the requests to finish.
#
# @see Puma::Server#graceful_shutdown
#
def drain_on_shutdown(which=true)
@options[:drain_on_shutdown] = which
end
# Set the environment in which the rack's app will run. The value must be
# a string.
#
# The default is "development".
#
# @example
# environment 'production'
#
def environment(environment)
@options[:environment] = environment
end
# How long to wait for threads to stop when shutting them down.
# Specifying :immediately will cause Puma to kill the threads immediately.
# Otherwise the value is the number of seconds to wait.
#
# Puma always waits a few seconds after killing a thread for it to try
# to finish up it's work, even in :immediately mode.
#
# The default is +:forever+.
#
# @see Puma::Server#graceful_shutdown
#
def force_shutdown_after(val=:forever)
i = case val
when :forever
-1
when :immediately
0
else
Float(val)
end
@options[:force_shutdown_after] = i
end
# Code to run before doing a restart. This code should
# close log files, database connections, etc.
#
# This can be called multiple times to add code each time.
#
# @example
# on_restart do
# puts 'On restart...'
# end
#
def on_restart(&block)
process_hook :on_restart, nil, block, 'on_restart'
end
# Command to use to restart Puma. This should be just how to
# load Puma itself (ie. 'ruby -Ilib bin/puma'), not the arguments
# to Puma, as those are the same as the original process.
#
# @example
# restart_command '/u/app/lolcat/bin/restart_puma'
#
def restart_command(cmd)
@options[:restart_cmd] = cmd.to_s
end
# Store the pid of the server in the file at "path".
#
# @example
# pidfile '/u/apps/lolcat/tmp/pids/puma.pid'
#
def pidfile(path)
@options[:pidfile] = path.to_s
end
# Disable request logging, the inverse of `log_requests`.
#
# The default is +true+.
#
# @example
# quiet
#
def quiet(which=true)
@options[:log_requests] = !which
end
# Enable request logging, the inverse of `quiet`.
#
# The default is +false+.
#
# @example
# log_requests
#
def log_requests(which=true)
@options[:log_requests] = which
end
# Pass in a custom logging class instance
#
# @example
# custom_logger Logger.new('t.log')
#
def custom_logger(custom_logger)
@options[:custom_logger] = custom_logger
end
# Show debugging info
#
# The default is +false+.
#
# @example
# debug
#
def debug
@options[:debug] = true
end
# Load +path+ as a rackup file.
#
# The default is "config.ru".
#
# @example
# rackup '/u/apps/lolcat/config.ru'
#
def rackup(path)
@options[:rackup] ||= path.to_s
end
# Allows setting `env['rack.url_scheme']`.
# Only necessary if X-Forwarded-Proto is not being set by your proxy
# Normal values are 'http' or 'https'.
#
def rack_url_scheme(scheme=nil)
@options[:rack_url_scheme] = scheme
end
# Enable HTTP 103 Early Hints responses.
#
# The default is +nil+.
#
# @example
# early_hints
#
def early_hints(answer=true)
@options[:early_hints] = answer
end
# Redirect +STDOUT+ and +STDERR+ to files specified. The +append+ parameter
# specifies whether the output is appended.
#
# The default is +false+.
#
# @example
# stdout_redirect '/app/lolcat/log/stdout', '/app/lolcat/log/stderr'
# @example
# stdout_redirect '/app/lolcat/log/stdout', '/app/lolcat/log/stderr', true
#
def stdout_redirect(stdout=nil, stderr=nil, append=false)
@options[:redirect_stdout] = stdout
@options[:redirect_stderr] = stderr
@options[:redirect_append] = append
end
def log_formatter(&block)
@options[:log_formatter] = block
end
# Configure the number of threads to use to answer requests.
#
# It can be a single fixed number, or a +min+ and a +max+.
#
# The default is the environment variables +PUMA_MIN_THREADS+ / +PUMA_MAX_THREADS+
# (or +MIN_THREADS+ / +MAX_THREADS+ if the +PUMA_+ variables aren't set).
#
# If these environment variables aren't set, the default is "0, 5" in MRI or "0, 16" for other interpreters.
#
# @example
# threads 5
# @example
# threads 0, 16
# @example
# threads 5, 5
#
def threads(min, max = min)
min = Integer(min)
max = Integer(max)
if min > max
raise "The minimum (#{min}) number of threads must be less than or equal to the max (#{max})"
end
if max < 1
raise "The maximum number of threads (#{max}) must be greater than 0"
end
@options[:min_threads] = min
@options[:max_threads] = max
end
# Instead of using +bind+ and manually constructing a URI like:
#
# bind 'ssl://127.0.0.1:9292?key=key_path&cert=cert_path'
#
# you can use the this method.
#
# When binding on localhost you don't need to specify +cert+ and +key+,
# Puma will assume you are using the +localhost+ gem and try to load the
# appropriate files.
#
# When using the options hash parameter, the `reuse:` value is either
# `true`, which sets reuse 'on' with default values, or a hash, with `:size`
# and/or `:timeout` keys, each with integer values.
#
# The `cert:` options hash parameter can be the path to a certificate
# file including all intermediate certificates in PEM format.
#
# The `cert_pem:` options hash parameter can be String containing the
# cerificate and all intermediate certificates in PEM format.
#
# @example
# ssl_bind '127.0.0.1', '9292', {
# cert: path_to_cert,
# key: path_to_key,
# ssl_cipher_filter: cipher_filter, # optional
# ssl_ciphersuites: ciphersuites, # optional
# verify_mode: verify_mode, # default 'none'
# verification_flags: flags, # optional, not supported by JRuby
# reuse: true # optional
# }
#
# @example Using self-signed certificate with the +localhost+ gem:
# ssl_bind '127.0.0.1', '9292'
#
# @example Alternatively, you can provide +cert_pem+ and +key_pem+:
# ssl_bind '127.0.0.1', '9292', {
# cert_pem: File.read(path_to_cert),
# key_pem: File.read(path_to_key),
# reuse: {size: 2_000, timeout: 20} # optional
# }
#
# @example For JRuby, two keys are required: +keystore+ & +keystore_pass+
# ssl_bind '127.0.0.1', '9292', {
# keystore: path_to_keystore,
# keystore_pass: password,
# ssl_cipher_list: cipher_list, # optional
# verify_mode: verify_mode # default 'none'
# }
#
def ssl_bind(host, port, opts = {})
add_pem_values_to_options_store(opts)
bind self.class.ssl_bind_str(host, port, opts)
end
# Use +path+ as the file to store the server info state. This is
# used by +pumactl+ to query and control the server.
#
# @example
# state_path '/u/apps/lolcat/tmp/pids/puma.state'
#
def state_path(path)
@options[:state] = path.to_s
end
# Use +permission+ to restrict permissions for the state file.
#
# @example
# state_permission 0600
#
def state_permission(permission)
@options[:state_permission] = permission
end
# How many worker processes to run. Typically this is set to
# the number of available cores.
#
# The default is the value of the environment variable +WEB_CONCURRENCY+ if
# set, otherwise 0.
#
# @note Cluster mode only.
#
# @example
# workers 2
#
# @see Puma::Cluster
#
def workers(count)
@options[:workers] = count.to_i
end
# Disable warning message when running in cluster mode with a single worker.
#
# Cluster mode has some overhead of running an additional 'control' process
# in order to manage the cluster. If only running a single worker it is
# likely not worth paying that overhead vs running in single mode with
# additional threads instead.
#
# There are some scenarios where running cluster mode with a single worker
# may still be warranted and valid under certain deployment scenarios, see
# https://github.com/puma/puma/issues/2534
#
# Moving from workers = 1 to workers = 0 will save 10-30% of memory use.
#
# The default is +false+.
#
# @note Cluster mode only.
#
# @example
# silence_single_worker_warning
#
def silence_single_worker_warning
@options[:silence_single_worker_warning] = true
end
# Disable warning message when running single mode with callback hook defined.
#
# The default is +false+.
#
# @example
# silence_fork_callback_warning
#
def silence_fork_callback_warning
@options[:silence_fork_callback_warning] = true
end
# Code to run immediately before master process
# forks workers (once on boot). These hooks can block if necessary
# to wait for background operations unknown to Puma to finish before
# the process terminates.
# This can be used to close any connections to remote servers (database,
# Redis, ...) that were opened when preloading the code.
#
# This can be called multiple times to add several hooks.
#
# @note Cluster mode only.
#
# @example
# before_fork do
# puts "Starting workers..."
# end
#
def before_fork(&block)
warn_if_in_single_mode('before_fork')
process_hook :before_fork, nil, block, 'before_fork'
end
# Code to run in a worker when it boots to setup
# the process before booting the app.
#
# This can be called multiple times to add several hooks.
#
# @note Cluster mode only.
#
# @example
# on_worker_boot do
# puts 'Before worker boot...'
# end
#
def on_worker_boot(key = nil, &block)
warn_if_in_single_mode('on_worker_boot')
process_hook :before_worker_boot, key, block, 'on_worker_boot'
end
# Code to run immediately before a worker shuts
# down (after it has finished processing HTTP requests). The worker's
# index is passed as an argument. These hooks
# can block if necessary to wait for background operations unknown
# to Puma to finish before the process terminates.
#
# This can be called multiple times to add several hooks.
#
# @note Cluster mode only.
#
# @example
# on_worker_shutdown do
# puts 'On worker shutdown...'
# end
#
def on_worker_shutdown(key = nil, &block)
warn_if_in_single_mode('on_worker_shutdown')
process_hook :before_worker_shutdown, key, block, 'on_worker_shutdown'
end
# Code to run in the master right before a worker is started. The worker's
# index is passed as an argument.
#
# This can be called multiple times to add several hooks.
#
# @note Cluster mode only.
#
# @example
# on_worker_fork do
# puts 'Before worker fork...'
# end
#
def on_worker_fork(&block)
warn_if_in_single_mode('on_worker_fork')
process_hook :before_worker_fork, nil, block, 'on_worker_fork'
end
# Code to run in the master after a worker has been started. The worker's
# index is passed as an argument.
#
# This is called everytime a worker is to be started.
#
# @note Cluster mode only.
#
# @example
# after_worker_fork do
# puts 'After worker fork...'
# end
#
def after_worker_fork(&block)
warn_if_in_single_mode('after_worker_fork')
process_hook :after_worker_fork, nil, block, 'after_worker_fork'
end
alias_method :after_worker_boot, :after_worker_fork
# Code to run after puma is booted (works for both single and cluster modes).
#
# @example
# on_booted do
# puts 'After booting...'
# end
#
def on_booted(&block)
@config.options[:events].on_booted(&block)
end
# Code to run after puma is stopped (works for both single and cluster modes).
#
# @example
# on_stopped do
# puts 'After stopping...'
# end
#
def on_stopped(&block)
@config.options[:events].on_stopped(&block)
end
# When `fork_worker` is enabled, code to run in Worker 0
# before all other workers are re-forked from this process,
# after the server has temporarily stopped serving requests
# (once per complete refork cycle).
#
# This can be used to trigger extra garbage-collection to maximize
# copy-on-write efficiency, or close any connections to remote servers
# (database, Redis, ...) that were opened while the server was running.
#
# This can be called multiple times to add several hooks.
#
# @note Cluster mode with `fork_worker` enabled only.
#
# @example
# on_refork do
# 3.times {GC.start}
# end
#
def on_refork(key = nil, &block)
warn_if_in_single_mode('on_refork')
process_hook :before_refork, key, block, 'on_refork'
end
# When `fork_worker` is enabled, code to run in Worker 0
# after all other workers are re-forked from this process,
# after the server has temporarily stopped serving requests
# (once per complete refork cycle).
#
# This can be used to re-open any connections to remote servers
# (database, Redis, ...) that were closed via on_refork.
#
# This can be called multiple times to add several hooks.
#
# @note Cluster mode with `fork_worker` enabled only.
#
# @example
# after_refork do
# puts 'After refork...'
# end
#
def after_refork(key = nil, &block)
process_hook :after_refork, key, block, 'after_refork'
end
# Provide a block to be executed just before a thread is added to the thread
# pool. Be careful: while the block executes, thread creation is delayed, and
# probably a request will have to wait too! The new thread will not be added to
# the threadpool until the provided block returns.
#
# Return values are ignored.
# Raising an exception will log a warning.
#
# This hook is useful for doing something when the thread pool grows.
#
# This can be called multiple times to add several hooks.
#
# @example
# on_thread_start do
# puts 'On thread start...'
# end
#
def on_thread_start(&block)
process_hook :before_thread_start, nil, block, 'on_thread_start'
end
# Provide a block to be executed after a thread is trimmed from the thread
# pool. Be careful: while this block executes, Puma's main loop is
# blocked, so no new requests will be picked up.
#
# This hook only runs when a thread in the threadpool is trimmed by Puma.
# It does not run when a thread dies due to exceptions or any other cause.
#
# Return values are ignored.
# Raising an exception will log a warning.
#
# This hook is useful for cleaning up thread local resources when a thread
# is trimmed.
#
# This can be called multiple times to add several hooks.
#
# @example
# on_thread_exit do
# puts 'On thread exit...'
# end
#
def on_thread_exit(&block)
process_hook :before_thread_exit, nil, block, 'on_thread_exit'
end
# Code to run out-of-band when the worker is idle.
# These hooks run immediately after a request has finished
# processing and there are no busy threads on the worker.
# The worker doesn't accept new requests until this code finishes.
#
# This hook is useful for running out-of-band garbage collection
# or scheduling asynchronous tasks to execute after a response.
#
# This can be called multiple times to add several hooks.
#
def out_of_band(&block)
process_hook :out_of_band, nil, block, 'out_of_band'
end
# The directory to operate out of.
#
# The default is the current directory.
#
# @example
# directory '/u/apps/lolcat'
#
def directory(dir)
@options[:directory] = dir.to_s
end
# Preload the application before starting the workers; this conflicts with
# phased restart feature.
#
# The default is +true+ if your app uses more than 1 worker.
#
# @note Cluster mode only.
#
# @example
# preload_app!
#
def preload_app!(answer=true)
@options[:preload_app] = answer
end
# Use +obj+ or +block+ as the low level error handler. This allows the
# configuration file to change the default error on the server.
#
# @example
# lowlevel_error_handler do |err|
# [200, {}, ["error page"]]
# end
#
def lowlevel_error_handler(obj=nil, &block)
obj ||= block
raise "Provide either a #call'able or a block" unless obj
@options[:lowlevel_error_handler] = obj
end
# This option is used to allow your app and its gems to be
# properly reloaded when not using preload.
#
# When set, if Puma detects that it's been invoked in the
# context of Bundler, it will cleanup the environment and
# re-run itself outside the Bundler environment, but directly
# using the files that Bundler has setup.
#
# This means that Puma is now decoupled from your Bundler
# context and when each worker loads, it will be loading a
# new Bundler context and thus can float around as the release
# dictates.
#
# @note This is incompatible with +preload_app!+.
# @note This is only supported for RubyGems 2.2+
#
# @see extra_runtime_dependencies
#
def prune_bundler(answer=true)
@options[:prune_bundler] = answer
end
# Raises a SignalException when SIGTERM is received. In environments where
# SIGTERM is something expected, you can suppress these with this option.