Skip to content

Instantly share code, notes, and snippets.

@trevor-vaughan
Last active September 28, 2021 13:02
Show Gist options
  • Save trevor-vaughan/485749336a0343d57a6b64627b71a240 to your computer and use it in GitHub Desktop.
Save trevor-vaughan/485749336a0343d57a6b64627b71a240 to your computer and use it in GitHub Desktop.
Get application and stack size in a form useful for using with pam_limits
#!/usr/bin/ruby
# Get application and stack size in a form useful for using with pam_limits
require 'json'
PAGE_SIZE = %x(getconf PAGESIZE).to_i
UID = Process.uid
mem_info = Hash.new
max_stack_entry = nil
max_stack_size = 0.0
max_address_entry = nil
max_address_size = 0.0
Dir.glob('/proc/*').each do |dir|
pid = File.basename(dir)
next unless pid =~ /^\d+$/
next unless File.directory?(dir)
unless UID == 0
next unless UID == File.stat("#{dir}/maps").uid
end
command = %x(cat #{dir}/comm).strip
mapfile = %x(cat #{dir}/maps)
address_size = (%x(ps -ho sz #{pid}).strip.to_i * PAGE_SIZE)
stack_size = 0.0
mapfile.each_line do |map|
info = map.split(/\s+/)
mem_start, mem_end = info.first.split('-').map{|x| x.to_i(16)}
mem_size = mem_end - mem_start
path = info.last
if path =~ /\[stack/
stack_size += mem_size
end
end
mem_info[command] ||= Hash.new
mem_info[command][pid] = {
:address_size => {
:b => address_size,
:kb => address_size/1024,
:mb => address_size/(1024**2),
:gb => address_size/(1024**3)
},
:stack_size => {
:b => stack_size,
:kb => stack_size/1024,
:mb => stack_size/(1024**2),
:gb => stack_size/(1024**3)
}
}
if address_size >= max_address_size
max_address_size = address_size
max_address_entry = {
command => mem_info[command]
}
end
if stack_size >= max_stack_size
max_stack_size = stack_size
max_stack_entry = {
command => mem_info[command]
}
end
end
#puts JSON.pretty_generate(mem_info)
puts 'Largest App: '
puts JSON.pretty_generate(max_address_entry)
puts 'Largest Stack: '
puts JSON.pretty_generate(max_stack_entry)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment