Sha256: 5ce61472596381b14f5b42cb05d1a477f028cf55fafd3266eb92e0d0f742f3c7

Contents?: true

Size: 1.84 KB

Versions: 3

Compression:

Stored size: 1.84 KB

Contents

module Datacenter
  class Process

    ATTRIBUTES = [
      :command, 
      :status, 
      :memory, 
      :virtual_memory,
      :cpu,
      :user,
      :name,
      :cpu_usage,
      :mem_usage
    ]

    attr_reader :pid

    def initialize(pid, shell=nil)
      @pid = pid
      @shell = shell || Shell::Local.new
      @cache = Cache.new Datacenter.process_cache_expiration
      @mutex = Mutex.new
    end

    ATTRIBUTES.each do |attribute|
      define_method attribute do
        info[attribute]
      end
    end

    def alive?
      command = %Q{
        if [ -d "#{proc_dir}" ]; then 
          echo -n "true"
        else
          echo -n "false"
        fi
      }

      alive = shell.run(command) == 'true'

      Datacenter.logger.info(self.class) { "pid: #{pid} - ALIVE: #{alive}" } if !alive
      alive
    end

    def send_signal(signal)
      shell.run "kill -s #{signal} #{pid}"
    end

    private

    attr_reader :shell

    def info
      @mutex.synchronize do
        @cache.fetch(:info) do
          status = Hash[proc_file(:status).split("\n").map{ |s| s.split(':').map(&:strip) }]
          ps = shell.run("ps -p #{pid} -o user,pid,pcpu,%mem,vsize,rss,stat,command").split("\n")[1].split
          Hash.new.tap do |info|
            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[6]
            info[:command] = ps[7..-1].reduce { |acum,e| "#{acum} #{e}" }
          end
        end
      end
    end

    def proc_dir
      File.join '/proc', pid.to_s
    end

    def proc_file(name)
      filename = File.join proc_dir, name.to_s
      shell.run "cat #{filename}"
    end

  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
datacenter-0.5.1 lib/datacenter/process.rb
datacenter-0.5.0 lib/datacenter/process.rb
datacenter-0.4.4 lib/datacenter/process.rb