Class: Datacenter::Machine

Inherits:
Object
  • Object
show all
Defined in:
lib/datacenter/machine.rb

Defined Under Namespace

Classes: DiskPartition

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(shell = nil) ⇒ Machine

Returns a new instance of Machine.



6
7
8
# File 'lib/datacenter/machine.rb', line 6

def initialize(shell=nil)
  @shell = shell || Shell::Local.new
end

Instance Attribute Details

#shellObject (readonly)

Returns the value of attribute shell.



4
5
6
# File 'lib/datacenter/machine.rb', line 4

def shell
  @shell
end

Instance Method Details

#coresObject



28
29
30
# File 'lib/datacenter/machine.rb', line 28

def cores
  shell.run('nproc').to_i
end

#cpuObject



24
25
26
# File 'lib/datacenter/machine.rb', line 24

def cpu
  cpuinfo['model name']
end

#disk_partitionsObject



56
57
58
# File 'lib/datacenter/machine.rb', line 56

def disk_partitions
  partitions.map { |p| DiskPartition.new p }
end

#ipsObject



10
11
12
13
14
# File 'lib/datacenter/machine.rb', line 10

def ips
  shell.run('ifconfig')
       .scan(/inet addr:(([0-9]*\.){3}[0-9]*)/)
       .map { |s| s[0] }
end

#memoryObject



32
33
34
# File 'lib/datacenter/machine.rb', line 32

def memory
  meminfo['MemTotal'].to_i / 1024.0
end

#memory_freeObject



36
37
38
# File 'lib/datacenter/machine.rb', line 36

def memory_free
  meminfo['MemFree'].to_i / 1024.0
end

#memory_usedObject



40
41
42
# File 'lib/datacenter/machine.rb', line 40

def memory_used
  memory - memory_free
end

#nameObject



16
17
18
# File 'lib/datacenter/machine.rb', line 16

def name
  shell.run('hostname').strip
end

#osObject



20
21
22
# File 'lib/datacenter/machine.rb', line 20

def os
  @os ||= OS.new shell
end

#processes(filter = '') ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/datacenter/machine.rb', line 60

def processes(filter='')
  if filter.empty?
    command = 'ps aux'
    start = 1
  else
    command = "ps aux | grep \"#{filter}\" | grep -v grep"
    start =  0
  end
  shell.run(command)
       .split("\n")[start..-1]
       .map { |l| Process.new l.split[1].to_i, shell }
end

#swapObject



44
45
46
# File 'lib/datacenter/machine.rb', line 44

def swap
  meminfo['SwapTotal'].to_i / 1024.0
end

#swap_freeObject



48
49
50
# File 'lib/datacenter/machine.rb', line 48

def swap_free
  meminfo['SwapFree'].to_i / 1024.0
end

#swap_usedObject



52
53
54
# File 'lib/datacenter/machine.rb', line 52

def swap_used
  swap - swap_free
end

#top(order, n = 10) ⇒ Object



73
74
75
76
77
78
# File 'lib/datacenter/machine.rb', line 73

def top(order, n=10)
  mappings = {memory: 'rss', pid: 'pid', cpu: '%cpu'}
  shell.run("ps aux --sort -#{mappings[order]} | head -n #{n+1}")
       .split("\n")[1..-1]
       .map { |l| Process.new l.split[1], shell }
end