CAL refactoring
[osm/SO.git] / rwcal / plugins / vala / rwcal_openstack / rift / rwcal / openstack / neutron / neutron_drv.py
1 #!/usr/bin/python
2
3 #
4 # Copyright 2017 RIFT.IO Inc
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 #
18 import logging
19 import ipaddress
20 from neutronclient.neutron import client as ntclient
21
22 import neutronclient.common.exceptions as NeutronException
23
24
25 class NeutronAPIVersionException(Exception):
26 def __init__(self, errors):
27 self.errors = errors
28 super(NeutronAPIVersionException, self).__init__("Multiple Exception Received")
29
30 def __str__(self):
31 return self.__repr__()
32
33 def __repr__(self):
34 msg = "{} : Following Exception(s) have occured during Neutron API discovery".format(self.__class__)
35 for n,e in enumerate(self.errors):
36 msg += "\n"
37 msg += " {}: {}".format(n, str(e))
38 return msg
39
40
41 class NeutronDriver(object):
42 """
43 NeutronDriver Class for network orchestration
44 """
45 ### List of supported API versions in prioritized order
46 supported_versions = ["2"]
47
48 def __init__(self,
49 sess_handle,
50 region_name = 'RegionOne',
51 service_type = 'network',
52 logger = None):
53 """
54 Constructor for NeutronDriver class
55 Arguments:
56 sess_handle (instance of class SessionDriver)
57 region_name (string): Region Name
58 service_type(string): Type of service in service catalog
59 logger (instance of logging.Logger)
60 """
61
62 if logger is None:
63 self.log = logging.getLogger('rwcal.openstack.neutron')
64 self.log.setLevel(logging.DEBUG)
65 else:
66 self.log = logger
67
68 self._sess_handle = sess_handle
69
70 #### Attempt to use API versions in prioritized order defined in
71 #### NeutronDriver.supported_versions
72 def select_version(version):
73 try:
74 self.log.info("Attempting to use Neutron v%s APIs", version)
75 ntdrv = ntclient.Client(api_version = version,
76 region_name = region_name,
77 service_type = service_type,
78 session = self._sess_handle.session,
79 logger = self.log)
80 except Exception as e:
81 self.log.info(str(e))
82 raise
83 else:
84 self.log.info("Neutron API v%s selected", version)
85 return (version, ntdrv)
86
87 errors = []
88 for v in NeutronDriver.supported_versions:
89 try:
90 (self._version, self._nt_drv) = select_version(v)
91 except Exception as e:
92 errors.append(e)
93 else:
94 break
95 else:
96 raise NeutronAPIVersionException(errors)
97
98 @property
99 def neutron_endpoint(self):
100 return self._nt_drv.get_auth_info()['endpoint_url']
101
102 @property
103 def project_id(self):
104 return self._sess_handle.project_id
105
106 @property
107 def neutron_quota(self):
108 """
109 Returns Neutron Quota (a dictionary) for project
110 """
111 try:
112 quota = self._nt_drv.show_quota(self.project_id)
113 except Exception as e:
114 self.log.exception("Get Neutron quota operation failed. Exception: %s", str(e))
115 raise
116 return quota
117
118 def extensions_list(self):
119 """
120 Returns a list of available neutron extensions.
121 Arguments:
122 None
123 Returns:
124 A list of dictionaries. Each dictionary contains attributes for a single Neutron extension
125 """
126 try:
127 extensions = self._nt_drv.list_extensions()
128 except Exception as e:
129 self.log.exception("List extension operation failed. Exception: %s", str(e))
130 raise
131 if 'extensions' in extensions:
132 return extensions['extensions']
133 return list()
134
135
136 def _get_neutron_connection(self):
137 """
138 Returns instance of object neutronclient.neutron.client.Client
139 Use for DEBUG ONLY
140 """
141 return self._nt_drv
142
143 def _network_find(self, **kwargs):
144 """
145 Returns a network object dictionary based on the filters provided in kwargs
146
147 Arguments:
148 kwargs (dictionary): A dictionary of key-value pair filters
149
150 Returns:
151 One or more dictionary object associated with network
152 """
153 try:
154 networks = self._nt_drv.list_networks(**kwargs)['networks']
155 except Exception as e:
156 self.log.exception("List network operation failed. Exception: %s", str(e))
157 raise
158 return networks
159
160 def network_list(self):
161 """
162 Returns list of dictionaries. Each dictionary contains the attributes for a network
163 under project
164
165 Arguments: None
166
167 Returns:
168 A list of dictionaries
169 """
170 return self._network_find(**{'tenant_id':self.project_id}) + self._network_find(**{'shared':True})
171
172
173 def network_create(self, **kwargs):
174 """
175 Creates a new network for the project
176
177 Arguments:
178 A dictionary with following key-values
179 {
180 name (string) : Name of the network
181 admin_state_up(Boolean) : True/False (Defaults: True)
182 external_router(Boolean) : Connectivity with external router. True/False (Defaults: False)
183 shared(Boolean) : Shared among tenants. True/False (Defaults: False)
184 physical_network(string) : The physical network where this network object is implemented (optional).
185 network_type : The type of physical network that maps to this network resource (optional).
186 Possible values are: 'flat', 'vlan', 'vxlan', 'gre'
187 segmentation_id : An isolated segment on the physical network. The network_type attribute
188 defines the segmentation model. For example, if the network_type value
189 is vlan, this ID is a vlan identifier. If the network_type value is gre,
190 this ID is a gre key.
191 }
192 """
193 params = {'network':
194 {'name' : kwargs['name'],
195 'admin_state_up' : kwargs['admin_state_up'],
196 'tenant_id' : self.project_id,
197 'shared' : kwargs['shared'],
198 #'port_security_enabled': port_security_enabled,
199 'router:external' : kwargs['external_router']}}
200
201 if 'physical_network' in kwargs:
202 params['network']['provider:physical_network'] = kwargs['physical_network']
203 if 'network_type' in kwargs:
204 params['network']['provider:network_type'] = kwargs['network_type']
205 if 'segmentation_id' in kwargs:
206 params['network']['provider:segmentation_id'] = kwargs['segmentation_id']
207
208 try:
209 self.log.debug("Calling neutron create_network() with params: %s", str(params))
210 net = self._nt_drv.create_network(params)
211 except Exception as e:
212 self.log.exception("Create Network operation failed. Exception: %s", str(e))
213 raise
214
215 network_id = net['network']['id']
216 if not network_id:
217 raise Exception("Empty network id returned from create_network. (params: %s)" % str(params))
218
219 return network_id
220
221 def network_delete(self, network_id):
222 """
223 Deletes a network identified by network_id
224
225 Arguments:
226 network_id (string): UUID of the network
227
228 Returns: None
229 """
230 try:
231 self._nt_drv.delete_network(network_id)
232 except Exception as e:
233 self.log.exception("Delete Network operation failed. Exception: %s",str(e))
234 raise
235
236
237 def network_get(self, network_id='', network_name=''):
238 """
239 Returns a dictionary object describing the attributes of the network
240
241 Arguments:
242 network_id (string): UUID of the network
243
244 Returns:
245 A dictionary object of the network attributes
246 """
247 networks = self._network_find(**{'id': network_id, 'name': network_name})
248 if not networks:
249 raise NeutronException.NotFound("Could not find network. Network id: %s, Network name: %s " %(network_id, network_name))
250 return networks[0]
251
252
253 def subnet_create(self, **kwargs):
254 """
255 Creates a subnet on the network
256
257 Arguments:
258 A dictionary with following key value pairs
259 {
260 network_id(string) : UUID of the network where subnet needs to be created
261 subnet_cidr(string) : IPv4 address prefix (e.g. '1.1.1.0/24') for the subnet
262 ip_version (integer): 4 for IPv4 and 6 for IPv6
263
264 }
265
266 Returns:
267 subnet_id (string): UUID of the created subnet
268 """
269 params = {}
270 params['network_id'] = kwargs['network_id']
271 params['ip_version'] = kwargs['ip_version']
272
273 # if params['ip_version'] == 6:
274 # assert 0, "IPv6 is not supported"
275
276 if 'subnetpool_id' in kwargs:
277 params['subnetpool_id'] = kwargs['subnetpool_id']
278 else:
279 params['cidr'] = kwargs['cidr']
280
281 if 'gateway_ip' in kwargs:
282 params['gateway_ip'] = kwargs['gateway_ip']
283 else:
284 params['gateway_ip'] = None
285
286 if 'dhcp_params' in kwargs:
287 params['enable_dhcp'] = kwargs['dhcp_params']['enable_dhcp']
288 if 'start_address' in kwargs['dhcp_params'] and 'count' in kwargs['dhcp_params']:
289 end_address = (ipaddress.IPv4Address(kwargs['dhcp_params']['start_address']) + kwargs['dhcp_params']['count']).compressed
290 params['allocation_pools'] = [ {'start': kwargs['dhcp_params']['start_address'] ,
291 'end' : end_address} ]
292
293 if 'dns_server' in kwargs:
294 params['dns_nameservers'] = []
295 for server in kwargs['dns_server']:
296 params['dns_nameservers'].append(server)
297
298 try:
299 subnet = self._nt_drv.create_subnet({'subnets': [params]})
300 except Exception as e:
301 self.log.exception("Create Subnet operation failed. Exception: %s",str(e))
302 raise
303
304 return subnet['subnets'][0]['id']
305
306 def subnet_list(self, **kwargs):
307 """
308 Returns a list of dictionaries. Each dictionary contains attributes describing the subnet
309
310 Arguments: None
311
312 Returns:
313 A dictionary of the objects of subnet attributes
314 """
315 try:
316 subnets = self._nt_drv.list_subnets(**kwargs)['subnets']
317 except Exception as e:
318 self.log.exception("List Subnet operation failed. Exception: %s", str(e))
319 raise
320 return subnets
321
322 def _subnet_get(self, subnet_id):
323 """
324 Returns a dictionary object describing the attributes of a subnet.
325
326 Arguments:
327 subnet_id (string): UUID of the subnet
328
329 Returns:
330 A dictionary object of the subnet attributes
331 """
332 subnets = self._nt_drv.list_subnets(id=subnet_id)
333 if not subnets['subnets']:
334 self.log.error("Get subnet operation failed for subnet_id: %s", subnet_id)
335 #raise NeutronException.NotFound("Could not find subnet_id %s" %(subnet_id))
336 return {'cidr': ''}
337 else:
338 return subnets['subnets'][0]
339
340 def subnet_get(self, subnet_id):
341 """
342 Returns a dictionary object describing the attributes of a subnet.
343
344 Arguments:
345 subnet_id (string): UUID of the subnet
346
347 Returns:
348 A dictionary object of the subnet attributes
349 """
350 return self._subnet_get(subnet_id)
351
352 def subnet_delete(self, subnet_id):
353 """
354 Deletes a subnet identified by subnet_id
355
356 Arguments:
357 subnet_id (string): UUID of the subnet to be deleted
358
359 Returns: None
360 """
361 assert subnet_id == self._subnet_get(self,subnet_id)
362 try:
363 self._nt_drv.delete_subnet(subnet_id)
364 except Exception as e:
365 self.log.exception("Delete Subnet operation failed for subnet_id : %s. Exception: %s", subnet_id, str(e))
366 raise
367
368 def port_list(self, **kwargs):
369 """
370 Returns a list of dictionaries. Each dictionary contains attributes describing the port
371
372 Arguments:
373 kwargs (dictionary): A dictionary for filters for port_list operation
374
375 Returns:
376 A dictionary of the objects of port attributes
377
378 """
379 ports = []
380
381 kwargs['tenant_id'] = self.project_id
382
383 try:
384 ports = self._nt_drv.list_ports(**kwargs)
385 except Exception as e:
386 self.log.exception("List Port operation failed. Exception: %s",str(e))
387 raise
388 return ports['ports']
389
390 def port_create(self, ports):
391 """
392 Create a port in network
393
394 Arguments:
395 Ports
396 List of dictionaries of following
397 {
398 name (string) : Name of the port
399 network_id(string) : UUID of the network_id identifying the network to which port belongs
400 ip_address(string) : (Optional) Static IP address to assign to the port
401 vnic_type(string) : Possible values are "normal", "direct", "macvtap"
402 admin_state_up : True/False
403 port_security_enabled : True/False
404 security_groups : A List of Neutron security group Ids
405 }
406 Returns:
407 A list of port_id (string)
408 """
409 params = dict()
410 params['ports'] = ports
411 self.log.debug("Port create params: {}".format(params))
412 try:
413 ports = self._nt_drv.create_port(params)
414 except Exception as e:
415 self.log.exception("Ports Create operation failed. Exception: %s",str(e))
416 raise
417 return [ p['id'] for p in ports['ports'] ]
418
419
420 def port_update(self, port_id, no_security_groups=None,port_security_enabled=None):
421 """
422 Update a port in network
423 """
424 params = {}
425 params["port"] = {}
426 if no_security_groups:
427 params["port"]["security_groups"] = []
428 if port_security_enabled == False:
429 params["port"]["port_security_enabled"] = False
430 elif port_security_enabled == True:
431 params["port"]["port_security_enabled"] = True
432
433 try:
434 port = self._nt_drv.update_port(port_id,params)
435 except Exception as e:
436 self.log.exception("Port Update operation failed. Exception: %s", str(e))
437 raise
438 return port['port']['id']
439
440 def _port_get(self, port_id):
441 """
442 Returns a dictionary object describing the attributes of the port
443
444 Arguments:
445 port_id (string): UUID of the port
446
447 Returns:
448 A dictionary object of the port attributes
449 """
450 port = self._nt_drv.list_ports(id=port_id)['ports']
451 if not port:
452 raise NeutronException.NotFound("Could not find port_id %s" %(port_id))
453 return port[0]
454
455 def port_get(self, port_id):
456 """
457 Returns a dictionary object describing the attributes of the port
458
459 Arguments:
460 port_id (string): UUID of the port
461
462 Returns:
463 A dictionary object of the port attributes
464 """
465 return self._port_get(port_id)
466
467 def port_delete(self, port_id):
468 """
469 Deletes a port identified by port_id
470
471 Arguments:
472 port_id (string) : UUID of the port
473
474 Returns: None
475 """
476 assert port_id == self._port_get(port_id)['id']
477 try:
478 self._nt_drv.delete_port(port_id)
479 except Exception as e:
480 self.log.exception("Port Delete operation failed for port_id : %s. Exception: %s",port_id, str(e))
481 raise
482
483 def security_group_list(self, **kwargs):
484 """
485 Returns a list of dictionaries. Each dictionary contains attributes describing the security group
486
487 Arguments:
488 None
489
490 Returns:
491 A dictionary of the objects of security group attributes
492 """
493 try:
494 kwargs['tenant_id'] = self.project_id
495 group_list = self._nt_drv.list_security_groups(**kwargs)
496 except Exception as e:
497 self.log.exception("List Security group operation, Exception: %s", str(e))
498 raise
499 return group_list['security_groups']
500
501
502 def subnetpool_list(self, **kwargs):
503 """
504 Returns a list of dictionaries. Each dictionary contains attributes describing a subnet prefix pool
505
506 Arguments:
507 None
508
509 Returns:
510 A dictionary of the objects of subnet prefix pool
511 """
512 try:
513 pool_list = self._nt_drv.list_subnetpools(**kwargs)
514 except Exception as e:
515 self.log.exception("List SubnetPool operation, Exception: %s",str(e))
516 raise
517
518 if 'subnetpools' in pool_list:
519 return pool_list['subnetpools']
520 else:
521 return []
522