lib/datacenter/process.rb in datacenter-0.0.1 vs lib/datacenter/process.rb in datacenter-0.1.0
- old
+ new
@@ -11,57 +11,71 @@
:name,
:cpu_usage,
:mem_usage
]
- TIME_CACHE = 2
+ EXPIRATION_TIME = 2
- attr_reader :pid, :machine, :cache
+ attr_reader :pid
- def initialize(pid, machine=nil)
+ def initialize(pid, shell=nil)
@pid = pid
- @machine = machine
- @cache = {:fetched=>0, :content=>[]}
+ @shell = shell || Shell::Local.new
+ @cache = Cache.new EXPIRATION_TIME
end
- def alive?
- !(machine.shell.run 'ls /proc').scan("\n#{pid}\n").empty?
- end
-
ATTRIBUTES.each do |attribute|
define_method attribute do
info[attribute]
end
end
+ def alive?
+ send_signal 0
+ true
+ rescue Errno::ESRCH
+ false
+ end
+
+ def send_signal(signal)
+ out = shell.run("kill -s #{signal} #{pid}")
+ raise Errno::ESRCH, pid.to_s if out.match 'No such process'
+ end
+
+ def stop
+ send_signal :TERM if alive?
+ end
+
+ def kill
+ send_signal :KILL if alive?
+ while alive?; end
+ end
+
private
+ attr_reader :shell
+
def info
- if cache[:content].empty? || (Time.now - cache[:fetched] > TIME_CACHE)
- ps = machine.shell.run('ps aux').scan(/.*#{pid}.*/)[0].split
+ @cache.fetch(:info) do
+ ps = shell.run('ps aux').scan(/.*#{pid}.*/)[0].split
Hash.new.tap do |info|
status = Hash[proc_file(:status).split("\n").map{ |s| s.split(':').map(&:strip) }]
info[:name] = status['Name']
info[:user] = ps[0]
info[:pid] = ps[1]
info[:cpu_usage] = ps[2].to_f
info[:mem_usage] = ps[3].to_f
info[:virtual_memory] = ps[4].to_i / 1024.0
info[:memory] = ps[5].to_i / 1024.0
info[:status] = ps[7]
- info[:command] = ps[10..-1].reduce {|acum,e| "#{acum} #{e}"}
- @cache = {:fetched => Time.now, :content=>info}
+ info[:command] = ps[10..-1].reduce { |acum,e| "#{acum} #{e}" }
end
- else
- cache[:content]
- end
+ end
end
- def proc_dir
- "/proc/#{pid}"
+ def proc_file(name)
+ filename = File.join '/proc', pid.to_s, name.to_s
+ shell.run "cat #{filename}"
end
- def proc_file(file)
- machine.shell.run "cat #{File.join(proc_dir, file.to_s)}"
- end
end
end