try again, with puppetforge modules, correctly included now
[mirror/dsa-puppet.git] / 3rdparty / modules / neutron / lib / puppet / provider / neutron.rb
1 require 'csv'
2 require 'puppet/util/inifile'
3
4 class Puppet::Provider::Neutron < Puppet::Provider
5
6   def self.conf_filename
7     '/etc/neutron/neutron.conf'
8   end
9
10   def self.withenv(hash, &block)
11     saved = ENV.to_hash
12     hash.each do |name, val|
13       ENV[name.to_s] = val
14     end
15
16     yield
17   ensure
18     ENV.clear
19     saved.each do |name, val|
20       ENV[name] = val
21     end
22   end
23
24   def self.neutron_credentials
25     @neutron_credentials ||= get_neutron_credentials
26   end
27
28   def self.get_neutron_credentials
29     auth_keys = ['admin_tenant_name', 'admin_user', 'admin_password']
30     deprecated_auth_url = ['auth_host', 'auth_port', 'auth_protocol']
31     conf = neutron_conf
32     if conf and conf['keystone_authtoken'] and
33         auth_keys.all?{|k| !conf['keystone_authtoken'][k].nil?} and
34         ( deprecated_auth_url.all?{|k| !conf['keystone_authtoken'][k].nil?} or
35         !conf['keystone_authtoken']['auth_uri'].nil? )
36       creds = Hash[ auth_keys.map \
37                    { |k| [k, conf['keystone_authtoken'][k].strip] } ]
38       if !conf['keystone_authtoken']['auth_uri'].nil?
39         creds['auth_uri'] = conf['keystone_authtoken']['auth_uri']
40       else
41         q = conf['keystone_authtoken']
42         creds['auth_uri'] = "#{q['auth_protocol']}://#{q['auth_host']}:#{q['auth_port']}/v2.0/"
43       end
44       if conf['DEFAULT'] and !conf['DEFAULT']['nova_region_name'].nil?
45         creds['nova_region_name'] = conf['DEFAULT']['nova_region_name']
46       end
47       return creds
48     else
49       raise(Puppet::Error, "File: #{conf_filename} does not contain all \
50 required sections.  Neutron types will not work if neutron is not \
51 correctly configured.")
52     end
53   end
54
55   def neutron_credentials
56     self.class.neutron_credentials
57   end
58
59   def self.auth_endpoint
60     @auth_endpoint ||= get_auth_endpoint
61   end
62
63   def self.get_auth_endpoint
64     q = neutron_credentials
65     if q['auth_uri'].nil?
66       return "#{q['auth_protocol']}://#{q['auth_host']}:#{q['auth_port']}/v2.0/"
67     else
68       return "#{q['auth_uri']}".strip
69     end
70   end
71
72   def self.neutron_conf
73     return @neutron_conf if @neutron_conf
74     @neutron_conf = Puppet::Util::IniConfig::File.new
75     @neutron_conf.read(conf_filename)
76     @neutron_conf
77   end
78
79   def self.auth_neutron(*args)
80     q = neutron_credentials
81     authenv = {
82       :OS_AUTH_URL    => self.auth_endpoint,
83       :OS_USERNAME    => q['admin_user'],
84       :OS_TENANT_NAME => q['admin_tenant_name'],
85       :OS_PASSWORD    => q['admin_password']
86     }
87     if q.key?('nova_region_name')
88       authenv[:OS_REGION_NAME] = q['nova_region_name']
89     end
90     rv = nil
91     timeout = 10
92     end_time = Time.now.to_i + timeout
93     loop do
94       begin
95         withenv authenv do
96           rv = neutron(args)
97         end
98         break
99       rescue Puppet::ExecutionFailure => e
100         if ! e.message =~ /(\(HTTP\s+400\))|
101               (400-\{\'message\'\:\s+\'\'\})|
102               (\[Errno 111\]\s+Connection\s+refused)|
103               (503\s+Service\s+Unavailable)|
104               (504\s+Gateway\s+Time-out)|
105               (\:\s+Maximum\s+attempts\s+reached)|
106               (Unauthorized\:\s+bad\s+credentials)|
107               (Max\s+retries\s+exceeded)/
108           raise(e)
109         end
110         current_time = Time.now.to_i
111         if current_time > end_time
112           break
113         else
114           wait = end_time - current_time
115           Puppet::debug("Non-fatal error: \"#{e.message}\"")
116           notice("Neutron API not avalaible. Wait up to #{wait} sec.")
117         end
118         sleep(2)
119         # Note(xarses): Don't remove, we know that there is one of the
120         # Recoverable erros above, So we will retry a few more times
121       end
122     end
123     return rv
124   end
125
126   def auth_neutron(*args)
127     self.class.auth_neutron(args)
128   end
129
130   def self.reset
131     @neutron_conf        = nil
132     @neutron_credentials = nil
133   end
134
135   def self.list_neutron_resources(type)
136     ids = []
137     list = auth_neutron("#{type}-list", '--format=csv',
138                         '--column=id', '--quote=none')
139     if list.nil?
140       raise(Puppet::ExecutionFailure, "Can't retrieve #{type}-list because Neutron or Keystone API is not avalaible.")
141     end
142
143     (list.split("\n")[1..-1] || []).compact.collect do |line|
144       ids << line.strip
145     end
146     return ids
147   end
148
149   def self.get_neutron_resource_attrs(type, id)
150     attrs = {}
151     net = auth_neutron("#{type}-show", '--format=shell', id)
152     if net.nil?
153       raise(Puppet::ExecutionFailure, "Can't retrieve #{type}-show because Neutron or Keystone API is not avalaible.")
154     end
155
156     last_key = nil
157     (net.split("\n") || []).compact.collect do |line|
158       if line.include? '='
159         k, v = line.split('=', 2)
160         attrs[k] = v.gsub(/\A"|"\Z/, '')
161         last_key = k
162       else
163         # Handle the case of a list of values
164         v = line.gsub(/\A"|"\Z/, '')
165         attrs[last_key] = [attrs[last_key], v].flatten
166       end
167     end
168     return attrs
169   end
170
171   def self.list_router_ports(router_name_or_id)
172     results = []
173     cmd_output = auth_neutron("router-port-list",
174                               '--format=csv',
175                               router_name_or_id)
176     if ! cmd_output
177       return results
178     end
179
180     headers = nil
181     CSV.parse(cmd_output) do |row|
182       if headers == nil
183         headers = row
184       else
185         result = Hash[*headers.zip(row).flatten]
186         match_data = /.*"subnet_id": "(.*)", .*/.match(result['fixed_ips'])
187         if match_data
188           result['subnet_id'] = match_data[1]
189         end
190         results << result
191       end
192     end
193     return results
194   end
195
196   def self.get_tenant_id(catalog, name)
197     instance_type = 'keystone_tenant'
198     instance = catalog.resource("#{instance_type.capitalize!}[#{name}]")
199     if ! instance
200       instance = Puppet::Type.type(instance_type).instances.find do |i|
201         i.provider.name == name
202       end
203     end
204     if instance
205       return instance.provider.id
206     else
207       fail("Unable to find #{instance_type} for name #{name}")
208     end
209   end
210
211   def self.parse_creation_output(data)
212     hash = {}
213     data.split("\n").compact.each do |line|
214       if line.include? '='
215         hash[line.split('=').first] = line.split('=', 2)[1].gsub(/\A"|"\Z/, '')
216       end
217     end
218     hash
219   end
220
221 end