-
Notifications
You must be signed in to change notification settings - Fork 1
/
process_wrapper.rb
64 lines (53 loc) · 1.58 KB
/
process_wrapper.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
require 'virtus'
class ProcessWrapper
include Virtus.model
attribute :pid, String
attribute :state, String
attribute :name, String
attribute :path, String
attribute :username, String
attribute :cpu, String
attribute :mem, String
attribute :working_time, String
STAT_ATTRIBUTES_MAPPING = {
pid: 0,
name: 1,
state: 2,
utime: 13,
stime: 14,
cutime: 15,
cstime: 16,
starttime: 21
}.freeze
def initialize stat, mem_total, page_size, uptime
@stat = stat
@mem_total = mem_total * 1024
@pid, @name, @state, @utime, @stime, @cutime, @cstime, @starttime = parse_stat
@pid = @pid.to_i
@name.gsub! /[\(\)]/, ''
@path = File.open(['/proc/', @pid.to_i, '/cmdline'].join(''), 'r').each_line.first
@statm = File.open(['/proc/', @pid.to_i, '/statm'].join(''), 'r').each_line.first
@mem = @statm.split(' ')[1].to_f * (page_size / 1024) / mem_total * 100
@working_time = uptime - (@starttime / Process.clock_getres(1, :hertz))
@username = figure_out_username
end
def calculate_cpu process_diff, cpu_diff
@cpu = process_diff / cpu_diff * 100
end
def time
@utime + @stime + @cutime + @cstime
end
def figure_out_username
`uid=$(awk '/^Uid:/{print $2}' /proc/#{@pid}/status); getent passwd "$uid" | awk -F: '{print $1}'`.gsub("\n", '')
end
def parse_stat
@stat
.split(' ')
.each_with_index
.select { |k,v| STAT_ATTRIBUTES_MAPPING.values.include? v }
.map(&:first)
.map do |item|
/[^\d]+/.match(item).nil? ? item.to_f : item
end
end
end