Class: MemoryLimit

Inherits:
Object
  • Object
show all
Includes:
ClassLogging
Defined in:
lib/unicorn-cuba-base/memory_limit.rb

Defined Under Namespace

Modules: IO Classes: MemoryLimitedExceededError

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from ClassLogging

included, #log, #logger_for

Constructor Details

#initialize(bytes = 256 * 1024 ** 2) ⇒ MemoryLimit

Returns a new instance of MemoryLimit.



30
31
32
33
# File 'lib/unicorn-cuba-base/memory_limit.rb', line 30

def initialize(bytes = 256 * 1024 ** 2)
  log.debug "setting up new memory limit of #{bytes} bytes" if bytes
  @limit = bytes
end

Instance Attribute Details

#limitObject (readonly)

Returns the value of attribute limit.



35
36
37
# File 'lib/unicorn-cuba-base/memory_limit.rb', line 35

def limit
  @limit
end

Instance Method Details

#borrow(bytes, reason = nil) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/unicorn-cuba-base/memory_limit.rb', line 43

def borrow(bytes, reason = nil)
  if reason
    log.debug "borrowing #{bytes} from #{@limit} bytes of limit for #{reason}"
  else
    log.debug "borrowing #{bytes} from #{@limit} bytes of limit"
  end
  
  bytes > @limit and raise MemoryLimitedExceededError
  @limit -= bytes
  bytes
end

#get(reason = nil) ⇒ Object



37
38
39
40
41
# File 'lib/unicorn-cuba-base/memory_limit.rb', line 37

def get(reason = nil)
  yield(@limit).tap do |data|
    borrow(data.bytesize, reason) if data
  end
end

#io(io) ⇒ Object



65
66
67
68
69
# File 'lib/unicorn-cuba-base/memory_limit.rb', line 65

def io(io)
  io.extend MemoryLimit::IO
  io.root_limit self
  io
end

#return(bytes, reason = nil) ⇒ Object



55
56
57
58
59
60
61
62
63
# File 'lib/unicorn-cuba-base/memory_limit.rb', line 55

def return(bytes, reason = nil)
  if reason
    log.debug "returning #{bytes} to #{@limit} bytes of limit used for #{reason}"
  else
    log.debug "returning #{bytes} to #{@limit} bytes of limit"
  end
  @limit += bytes
  bytes
end