8764f1b8f0488b0b098036b2bec3246e6e34426d
[mirror/dsa-puppet.git] / 3rdparty / modules / openstacklib / lib / puppet / parser / functions / os_database_connection.rb
1 require 'puppet/parser/functions'
2
3 Puppet::Parser::Functions.newfunction(:os_database_connection,
4                                       :type => :rvalue,
5                                       :doc => <<-EOS
6 This function builds a os_database_connection string from various parameters.
7 EOS
8 ) do |arguments|
9
10   require 'uri'
11
12   if (arguments.size != 1) then
13     raise(Puppet::ParseError, "os_database_connection(): Wrong number of arguments " +
14       "given (#{arguments.size} for 1)")
15   end
16
17   v = arguments[0]
18   klass = v.class
19
20   unless klass == Hash
21     raise(Puppet::ParseError, "os_database_connection(): Requires an hash, got #{klass}")
22   end
23
24   v.keys.each do |key|
25     unless (v[key].class == String) or (v[key] == :undef)
26       raise(Puppet::ParseError, "os_database_connection(): #{key} should be a String")
27     end
28   end
29
30   parts = {}
31
32   unless v.include?('dialect')
33     raise(Puppet::ParseError, 'os_database_connection(): dialect is required')
34   end
35
36   if v.include?('host')
37     parts[:host] = v['host']
38   end
39
40   unless v.include?('database')
41     raise(Puppet::ParseError, 'os_database_connection(): database is required')
42   end
43
44   if v.include?('port')
45     if v.include?('host')
46       parts[:port] = v['port'].to_i
47     else
48       raise(Puppet::ParseError, 'os_database_connection(): host is required with port')
49     end
50   end
51
52   if v.include?('username') and (v['username'] != :undef) and (v['username'].to_s != '')
53     parts[:userinfo] = URI.escape(v['username'])
54     if v.include?('password') and (v['password'] != :undef) and (v['password'].to_s != '')
55       parts[:userinfo] += ":#{URI.escape(v['password'])}"
56     end
57   end
58
59   if v.include?('charset')
60     parts[:query] = "charset=#{v['charset']}"
61   end
62
63   parts[:scheme] = v['dialect']
64
65   if v.include?('host')
66     parts[:path] = "/#{v['database']}"
67   else
68     parts[:path] = "///#{v['database']}"
69   end
70
71   URI::Generic.build(parts).to_s
72 end