blob: 734f7a307de27cc1148236171a525ef60f0d4230 [file] [log] [blame]
tierno7edb6752016-03-21 17:37:52 +01001# -*- coding: utf-8 -*-
2
3##
4# Copyright 2015 Telefónica Investigación 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'''
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +000025osconnector implements all the methods to interact with openstack using the python-neutronclient.
26
27For the VNF forwarding graph, The OpenStack VIM connector calls the
28networking-sfc Neutron extension methods, whose resources are mapped
29to 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)
tierno7edb6752016-03-21 17:37:52 +010034'''
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +000035__author__ = "Alfonso Tierno, Gerardo Garcia, Pablo Montes, xFlow Research, Igor D.C."
36__date__ = "$22-sep-2017 23:59:59$"
tierno7edb6752016-03-21 17:37:52 +010037
38import vimconn
tierno69b590e2018-03-13 18:52:23 +010039# import json
tiernoae4a8d12016-07-08 12:30:39 +020040import logging
garciadeblas9f8456e2016-09-05 05:02:59 +020041import netaddr
montesmoreno0c8def02016-12-22 12:16:23 +000042import time
tierno36c0b172017-01-12 18:32:28 +010043import yaml
garciadeblas2299e3b2017-01-26 14:35:55 +000044import random
kate721d79b2017-06-24 04:21:38 -070045import re
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +000046import copy
tierno7edb6752016-03-21 17:37:52 +010047
tiernob5cef372017-06-19 15:52:22 +020048from novaclient import client as nClient, exceptions as nvExceptions
49from keystoneauth1.identity import v2, v3
50from keystoneauth1 import session
tierno7edb6752016-03-21 17:37:52 +010051import keystoneclient.exceptions as ksExceptions
tiernof716aea2017-06-21 18:01:40 +020052import keystoneclient.v3.client as ksClient_v3
53import keystoneclient.v2_0.client as ksClient_v2
tiernob5cef372017-06-19 15:52:22 +020054from glanceclient import client as glClient
tierno7edb6752016-03-21 17:37:52 +010055import glanceclient.client as gl1Client
56import glanceclient.exc as gl1Exceptions
tiernob5cef372017-06-19 15:52:22 +020057from cinderclient import client as cClient
tierno7edb6752016-03-21 17:37:52 +010058from httplib import HTTPException
tiernob5cef372017-06-19 15:52:22 +020059from neutronclient.neutron import client as neClient
tierno7edb6752016-03-21 17:37:52 +010060from neutronclient.common import exceptions as neExceptions
61from requests.exceptions import ConnectionError
62
tierno40e1bce2017-08-09 09:12:04 +020063
64"""contain the openstack virtual machine status to openmano status"""
tierno7edb6752016-03-21 17:37:52 +010065vmStatus2manoFormat={'ACTIVE':'ACTIVE',
66 'PAUSED':'PAUSED',
67 'SUSPENDED': 'SUSPENDED',
68 'SHUTOFF':'INACTIVE',
69 'BUILD':'BUILD',
70 'ERROR':'ERROR','DELETED':'DELETED'
71 }
72netStatus2manoFormat={'ACTIVE':'ACTIVE','PAUSED':'PAUSED','INACTIVE':'INACTIVE','BUILD':'BUILD','ERROR':'ERROR','DELETED':'DELETED'
73 }
74
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +000075supportedClassificationTypes = ['legacy_flow_classifier']
76
montesmoreno0c8def02016-12-22 12:16:23 +000077#global var to have a timeout creating and deleting volumes
tierno00e3df72017-11-29 17:20:13 +010078volume_timeout = 600
79server_timeout = 600
montesmoreno0c8def02016-12-22 12:16:23 +000080
tierno7edb6752016-03-21 17:37:52 +010081class vimconnector(vimconn.vimconnector):
tiernob3d36742017-03-03 23:51:05 +010082 def __init__(self, uuid, name, tenant_id, tenant_name, url, url_admin=None, user=None, passwd=None,
83 log_level=None, config={}, persistent_info={}):
ahmadsa96af9f42017-01-31 16:17:14 +050084 '''using common constructor parameters. In this case
tierno7edb6752016-03-21 17:37:52 +010085 'url' is the keystone authorization url,
86 'url_admin' is not use
87 '''
tiernof716aea2017-06-21 18:01:40 +020088 api_version = config.get('APIversion')
89 if api_version and api_version not in ('v3.3', 'v2.0', '2', '3'):
tiernob5cef372017-06-19 15:52:22 +020090 raise vimconn.vimconnException("Invalid value '{}' for config:APIversion. "
tiernof716aea2017-06-21 18:01:40 +020091 "Allowed values are 'v3.3', 'v2.0', '2' or '3'".format(api_version))
kate721d79b2017-06-24 04:21:38 -070092 vim_type = config.get('vim_type')
93 if vim_type and vim_type not in ('vio', 'VIO'):
94 raise vimconn.vimconnException("Invalid value '{}' for config:vim_type."
95 "Allowed values are 'vio' or 'VIO'".format(vim_type))
96
97 if config.get('dataplane_net_vlan_range') is not None:
98 #validate vlan ranges provided by user
99 self._validate_vlan_ranges(config.get('dataplane_net_vlan_range'))
100
tiernob5cef372017-06-19 15:52:22 +0200101 vimconn.vimconnector.__init__(self, uuid, name, tenant_id, tenant_name, url, url_admin, user, passwd, log_level,
102 config)
tiernob3d36742017-03-03 23:51:05 +0100103
tiernob5cef372017-06-19 15:52:22 +0200104 self.insecure = self.config.get("insecure", False)
tierno7edb6752016-03-21 17:37:52 +0100105 if not url:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000106 raise TypeError('url param can not be NoneType')
tiernob5cef372017-06-19 15:52:22 +0200107 self.persistent_info = persistent_info
mirabal29356312017-07-27 12:21:22 +0200108 self.availability_zone = persistent_info.get('availability_zone', None)
tiernob5cef372017-06-19 15:52:22 +0200109 self.session = persistent_info.get('session', {'reload_client': True})
110 self.nova = self.session.get('nova')
111 self.neutron = self.session.get('neutron')
112 self.cinder = self.session.get('cinder')
113 self.glance = self.session.get('glance')
tiernob39d49e2017-08-02 14:02:15 +0200114 self.glancev1 = self.session.get('glancev1')
tiernof716aea2017-06-21 18:01:40 +0200115 self.keystone = self.session.get('keystone')
116 self.api_version3 = self.session.get('api_version3')
kate721d79b2017-06-24 04:21:38 -0700117 self.vim_type = self.config.get("vim_type")
118 if self.vim_type:
119 self.vim_type = self.vim_type.upper()
120 if self.config.get("use_internal_endpoint"):
121 self.endpoint_type = "internalURL"
122 else:
123 self.endpoint_type = None
montesmoreno0c8def02016-12-22 12:16:23 +0000124
tierno73ad9e42016-09-12 18:11:11 +0200125 self.logger = logging.getLogger('openmano.vim.openstack')
kate721d79b2017-06-24 04:21:38 -0700126
127 ####### VIO Specific Changes #########
128 if self.vim_type == "VIO":
129 self.logger = logging.getLogger('openmano.vim.vio')
130
tiernofe789902016-09-29 14:20:44 +0000131 if log_level:
kate54616752017-09-05 23:26:28 -0700132 self.logger.setLevel( getattr(logging, log_level))
tiernof716aea2017-06-21 18:01:40 +0200133
134 def __getitem__(self, index):
135 """Get individuals parameters.
136 Throw KeyError"""
137 if index == 'project_domain_id':
138 return self.config.get("project_domain_id")
139 elif index == 'user_domain_id':
140 return self.config.get("user_domain_id")
141 else:
tierno76a3c312017-06-29 16:42:15 +0200142 return vimconn.vimconnector.__getitem__(self, index)
tiernof716aea2017-06-21 18:01:40 +0200143
144 def __setitem__(self, index, value):
145 """Set individuals parameters and it is marked as dirty so to force connection reload.
146 Throw KeyError"""
147 if index == 'project_domain_id':
148 self.config["project_domain_id"] = value
149 elif index == 'user_domain_id':
150 self.config["user_domain_id"] = value
151 else:
152 vimconn.vimconnector.__setitem__(self, index, value)
tiernob5cef372017-06-19 15:52:22 +0200153 self.session['reload_client'] = True
tiernof716aea2017-06-21 18:01:40 +0200154
tierno7edb6752016-03-21 17:37:52 +0100155 def _reload_connection(self):
156 '''Called before any operation, it check if credentials has changed
157 Throw keystoneclient.apiclient.exceptions.AuthorizationFailure
158 '''
159 #TODO control the timing and possible token timeout, but it seams that python client does this task for us :-)
tiernob5cef372017-06-19 15:52:22 +0200160 if self.session['reload_client']:
tiernof716aea2017-06-21 18:01:40 +0200161 if self.config.get('APIversion'):
162 self.api_version3 = self.config['APIversion'] == 'v3.3' or self.config['APIversion'] == '3'
163 else: # get from ending auth_url that end with v3 or with v2.0
tierno3cb8dc32017-10-24 18:13:19 +0200164 self.api_version3 = self.url.endswith("/v3") or self.url.endswith("/v3/")
tiernof716aea2017-06-21 18:01:40 +0200165 self.session['api_version3'] = self.api_version3
166 if self.api_version3:
tierno3cb8dc32017-10-24 18:13:19 +0200167 if self.config.get('project_domain_id') or self.config.get('project_domain_name'):
168 project_domain_id_default = None
169 else:
170 project_domain_id_default = 'default'
171 if self.config.get('user_domain_id') or self.config.get('user_domain_name'):
172 user_domain_id_default = None
173 else:
174 user_domain_id_default = 'default'
tiernof716aea2017-06-21 18:01:40 +0200175 auth = v3.Password(auth_url=self.url,
tiernob5cef372017-06-19 15:52:22 +0200176 username=self.user,
177 password=self.passwd,
178 project_name=self.tenant_name,
179 project_id=self.tenant_id,
tierno3cb8dc32017-10-24 18:13:19 +0200180 project_domain_id=self.config.get('project_domain_id', project_domain_id_default),
181 user_domain_id=self.config.get('user_domain_id', user_domain_id_default),
182 project_domain_name=self.config.get('project_domain_name'),
183 user_domain_name=self.config.get('user_domain_name'))
ahmadsa95baa272016-11-30 09:14:11 +0500184 else:
tiernof716aea2017-06-21 18:01:40 +0200185 auth = v2.Password(auth_url=self.url,
tiernob5cef372017-06-19 15:52:22 +0200186 username=self.user,
187 password=self.passwd,
188 tenant_name=self.tenant_name,
189 tenant_id=self.tenant_id)
190 sess = session.Session(auth=auth, verify=not self.insecure)
tiernof716aea2017-06-21 18:01:40 +0200191 if self.api_version3:
kate721d79b2017-06-24 04:21:38 -0700192 self.keystone = ksClient_v3.Client(session=sess, endpoint_type=self.endpoint_type)
tiernof716aea2017-06-21 18:01:40 +0200193 else:
kate721d79b2017-06-24 04:21:38 -0700194 self.keystone = ksClient_v2.Client(session=sess, endpoint_type=self.endpoint_type)
tiernof716aea2017-06-21 18:01:40 +0200195 self.session['keystone'] = self.keystone
montesmoreno9317d302017-08-16 12:48:23 +0200196 # In order to enable microversion functionality an explicit microversion must be specified in 'config'.
197 # This implementation approach is due to the warning message in
198 # https://developer.openstack.org/api-guide/compute/microversions.html
199 # where it is stated that microversion backwards compatibility is not guaranteed and clients should
200 # always require an specific microversion.
201 # To be able to use 'device role tagging' functionality define 'microversion: 2.32' in datacenter config
202 version = self.config.get("microversion")
203 if not version:
204 version = "2.1"
kate54616752017-09-05 23:26:28 -0700205 self.nova = self.session['nova'] = nClient.Client(str(version), session=sess, endpoint_type=self.endpoint_type)
kate721d79b2017-06-24 04:21:38 -0700206 self.neutron = self.session['neutron'] = neClient.Client('2.0', session=sess, endpoint_type=self.endpoint_type)
207 self.cinder = self.session['cinder'] = cClient.Client(2, session=sess, endpoint_type=self.endpoint_type)
208 if self.endpoint_type == "internalURL":
209 glance_service_id = self.keystone.services.list(name="glance")[0].id
210 glance_endpoint = self.keystone.endpoints.list(glance_service_id, interface="internal")[0].url
211 else:
212 glance_endpoint = None
213 self.glance = self.session['glance'] = glClient.Client(2, session=sess, endpoint=glance_endpoint)
214 #using version 1 of glance client in new_image()
215 self.glancev1 = self.session['glancev1'] = glClient.Client('1', session=sess,
216 endpoint=glance_endpoint)
tiernob5cef372017-06-19 15:52:22 +0200217 self.session['reload_client'] = False
218 self.persistent_info['session'] = self.session
mirabal29356312017-07-27 12:21:22 +0200219 # add availablity zone info inside self.persistent_info
220 self._set_availablity_zones()
221 self.persistent_info['availability_zone'] = self.availability_zone
ahmadsa95baa272016-11-30 09:14:11 +0500222
tierno7edb6752016-03-21 17:37:52 +0100223 def __net_os2mano(self, net_list_dict):
224 '''Transform the net openstack format to mano format
225 net_list_dict can be a list of dict or a single dict'''
226 if type(net_list_dict) is dict:
227 net_list_=(net_list_dict,)
228 elif type(net_list_dict) is list:
229 net_list_=net_list_dict
230 else:
231 raise TypeError("param net_list_dict must be a list or a dictionary")
232 for net in net_list_:
233 if net.get('provider:network_type') == "vlan":
234 net['type']='data'
235 else:
236 net['type']='bridge'
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +0200237
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000238 def __classification_os2mano(self, class_list_dict):
239 """Transform the openstack format (Flow Classifier) to mano format
240 (Classification) class_list_dict can be a list of dict or a single dict
241 """
242 if isinstance(class_list_dict, dict):
243 class_list_ = [class_list_dict]
244 elif isinstance(class_list_dict, list):
245 class_list_ = class_list_dict
246 else:
247 raise TypeError(
248 "param class_list_dict must be a list or a dictionary")
249 for classification in class_list_:
250 id = classification.pop('id')
251 name = classification.pop('name')
252 description = classification.pop('description')
253 project_id = classification.pop('project_id')
254 tenant_id = classification.pop('tenant_id')
255 original_classification = copy.deepcopy(classification)
256 classification.clear()
257 classification['ctype'] = 'legacy_flow_classifier'
258 classification['definition'] = original_classification
259 classification['id'] = id
260 classification['name'] = name
261 classification['description'] = description
262 classification['project_id'] = project_id
263 classification['tenant_id'] = tenant_id
264
265 def __sfi_os2mano(self, sfi_list_dict):
266 """Transform the openstack format (Port Pair) to mano format (SFI)
267 sfi_list_dict can be a list of dict or a single dict
268 """
269 if isinstance(sfi_list_dict, dict):
270 sfi_list_ = [sfi_list_dict]
271 elif isinstance(sfi_list_dict, list):
272 sfi_list_ = sfi_list_dict
273 else:
274 raise TypeError(
275 "param sfi_list_dict must be a list or a dictionary")
276 for sfi in sfi_list_:
277 sfi['ingress_ports'] = []
278 sfi['egress_ports'] = []
279 if sfi.get('ingress'):
280 sfi['ingress_ports'].append(sfi['ingress'])
281 if sfi.get('egress'):
282 sfi['egress_ports'].append(sfi['egress'])
283 del sfi['ingress']
284 del sfi['egress']
285 params = sfi.get('service_function_parameters')
286 sfc_encap = False
287 if params:
288 correlation = params.get('correlation')
289 if correlation:
290 sfc_encap = True
291 sfi['sfc_encap'] = sfc_encap
292 del sfi['service_function_parameters']
293
294 def __sf_os2mano(self, sf_list_dict):
295 """Transform the openstack format (Port Pair Group) to mano format (SF)
296 sf_list_dict can be a list of dict or a single dict
297 """
298 if isinstance(sf_list_dict, dict):
299 sf_list_ = [sf_list_dict]
300 elif isinstance(sf_list_dict, list):
301 sf_list_ = sf_list_dict
302 else:
303 raise TypeError(
304 "param sf_list_dict must be a list or a dictionary")
305 for sf in sf_list_:
306 del sf['port_pair_group_parameters']
307 sf['sfis'] = sf['port_pairs']
308 del sf['port_pairs']
309
310 def __sfp_os2mano(self, sfp_list_dict):
311 """Transform the openstack format (Port Chain) to mano format (SFP)
312 sfp_list_dict can be a list of dict or a single dict
313 """
314 if isinstance(sfp_list_dict, dict):
315 sfp_list_ = [sfp_list_dict]
316 elif isinstance(sfp_list_dict, list):
317 sfp_list_ = sfp_list_dict
318 else:
319 raise TypeError(
320 "param sfp_list_dict must be a list or a dictionary")
321 for sfp in sfp_list_:
322 params = sfp.pop('chain_parameters')
323 sfc_encap = False
324 if params:
325 correlation = params.get('correlation')
326 if correlation:
327 sfc_encap = True
328 sfp['sfc_encap'] = sfc_encap
329 sfp['spi'] = sfp.pop('chain_id')
330 sfp['classifications'] = sfp.pop('flow_classifiers')
331 sfp['service_functions'] = sfp.pop('port_pair_groups')
332
333 # placeholder for now; read TODO note below
334 def _validate_classification(self, type, definition):
335 # only legacy_flow_classifier Type is supported at this point
336 return True
337 # TODO(igordcard): this method should be an abstract method of an
338 # abstract Classification class to be implemented by the specific
339 # Types. Also, abstract vimconnector should call the validation
340 # method before the implemented VIM connectors are called.
341
tiernoae4a8d12016-07-08 12:30:39 +0200342 def _format_exception(self, exception):
343 '''Transform a keystone, nova, neutron exception into a vimconn exception'''
344 if isinstance(exception, (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError,
tierno8e995ce2016-09-22 08:13:00 +0000345 ConnectionError, ksExceptions.ConnectionError, neExceptions.ConnectionFailed
346 )):
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000347 raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + str(exception))
348 elif isinstance(exception, (nvExceptions.ClientException, ksExceptions.ClientException,
tiernoae4a8d12016-07-08 12:30:39 +0200349 neExceptions.NeutronException, nvExceptions.BadRequest)):
350 raise vimconn.vimconnUnexpectedResponse(type(exception).__name__ + ": " + str(exception))
351 elif isinstance(exception, (neExceptions.NetworkNotFoundClient, nvExceptions.NotFound)):
352 raise vimconn.vimconnNotFoundException(type(exception).__name__ + ": " + str(exception))
353 elif isinstance(exception, nvExceptions.Conflict):
354 raise vimconn.vimconnConflictException(type(exception).__name__ + ": " + str(exception))
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +0200355 elif isinstance(exception, vimconn.vimconnException):
tierno41a69812018-02-16 14:34:33 +0100356 raise exception
tiernof716aea2017-06-21 18:01:40 +0200357 else: # ()
tiernob84cbdc2017-07-07 14:30:30 +0200358 self.logger.error("General Exception " + str(exception), exc_info=True)
tiernoae4a8d12016-07-08 12:30:39 +0200359 raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + str(exception))
360
361 def get_tenant_list(self, filter_dict={}):
362 '''Obtain tenants of VIM
363 filter_dict can contain the following keys:
364 name: filter by tenant name
365 id: filter by tenant uuid/id
366 <other VIM specific>
367 Returns the tenant list of dictionaries: [{'name':'<name>, 'id':'<id>, ...}, ...]
368 '''
ahmadsa95baa272016-11-30 09:14:11 +0500369 self.logger.debug("Getting tenants from VIM filter: '%s'", str(filter_dict))
tiernoae4a8d12016-07-08 12:30:39 +0200370 try:
371 self._reload_connection()
tiernof716aea2017-06-21 18:01:40 +0200372 if self.api_version3:
373 project_class_list = self.keystone.projects.list(name=filter_dict.get("name"))
ahmadsa95baa272016-11-30 09:14:11 +0500374 else:
tiernof716aea2017-06-21 18:01:40 +0200375 project_class_list = self.keystone.tenants.findall(**filter_dict)
ahmadsa95baa272016-11-30 09:14:11 +0500376 project_list=[]
377 for project in project_class_list:
tiernof716aea2017-06-21 18:01:40 +0200378 if filter_dict.get('id') and filter_dict["id"] != project.id:
379 continue
ahmadsa95baa272016-11-30 09:14:11 +0500380 project_list.append(project.to_dict())
381 return project_list
tiernof716aea2017-06-21 18:01:40 +0200382 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200383 self._format_exception(e)
384
385 def new_tenant(self, tenant_name, tenant_description):
386 '''Adds a new tenant to openstack VIM. Returns the tenant identifier'''
387 self.logger.debug("Adding a new tenant name: %s", tenant_name)
388 try:
389 self._reload_connection()
tiernof716aea2017-06-21 18:01:40 +0200390 if self.api_version3:
391 project = self.keystone.projects.create(tenant_name, self.config.get("project_domain_id", "default"),
392 description=tenant_description, is_domain=False)
ahmadsa95baa272016-11-30 09:14:11 +0500393 else:
tiernof716aea2017-06-21 18:01:40 +0200394 project = self.keystone.tenants.create(tenant_name, tenant_description)
ahmadsa95baa272016-11-30 09:14:11 +0500395 return project.id
tierno8e995ce2016-09-22 08:13:00 +0000396 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200397 self._format_exception(e)
398
399 def delete_tenant(self, tenant_id):
400 '''Delete a tenant from openstack VIM. Returns the old tenant identifier'''
401 self.logger.debug("Deleting tenant %s from VIM", tenant_id)
402 try:
403 self._reload_connection()
tiernof716aea2017-06-21 18:01:40 +0200404 if self.api_version3:
ahmadsa95baa272016-11-30 09:14:11 +0500405 self.keystone.projects.delete(tenant_id)
406 else:
407 self.keystone.tenants.delete(tenant_id)
tiernoae4a8d12016-07-08 12:30:39 +0200408 return tenant_id
tierno8e995ce2016-09-22 08:13:00 +0000409 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200410 self._format_exception(e)
ahmadsa95baa272016-11-30 09:14:11 +0500411
garciadeblas9f8456e2016-09-05 05:02:59 +0200412 def new_network(self,net_name, net_type, ip_profile=None, shared=False, vlan=None):
tiernoae4a8d12016-07-08 12:30:39 +0200413 '''Adds a tenant network to VIM. Returns the network identifier'''
414 self.logger.debug("Adding a new network to VIM name '%s', type '%s'", net_name, net_type)
garciadeblasedca7b32016-09-29 14:01:52 +0000415 #self.logger.debug(">>>>>>>>>>>>>>>>>> IP profile %s", str(ip_profile))
tierno7edb6752016-03-21 17:37:52 +0100416 try:
garciadeblasedca7b32016-09-29 14:01:52 +0000417 new_net = None
tierno7edb6752016-03-21 17:37:52 +0100418 self._reload_connection()
419 network_dict = {'name': net_name, 'admin_state_up': True}
420 if net_type=="data" or net_type=="ptp":
421 if self.config.get('dataplane_physical_net') == None:
tiernoae4a8d12016-07-08 12:30:39 +0200422 raise vimconn.vimconnConflictException("You must provide a 'dataplane_physical_net' at config value before creating sriov network")
tierno7edb6752016-03-21 17:37:52 +0100423 network_dict["provider:physical_network"] = self.config['dataplane_physical_net'] #"physnet_sriov" #TODO physical
424 network_dict["provider:network_type"] = "vlan"
425 if vlan!=None:
426 network_dict["provider:network_type"] = vlan
kate721d79b2017-06-24 04:21:38 -0700427
428 ####### VIO Specific Changes #########
429 if self.vim_type == "VIO":
430 if vlan is not None:
431 network_dict["provider:segmentation_id"] = vlan
432 else:
433 if self.config.get('dataplane_net_vlan_range') is None:
434 raise vimconn.vimconnConflictException("You must provide "\
435 "'dataplane_net_vlan_range' in format [start_ID - end_ID]"\
436 "at config value before creating sriov network with vlan tag")
437
438 network_dict["provider:segmentation_id"] = self._genrate_vlanID()
439
tiernoae4a8d12016-07-08 12:30:39 +0200440 network_dict["shared"]=shared
tierno7edb6752016-03-21 17:37:52 +0100441 new_net=self.neutron.create_network({'network':network_dict})
442 #print new_net
garciadeblas9f8456e2016-09-05 05:02:59 +0200443 #create subnetwork, even if there is no profile
444 if not ip_profile:
445 ip_profile = {}
tierno41a69812018-02-16 14:34:33 +0100446 if not ip_profile.get('subnet_address'):
garciadeblas2299e3b2017-01-26 14:35:55 +0000447 #Fake subnet is required
448 subnet_rand = random.randint(0, 255)
449 ip_profile['subnet_address'] = "192.168.{}.0/24".format(subnet_rand)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000450 if 'ip_version' not in ip_profile:
garciadeblas9f8456e2016-09-05 05:02:59 +0200451 ip_profile['ip_version'] = "IPv4"
tiernoa1fb4462017-06-30 12:25:50 +0200452 subnet = {"name":net_name+"-subnet",
tierno7edb6752016-03-21 17:37:52 +0100453 "network_id": new_net["network"]["id"],
garciadeblas9f8456e2016-09-05 05:02:59 +0200454 "ip_version": 4 if ip_profile['ip_version']=="IPv4" else 6,
455 "cidr": ip_profile['subnet_address']
tierno7edb6752016-03-21 17:37:52 +0100456 }
tiernoa1fb4462017-06-30 12:25:50 +0200457 # Gateway should be set to None if not needed. Otherwise openstack assigns one by default
tierno41a69812018-02-16 14:34:33 +0100458 if ip_profile.get('gateway_address'):
459 subnet['gateway_ip'] = ip_profile.get('gateway_address')
garciadeblasedca7b32016-09-29 14:01:52 +0000460 if ip_profile.get('dns_address'):
tierno455612d2017-05-30 16:40:10 +0200461 subnet['dns_nameservers'] = ip_profile['dns_address'].split(";")
garciadeblas9f8456e2016-09-05 05:02:59 +0200462 if 'dhcp_enabled' in ip_profile:
tierno41a69812018-02-16 14:34:33 +0100463 subnet['enable_dhcp'] = False if \
464 ip_profile['dhcp_enabled']=="false" or ip_profile['dhcp_enabled']==False else True
465 if ip_profile.get('dhcp_start_address'):
tiernoa1fb4462017-06-30 12:25:50 +0200466 subnet['allocation_pools'] = []
garciadeblas9f8456e2016-09-05 05:02:59 +0200467 subnet['allocation_pools'].append(dict())
468 subnet['allocation_pools'][0]['start'] = ip_profile['dhcp_start_address']
tierno41a69812018-02-16 14:34:33 +0100469 if ip_profile.get('dhcp_count'):
garciadeblas9f8456e2016-09-05 05:02:59 +0200470 #parts = ip_profile['dhcp_start_address'].split('.')
471 #ip_int = (int(parts[0]) << 24) + (int(parts[1]) << 16) + (int(parts[2]) << 8) + int(parts[3])
472 ip_int = int(netaddr.IPAddress(ip_profile['dhcp_start_address']))
garciadeblas21d795b2016-09-29 17:31:46 +0200473 ip_int += ip_profile['dhcp_count'] - 1
garciadeblas9f8456e2016-09-05 05:02:59 +0200474 ip_str = str(netaddr.IPAddress(ip_int))
475 subnet['allocation_pools'][0]['end'] = ip_str
garciadeblasedca7b32016-09-29 14:01:52 +0000476 #self.logger.debug(">>>>>>>>>>>>>>>>>> Subnet: %s", str(subnet))
tierno7edb6752016-03-21 17:37:52 +0100477 self.neutron.create_subnet({"subnet": subnet} )
tiernoae4a8d12016-07-08 12:30:39 +0200478 return new_net["network"]["id"]
tierno41a69812018-02-16 14:34:33 +0100479 except Exception as e:
garciadeblasedca7b32016-09-29 14:01:52 +0000480 if new_net:
481 self.neutron.delete_network(new_net['network']['id'])
tiernoae4a8d12016-07-08 12:30:39 +0200482 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100483
484 def get_network_list(self, filter_dict={}):
485 '''Obtain tenant networks of VIM
486 Filter_dict can be:
487 name: network name
488 id: network uuid
489 shared: boolean
490 tenant_id: tenant
491 admin_state_up: boolean
492 status: 'ACTIVE'
493 Returns the network list of dictionaries
494 '''
tiernoae4a8d12016-07-08 12:30:39 +0200495 self.logger.debug("Getting network from VIM filter: '%s'", str(filter_dict))
tierno7edb6752016-03-21 17:37:52 +0100496 try:
497 self._reload_connection()
tierno69b590e2018-03-13 18:52:23 +0100498 filter_dict_os = filter_dict.copy()
499 if self.api_version3 and "tenant_id" in filter_dict_os:
500 filter_dict_os['project_id'] = filter_dict_os.pop('tenant_id') #T ODO check
501 net_dict = self.neutron.list_networks(**filter_dict_os)
tierno00e3df72017-11-29 17:20:13 +0100502 net_list = net_dict["networks"]
tierno7edb6752016-03-21 17:37:52 +0100503 self.__net_os2mano(net_list)
tiernoae4a8d12016-07-08 12:30:39 +0200504 return net_list
tierno8e995ce2016-09-22 08:13:00 +0000505 except (neExceptions.ConnectionFailed, ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200506 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100507
tiernoae4a8d12016-07-08 12:30:39 +0200508 def get_network(self, net_id):
509 '''Obtain details of network from VIM
510 Returns the network information from a network id'''
511 self.logger.debug(" Getting tenant network %s from VIM", net_id)
tierno7edb6752016-03-21 17:37:52 +0100512 filter_dict={"id": net_id}
tiernoae4a8d12016-07-08 12:30:39 +0200513 net_list = self.get_network_list(filter_dict)
tierno7edb6752016-03-21 17:37:52 +0100514 if len(net_list)==0:
tiernoae4a8d12016-07-08 12:30:39 +0200515 raise vimconn.vimconnNotFoundException("Network '{}' not found".format(net_id))
tierno7edb6752016-03-21 17:37:52 +0100516 elif len(net_list)>1:
tiernoae4a8d12016-07-08 12:30:39 +0200517 raise vimconn.vimconnConflictException("Found more than one network with this criteria")
tierno7edb6752016-03-21 17:37:52 +0100518 net = net_list[0]
519 subnets=[]
520 for subnet_id in net.get("subnets", () ):
521 try:
522 subnet = self.neutron.show_subnet(subnet_id)
523 except Exception as e:
tiernoae4a8d12016-07-08 12:30:39 +0200524 self.logger.error("osconnector.get_network(): Error getting subnet %s %s" % (net_id, str(e)))
525 subnet = {"id": subnet_id, "fault": str(e)}
tierno7edb6752016-03-21 17:37:52 +0100526 subnets.append(subnet)
527 net["subnets"] = subnets
Pablo Montes Moreno51e553b2017-03-23 16:39:12 +0100528 net["encapsulation"] = net.get('provider:network_type')
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100529 net["segmentation_id"] = net.get('provider:segmentation_id')
tiernoae4a8d12016-07-08 12:30:39 +0200530 return net
tierno7edb6752016-03-21 17:37:52 +0100531
tiernoae4a8d12016-07-08 12:30:39 +0200532 def delete_network(self, net_id):
533 '''Deletes a tenant network from VIM. Returns the old network identifier'''
534 self.logger.debug("Deleting network '%s' from VIM", net_id)
tierno7edb6752016-03-21 17:37:52 +0100535 try:
536 self._reload_connection()
537 #delete VM ports attached to this networks before the network
538 ports = self.neutron.list_ports(network_id=net_id)
539 for p in ports['ports']:
540 try:
541 self.neutron.delete_port(p["id"])
542 except Exception as e:
tiernoae4a8d12016-07-08 12:30:39 +0200543 self.logger.error("Error deleting port %s: %s", p["id"], str(e))
tierno7edb6752016-03-21 17:37:52 +0100544 self.neutron.delete_network(net_id)
tiernoae4a8d12016-07-08 12:30:39 +0200545 return net_id
546 except (neExceptions.ConnectionFailed, neExceptions.NetworkNotFoundClient, neExceptions.NeutronException,
tierno8e995ce2016-09-22 08:13:00 +0000547 ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200548 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100549
tiernoae4a8d12016-07-08 12:30:39 +0200550 def refresh_nets_status(self, net_list):
551 '''Get the status of the networks
552 Params: the list of network identifiers
553 Returns a dictionary with:
554 net_id: #VIM id of this network
555 status: #Mandatory. Text with one of:
556 # DELETED (not found at vim)
557 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
558 # OTHER (Vim reported other status not understood)
559 # ERROR (VIM indicates an ERROR status)
560 # ACTIVE, INACTIVE, DOWN (admin down),
561 # BUILD (on building process)
562 #
563 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
564 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
565
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000566 '''
tiernoae4a8d12016-07-08 12:30:39 +0200567 net_dict={}
568 for net_id in net_list:
569 net = {}
570 try:
571 net_vim = self.get_network(net_id)
572 if net_vim['status'] in netStatus2manoFormat:
573 net["status"] = netStatus2manoFormat[ net_vim['status'] ]
574 else:
575 net["status"] = "OTHER"
576 net["error_msg"] = "VIM status reported " + net_vim['status']
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000577
tierno8e995ce2016-09-22 08:13:00 +0000578 if net['status'] == "ACTIVE" and not net_vim['admin_state_up']:
tiernoae4a8d12016-07-08 12:30:39 +0200579 net['status'] = 'DOWN'
tierno8e995ce2016-09-22 08:13:00 +0000580 try:
581 net['vim_info'] = yaml.safe_dump(net_vim, default_flow_style=True, width=256)
582 except yaml.representer.RepresenterError:
583 net['vim_info'] = str(net_vim)
tiernoae4a8d12016-07-08 12:30:39 +0200584 if net_vim.get('fault'): #TODO
585 net['error_msg'] = str(net_vim['fault'])
586 except vimconn.vimconnNotFoundException as e:
587 self.logger.error("Exception getting net status: %s", str(e))
588 net['status'] = "DELETED"
589 net['error_msg'] = str(e)
590 except vimconn.vimconnException as e:
591 self.logger.error("Exception getting net status: %s", str(e))
592 net['status'] = "VIM_ERROR"
593 net['error_msg'] = str(e)
594 net_dict[net_id] = net
595 return net_dict
596
597 def get_flavor(self, flavor_id):
598 '''Obtain flavor details from the VIM. Returns the flavor dict details'''
599 self.logger.debug("Getting flavor '%s'", flavor_id)
tierno7edb6752016-03-21 17:37:52 +0100600 try:
601 self._reload_connection()
602 flavor = self.nova.flavors.find(id=flavor_id)
603 #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
tiernoae4a8d12016-07-08 12:30:39 +0200604 return flavor.to_dict()
tierno8e995ce2016-09-22 08:13:00 +0000605 except (nvExceptions.NotFound, nvExceptions.ClientException, ksExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200606 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100607
tiernocf157a82017-01-30 14:07:06 +0100608 def get_flavor_id_from_data(self, flavor_dict):
609 """Obtain flavor id that match the flavor description
610 Returns the flavor_id or raises a vimconnNotFoundException
tiernoe26fc7a2017-05-30 14:43:03 +0200611 flavor_dict: contains the required ram, vcpus, disk
612 If 'use_existing_flavors' is set to True at config, the closer flavor that provides same or more ram, vcpus
613 and disk is returned. Otherwise a flavor with exactly same ram, vcpus and disk is returned or a
614 vimconnNotFoundException is raised
tiernocf157a82017-01-30 14:07:06 +0100615 """
tiernoe26fc7a2017-05-30 14:43:03 +0200616 exact_match = False if self.config.get('use_existing_flavors') else True
tiernocf157a82017-01-30 14:07:06 +0100617 try:
618 self._reload_connection()
tiernoe26fc7a2017-05-30 14:43:03 +0200619 flavor_candidate_id = None
620 flavor_candidate_data = (10000, 10000, 10000)
621 flavor_target = (flavor_dict["ram"], flavor_dict["vcpus"], flavor_dict["disk"])
622 # numa=None
623 numas = flavor_dict.get("extended", {}).get("numas")
tiernocf157a82017-01-30 14:07:06 +0100624 if numas:
625 #TODO
626 raise vimconn.vimconnNotFoundException("Flavor with EPA still not implemted")
627 # if len(numas) > 1:
628 # raise vimconn.vimconnNotFoundException("Cannot find any flavor with more than one numa")
629 # numa=numas[0]
630 # numas = extended.get("numas")
631 for flavor in self.nova.flavors.list():
632 epa = flavor.get_keys()
633 if epa:
634 continue
tiernoe26fc7a2017-05-30 14:43:03 +0200635 # TODO
636 flavor_data = (flavor.ram, flavor.vcpus, flavor.disk)
637 if flavor_data == flavor_target:
638 return flavor.id
639 elif not exact_match and flavor_target < flavor_data < flavor_candidate_data:
640 flavor_candidate_id = flavor.id
641 flavor_candidate_data = flavor_data
642 if not exact_match and flavor_candidate_id:
643 return flavor_candidate_id
tiernocf157a82017-01-30 14:07:06 +0100644 raise vimconn.vimconnNotFoundException("Cannot find any flavor matching '{}'".format(str(flavor_dict)))
645 except (nvExceptions.NotFound, nvExceptions.ClientException, ksExceptions.ClientException, ConnectionError) as e:
646 self._format_exception(e)
647
tiernoae4a8d12016-07-08 12:30:39 +0200648 def new_flavor(self, flavor_data, change_name_if_used=True):
tierno7edb6752016-03-21 17:37:52 +0100649 '''Adds a tenant flavor to openstack VIM
tiernoae4a8d12016-07-08 12:30:39 +0200650 if change_name_if_used is True, it will change name in case of conflict, because it is not supported name repetition
tierno7edb6752016-03-21 17:37:52 +0100651 Returns the flavor identifier
652 '''
tiernoae4a8d12016-07-08 12:30:39 +0200653 self.logger.debug("Adding flavor '%s'", str(flavor_data))
tierno7edb6752016-03-21 17:37:52 +0100654 retry=0
tiernoae4a8d12016-07-08 12:30:39 +0200655 max_retries=3
tierno7edb6752016-03-21 17:37:52 +0100656 name_suffix = 0
tiernoae4a8d12016-07-08 12:30:39 +0200657 name=flavor_data['name']
658 while retry<max_retries:
tierno7edb6752016-03-21 17:37:52 +0100659 retry+=1
660 try:
661 self._reload_connection()
662 if change_name_if_used:
663 #get used names
664 fl_names=[]
665 fl=self.nova.flavors.list()
666 for f in fl:
667 fl_names.append(f.name)
668 while name in fl_names:
669 name_suffix += 1
tiernoae4a8d12016-07-08 12:30:39 +0200670 name = flavor_data['name']+"-" + str(name_suffix)
kate721d79b2017-06-24 04:21:38 -0700671
tiernoae4a8d12016-07-08 12:30:39 +0200672 ram = flavor_data.get('ram',64)
673 vcpus = flavor_data.get('vcpus',1)
tierno7edb6752016-03-21 17:37:52 +0100674 numa_properties=None
675
tiernoae4a8d12016-07-08 12:30:39 +0200676 extended = flavor_data.get("extended")
tierno7edb6752016-03-21 17:37:52 +0100677 if extended:
678 numas=extended.get("numas")
679 if numas:
680 numa_nodes = len(numas)
681 if numa_nodes > 1:
682 return -1, "Can not add flavor with more than one numa"
683 numa_properties = {"hw:numa_nodes":str(numa_nodes)}
684 numa_properties["hw:mem_page_size"] = "large"
685 numa_properties["hw:cpu_policy"] = "dedicated"
686 numa_properties["hw:numa_mempolicy"] = "strict"
kate721d79b2017-06-24 04:21:38 -0700687 if self.vim_type == "VIO":
688 numa_properties["vmware:extra_config"] = '{"numa.nodeAffinity":"0"}'
689 numa_properties["vmware:latency_sensitivity_level"] = "high"
tierno7edb6752016-03-21 17:37:52 +0100690 for numa in numas:
691 #overwrite ram and vcpus
dhumalae3b28d2017-11-22 21:41:41 -0800692 #check if key 'memory' is present in numa else use ram value at flavor
693 if 'memory' in numa:
694 ram = numa['memory']*1024
Pablo Montes Morenoea1d6232017-05-24 11:33:24 +0200695 #See for reference: https://specs.openstack.org/openstack/nova-specs/specs/mitaka/implemented/virt-driver-cpu-thread-pinning.html
tierno7edb6752016-03-21 17:37:52 +0100696 if 'paired-threads' in numa:
697 vcpus = numa['paired-threads']*2
Pablo Montes Morenoea1d6232017-05-24 11:33:24 +0200698 #cpu_thread_policy "require" implies that the compute node must have an STM architecture
699 numa_properties["hw:cpu_thread_policy"] = "require"
700 numa_properties["hw:cpu_policy"] = "dedicated"
tierno7edb6752016-03-21 17:37:52 +0100701 elif 'cores' in numa:
702 vcpus = numa['cores']
Pablo Montes Morenoea1d6232017-05-24 11:33:24 +0200703 # cpu_thread_policy "prefer" implies that the host must not have an SMT architecture, or a non-SMT architecture will be emulated
704 numa_properties["hw:cpu_thread_policy"] = "isolate"
705 numa_properties["hw:cpu_policy"] = "dedicated"
tierno7edb6752016-03-21 17:37:52 +0100706 elif 'threads' in numa:
707 vcpus = numa['threads']
Pablo Montes Morenoea1d6232017-05-24 11:33:24 +0200708 # cpu_thread_policy "prefer" implies that the host may or may not have an SMT architecture
709 numa_properties["hw:cpu_thread_policy"] = "prefer"
710 numa_properties["hw:cpu_policy"] = "dedicated"
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +0200711 # for interface in numa.get("interfaces",() ):
712 # if interface["dedicated"]=="yes":
713 # raise vimconn.vimconnException("Passthrough interfaces are not supported for the openstack connector", http_code=vimconn.HTTP_Service_Unavailable)
714 # #TODO, add the key 'pci_passthrough:alias"="<label at config>:<number ifaces>"' when a way to connect it is available
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000715
tierno7edb6752016-03-21 17:37:52 +0100716 #create flavor
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000717 new_flavor=self.nova.flavors.create(name,
718 ram,
719 vcpus,
garciadeblas79d1a1a2017-12-11 16:07:07 +0100720 flavor_data.get('disk',0),
tiernoae4a8d12016-07-08 12:30:39 +0200721 is_public=flavor_data.get('is_public', True)
kate721d79b2017-06-24 04:21:38 -0700722 )
tierno7edb6752016-03-21 17:37:52 +0100723 #add metadata
724 if numa_properties:
725 new_flavor.set_keys(numa_properties)
tiernoae4a8d12016-07-08 12:30:39 +0200726 return new_flavor.id
tierno7edb6752016-03-21 17:37:52 +0100727 except nvExceptions.Conflict as e:
tiernoae4a8d12016-07-08 12:30:39 +0200728 if change_name_if_used and retry < max_retries:
tierno7edb6752016-03-21 17:37:52 +0100729 continue
tiernoae4a8d12016-07-08 12:30:39 +0200730 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100731 #except nvExceptions.BadRequest as e:
732 except (ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200733 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100734
tiernoae4a8d12016-07-08 12:30:39 +0200735 def delete_flavor(self,flavor_id):
736 '''Deletes a tenant flavor from openstack VIM. Returns the old flavor_id
tierno7edb6752016-03-21 17:37:52 +0100737 '''
tiernoae4a8d12016-07-08 12:30:39 +0200738 try:
739 self._reload_connection()
740 self.nova.flavors.delete(flavor_id)
741 return flavor_id
742 #except nvExceptions.BadRequest as e:
tierno8e995ce2016-09-22 08:13:00 +0000743 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200744 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100745
tiernoae4a8d12016-07-08 12:30:39 +0200746 def new_image(self,image_dict):
tierno7edb6752016-03-21 17:37:52 +0100747 '''
tiernoae4a8d12016-07-08 12:30:39 +0200748 Adds a tenant image to VIM. imge_dict is a dictionary with:
749 name: name
750 disk_format: qcow2, vhd, vmdk, raw (by default), ...
751 location: path or URI
752 public: "yes" or "no"
753 metadata: metadata of the image
754 Returns the image_id
tierno7edb6752016-03-21 17:37:52 +0100755 '''
tiernoae4a8d12016-07-08 12:30:39 +0200756 retry=0
757 max_retries=3
758 while retry<max_retries:
tierno7edb6752016-03-21 17:37:52 +0100759 retry+=1
760 try:
761 self._reload_connection()
762 #determine format http://docs.openstack.org/developer/glance/formats.html
763 if "disk_format" in image_dict:
764 disk_format=image_dict["disk_format"]
garciadeblas14480452017-01-10 13:08:07 +0100765 else: #autodiscover based on extension
tierno7edb6752016-03-21 17:37:52 +0100766 if image_dict['location'][-6:]==".qcow2":
767 disk_format="qcow2"
768 elif image_dict['location'][-4:]==".vhd":
769 disk_format="vhd"
770 elif image_dict['location'][-5:]==".vmdk":
771 disk_format="vmdk"
772 elif image_dict['location'][-4:]==".vdi":
773 disk_format="vdi"
774 elif image_dict['location'][-4:]==".iso":
775 disk_format="iso"
776 elif image_dict['location'][-4:]==".aki":
777 disk_format="aki"
778 elif image_dict['location'][-4:]==".ari":
779 disk_format="ari"
780 elif image_dict['location'][-4:]==".ami":
781 disk_format="ami"
782 else:
783 disk_format="raw"
tiernoae4a8d12016-07-08 12:30:39 +0200784 self.logger.debug("new_image: '%s' loading from '%s'", image_dict['name'], image_dict['location'])
tierno7edb6752016-03-21 17:37:52 +0100785 if image_dict['location'][0:4]=="http":
tiernob39d49e2017-08-02 14:02:15 +0200786 new_image = self.glancev1.images.create(name=image_dict['name'], is_public=image_dict.get('public',"yes")=="yes",
tierno7edb6752016-03-21 17:37:52 +0100787 container_format="bare", location=image_dict['location'], disk_format=disk_format)
788 else: #local path
789 with open(image_dict['location']) as fimage:
tiernob39d49e2017-08-02 14:02:15 +0200790 new_image = self.glancev1.images.create(name=image_dict['name'], is_public=image_dict.get('public',"yes")=="yes",
tierno7edb6752016-03-21 17:37:52 +0100791 container_format="bare", data=fimage, disk_format=disk_format)
792 #insert metadata. We cannot use 'new_image.properties.setdefault'
793 #because nova and glance are "INDEPENDENT" and we are using nova for reading metadata
794 new_image_nova=self.nova.images.find(id=new_image.id)
795 new_image_nova.metadata.setdefault('location',image_dict['location'])
796 metadata_to_load = image_dict.get('metadata')
797 if metadata_to_load:
798 for k,v in yaml.load(metadata_to_load).iteritems():
799 new_image_nova.metadata.setdefault(k,v)
tiernoae4a8d12016-07-08 12:30:39 +0200800 return new_image.id
801 except (nvExceptions.Conflict, ksExceptions.ClientException, nvExceptions.ClientException) as e:
802 self._format_exception(e)
tierno8e995ce2016-09-22 08:13:00 +0000803 except (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200804 if retry==max_retries:
805 continue
806 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100807 except IOError as e: #can not open the file
tiernoae4a8d12016-07-08 12:30:39 +0200808 raise vimconn.vimconnConnectionException(type(e).__name__ + ": " + str(e)+ " for " + image_dict['location'],
809 http_code=vimconn.HTTP_Bad_Request)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000810
tiernoae4a8d12016-07-08 12:30:39 +0200811 def delete_image(self, image_id):
812 '''Deletes a tenant image from openstack VIM. Returns the old id
tierno7edb6752016-03-21 17:37:52 +0100813 '''
tiernoae4a8d12016-07-08 12:30:39 +0200814 try:
815 self._reload_connection()
816 self.nova.images.delete(image_id)
817 return image_id
tierno8e995ce2016-09-22 08:13:00 +0000818 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e: #TODO remove
tiernoae4a8d12016-07-08 12:30:39 +0200819 self._format_exception(e)
820
821 def get_image_id_from_path(self, path):
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000822 '''Get the image id from image path in the VIM database. Returns the image_id'''
tiernoae4a8d12016-07-08 12:30:39 +0200823 try:
824 self._reload_connection()
825 images = self.nova.images.list()
826 for image in images:
827 if image.metadata.get("location")==path:
828 return image.id
829 raise vimconn.vimconnNotFoundException("image with location '{}' not found".format( path))
tierno8e995ce2016-09-22 08:13:00 +0000830 except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200831 self._format_exception(e)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000832
garciadeblasb69fa9f2016-09-28 12:04:10 +0200833 def get_image_list(self, filter_dict={}):
834 '''Obtain tenant images from VIM
835 Filter_dict can be:
836 id: image id
837 name: image name
838 checksum: image checksum
839 Returns the image list of dictionaries:
840 [{<the fields at Filter_dict plus some VIM specific>}, ...]
841 List can be empty
842 '''
843 self.logger.debug("Getting image list from VIM filter: '%s'", str(filter_dict))
844 try:
845 self._reload_connection()
tierno69b590e2018-03-13 18:52:23 +0100846 filter_dict_os = filter_dict.copy()
garciadeblasb69fa9f2016-09-28 12:04:10 +0200847 #First we filter by the available filter fields: name, id. The others are removed.
tierno69b590e2018-03-13 18:52:23 +0100848 filter_dict_os.pop('checksum', None)
tierno3cb8dc32017-10-24 18:13:19 +0200849 image_list = self.nova.images.findall(**filter_dict_os)
850 if len(image_list) == 0:
garciadeblasb69fa9f2016-09-28 12:04:10 +0200851 return []
852 #Then we filter by the rest of filter fields: checksum
853 filtered_list = []
854 for image in image_list:
tierno3cb8dc32017-10-24 18:13:19 +0200855 try:
856 image_class = self.glance.images.get(image.id)
tierno69b590e2018-03-13 18:52:23 +0100857 if 'checksum' not in filter_dict or image_class['checksum'] == filter_dict.get('checksum'):
tierno3cb8dc32017-10-24 18:13:19 +0200858 filtered_list.append(image_class.copy())
859 except gl1Exceptions.HTTPNotFound:
860 pass
garciadeblasb69fa9f2016-09-28 12:04:10 +0200861 return filtered_list
862 except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError, ConnectionError) as e:
863 self._format_exception(e)
864
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +0200865 def __wait_for_vm(self, vm_id, status):
866 """wait until vm is in the desired status and return True.
867 If the VM gets in ERROR status, return false.
868 If the timeout is reached generate an exception"""
869 elapsed_time = 0
870 while elapsed_time < server_timeout:
871 vm_status = self.nova.servers.get(vm_id).status
872 if vm_status == status:
873 return True
874 if vm_status == 'ERROR':
875 return False
876 time.sleep(1)
877 elapsed_time += 1
878
879 # if we exceeded the timeout rollback
880 if elapsed_time >= server_timeout:
881 raise vimconn.vimconnException('Timeout waiting for instance ' + vm_id + ' to get ' + status,
882 http_code=vimconn.HTTP_Request_Timeout)
883
mirabal29356312017-07-27 12:21:22 +0200884 def _get_openstack_availablity_zones(self):
885 """
886 Get from openstack availability zones available
887 :return:
888 """
889 try:
890 openstack_availability_zone = self.nova.availability_zones.list()
891 openstack_availability_zone = [str(zone.zoneName) for zone in openstack_availability_zone
892 if zone.zoneName != 'internal']
893 return openstack_availability_zone
894 except Exception as e:
895 return None
896
897 def _set_availablity_zones(self):
898 """
899 Set vim availablity zone
900 :return:
901 """
902
903 if 'availability_zone' in self.config:
904 vim_availability_zones = self.config.get('availability_zone')
905 if isinstance(vim_availability_zones, str):
906 self.availability_zone = [vim_availability_zones]
907 elif isinstance(vim_availability_zones, list):
908 self.availability_zone = vim_availability_zones
909 else:
910 self.availability_zone = self._get_openstack_availablity_zones()
911
tierno5a3273c2017-08-29 11:43:46 +0200912 def _get_vm_availability_zone(self, availability_zone_index, availability_zone_list):
mirabal29356312017-07-27 12:21:22 +0200913 """
tierno5a3273c2017-08-29 11:43:46 +0200914 Return thge availability zone to be used by the created VM.
915 :return: The VIM availability zone to be used or None
mirabal29356312017-07-27 12:21:22 +0200916 """
tierno5a3273c2017-08-29 11:43:46 +0200917 if availability_zone_index is None:
918 if not self.config.get('availability_zone'):
919 return None
920 elif isinstance(self.config.get('availability_zone'), str):
921 return self.config['availability_zone']
922 else:
923 # TODO consider using a different parameter at config for default AV and AV list match
924 return self.config['availability_zone'][0]
mirabal29356312017-07-27 12:21:22 +0200925
tierno5a3273c2017-08-29 11:43:46 +0200926 vim_availability_zones = self.availability_zone
927 # check if VIM offer enough availability zones describe in the VNFD
928 if vim_availability_zones and len(availability_zone_list) <= len(vim_availability_zones):
929 # check if all the names of NFV AV match VIM AV names
930 match_by_index = False
931 for av in availability_zone_list:
932 if av not in vim_availability_zones:
933 match_by_index = True
934 break
935 if match_by_index:
936 return vim_availability_zones[availability_zone_index]
937 else:
938 return availability_zone_list[availability_zone_index]
mirabal29356312017-07-27 12:21:22 +0200939 else:
tierno5a3273c2017-08-29 11:43:46 +0200940 raise vimconn.vimconnConflictException("No enough availability zones at VIM for this deployment")
mirabal29356312017-07-27 12:21:22 +0200941
tierno5a3273c2017-08-29 11:43:46 +0200942 def new_vminstance(self, name, description, start, image_id, flavor_id, net_list, cloud_config=None, disk_list=None,
943 availability_zone_index=None, availability_zone_list=None):
tierno98e909c2017-10-14 13:27:03 +0200944 """Adds a VM instance to VIM
tierno7edb6752016-03-21 17:37:52 +0100945 Params:
946 start: indicates if VM must start or boot in pause mode. Ignored
947 image_id,flavor_id: iamge and flavor uuid
948 net_list: list of interfaces, each one is a dictionary with:
949 name:
950 net_id: network uuid to connect
951 vpci: virtual vcpi to assign, ignored because openstack lack #TODO
952 model: interface model, ignored #TODO
953 mac_address: used for SR-IOV ifaces #TODO for other types
954 use: 'data', 'bridge', 'mgmt'
tierno66eba6e2017-11-10 17:09:18 +0100955 type: 'virtual', 'PCI-PASSTHROUGH'('PF'), 'SR-IOV'('VF'), 'VFnotShared'
tierno7edb6752016-03-21 17:37:52 +0100956 vim_id: filled/added by this function
ahmadsaf853d452016-12-22 11:33:47 +0500957 floating_ip: True/False (or it can be None)
tierno41a69812018-02-16 14:34:33 +0100958 'cloud_config': (optional) dictionary with:
959 'key-pairs': (optional) list of strings with the public key to be inserted to the default user
960 'users': (optional) list of users to be inserted, each item is a dict with:
961 'name': (mandatory) user name,
962 'key-pairs': (optional) list of strings with the public key to be inserted to the user
963 'user-data': (optional) string is a text script to be passed directly to cloud-init
964 'config-files': (optional). List of files to be transferred. Each item is a dict with:
965 'dest': (mandatory) string with the destination absolute path
966 'encoding': (optional, by default text). Can be one of:
967 'b64', 'base64', 'gz', 'gz+b64', 'gz+base64', 'gzip+b64', 'gzip+base64'
968 'content' (mandatory): string with the content of the file
969 'permissions': (optional) string with file permissions, typically octal notation '0644'
970 'owner': (optional) file owner, string with the format 'owner:group'
971 'boot-data-drive': boolean to indicate if user-data must be passed using a boot drive (hard disk)
mirabal29356312017-07-27 12:21:22 +0200972 'disk_list': (optional) list with additional disks to the VM. Each item is a dict with:
973 'image_id': (optional). VIM id of an existing image. If not provided an empty disk must be mounted
974 'size': (mandatory) string with the size of the disk in GB
tierno5a3273c2017-08-29 11:43:46 +0200975 availability_zone_index: Index of availability_zone_list to use for this this VM. None if not AV required
976 availability_zone_list: list of availability zones given by user in the VNFD descriptor. Ignore if
977 availability_zone_index is None
tierno7edb6752016-03-21 17:37:52 +0100978 #TODO ip, security groups
tierno98e909c2017-10-14 13:27:03 +0200979 Returns a tuple with the instance identifier and created_items or raises an exception on error
980 created_items can be None or a dictionary where this method can include key-values that will be passed to
981 the method delete_vminstance and action_vminstance. Can be used to store created ports, volumes, etc.
982 Format is vimconnector dependent, but do not use nested dictionaries and a value of None should be the same
983 as not present.
984 """
tiernofa51c202017-01-27 14:58:17 +0100985 self.logger.debug("new_vminstance input: image='%s' flavor='%s' nics='%s'",image_id, flavor_id,str(net_list))
tierno7edb6752016-03-21 17:37:52 +0100986 try:
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +0200987 server = None
tierno98e909c2017-10-14 13:27:03 +0200988 created_items = {}
tiernob0b9dab2017-10-14 14:25:20 +0200989 # metadata = {}
tierno98e909c2017-10-14 13:27:03 +0200990 net_list_vim = []
991 external_network = [] # list of external networks to be connected to instance, later on used to create floating_ip
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +0200992 no_secured_ports = [] # List of port-is with port-security disabled
tierno7edb6752016-03-21 17:37:52 +0100993 self._reload_connection()
tiernob0b9dab2017-10-14 14:25:20 +0200994 # metadata_vpci = {} # For a specific neutron plugin
tiernob84cbdc2017-07-07 14:30:30 +0200995 block_device_mapping = None
tierno7edb6752016-03-21 17:37:52 +0100996 for net in net_list:
tierno98e909c2017-10-14 13:27:03 +0200997 if not net.get("net_id"): # skip non connected iface
tierno7edb6752016-03-21 17:37:52 +0100998 continue
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +0200999
1000 port_dict={
1001 "network_id": net["net_id"],
1002 "name": net.get("name"),
1003 "admin_state_up": True
1004 }
1005 if net["type"]=="virtual":
tiernob0b9dab2017-10-14 14:25:20 +02001006 pass
1007 # if "vpci" in net:
1008 # metadata_vpci[ net["net_id"] ] = [[ net["vpci"], "" ]]
tierno66eba6e2017-11-10 17:09:18 +01001009 elif net["type"] == "VF" or net["type"] == "SR-IOV": # for VF
tiernob0b9dab2017-10-14 14:25:20 +02001010 # if "vpci" in net:
1011 # if "VF" not in metadata_vpci:
1012 # metadata_vpci["VF"]=[]
1013 # metadata_vpci["VF"].append([ net["vpci"], "" ])
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001014 port_dict["binding:vnic_type"]="direct"
tiernob0b9dab2017-10-14 14:25:20 +02001015 # VIO specific Changes
kate721d79b2017-06-24 04:21:38 -07001016 if self.vim_type == "VIO":
tiernob0b9dab2017-10-14 14:25:20 +02001017 # Need to create port with port_security_enabled = False and no-security-groups
kate721d79b2017-06-24 04:21:38 -07001018 port_dict["port_security_enabled"]=False
1019 port_dict["provider_security_groups"]=[]
1020 port_dict["security_groups"]=[]
tierno66eba6e2017-11-10 17:09:18 +01001021 else: # For PT PCI-PASSTHROUGH
tiernob0b9dab2017-10-14 14:25:20 +02001022 # VIO specific Changes
1023 # Current VIO release does not support port with type 'direct-physical'
1024 # So no need to create virtual port in case of PCI-device.
1025 # Will update port_dict code when support gets added in next VIO release
kate721d79b2017-06-24 04:21:38 -07001026 if self.vim_type == "VIO":
tiernob0b9dab2017-10-14 14:25:20 +02001027 raise vimconn.vimconnNotSupportedException(
1028 "Current VIO release does not support full passthrough (PT)")
1029 # if "vpci" in net:
1030 # if "PF" not in metadata_vpci:
1031 # metadata_vpci["PF"]=[]
1032 # metadata_vpci["PF"].append([ net["vpci"], "" ])
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001033 port_dict["binding:vnic_type"]="direct-physical"
1034 if not port_dict["name"]:
1035 port_dict["name"]=name
1036 if net.get("mac_address"):
1037 port_dict["mac_address"]=net["mac_address"]
tierno41a69812018-02-16 14:34:33 +01001038 if net.get("ip_address"):
1039 port_dict["fixed_ips"] = [{'ip_address': net["ip_address"]}]
1040 # TODO add 'subnet_id': <subnet_id>
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001041 new_port = self.neutron.create_port({"port": port_dict })
tierno00e3df72017-11-29 17:20:13 +01001042 created_items["port:" + str(new_port["port"]["id"])] = True
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001043 net["mac_adress"] = new_port["port"]["mac_address"]
1044 net["vim_id"] = new_port["port"]["id"]
tiernob84cbdc2017-07-07 14:30:30 +02001045 # if try to use a network without subnetwork, it will return a emtpy list
1046 fixed_ips = new_port["port"].get("fixed_ips")
1047 if fixed_ips:
1048 net["ip"] = fixed_ips[0].get("ip_address")
1049 else:
1050 net["ip"] = None
montesmoreno994a29d2017-08-22 11:23:06 +02001051
1052 port = {"port-id": new_port["port"]["id"]}
1053 if float(self.nova.api_version.get_string()) >= 2.32:
1054 port["tag"] = new_port["port"]["name"]
1055 net_list_vim.append(port)
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001056
ahmadsaf853d452016-12-22 11:33:47 +05001057 if net.get('floating_ip', False):
tiernof8383b82017-01-18 15:49:48 +01001058 net['exit_on_floating_ip_error'] = True
ahmadsaf853d452016-12-22 11:33:47 +05001059 external_network.append(net)
tiernof8383b82017-01-18 15:49:48 +01001060 elif net['use'] == 'mgmt' and self.config.get('use_floating_ip'):
1061 net['exit_on_floating_ip_error'] = False
1062 external_network.append(net)
1063
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001064 # If port security is disabled when the port has not yet been attached to the VM, then all vm traffic is dropped.
1065 # As a workaround we wait until the VM is active and then disable the port-security
1066 if net.get("port_security") == False:
1067 no_secured_ports.append(new_port["port"]["id"])
1068
tiernob0b9dab2017-10-14 14:25:20 +02001069 # if metadata_vpci:
1070 # metadata = {"pci_assignement": json.dumps(metadata_vpci)}
1071 # if len(metadata["pci_assignement"]) >255:
1072 # #limit the metadata size
1073 # #metadata["pci_assignement"] = metadata["pci_assignement"][0:255]
1074 # self.logger.warn("Metadata deleted since it exceeds the expected length (255) ")
1075 # metadata = {}
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001076
tiernob0b9dab2017-10-14 14:25:20 +02001077 self.logger.debug("name '%s' image_id '%s'flavor_id '%s' net_list_vim '%s' description '%s'",
1078 name, image_id, flavor_id, str(net_list_vim), description)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001079
tiernob0b9dab2017-10-14 14:25:20 +02001080 security_groups = self.config.get('security_groups')
tierno7edb6752016-03-21 17:37:52 +01001081 if type(security_groups) is str:
1082 security_groups = ( security_groups, )
tierno98e909c2017-10-14 13:27:03 +02001083 # cloud config
tierno0a1437e2017-10-02 00:17:43 +02001084 config_drive, userdata = self._create_user_data(cloud_config)
montesmoreno0c8def02016-12-22 12:16:23 +00001085
tierno98e909c2017-10-14 13:27:03 +02001086 # Create additional volumes in case these are present in disk_list
montesmoreno0c8def02016-12-22 12:16:23 +00001087 base_disk_index = ord('b')
1088 if disk_list != None:
tiernob84cbdc2017-07-07 14:30:30 +02001089 block_device_mapping = {}
montesmoreno0c8def02016-12-22 12:16:23 +00001090 for disk in disk_list:
1091 if 'image_id' in disk:
1092 volume = self.cinder.volumes.create(size = disk['size'],name = name + '_vd' +
1093 chr(base_disk_index), imageRef = disk['image_id'])
1094 else:
1095 volume = self.cinder.volumes.create(size=disk['size'], name=name + '_vd' +
1096 chr(base_disk_index))
tierno00e3df72017-11-29 17:20:13 +01001097 created_items["volume:" + str(volume.id)] = True
montesmoreno0c8def02016-12-22 12:16:23 +00001098 block_device_mapping['_vd' + chr(base_disk_index)] = volume.id
1099 base_disk_index += 1
1100
tiernob0b9dab2017-10-14 14:25:20 +02001101 # Wait until volumes are with status available
montesmoreno0c8def02016-12-22 12:16:23 +00001102 keep_waiting = True
1103 elapsed_time = 0
1104 while keep_waiting and elapsed_time < volume_timeout:
1105 keep_waiting = False
1106 for volume_id in block_device_mapping.itervalues():
1107 if self.cinder.volumes.get(volume_id).status != 'available':
1108 keep_waiting = True
1109 if keep_waiting:
1110 time.sleep(1)
1111 elapsed_time += 1
1112
tiernob0b9dab2017-10-14 14:25:20 +02001113 # If we exceeded the timeout rollback
montesmoreno0c8def02016-12-22 12:16:23 +00001114 if elapsed_time >= volume_timeout:
montesmoreno0c8def02016-12-22 12:16:23 +00001115 raise vimconn.vimconnException('Timeout creating volumes for instance ' + name,
1116 http_code=vimconn.HTTP_Request_Timeout)
mirabal29356312017-07-27 12:21:22 +02001117 # get availability Zone
tierno5a3273c2017-08-29 11:43:46 +02001118 vm_av_zone = self._get_vm_availability_zone(availability_zone_index, availability_zone_list)
montesmoreno0c8def02016-12-22 12:16:23 +00001119
tiernob0b9dab2017-10-14 14:25:20 +02001120 self.logger.debug("nova.servers.create({}, {}, {}, nics={}, security_groups={}, "
mirabal29356312017-07-27 12:21:22 +02001121 "availability_zone={}, key_name={}, userdata={}, config_drive={}, "
tiernob0b9dab2017-10-14 14:25:20 +02001122 "block_device_mapping={})".format(name, image_id, flavor_id, net_list_vim,
mirabal29356312017-07-27 12:21:22 +02001123 security_groups, vm_av_zone, self.config.get('keypair'),
tiernob0b9dab2017-10-14 14:25:20 +02001124 userdata, config_drive, block_device_mapping))
1125 server = self.nova.servers.create(name, image_id, flavor_id, nics=net_list_vim,
montesmoreno0c8def02016-12-22 12:16:23 +00001126 security_groups=security_groups,
mirabal29356312017-07-27 12:21:22 +02001127 availability_zone=vm_av_zone,
montesmoreno0c8def02016-12-22 12:16:23 +00001128 key_name=self.config.get('keypair'),
1129 userdata=userdata,
tiernob84cbdc2017-07-07 14:30:30 +02001130 config_drive=config_drive,
1131 block_device_mapping=block_device_mapping
montesmoreno0c8def02016-12-22 12:16:23 +00001132 ) # , description=description)
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001133
1134 # Previously mentioned workaround to wait until the VM is active and then disable the port-security
1135 if no_secured_ports:
1136 self.__wait_for_vm(server.id, 'ACTIVE')
1137
1138 for port_id in no_secured_ports:
1139 try:
1140 self.neutron.update_port(port_id, {"port": {"port_security_enabled": False, "security_groups": None} })
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001141 except Exception as e:
1142 self.logger.error("It was not possible to disable port security for port {}".format(port_id))
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001143 raise
1144
tierno98e909c2017-10-14 13:27:03 +02001145 # print "DONE :-)", server
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001146
tierno98e909c2017-10-14 13:27:03 +02001147 pool_id = None
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001148 if external_network:
tierno98e909c2017-10-14 13:27:03 +02001149 floating_ips = self.neutron.list_floatingips().get("floatingips", ())
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001150 self.__wait_for_vm(server.id, 'ACTIVE')
1151
ahmadsaf853d452016-12-22 11:33:47 +05001152 for floating_network in external_network:
tiernof8383b82017-01-18 15:49:48 +01001153 try:
tiernof8383b82017-01-18 15:49:48 +01001154 assigned = False
tierno98e909c2017-10-14 13:27:03 +02001155 while not assigned:
tiernof8383b82017-01-18 15:49:48 +01001156 if floating_ips:
1157 ip = floating_ips.pop(0)
1158 if not ip.get("port_id", False) and ip.get('tenant_id') == server.tenant_id:
1159 free_floating_ip = ip.get("floating_ip_address")
1160 try:
1161 fix_ip = floating_network.get('ip')
1162 server.add_floating_ip(free_floating_ip, fix_ip)
1163 assigned = True
1164 except Exception as e:
1165 raise vimconn.vimconnException(type(e).__name__ + ": Cannot create floating_ip "+ str(e), http_code=vimconn.HTTP_Conflict)
1166 else:
1167 #Find the external network
1168 external_nets = list()
1169 for net in self.neutron.list_networks()['networks']:
1170 if net['router:external']:
1171 external_nets.append(net)
1172
1173 if len(external_nets) == 0:
1174 raise vimconn.vimconnException("Cannot create floating_ip automatically since no external "
1175 "network is present",
1176 http_code=vimconn.HTTP_Conflict)
1177 if len(external_nets) > 1:
1178 raise vimconn.vimconnException("Cannot create floating_ip automatically since multiple "
1179 "external networks are present",
1180 http_code=vimconn.HTTP_Conflict)
1181
1182 pool_id = external_nets[0].get('id')
1183 param = {'floatingip': {'floating_network_id': pool_id, 'tenant_id': server.tenant_id}}
ahmadsaf853d452016-12-22 11:33:47 +05001184 try:
tiernof8383b82017-01-18 15:49:48 +01001185 #self.logger.debug("Creating floating IP")
1186 new_floating_ip = self.neutron.create_floatingip(param)
1187 free_floating_ip = new_floating_ip['floatingip']['floating_ip_address']
ahmadsaf853d452016-12-22 11:33:47 +05001188 fix_ip = floating_network.get('ip')
1189 server.add_floating_ip(free_floating_ip, fix_ip)
tiernof8383b82017-01-18 15:49:48 +01001190 assigned=True
ahmadsaf853d452016-12-22 11:33:47 +05001191 except Exception as e:
tiernof8383b82017-01-18 15:49:48 +01001192 raise vimconn.vimconnException(type(e).__name__ + ": Cannot assign floating_ip "+ str(e), http_code=vimconn.HTTP_Conflict)
1193 except Exception as e:
1194 if not floating_network['exit_on_floating_ip_error']:
1195 self.logger.warn("Cannot create floating_ip. %s", str(e))
1196 continue
tiernof8383b82017-01-18 15:49:48 +01001197 raise
montesmoreno2a1fc4e2017-01-09 16:46:04 +00001198
tierno98e909c2017-10-14 13:27:03 +02001199 return server.id, created_items
tierno7edb6752016-03-21 17:37:52 +01001200# except nvExceptions.NotFound as e:
1201# error_value=-vimconn.HTTP_Not_Found
1202# error_text= "vm instance %s not found" % vm_id
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001203# except TypeError as e:
1204# raise vimconn.vimconnException(type(e).__name__ + ": "+ str(e), http_code=vimconn.HTTP_Bad_Request)
1205
1206 except Exception as e:
tierno98e909c2017-10-14 13:27:03 +02001207 server_id = None
1208 if server:
1209 server_id = server.id
1210 try:
1211 self.delete_vminstance(server_id, created_items)
1212 except Exception as e2:
1213 self.logger.error("new_vminstance rollback fail {}".format(e2))
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001214
tiernoae4a8d12016-07-08 12:30:39 +02001215 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001216
tiernoae4a8d12016-07-08 12:30:39 +02001217 def get_vminstance(self,vm_id):
tierno7edb6752016-03-21 17:37:52 +01001218 '''Returns the VM instance information from VIM'''
tiernoae4a8d12016-07-08 12:30:39 +02001219 #self.logger.debug("Getting VM from VIM")
tierno7edb6752016-03-21 17:37:52 +01001220 try:
1221 self._reload_connection()
1222 server = self.nova.servers.find(id=vm_id)
1223 #TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
tiernoae4a8d12016-07-08 12:30:39 +02001224 return server.to_dict()
tierno8e995ce2016-09-22 08:13:00 +00001225 except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001226 self._format_exception(e)
1227
1228 def get_vminstance_console(self,vm_id, console_type="vnc"):
tierno7edb6752016-03-21 17:37:52 +01001229 '''
1230 Get a console for the virtual machine
1231 Params:
1232 vm_id: uuid of the VM
1233 console_type, can be:
1234 "novnc" (by default), "xvpvnc" for VNC types,
1235 "rdp-html5" for RDP types, "spice-html5" for SPICE types
tiernoae4a8d12016-07-08 12:30:39 +02001236 Returns dict with the console parameters:
1237 protocol: ssh, ftp, http, https, ...
1238 server: usually ip address
1239 port: the http, ssh, ... port
1240 suffix: extra text, e.g. the http path and query string
tierno7edb6752016-03-21 17:37:52 +01001241 '''
tiernoae4a8d12016-07-08 12:30:39 +02001242 self.logger.debug("Getting VM CONSOLE from VIM")
tierno7edb6752016-03-21 17:37:52 +01001243 try:
1244 self._reload_connection()
1245 server = self.nova.servers.find(id=vm_id)
1246 if console_type == None or console_type == "novnc":
1247 console_dict = server.get_vnc_console("novnc")
1248 elif console_type == "xvpvnc":
1249 console_dict = server.get_vnc_console(console_type)
1250 elif console_type == "rdp-html5":
1251 console_dict = server.get_rdp_console(console_type)
1252 elif console_type == "spice-html5":
1253 console_dict = server.get_spice_console(console_type)
1254 else:
tiernoae4a8d12016-07-08 12:30:39 +02001255 raise vimconn.vimconnException("console type '{}' not allowed".format(console_type), http_code=vimconn.HTTP_Bad_Request)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001256
tierno7edb6752016-03-21 17:37:52 +01001257 console_dict1 = console_dict.get("console")
1258 if console_dict1:
1259 console_url = console_dict1.get("url")
1260 if console_url:
1261 #parse console_url
1262 protocol_index = console_url.find("//")
1263 suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2
1264 port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2
1265 if protocol_index < 0 or port_index<0 or suffix_index<0:
1266 return -vimconn.HTTP_Internal_Server_Error, "Unexpected response from VIM"
1267 console_dict={"protocol": console_url[0:protocol_index],
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001268 "server": console_url[protocol_index+2:port_index],
1269 "port": console_url[port_index:suffix_index],
1270 "suffix": console_url[suffix_index+1:]
tierno7edb6752016-03-21 17:37:52 +01001271 }
1272 protocol_index += 2
tiernoae4a8d12016-07-08 12:30:39 +02001273 return console_dict
1274 raise vimconn.vimconnUnexpectedResponse("Unexpected response from VIM")
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001275
tierno8e995ce2016-09-22 08:13:00 +00001276 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.BadRequest, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001277 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001278
tierno98e909c2017-10-14 13:27:03 +02001279 def delete_vminstance(self, vm_id, created_items=None):
tiernoae4a8d12016-07-08 12:30:39 +02001280 '''Removes a VM instance from VIM. Returns the old identifier
tierno7edb6752016-03-21 17:37:52 +01001281 '''
tiernoae4a8d12016-07-08 12:30:39 +02001282 #print "osconnector: Getting VM from VIM"
tierno98e909c2017-10-14 13:27:03 +02001283 if created_items == None:
1284 created_items = {}
tierno7edb6752016-03-21 17:37:52 +01001285 try:
1286 self._reload_connection()
tierno98e909c2017-10-14 13:27:03 +02001287 # delete VM ports attached to this networks before the virtual machine
1288 for k, v in created_items.items():
1289 if not v: # skip already deleted
1290 continue
tierno7edb6752016-03-21 17:37:52 +01001291 try:
tiernoad6bdd42018-01-10 10:43:46 +01001292 k_item, _, k_id = k.partition(":")
1293 if k_item == "port":
1294 self.neutron.delete_port(k_id)
tierno7edb6752016-03-21 17:37:52 +01001295 except Exception as e:
tierno00e3df72017-11-29 17:20:13 +01001296 self.logger.error("Error deleting port: {}: {}".format(type(e).__name__, e))
montesmoreno0c8def02016-12-22 12:16:23 +00001297
tierno98e909c2017-10-14 13:27:03 +02001298 # #commented because detaching the volumes makes the servers.delete not work properly ?!?
1299 # #dettach volumes attached
1300 # server = self.nova.servers.get(vm_id)
1301 # volumes_attached_dict = server._info['os-extended-volumes:volumes_attached'] #volume['id']
1302 # #for volume in volumes_attached_dict:
1303 # # self.cinder.volumes.detach(volume['id'])
montesmoreno0c8def02016-12-22 12:16:23 +00001304
tierno98e909c2017-10-14 13:27:03 +02001305 if vm_id:
1306 self.nova.servers.delete(vm_id)
montesmoreno0c8def02016-12-22 12:16:23 +00001307
tierno98e909c2017-10-14 13:27:03 +02001308 # delete volumes. Although having detached, they should have in active status before deleting
1309 # we ensure in this loop
montesmoreno0c8def02016-12-22 12:16:23 +00001310 keep_waiting = True
1311 elapsed_time = 0
1312 while keep_waiting and elapsed_time < volume_timeout:
1313 keep_waiting = False
tierno98e909c2017-10-14 13:27:03 +02001314 for k, v in created_items.items():
1315 if not v: # skip already deleted
1316 continue
1317 try:
tiernoad6bdd42018-01-10 10:43:46 +01001318 k_item, _, k_id = k.partition(":")
1319 if k_item == "volume":
1320 if self.cinder.volumes.get(k_id).status != 'available':
tierno98e909c2017-10-14 13:27:03 +02001321 keep_waiting = True
1322 else:
tiernoad6bdd42018-01-10 10:43:46 +01001323 self.cinder.volumes.delete(k_id)
tierno98e909c2017-10-14 13:27:03 +02001324 except Exception as e:
tierno00e3df72017-11-29 17:20:13 +01001325 self.logger.error("Error deleting volume: {}: {}".format(type(e).__name__, e))
montesmoreno0c8def02016-12-22 12:16:23 +00001326 if keep_waiting:
1327 time.sleep(1)
1328 elapsed_time += 1
tierno98e909c2017-10-14 13:27:03 +02001329 return None
tierno8e995ce2016-09-22 08:13:00 +00001330 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001331 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001332
tiernoae4a8d12016-07-08 12:30:39 +02001333 def refresh_vms_status(self, vm_list):
1334 '''Get the status of the virtual machines and their interfaces/ports
1335 Params: the list of VM identifiers
1336 Returns a dictionary with:
1337 vm_id: #VIM id of this Virtual Machine
1338 status: #Mandatory. Text with one of:
1339 # DELETED (not found at vim)
1340 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
1341 # OTHER (Vim reported other status not understood)
1342 # ERROR (VIM indicates an ERROR status)
1343 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
1344 # CREATING (on building process), ERROR
1345 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
1346 #
1347 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
1348 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1349 interfaces:
1350 - vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1351 mac_address: #Text format XX:XX:XX:XX:XX:XX
1352 vim_net_id: #network id where this interface is connected
1353 vim_interface_id: #interface/port VIM id
1354 ip_address: #null, or text with IPv4, IPv6 address
tierno867ffe92017-03-27 12:50:34 +02001355 compute_node: #identification of compute node where PF,VF interface is allocated
1356 pci: #PCI address of the NIC that hosts the PF,VF
1357 vlan: #physical VLAN used for VF
tierno7edb6752016-03-21 17:37:52 +01001358 '''
tiernoae4a8d12016-07-08 12:30:39 +02001359 vm_dict={}
1360 self.logger.debug("refresh_vms status: Getting tenant VM instance information from VIM")
1361 for vm_id in vm_list:
1362 vm={}
1363 try:
1364 vm_vim = self.get_vminstance(vm_id)
1365 if vm_vim['status'] in vmStatus2manoFormat:
1366 vm['status'] = vmStatus2manoFormat[ vm_vim['status'] ]
tierno7edb6752016-03-21 17:37:52 +01001367 else:
tiernoae4a8d12016-07-08 12:30:39 +02001368 vm['status'] = "OTHER"
1369 vm['error_msg'] = "VIM status reported " + vm_vim['status']
tierno8e995ce2016-09-22 08:13:00 +00001370 try:
1371 vm['vim_info'] = yaml.safe_dump(vm_vim, default_flow_style=True, width=256)
1372 except yaml.representer.RepresenterError:
1373 vm['vim_info'] = str(vm_vim)
tiernoae4a8d12016-07-08 12:30:39 +02001374 vm["interfaces"] = []
1375 if vm_vim.get('fault'):
1376 vm['error_msg'] = str(vm_vim['fault'])
1377 #get interfaces
tierno7edb6752016-03-21 17:37:52 +01001378 try:
tiernoae4a8d12016-07-08 12:30:39 +02001379 self._reload_connection()
1380 port_dict=self.neutron.list_ports(device_id=vm_id)
1381 for port in port_dict["ports"]:
1382 interface={}
tierno8e995ce2016-09-22 08:13:00 +00001383 try:
1384 interface['vim_info'] = yaml.safe_dump(port, default_flow_style=True, width=256)
1385 except yaml.representer.RepresenterError:
1386 interface['vim_info'] = str(port)
tiernoae4a8d12016-07-08 12:30:39 +02001387 interface["mac_address"] = port.get("mac_address")
1388 interface["vim_net_id"] = port["network_id"]
1389 interface["vim_interface_id"] = port["id"]
Mike Marchetti5b9da422017-05-02 15:35:47 -04001390 # check if OS-EXT-SRV-ATTR:host is there,
1391 # in case of non-admin credentials, it will be missing
1392 if vm_vim.get('OS-EXT-SRV-ATTR:host'):
1393 interface["compute_node"] = vm_vim['OS-EXT-SRV-ATTR:host']
tierno867ffe92017-03-27 12:50:34 +02001394 interface["pci"] = None
Mike Marchetti5b9da422017-05-02 15:35:47 -04001395
1396 # check if binding:profile is there,
1397 # in case of non-admin credentials, it will be missing
1398 if port.get('binding:profile'):
1399 if port['binding:profile'].get('pci_slot'):
1400 # TODO: At the moment sr-iov pci addresses are converted to PF pci addresses by setting the slot to 0x00
1401 # TODO: This is just a workaround valid for niantinc. Find a better way to do so
1402 # CHANGE DDDD:BB:SS.F to DDDD:BB:00.(F%2) assuming there are 2 ports per nic
1403 pci = port['binding:profile']['pci_slot']
1404 # interface["pci"] = pci[:-4] + "00." + str(int(pci[-1]) % 2)
1405 interface["pci"] = pci
tierno867ffe92017-03-27 12:50:34 +02001406 interface["vlan"] = None
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001407 #if network is of type vlan and port is of type direct (sr-iov) then set vlan id
Pablo Montes Moreno51e553b2017-03-23 16:39:12 +01001408 network = self.neutron.show_network(port["network_id"])
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001409 if network['network'].get('provider:network_type') == 'vlan' and \
1410 port.get("binding:vnic_type") == "direct":
tierno867ffe92017-03-27 12:50:34 +02001411 interface["vlan"] = network['network'].get('provider:segmentation_id')
tiernoae4a8d12016-07-08 12:30:39 +02001412 ips=[]
1413 #look for floating ip address
1414 floating_ip_dict = self.neutron.list_floatingips(port_id=port["id"])
1415 if floating_ip_dict.get("floatingips"):
1416 ips.append(floating_ip_dict["floatingips"][0].get("floating_ip_address") )
tierno7edb6752016-03-21 17:37:52 +01001417
tiernoae4a8d12016-07-08 12:30:39 +02001418 for subnet in port["fixed_ips"]:
1419 ips.append(subnet["ip_address"])
1420 interface["ip_address"] = ";".join(ips)
1421 vm["interfaces"].append(interface)
1422 except Exception as e:
1423 self.logger.error("Error getting vm interface information " + type(e).__name__ + ": "+ str(e))
1424 except vimconn.vimconnNotFoundException as e:
1425 self.logger.error("Exception getting vm status: %s", str(e))
1426 vm['status'] = "DELETED"
1427 vm['error_msg'] = str(e)
1428 except vimconn.vimconnException as e:
1429 self.logger.error("Exception getting vm status: %s", str(e))
1430 vm['status'] = "VIM_ERROR"
1431 vm['error_msg'] = str(e)
1432 vm_dict[vm_id] = vm
1433 return vm_dict
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001434
tierno98e909c2017-10-14 13:27:03 +02001435 def action_vminstance(self, vm_id, action_dict, created_items={}):
tierno7edb6752016-03-21 17:37:52 +01001436 '''Send and action over a VM instance from VIM
tierno98e909c2017-10-14 13:27:03 +02001437 Returns None or the console dict if the action was successfully sent to the VIM'''
tiernoae4a8d12016-07-08 12:30:39 +02001438 self.logger.debug("Action over VM '%s': %s", vm_id, str(action_dict))
tierno7edb6752016-03-21 17:37:52 +01001439 try:
1440 self._reload_connection()
1441 server = self.nova.servers.find(id=vm_id)
1442 if "start" in action_dict:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001443 if action_dict["start"]=="rebuild":
tierno7edb6752016-03-21 17:37:52 +01001444 server.rebuild()
1445 else:
1446 if server.status=="PAUSED":
1447 server.unpause()
1448 elif server.status=="SUSPENDED":
1449 server.resume()
1450 elif server.status=="SHUTOFF":
1451 server.start()
1452 elif "pause" in action_dict:
1453 server.pause()
1454 elif "resume" in action_dict:
1455 server.resume()
1456 elif "shutoff" in action_dict or "shutdown" in action_dict:
1457 server.stop()
1458 elif "forceOff" in action_dict:
1459 server.stop() #TODO
1460 elif "terminate" in action_dict:
1461 server.delete()
1462 elif "createImage" in action_dict:
1463 server.create_image()
1464 #"path":path_schema,
1465 #"description":description_schema,
1466 #"name":name_schema,
1467 #"metadata":metadata_schema,
1468 #"imageRef": id_schema,
1469 #"disk": {"oneOf":[{"type": "null"}, {"type":"string"}] },
1470 elif "rebuild" in action_dict:
1471 server.rebuild(server.image['id'])
1472 elif "reboot" in action_dict:
1473 server.reboot() #reboot_type='SOFT'
1474 elif "console" in action_dict:
1475 console_type = action_dict["console"]
1476 if console_type == None or console_type == "novnc":
1477 console_dict = server.get_vnc_console("novnc")
1478 elif console_type == "xvpvnc":
1479 console_dict = server.get_vnc_console(console_type)
1480 elif console_type == "rdp-html5":
1481 console_dict = server.get_rdp_console(console_type)
1482 elif console_type == "spice-html5":
1483 console_dict = server.get_spice_console(console_type)
1484 else:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001485 raise vimconn.vimconnException("console type '{}' not allowed".format(console_type),
tiernoae4a8d12016-07-08 12:30:39 +02001486 http_code=vimconn.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001487 try:
1488 console_url = console_dict["console"]["url"]
1489 #parse console_url
1490 protocol_index = console_url.find("//")
1491 suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2
1492 port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2
1493 if protocol_index < 0 or port_index<0 or suffix_index<0:
tiernoae4a8d12016-07-08 12:30:39 +02001494 raise vimconn.vimconnException("Unexpected response from VIM " + str(console_dict))
tierno7edb6752016-03-21 17:37:52 +01001495 console_dict2={"protocol": console_url[0:protocol_index],
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001496 "server": console_url[protocol_index+2 : port_index],
1497 "port": int(console_url[port_index+1 : suffix_index]),
1498 "suffix": console_url[suffix_index+1:]
tierno7edb6752016-03-21 17:37:52 +01001499 }
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001500 return console_dict2
tiernoae4a8d12016-07-08 12:30:39 +02001501 except Exception as e:
1502 raise vimconn.vimconnException("Unexpected response from VIM " + str(console_dict))
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001503
tierno98e909c2017-10-14 13:27:03 +02001504 return None
tierno8e995ce2016-09-22 08:13:00 +00001505 except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001506 self._format_exception(e)
1507 #TODO insert exception vimconn.HTTP_Unauthorized
1508
kate721d79b2017-06-24 04:21:38 -07001509 ####### VIO Specific Changes #########
1510 def _genrate_vlanID(self):
1511 """
1512 Method to get unused vlanID
1513 Args:
1514 None
1515 Returns:
1516 vlanID
1517 """
1518 #Get used VLAN IDs
1519 usedVlanIDs = []
1520 networks = self.get_network_list()
1521 for net in networks:
1522 if net.get('provider:segmentation_id'):
1523 usedVlanIDs.append(net.get('provider:segmentation_id'))
1524 used_vlanIDs = set(usedVlanIDs)
1525
1526 #find unused VLAN ID
1527 for vlanID_range in self.config.get('dataplane_net_vlan_range'):
1528 try:
1529 start_vlanid , end_vlanid = map(int, vlanID_range.replace(" ", "").split("-"))
1530 for vlanID in xrange(start_vlanid, end_vlanid + 1):
1531 if vlanID not in used_vlanIDs:
1532 return vlanID
1533 except Exception as exp:
1534 raise vimconn.vimconnException("Exception {} occurred while generating VLAN ID.".format(exp))
1535 else:
1536 raise vimconn.vimconnConflictException("Unable to create the SRIOV VLAN network."\
1537 " All given Vlan IDs {} are in use.".format(self.config.get('dataplane_net_vlan_range')))
1538
1539
1540 def _validate_vlan_ranges(self, dataplane_net_vlan_range):
1541 """
1542 Method to validate user given vlanID ranges
1543 Args: None
1544 Returns: None
1545 """
1546 for vlanID_range in dataplane_net_vlan_range:
1547 vlan_range = vlanID_range.replace(" ", "")
1548 #validate format
1549 vlanID_pattern = r'(\d)*-(\d)*$'
1550 match_obj = re.match(vlanID_pattern, vlan_range)
1551 if not match_obj:
1552 raise vimconn.vimconnConflictException("Invalid dataplane_net_vlan_range {}.You must provide "\
1553 "'dataplane_net_vlan_range' in format [start_ID - end_ID].".format(vlanID_range))
1554
1555 start_vlanid , end_vlanid = map(int,vlan_range.split("-"))
1556 if start_vlanid <= 0 :
1557 raise vimconn.vimconnConflictException("Invalid dataplane_net_vlan_range {}."\
1558 "Start ID can not be zero. For VLAN "\
1559 "networks valid IDs are 1 to 4094 ".format(vlanID_range))
1560 if end_vlanid > 4094 :
1561 raise vimconn.vimconnConflictException("Invalid dataplane_net_vlan_range {}."\
1562 "End VLAN ID can not be greater than 4094. For VLAN "\
1563 "networks valid IDs are 1 to 4094 ".format(vlanID_range))
1564
1565 if start_vlanid > end_vlanid:
1566 raise vimconn.vimconnConflictException("Invalid dataplane_net_vlan_range {}."\
1567 "You must provide a 'dataplane_net_vlan_range' in format start_ID - end_ID and "\
1568 "start_ID < end_ID ".format(vlanID_range))
1569
tiernoae4a8d12016-07-08 12:30:39 +02001570#NOT USED FUNCTIONS
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001571
tiernoae4a8d12016-07-08 12:30:39 +02001572 def new_external_port(self, port_data):
1573 #TODO openstack if needed
1574 '''Adds a external port to VIM'''
1575 '''Returns the port identifier'''
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001576 return -vimconn.HTTP_Internal_Server_Error, "osconnector.new_external_port() not implemented"
1577
tiernoae4a8d12016-07-08 12:30:39 +02001578 def connect_port_network(self, port_id, network_id, admin=False):
1579 #TODO openstack if needed
1580 '''Connects a external port to a network'''
1581 '''Returns status code of the VIM response'''
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001582 return -vimconn.HTTP_Internal_Server_Error, "osconnector.connect_port_network() not implemented"
1583
tiernoae4a8d12016-07-08 12:30:39 +02001584 def new_user(self, user_name, user_passwd, tenant_id=None):
1585 '''Adds a new user to openstack VIM'''
1586 '''Returns the user identifier'''
1587 self.logger.debug("osconnector: Adding a new user to VIM")
1588 try:
1589 self._reload_connection()
1590 user=self.keystone.users.create(user_name, user_passwd, tenant_id=tenant_id)
1591 #self.keystone.tenants.add_user(self.k_creds["username"], #role)
1592 return user.id
1593 except ksExceptions.ConnectionError as e:
1594 error_value=-vimconn.HTTP_Bad_Request
1595 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1596 except ksExceptions.ClientException as e: #TODO remove
tierno7edb6752016-03-21 17:37:52 +01001597 error_value=-vimconn.HTTP_Bad_Request
1598 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1599 #TODO insert exception vimconn.HTTP_Unauthorized
1600 #if reaching here is because an exception
1601 if self.debug:
tiernoae4a8d12016-07-08 12:30:39 +02001602 self.logger.debug("new_user " + error_text)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001603 return error_value, error_text
tiernoae4a8d12016-07-08 12:30:39 +02001604
1605 def delete_user(self, user_id):
1606 '''Delete a user from openstack VIM'''
1607 '''Returns the user identifier'''
1608 if self.debug:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001609 print("osconnector: Deleting a user from VIM")
tiernoae4a8d12016-07-08 12:30:39 +02001610 try:
1611 self._reload_connection()
1612 self.keystone.users.delete(user_id)
1613 return 1, user_id
1614 except ksExceptions.ConnectionError as e:
1615 error_value=-vimconn.HTTP_Bad_Request
1616 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1617 except ksExceptions.NotFound as e:
1618 error_value=-vimconn.HTTP_Not_Found
1619 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1620 except ksExceptions.ClientException as e: #TODO remove
1621 error_value=-vimconn.HTTP_Bad_Request
1622 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1623 #TODO insert exception vimconn.HTTP_Unauthorized
1624 #if reaching here is because an exception
1625 if self.debug:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001626 print("delete_tenant " + error_text)
tiernoae4a8d12016-07-08 12:30:39 +02001627 return error_value, error_text
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001628
tierno7edb6752016-03-21 17:37:52 +01001629 def get_hosts_info(self):
1630 '''Get the information of deployed hosts
1631 Returns the hosts content'''
1632 if self.debug:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001633 print("osconnector: Getting Host info from VIM")
tierno7edb6752016-03-21 17:37:52 +01001634 try:
1635 h_list=[]
1636 self._reload_connection()
1637 hypervisors = self.nova.hypervisors.list()
1638 for hype in hypervisors:
1639 h_list.append( hype.to_dict() )
1640 return 1, {"hosts":h_list}
1641 except nvExceptions.NotFound as e:
1642 error_value=-vimconn.HTTP_Not_Found
1643 error_text= (str(e) if len(e.args)==0 else str(e.args[0]))
1644 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
1645 error_value=-vimconn.HTTP_Bad_Request
1646 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1647 #TODO insert exception vimconn.HTTP_Unauthorized
1648 #if reaching here is because an exception
1649 if self.debug:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001650 print("get_hosts_info " + error_text)
1651 return error_value, error_text
tierno7edb6752016-03-21 17:37:52 +01001652
1653 def get_hosts(self, vim_tenant):
1654 '''Get the hosts and deployed instances
1655 Returns the hosts content'''
1656 r, hype_dict = self.get_hosts_info()
1657 if r<0:
1658 return r, hype_dict
1659 hypervisors = hype_dict["hosts"]
1660 try:
1661 servers = self.nova.servers.list()
1662 for hype in hypervisors:
1663 for server in servers:
1664 if server.to_dict()['OS-EXT-SRV-ATTR:hypervisor_hostname']==hype['hypervisor_hostname']:
1665 if 'vm' in hype:
1666 hype['vm'].append(server.id)
1667 else:
1668 hype['vm'] = [server.id]
1669 return 1, hype_dict
1670 except nvExceptions.NotFound as e:
1671 error_value=-vimconn.HTTP_Not_Found
1672 error_text= (str(e) if len(e.args)==0 else str(e.args[0]))
1673 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
1674 error_value=-vimconn.HTTP_Bad_Request
1675 error_text= type(e).__name__ + ": "+ (str(e) if len(e.args)==0 else str(e.args[0]))
1676 #TODO insert exception vimconn.HTTP_Unauthorized
1677 #if reaching here is because an exception
1678 if self.debug:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001679 print("get_hosts " + error_text)
1680 return error_value, error_text
tierno7edb6752016-03-21 17:37:52 +01001681
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001682 def new_classification(self, name, ctype, definition):
1683 self.logger.debug(
1684 'Adding a new (Traffic) Classification to VIM, named %s', name)
1685 try:
1686 new_class = None
1687 self._reload_connection()
1688 if ctype not in supportedClassificationTypes:
1689 raise vimconn.vimconnNotSupportedException(
1690 'OpenStack VIM connector doesn\'t support provided '
1691 'Classification Type {}, supported ones are: '
1692 '{}'.format(ctype, supportedClassificationTypes))
1693 if not self._validate_classification(ctype, definition):
1694 raise vimconn.vimconnException(
1695 'Incorrect Classification definition '
1696 'for the type specified.')
1697 classification_dict = definition
1698 classification_dict['name'] = name
tierno7edb6752016-03-21 17:37:52 +01001699
Igor D.Ccaadc442017-11-06 12:48:48 +00001700 new_class = self.neutron.create_sfc_flow_classifier(
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001701 {'flow_classifier': classification_dict})
1702 return new_class['flow_classifier']['id']
1703 except (neExceptions.ConnectionFailed, ksExceptions.ClientException,
1704 neExceptions.NeutronException, ConnectionError) as e:
1705 self.logger.error(
1706 'Creation of Classification failed.')
1707 self._format_exception(e)
1708
1709 def get_classification(self, class_id):
1710 self.logger.debug(" Getting Classification %s from VIM", class_id)
1711 filter_dict = {"id": class_id}
1712 class_list = self.get_classification_list(filter_dict)
1713 if len(class_list) == 0:
1714 raise vimconn.vimconnNotFoundException(
1715 "Classification '{}' not found".format(class_id))
1716 elif len(class_list) > 1:
1717 raise vimconn.vimconnConflictException(
1718 "Found more than one Classification with this criteria")
1719 classification = class_list[0]
1720 return classification
1721
1722 def get_classification_list(self, filter_dict={}):
1723 self.logger.debug("Getting Classifications from VIM filter: '%s'",
1724 str(filter_dict))
1725 try:
tierno69b590e2018-03-13 18:52:23 +01001726 filter_dict_os = filter_dict.copy()
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001727 self._reload_connection()
tierno69b590e2018-03-13 18:52:23 +01001728 if self.api_version3 and "tenant_id" in filter_dict_os:
1729 filter_dict_os['project_id'] = filter_dict_os.pop('tenant_id')
Igor D.Ccaadc442017-11-06 12:48:48 +00001730 classification_dict = self.neutron.list_sfc_flow_classifiers(
tierno69b590e2018-03-13 18:52:23 +01001731 **filter_dict_os)
1732 classification_list = classification_dict["flow_classifiers"]
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001733 self.__classification_os2mano(classification_list)
1734 return classification_list
1735 except (neExceptions.ConnectionFailed, ksExceptions.ClientException,
1736 neExceptions.NeutronException, ConnectionError) as e:
1737 self._format_exception(e)
1738
1739 def delete_classification(self, class_id):
1740 self.logger.debug("Deleting Classification '%s' from VIM", class_id)
1741 try:
1742 self._reload_connection()
Igor D.Ccaadc442017-11-06 12:48:48 +00001743 self.neutron.delete_sfc_flow_classifier(class_id)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001744 return class_id
1745 except (neExceptions.ConnectionFailed, neExceptions.NeutronException,
1746 ksExceptions.ClientException, neExceptions.NeutronException,
1747 ConnectionError) as e:
1748 self._format_exception(e)
1749
1750 def new_sfi(self, name, ingress_ports, egress_ports, sfc_encap=True):
1751 self.logger.debug(
1752 "Adding a new Service Function Instance to VIM, named '%s'", name)
1753 try:
1754 new_sfi = None
1755 self._reload_connection()
1756 correlation = None
1757 if sfc_encap:
Igor D.Ccaadc442017-11-06 12:48:48 +00001758 correlation = 'nsh'
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001759 if len(ingress_ports) != 1:
1760 raise vimconn.vimconnNotSupportedException(
1761 "OpenStack VIM connector can only have "
1762 "1 ingress port per SFI")
1763 if len(egress_ports) != 1:
1764 raise vimconn.vimconnNotSupportedException(
1765 "OpenStack VIM connector can only have "
1766 "1 egress port per SFI")
1767 sfi_dict = {'name': name,
1768 'ingress': ingress_ports[0],
1769 'egress': egress_ports[0],
1770 'service_function_parameters': {
1771 'correlation': correlation}}
Igor D.Ccaadc442017-11-06 12:48:48 +00001772 new_sfi = self.neutron.create_sfc_port_pair({'port_pair': sfi_dict})
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001773 return new_sfi['port_pair']['id']
1774 except (neExceptions.ConnectionFailed, ksExceptions.ClientException,
1775 neExceptions.NeutronException, ConnectionError) as e:
1776 if new_sfi:
1777 try:
Igor D.Ccaadc442017-11-06 12:48:48 +00001778 self.neutron.delete_sfc_port_pair(
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001779 new_sfi['port_pair']['id'])
1780 except Exception:
1781 self.logger.error(
1782 'Creation of Service Function Instance failed, with '
1783 'subsequent deletion failure as well.')
1784 self._format_exception(e)
1785
1786 def get_sfi(self, sfi_id):
1787 self.logger.debug(
1788 'Getting Service Function Instance %s from VIM', sfi_id)
1789 filter_dict = {"id": sfi_id}
1790 sfi_list = self.get_sfi_list(filter_dict)
1791 if len(sfi_list) == 0:
1792 raise vimconn.vimconnNotFoundException(
1793 "Service Function Instance '{}' not found".format(sfi_id))
1794 elif len(sfi_list) > 1:
1795 raise vimconn.vimconnConflictException(
1796 'Found more than one Service Function Instance '
1797 'with this criteria')
1798 sfi = sfi_list[0]
1799 return sfi
1800
1801 def get_sfi_list(self, filter_dict={}):
1802 self.logger.debug("Getting Service Function Instances from "
1803 "VIM filter: '%s'", str(filter_dict))
1804 try:
1805 self._reload_connection()
tierno69b590e2018-03-13 18:52:23 +01001806 filter_dict_os = filter_dict.copy()
1807 if self.api_version3 and "tenant_id" in filter_dict_os:
1808 filter_dict_os['project_id'] = filter_dict_os.pop('tenant_id')
1809 sfi_dict = self.neutron.list_sfc_port_pairs(**filter_dict_os)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001810 sfi_list = sfi_dict["port_pairs"]
1811 self.__sfi_os2mano(sfi_list)
1812 return sfi_list
1813 except (neExceptions.ConnectionFailed, ksExceptions.ClientException,
1814 neExceptions.NeutronException, ConnectionError) as e:
1815 self._format_exception(e)
1816
1817 def delete_sfi(self, sfi_id):
1818 self.logger.debug("Deleting Service Function Instance '%s' "
1819 "from VIM", sfi_id)
1820 try:
1821 self._reload_connection()
Igor D.Ccaadc442017-11-06 12:48:48 +00001822 self.neutron.delete_sfc_port_pair(sfi_id)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001823 return sfi_id
1824 except (neExceptions.ConnectionFailed, neExceptions.NeutronException,
1825 ksExceptions.ClientException, neExceptions.NeutronException,
1826 ConnectionError) as e:
1827 self._format_exception(e)
1828
1829 def new_sf(self, name, sfis, sfc_encap=True):
1830 self.logger.debug("Adding a new Service Function to VIM, "
1831 "named '%s'", name)
1832 try:
1833 new_sf = None
1834 self._reload_connection()
1835 correlation = None
1836 if sfc_encap:
Igor D.Ccaadc442017-11-06 12:48:48 +00001837 correlation = 'nsh'
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001838 for instance in sfis:
1839 sfi = self.get_sfi(instance)
Igor D.Ccaadc442017-11-06 12:48:48 +00001840 if sfi.get('sfc_encap') != sfc_encap:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001841 raise vimconn.vimconnNotSupportedException(
1842 "OpenStack VIM connector requires all SFIs of the "
1843 "same SF to share the same SFC Encapsulation")
1844 sf_dict = {'name': name,
1845 'port_pairs': sfis}
Igor D.Ccaadc442017-11-06 12:48:48 +00001846 new_sf = self.neutron.create_sfc_port_pair_group({
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001847 'port_pair_group': sf_dict})
1848 return new_sf['port_pair_group']['id']
1849 except (neExceptions.ConnectionFailed, ksExceptions.ClientException,
1850 neExceptions.NeutronException, ConnectionError) as e:
1851 if new_sf:
1852 try:
Igor D.Ccaadc442017-11-06 12:48:48 +00001853 self.neutron.delete_sfc_port_pair_group(
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001854 new_sf['port_pair_group']['id'])
1855 except Exception:
1856 self.logger.error(
1857 'Creation of Service Function failed, with '
1858 'subsequent deletion failure as well.')
1859 self._format_exception(e)
1860
1861 def get_sf(self, sf_id):
1862 self.logger.debug("Getting Service Function %s from VIM", sf_id)
1863 filter_dict = {"id": sf_id}
1864 sf_list = self.get_sf_list(filter_dict)
1865 if len(sf_list) == 0:
1866 raise vimconn.vimconnNotFoundException(
1867 "Service Function '{}' not found".format(sf_id))
1868 elif len(sf_list) > 1:
1869 raise vimconn.vimconnConflictException(
1870 "Found more than one Service Function with this criteria")
1871 sf = sf_list[0]
1872 return sf
1873
1874 def get_sf_list(self, filter_dict={}):
1875 self.logger.debug("Getting Service Function from VIM filter: '%s'",
1876 str(filter_dict))
1877 try:
1878 self._reload_connection()
tierno69b590e2018-03-13 18:52:23 +01001879 filter_dict_os = filter_dict.copy()
1880 if self.api_version3 and "tenant_id" in filter_dict_os:
1881 filter_dict_os['project_id'] = filter_dict_os.pop('tenant_id')
1882 sf_dict = self.neutron.list_sfc_port_pair_groups(**filter_dict_os)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001883 sf_list = sf_dict["port_pair_groups"]
1884 self.__sf_os2mano(sf_list)
1885 return sf_list
1886 except (neExceptions.ConnectionFailed, ksExceptions.ClientException,
1887 neExceptions.NeutronException, ConnectionError) as e:
1888 self._format_exception(e)
1889
1890 def delete_sf(self, sf_id):
1891 self.logger.debug("Deleting Service Function '%s' from VIM", sf_id)
1892 try:
1893 self._reload_connection()
Igor D.Ccaadc442017-11-06 12:48:48 +00001894 self.neutron.delete_sfc_port_pair_group(sf_id)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001895 return sf_id
1896 except (neExceptions.ConnectionFailed, neExceptions.NeutronException,
1897 ksExceptions.ClientException, neExceptions.NeutronException,
1898 ConnectionError) as e:
1899 self._format_exception(e)
1900
1901 def new_sfp(self, name, classifications, sfs, sfc_encap=True, spi=None):
1902 self.logger.debug("Adding a new Service Function Path to VIM, "
1903 "named '%s'", name)
1904 try:
1905 new_sfp = None
1906 self._reload_connection()
Igor D.Ccaadc442017-11-06 12:48:48 +00001907 # In networking-sfc the MPLS encapsulation is legacy
1908 # should be used when no full SFC Encapsulation is intended
1909 sfc_encap = 'mpls'
1910 if sfc_encap:
1911 correlation = 'nsh'
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001912 sfp_dict = {'name': name,
1913 'flow_classifiers': classifications,
1914 'port_pair_groups': sfs,
1915 'chain_parameters': {'correlation': correlation}}
1916 if spi:
1917 sfp_dict['chain_id'] = spi
Igor D.Ccaadc442017-11-06 12:48:48 +00001918 new_sfp = self.neutron.create_sfc_port_chain({'port_chain': sfp_dict})
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001919 return new_sfp["port_chain"]["id"]
1920 except (neExceptions.ConnectionFailed, ksExceptions.ClientException,
1921 neExceptions.NeutronException, ConnectionError) as e:
1922 if new_sfp:
1923 try:
Igor D.Ccaadc442017-11-06 12:48:48 +00001924 self.neutron.delete_sfc_port_chain(new_sfp['port_chain']['id'])
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001925 except Exception:
1926 self.logger.error(
1927 'Creation of Service Function Path failed, with '
1928 'subsequent deletion failure as well.')
1929 self._format_exception(e)
1930
1931 def get_sfp(self, sfp_id):
1932 self.logger.debug(" Getting Service Function Path %s from VIM", sfp_id)
1933 filter_dict = {"id": sfp_id}
1934 sfp_list = self.get_sfp_list(filter_dict)
1935 if len(sfp_list) == 0:
1936 raise vimconn.vimconnNotFoundException(
1937 "Service Function Path '{}' not found".format(sfp_id))
1938 elif len(sfp_list) > 1:
1939 raise vimconn.vimconnConflictException(
1940 "Found more than one Service Function Path with this criteria")
1941 sfp = sfp_list[0]
1942 return sfp
1943
1944 def get_sfp_list(self, filter_dict={}):
1945 self.logger.debug("Getting Service Function Paths from VIM filter: "
1946 "'%s'", str(filter_dict))
1947 try:
1948 self._reload_connection()
tierno69b590e2018-03-13 18:52:23 +01001949 filter_dict_os = filter_dict.copy()
1950 if self.api_version3 and "tenant_id" in filter_dict_os:
1951 filter_dict_os['project_id'] = filter_dict_os.pop('tenant_id')
1952 sfp_dict = self.neutron.list_sfc_port_chains(**filter_dict_os)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001953 sfp_list = sfp_dict["port_chains"]
1954 self.__sfp_os2mano(sfp_list)
1955 return sfp_list
1956 except (neExceptions.ConnectionFailed, ksExceptions.ClientException,
1957 neExceptions.NeutronException, ConnectionError) as e:
1958 self._format_exception(e)
1959
1960 def delete_sfp(self, sfp_id):
1961 self.logger.debug(
1962 "Deleting Service Function Path '%s' from VIM", sfp_id)
1963 try:
1964 self._reload_connection()
Igor D.Ccaadc442017-11-06 12:48:48 +00001965 self.neutron.delete_sfc_port_chain(sfp_id)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001966 return sfp_id
1967 except (neExceptions.ConnectionFailed, neExceptions.NeutronException,
1968 ksExceptions.ClientException, neExceptions.NeutronException,
1969 ConnectionError) as e:
1970 self._format_exception(e)