1 # Copyright (c) 2017 Cable Television Laboratories, Inc. ("CableLabs")
2 # and others. All rights reserved.
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:
8 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 from neutronclient.common.exceptions import NotFound
18 from neutronclient.neutron.client import Client
20 from snaps.domain.network import (
21 Port, SecurityGroup, SecurityGroupRule, Router, InterfaceRouter, Subnet,
23 from snaps.domain.vm_inst import FloatingIp
24 from snaps.openstack.utils import keystone_utils
26 __author__ = 'spisarski'
28 logger = logging.getLogger('neutron_utils')
31 Utilities for basic neutron API calls
35 def neutron_client(os_creds):
37 Instantiates and returns a client for communications with OpenStack's
39 :param os_creds: the credentials for connecting to the OpenStack remote API
40 :return: the client object
42 return Client(api_version=os_creds.network_api_version,
43 session=keystone_utils.keystone_session(os_creds))
46 def create_network(neutron, os_creds, network_settings):
48 Creates a network for OpenStack
49 :param neutron: the client
50 :param os_creds: the OpenStack credentials
51 :param network_settings: A dictionary containing the network configuration
52 and is responsible for creating the network
54 :return: a SNAPS-OO Network domain object
56 if neutron and network_settings:
57 logger.info('Creating network with name ' + network_settings.name)
58 json_body = network_settings.dict_for_neutron(os_creds)
59 os_network = neutron.create_network(body=json_body)
60 return Network(**os_network['network'])
62 logger.error("Failed to create network")
66 def delete_network(neutron, network):
68 Deletes a network for OpenStack
69 :param neutron: the client
70 :param network: a SNAPS-OO Network domain object
72 if neutron and network:
73 logger.info('Deleting network with name ' + network.name)
74 neutron.delete_network(network.id)
77 def get_network(neutron, network_name, project_id=None):
79 Returns an object (dictionary) of the first network found with a given name
80 and project_id (if included)
81 :param neutron: the client
82 :param network_name: the name of the network to retrieve
83 :param project_id: the id of the network's project
84 :return: a SNAPS-OO Network domain object
88 net_filter['name'] = network_name
90 net_filter['project_id'] = project_id
92 networks = neutron.list_networks(**net_filter)
93 for network, netInsts in networks.items():
95 if inst.get('name') == network_name:
96 if project_id and inst.get('project_id') == project_id:
97 return {'network': inst}
99 return Network(**inst)
103 def get_network_by_id(neutron, network_id):
105 Returns the network object (dictionary) with the given ID
106 :param neutron: the client
107 :param network_id: the id of the network to retrieve
108 :return: a SNAPS-OO Network domain object
110 networks = neutron.list_networks(**{'id': network_id})
111 for network, netInsts in networks.items():
112 for inst in netInsts:
113 if inst.get('id') == network_id:
114 return Network(**inst)
118 def create_subnet(neutron, subnet_settings, os_creds, network=None):
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
126 :param os_creds: the OpenStack credentials
127 :return: a SNAPS-OO Subnet domain object
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])
136 logger.error("Failed to create subnet.")
140 def delete_subnet(neutron, subnet):
142 Deletes a network subnet for OpenStack
143 :param neutron: the client
144 :param subnet: a SNAPS-OO Subnet domain object
146 if neutron and subnet:
147 logger.info('Deleting subnet with name ' + subnet.name)
148 neutron.delete_subnet(subnet.id)
151 def get_subnet_by_name(neutron, subnet_name):
153 Returns the first subnet object (dictionary) found with a given name
154 :param neutron: the client
155 :param subnet_name: the name of the network to retrieve
156 :return: a SNAPS-OO Subnet domain object
158 subnets = neutron.list_subnets(**{'name': subnet_name})
159 for subnet, subnetInst in subnets.items():
160 for inst in subnetInst:
161 if inst['name'] == subnet_name:
162 return Subnet(**inst)
166 def create_router(neutron, os_creds, router_settings):
168 Creates a router for OpenStack
169 :param neutron: the client
170 :param os_creds: the OpenStack credentials
171 :param router_settings: A dictionary containing the router configuration
172 and is responsible for creating the subnet request
174 :return: a SNAPS-OO Router domain object
177 json_body = router_settings.dict_for_neutron(neutron, os_creds)
178 logger.info('Creating router with name - ' + router_settings.name)
179 os_router = neutron.create_router(json_body)
180 return Router(**os_router['router'])
182 logger.error("Failed to create router.")
186 def delete_router(neutron, router):
188 Deletes a router for OpenStack
189 :param neutron: the client
190 :param router: a SNAPS-OO Router domain object
192 if neutron and router:
193 logger.info('Deleting router with name - ' + router.name)
194 neutron.delete_router(router=router.id)
197 def get_router_by_name(neutron, router_name):
199 Returns the first router object (dictionary) found with a given name
200 :param neutron: the client
201 :param router_name: the name of the network to retrieve
202 :return: a SNAPS-OO Router domain object
204 routers = neutron.list_routers(**{'name': router_name})
205 for router, routerInst in routers.items():
206 for inst in routerInst:
207 if inst.get('name') == router_name:
208 return Router(**inst)
212 def add_interface_router(neutron, router, subnet=None, port=None):
214 Adds an interface router for OpenStack for either a subnet or port.
215 Exception will be raised if requesting for both.
216 :param neutron: the client
217 :param router: the router object
218 :param subnet: the subnet object
219 :param port: the port object
220 :return: the interface router object
223 raise Exception('Cannot add interface to the router. Both subnet and '
224 'port were sent in. Either or please.')
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)
232 raise Exception('Unable to create interface router as neutron client,'
233 ' router or subnet were not created')
236 def remove_interface_router(neutron, router, subnet=None, port=None):
238 Removes an interface router for OpenStack
239 :param neutron: the client
240 :param router: the SNAPS-OO Router domain object
241 :param subnet: the subnet object (either subnet or port, not both)
242 :param port: the port object
246 logger.info('Removing router interface from router named ' +
248 neutron.remove_interface_router(
250 body=__create_port_json_body(subnet, port))
251 except NotFound as e:
252 logger.warning('Could not remove router interface. NotFound - %s',
256 logger.warning('Could not remove router interface, No router object')
259 def __create_port_json_body(subnet=None, port=None):
261 Returns the dictionary required for creating and deleting router
262 interfaces. Will only work on a subnet or port object. Will throw and
263 exception if parameters contain both or neither
264 :param subnet: the subnet object
265 :param port: the port object
269 raise Exception('Cannot create JSON body with both subnet and port')
270 if not subnet and not port:
271 raise Exception('Cannot create JSON body without subnet or port')
274 return {"subnet_id": subnet.id}
276 return {"port_id": port.id}
279 def create_port(neutron, os_creds, port_settings):
281 Creates a port for OpenStack
282 :param neutron: the client
283 :param os_creds: the OpenStack credentials
284 :param port_settings: the settings object for port configuration
285 :return: the SNAPS-OO Port domain object
287 json_body = port_settings.dict_for_neutron(neutron, os_creds)
288 logger.info('Creating port for network with name - %s',
289 port_settings.network_name)
290 os_port = neutron.create_port(body=json_body)['port']
291 return Port(name=os_port['name'], id=os_port['id'],
292 ips=os_port['fixed_ips'],
293 mac_address=os_port['mac_address'],
294 allowed_address_pairs=os_port['allowed_address_pairs'])
297 def delete_port(neutron, port):
299 Removes an OpenStack port
300 :param neutron: the client
301 :param port: the SNAPS-OO Port domain object
304 logger.info('Deleting port with name ' + port.name)
305 neutron.delete_port(port.id)
308 def get_port_by_name(neutron, port_name):
310 Returns the first port object (dictionary) found with a given name
311 :param neutron: the client
312 :param port_name: the name of the port to retrieve
315 ports = neutron.list_ports(**{'name': port_name})
316 for port in ports['ports']:
317 if port['name'] == port_name:
318 return Port(name=port['name'], id=port['id'],
319 ips=port['fixed_ips'], mac_address=port['mac_address'])
323 def create_security_group(neutron, keystone, sec_grp_settings):
325 Creates a security group object in OpenStack
326 :param neutron: the Neutron client
327 :param keystone: the Keystone client
328 :param sec_grp_settings: the security group settings
329 :return: the security group object
331 logger.info('Creating security group with name - %s',
332 sec_grp_settings.name)
333 os_group = neutron.create_security_group(
334 sec_grp_settings.dict_for_neutron(keystone))
335 return SecurityGroup(
336 id=os_group['security_group']['id'],
337 name=os_group['security_group']['name'],
338 project_id=os_group['security_group'].get(
339 'project_id', os_group['security_group'].get('tenant_id')))
342 def delete_security_group(neutron, sec_grp):
344 Deletes a security group object from OpenStack
345 :param neutron: the client
346 :param sec_grp: the SNAPS SecurityGroup object to delete
348 logger.info('Deleting security group with name - %s', sec_grp.name)
349 neutron.delete_security_group(sec_grp.id)
352 def get_security_group(neutron, name):
354 Returns the first security group object of the given name else None
355 :param neutron: the client
356 :param name: the name of security group object to retrieve
358 logger.info('Retrieving security group with name - ' + name)
360 groups = neutron.list_security_groups(**{'name': name})
361 for group in groups['security_groups']:
362 if group['name'] == name:
363 return SecurityGroup(
364 id=group['id'], name=group['name'],
365 project_id=group.get('project_id', group.get('tenant_id')))
369 def get_security_group_by_id(neutron, sec_grp_id):
371 Returns the first security group object of the given name else None
372 :param neutron: the client
373 :param sec_grp_id: the id of the security group to retrieve
375 logger.info('Retrieving security group with ID - ' + sec_grp_id)
377 groups = neutron.list_security_groups(**{'id': sec_grp_id})
378 for group in groups['security_groups']:
379 if group['id'] == sec_grp_id:
380 return SecurityGroup(
381 id=group['id'], name=group['name'],
382 project_id=group.get('project_id', group.get('tenant_id')))
386 def create_security_group_rule(neutron, sec_grp_rule_settings):
388 Creates a security group object in OpenStack
389 :param neutron: the client
390 :param sec_grp_rule_settings: the security group rule settings
391 :return: the security group object
393 logger.info('Creating security group to security group - %s',
394 sec_grp_rule_settings.sec_grp_name)
395 os_rule = neutron.create_security_group_rule(
396 sec_grp_rule_settings.dict_for_neutron(neutron))
397 return SecurityGroupRule(**os_rule['security_group_rule'])
400 def delete_security_group_rule(neutron, sec_grp_rule):
402 Deletes a security group object from OpenStack
403 :param neutron: the client
404 :param sec_grp_rule: the SNAPS SecurityGroupRule object to delete
406 logger.info('Deleting security group rule with ID - %s',
408 neutron.delete_security_group_rule(sec_grp_rule.id)
411 def get_rules_by_security_group(neutron, sec_grp):
413 Retrieves all of the rules for a given security group
414 :param neutron: the client
415 :param sec_grp: the SNAPS SecurityGroup object
417 logger.info('Retrieving security group rules associate with the '
418 'security group - %s', sec_grp.name)
420 rules = neutron.list_security_group_rules(
421 **{'security_group_id': sec_grp.id})
422 for rule in rules['security_group_rules']:
423 if rule['security_group_id'] == sec_grp.id:
424 out.append(SecurityGroupRule(**rule))
428 def get_rule_by_id(neutron, sec_grp, rule_id):
430 Deletes a security group object from OpenStack
431 :param neutron: the client
432 :param sec_grp: the SNAPS SecurityGroup domain object
433 :param rule_id: the rule's ID
435 rules = neutron.list_security_group_rules(
436 **{'security_group_id': sec_grp.id})
437 for rule in rules['security_group_rules']:
438 if rule['id'] == rule_id:
439 return SecurityGroupRule(**rule)
443 def get_external_networks(neutron):
445 Returns a list of external OpenStack network object/dict for all external
447 :param neutron: the client
448 :return: a list of external networks (empty list if none configured)
451 for network in neutron.list_networks(
452 **{'router:external': True})['networks']:
453 out.append({'network': network})
457 def get_floating_ips(neutron):
459 Returns all of the floating IPs
460 :param neutron: the Neutron client
461 :return: a list of SNAPS FloatingIp objects
464 fips = neutron.list_floatingips()
465 for fip in fips['floatingips']:
466 out.append(FloatingIp(inst_id=fip['id'],
467 ip=fip['floating_ip_address']))
472 def create_floating_ip(neutron, ext_net_name):
474 Returns the floating IP object that was created with this call
475 :param neutron: the Neutron client
476 :param ext_net_name: the name of the external network on which to apply the
478 :return: the SNAPS FloatingIp object
480 logger.info('Creating floating ip to external network - ' + ext_net_name)
481 ext_net = get_network(neutron, ext_net_name)
483 fip = neutron.create_floatingip(
485 {'floating_network_id': ext_net.id}})
487 return FloatingIp(inst_id=fip['floatingip']['id'],
488 ip=fip['floatingip']['floating_ip_address'])
490 raise Exception('Cannot create floating IP, '
491 'external network not found')
494 def get_floating_ip(neutron, floating_ip):
496 Returns a floating IP object that should be identical to the floating_ip
498 :param neutron: the Neutron client
499 :param floating_ip: the SNAPS FloatingIp object
500 :return: hopefully the same floating IP object input
502 logger.debug('Attempting to retrieve existing floating ip with IP - %s',
504 os_fip = __get_os_floating_ip(neutron, floating_ip)
507 inst_id=os_fip['id'], ip=os_fip['floating_ip_address'])
510 def __get_os_floating_ip(neutron, floating_ip):
512 Returns an OpenStack floating IP object
514 :param neutron: the Neutron client
515 :param floating_ip: the SNAPS FloatingIp object
516 :return: hopefully the same floating IP object input
518 logger.debug('Attempting to retrieve existing floating ip with IP - %s',
520 fips = neutron.list_floatingips(ip=floating_ip.id)
522 for fip in fips['floatingips']:
523 if fip['id'] == floating_ip.id:
527 def delete_floating_ip(neutron, floating_ip):
529 Responsible for deleting a floating IP
530 :param neutron: the Neutron client
531 :param floating_ip: the SNAPS FloatingIp object
534 logger.debug('Attempting to delete existing floating ip with IP - %s',
536 return neutron.delete_floatingip(floating_ip.id)