Skip to content

Instantly share code, notes, and snippets.

@mowings
Last active September 10, 2018 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mowings/c9c847e07c19da15a612a270064299da to your computer and use it in GitHub Desktop.
Save mowings/c9c847e07c19da15a612a270064299da to your computer and use it in GitHub Desktop.
lxc-top -- Crappy ruby code to show top lxc containers eating cpu
#!/usr/bin/env ruby
require 'yaml'
require 'curses'
include Curses
class Container
attr_accessor :name, :secs, :elapsed, :pct, :last_check, :mem
def initialize(name, secs)
@name = name
@secs = secs
@elapsed = 0
@pct = 0.0
@last_check = nil
@mem = ""
end
end
def show_top(top)
clear
attrset(A_REVERSE)
setpos(0,0)
addstr(" "*80)
setpos(0,0)
addstr("CONTAINER")
setpos(0,48)
addstr("CPU %")
setpos(0, 58)
addstr("MEM")
attrset(A_NORMAL)
top.each_with_index do |c, i|
setpos(i+1, 0)
addstr(c.name)
setpos(i+1, 48)
addstr("#{c.pct}")
setpos(i+1, 58)
addstr(c.mem)
end
refresh
end
def run
container_map = {}
top_items = 0
first = true
if `lxc-ls` == ""
puts "No containers found or you are not root."
exit 3
end
init_screen
Curses.timeout=0
curs_set(0)
setpos(0,0)
addstr("lxc-top initializing...")
refresh
begin
crmode
loop do
top_items = lines - 4
containers = `lxc-ls`
containers.split(' ').each do |container|
return if Curses.getch == 'q'
info = `lxc-info -n #{container}`
m = /CPU use: +([\d.]+)/.match(info)
check_time = Time.now
if m != nil
c = Container.new(container, m[1].to_f)
last = container_map[container]
if last != nil
dur = (check_time - last.last_check).to_f
c.elapsed = c.secs - last.secs
c.pct = (c.elapsed/dur * 100).to_i
end
m = /Memory use: +(.*)/.match(info)
if m != nil
c.mem = m[1]
end
c.last_check = check_time
container_map[container] = c
end
end
# Sort by elapsed time
top = container_map.values.sort(){|l, r| r.elapsed <=> l.elapsed}[0..top_items]
unless first
show_top(top)
end
first = false
sleep 1
end
rescue Interrupt
return
ensure
close_screen
end
end
run
@mowings
Copy link
Author

mowings commented Sep 7, 2018

We show what I think is the right way to calculate cpu pct, but that could be wrong. Should still give you a basic idea of the magnitude of impact on the system of a given container

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment