]> git.openstreetmap.org Git - rails.git/blob - config/initializers/memory_limits.rb
Fix most auto-correctable rubocop issues
[rails.git] / config / initializers / memory_limits.rb
1 # Setup any specified hard limit on the virtual size of the process
2 if defined?(HARD_MEMORY_LIMIT) && defined?(PhusionPassenger) && Process.const_defined?(:RLIMIT_AS)
3   Process.setrlimit Process::RLIMIT_AS, HARD_MEMORY_LIMIT * 1024 * 1024, Process::RLIM_INFINITY
4 end
5
6 # If we're running under passenger and a soft memory limit is
7 # configured then setup some rack middleware to police the limit
8 if defined?(SOFT_MEMORY_LIMIT) && defined?(PhusionPassenger)
9   # Define some rack middleware to police the soft memory limit
10   class MemoryLimit
11     def initialize(app)
12       @app = app
13     end
14
15     def call(env)
16       # Process this requst
17       status, headers, body = @app.call(env)
18
19       # Restart if we've hit our memory limit
20       if resident_size > SOFT_MEMORY_LIMIT
21         Process.kill("USR1", Process.pid)
22       end
23
24       # Return the result of this request
25       [status, headers, body]
26     end
27
28     private
29
30     def resident_size
31       # Read statm to get process sizes. Format is
32       #   Size RSS Shared Text Lib Data
33       fields = File.open("/proc/self/statm") do |file|
34         fields = file.gets.split(" ")
35       end
36
37       # Return resident size in megabytes
38       fields[1].to_i / 256
39     end
40   end
41
42   # Install the memory limit checker
43   Rails.configuration.middleware.use MemoryLimit
44 end