Class: Process::Metrics::Host::Memory::Darwin

Inherits:
Object
  • Object
show all
Defined in:
lib/process/metrics/host/memory/darwin.rb

Overview

Darwin (macOS) implementation of host memory metrics. Uses sysctl (hw.memsize), vm_stat (free + inactive pages), and vm.swapusage for swap.

Class Method Summary collapse

Class Method Details

.captureObject

Capture current host memory. Reads total (hw.memsize), free (vm_stat), and swap (vm.swapusage).



30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/process/metrics/host/memory/darwin.rb', line 30

def self.capture
	total = capture_total
	return nil unless total && total.positive?
	
	free = capture_free
	return nil unless free
	
	free = 0 if free.negative?
	used = [total - free, 0].max
	swap_total, swap_used = capture_swap
	
	return Host::Memory.new(total, used, swap_total, swap_used, nil)
end

.capture_freeObject

Free + inactive (reclaimable) memory in bytes, from vm_stat. Matches Linux MemAvailable semantics.



52
53
54
55
56
57
58
59
60
# File 'lib/process/metrics/host/memory/darwin.rb', line 52

def self.capture_free
	output = IO.popen(["vm_stat"], "r", &:read)
	page_size = output[/page size of (\d+) bytes/, 1]&.to_i
	return nil unless page_size && page_size.positive?
	
	pages_free = output[/Pages free:\s*(\d+)/, 1]&.to_i || 0
	pages_inactive = output[/Pages inactive:\s*(\d+)/, 1]&.to_i || 0
	return (pages_free + pages_inactive) * page_size
end

.capture_swapObject

Swap total and used in bytes, from sysctl vm.swapusage (e.g. "total = 64.00M used = 32.00M free = 32.00M").



64
65
66
67
68
69
70
71
72
73
74
# File 'lib/process/metrics/host/memory/darwin.rb', line 64

def self.capture_swap
	output = IO.popen(["sysctl", "-n", "vm.swapusage"], "r", &:read)
	return [nil, nil] unless output
	
	total_string = output[/total\s*=\s*([\d.]+\s*[KMG]?)/i, 1]
	used_string = output[/used\s*=\s*([\d.]+\s*[KMG]?)/i, 1]
	swap_total = total_string ? parse_swap_size(total_string) : nil
	swap_used = used_string ? parse_swap_size(used_string) : nil
	
	return swap_total, swap_used
end

.capture_totalObject

Total physical RAM in bytes, from sysctl hw.memsize.



46
47
48
# File 'lib/process/metrics/host/memory/darwin.rb', line 46

def self.capture_total
	IO.popen(["sysctl", "-n", "hw.memsize"], "r", &:read)&.strip&.to_i
end

.parse_swap_size(size_string) ⇒ Object

Parse a size string from vm.swapusage (e.g. "1024.00M", "512.00K") into bytes.



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/process/metrics/host/memory/darwin.rb', line 15

def self.parse_swap_size(size_string)
	return nil unless size_string
	
	size_string = size_string.strip
	
	case size_string
	when /([\d.]+)M/i then ($1.to_f * 1024 * 1024).round
	when /([\d.]+)G/i then ($1.to_f * 1024 * 1024 * 1024).round
	when /([\d.]+)K/i then ($1.to_f * 1024).round
	else size_string.to_f.round
	end
end