fac25fdb3c8d7c0c40bd4e3192bda3cad76fb437
[mirror/dsa-puppet.git] / 3rdparty / modules / memcached / lib / puppet / parser / functions / memcached_max_memory.rb
1 module Puppet::Parser::Functions
2   newfunction(:memcached_max_memory, :type => :rvalue, :doc => <<-EOS
3     Calculate max_memory size from fact 'memsize' and passed argument.
4     EOS
5   ) do |arguments|
6
7     raise(Puppet::ParseError, "memcached_max_memory(): " +
8           "Wrong number of arguments given " +
9           "(#{arguments.size} for 1)") if arguments.size != 1
10
11     arg = arguments[0]
12     memsize = lookupvar('memorysize')
13
14     if arg and !arg.to_s.end_with?('%')
15       result_in_mb = arg.to_i
16     else
17       max_memory_percent = arg ? arg : '95%'
18
19       # Taken from puppetlabs-stdlib to_bytes() function
20       value,prefix = */([0-9.e+-]*)\s*([^bB]?)/.match(memsize)[1,2]
21
22       value = value.to_f
23       case prefix
24         when '' then value = value
25         when 'k' then value *= (1<<10)
26         when 'M' then value *= (1<<20)
27         when 'G' then value *= (1<<30)
28         when 'T' then value *= (1<<40)
29         when 'E' then value *= (1<<50)
30         else raise Puppet::ParseError, "memcached_max_memory(): Unknown prefix #{prefix}"
31       end
32       value = value.to_i
33       result_in_mb = ( (value / (1 << 20) ) * (max_memory_percent.to_f / 100.0) ).floor
34     end
35
36     return result_in_mb
37   end
38 end