Merge "Refactored port retrieval to include PortSettigs."
[snaps.git] / snaps / openstack / utils / neutron_utils.py
1 # Copyright (c) 2017 Cable Television Laboratories, Inc. ("CableLabs")
2 #                    and others.  All rights reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at:
7 #
8 #     http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 import logging
16
17 from neutronclient.common.exceptions import NotFound
18 from neutronclient.neutron.client import Client
19
20 from snaps.domain.network import (
21     Port, SecurityGroup, SecurityGroupRule, Router, InterfaceRouter, Subnet,
22     Network)
23 from snaps.domain.vm_inst import FloatingIp
24 from snaps.openstack.utils import keystone_utils
25
26 __author__ = 'spisarski'
27
28 logger = logging.getLogger('neutron_utils')
29
30 """
31 Utilities for basic neutron API calls
32 """
33
34
35 def neutron_client(os_creds):
36     """
37     Instantiates and returns a client for communications with OpenStack's
38     Neutron server
39     :param os_creds: the credentials for connecting to the OpenStack remote API
40     :return: the client object
41     """
42     return Client(api_version=os_creds.network_api_version,
43                   session=keystone_utils.keystone_session(os_creds),
44                   region_name=os_creds.region_name)
45
46
47 def create_network(neutron, os_creds, network_settings):
48     """
49     Creates a network for OpenStack
50     :param neutron: the client
51     :param os_creds: the OpenStack credentials
52     :param network_settings: A dictionary containing the network configuration
53                              and is responsible for creating the network
54                             request JSON body
55     :return: a SNAPS-OO Network domain object
56     """
57     if neutron and network_settings:
58         logger.info('Creating network with name ' + network_settings.name)
59         json_body = network_settings.dict_for_neutron(os_creds)
60         os_network = neutron.create_network(body=json_body)
61         return Network(**os_network['network'])
62     else:
63         raise NeutronException('Failded to create network')
64
65
66 def delete_network(neutron, network):
67     """
68     Deletes a network for OpenStack
69     :param neutron: the client
70     :param network: a SNAPS-OO Network domain object
71     """
72     if neutron and network:
73         logger.info('Deleting network with name ' + network.name)
74         neutron.delete_network(network.id)
75
76
77 def get_network(neutron, network_settings=None, network_name=None,
78                 project_id=None):
79     """
80     Returns Network SNAPS-OO domain object the first network found with
81     either the given attributes from the network_settings object if not None,
82     else the query will use just the name from the network_name parameter.
83     When the project_id is included, that will be added to the query filter.
84     :param neutron: the client
85     :param network_settings: the NetworkSettings object used to create filter
86     :param network_name: the name of the network to retrieve
87     :param project_id: the id of the network's project
88     :return: a SNAPS-OO Network domain object
89     """
90     net_filter = dict()
91     if network_settings:
92         net_filter['name'] = network_settings.name
93     elif network_name:
94         net_filter['name'] = network_name
95
96     if project_id:
97         net_filter['project_id'] = project_id
98
99     networks = neutron.list_networks(**net_filter)
100     for network, netInsts in networks.items():
101         for inst in netInsts:
102             return Network(**inst)
103
104
105 def get_network_by_id(neutron, network_id):
106     """
107     Returns the network object (dictionary) with the given ID else None
108     :param neutron: the client
109     :param network_id: the id of the network to retrieve
110     :return: a SNAPS-OO Network domain object
111     """
112     networks = neutron.list_networks(**{'id': network_id})
113     for network in networks['networks']:
114         if network['id'] == network_id:
115             return Network(**network)
116
117
118 def create_subnet(neutron, subnet_settings, os_creds, network=None):
119     """
120     Creates a network subnet for OpenStack
121     :param neutron: the client
122     :param network: the network object
123     :param subnet_settings: A dictionary containing the subnet configuration
124                             and is responsible for creating the subnet request
125                             JSON body
126     :param os_creds: the OpenStack credentials
127     :return: a SNAPS-OO Subnet domain object
128     """
129     if neutron and network and subnet_settings:
130         json_body = {'subnets': [subnet_settings.dict_for_neutron(
131             os_creds, network=network)]}
132         logger.info('Creating subnet with name ' + subnet_settings.name)
133         subnets = neutron.create_subnet(body=json_body)
134         return Subnet(**subnets['subnets'][0])
135     else:
136         raise NeutronException('Failed to create subnet')
137
138
139 def delete_subnet(neutron, subnet):
140     """
141     Deletes a network subnet for OpenStack
142     :param neutron: the client
143     :param subnet: a SNAPS-OO Subnet domain object
144     """
145     if neutron and subnet:
146         logger.info('Deleting subnet with name ' + subnet.name)
147         neutron.delete_subnet(subnet.id)
148
149
150 def get_subnet_by_name(neutron, subnet_name):
151     """
152     Returns the first subnet object (dictionary) found with a given name
153     :param neutron: the client
154     :param subnet_name: the name of the network to retrieve
155     :return: a SNAPS-OO Subnet domain object
156     """
157     subnets = neutron.list_subnets(**{'name': subnet_name})
158     for subnet, subnetInst in subnets.items():
159         for inst in subnetInst:
160             if inst['name'] == subnet_name:
161                 return Subnet(**inst)
162     return None
163
164
165 def create_router(neutron, os_creds, router_settings):
166     """
167     Creates a router for OpenStack
168     :param neutron: the client
169     :param os_creds: the OpenStack credentials
170     :param router_settings: A dictionary containing the router configuration
171                             and is responsible for creating the subnet request
172                             JSON body
173     :return: a SNAPS-OO Router domain object
174     """
175     if neutron:
176         json_body = router_settings.dict_for_neutron(neutron, os_creds)
177         logger.info('Creating router with name - ' + router_settings.name)
178         os_router = neutron.create_router(json_body)
179         return Router(**os_router['router'])
180     else:
181         logger.error("Failed to create router.")
182         raise NeutronException('Failed to create router')
183
184
185 def delete_router(neutron, router):
186     """
187     Deletes a router for OpenStack
188     :param neutron: the client
189     :param router: a SNAPS-OO Router domain object
190     """
191     if neutron and router:
192         logger.info('Deleting router with name - ' + router.name)
193         neutron.delete_router(router=router.id)
194
195
196 def get_router_by_name(neutron, router_name):
197     """
198     Returns the first router object (dictionary) found with a given name
199     :param neutron: the client
200     :param router_name: the name of the network to retrieve
201     :return: a SNAPS-OO Router domain object
202     """
203     routers = neutron.list_routers(**{'name': router_name})
204     for router, routerInst in routers.items():
205         for inst in routerInst:
206             if inst.get('name') == router_name:
207                 return Router(**inst)
208     return None
209
210
211 def add_interface_router(neutron, router, subnet=None, port=None):
212     """
213     Adds an interface router for OpenStack for either a subnet or port.
214     Exception will be raised if requesting for both.
215     :param neutron: the client
216     :param router: the router object
217     :param subnet: the subnet object
218     :param port: the port object
219     :return: the interface router object
220     """
221     if subnet and port:
222         raise NeutronException(
223             'Cannot add interface to the router. Both subnet and '
224             'port were sent in. Either or please.')
225
226     if neutron and router and (router or subnet):
227         logger.info('Adding interface to router with name ' + router.name)
228         os_intf_router = neutron.add_interface_router(
229             router=router.id, body=__create_port_json_body(subnet, port))
230         return InterfaceRouter(**os_intf_router)
231     else:
232         raise NeutronException(
233             'Unable to create interface router as neutron client,'
234             ' router or subnet were not created')
235
236
237 def remove_interface_router(neutron, router, subnet=None, port=None):
238     """
239     Removes an interface router for OpenStack
240     :param neutron: the client
241     :param router: the SNAPS-OO Router domain object
242     :param subnet: the subnet object (either subnet or port, not both)
243     :param port: the port object
244     """
245     if router:
246         try:
247             logger.info('Removing router interface from router named ' +
248                         router.name)
249             neutron.remove_interface_router(
250                 router=router.id,
251                 body=__create_port_json_body(subnet, port))
252         except NotFound as e:
253             logger.warning('Could not remove router interface. NotFound - %s',
254                            e)
255             pass
256     else:
257         logger.warning('Could not remove router interface, No router object')
258
259
260 def __create_port_json_body(subnet=None, port=None):
261     """
262     Returns the dictionary required for creating and deleting router
263     interfaces. Will only work on a subnet or port object. Will throw and
264     exception if parameters contain both or neither
265     :param subnet: the subnet object
266     :param port: the port object
267     :return: the dict
268     """
269     if subnet and port:
270         raise NeutronException(
271             'Cannot create JSON body with both subnet and port')
272     if not subnet and not port:
273         raise NeutronException(
274             'Cannot create JSON body without subnet or port')
275
276     if subnet:
277         return {"subnet_id": subnet.id}
278     else:
279         return {"port_id": port.id}
280
281
282 def create_port(neutron, os_creds, port_settings):
283     """
284     Creates a port for OpenStack
285     :param neutron: the client
286     :param os_creds: the OpenStack credentials
287     :param port_settings: the settings object for port configuration
288     :return: the SNAPS-OO Port domain object
289     """
290     json_body = port_settings.dict_for_neutron(neutron, os_creds)
291     logger.info('Creating port for network with name - %s',
292                 port_settings.network_name)
293     os_port = neutron.create_port(body=json_body)['port']
294     return Port(name=os_port['name'], id=os_port['id'],
295                 ips=os_port['fixed_ips'],
296                 mac_address=os_port['mac_address'],
297                 allowed_address_pairs=os_port['allowed_address_pairs'])
298
299
300 def delete_port(neutron, port):
301     """
302     Removes an OpenStack port
303     :param neutron: the client
304     :param port: the SNAPS-OO Port domain object
305     """
306     logger.info('Deleting port with name ' + port.name)
307     neutron.delete_port(port.id)
308
309
310 def get_port(neutron, port_settings=None, port_name=None):
311     """
312     Returns the first port object (dictionary) found for the given query
313     :param neutron: the client
314     :param port_settings: the PortSettings object used for generating the query
315     :param port_name: if port_settings is None, this name is the value to place
316                       into the query
317     :return: a SNAPS-OO Port domain object
318     """
319     port_filter = dict()
320
321     if port_settings:
322         port_filter['name'] = port_settings.name
323         if port_settings.admin_state_up:
324             port_filter['admin_state_up'] = port_settings.admin_state_up
325         if port_settings.device_id:
326             port_filter['device_id'] = port_settings.device_id
327         if port_settings.mac_address:
328             port_filter['mac_address'] = port_settings.mac_address
329     elif port_name:
330         port_filter['name'] = port_name
331
332     ports = neutron.list_ports(**port_filter)
333     for port in ports['ports']:
334         return Port(name=port['name'], id=port['id'],
335                     ips=port['fixed_ips'], mac_address=port['mac_address'])
336     return None
337
338
339 def create_security_group(neutron, keystone, sec_grp_settings):
340     """
341     Creates a security group object in OpenStack
342     :param neutron: the Neutron client
343     :param keystone: the Keystone client
344     :param sec_grp_settings: the security group settings
345     :return: a SNAPS-OO SecurityGroup domain object
346     """
347     logger.info('Creating security group with name - %s',
348                 sec_grp_settings.name)
349     os_group = neutron.create_security_group(
350         sec_grp_settings.dict_for_neutron(keystone))
351     return SecurityGroup(**os_group['security_group'])
352
353
354 def delete_security_group(neutron, sec_grp):
355     """
356     Deletes a security group object from OpenStack
357     :param neutron: the client
358     :param sec_grp: the SNAPS SecurityGroup object to delete
359     """
360     logger.info('Deleting security group with name - %s', sec_grp.name)
361     neutron.delete_security_group(sec_grp.id)
362
363
364 def get_security_group(neutron, name, tenant_id=None):
365     """
366     Returns the first security group object of the given name else None
367     :param neutron: the client
368     :param name: the name of security group object to retrieve
369     :return: a SNAPS-OO SecurityGroup domain object or None if not found
370     """
371     logger.info('Retrieving security group with name - ' + name)
372
373     filter = {'name': name}
374     if tenant_id:
375         filter['tenant_id'] = tenant_id
376     groups = neutron.list_security_groups(**filter)
377     for group in groups['security_groups']:
378         if group['name'] == name:
379             return SecurityGroup(**group)
380     return None
381
382
383 def get_security_group_by_id(neutron, sec_grp_id):
384     """
385     Returns the first security group object of the given name else None
386     :param neutron: the client
387     :param sec_grp_id: the id of the security group to retrieve
388     :return: a SNAPS-OO SecurityGroup domain object or None if not found
389     """
390     logger.info('Retrieving security group with ID - ' + sec_grp_id)
391
392     groups = neutron.list_security_groups(**{'id': sec_grp_id})
393     for group in groups['security_groups']:
394         if group['id'] == sec_grp_id:
395             return SecurityGroup(**group)
396     return None
397
398
399 def create_security_group_rule(neutron, sec_grp_rule_settings):
400     """
401     Creates a security group object in OpenStack
402     :param neutron: the client
403     :param sec_grp_rule_settings: the security group rule settings
404     :return: a SNAPS-OO SecurityGroupRule domain object
405     """
406     logger.info('Creating security group to security group - %s',
407                 sec_grp_rule_settings.sec_grp_name)
408     os_rule = neutron.create_security_group_rule(
409         sec_grp_rule_settings.dict_for_neutron(neutron))
410     return SecurityGroupRule(**os_rule['security_group_rule'])
411
412
413 def delete_security_group_rule(neutron, sec_grp_rule):
414     """
415     Deletes a security group object from OpenStack
416     :param neutron: the client
417     :param sec_grp_rule: the SNAPS SecurityGroupRule object to delete
418     """
419     logger.info('Deleting security group rule with ID - %s',
420                 sec_grp_rule.id)
421     neutron.delete_security_group_rule(sec_grp_rule.id)
422
423
424 def get_rules_by_security_group(neutron, sec_grp):
425     """
426     Retrieves all of the rules for a given security group
427     :param neutron: the client
428     :param sec_grp: a list of SNAPS SecurityGroupRule domain objects
429     """
430     logger.info('Retrieving security group rules associate with the '
431                 'security group - %s', sec_grp.name)
432     out = list()
433     rules = neutron.list_security_group_rules(
434         **{'security_group_id': sec_grp.id})
435     for rule in rules['security_group_rules']:
436         if rule['security_group_id'] == sec_grp.id:
437             out.append(SecurityGroupRule(**rule))
438     return out
439
440
441 def get_rule_by_id(neutron, sec_grp, rule_id):
442     """
443     Deletes a security group object from OpenStack
444     :param neutron: the client
445     :param sec_grp: the SNAPS SecurityGroup domain object
446     :param rule_id: the rule's ID
447     :param sec_grp: a SNAPS SecurityGroupRule domain object
448     """
449     rules = neutron.list_security_group_rules(
450         **{'security_group_id': sec_grp.id})
451     for rule in rules['security_group_rules']:
452         if rule['id'] == rule_id:
453             return SecurityGroupRule(**rule)
454     return None
455
456
457 def get_external_networks(neutron):
458     """
459     Returns a list of external OpenStack network object/dict for all external
460     networks
461     :param neutron: the client
462     :return: a list of external networks of Type SNAPS-OO domain class Network
463     """
464     out = list()
465     for network in neutron.list_networks(
466             **{'router:external': True})['networks']:
467         out.append(Network(**network))
468     return out
469
470
471 def get_floating_ips(neutron, ports=None):
472     """
473     Returns all of the floating IPs
474     When ports is not None, FIPs returned must be associated with one of the
475     ports in the list and a tuple 2 where the first element being the port's
476     name and the second being the FloatingIp SNAPS-OO domain object.
477     When ports is None, all known FloatingIp SNAPS-OO domain objects will be
478     returned in a list
479     :param neutron: the Neutron client
480     :param ports: a list of SNAPS-OO Port objects to join
481     :return: a list of tuple 2 (port_name, SNAPS FloatingIp) objects when ports
482              is not None else a list of Port objects
483     """
484     out = list()
485     fips = neutron.list_floatingips()
486     for fip in fips['floatingips']:
487         if ports:
488             for port_name, port in ports:
489                 if fip['port_id'] == port.id:
490                     out.append((port.name, FloatingIp(
491                         inst_id=fip['id'], ip=fip['floating_ip_address'])))
492                     break
493         else:
494             out.append(FloatingIp(inst_id=fip['id'],
495                                   ip=fip['floating_ip_address']))
496
497     return out
498
499
500 def create_floating_ip(neutron, ext_net_name):
501     """
502     Returns the floating IP object that was created with this call
503     :param neutron: the Neutron client
504     :param ext_net_name: the name of the external network on which to apply the
505                          floating IP address
506     :return: the SNAPS FloatingIp object
507     """
508     logger.info('Creating floating ip to external network - ' + ext_net_name)
509     ext_net = get_network(neutron, network_name=ext_net_name)
510     if ext_net:
511         fip = neutron.create_floatingip(
512             body={'floatingip':
513                   {'floating_network_id': ext_net.id}})
514
515         return FloatingIp(inst_id=fip['floatingip']['id'],
516                           ip=fip['floatingip']['floating_ip_address'])
517     else:
518         raise NeutronException(
519             'Cannot create floating IP, external network not found')
520
521
522 def get_floating_ip(neutron, floating_ip):
523     """
524     Returns a floating IP object that should be identical to the floating_ip
525     parameter
526     :param neutron: the Neutron client
527     :param floating_ip: the SNAPS FloatingIp object
528     :return: hopefully the same floating IP object input
529     """
530     logger.debug('Attempting to retrieve existing floating ip with IP - %s',
531                  floating_ip.ip)
532     os_fip = __get_os_floating_ip(neutron, floating_ip)
533     if os_fip:
534         return FloatingIp(
535             inst_id=os_fip['id'], ip=os_fip['floating_ip_address'])
536
537
538 def __get_os_floating_ip(neutron, floating_ip):
539     """
540     Returns an OpenStack floating IP object
541     parameter
542     :param neutron: the Neutron client
543     :param floating_ip: the SNAPS FloatingIp object
544     :return: hopefully the same floating IP object input
545     """
546     logger.debug('Attempting to retrieve existing floating ip with IP - %s',
547                  floating_ip.ip)
548     fips = neutron.list_floatingips(ip=floating_ip.id)
549
550     for fip in fips['floatingips']:
551         if fip['id'] == floating_ip.id:
552             return fip
553
554
555 def delete_floating_ip(neutron, floating_ip):
556     """
557     Responsible for deleting a floating IP
558     :param neutron: the Neutron client
559     :param floating_ip: the SNAPS FloatingIp object
560     :return:
561     """
562     logger.debug('Attempting to delete existing floating ip with IP - %s',
563                  floating_ip.ip)
564     return neutron.delete_floatingip(floating_ip.id)
565
566
567 class NeutronException(Exception):
568     """
569     Exception when calls to the Keystone client cannot be served properly
570     """