Update stdlib
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / fqdn_rotate.rb
1 #
2 # fqdn_rotate.rb
3 #
4
5 Puppet::Parser::Functions.newfunction(
6   :fqdn_rotate,
7   :type => :rvalue,
8   :doc => "Usage: `fqdn_rotate(VALUE, [SEED])`. VALUE is required and
9   must be an array or a string. SEED is optional and may be any number
10   or string.
11
12   Rotates VALUE a random number of times, combining the `$fqdn` fact and
13   the value of SEED for repeatable randomness. (That is, each node will
14   get a different random rotation from this function, but a given node's
15   result will be the same every time unless its hostname changes.) Adding
16   a SEED can be useful if you need more than one unrelated rotation.") do |args|
17
18     raise(Puppet::ParseError, "fqdn_rotate(): Wrong number of arguments given (#{args.size} for 1)") if args.size < 1
19
20     value = args.shift
21     require 'digest/md5'
22
23     unless value.is_a?(Array) || value.is_a?(String)
24       raise(Puppet::ParseError, 'fqdn_rotate(): Requires either array or string to work with')
25     end
26
27     result = value.clone
28
29     string = value.is_a?(String) ? true : false
30
31     # Check whether it makes sense to rotate ...
32     return result if result.size <= 1
33
34     # We turn any string value into an array to be able to rotate ...
35     result = string ? result.split('') : result
36
37     elements = result.size
38
39     seed = Digest::MD5.hexdigest([lookupvar('::fqdn'),args].join(':')).hex
40     # deterministic_rand() was added in Puppet 3.2.0; reimplement if necessary
41     if Puppet::Util.respond_to?(:deterministic_rand)
42       offset = Puppet::Util.deterministic_rand(seed, elements).to_i
43     else
44       if defined?(Random) == 'constant' && Random.class == Class
45         offset = Random.new(seed).rand(elements)
46       else
47         old_seed = srand(seed)
48         offset = rand(elements)
49         srand(old_seed)
50       end
51     end
52     offset.times {
53        result.push result.shift
54     }
55
56     result = string ? result.join : result
57
58     return result
59 end
60
61 # vim: set ts=2 sw=2 et :