Disable port security at network creation (openstack)
[osm/RO.git] / osm_ro / vimconn_openstack.py
1 # -*- coding: utf-8 -*-
2
3 ##
4 # Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U.
5 # This file is part of openmano
6 # All Rights Reserved.
7 #
8 # Licensed under the Apache License, Version 2.0 (the "License"); you may
9 # not use this file except in compliance with the License. You may obtain
10 # a copy of the License at
11 #
12 # http://www.apache.org/licenses/LICENSE-2.0
13 #
14 # Unless required by applicable law or agreed to in writing, software
15 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17 # License for the specific language governing permissions and limitations
18 # under the License.
19 #
20 # For those usages not covered by the Apache License, Version 2.0 please
21 # contact with: nfvlabs@tid.es
22 ##
23
24 '''
25 osconnector implements all the methods to interact with openstack using the python-neutronclient.
26
27 For the VNF forwarding graph, The OpenStack VIM connector calls the
28 networking-sfc Neutron extension methods, whose resources are mapped
29 to the VIM connector's SFC resources as follows:
30 - Classification (OSM) -> Flow Classifier (Neutron)
31 - Service Function Instance (OSM) -> Port Pair (Neutron)
32 - Service Function (OSM) -> Port Pair Group (Neutron)
33 - Service Function Path (OSM) -> Port Chain (Neutron)
34 '''
35 __author__ = "Alfonso Tierno, Gerardo Garcia, Pablo Montes, xFlow Research, Igor D.C., Eduardo Sousa"
36 __date__ = "$22-sep-2017 23:59:59$"
37
38 import vimconn
39 # import json
40 import logging
41 import netaddr
42 import time
43 import yaml
44 import random
45 import re
46 import copy
47 from pprint import pformat
48 from types import StringTypes
49
50 from novaclient import client as nClient, exceptions as nvExceptions
51 from keystoneauth1.identity import v2, v3
52 from keystoneauth1 import session
53 import keystoneclient.exceptions as ksExceptions
54 import keystoneclient.v3.client as ksClient_v3
55 import keystoneclient.v2_0.client as ksClient_v2
56 from glanceclient import client as glClient
57 import glanceclient.exc as gl1Exceptions
58 from cinderclient import client as cClient
59 from httplib import HTTPException
60 from neutronclient.neutron import client as neClient
61 from neutronclient.common import exceptions as neExceptions
62 from requests.exceptions import ConnectionError
63
64
65 """contain the openstack virtual machine status to openmano status"""
66 vmStatus2manoFormat={'ACTIVE':'ACTIVE',
67 'PAUSED':'PAUSED',
68 'SUSPENDED': 'SUSPENDED',
69 'SHUTOFF':'INACTIVE',
70 'BUILD':'BUILD',
71 'ERROR':'ERROR','DELETED':'DELETED'
72 }
73 netStatus2manoFormat={'ACTIVE':'ACTIVE','PAUSED':'PAUSED','INACTIVE':'INACTIVE','BUILD':'BUILD','ERROR':'ERROR','DELETED':'DELETED'
74 }
75
76 supportedClassificationTypes = ['legacy_flow_classifier']
77
78 #global var to have a timeout creating and deleting volumes
79 volume_timeout = 600
80 server_timeout = 600
81
82
83 class SafeDumper(yaml.SafeDumper):
84 def represent_data(self, data):
85 # Openstack APIs use custom subclasses of dict and YAML safe dumper
86 # is designed to not handle that (reference issue 142 of pyyaml)
87 if isinstance(data, dict) and data.__class__ != dict:
88 # A simple solution is to convert those items back to dicts
89 data = dict(data.items())
90
91 return super(SafeDumper, self).represent_data(data)
92
93
94 class vimconnector(vimconn.vimconnector):
95 def __init__(self, uuid, name, tenant_id, tenant_name, url, url_admin=None, user=None, passwd=None,
96 log_level=None, config={}, persistent_info={}):
97 '''using common constructor parameters. In this case
98 'url' is the keystone authorization url,
99 'url_admin' is not use
100 '''
101 api_version = config.get('APIversion')
102 if api_version and api_version not in ('v3.3', 'v2.0', '2', '3'):
103 raise vimconn.vimconnException("Invalid value '{}' for config:APIversion. "
104 "Allowed values are 'v3.3', 'v2.0', '2' or '3'".format(api_version))
105 vim_type = config.get('vim_type')
106 if vim_type and vim_type not in ('vio', 'VIO'):
107 raise vimconn.vimconnException("Invalid value '{}' for config:vim_type."
108 "Allowed values are 'vio' or 'VIO'".format(vim_type))
109
110 if config.get('dataplane_net_vlan_range') is not None:
111 #validate vlan ranges provided by user
112 self._validate_vlan_ranges(config.get('dataplane_net_vlan_range'), 'dataplane_net_vlan_range')
113
114 if config.get('multisegment_vlan_range') is not None:
115 #validate vlan ranges provided by user
116 self._validate_vlan_ranges(config.get('multisegment_vlan_range'), 'multisegment_vlan_range')
117
118 vimconn.vimconnector.__init__(self, uuid, name, tenant_id, tenant_name, url, url_admin, user, passwd, log_level,
119 config)
120
121 if self.config.get("insecure") and self.config.get("ca_cert"):
122 raise vimconn.vimconnException("options insecure and ca_cert are mutually exclusive")
123 self.verify = True
124 if self.config.get("insecure"):
125 self.verify = False
126 if self.config.get("ca_cert"):
127 self.verify = self.config.get("ca_cert")
128
129 if not url:
130 raise TypeError('url param can not be NoneType')
131 self.persistent_info = persistent_info
132 self.availability_zone = persistent_info.get('availability_zone', None)
133 self.session = persistent_info.get('session', {'reload_client': True})
134 self.my_tenant_id = self.session.get('my_tenant_id')
135 self.nova = self.session.get('nova')
136 self.neutron = self.session.get('neutron')
137 self.cinder = self.session.get('cinder')
138 self.glance = self.session.get('glance')
139 # self.glancev1 = self.session.get('glancev1')
140 self.keystone = self.session.get('keystone')
141 self.api_version3 = self.session.get('api_version3')
142 self.vim_type = self.config.get("vim_type")
143 if self.vim_type:
144 self.vim_type = self.vim_type.upper()
145 if self.config.get("use_internal_endpoint"):
146 self.endpoint_type = "internalURL"
147 else:
148 self.endpoint_type = None
149
150 self.logger = logging.getLogger('openmano.vim.openstack')
151
152 # allow security_groups to be a list or a single string
153 if isinstance(self.config.get('security_groups'), str):
154 self.config['security_groups'] = [self.config['security_groups']]
155 self.security_groups_id = None
156
157 ####### VIO Specific Changes #########
158 if self.vim_type == "VIO":
159 self.logger = logging.getLogger('openmano.vim.vio')
160
161 if log_level:
162 self.logger.setLevel( getattr(logging, log_level))
163
164 def __getitem__(self, index):
165 """Get individuals parameters.
166 Throw KeyError"""
167 if index == 'project_domain_id':
168 return self.config.get("project_domain_id")
169 elif index == 'user_domain_id':
170 return self.config.get("user_domain_id")
171 else:
172 return vimconn.vimconnector.__getitem__(self, index)
173
174 def __setitem__(self, index, value):
175 """Set individuals parameters and it is marked as dirty so to force connection reload.
176 Throw KeyError"""
177 if index == 'project_domain_id':
178 self.config["project_domain_id"] = value
179 elif index == 'user_domain_id':
180 self.config["user_domain_id"] = value
181 else:
182 vimconn.vimconnector.__setitem__(self, index, value)
183 self.session['reload_client'] = True
184
185 def serialize(self, value):
186 """Serialization of python basic types.
187
188 In the case value is not serializable a message will be logged and a
189 simple representation of the data that cannot be converted back to
190 python is returned.
191 """
192 if isinstance(value, StringTypes):
193 return value
194
195 try:
196 return yaml.dump(value, Dumper=SafeDumper,
197 default_flow_style=True, width=256)
198 except yaml.representer.RepresenterError:
199 self.logger.debug(
200 'The following entity cannot be serialized in YAML:'
201 '\n\n%s\n\n', pformat(value), exc_info=True)
202 return str(value)
203
204 def _reload_connection(self):
205 '''Called before any operation, it check if credentials has changed
206 Throw keystoneclient.apiclient.exceptions.AuthorizationFailure
207 '''
208 #TODO control the timing and possible token timeout, but it seams that python client does this task for us :-)
209 if self.session['reload_client']:
210 if self.config.get('APIversion'):
211 self.api_version3 = self.config['APIversion'] == 'v3.3' or self.config['APIversion'] == '3'
212 else: # get from ending auth_url that end with v3 or with v2.0
213 self.api_version3 = self.url.endswith("/v3") or self.url.endswith("/v3/")
214 self.session['api_version3'] = self.api_version3
215 if self.api_version3:
216 if self.config.get('project_domain_id') or self.config.get('project_domain_name'):
217 project_domain_id_default = None
218 else:
219 project_domain_id_default = 'default'
220 if self.config.get('user_domain_id') or self.config.get('user_domain_name'):
221 user_domain_id_default = None
222 else:
223 user_domain_id_default = 'default'
224 auth = v3.Password(auth_url=self.url,
225 username=self.user,
226 password=self.passwd,
227 project_name=self.tenant_name,
228 project_id=self.tenant_id,
229 project_domain_id=self.config.get('project_domain_id', project_domain_id_default),
230 user_domain_id=self.config.get('user_domain_id', user_domain_id_default),
231 project_domain_name=self.config.get('project_domain_name'),
232 user_domain_name=self.config.get('user_domain_name'))
233 else:
234 auth = v2.Password(auth_url=self.url,
235 username=self.user,
236 password=self.passwd,
237 tenant_name=self.tenant_name,
238 tenant_id=self.tenant_id)
239 sess = session.Session(auth=auth, verify=self.verify)
240 # addedd region_name to keystone, nova, neutron and cinder to support distributed cloud for Wind River Titanium cloud and StarlingX
241 region_name = self.config.get('region_name')
242 if self.api_version3:
243 self.keystone = ksClient_v3.Client(session=sess, endpoint_type=self.endpoint_type, region_name=region_name)
244 else:
245 self.keystone = ksClient_v2.Client(session=sess, endpoint_type=self.endpoint_type)
246 self.session['keystone'] = self.keystone
247 # In order to enable microversion functionality an explicit microversion must be specified in 'config'.
248 # This implementation approach is due to the warning message in
249 # https://developer.openstack.org/api-guide/compute/microversions.html
250 # where it is stated that microversion backwards compatibility is not guaranteed and clients should
251 # always require an specific microversion.
252 # To be able to use 'device role tagging' functionality define 'microversion: 2.32' in datacenter config
253 version = self.config.get("microversion")
254 if not version:
255 version = "2.1"
256 # addedd region_name to keystone, nova, neutron and cinder to support distributed cloud for Wind River Titanium cloud and StarlingX
257 self.nova = self.session['nova'] = nClient.Client(str(version), session=sess, endpoint_type=self.endpoint_type, region_name=region_name)
258 self.neutron = self.session['neutron'] = neClient.Client('2.0', session=sess, endpoint_type=self.endpoint_type, region_name=region_name)
259 self.cinder = self.session['cinder'] = cClient.Client(2, session=sess, endpoint_type=self.endpoint_type, region_name=region_name)
260 try:
261 self.my_tenant_id = self.session['my_tenant_id'] = sess.get_project_id()
262 except Exception as e:
263 self.logger.error("Cannot get project_id from session", exc_info=True)
264 if self.endpoint_type == "internalURL":
265 glance_service_id = self.keystone.services.list(name="glance")[0].id
266 glance_endpoint = self.keystone.endpoints.list(glance_service_id, interface="internal")[0].url
267 else:
268 glance_endpoint = None
269 self.glance = self.session['glance'] = glClient.Client(2, session=sess, endpoint=glance_endpoint)
270 # using version 1 of glance client in new_image()
271 # self.glancev1 = self.session['glancev1'] = glClient.Client('1', session=sess,
272 # endpoint=glance_endpoint)
273 self.session['reload_client'] = False
274 self.persistent_info['session'] = self.session
275 # add availablity zone info inside self.persistent_info
276 self._set_availablity_zones()
277 self.persistent_info['availability_zone'] = self.availability_zone
278 self.security_groups_id = None # force to get again security_groups_ids next time they are needed
279
280 def __net_os2mano(self, net_list_dict):
281 '''Transform the net openstack format to mano format
282 net_list_dict can be a list of dict or a single dict'''
283 if type(net_list_dict) is dict:
284 net_list_=(net_list_dict,)
285 elif type(net_list_dict) is list:
286 net_list_=net_list_dict
287 else:
288 raise TypeError("param net_list_dict must be a list or a dictionary")
289 for net in net_list_:
290 if net.get('provider:network_type') == "vlan":
291 net['type']='data'
292 else:
293 net['type']='bridge'
294
295 def __classification_os2mano(self, class_list_dict):
296 """Transform the openstack format (Flow Classifier) to mano format
297 (Classification) class_list_dict can be a list of dict or a single dict
298 """
299 if isinstance(class_list_dict, dict):
300 class_list_ = [class_list_dict]
301 elif isinstance(class_list_dict, list):
302 class_list_ = class_list_dict
303 else:
304 raise TypeError(
305 "param class_list_dict must be a list or a dictionary")
306 for classification in class_list_:
307 id = classification.pop('id')
308 name = classification.pop('name')
309 description = classification.pop('description')
310 project_id = classification.pop('project_id')
311 tenant_id = classification.pop('tenant_id')
312 original_classification = copy.deepcopy(classification)
313 classification.clear()
314 classification['ctype'] = 'legacy_flow_classifier'
315 classification['definition'] = original_classification
316 classification['id'] = id
317 classification['name'] = name
318 classification['description'] = description
319 classification['project_id'] = project_id
320 classification['tenant_id'] = tenant_id
321
322 def __sfi_os2mano(self, sfi_list_dict):
323 """Transform the openstack format (Port Pair) to mano format (SFI)
324 sfi_list_dict can be a list of dict or a single dict
325 """
326 if isinstance(sfi_list_dict, dict):
327 sfi_list_ = [sfi_list_dict]
328 elif isinstance(sfi_list_dict, list):
329 sfi_list_ = sfi_list_dict
330 else:
331 raise TypeError(
332 "param sfi_list_dict must be a list or a dictionary")
333 for sfi in sfi_list_:
334 sfi['ingress_ports'] = []
335 sfi['egress_ports'] = []
336 if sfi.get('ingress'):
337 sfi['ingress_ports'].append(sfi['ingress'])
338 if sfi.get('egress'):
339 sfi['egress_ports'].append(sfi['egress'])
340 del sfi['ingress']
341 del sfi['egress']
342 params = sfi.get('service_function_parameters')
343 sfc_encap = False
344 if params:
345 correlation = params.get('correlation')
346 if correlation:
347 sfc_encap = True
348 sfi['sfc_encap'] = sfc_encap
349 del sfi['service_function_parameters']
350
351 def __sf_os2mano(self, sf_list_dict):
352 """Transform the openstack format (Port Pair Group) to mano format (SF)
353 sf_list_dict can be a list of dict or a single dict
354 """
355 if isinstance(sf_list_dict, dict):
356 sf_list_ = [sf_list_dict]
357 elif isinstance(sf_list_dict, list):
358 sf_list_ = sf_list_dict
359 else:
360 raise TypeError(
361 "param sf_list_dict must be a list or a dictionary")
362 for sf in sf_list_:
363 del sf['port_pair_group_parameters']
364 sf['sfis'] = sf['port_pairs']
365 del sf['port_pairs']
366
367 def __sfp_os2mano(self, sfp_list_dict):
368 """Transform the openstack format (Port Chain) to mano format (SFP)
369 sfp_list_dict can be a list of dict or a single dict
370 """
371 if isinstance(sfp_list_dict, dict):
372 sfp_list_ = [sfp_list_dict]
373 elif isinstance(sfp_list_dict, list):
374 sfp_list_ = sfp_list_dict
375 else:
376 raise TypeError(
377 "param sfp_list_dict must be a list or a dictionary")
378 for sfp in sfp_list_:
379 params = sfp.pop('chain_parameters')
380 sfc_encap = False
381 if params:
382 correlation = params.get('correlation')
383 if correlation:
384 sfc_encap = True
385 sfp['sfc_encap'] = sfc_encap
386 sfp['spi'] = sfp.pop('chain_id')
387 sfp['classifications'] = sfp.pop('flow_classifiers')
388 sfp['service_functions'] = sfp.pop('port_pair_groups')
389
390 # placeholder for now; read TODO note below
391 def _validate_classification(self, type, definition):
392 # only legacy_flow_classifier Type is supported at this point
393 return True
394 # TODO(igordcard): this method should be an abstract method of an
395 # abstract Classification class to be implemented by the specific
396 # Types. Also, abstract vimconnector should call the validation
397 # method before the implemented VIM connectors are called.
398
399 def _format_exception(self, exception):
400 '''Transform a keystone, nova, neutron exception into a vimconn exception'''
401
402 # Fixing bug 665 https://osm.etsi.org/bugzilla/show_bug.cgi?id=665
403 # There are some openstack versions that message error are unicode with non English
404 message_error = exception.message
405 if isinstance(message_error, unicode):
406 message_error = message_error.encode("utf")
407
408 if isinstance(exception, (neExceptions.NetworkNotFoundClient, nvExceptions.NotFound, ksExceptions.NotFound,
409 gl1Exceptions.HTTPNotFound)):
410 raise vimconn.vimconnNotFoundException(type(exception).__name__ + ": " + message_error)
411 elif isinstance(exception, (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError,
412 ConnectionError, ksExceptions.ConnectionError, neExceptions.ConnectionFailed)):
413 raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + message_error)
414 elif isinstance(exception, (KeyError, nvExceptions.BadRequest, ksExceptions.BadRequest)):
415 raise vimconn.vimconnException(type(exception).__name__ + ": " + message_error)
416 elif isinstance(exception, (nvExceptions.ClientException, ksExceptions.ClientException,
417 neExceptions.NeutronException)):
418 raise vimconn.vimconnUnexpectedResponse(type(exception).__name__ + ": " + message_error)
419 elif isinstance(exception, nvExceptions.Conflict):
420 raise vimconn.vimconnConflictException(type(exception).__name__ + ": " + message_error)
421 elif isinstance(exception, vimconn.vimconnException):
422 raise exception
423 else: # ()
424 self.logger.error("General Exception " + message_error, exc_info=True)
425 raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + message_error)
426
427 def _get_ids_from_name(self):
428 """
429 Obtain ids from name of tenant and security_groups. Store at self .security_groups_id"
430 :return: None
431 """
432 # get tenant_id if only tenant_name is supplied
433 self._reload_connection()
434 if not self.my_tenant_id:
435 raise vimconn.vimconnConnectionException("Error getting tenant information from name={} id={}".
436 format(self.tenant_name, self.tenant_id))
437 if self.config.get('security_groups') and not self.security_groups_id:
438 # convert from name to id
439 neutron_sg_list = self.neutron.list_security_groups(tenant_id=self.my_tenant_id)["security_groups"]
440
441 self.security_groups_id = []
442 for sg in self.config.get('security_groups'):
443 for neutron_sg in neutron_sg_list:
444 if sg in (neutron_sg["id"], neutron_sg["name"]):
445 self.security_groups_id.append(neutron_sg["id"])
446 break
447 else:
448 self.security_groups_id = None
449 raise vimconn.vimconnConnectionException("Not found security group {} for this tenant".format(sg))
450
451 def get_tenant_list(self, filter_dict={}):
452 '''Obtain tenants of VIM
453 filter_dict can contain the following keys:
454 name: filter by tenant name
455 id: filter by tenant uuid/id
456 <other VIM specific>
457 Returns the tenant list of dictionaries: [{'name':'<name>, 'id':'<id>, ...}, ...]
458 '''
459 self.logger.debug("Getting tenants from VIM filter: '%s'", str(filter_dict))
460 try:
461 self._reload_connection()
462 if self.api_version3:
463 project_class_list = self.keystone.projects.list(name=filter_dict.get("name"))
464 else:
465 project_class_list = self.keystone.tenants.findall(**filter_dict)
466 project_list=[]
467 for project in project_class_list:
468 if filter_dict.get('id') and filter_dict["id"] != project.id:
469 continue
470 project_list.append(project.to_dict())
471 return project_list
472 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
473 self._format_exception(e)
474
475 def new_tenant(self, tenant_name, tenant_description):
476 '''Adds a new tenant to openstack VIM. Returns the tenant identifier'''
477 self.logger.debug("Adding a new tenant name: %s", tenant_name)
478 try:
479 self._reload_connection()
480 if self.api_version3:
481 project = self.keystone.projects.create(tenant_name, self.config.get("project_domain_id", "default"),
482 description=tenant_description, is_domain=False)
483 else:
484 project = self.keystone.tenants.create(tenant_name, tenant_description)
485 return project.id
486 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ksExceptions.BadRequest, ConnectionError) as e:
487 self._format_exception(e)
488
489 def delete_tenant(self, tenant_id):
490 '''Delete a tenant from openstack VIM. Returns the old tenant identifier'''
491 self.logger.debug("Deleting tenant %s from VIM", tenant_id)
492 try:
493 self._reload_connection()
494 if self.api_version3:
495 self.keystone.projects.delete(tenant_id)
496 else:
497 self.keystone.tenants.delete(tenant_id)
498 return tenant_id
499 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ksExceptions.NotFound, ConnectionError) as e:
500 self._format_exception(e)
501
502 def new_network(self,net_name, net_type, ip_profile=None, shared=False, vlan=None):
503 """Adds a tenant network to VIM
504 Params:
505 'net_name': name of the network
506 'net_type': one of:
507 'bridge': overlay isolated network
508 'data': underlay E-LAN network for Passthrough and SRIOV interfaces
509 'ptp': underlay E-LINE network for Passthrough and SRIOV interfaces.
510 'ip_profile': is a dict containing the IP parameters of the network
511 'ip_version': can be "IPv4" or "IPv6" (Currently only IPv4 is implemented)
512 'subnet_address': ip_prefix_schema, that is X.X.X.X/Y
513 'gateway_address': (Optional) ip_schema, that is X.X.X.X
514 'dns_address': (Optional) comma separated list of ip_schema, e.g. X.X.X.X[,X,X,X,X]
515 'dhcp_enabled': True or False
516 'dhcp_start_address': ip_schema, first IP to grant
517 'dhcp_count': number of IPs to grant.
518 'shared': if this network can be seen/use by other tenants/organization
519 'vlan': in case of a data or ptp net_type, the intended vlan tag to be used for the network
520 Returns a tuple with the network identifier and created_items, or raises an exception on error
521 created_items can be None or a dictionary where this method can include key-values that will be passed to
522 the method delete_network. Can be used to store created segments, created l2gw connections, etc.
523 Format is vimconnector dependent, but do not use nested dictionaries and a value of None should be the same
524 as not present.
525 """
526 self.logger.debug("Adding a new network to VIM name '%s', type '%s'", net_name, net_type)
527 # self.logger.debug(">>>>>>>>>>>>>>>>>> IP profile %s", str(ip_profile))
528 try:
529 new_net = None
530 created_items = {}
531 self._reload_connection()
532 network_dict = {'name': net_name, 'admin_state_up': True}
533 if net_type=="data" or net_type=="ptp":
534 if self.config.get('dataplane_physical_net') == None:
535 raise vimconn.vimconnConflictException("You must provide a 'dataplane_physical_net' at config value before creating sriov network")
536 if not self.config.get('multisegment_support'):
537 network_dict["provider:physical_network"] = self.config[
538 'dataplane_physical_net'] # "physnet_sriov" #TODO physical
539 network_dict["provider:network_type"] = "vlan"
540 if vlan!=None:
541 network_dict["provider:network_type"] = vlan
542 else:
543 ###### Multi-segment case ######
544 segment_list = []
545 segment1_dict = {}
546 segment1_dict["provider:physical_network"] = ''
547 segment1_dict["provider:network_type"] = 'vxlan'
548 segment_list.append(segment1_dict)
549 segment2_dict = {}
550 segment2_dict["provider:physical_network"] = self.config['dataplane_physical_net']
551 segment2_dict["provider:network_type"] = "vlan"
552 if self.config.get('multisegment_vlan_range'):
553 vlanID = self._generate_multisegment_vlanID()
554 segment2_dict["provider:segmentation_id"] = vlanID
555 # else
556 # raise vimconn.vimconnConflictException(
557 # "You must provide 'multisegment_vlan_range' at config dict before creating a multisegment network")
558 segment_list.append(segment2_dict)
559 network_dict["segments"] = segment_list
560
561 ####### VIO Specific Changes #########
562 if self.vim_type == "VIO":
563 if vlan is not None:
564 network_dict["provider:segmentation_id"] = vlan
565 else:
566 if self.config.get('dataplane_net_vlan_range') is None:
567 raise vimconn.vimconnConflictException("You must provide "\
568 "'dataplane_net_vlan_range' in format [start_ID - end_ID]"\
569 "at config value before creating sriov network with vlan tag")
570
571 network_dict["provider:segmentation_id"] = self._generate_vlanID()
572
573 network_dict["shared"] = shared
574 if self.config.get("disable_network_port_security"):
575 network_dict["port_security_enabled"] = False
576 new_net = self.neutron.create_network({'network':network_dict})
577 # print new_net
578 # create subnetwork, even if there is no profile
579 if not ip_profile:
580 ip_profile = {}
581 if not ip_profile.get('subnet_address'):
582 #Fake subnet is required
583 subnet_rand = random.randint(0, 255)
584 ip_profile['subnet_address'] = "192.168.{}.0/24".format(subnet_rand)
585 if 'ip_version' not in ip_profile:
586 ip_profile['ip_version'] = "IPv4"
587 subnet = {"name": net_name+"-subnet",
588 "network_id": new_net["network"]["id"],
589 "ip_version": 4 if ip_profile['ip_version']=="IPv4" else 6,
590 "cidr": ip_profile['subnet_address']
591 }
592 # Gateway should be set to None if not needed. Otherwise openstack assigns one by default
593 if ip_profile.get('gateway_address'):
594 subnet['gateway_ip'] = ip_profile['gateway_address']
595 else:
596 subnet['gateway_ip'] = None
597 if ip_profile.get('dns_address'):
598 subnet['dns_nameservers'] = ip_profile['dns_address'].split(";")
599 if 'dhcp_enabled' in ip_profile:
600 subnet['enable_dhcp'] = False if \
601 ip_profile['dhcp_enabled']=="false" or ip_profile['dhcp_enabled']==False else True
602 if ip_profile.get('dhcp_start_address'):
603 subnet['allocation_pools'] = []
604 subnet['allocation_pools'].append(dict())
605 subnet['allocation_pools'][0]['start'] = ip_profile['dhcp_start_address']
606 if ip_profile.get('dhcp_count'):
607 #parts = ip_profile['dhcp_start_address'].split('.')
608 #ip_int = (int(parts[0]) << 24) + (int(parts[1]) << 16) + (int(parts[2]) << 8) + int(parts[3])
609 ip_int = int(netaddr.IPAddress(ip_profile['dhcp_start_address']))
610 ip_int += ip_profile['dhcp_count'] - 1
611 ip_str = str(netaddr.IPAddress(ip_int))
612 subnet['allocation_pools'][0]['end'] = ip_str
613 #self.logger.debug(">>>>>>>>>>>>>>>>>> Subnet: %s", str(subnet))
614 self.neutron.create_subnet({"subnet": subnet} )
615
616 if net_type == "data" and self.config.get('multisegment_support'):
617 if self.config.get('l2gw_support'):
618 l2gw_list = self.neutron.list_l2_gateways().get("l2_gateways", ())
619 for l2gw in l2gw_list:
620 l2gw_conn = {}
621 l2gw_conn["l2_gateway_id"] = l2gw["id"]
622 l2gw_conn["network_id"] = new_net["network"]["id"]
623 l2gw_conn["segmentation_id"] = str(vlanID)
624 new_l2gw_conn = self.neutron.create_l2_gateway_connection({"l2_gateway_connection": l2gw_conn})
625 created_items["l2gwconn:" + str(new_l2gw_conn["l2_gateway_connection"]["id"])] = True
626 return new_net["network"]["id"], created_items
627 except Exception as e:
628 #delete l2gw connections (if any) before deleting the network
629 for k, v in created_items.items():
630 if not v: # skip already deleted
631 continue
632 try:
633 k_item, _, k_id = k.partition(":")
634 if k_item == "l2gwconn":
635 self.neutron.delete_l2_gateway_connection(k_id)
636 except Exception as e2:
637 self.logger.error("Error deleting l2 gateway connection: {}: {}".format(type(e2).__name__, e2))
638 if new_net:
639 self.neutron.delete_network(new_net['network']['id'])
640 self._format_exception(e)
641
642 def get_network_list(self, filter_dict={}):
643 '''Obtain tenant networks of VIM
644 Filter_dict can be:
645 name: network name
646 id: network uuid
647 shared: boolean
648 tenant_id: tenant
649 admin_state_up: boolean
650 status: 'ACTIVE'
651 Returns the network list of dictionaries
652 '''
653 self.logger.debug("Getting network from VIM filter: '%s'", str(filter_dict))
654 try:
655 self._reload_connection()
656 filter_dict_os = filter_dict.copy()
657 if self.api_version3 and "tenant_id" in filter_dict_os:
658 filter_dict_os['project_id'] = filter_dict_os.pop('tenant_id') #T ODO check
659 net_dict = self.neutron.list_networks(**filter_dict_os)
660 net_list = net_dict["networks"]
661 self.__net_os2mano(net_list)
662 return net_list
663 except (neExceptions.ConnectionFailed, ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e:
664 self._format_exception(e)
665
666 def get_network(self, net_id):
667 '''Obtain details of network from VIM
668 Returns the network information from a network id'''
669 self.logger.debug(" Getting tenant network %s from VIM", net_id)
670 filter_dict={"id": net_id}
671 net_list = self.get_network_list(filter_dict)
672 if len(net_list)==0:
673 raise vimconn.vimconnNotFoundException("Network '{}' not found".format(net_id))
674 elif len(net_list)>1:
675 raise vimconn.vimconnConflictException("Found more than one network with this criteria")
676 net = net_list[0]
677 subnets=[]
678 for subnet_id in net.get("subnets", () ):
679 try:
680 subnet = self.neutron.show_subnet(subnet_id)
681 except Exception as e:
682 self.logger.error("osconnector.get_network(): Error getting subnet %s %s" % (net_id, str(e)))
683 subnet = {"id": subnet_id, "fault": str(e)}
684 subnets.append(subnet)
685 net["subnets"] = subnets
686 net["encapsulation"] = net.get('provider:network_type')
687 net["encapsulation_type"] = net.get('provider:network_type')
688 net["segmentation_id"] = net.get('provider:segmentation_id')
689 net["encapsulation_id"] = net.get('provider:segmentation_id')
690 return net
691
692 def delete_network(self, net_id, created_items=None):
693 """
694 Removes a tenant network from VIM and its associated elements
695 :param net_id: VIM identifier of the network, provided by method new_network
696 :param created_items: dictionary with extra items to be deleted. provided by method new_network
697 Returns the network identifier or raises an exception upon error or when network is not found
698 """
699 self.logger.debug("Deleting network '%s' from VIM", net_id)
700 if created_items == None:
701 created_items = {}
702 try:
703 self._reload_connection()
704 #delete l2gw connections (if any) before deleting the network
705 for k, v in created_items.items():
706 if not v: # skip already deleted
707 continue
708 try:
709 k_item, _, k_id = k.partition(":")
710 if k_item == "l2gwconn":
711 self.neutron.delete_l2_gateway_connection(k_id)
712 except Exception as e:
713 self.logger.error("Error deleting l2 gateway connection: {}: {}".format(type(e).__name__, e))
714 #delete VM ports attached to this networks before the network
715 ports = self.neutron.list_ports(network_id=net_id)
716 for p in ports['ports']:
717 try:
718 self.neutron.delete_port(p["id"])
719 except Exception as e:
720 self.logger.error("Error deleting port %s: %s", p["id"], str(e))
721 self.neutron.delete_network(net_id)
722 return net_id
723 except (neExceptions.ConnectionFailed, neExceptions.NetworkNotFoundClient, neExceptions.NeutronException,
724 ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e:
725 self._format_exception(e)
726
727 def refresh_nets_status(self, net_list):
728 '''Get the status of the networks
729 Params: the list of network identifiers
730 Returns a dictionary with:
731 net_id: #VIM id of this network
732 status: #Mandatory. Text with one of:
733 # DELETED (not found at vim)
734 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
735 # OTHER (Vim reported other status not understood)
736 # ERROR (VIM indicates an ERROR status)
737 # ACTIVE, INACTIVE, DOWN (admin down),
738 # BUILD (on building process)
739 #
740 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
741 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
742
743 '''
744 net_dict={}
745 for net_id in net_list:
746 net = {}
747 try:
748 net_vim = self.get_network(net_id)
749 if net_vim['status'] in netStatus2manoFormat:
750 net["status"] = netStatus2manoFormat[ net_vim['status'] ]
751 else:
752 net["status"] = "OTHER"
753 net["error_msg"] = "VIM status reported " + net_vim['status']
754
755 if net['status'] == "ACTIVE" and not net_vim['admin_state_up']:
756 net['status'] = 'DOWN'
757
758 net['vim_info'] = self.serialize(net_vim)
759
760 if net_vim.get('fault'): #TODO
761 net['error_msg'] = str(net_vim['fault'])
762 except vimconn.vimconnNotFoundException as e:
763 self.logger.error("Exception getting net status: %s", str(e))
764 net['status'] = "DELETED"
765 net['error_msg'] = str(e)
766 except vimconn.vimconnException as e:
767 self.logger.error("Exception getting net status: %s", str(e))
768 net['status'] = "VIM_ERROR"
769 net['error_msg'] = str(e)
770 net_dict[net_id] = net
771 return net_dict
772
773 def get_flavor(self, flavor_id):
774 '''Obtain flavor details from the VIM. Returns the flavor dict details'''
775 self.logger.debug("Getting flavor '%s'", flavor_id)
776 try:
777 self._reload_connection()
778 flavor = self.nova.flavors.find(id=flavor_id)
779 #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
780 return flavor.to_dict()
781 except (nvExceptions.NotFound, nvExceptions.ClientException, ksExceptions.ClientException, ConnectionError) as e:
782 self._format_exception(e)
783
784 def get_flavor_id_from_data(self, flavor_dict):
785 """Obtain flavor id that match the flavor description
786 Returns the flavor_id or raises a vimconnNotFoundException
787 flavor_dict: contains the required ram, vcpus, disk
788 If 'use_existing_flavors' is set to True at config, the closer flavor that provides same or more ram, vcpus
789 and disk is returned. Otherwise a flavor with exactly same ram, vcpus and disk is returned or a
790 vimconnNotFoundException is raised
791 """
792 exact_match = False if self.config.get('use_existing_flavors') else True
793 try:
794 self._reload_connection()
795 flavor_candidate_id = None
796 flavor_candidate_data = (10000, 10000, 10000)
797 flavor_target = (flavor_dict["ram"], flavor_dict["vcpus"], flavor_dict["disk"])
798 # numa=None
799 numas = flavor_dict.get("extended", {}).get("numas")
800 if numas:
801 #TODO
802 raise vimconn.vimconnNotFoundException("Flavor with EPA still not implemted")
803 # if len(numas) > 1:
804 # raise vimconn.vimconnNotFoundException("Cannot find any flavor with more than one numa")
805 # numa=numas[0]
806 # numas = extended.get("numas")
807 for flavor in self.nova.flavors.list():
808 epa = flavor.get_keys()
809 if epa:
810 continue
811 # TODO
812 flavor_data = (flavor.ram, flavor.vcpus, flavor.disk)
813 if flavor_data == flavor_target:
814 return flavor.id
815 elif not exact_match and flavor_target < flavor_data < flavor_candidate_data:
816 flavor_candidate_id = flavor.id
817 flavor_candidate_data = flavor_data
818 if not exact_match and flavor_candidate_id:
819 return flavor_candidate_id
820 raise vimconn.vimconnNotFoundException("Cannot find any flavor matching '{}'".format(str(flavor_dict)))
821 except (nvExceptions.NotFound, nvExceptions.ClientException, ksExceptions.ClientException, ConnectionError) as e:
822 self._format_exception(e)
823
824 def new_flavor(self, flavor_data, change_name_if_used=True):
825 '''Adds a tenant flavor to openstack VIM
826 if change_name_if_used is True, it will change name in case of conflict, because it is not supported name repetition
827 Returns the flavor identifier
828 '''
829 self.logger.debug("Adding flavor '%s'", str(flavor_data))
830 retry=0
831 max_retries=3
832 name_suffix = 0
833 try:
834 name=flavor_data['name']
835 while retry<max_retries:
836 retry+=1
837 try:
838 self._reload_connection()
839 if change_name_if_used:
840 #get used names
841 fl_names=[]
842 fl=self.nova.flavors.list()
843 for f in fl:
844 fl_names.append(f.name)
845 while name in fl_names:
846 name_suffix += 1
847 name = flavor_data['name']+"-" + str(name_suffix)
848
849 ram = flavor_data.get('ram',64)
850 vcpus = flavor_data.get('vcpus',1)
851 numa_properties=None
852
853 extended = flavor_data.get("extended")
854 if extended:
855 numas=extended.get("numas")
856 if numas:
857 numa_nodes = len(numas)
858 if numa_nodes > 1:
859 return -1, "Can not add flavor with more than one numa"
860 numa_properties = {"hw:numa_nodes":str(numa_nodes)}
861 numa_properties["hw:mem_page_size"] = "large"
862 numa_properties["hw:cpu_policy"] = "dedicated"
863 numa_properties["hw:numa_mempolicy"] = "strict"
864 if self.vim_type == "VIO":
865 numa_properties["vmware:extra_config"] = '{"numa.nodeAffinity":"0"}'
866 numa_properties["vmware:latency_sensitivity_level"] = "high"
867 for numa in numas:
868 #overwrite ram and vcpus
869 #check if key 'memory' is present in numa else use ram value at flavor
870 if 'memory' in numa:
871 ram = numa['memory']*1024
872 #See for reference: https://specs.openstack.org/openstack/nova-specs/specs/mitaka/implemented/virt-driver-cpu-thread-pinning.html
873 if 'paired-threads' in numa:
874 vcpus = numa['paired-threads']*2
875 #cpu_thread_policy "require" implies that the compute node must have an STM architecture
876 numa_properties["hw:cpu_thread_policy"] = "require"
877 numa_properties["hw:cpu_policy"] = "dedicated"
878 elif 'cores' in numa:
879 vcpus = numa['cores']
880 # cpu_thread_policy "prefer" implies that the host must not have an SMT architecture, or a non-SMT architecture will be emulated
881 numa_properties["hw:cpu_thread_policy"] = "isolate"
882 numa_properties["hw:cpu_policy"] = "dedicated"
883 elif 'threads' in numa:
884 vcpus = numa['threads']
885 # cpu_thread_policy "prefer" implies that the host may or may not have an SMT architecture
886 numa_properties["hw:cpu_thread_policy"] = "prefer"
887 numa_properties["hw:cpu_policy"] = "dedicated"
888 # for interface in numa.get("interfaces",() ):
889 # if interface["dedicated"]=="yes":
890 # raise vimconn.vimconnException("Passthrough interfaces are not supported for the openstack connector", http_code=vimconn.HTTP_Service_Unavailable)
891 # #TODO, add the key 'pci_passthrough:alias"="<label at config>:<number ifaces>"' when a way to connect it is available
892
893 #create flavor
894 new_flavor=self.nova.flavors.create(name,
895 ram,
896 vcpus,
897 flavor_data.get('disk',0),
898 is_public=flavor_data.get('is_public', True)
899 )
900 #add metadata
901 if numa_properties:
902 new_flavor.set_keys(numa_properties)
903 return new_flavor.id
904 except nvExceptions.Conflict as e:
905 if change_name_if_used and retry < max_retries:
906 continue
907 self._format_exception(e)
908 #except nvExceptions.BadRequest as e:
909 except (ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError, KeyError) as e:
910 self._format_exception(e)
911
912 def delete_flavor(self,flavor_id):
913 '''Deletes a tenant flavor from openstack VIM. Returns the old flavor_id
914 '''
915 try:
916 self._reload_connection()
917 self.nova.flavors.delete(flavor_id)
918 return flavor_id
919 #except nvExceptions.BadRequest as e:
920 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
921 self._format_exception(e)
922
923 def new_image(self,image_dict):
924 '''
925 Adds a tenant image to VIM. imge_dict is a dictionary with:
926 name: name
927 disk_format: qcow2, vhd, vmdk, raw (by default), ...
928 location: path or URI
929 public: "yes" or "no"
930 metadata: metadata of the image
931 Returns the image_id
932 '''
933 retry=0
934 max_retries=3
935 while retry<max_retries:
936 retry+=1
937 try:
938 self._reload_connection()
939 #determine format http://docs.openstack.org/developer/glance/formats.html
940 if "disk_format" in image_dict:
941 disk_format=image_dict["disk_format"]
942 else: #autodiscover based on extension
943 if image_dict['location'].endswith(".qcow2"):
944 disk_format="qcow2"
945 elif image_dict['location'].endswith(".vhd"):
946 disk_format="vhd"
947 elif image_dict['location'].endswith(".vmdk"):
948 disk_format="vmdk"
949 elif image_dict['location'].endswith(".vdi"):
950 disk_format="vdi"
951 elif image_dict['location'].endswith(".iso"):
952 disk_format="iso"
953 elif image_dict['location'].endswith(".aki"):
954 disk_format="aki"
955 elif image_dict['location'].endswith(".ari"):
956 disk_format="ari"
957 elif image_dict['location'].endswith(".ami"):
958 disk_format="ami"
959 else:
960 disk_format="raw"
961 self.logger.debug("new_image: '%s' loading from '%s'", image_dict['name'], image_dict['location'])
962 if self.vim_type == "VIO":
963 container_format = "bare"
964 if 'container_format' in image_dict:
965 container_format = image_dict['container_format']
966 new_image = self.glance.images.create(name=image_dict['name'], container_format=container_format,
967 disk_format=disk_format)
968 else:
969 new_image = self.glance.images.create(name=image_dict['name'])
970 if image_dict['location'].startswith("http"):
971 # TODO there is not a method to direct download. It must be downloaded locally with requests
972 raise vimconn.vimconnNotImplemented("Cannot create image from URL")
973 else: #local path
974 with open(image_dict['location']) as fimage:
975 self.glance.images.upload(new_image.id, fimage)
976 #new_image = self.glancev1.images.create(name=image_dict['name'], is_public=image_dict.get('public',"yes")=="yes",
977 # container_format="bare", data=fimage, disk_format=disk_format)
978 metadata_to_load = image_dict.get('metadata')
979 # TODO location is a reserved word for current openstack versions. fixed for VIO please check for openstack
980 if self.vim_type == "VIO":
981 metadata_to_load['upload_location'] = image_dict['location']
982 else:
983 metadata_to_load['location'] = image_dict['location']
984 self.glance.images.update(new_image.id, **metadata_to_load)
985 return new_image.id
986 except (nvExceptions.Conflict, ksExceptions.ClientException, nvExceptions.ClientException) as e:
987 self._format_exception(e)
988 except (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError, ConnectionError) as e:
989 if retry==max_retries:
990 continue
991 self._format_exception(e)
992 except IOError as e: #can not open the file
993 raise vimconn.vimconnConnectionException(type(e).__name__ + ": " + str(e)+ " for " + image_dict['location'],
994 http_code=vimconn.HTTP_Bad_Request)
995
996 def delete_image(self, image_id):
997 '''Deletes a tenant image from openstack VIM. Returns the old id
998 '''
999 try:
1000 self._reload_connection()
1001 self.glance.images.delete(image_id)
1002 return image_id
1003 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, gl1Exceptions.HTTPNotFound, ConnectionError) as e: #TODO remove
1004 self._format_exception(e)
1005
1006 def get_image_id_from_path(self, path):
1007 '''Get the image id from image path in the VIM database. Returns the image_id'''
1008 try:
1009 self._reload_connection()
1010 images = self.glance.images.list()
1011 for image in images:
1012 if image.metadata.get("location")==path:
1013 return image.id
1014 raise vimconn.vimconnNotFoundException("image with location '{}' not found".format( path))
1015 except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e:
1016 self._format_exception(e)
1017
1018 def get_image_list(self, filter_dict={}):
1019 '''Obtain tenant images from VIM
1020 Filter_dict can be:
1021 id: image id
1022 name: image name
1023 checksum: image checksum
1024 Returns the image list of dictionaries:
1025 [{<the fields at Filter_dict plus some VIM specific>}, ...]
1026 List can be empty
1027 '''
1028 self.logger.debug("Getting image list from VIM filter: '%s'", str(filter_dict))
1029 try:
1030 self._reload_connection()
1031 filter_dict_os = filter_dict.copy()
1032 #First we filter by the available filter fields: name, id. The others are removed.
1033 image_list = self.glance.images.list()
1034 filtered_list = []
1035 for image in image_list:
1036 try:
1037 if filter_dict.get("name") and image["name"] != filter_dict["name"]:
1038 continue
1039 if filter_dict.get("id") and image["id"] != filter_dict["id"]:
1040 continue
1041 if filter_dict.get("checksum") and image["checksum"] != filter_dict["checksum"]:
1042 continue
1043
1044 filtered_list.append(image.copy())
1045 except gl1Exceptions.HTTPNotFound:
1046 pass
1047 return filtered_list
1048 except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e:
1049 self._format_exception(e)
1050
1051 def __wait_for_vm(self, vm_id, status):
1052 """wait until vm is in the desired status and return True.
1053 If the VM gets in ERROR status, return false.
1054 If the timeout is reached generate an exception"""
1055 elapsed_time = 0
1056 while elapsed_time < server_timeout:
1057 vm_status = self.nova.servers.get(vm_id).status
1058 if vm_status == status:
1059 return True
1060 if vm_status == 'ERROR':
1061 return False
1062 time.sleep(5)
1063 elapsed_time += 5
1064
1065 # if we exceeded the timeout rollback
1066 if elapsed_time >= server_timeout:
1067 raise vimconn.vimconnException('Timeout waiting for instance ' + vm_id + ' to get ' + status,
1068 http_code=vimconn.HTTP_Request_Timeout)
1069
1070 def _get_openstack_availablity_zones(self):
1071 """
1072 Get from openstack availability zones available
1073 :return:
1074 """
1075 try:
1076 openstack_availability_zone = self.nova.availability_zones.list()
1077 openstack_availability_zone = [str(zone.zoneName) for zone in openstack_availability_zone
1078 if zone.zoneName != 'internal']
1079 return openstack_availability_zone
1080 except Exception as e:
1081 return None
1082
1083 def _set_availablity_zones(self):
1084 """
1085 Set vim availablity zone
1086 :return:
1087 """
1088
1089 if 'availability_zone' in self.config:
1090 vim_availability_zones = self.config.get('availability_zone')
1091 if isinstance(vim_availability_zones, str):
1092 self.availability_zone = [vim_availability_zones]
1093 elif isinstance(vim_availability_zones, list):
1094 self.availability_zone = vim_availability_zones
1095 else:
1096 self.availability_zone = self._get_openstack_availablity_zones()
1097
1098 def _get_vm_availability_zone(self, availability_zone_index, availability_zone_list):
1099 """
1100 Return thge availability zone to be used by the created VM.
1101 :return: The VIM availability zone to be used or None
1102 """
1103 if availability_zone_index is None:
1104 if not self.config.get('availability_zone'):
1105 return None
1106 elif isinstance(self.config.get('availability_zone'), str):
1107 return self.config['availability_zone']
1108 else:
1109 # TODO consider using a different parameter at config for default AV and AV list match
1110 return self.config['availability_zone'][0]
1111
1112 vim_availability_zones = self.availability_zone
1113 # check if VIM offer enough availability zones describe in the VNFD
1114 if vim_availability_zones and len(availability_zone_list) <= len(vim_availability_zones):
1115 # check if all the names of NFV AV match VIM AV names
1116 match_by_index = False
1117 for av in availability_zone_list:
1118 if av not in vim_availability_zones:
1119 match_by_index = True
1120 break
1121 if match_by_index:
1122 return vim_availability_zones[availability_zone_index]
1123 else:
1124 return availability_zone_list[availability_zone_index]
1125 else:
1126 raise vimconn.vimconnConflictException("No enough availability zones at VIM for this deployment")
1127
1128 def new_vminstance(self, name, description, start, image_id, flavor_id, net_list, cloud_config=None, disk_list=None,
1129 availability_zone_index=None, availability_zone_list=None):
1130 """Adds a VM instance to VIM
1131 Params:
1132 start: indicates if VM must start or boot in pause mode. Ignored
1133 image_id,flavor_id: iamge and flavor uuid
1134 net_list: list of interfaces, each one is a dictionary with:
1135 name:
1136 net_id: network uuid to connect
1137 vpci: virtual vcpi to assign, ignored because openstack lack #TODO
1138 model: interface model, ignored #TODO
1139 mac_address: used for SR-IOV ifaces #TODO for other types
1140 use: 'data', 'bridge', 'mgmt'
1141 type: 'virtual', 'PCI-PASSTHROUGH'('PF'), 'SR-IOV'('VF'), 'VFnotShared'
1142 vim_id: filled/added by this function
1143 floating_ip: True/False (or it can be None)
1144 'cloud_config': (optional) dictionary with:
1145 'key-pairs': (optional) list of strings with the public key to be inserted to the default user
1146 'users': (optional) list of users to be inserted, each item is a dict with:
1147 'name': (mandatory) user name,
1148 'key-pairs': (optional) list of strings with the public key to be inserted to the user
1149 'user-data': (optional) string is a text script to be passed directly to cloud-init
1150 'config-files': (optional). List of files to be transferred. Each item is a dict with:
1151 'dest': (mandatory) string with the destination absolute path
1152 'encoding': (optional, by default text). Can be one of:
1153 'b64', 'base64', 'gz', 'gz+b64', 'gz+base64', 'gzip+b64', 'gzip+base64'
1154 'content' (mandatory): string with the content of the file
1155 'permissions': (optional) string with file permissions, typically octal notation '0644'
1156 'owner': (optional) file owner, string with the format 'owner:group'
1157 'boot-data-drive': boolean to indicate if user-data must be passed using a boot drive (hard disk)
1158 'disk_list': (optional) list with additional disks to the VM. Each item is a dict with:
1159 'image_id': (optional). VIM id of an existing image. If not provided an empty disk must be mounted
1160 'size': (mandatory) string with the size of the disk in GB
1161 'vim_id' (optional) should use this existing volume id
1162 availability_zone_index: Index of availability_zone_list to use for this this VM. None if not AV required
1163 availability_zone_list: list of availability zones given by user in the VNFD descriptor. Ignore if
1164 availability_zone_index is None
1165 #TODO ip, security groups
1166 Returns a tuple with the instance identifier and created_items or raises an exception on error
1167 created_items can be None or a dictionary where this method can include key-values that will be passed to
1168 the method delete_vminstance and action_vminstance. Can be used to store created ports, volumes, etc.
1169 Format is vimconnector dependent, but do not use nested dictionaries and a value of None should be the same
1170 as not present.
1171 """
1172 self.logger.debug("new_vminstance input: image='%s' flavor='%s' nics='%s'",image_id, flavor_id,str(net_list))
1173 try:
1174 server = None
1175 created_items = {}
1176 # metadata = {}
1177 net_list_vim = []
1178 external_network = [] # list of external networks to be connected to instance, later on used to create floating_ip
1179 no_secured_ports = [] # List of port-is with port-security disabled
1180 self._reload_connection()
1181 # metadata_vpci = {} # For a specific neutron plugin
1182 block_device_mapping = None
1183
1184 for net in net_list:
1185 if not net.get("net_id"): # skip non connected iface
1186 continue
1187
1188 port_dict = {
1189 "network_id": net["net_id"],
1190 "name": net.get("name"),
1191 "admin_state_up": True
1192 }
1193 if self.config.get("security_groups") and net.get("port_security") is not False and \
1194 not self.config.get("no_port_security_extension"):
1195 if not self.security_groups_id:
1196 self._get_ids_from_name()
1197 port_dict["security_groups"] = self.security_groups_id
1198
1199 if net["type"]=="virtual":
1200 pass
1201 # if "vpci" in net:
1202 # metadata_vpci[ net["net_id"] ] = [[ net["vpci"], "" ]]
1203 elif net["type"] == "VF" or net["type"] == "SR-IOV": # for VF
1204 # if "vpci" in net:
1205 # if "VF" not in metadata_vpci:
1206 # metadata_vpci["VF"]=[]
1207 # metadata_vpci["VF"].append([ net["vpci"], "" ])
1208 port_dict["binding:vnic_type"]="direct"
1209 # VIO specific Changes
1210 if self.vim_type == "VIO":
1211 # Need to create port with port_security_enabled = False and no-security-groups
1212 port_dict["port_security_enabled"]=False
1213 port_dict["provider_security_groups"]=[]
1214 port_dict["security_groups"]=[]
1215 else: # For PT PCI-PASSTHROUGH
1216 # VIO specific Changes
1217 # Current VIO release does not support port with type 'direct-physical'
1218 # So no need to create virtual port in case of PCI-device.
1219 # Will update port_dict code when support gets added in next VIO release
1220 if self.vim_type == "VIO":
1221 raise vimconn.vimconnNotSupportedException(
1222 "Current VIO release does not support full passthrough (PT)")
1223 # if "vpci" in net:
1224 # if "PF" not in metadata_vpci:
1225 # metadata_vpci["PF"]=[]
1226 # metadata_vpci["PF"].append([ net["vpci"], "" ])
1227 port_dict["binding:vnic_type"]="direct-physical"
1228 if not port_dict["name"]:
1229 port_dict["name"]=name
1230 if net.get("mac_address"):
1231 port_dict["mac_address"]=net["mac_address"]
1232 if net.get("ip_address"):
1233 port_dict["fixed_ips"] = [{'ip_address': net["ip_address"]}]
1234 # TODO add 'subnet_id': <subnet_id>
1235 new_port = self.neutron.create_port({"port": port_dict })
1236 created_items["port:" + str(new_port["port"]["id"])] = True
1237 net["mac_adress"] = new_port["port"]["mac_address"]
1238 net["vim_id"] = new_port["port"]["id"]
1239 # if try to use a network without subnetwork, it will return a emtpy list
1240 fixed_ips = new_port["port"].get("fixed_ips")
1241 if fixed_ips:
1242 net["ip"] = fixed_ips[0].get("ip_address")
1243 else:
1244 net["ip"] = None
1245
1246 port = {"port-id": new_port["port"]["id"]}
1247 if float(self.nova.api_version.get_string()) >= 2.32:
1248 port["tag"] = new_port["port"]["name"]
1249 net_list_vim.append(port)
1250
1251 if net.get('floating_ip', False):
1252 net['exit_on_floating_ip_error'] = True
1253 external_network.append(net)
1254 elif net['use'] == 'mgmt' and self.config.get('use_floating_ip'):
1255 net['exit_on_floating_ip_error'] = False
1256 external_network.append(net)
1257 net['floating_ip'] = self.config.get('use_floating_ip')
1258
1259 # If port security is disabled when the port has not yet been attached to the VM, then all vm traffic is dropped.
1260 # As a workaround we wait until the VM is active and then disable the port-security
1261 if net.get("port_security") == False and not self.config.get("no_port_security_extension"):
1262 no_secured_ports.append(new_port["port"]["id"])
1263
1264 # if metadata_vpci:
1265 # metadata = {"pci_assignement": json.dumps(metadata_vpci)}
1266 # if len(metadata["pci_assignement"]) >255:
1267 # #limit the metadata size
1268 # #metadata["pci_assignement"] = metadata["pci_assignement"][0:255]
1269 # self.logger.warn("Metadata deleted since it exceeds the expected length (255) ")
1270 # metadata = {}
1271
1272 self.logger.debug("name '%s' image_id '%s'flavor_id '%s' net_list_vim '%s' description '%s'",
1273 name, image_id, flavor_id, str(net_list_vim), description)
1274
1275 # cloud config
1276 config_drive, userdata = self._create_user_data(cloud_config)
1277
1278 # Create additional volumes in case these are present in disk_list
1279 base_disk_index = ord('b')
1280 if disk_list:
1281 block_device_mapping = {}
1282 for disk in disk_list:
1283 if disk.get('vim_id'):
1284 block_device_mapping['_vd' + chr(base_disk_index)] = disk['vim_id']
1285 else:
1286 if 'image_id' in disk:
1287 volume = self.cinder.volumes.create(size=disk['size'], name=name + '_vd' +
1288 chr(base_disk_index), imageRef=disk['image_id'])
1289 else:
1290 volume = self.cinder.volumes.create(size=disk['size'], name=name + '_vd' +
1291 chr(base_disk_index))
1292 created_items["volume:" + str(volume.id)] = True
1293 block_device_mapping['_vd' + chr(base_disk_index)] = volume.id
1294 base_disk_index += 1
1295
1296 # Wait until created volumes are with status available
1297 elapsed_time = 0
1298 while elapsed_time < volume_timeout:
1299 for created_item in created_items:
1300 v, _, volume_id = created_item.partition(":")
1301 if v == 'volume':
1302 if self.cinder.volumes.get(volume_id).status != 'available':
1303 break
1304 else: # all ready: break from while
1305 break
1306 time.sleep(5)
1307 elapsed_time += 5
1308 # If we exceeded the timeout rollback
1309 if elapsed_time >= volume_timeout:
1310 raise vimconn.vimconnException('Timeout creating volumes for instance ' + name,
1311 http_code=vimconn.HTTP_Request_Timeout)
1312 # get availability Zone
1313 vm_av_zone = self._get_vm_availability_zone(availability_zone_index, availability_zone_list)
1314
1315 self.logger.debug("nova.servers.create({}, {}, {}, nics={}, security_groups={}, "
1316 "availability_zone={}, key_name={}, userdata={}, config_drive={}, "
1317 "block_device_mapping={})".format(name, image_id, flavor_id, net_list_vim,
1318 self.config.get("security_groups"), vm_av_zone,
1319 self.config.get('keypair'), userdata, config_drive,
1320 block_device_mapping))
1321 server = self.nova.servers.create(name, image_id, flavor_id, nics=net_list_vim,
1322 security_groups=self.config.get("security_groups"),
1323 # TODO remove security_groups in future versions. Already at neutron port
1324 availability_zone=vm_av_zone,
1325 key_name=self.config.get('keypair'),
1326 userdata=userdata,
1327 config_drive=config_drive,
1328 block_device_mapping=block_device_mapping
1329 ) # , description=description)
1330
1331 vm_start_time = time.time()
1332 # Previously mentioned workaround to wait until the VM is active and then disable the port-security
1333 if no_secured_ports:
1334 self.__wait_for_vm(server.id, 'ACTIVE')
1335
1336 for port_id in no_secured_ports:
1337 try:
1338 self.neutron.update_port(port_id,
1339 {"port": {"port_security_enabled": False, "security_groups": None}})
1340 except Exception as e:
1341 raise vimconn.vimconnException("It was not possible to disable port security for port {}".format(
1342 port_id))
1343 # print "DONE :-)", server
1344
1345 # pool_id = None
1346 if external_network:
1347 floating_ips = self.neutron.list_floatingips().get("floatingips", ())
1348 for floating_network in external_network:
1349 try:
1350 assigned = False
1351 while not assigned:
1352 if floating_ips:
1353 ip = floating_ips.pop(0)
1354 if ip.get("port_id", False) or ip.get('tenant_id') != server.tenant_id:
1355 continue
1356 if isinstance(floating_network['floating_ip'], str):
1357 if ip.get("floating_network_id") != floating_network['floating_ip']:
1358 continue
1359 free_floating_ip = ip.get("floating_ip_address")
1360 else:
1361 if isinstance(floating_network['floating_ip'], str) and \
1362 floating_network['floating_ip'].lower() != "true":
1363 pool_id = floating_network['floating_ip']
1364 else:
1365 # Find the external network
1366 external_nets = list()
1367 for net in self.neutron.list_networks()['networks']:
1368 if net['router:external']:
1369 external_nets.append(net)
1370
1371 if len(external_nets) == 0:
1372 raise vimconn.vimconnException("Cannot create floating_ip automatically since no external "
1373 "network is present",
1374 http_code=vimconn.HTTP_Conflict)
1375 if len(external_nets) > 1:
1376 raise vimconn.vimconnException("Cannot create floating_ip automatically since multiple "
1377 "external networks are present",
1378 http_code=vimconn.HTTP_Conflict)
1379
1380 pool_id = external_nets[0].get('id')
1381 param = {'floatingip': {'floating_network_id': pool_id, 'tenant_id': server.tenant_id}}
1382 try:
1383 # self.logger.debug("Creating floating IP")
1384 new_floating_ip = self.neutron.create_floatingip(param)
1385 free_floating_ip = new_floating_ip['floatingip']['floating_ip_address']
1386 except Exception as e:
1387 raise vimconn.vimconnException(type(e).__name__ + ": Cannot create new floating_ip " +
1388 str(e), http_code=vimconn.HTTP_Conflict)
1389
1390 fix_ip = floating_network.get('ip')
1391 while not assigned:
1392 try:
1393 server.add_floating_ip(free_floating_ip, fix_ip)
1394 assigned = True
1395 except Exception as e:
1396 # openstack need some time after VM creation to asign an IP. So retry if fails
1397 vm_status = self.nova.servers.get(server.id).status
1398 if vm_status != 'ACTIVE' and vm_status != 'ERROR':
1399 if time.time() - vm_start_time < server_timeout:
1400 time.sleep(5)
1401 continue
1402 raise vimconn.vimconnException(
1403 "Cannot create floating_ip: {} {}".format(type(e).__name__, e),
1404 http_code=vimconn.HTTP_Conflict)
1405
1406 except Exception as e:
1407 if not floating_network['exit_on_floating_ip_error']:
1408 self.logger.warn("Cannot create floating_ip. %s", str(e))
1409 continue
1410 raise
1411
1412 return server.id, created_items
1413 # except nvExceptions.NotFound as e:
1414 # error_value=-vimconn.HTTP_Not_Found
1415 # error_text= "vm instance %s not found" % vm_id
1416 # except TypeError as e:
1417 # raise vimconn.vimconnException(type(e).__name__ + ": "+ str(e), http_code=vimconn.HTTP_Bad_Request)
1418
1419 except Exception as e:
1420 server_id = None
1421 if server:
1422 server_id = server.id
1423 try:
1424 self.delete_vminstance(server_id, created_items)
1425 except Exception as e2:
1426 self.logger.error("new_vminstance rollback fail {}".format(e2))
1427
1428 self._format_exception(e)
1429
1430 def get_vminstance(self,vm_id):
1431 '''Returns the VM instance information from VIM'''
1432 #self.logger.debug("Getting VM from VIM")
1433 try:
1434 self._reload_connection()
1435 server = self.nova.servers.find(id=vm_id)
1436 #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
1437 return server.to_dict()
1438 except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound, ConnectionError) as e:
1439 self._format_exception(e)
1440
1441 def get_vminstance_console(self,vm_id, console_type="vnc"):
1442 '''
1443 Get a console for the virtual machine
1444 Params:
1445 vm_id: uuid of the VM
1446 console_type, can be:
1447 "novnc" (by default), "xvpvnc" for VNC types,
1448 "rdp-html5" for RDP types, "spice-html5" for SPICE types
1449 Returns dict with the console parameters:
1450 protocol: ssh, ftp, http, https, ...
1451 server: usually ip address
1452 port: the http, ssh, ... port
1453 suffix: extra text, e.g. the http path and query string
1454 '''
1455 self.logger.debug("Getting VM CONSOLE from VIM")
1456 try:
1457 self._reload_connection()
1458 server = self.nova.servers.find(id=vm_id)
1459 if console_type == None or console_type == "novnc":
1460 console_dict = server.get_vnc_console("novnc")
1461 elif console_type == "xvpvnc":
1462 console_dict = server.get_vnc_console(console_type)
1463 elif console_type == "rdp-html5":
1464 console_dict = server.get_rdp_console(console_type)
1465 elif console_type == "spice-html5":
1466 console_dict = server.get_spice_console(console_type)
1467 else:
1468 raise vimconn.vimconnException("console type '{}' not allowed".format(console_type), http_code=vimconn.HTTP_Bad_Request)
1469
1470 console_dict1 = console_dict.get("console")
1471 if console_dict1:
1472 console_url = console_dict1.get("url")
1473 if console_url:
1474 #parse console_url
1475 protocol_index = console_url.find("//")
1476 suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2
1477 port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2
1478 if protocol_index < 0 or port_index<0 or suffix_index<0:
1479 return -vimconn.HTTP_Internal_Server_Error, "Unexpected response from VIM"
1480 console_dict={"protocol": console_url[0:protocol_index],
1481 "server": console_url[protocol_index+2:port_index],
1482 "port": console_url[port_index:suffix_index],
1483 "suffix": console_url[suffix_index+1:]
1484 }
1485 protocol_index += 2
1486 return console_dict
1487 raise vimconn.vimconnUnexpectedResponse("Unexpected response from VIM")
1488
1489 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.BadRequest, ConnectionError) as e:
1490 self._format_exception(e)
1491
1492 def delete_vminstance(self, vm_id, created_items=None):
1493 '''Removes a VM instance from VIM. Returns the old identifier
1494 '''
1495 #print "osconnector: Getting VM from VIM"
1496 if created_items == None:
1497 created_items = {}
1498 try:
1499 self._reload_connection()
1500 # delete VM ports attached to this networks before the virtual machine
1501 for k, v in created_items.items():
1502 if not v: # skip already deleted
1503 continue
1504 try:
1505 k_item, _, k_id = k.partition(":")
1506 if k_item == "port":
1507 self.neutron.delete_port(k_id)
1508 except Exception as e:
1509 self.logger.error("Error deleting port: {}: {}".format(type(e).__name__, e))
1510
1511 # #commented because detaching the volumes makes the servers.delete not work properly ?!?
1512 # #dettach volumes attached
1513 # server = self.nova.servers.get(vm_id)
1514 # volumes_attached_dict = server._info['os-extended-volumes:volumes_attached'] #volume['id']
1515 # #for volume in volumes_attached_dict:
1516 # # self.cinder.volumes.detach(volume['id'])
1517
1518 if vm_id:
1519 self.nova.servers.delete(vm_id)
1520
1521 # delete volumes. Although having detached, they should have in active status before deleting
1522 # we ensure in this loop
1523 keep_waiting = True
1524 elapsed_time = 0
1525 while keep_waiting and elapsed_time < volume_timeout:
1526 keep_waiting = False
1527 for k, v in created_items.items():
1528 if not v: # skip already deleted
1529 continue
1530 try:
1531 k_item, _, k_id = k.partition(":")
1532 if k_item == "volume":
1533 if self.cinder.volumes.get(k_id).status != 'available':
1534 keep_waiting = True
1535 else:
1536 self.cinder.volumes.delete(k_id)
1537 except Exception as e:
1538 self.logger.error("Error deleting volume: {}: {}".format(type(e).__name__, e))
1539 if keep_waiting:
1540 time.sleep(1)
1541 elapsed_time += 1
1542 return None
1543 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
1544 self._format_exception(e)
1545
1546 def refresh_vms_status(self, vm_list):
1547 '''Get the status of the virtual machines and their interfaces/ports
1548 Params: the list of VM identifiers
1549 Returns a dictionary with:
1550 vm_id: #VIM id of this Virtual Machine
1551 status: #Mandatory. Text with one of:
1552 # DELETED (not found at vim)
1553 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
1554 # OTHER (Vim reported other status not understood)
1555 # ERROR (VIM indicates an ERROR status)
1556 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
1557 # CREATING (on building process), ERROR
1558 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
1559 #
1560 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
1561 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1562 interfaces:
1563 - vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1564 mac_address: #Text format XX:XX:XX:XX:XX:XX
1565 vim_net_id: #network id where this interface is connected
1566 vim_interface_id: #interface/port VIM id
1567 ip_address: #null, or text with IPv4, IPv6 address
1568 compute_node: #identification of compute node where PF,VF interface is allocated
1569 pci: #PCI address of the NIC that hosts the PF,VF
1570 vlan: #physical VLAN used for VF
1571 '''
1572 vm_dict={}
1573 self.logger.debug("refresh_vms status: Getting tenant VM instance information from VIM")
1574 for vm_id in vm_list:
1575 vm={}
1576 try:
1577 vm_vim = self.get_vminstance(vm_id)
1578 if vm_vim['status'] in vmStatus2manoFormat:
1579 vm['status'] = vmStatus2manoFormat[ vm_vim['status'] ]
1580 else:
1581 vm['status'] = "OTHER"
1582 vm['error_msg'] = "VIM status reported " + vm_vim['status']
1583
1584 vm['vim_info'] = self.serialize(vm_vim)
1585
1586 vm["interfaces"] = []
1587 if vm_vim.get('fault'):
1588 vm['error_msg'] = str(vm_vim['fault'])
1589 #get interfaces
1590 try:
1591 self._reload_connection()
1592 port_dict = self.neutron.list_ports(device_id=vm_id)
1593 for port in port_dict["ports"]:
1594 interface={}
1595 interface['vim_info'] = self.serialize(port)
1596 interface["mac_address"] = port.get("mac_address")
1597 interface["vim_net_id"] = port["network_id"]
1598 interface["vim_interface_id"] = port["id"]
1599 # check if OS-EXT-SRV-ATTR:host is there,
1600 # in case of non-admin credentials, it will be missing
1601 if vm_vim.get('OS-EXT-SRV-ATTR:host'):
1602 interface["compute_node"] = vm_vim['OS-EXT-SRV-ATTR:host']
1603 interface["pci"] = None
1604
1605 # check if binding:profile is there,
1606 # in case of non-admin credentials, it will be missing
1607 if port.get('binding:profile'):
1608 if port['binding:profile'].get('pci_slot'):
1609 # TODO: At the moment sr-iov pci addresses are converted to PF pci addresses by setting the slot to 0x00
1610 # TODO: This is just a workaround valid for niantinc. Find a better way to do so
1611 # CHANGE DDDD:BB:SS.F to DDDD:BB:00.(F%2) assuming there are 2 ports per nic
1612 pci = port['binding:profile']['pci_slot']
1613 # interface["pci"] = pci[:-4] + "00." + str(int(pci[-1]) % 2)
1614 interface["pci"] = pci
1615 interface["vlan"] = None
1616 #if network is of type vlan and port is of type direct (sr-iov) then set vlan id
1617 network = self.neutron.show_network(port["network_id"])
1618 if network['network'].get('provider:network_type') == 'vlan' and \
1619 port.get("binding:vnic_type") == "direct":
1620 interface["vlan"] = network['network'].get('provider:segmentation_id')
1621 ips=[]
1622 #look for floating ip address
1623 try:
1624 floating_ip_dict = self.neutron.list_floatingips(port_id=port["id"])
1625 if floating_ip_dict.get("floatingips"):
1626 ips.append(floating_ip_dict["floatingips"][0].get("floating_ip_address") )
1627 except Exception:
1628 pass
1629
1630 for subnet in port["fixed_ips"]:
1631 ips.append(subnet["ip_address"])
1632 interface["ip_address"] = ";".join(ips)
1633 vm["interfaces"].append(interface)
1634 except Exception as e:
1635 self.logger.error("Error getting vm interface information {}: {}".format(type(e).__name__, e),
1636 exc_info=True)
1637 except vimconn.vimconnNotFoundException as e:
1638 self.logger.error("Exception getting vm status: %s", str(e))
1639 vm['status'] = "DELETED"
1640 vm['error_msg'] = str(e)
1641 except vimconn.vimconnException as e:
1642 self.logger.error("Exception getting vm status: %s", str(e))
1643 vm['status'] = "VIM_ERROR"
1644 vm['error_msg'] = str(e)
1645 vm_dict[vm_id] = vm
1646 return vm_dict
1647
1648 def action_vminstance(self, vm_id, action_dict, created_items={}):
1649 '''Send and action over a VM instance from VIM
1650 Returns None or the console dict if the action was successfully sent to the VIM'''
1651 self.logger.debug("Action over VM '%s': %s", vm_id, str(action_dict))
1652 try:
1653 self._reload_connection()
1654 server = self.nova.servers.find(id=vm_id)
1655 if "start" in action_dict:
1656 if action_dict["start"]=="rebuild":
1657 server.rebuild()
1658 else:
1659 if server.status=="PAUSED":
1660 server.unpause()
1661 elif server.status=="SUSPENDED":
1662 server.resume()
1663 elif server.status=="SHUTOFF":
1664 server.start()
1665 elif "pause" in action_dict:
1666 server.pause()
1667 elif "resume" in action_dict:
1668 server.resume()
1669 elif "shutoff" in action_dict or "shutdown" in action_dict:
1670 server.stop()
1671 elif "forceOff" in action_dict:
1672 server.stop() #TODO
1673 elif "terminate" in action_dict:
1674 server.delete()
1675 elif "createImage" in action_dict:
1676 server.create_image()
1677 #"path":path_schema,
1678 #"description":description_schema,
1679 #"name":name_schema,
1680 #"metadata":metadata_schema,
1681 #"imageRef": id_schema,
1682 #"disk": {"oneOf":[{"type": "null"}, {"type":"string"}] },
1683 elif "rebuild" in action_dict:
1684 server.rebuild(server.image['id'])
1685 elif "reboot" in action_dict:
1686 server.reboot() #reboot_type='SOFT'
1687 elif "console" in action_dict:
1688 console_type = action_dict["console"]
1689 if console_type == None or console_type == "novnc":
1690 console_dict = server.get_vnc_console("novnc")
1691 elif console_type == "xvpvnc":
1692 console_dict = server.get_vnc_console(console_type)
1693 elif console_type == "rdp-html5":
1694 console_dict = server.get_rdp_console(console_type)
1695 elif console_type == "spice-html5":
1696 console_dict = server.get_spice_console(console_type)
1697 else:
1698 raise vimconn.vimconnException("console type '{}' not allowed".format(console_type),
1699 http_code=vimconn.HTTP_Bad_Request)
1700 try:
1701 console_url = console_dict["console"]["url"]
1702 #parse console_url
1703 protocol_index = console_url.find("//")
1704 suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2
1705 port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2
1706 if protocol_index < 0 or port_index<0 or suffix_index<0:
1707 raise vimconn.vimconnException("Unexpected response from VIM " + str(console_dict))
1708 console_dict2={"protocol": console_url[0:protocol_index],
1709 "server": console_url[protocol_index+2 : port_index],
1710 "port": int(console_url[port_index+1 : suffix_index]),
1711 "suffix": console_url[suffix_index+1:]
1712 }
1713 return console_dict2
1714 except Exception as e:
1715 raise vimconn.vimconnException("Unexpected response from VIM " + str(console_dict))
1716
1717 return None
1718 except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound, ConnectionError) as e:
1719 self._format_exception(e)
1720 #TODO insert exception vimconn.HTTP_Unauthorized
1721
1722 ####### VIO Specific Changes #########
1723 def _generate_vlanID(self):
1724 """
1725 Method to get unused vlanID
1726 Args:
1727 None
1728 Returns:
1729 vlanID
1730 """
1731 #Get used VLAN IDs
1732 usedVlanIDs = []
1733 networks = self.get_network_list()
1734 for net in networks:
1735 if net.get('provider:segmentation_id'):
1736 usedVlanIDs.append(net.get('provider:segmentation_id'))
1737 used_vlanIDs = set(usedVlanIDs)
1738
1739 #find unused VLAN ID
1740 for vlanID_range in self.config.get('dataplane_net_vlan_range'):
1741 try:
1742 start_vlanid , end_vlanid = map(int, vlanID_range.replace(" ", "").split("-"))
1743 for vlanID in xrange(start_vlanid, end_vlanid + 1):
1744 if vlanID not in used_vlanIDs:
1745 return vlanID
1746 except Exception as exp:
1747 raise vimconn.vimconnException("Exception {} occurred while generating VLAN ID.".format(exp))
1748 else:
1749 raise vimconn.vimconnConflictException("Unable to create the SRIOV VLAN network."\
1750 " All given Vlan IDs {} are in use.".format(self.config.get('dataplane_net_vlan_range')))
1751
1752
1753 def _generate_multisegment_vlanID(self):
1754 """
1755 Method to get unused vlanID
1756 Args:
1757 None
1758 Returns:
1759 vlanID
1760 """
1761 #Get used VLAN IDs
1762 usedVlanIDs = []
1763 networks = self.get_network_list()
1764 for net in networks:
1765 if net.get('provider:network_type') == "vlan" and net.get('provider:segmentation_id'):
1766 usedVlanIDs.append(net.get('provider:segmentation_id'))
1767 elif net.get('segments'):
1768 for segment in net.get('segments'):
1769 if segment.get('provider:network_type') == "vlan" and segment.get('provider:segmentation_id'):
1770 usedVlanIDs.append(segment.get('provider:segmentation_id'))
1771 used_vlanIDs = set(usedVlanIDs)
1772
1773 #find unused VLAN ID
1774 for vlanID_range in self.config.get('multisegment_vlan_range'):
1775 try:
1776 start_vlanid , end_vlanid = map(int, vlanID_range.replace(" ", "").split("-"))
1777 for vlanID in xrange(start_vlanid, end_vlanid + 1):
1778 if vlanID not in used_vlanIDs:
1779 return vlanID
1780 except Exception as exp:
1781 raise vimconn.vimconnException("Exception {} occurred while generating VLAN ID.".format(exp))
1782 else:
1783 raise vimconn.vimconnConflictException("Unable to create the VLAN segment."\
1784 " All VLAN IDs {} are in use.".format(self.config.get('multisegment_vlan_range')))
1785
1786
1787 def _validate_vlan_ranges(self, input_vlan_range, text_vlan_range):
1788 """
1789 Method to validate user given vlanID ranges
1790 Args: None
1791 Returns: None
1792 """
1793 for vlanID_range in input_vlan_range:
1794 vlan_range = vlanID_range.replace(" ", "")
1795 #validate format
1796 vlanID_pattern = r'(\d)*-(\d)*$'
1797 match_obj = re.match(vlanID_pattern, vlan_range)
1798 if not match_obj:
1799 raise vimconn.vimconnConflictException("Invalid VLAN range for {}: {}.You must provide "\
1800 "'{}' in format [start_ID - end_ID].".format(text_vlan_range, vlanID_range, text_vlan_range))
1801
1802 start_vlanid , end_vlanid = map(int,vlan_range.split("-"))
1803 if start_vlanid <= 0 :
1804 raise vimconn.vimconnConflictException("Invalid VLAN range for {}: {}."\
1805 "Start ID can not be zero. For VLAN "\
1806 "networks valid IDs are 1 to 4094 ".format(text_vlan_range, vlanID_range))
1807 if end_vlanid > 4094 :
1808 raise vimconn.vimconnConflictException("Invalid VLAN range for {}: {}."\
1809 "End VLAN ID can not be greater than 4094. For VLAN "\
1810 "networks valid IDs are 1 to 4094 ".format(text_vlan_range, vlanID_range))
1811
1812 if start_vlanid > end_vlanid:
1813 raise vimconn.vimconnConflictException("Invalid VLAN range for {}: {}."\
1814 "You must provide '{}' in format start_ID - end_ID and "\
1815 "start_ID < end_ID ".format(text_vlan_range, vlanID_range, text_vlan_range))
1816
1817 #NOT USED FUNCTIONS
1818
1819 def new_external_port(self, port_data):
1820 #TODO openstack if needed
1821 '''Adds a external port to VIM'''
1822 '''Returns the port identifier'''
1823 return -vimconn.HTTP_Internal_Server_Error, "osconnector.new_external_port() not implemented"
1824
1825 def connect_port_network(self, port_id, network_id, admin=False):
1826 #TODO openstack if needed
1827 '''Connects a external port to a network'''
1828 '''Returns status code of the VIM response'''
1829 return -vimconn.HTTP_Internal_Server_Error, "osconnector.connect_port_network() not implemented"
1830
1831 def new_user(self, user_name, user_passwd, tenant_id=None):
1832 '''Adds a new user to openstack VIM'''
1833 '''Returns the user identifier'''
1834 self.logger.debug("osconnector: Adding a new user to VIM")
1835 try:
1836 self._reload_connection()
1837 user=self.keystone.users.create(user_name, password=user_passwd, default_project=tenant_id)
1838 #self.keystone.tenants.add_user(self.k_creds["username"], #role)
1839 return user.id
1840 except ksExceptions.ConnectionError as e:
1841 error_value=-vimconn.HTTP_Bad_Request
1842 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1843 except ksExceptions.ClientException as e: #TODO remove
1844 error_value=-vimconn.HTTP_Bad_Request
1845 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1846 #TODO insert exception vimconn.HTTP_Unauthorized
1847 #if reaching here is because an exception
1848 self.logger.debug("new_user " + error_text)
1849 return error_value, error_text
1850
1851 def delete_user(self, user_id):
1852 '''Delete a user from openstack VIM'''
1853 '''Returns the user identifier'''
1854 if self.debug:
1855 print("osconnector: Deleting a user from VIM")
1856 try:
1857 self._reload_connection()
1858 self.keystone.users.delete(user_id)
1859 return 1, user_id
1860 except ksExceptions.ConnectionError as e:
1861 error_value=-vimconn.HTTP_Bad_Request
1862 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1863 except ksExceptions.NotFound as e:
1864 error_value=-vimconn.HTTP_Not_Found
1865 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1866 except ksExceptions.ClientException as e: #TODO remove
1867 error_value=-vimconn.HTTP_Bad_Request
1868 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1869 #TODO insert exception vimconn.HTTP_Unauthorized
1870 #if reaching here is because an exception
1871 self.logger.debug("delete_tenant " + error_text)
1872 return error_value, error_text
1873
1874 def get_hosts_info(self):
1875 '''Get the information of deployed hosts
1876 Returns the hosts content'''
1877 if self.debug:
1878 print("osconnector: Getting Host info from VIM")
1879 try:
1880 h_list=[]
1881 self._reload_connection()
1882 hypervisors = self.nova.hypervisors.list()
1883 for hype in hypervisors:
1884 h_list.append( hype.to_dict() )
1885 return 1, {"hosts":h_list}
1886 except nvExceptions.NotFound as e:
1887 error_value=-vimconn.HTTP_Not_Found
1888 error_text= (str(e) if len(e.args)==0 else str(e.args[0]))
1889 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
1890 error_value=-vimconn.HTTP_Bad_Request
1891 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1892 #TODO insert exception vimconn.HTTP_Unauthorized
1893 #if reaching here is because an exception
1894 self.logger.debug("get_hosts_info " + error_text)
1895 return error_value, error_text
1896
1897 def get_hosts(self, vim_tenant):
1898 '''Get the hosts and deployed instances
1899 Returns the hosts content'''
1900 r, hype_dict = self.get_hosts_info()
1901 if r<0:
1902 return r, hype_dict
1903 hypervisors = hype_dict["hosts"]
1904 try:
1905 servers = self.nova.servers.list()
1906 for hype in hypervisors:
1907 for server in servers:
1908 if server.to_dict()['OS-EXT-SRV-ATTR:hypervisor_hostname']==hype['hypervisor_hostname']:
1909 if 'vm' in hype:
1910 hype['vm'].append(server.id)
1911 else:
1912 hype['vm'] = [server.id]
1913 return 1, hype_dict
1914 except nvExceptions.NotFound as e:
1915 error_value=-vimconn.HTTP_Not_Found
1916 error_text= (str(e) if len(e.args)==0 else str(e.args[0]))
1917 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
1918 error_value=-vimconn.HTTP_Bad_Request
1919 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1920 #TODO insert exception vimconn.HTTP_Unauthorized
1921 #if reaching here is because an exception
1922 self.logger.debug("get_hosts " + error_text)
1923 return error_value, error_text
1924
1925 def new_classification(self, name, ctype, definition):
1926 self.logger.debug(
1927 'Adding a new (Traffic) Classification to VIM, named %s', name)
1928 try:
1929 new_class = None
1930 self._reload_connection()
1931 if ctype not in supportedClassificationTypes:
1932 raise vimconn.vimconnNotSupportedException(
1933 'OpenStack VIM connector doesn\'t support provided '
1934 'Classification Type {}, supported ones are: '
1935 '{}'.format(ctype, supportedClassificationTypes))
1936 if not self._validate_classification(ctype, definition):
1937 raise vimconn.vimconnException(
1938 'Incorrect Classification definition '
1939 'for the type specified.')
1940 classification_dict = definition
1941 classification_dict['name'] = name
1942
1943 new_class = self.neutron.create_sfc_flow_classifier(
1944 {'flow_classifier': classification_dict})
1945 return new_class['flow_classifier']['id']
1946 except (neExceptions.ConnectionFailed, ksExceptions.ClientException,
1947 neExceptions.NeutronException, ConnectionError) as e:
1948 self.logger.error(
1949 'Creation of Classification failed.')
1950 self._format_exception(e)
1951
1952 def get_classification(self, class_id):
1953 self.logger.debug(" Getting Classification %s from VIM", class_id)
1954 filter_dict = {"id": class_id}
1955 class_list = self.get_classification_list(filter_dict)
1956 if len(class_list) == 0:
1957 raise vimconn.vimconnNotFoundException(
1958 "Classification '{}' not found".format(class_id))
1959 elif len(class_list) > 1:
1960 raise vimconn.vimconnConflictException(
1961 "Found more than one Classification with this criteria")
1962 classification = class_list[0]
1963 return classification
1964
1965 def get_classification_list(self, filter_dict={}):
1966 self.logger.debug("Getting Classifications from VIM filter: '%s'",
1967 str(filter_dict))
1968 try:
1969 filter_dict_os = filter_dict.copy()
1970 self._reload_connection()
1971 if self.api_version3 and "tenant_id" in filter_dict_os:
1972 filter_dict_os['project_id'] = filter_dict_os.pop('tenant_id')
1973 classification_dict = self.neutron.list_sfc_flow_classifiers(
1974 **filter_dict_os)
1975 classification_list = classification_dict["flow_classifiers"]
1976 self.__classification_os2mano(classification_list)
1977 return classification_list
1978 except (neExceptions.ConnectionFailed, ksExceptions.ClientException,
1979 neExceptions.NeutronException, ConnectionError) as e:
1980 self._format_exception(e)
1981
1982 def delete_classification(self, class_id):
1983 self.logger.debug("Deleting Classification '%s' from VIM", class_id)
1984 try:
1985 self._reload_connection()
1986 self.neutron.delete_sfc_flow_classifier(class_id)
1987 return class_id
1988 except (neExceptions.ConnectionFailed, neExceptions.NeutronException,
1989 ksExceptions.ClientException, neExceptions.NeutronException,
1990 ConnectionError) as e:
1991 self._format_exception(e)
1992
1993 def new_sfi(self, name, ingress_ports, egress_ports, sfc_encap=True):
1994 self.logger.debug(
1995 "Adding a new Service Function Instance to VIM, named '%s'", name)
1996 try:
1997 new_sfi = None
1998 self._reload_connection()
1999 correlation = None
2000 if sfc_encap:
2001 correlation = 'nsh'
2002 if len(ingress_ports) != 1:
2003 raise vimconn.vimconnNotSupportedException(
2004 "OpenStack VIM connector can only have "
2005 "1 ingress port per SFI")
2006 if len(egress_ports) != 1:
2007 raise vimconn.vimconnNotSupportedException(
2008 "OpenStack VIM connector can only have "
2009 "1 egress port per SFI")
2010 sfi_dict = {'name': name,
2011 'ingress': ingress_ports[0],
2012 'egress': egress_ports[0],
2013 'service_function_parameters': {
2014 'correlation': correlation}}
2015 new_sfi = self.neutron.create_sfc_port_pair({'port_pair': sfi_dict})
2016 return new_sfi['port_pair']['id']
2017 except (neExceptions.ConnectionFailed, ksExceptions.ClientException,
2018 neExceptions.NeutronException, ConnectionError) as e:
2019 if new_sfi:
2020 try:
2021 self.neutron.delete_sfc_port_pair(
2022 new_sfi['port_pair']['id'])
2023 except Exception:
2024 self.logger.error(
2025 'Creation of Service Function Instance failed, with '
2026 'subsequent deletion failure as well.')
2027 self._format_exception(e)
2028
2029 def get_sfi(self, sfi_id):
2030 self.logger.debug(
2031 'Getting Service Function Instance %s from VIM', sfi_id)
2032 filter_dict = {"id": sfi_id}
2033 sfi_list = self.get_sfi_list(filter_dict)
2034 if len(sfi_list) == 0:
2035 raise vimconn.vimconnNotFoundException(
2036 "Service Function Instance '{}' not found".format(sfi_id))
2037 elif len(sfi_list) > 1:
2038 raise vimconn.vimconnConflictException(
2039 'Found more than one Service Function Instance '
2040 'with this criteria')
2041 sfi = sfi_list[0]
2042 return sfi
2043
2044 def get_sfi_list(self, filter_dict={}):
2045 self.logger.debug("Getting Service Function Instances from "
2046 "VIM filter: '%s'", str(filter_dict))
2047 try:
2048 self._reload_connection()
2049 filter_dict_os = filter_dict.copy()
2050 if self.api_version3 and "tenant_id" in filter_dict_os:
2051 filter_dict_os['project_id'] = filter_dict_os.pop('tenant_id')
2052 sfi_dict = self.neutron.list_sfc_port_pairs(**filter_dict_os)
2053 sfi_list = sfi_dict["port_pairs"]
2054 self.__sfi_os2mano(sfi_list)
2055 return sfi_list
2056 except (neExceptions.ConnectionFailed, ksExceptions.ClientException,
2057 neExceptions.NeutronException, ConnectionError) as e:
2058 self._format_exception(e)
2059
2060 def delete_sfi(self, sfi_id):
2061 self.logger.debug("Deleting Service Function Instance '%s' "
2062 "from VIM", sfi_id)
2063 try:
2064 self._reload_connection()
2065 self.neutron.delete_sfc_port_pair(sfi_id)
2066 return sfi_id
2067 except (neExceptions.ConnectionFailed, neExceptions.NeutronException,
2068 ksExceptions.ClientException, neExceptions.NeutronException,
2069 ConnectionError) as e:
2070 self._format_exception(e)
2071
2072 def new_sf(self, name, sfis, sfc_encap=True):
2073 self.logger.debug("Adding a new Service Function to VIM, "
2074 "named '%s'", name)
2075 try:
2076 new_sf = None
2077 self._reload_connection()
2078 # correlation = None
2079 # if sfc_encap:
2080 # correlation = 'nsh'
2081 for instance in sfis:
2082 sfi = self.get_sfi(instance)
2083 if sfi.get('sfc_encap') != sfc_encap:
2084 raise vimconn.vimconnNotSupportedException(
2085 "OpenStack VIM connector requires all SFIs of the "
2086 "same SF to share the same SFC Encapsulation")
2087 sf_dict = {'name': name,
2088 'port_pairs': sfis}
2089 new_sf = self.neutron.create_sfc_port_pair_group({
2090 'port_pair_group': sf_dict})
2091 return new_sf['port_pair_group']['id']
2092 except (neExceptions.ConnectionFailed, ksExceptions.ClientException,
2093 neExceptions.NeutronException, ConnectionError) as e:
2094 if new_sf:
2095 try:
2096 self.neutron.delete_sfc_port_pair_group(
2097 new_sf['port_pair_group']['id'])
2098 except Exception:
2099 self.logger.error(
2100 'Creation of Service Function failed, with '
2101 'subsequent deletion failure as well.')
2102 self._format_exception(e)
2103
2104 def get_sf(self, sf_id):
2105 self.logger.debug("Getting Service Function %s from VIM", sf_id)
2106 filter_dict = {"id": sf_id}
2107 sf_list = self.get_sf_list(filter_dict)
2108 if len(sf_list) == 0:
2109 raise vimconn.vimconnNotFoundException(
2110 "Service Function '{}' not found".format(sf_id))
2111 elif len(sf_list) > 1:
2112 raise vimconn.vimconnConflictException(
2113 "Found more than one Service Function with this criteria")
2114 sf = sf_list[0]
2115 return sf
2116
2117 def get_sf_list(self, filter_dict={}):
2118 self.logger.debug("Getting Service Function from VIM filter: '%s'",
2119 str(filter_dict))
2120 try:
2121 self._reload_connection()
2122 filter_dict_os = filter_dict.copy()
2123 if self.api_version3 and "tenant_id" in filter_dict_os:
2124 filter_dict_os['project_id'] = filter_dict_os.pop('tenant_id')
2125 sf_dict = self.neutron.list_sfc_port_pair_groups(**filter_dict_os)
2126 sf_list = sf_dict["port_pair_groups"]
2127 self.__sf_os2mano(sf_list)
2128 return sf_list
2129 except (neExceptions.ConnectionFailed, ksExceptions.ClientException,
2130 neExceptions.NeutronException, ConnectionError) as e:
2131 self._format_exception(e)
2132
2133 def delete_sf(self, sf_id):
2134 self.logger.debug("Deleting Service Function '%s' from VIM", sf_id)
2135 try:
2136 self._reload_connection()
2137 self.neutron.delete_sfc_port_pair_group(sf_id)
2138 return sf_id
2139 except (neExceptions.ConnectionFailed, neExceptions.NeutronException,
2140 ksExceptions.ClientException, neExceptions.NeutronException,
2141 ConnectionError) as e:
2142 self._format_exception(e)
2143
2144 def new_sfp(self, name, classifications, sfs, sfc_encap=True, spi=None):
2145 self.logger.debug("Adding a new Service Function Path to VIM, "
2146 "named '%s'", name)
2147 try:
2148 new_sfp = None
2149 self._reload_connection()
2150 # In networking-sfc the MPLS encapsulation is legacy
2151 # should be used when no full SFC Encapsulation is intended
2152 correlation = 'mpls'
2153 if sfc_encap:
2154 correlation = 'nsh'
2155 sfp_dict = {'name': name,
2156 'flow_classifiers': classifications,
2157 'port_pair_groups': sfs,
2158 'chain_parameters': {'correlation': correlation}}
2159 if spi:
2160 sfp_dict['chain_id'] = spi
2161 new_sfp = self.neutron.create_sfc_port_chain({'port_chain': sfp_dict})
2162 return new_sfp["port_chain"]["id"]
2163 except (neExceptions.ConnectionFailed, ksExceptions.ClientException,
2164 neExceptions.NeutronException, ConnectionError) as e:
2165 if new_sfp:
2166 try:
2167 self.neutron.delete_sfc_port_chain(new_sfp['port_chain']['id'])
2168 except Exception:
2169 self.logger.error(
2170 'Creation of Service Function Path failed, with '
2171 'subsequent deletion failure as well.')
2172 self._format_exception(e)
2173
2174 def get_sfp(self, sfp_id):
2175 self.logger.debug(" Getting Service Function Path %s from VIM", sfp_id)
2176 filter_dict = {"id": sfp_id}
2177 sfp_list = self.get_sfp_list(filter_dict)
2178 if len(sfp_list) == 0:
2179 raise vimconn.vimconnNotFoundException(
2180 "Service Function Path '{}' not found".format(sfp_id))
2181 elif len(sfp_list) > 1:
2182 raise vimconn.vimconnConflictException(
2183 "Found more than one Service Function Path with this criteria")
2184 sfp = sfp_list[0]
2185 return sfp
2186
2187 def get_sfp_list(self, filter_dict={}):
2188 self.logger.debug("Getting Service Function Paths from VIM filter: "
2189 "'%s'", str(filter_dict))
2190 try:
2191 self._reload_connection()
2192 filter_dict_os = filter_dict.copy()
2193 if self.api_version3 and "tenant_id" in filter_dict_os:
2194 filter_dict_os['project_id'] = filter_dict_os.pop('tenant_id')
2195 sfp_dict = self.neutron.list_sfc_port_chains(**filter_dict_os)
2196 sfp_list = sfp_dict["port_chains"]
2197 self.__sfp_os2mano(sfp_list)
2198 return sfp_list
2199 except (neExceptions.ConnectionFailed, ksExceptions.ClientException,
2200 neExceptions.NeutronException, ConnectionError) as e:
2201 self._format_exception(e)
2202
2203 def delete_sfp(self, sfp_id):
2204 self.logger.debug(
2205 "Deleting Service Function Path '%s' from VIM", sfp_id)
2206 try:
2207 self._reload_connection()
2208 self.neutron.delete_sfc_port_chain(sfp_id)
2209 return sfp_id
2210 except (neExceptions.ConnectionFailed, neExceptions.NeutronException,
2211 ksExceptions.ClientException, neExceptions.NeutronException,
2212 ConnectionError) as e:
2213 self._format_exception(e)