Module: Maxprocs

Defined in:
lib/maxprocs.rb,
lib/maxprocs/version.rb

Overview

Maxprocs detects CPU quota from Linux cgroups and returns the appropriate number of processors for container environments.

Constant Summary collapse

CGROUP_FILE_PATH =
"/proc/self/cgroup"
CGROUP_V1_QUOTA_PATH =
"/sys/fs/cgroup/cpu/cpu.cfs_quota_us"
CGROUP_V1_PERIOD_PATH =
"/sys/fs/cgroup/cpu/cpu.cfs_period_us"
CGROUP_V2_CONTROLLERS_PATH =
"/sys/fs/cgroup/cgroup.controllers"
CGROUP_V2_CPU_MAX_PATH =
"/sys/fs/cgroup/cpu.max"
VERSION =

: String

"0.1.0"

Class Method Summary collapse

Class Method Details

.cgroup_versionObject

Returns the detected cgroup version.



59
60
61
62
# File 'lib/maxprocs.rb', line 59

def cgroup_version
  ensure_initialized
  @version_cache
end

.count(round: :floor) ⇒ Object

Returns the number of CPUs available, considering cgroup quota.



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/maxprocs.rb', line 27

def count(round: :floor)
  q = quota
  return Etc.nprocessors if q.nil?

  result = case round
  when :ceil
    q.ceil
  else
    q.floor
  end

  [result, 1].max
end

.limited?Boolean

Returns whether CPU is limited by cgroup.

Returns:

  • (Boolean)


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

def limited?
  !quota.nil?
end

.quotaObject

Returns the raw CPU quota as a float.



44
45
46
47
# File 'lib/maxprocs.rb', line 44

def quota
  ensure_initialized
  @quota_cache
end

.reset!Object

Clears the cached values. Useful for testing.



67
68
69
70
71
72
73
# File 'lib/maxprocs.rb', line 67

def reset!
  @mutex.synchronize do
    @quota_cache = nil
    @version_cache = nil
    @initialized = false
  end
end