Suggest different variables to use if we want to tunnel both v4 and v6
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / fqdn_rotate.rb
1 #
2 # fqdn_rotate.rb
3 #
4 Puppet::Parser::Functions.newfunction(
5   :fqdn_rotate,
6   :type => :rvalue,
7   :doc => "Usage: `fqdn_rotate(VALUE, [SEED])`. VALUE is required and
8   must be an array or a string. SEED is optional and may be any number
9   or string.
10
11   Rotates VALUE a random number of times, combining the `$fqdn` fact and
12   the value of SEED for repeatable randomness. (That is, each node will
13   get a different random rotation from this function, but a given node's
14   result will be the same every time unless its hostname changes.) Adding
15   a SEED can be useful if you need more than one unrelated rotation.",
16 ) do |args|
17
18   raise(Puppet::ParseError, "fqdn_rotate(): Wrong number of arguments given (#{args.size} for 1)") if args.empty?
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     return offset = Random.new(seed).rand(elements) if defined?(Random) == 'constant' && Random.class == Class
45
46     old_seed = srand(seed)
47     offset = rand(elements)
48     srand(old_seed)
49   end
50   offset.times do
51     result.push result.shift
52   end
53
54   result = string ? result.join : result
55
56   return result
57 end
58
59 # vim: set ts=2 sw=2 et :