blob: acc5ba8ab00e24229f5bf3b0abd2a4eeb99d3cb2 [file] [log] [blame]
tierno7edb6752016-03-21 17:37:52 +01001# -*- coding: utf-8 -*-
2
3##
tierno92021022018-09-12 16:29:23 +02004# Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U.
tierno7edb6752016-03-21 17:37:52 +01005# 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.
tierno7edb6752016-03-21 17:37:52 +010019##
20
tierno1ec592d2020-06-16 15:29:47 +000021"""
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +000022osconnector implements all the methods to interact with openstack using the python-neutronclient.
23
24For the VNF forwarding graph, The OpenStack VIM connector calls the
25networking-sfc Neutron extension methods, whose resources are mapped
26to the VIM connector's SFC resources as follows:
27- Classification (OSM) -> Flow Classifier (Neutron)
28- Service Function Instance (OSM) -> Port Pair (Neutron)
29- Service Function (OSM) -> Port Pair Group (Neutron)
30- Service Function Path (OSM) -> Port Chain (Neutron)
tierno1ec592d2020-06-16 15:29:47 +000031"""
tierno7edb6752016-03-21 17:37:52 +010032
tierno72774862020-05-04 11:44:15 +000033from osm_ro_plugin import vimconn
tierno69b590e2018-03-13 18:52:23 +010034# import json
tiernoae4a8d12016-07-08 12:30:39 +020035import logging
garciadeblas9f8456e2016-09-05 05:02:59 +020036import netaddr
montesmoreno0c8def02016-12-22 12:16:23 +000037import time
tierno36c0b172017-01-12 18:32:28 +010038import yaml
garciadeblas2299e3b2017-01-26 14:35:55 +000039import random
kate721d79b2017-06-24 04:21:38 -070040import re
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +000041import copy
Anderson Bravalheri0446cd52018-08-17 15:26:19 +010042from pprint import pformat
tierno7edb6752016-03-21 17:37:52 +010043
tiernob5cef372017-06-19 15:52:22 +020044from novaclient import client as nClient, exceptions as nvExceptions
45from keystoneauth1.identity import v2, v3
46from keystoneauth1 import session
tierno7edb6752016-03-21 17:37:52 +010047import keystoneclient.exceptions as ksExceptions
tiernof716aea2017-06-21 18:01:40 +020048import keystoneclient.v3.client as ksClient_v3
49import keystoneclient.v2_0.client as ksClient_v2
tiernob5cef372017-06-19 15:52:22 +020050from glanceclient import client as glClient
tierno7edb6752016-03-21 17:37:52 +010051import glanceclient.exc as gl1Exceptions
tierno1ec592d2020-06-16 15:29:47 +000052from cinderclient import client as cClient
53from http.client import HTTPException # TODO py3 check that this base exception matches python2 httplib.HTTPException
tiernob5cef372017-06-19 15:52:22 +020054from neutronclient.neutron import client as neClient
tierno7edb6752016-03-21 17:37:52 +010055from neutronclient.common import exceptions as neExceptions
56from requests.exceptions import ConnectionError
57
tierno1ec592d2020-06-16 15:29:47 +000058__author__ = "Alfonso Tierno, Gerardo Garcia, Pablo Montes, xFlow Research, Igor D.C., Eduardo Sousa"
59__date__ = "$22-sep-2017 23:59:59$"
tierno40e1bce2017-08-09 09:12:04 +020060
61"""contain the openstack virtual machine status to openmano status"""
tierno1ec592d2020-06-16 15:29:47 +000062vmStatus2manoFormat = {'ACTIVE': 'ACTIVE',
63 'PAUSED': 'PAUSED',
64 'SUSPENDED': 'SUSPENDED',
65 'SHUTOFF': 'INACTIVE',
66 'BUILD': 'BUILD',
67 'ERROR': 'ERROR',
68 'DELETED': 'DELETED'
69 }
70netStatus2manoFormat = {'ACTIVE': 'ACTIVE',
71 'PAUSED': 'PAUSED',
72 'INACTIVE': 'INACTIVE',
73 'BUILD': 'BUILD',
74 'ERROR': 'ERROR',
75 'DELETED': 'DELETED'
76 }
tierno7edb6752016-03-21 17:37:52 +010077
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +000078supportedClassificationTypes = ['legacy_flow_classifier']
79
tierno1ec592d2020-06-16 15:29:47 +000080# global var to have a timeout creating and deleting volumes
garciadeblas64b39c52020-05-21 08:07:25 +000081volume_timeout = 1800
82server_timeout = 1800
montesmoreno0c8def02016-12-22 12:16:23 +000083
Anderson Bravalheri0446cd52018-08-17 15:26:19 +010084
85class SafeDumper(yaml.SafeDumper):
86 def represent_data(self, data):
87 # Openstack APIs use custom subclasses of dict and YAML safe dumper
88 # is designed to not handle that (reference issue 142 of pyyaml)
89 if isinstance(data, dict) and data.__class__ != dict:
90 # A simple solution is to convert those items back to dicts
91 data = dict(data.items())
92
93 return super(SafeDumper, self).represent_data(data)
94
95
tierno72774862020-05-04 11:44:15 +000096class vimconnector(vimconn.VimConnector):
tiernob3d36742017-03-03 23:51:05 +010097 def __init__(self, uuid, name, tenant_id, tenant_name, url, url_admin=None, user=None, passwd=None,
98 log_level=None, config={}, persistent_info={}):
tierno1ec592d2020-06-16 15:29:47 +000099 """using common constructor parameters. In this case
tierno7edb6752016-03-21 17:37:52 +0100100 'url' is the keystone authorization url,
101 'url_admin' is not use
tierno1ec592d2020-06-16 15:29:47 +0000102 """
tiernof716aea2017-06-21 18:01:40 +0200103 api_version = config.get('APIversion')
104 if api_version and api_version not in ('v3.3', 'v2.0', '2', '3'):
tierno72774862020-05-04 11:44:15 +0000105 raise vimconn.VimConnException("Invalid value '{}' for config:APIversion. "
tiernof716aea2017-06-21 18:01:40 +0200106 "Allowed values are 'v3.3', 'v2.0', '2' or '3'".format(api_version))
kate721d79b2017-06-24 04:21:38 -0700107 vim_type = config.get('vim_type')
108 if vim_type and vim_type not in ('vio', 'VIO'):
tierno72774862020-05-04 11:44:15 +0000109 raise vimconn.VimConnException("Invalid value '{}' for config:vim_type."
tierno1ec592d2020-06-16 15:29:47 +0000110 "Allowed values are 'vio' or 'VIO'".format(vim_type))
kate721d79b2017-06-24 04:21:38 -0700111
112 if config.get('dataplane_net_vlan_range') is not None:
tierno1ec592d2020-06-16 15:29:47 +0000113 # validate vlan ranges provided by user
garciadeblasebd66722019-01-31 16:01:31 +0000114 self._validate_vlan_ranges(config.get('dataplane_net_vlan_range'), 'dataplane_net_vlan_range')
115
116 if config.get('multisegment_vlan_range') is not None:
tierno1ec592d2020-06-16 15:29:47 +0000117 # validate vlan ranges provided by user
garciadeblasebd66722019-01-31 16:01:31 +0000118 self._validate_vlan_ranges(config.get('multisegment_vlan_range'), 'multisegment_vlan_range')
kate721d79b2017-06-24 04:21:38 -0700119
tierno72774862020-05-04 11:44:15 +0000120 vimconn.VimConnector.__init__(self, uuid, name, tenant_id, tenant_name, url, url_admin, user, passwd, log_level,
tiernob5cef372017-06-19 15:52:22 +0200121 config)
tiernob3d36742017-03-03 23:51:05 +0100122
tierno4d1ce222018-04-06 10:41:06 +0200123 if self.config.get("insecure") and self.config.get("ca_cert"):
tierno72774862020-05-04 11:44:15 +0000124 raise vimconn.VimConnException("options insecure and ca_cert are mutually exclusive")
tierno4d1ce222018-04-06 10:41:06 +0200125 self.verify = True
126 if self.config.get("insecure"):
127 self.verify = False
128 if self.config.get("ca_cert"):
129 self.verify = self.config.get("ca_cert")
tierno4d1ce222018-04-06 10:41:06 +0200130
tierno7edb6752016-03-21 17:37:52 +0100131 if not url:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000132 raise TypeError('url param can not be NoneType')
tiernob5cef372017-06-19 15:52:22 +0200133 self.persistent_info = persistent_info
mirabal29356312017-07-27 12:21:22 +0200134 self.availability_zone = persistent_info.get('availability_zone', None)
tiernob5cef372017-06-19 15:52:22 +0200135 self.session = persistent_info.get('session', {'reload_client': True})
tiernoa05b65a2019-02-01 12:30:27 +0000136 self.my_tenant_id = self.session.get('my_tenant_id')
tiernob5cef372017-06-19 15:52:22 +0200137 self.nova = self.session.get('nova')
138 self.neutron = self.session.get('neutron')
139 self.cinder = self.session.get('cinder')
140 self.glance = self.session.get('glance')
tierno1beea862018-07-11 15:47:37 +0200141 # self.glancev1 = self.session.get('glancev1')
tiernof716aea2017-06-21 18:01:40 +0200142 self.keystone = self.session.get('keystone')
143 self.api_version3 = self.session.get('api_version3')
kate721d79b2017-06-24 04:21:38 -0700144 self.vim_type = self.config.get("vim_type")
145 if self.vim_type:
146 self.vim_type = self.vim_type.upper()
147 if self.config.get("use_internal_endpoint"):
148 self.endpoint_type = "internalURL"
149 else:
150 self.endpoint_type = None
montesmoreno0c8def02016-12-22 12:16:23 +0000151
garciadeblasa0a356e2019-12-18 09:32:09 +0100152 logging.getLogger('urllib3').setLevel(logging.WARNING)
153 logging.getLogger('keystoneauth').setLevel(logging.WARNING)
154 logging.getLogger('novaclient').setLevel(logging.WARNING)
tierno73ad9e42016-09-12 18:11:11 +0200155 self.logger = logging.getLogger('openmano.vim.openstack')
kate721d79b2017-06-24 04:21:38 -0700156
tiernoa05b65a2019-02-01 12:30:27 +0000157 # allow security_groups to be a list or a single string
158 if isinstance(self.config.get('security_groups'), str):
159 self.config['security_groups'] = [self.config['security_groups']]
160 self.security_groups_id = None
161
tierno1ec592d2020-06-16 15:29:47 +0000162 # ###### VIO Specific Changes #########
kate721d79b2017-06-24 04:21:38 -0700163 if self.vim_type == "VIO":
164 self.logger = logging.getLogger('openmano.vim.vio')
165
tiernofe789902016-09-29 14:20:44 +0000166 if log_level:
tierno1ec592d2020-06-16 15:29:47 +0000167 self.logger.setLevel(getattr(logging, log_level))
tiernof716aea2017-06-21 18:01:40 +0200168
169 def __getitem__(self, index):
170 """Get individuals parameters.
171 Throw KeyError"""
172 if index == 'project_domain_id':
173 return self.config.get("project_domain_id")
174 elif index == 'user_domain_id':
175 return self.config.get("user_domain_id")
176 else:
tierno72774862020-05-04 11:44:15 +0000177 return vimconn.VimConnector.__getitem__(self, index)
tiernof716aea2017-06-21 18:01:40 +0200178
179 def __setitem__(self, index, value):
180 """Set individuals parameters and it is marked as dirty so to force connection reload.
181 Throw KeyError"""
182 if index == 'project_domain_id':
183 self.config["project_domain_id"] = value
184 elif index == 'user_domain_id':
tierno1ec592d2020-06-16 15:29:47 +0000185 self.config["user_domain_id"] = value
tiernof716aea2017-06-21 18:01:40 +0200186 else:
tierno72774862020-05-04 11:44:15 +0000187 vimconn.VimConnector.__setitem__(self, index, value)
tiernob5cef372017-06-19 15:52:22 +0200188 self.session['reload_client'] = True
tiernof716aea2017-06-21 18:01:40 +0200189
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100190 def serialize(self, value):
191 """Serialization of python basic types.
192
193 In the case value is not serializable a message will be logged and a
194 simple representation of the data that cannot be converted back to
195 python is returned.
196 """
tierno7d782ef2019-10-04 12:56:31 +0000197 if isinstance(value, str):
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100198 return value
199
200 try:
201 return yaml.dump(value, Dumper=SafeDumper,
202 default_flow_style=True, width=256)
203 except yaml.representer.RepresenterError:
tierno1ec592d2020-06-16 15:29:47 +0000204 self.logger.debug('The following entity cannot be serialized in YAML:\n\n%s\n\n', pformat(value),
205 exc_info=True)
206 return str(value)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100207
tierno7edb6752016-03-21 17:37:52 +0100208 def _reload_connection(self):
tierno1ec592d2020-06-16 15:29:47 +0000209 """Called before any operation, it check if credentials has changed
tierno7edb6752016-03-21 17:37:52 +0100210 Throw keystoneclient.apiclient.exceptions.AuthorizationFailure
tierno1ec592d2020-06-16 15:29:47 +0000211 """
212 # 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 +0200213 if self.session['reload_client']:
tiernof716aea2017-06-21 18:01:40 +0200214 if self.config.get('APIversion'):
215 self.api_version3 = self.config['APIversion'] == 'v3.3' or self.config['APIversion'] == '3'
216 else: # get from ending auth_url that end with v3 or with v2.0
tierno1ec592d2020-06-16 15:29:47 +0000217 self.api_version3 = self.url.endswith("/v3") or self.url.endswith("/v3/")
tiernof716aea2017-06-21 18:01:40 +0200218 self.session['api_version3'] = self.api_version3
219 if self.api_version3:
tierno3cb8dc32017-10-24 18:13:19 +0200220 if self.config.get('project_domain_id') or self.config.get('project_domain_name'):
221 project_domain_id_default = None
222 else:
223 project_domain_id_default = 'default'
224 if self.config.get('user_domain_id') or self.config.get('user_domain_name'):
225 user_domain_id_default = None
226 else:
227 user_domain_id_default = 'default'
tiernof716aea2017-06-21 18:01:40 +0200228 auth = v3.Password(auth_url=self.url,
tiernob5cef372017-06-19 15:52:22 +0200229 username=self.user,
230 password=self.passwd,
231 project_name=self.tenant_name,
232 project_id=self.tenant_id,
tierno3cb8dc32017-10-24 18:13:19 +0200233 project_domain_id=self.config.get('project_domain_id', project_domain_id_default),
234 user_domain_id=self.config.get('user_domain_id', user_domain_id_default),
235 project_domain_name=self.config.get('project_domain_name'),
236 user_domain_name=self.config.get('user_domain_name'))
ahmadsa95baa272016-11-30 09:14:11 +0500237 else:
tiernof716aea2017-06-21 18:01:40 +0200238 auth = v2.Password(auth_url=self.url,
tiernob5cef372017-06-19 15:52:22 +0200239 username=self.user,
240 password=self.passwd,
241 tenant_name=self.tenant_name,
242 tenant_id=self.tenant_id)
tierno4d1ce222018-04-06 10:41:06 +0200243 sess = session.Session(auth=auth, verify=self.verify)
tierno1ec592d2020-06-16 15:29:47 +0000244 # addedd region_name to keystone, nova, neutron and cinder to support distributed cloud for Wind River
245 # Titanium cloud and StarlingX
fatollahy40c6a3f2019-02-19 12:53:40 +0000246 region_name = self.config.get('region_name')
tiernof716aea2017-06-21 18:01:40 +0200247 if self.api_version3:
tierno1ec592d2020-06-16 15:29:47 +0000248 self.keystone = ksClient_v3.Client(session=sess, endpoint_type=self.endpoint_type,
249 region_name=region_name)
tiernof716aea2017-06-21 18:01:40 +0200250 else:
kate721d79b2017-06-24 04:21:38 -0700251 self.keystone = ksClient_v2.Client(session=sess, endpoint_type=self.endpoint_type)
tiernof716aea2017-06-21 18:01:40 +0200252 self.session['keystone'] = self.keystone
montesmoreno9317d302017-08-16 12:48:23 +0200253 # In order to enable microversion functionality an explicit microversion must be specified in 'config'.
254 # This implementation approach is due to the warning message in
255 # https://developer.openstack.org/api-guide/compute/microversions.html
256 # where it is stated that microversion backwards compatibility is not guaranteed and clients should
257 # always require an specific microversion.
258 # To be able to use 'device role tagging' functionality define 'microversion: 2.32' in datacenter config
259 version = self.config.get("microversion")
260 if not version:
261 version = "2.1"
tierno1ec592d2020-06-16 15:29:47 +0000262 # addedd region_name to keystone, nova, neutron and cinder to support distributed cloud for Wind River
263 # Titanium cloud and StarlingX
264 self.nova = self.session['nova'] = nClient.Client(str(version), session=sess,
265 endpoint_type=self.endpoint_type, region_name=region_name)
266 self.neutron = self.session['neutron'] = neClient.Client('2.0', session=sess,
267 endpoint_type=self.endpoint_type,
268 region_name=region_name)
269 self.cinder = self.session['cinder'] = cClient.Client(2, session=sess, endpoint_type=self.endpoint_type,
270 region_name=region_name)
tiernoa05b65a2019-02-01 12:30:27 +0000271 try:
272 self.my_tenant_id = self.session['my_tenant_id'] = sess.get_project_id()
tierno1ec592d2020-06-16 15:29:47 +0000273 except Exception:
tiernoa05b65a2019-02-01 12:30:27 +0000274 self.logger.error("Cannot get project_id from session", exc_info=True)
kate721d79b2017-06-24 04:21:38 -0700275 if self.endpoint_type == "internalURL":
276 glance_service_id = self.keystone.services.list(name="glance")[0].id
277 glance_endpoint = self.keystone.endpoints.list(glance_service_id, interface="internal")[0].url
278 else:
279 glance_endpoint = None
280 self.glance = self.session['glance'] = glClient.Client(2, session=sess, endpoint=glance_endpoint)
tiernoa05b65a2019-02-01 12:30:27 +0000281 # using version 1 of glance client in new_image()
tierno1beea862018-07-11 15:47:37 +0200282 # self.glancev1 = self.session['glancev1'] = glClient.Client('1', session=sess,
283 # endpoint=glance_endpoint)
tiernob5cef372017-06-19 15:52:22 +0200284 self.session['reload_client'] = False
285 self.persistent_info['session'] = self.session
mirabal29356312017-07-27 12:21:22 +0200286 # add availablity zone info inside self.persistent_info
287 self._set_availablity_zones()
288 self.persistent_info['availability_zone'] = self.availability_zone
tiernoa05b65a2019-02-01 12:30:27 +0000289 self.security_groups_id = None # force to get again security_groups_ids next time they are needed
ahmadsa95baa272016-11-30 09:14:11 +0500290
tierno7edb6752016-03-21 17:37:52 +0100291 def __net_os2mano(self, net_list_dict):
tierno1ec592d2020-06-16 15:29:47 +0000292 """Transform the net openstack format to mano format
293 net_list_dict can be a list of dict or a single dict"""
tierno7edb6752016-03-21 17:37:52 +0100294 if type(net_list_dict) is dict:
tierno1ec592d2020-06-16 15:29:47 +0000295 net_list_ = (net_list_dict,)
tierno7edb6752016-03-21 17:37:52 +0100296 elif type(net_list_dict) is list:
tierno1ec592d2020-06-16 15:29:47 +0000297 net_list_ = net_list_dict
tierno7edb6752016-03-21 17:37:52 +0100298 else:
299 raise TypeError("param net_list_dict must be a list or a dictionary")
300 for net in net_list_:
301 if net.get('provider:network_type') == "vlan":
tierno1ec592d2020-06-16 15:29:47 +0000302 net['type'] = 'data'
tierno7edb6752016-03-21 17:37:52 +0100303 else:
tierno1ec592d2020-06-16 15:29:47 +0000304 net['type'] = 'bridge'
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +0200305
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000306 def __classification_os2mano(self, class_list_dict):
307 """Transform the openstack format (Flow Classifier) to mano format
308 (Classification) class_list_dict can be a list of dict or a single dict
309 """
310 if isinstance(class_list_dict, dict):
311 class_list_ = [class_list_dict]
312 elif isinstance(class_list_dict, list):
313 class_list_ = class_list_dict
314 else:
tierno1ec592d2020-06-16 15:29:47 +0000315 raise TypeError("param class_list_dict must be a list or a dictionary")
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000316 for classification in class_list_:
317 id = classification.pop('id')
318 name = classification.pop('name')
319 description = classification.pop('description')
320 project_id = classification.pop('project_id')
321 tenant_id = classification.pop('tenant_id')
322 original_classification = copy.deepcopy(classification)
323 classification.clear()
324 classification['ctype'] = 'legacy_flow_classifier'
325 classification['definition'] = original_classification
326 classification['id'] = id
327 classification['name'] = name
328 classification['description'] = description
329 classification['project_id'] = project_id
330 classification['tenant_id'] = tenant_id
331
332 def __sfi_os2mano(self, sfi_list_dict):
333 """Transform the openstack format (Port Pair) to mano format (SFI)
334 sfi_list_dict can be a list of dict or a single dict
335 """
336 if isinstance(sfi_list_dict, dict):
337 sfi_list_ = [sfi_list_dict]
338 elif isinstance(sfi_list_dict, list):
339 sfi_list_ = sfi_list_dict
340 else:
341 raise TypeError(
342 "param sfi_list_dict must be a list or a dictionary")
343 for sfi in sfi_list_:
344 sfi['ingress_ports'] = []
345 sfi['egress_ports'] = []
346 if sfi.get('ingress'):
347 sfi['ingress_ports'].append(sfi['ingress'])
348 if sfi.get('egress'):
349 sfi['egress_ports'].append(sfi['egress'])
350 del sfi['ingress']
351 del sfi['egress']
352 params = sfi.get('service_function_parameters')
353 sfc_encap = False
354 if params:
355 correlation = params.get('correlation')
356 if correlation:
357 sfc_encap = True
358 sfi['sfc_encap'] = sfc_encap
359 del sfi['service_function_parameters']
360
361 def __sf_os2mano(self, sf_list_dict):
362 """Transform the openstack format (Port Pair Group) to mano format (SF)
363 sf_list_dict can be a list of dict or a single dict
364 """
365 if isinstance(sf_list_dict, dict):
366 sf_list_ = [sf_list_dict]
367 elif isinstance(sf_list_dict, list):
368 sf_list_ = sf_list_dict
369 else:
370 raise TypeError(
371 "param sf_list_dict must be a list or a dictionary")
372 for sf in sf_list_:
373 del sf['port_pair_group_parameters']
374 sf['sfis'] = sf['port_pairs']
375 del sf['port_pairs']
376
377 def __sfp_os2mano(self, sfp_list_dict):
378 """Transform the openstack format (Port Chain) to mano format (SFP)
379 sfp_list_dict can be a list of dict or a single dict
380 """
381 if isinstance(sfp_list_dict, dict):
382 sfp_list_ = [sfp_list_dict]
383 elif isinstance(sfp_list_dict, list):
384 sfp_list_ = sfp_list_dict
385 else:
386 raise TypeError(
387 "param sfp_list_dict must be a list or a dictionary")
388 for sfp in sfp_list_:
389 params = sfp.pop('chain_parameters')
390 sfc_encap = False
391 if params:
392 correlation = params.get('correlation')
393 if correlation:
394 sfc_encap = True
395 sfp['sfc_encap'] = sfc_encap
396 sfp['spi'] = sfp.pop('chain_id')
397 sfp['classifications'] = sfp.pop('flow_classifiers')
398 sfp['service_functions'] = sfp.pop('port_pair_groups')
399
400 # placeholder for now; read TODO note below
401 def _validate_classification(self, type, definition):
402 # only legacy_flow_classifier Type is supported at this point
403 return True
404 # TODO(igordcard): this method should be an abstract method of an
405 # abstract Classification class to be implemented by the specific
406 # Types. Also, abstract vimconnector should call the validation
407 # method before the implemented VIM connectors are called.
408
tiernoae4a8d12016-07-08 12:30:39 +0200409 def _format_exception(self, exception):
tierno69647792020-03-05 16:45:48 +0000410 """Transform a keystone, nova, neutron exception into a vimconn exception discovering the cause"""
tiernode12f782019-04-05 12:46:42 +0000411
tierno69647792020-03-05 16:45:48 +0000412 message_error = str(exception)
tierno5ad826a2020-08-11 11:19:44 +0000413 tip = ""
tiernode12f782019-04-05 12:46:42 +0000414
415 if isinstance(exception, (neExceptions.NetworkNotFoundClient, nvExceptions.NotFound, ksExceptions.NotFound,
416 gl1Exceptions.HTTPNotFound)):
tierno72774862020-05-04 11:44:15 +0000417 raise vimconn.VimConnNotFoundException(type(exception).__name__ + ": " + message_error)
shashankjain3c83a212018-10-04 13:05:46 +0530418 elif isinstance(exception, (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError,
tierno69647792020-03-05 16:45:48 +0000419 ConnectionError, ksExceptions.ConnectionError, neExceptions.ConnectionFailed)):
tierno5ad826a2020-08-11 11:19:44 +0000420 if type(exception).__name__ == "SSLError":
421 tip = " (maybe option 'insecure' must be added to the VIM)"
422 raise vimconn.VimConnConnectionException("Invalid URL or credentials{}: {}".format(tip, message_error))
tierno69647792020-03-05 16:45:48 +0000423 elif isinstance(exception, (KeyError, nvExceptions.BadRequest, ksExceptions.BadRequest)):
tierno72774862020-05-04 11:44:15 +0000424 raise vimconn.VimConnException(type(exception).__name__ + ": " + message_error)
anwarsc76a3ee2018-10-04 14:05:32 +0530425 elif isinstance(exception, (nvExceptions.ClientException, ksExceptions.ClientException,
426 neExceptions.NeutronException)):
tierno72774862020-05-04 11:44:15 +0000427 raise vimconn.VimConnUnexpectedResponse(type(exception).__name__ + ": " + message_error)
tiernoae4a8d12016-07-08 12:30:39 +0200428 elif isinstance(exception, nvExceptions.Conflict):
tierno72774862020-05-04 11:44:15 +0000429 raise vimconn.VimConnConflictException(type(exception).__name__ + ": " + message_error)
430 elif isinstance(exception, vimconn.VimConnException):
tierno41a69812018-02-16 14:34:33 +0100431 raise exception
tiernof716aea2017-06-21 18:01:40 +0200432 else: # ()
tiernode12f782019-04-05 12:46:42 +0000433 self.logger.error("General Exception " + message_error, exc_info=True)
tierno72774862020-05-04 11:44:15 +0000434 raise vimconn.VimConnConnectionException(type(exception).__name__ + ": " + message_error)
tiernoae4a8d12016-07-08 12:30:39 +0200435
tiernoa05b65a2019-02-01 12:30:27 +0000436 def _get_ids_from_name(self):
437 """
438 Obtain ids from name of tenant and security_groups. Store at self .security_groups_id"
439 :return: None
440 """
441 # get tenant_id if only tenant_name is supplied
442 self._reload_connection()
443 if not self.my_tenant_id:
tierno72774862020-05-04 11:44:15 +0000444 raise vimconn.VimConnConnectionException("Error getting tenant information from name={} id={}".
tiernoa05b65a2019-02-01 12:30:27 +0000445 format(self.tenant_name, self.tenant_id))
446 if self.config.get('security_groups') and not self.security_groups_id:
447 # convert from name to id
448 neutron_sg_list = self.neutron.list_security_groups(tenant_id=self.my_tenant_id)["security_groups"]
449
450 self.security_groups_id = []
451 for sg in self.config.get('security_groups'):
452 for neutron_sg in neutron_sg_list:
453 if sg in (neutron_sg["id"], neutron_sg["name"]):
454 self.security_groups_id.append(neutron_sg["id"])
455 break
456 else:
457 self.security_groups_id = None
tierno72774862020-05-04 11:44:15 +0000458 raise vimconn.VimConnConnectionException("Not found security group {} for this tenant".format(sg))
tiernoa05b65a2019-02-01 12:30:27 +0000459
tierno5509c2e2019-07-04 16:23:20 +0000460 def check_vim_connectivity(self):
461 # just get network list to check connectivity and credentials
462 self.get_network_list(filter_dict={})
463
tiernoae4a8d12016-07-08 12:30:39 +0200464 def get_tenant_list(self, filter_dict={}):
tierno1ec592d2020-06-16 15:29:47 +0000465 """Obtain tenants of VIM
tiernoae4a8d12016-07-08 12:30:39 +0200466 filter_dict can contain the following keys:
467 name: filter by tenant name
468 id: filter by tenant uuid/id
469 <other VIM specific>
470 Returns the tenant list of dictionaries: [{'name':'<name>, 'id':'<id>, ...}, ...]
tierno1ec592d2020-06-16 15:29:47 +0000471 """
ahmadsa95baa272016-11-30 09:14:11 +0500472 self.logger.debug("Getting tenants from VIM filter: '%s'", str(filter_dict))
tiernoae4a8d12016-07-08 12:30:39 +0200473 try:
474 self._reload_connection()
tiernof716aea2017-06-21 18:01:40 +0200475 if self.api_version3:
476 project_class_list = self.keystone.projects.list(name=filter_dict.get("name"))
ahmadsa95baa272016-11-30 09:14:11 +0500477 else:
tiernof716aea2017-06-21 18:01:40 +0200478 project_class_list = self.keystone.tenants.findall(**filter_dict)
tierno1ec592d2020-06-16 15:29:47 +0000479 project_list = []
ahmadsa95baa272016-11-30 09:14:11 +0500480 for project in project_class_list:
tiernof716aea2017-06-21 18:01:40 +0200481 if filter_dict.get('id') and filter_dict["id"] != project.id:
482 continue
ahmadsa95baa272016-11-30 09:14:11 +0500483 project_list.append(project.to_dict())
484 return project_list
tiernof716aea2017-06-21 18:01:40 +0200485 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200486 self._format_exception(e)
487
488 def new_tenant(self, tenant_name, tenant_description):
tierno1ec592d2020-06-16 15:29:47 +0000489 """Adds a new tenant to openstack VIM. Returns the tenant identifier"""
tiernoae4a8d12016-07-08 12:30:39 +0200490 self.logger.debug("Adding a new tenant name: %s", tenant_name)
491 try:
492 self._reload_connection()
tiernof716aea2017-06-21 18:01:40 +0200493 if self.api_version3:
494 project = self.keystone.projects.create(tenant_name, self.config.get("project_domain_id", "default"),
495 description=tenant_description, is_domain=False)
ahmadsa95baa272016-11-30 09:14:11 +0500496 else:
tiernof716aea2017-06-21 18:01:40 +0200497 project = self.keystone.tenants.create(tenant_name, tenant_description)
ahmadsa95baa272016-11-30 09:14:11 +0500498 return project.id
tierno1ec592d2020-06-16 15:29:47 +0000499 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ksExceptions.BadRequest, ConnectionError)\
500 as e:
tiernoae4a8d12016-07-08 12:30:39 +0200501 self._format_exception(e)
502
503 def delete_tenant(self, tenant_id):
tierno1ec592d2020-06-16 15:29:47 +0000504 """Delete a tenant from openstack VIM. Returns the old tenant identifier"""
tiernoae4a8d12016-07-08 12:30:39 +0200505 self.logger.debug("Deleting tenant %s from VIM", tenant_id)
506 try:
507 self._reload_connection()
tiernof716aea2017-06-21 18:01:40 +0200508 if self.api_version3:
ahmadsa95baa272016-11-30 09:14:11 +0500509 self.keystone.projects.delete(tenant_id)
510 else:
511 self.keystone.tenants.delete(tenant_id)
tiernoae4a8d12016-07-08 12:30:39 +0200512 return tenant_id
tierno1ec592d2020-06-16 15:29:47 +0000513 except (ksExceptions.ConnectionError, ksExceptions.ClientException, ksExceptions.NotFound, ConnectionError)\
514 as e:
tiernoae4a8d12016-07-08 12:30:39 +0200515 self._format_exception(e)
ahmadsa95baa272016-11-30 09:14:11 +0500516
tierno6869ae72020-01-09 17:37:34 +0000517 def new_network(self, net_name, net_type, ip_profile=None, shared=False, provider_network_profile=None):
garciadeblasebd66722019-01-31 16:01:31 +0000518 """Adds a tenant network to VIM
519 Params:
520 'net_name': name of the network
521 'net_type': one of:
522 'bridge': overlay isolated network
523 'data': underlay E-LAN network for Passthrough and SRIOV interfaces
524 'ptp': underlay E-LINE network for Passthrough and SRIOV interfaces.
525 'ip_profile': is a dict containing the IP parameters of the network
526 'ip_version': can be "IPv4" or "IPv6" (Currently only IPv4 is implemented)
527 'subnet_address': ip_prefix_schema, that is X.X.X.X/Y
528 'gateway_address': (Optional) ip_schema, that is X.X.X.X
529 'dns_address': (Optional) comma separated list of ip_schema, e.g. X.X.X.X[,X,X,X,X]
530 'dhcp_enabled': True or False
531 'dhcp_start_address': ip_schema, first IP to grant
532 'dhcp_count': number of IPs to grant.
533 'shared': if this network can be seen/use by other tenants/organization
garciadeblas4af0d542020-02-18 16:01:13 +0100534 'provider_network_profile': (optional) contains {segmentation-id: vlan, network-type: vlan|vxlan,
535 physical-network: physnet-label}
garciadeblasebd66722019-01-31 16:01:31 +0000536 Returns a tuple with the network identifier and created_items, or raises an exception on error
537 created_items can be None or a dictionary where this method can include key-values that will be passed to
538 the method delete_network. Can be used to store created segments, created l2gw connections, etc.
539 Format is vimconnector dependent, but do not use nested dictionaries and a value of None should be the same
540 as not present.
541 """
tiernoae4a8d12016-07-08 12:30:39 +0200542 self.logger.debug("Adding a new network to VIM name '%s', type '%s'", net_name, net_type)
garciadeblasebd66722019-01-31 16:01:31 +0000543 # self.logger.debug(">>>>>>>>>>>>>>>>>> IP profile %s", str(ip_profile))
kbsuba85c54d2019-10-17 16:30:32 +0000544
tierno7edb6752016-03-21 17:37:52 +0100545 try:
kbsuba85c54d2019-10-17 16:30:32 +0000546 vlan = None
547 if provider_network_profile:
548 vlan = provider_network_profile.get("segmentation-id")
garciadeblasedca7b32016-09-29 14:01:52 +0000549 new_net = None
garciadeblasebd66722019-01-31 16:01:31 +0000550 created_items = {}
tierno7edb6752016-03-21 17:37:52 +0100551 self._reload_connection()
552 network_dict = {'name': net_name, 'admin_state_up': True}
tierno6869ae72020-01-09 17:37:34 +0000553 if net_type in ("data", "ptp"):
554 provider_physical_network = None
555 if provider_network_profile and provider_network_profile.get("physical-network"):
556 provider_physical_network = provider_network_profile.get("physical-network")
557 # provider-network must be one of the dataplane_physcial_netowrk if this is a list. If it is string
558 # or not declared, just ignore the checking
559 if isinstance(self.config.get('dataplane_physical_net'), (tuple, list)) and \
560 provider_physical_network not in self.config['dataplane_physical_net']:
tierno72774862020-05-04 11:44:15 +0000561 raise vimconn.VimConnConflictException(
tierno6869ae72020-01-09 17:37:34 +0000562 "Invalid parameter 'provider-network:physical-network' for network creation. '{}' is not "
563 "one of the declared list at VIM_config:dataplane_physical_net".format(
564 provider_physical_network))
565 if not provider_physical_network: # use the default dataplane_physical_net
566 provider_physical_network = self.config.get('dataplane_physical_net')
567 # if it is non empty list, use the first value. If it is a string use the value directly
568 if isinstance(provider_physical_network, (tuple, list)) and provider_physical_network:
569 provider_physical_network = provider_physical_network[0]
570
571 if not provider_physical_network:
tierno5ad826a2020-08-11 11:19:44 +0000572 raise vimconn.VimConnConflictException(
573 "missing information needed for underlay networks. Provide 'dataplane_physical_net' "
574 "configuration at VIM or use the NS instantiation parameter 'provider-network.physical-network'"
575 " for the VLD")
tierno6869ae72020-01-09 17:37:34 +0000576
garciadeblasebd66722019-01-31 16:01:31 +0000577 if not self.config.get('multisegment_support'):
tierno6869ae72020-01-09 17:37:34 +0000578 network_dict["provider:physical_network"] = provider_physical_network
garciadeblas4af0d542020-02-18 16:01:13 +0100579 if provider_network_profile and "network-type" in provider_network_profile:
580 network_dict["provider:network_type"] = provider_network_profile["network-type"]
581 else:
tierno1ec592d2020-06-16 15:29:47 +0000582 network_dict["provider:network_type"] = self.config.get('dataplane_network_type', 'vlan')
tierno6869ae72020-01-09 17:37:34 +0000583 if vlan:
584 network_dict["provider:segmentation_id"] = vlan
garciadeblasebd66722019-01-31 16:01:31 +0000585 else:
tierno6869ae72020-01-09 17:37:34 +0000586 # Multi-segment case
garciadeblasebd66722019-01-31 16:01:31 +0000587 segment_list = []
tierno6869ae72020-01-09 17:37:34 +0000588 segment1_dict = {
589 "provider:physical_network": '',
590 "provider:network_type": 'vxlan'
591 }
garciadeblasebd66722019-01-31 16:01:31 +0000592 segment_list.append(segment1_dict)
tierno6869ae72020-01-09 17:37:34 +0000593 segment2_dict = {
594 "provider:physical_network": provider_physical_network,
595 "provider:network_type": "vlan"
596 }
597 if vlan:
598 segment2_dict["provider:segmentation_id"] = vlan
599 elif self.config.get('multisegment_vlan_range'):
garciadeblasebd66722019-01-31 16:01:31 +0000600 vlanID = self._generate_multisegment_vlanID()
601 segment2_dict["provider:segmentation_id"] = vlanID
602 # else
tierno72774862020-05-04 11:44:15 +0000603 # raise vimconn.VimConnConflictException(
tierno1ec592d2020-06-16 15:29:47 +0000604 # "You must provide 'multisegment_vlan_range' at config dict before creating a multisegment
605 # network")
garciadeblasebd66722019-01-31 16:01:31 +0000606 segment_list.append(segment2_dict)
607 network_dict["segments"] = segment_list
kate721d79b2017-06-24 04:21:38 -0700608
tierno6869ae72020-01-09 17:37:34 +0000609 # VIO Specific Changes. It needs a concrete VLAN
610 if self.vim_type == "VIO" and vlan is None:
611 if self.config.get('dataplane_net_vlan_range') is None:
tierno72774862020-05-04 11:44:15 +0000612 raise vimconn.VimConnConflictException(
tierno6869ae72020-01-09 17:37:34 +0000613 "You must provide 'dataplane_net_vlan_range' in format [start_ID - end_ID] at VIM_config "
614 "for creating underlay networks")
615 network_dict["provider:segmentation_id"] = self._generate_vlanID()
kate721d79b2017-06-24 04:21:38 -0700616
garciadeblasebd66722019-01-31 16:01:31 +0000617 network_dict["shared"] = shared
anwarsff168192019-05-06 11:23:07 +0530618 if self.config.get("disable_network_port_security"):
619 network_dict["port_security_enabled"] = False
tierno1ec592d2020-06-16 15:29:47 +0000620 new_net = self.neutron.create_network({'network': network_dict})
garciadeblasebd66722019-01-31 16:01:31 +0000621 # print new_net
622 # create subnetwork, even if there is no profile
garciadeblas9f8456e2016-09-05 05:02:59 +0200623 if not ip_profile:
624 ip_profile = {}
tierno41a69812018-02-16 14:34:33 +0100625 if not ip_profile.get('subnet_address'):
tierno1ec592d2020-06-16 15:29:47 +0000626 # Fake subnet is required
garciadeblas2299e3b2017-01-26 14:35:55 +0000627 subnet_rand = random.randint(0, 255)
628 ip_profile['subnet_address'] = "192.168.{}.0/24".format(subnet_rand)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000629 if 'ip_version' not in ip_profile:
garciadeblas9f8456e2016-09-05 05:02:59 +0200630 ip_profile['ip_version'] = "IPv4"
garciadeblasebd66722019-01-31 16:01:31 +0000631 subnet = {"name": net_name+"-subnet",
tierno1ec592d2020-06-16 15:29:47 +0000632 "network_id": new_net["network"]["id"],
633 "ip_version": 4 if ip_profile['ip_version'] == "IPv4" else 6,
634 "cidr": ip_profile['subnet_address']
635 }
tiernoa1fb4462017-06-30 12:25:50 +0200636 # Gateway should be set to None if not needed. Otherwise openstack assigns one by default
tierno41a69812018-02-16 14:34:33 +0100637 if ip_profile.get('gateway_address'):
tierno55d234c2018-07-04 18:29:21 +0200638 subnet['gateway_ip'] = ip_profile['gateway_address']
639 else:
640 subnet['gateway_ip'] = None
garciadeblasedca7b32016-09-29 14:01:52 +0000641 if ip_profile.get('dns_address'):
tierno455612d2017-05-30 16:40:10 +0200642 subnet['dns_nameservers'] = ip_profile['dns_address'].split(";")
garciadeblas9f8456e2016-09-05 05:02:59 +0200643 if 'dhcp_enabled' in ip_profile:
tierno41a69812018-02-16 14:34:33 +0100644 subnet['enable_dhcp'] = False if \
tierno1ec592d2020-06-16 15:29:47 +0000645 ip_profile['dhcp_enabled'] == "false" or ip_profile['dhcp_enabled'] is False else True
tierno41a69812018-02-16 14:34:33 +0100646 if ip_profile.get('dhcp_start_address'):
tiernoa1fb4462017-06-30 12:25:50 +0200647 subnet['allocation_pools'] = []
garciadeblas9f8456e2016-09-05 05:02:59 +0200648 subnet['allocation_pools'].append(dict())
649 subnet['allocation_pools'][0]['start'] = ip_profile['dhcp_start_address']
tierno41a69812018-02-16 14:34:33 +0100650 if ip_profile.get('dhcp_count'):
tierno1ec592d2020-06-16 15:29:47 +0000651 # parts = ip_profile['dhcp_start_address'].split('.')
652 # ip_int = (int(parts[0]) << 24) + (int(parts[1]) << 16) + (int(parts[2]) << 8) + int(parts[3])
garciadeblas9f8456e2016-09-05 05:02:59 +0200653 ip_int = int(netaddr.IPAddress(ip_profile['dhcp_start_address']))
garciadeblas21d795b2016-09-29 17:31:46 +0200654 ip_int += ip_profile['dhcp_count'] - 1
garciadeblas9f8456e2016-09-05 05:02:59 +0200655 ip_str = str(netaddr.IPAddress(ip_int))
656 subnet['allocation_pools'][0]['end'] = ip_str
tierno1ec592d2020-06-16 15:29:47 +0000657 # self.logger.debug(">>>>>>>>>>>>>>>>>> Subnet: %s", str(subnet))
658 self.neutron.create_subnet({"subnet": subnet})
garciadeblasebd66722019-01-31 16:01:31 +0000659
660 if net_type == "data" and self.config.get('multisegment_support'):
661 if self.config.get('l2gw_support'):
662 l2gw_list = self.neutron.list_l2_gateways().get("l2_gateways", ())
663 for l2gw in l2gw_list:
tierno1ec592d2020-06-16 15:29:47 +0000664 l2gw_conn = {
665 "l2_gateway_id": l2gw["id"],
666 "network_id": new_net["network"]["id"],
667 "segmentation_id": str(vlanID),
668 }
garciadeblasebd66722019-01-31 16:01:31 +0000669 new_l2gw_conn = self.neutron.create_l2_gateway_connection({"l2_gateway_connection": l2gw_conn})
670 created_items["l2gwconn:" + str(new_l2gw_conn["l2_gateway_connection"]["id"])] = True
671 return new_net["network"]["id"], created_items
tierno41a69812018-02-16 14:34:33 +0100672 except Exception as e:
tierno1ec592d2020-06-16 15:29:47 +0000673 # delete l2gw connections (if any) before deleting the network
garciadeblasebd66722019-01-31 16:01:31 +0000674 for k, v in created_items.items():
675 if not v: # skip already deleted
676 continue
677 try:
678 k_item, _, k_id = k.partition(":")
679 if k_item == "l2gwconn":
680 self.neutron.delete_l2_gateway_connection(k_id)
681 except Exception as e2:
682 self.logger.error("Error deleting l2 gateway connection: {}: {}".format(type(e2).__name__, e2))
garciadeblasedca7b32016-09-29 14:01:52 +0000683 if new_net:
684 self.neutron.delete_network(new_net['network']['id'])
tiernoae4a8d12016-07-08 12:30:39 +0200685 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100686
687 def get_network_list(self, filter_dict={}):
tierno1ec592d2020-06-16 15:29:47 +0000688 """Obtain tenant networks of VIM
tierno7edb6752016-03-21 17:37:52 +0100689 Filter_dict can be:
690 name: network name
691 id: network uuid
692 shared: boolean
693 tenant_id: tenant
694 admin_state_up: boolean
695 status: 'ACTIVE'
696 Returns the network list of dictionaries
tierno1ec592d2020-06-16 15:29:47 +0000697 """
tiernoae4a8d12016-07-08 12:30:39 +0200698 self.logger.debug("Getting network from VIM filter: '%s'", str(filter_dict))
tierno7edb6752016-03-21 17:37:52 +0100699 try:
700 self._reload_connection()
tierno69b590e2018-03-13 18:52:23 +0100701 filter_dict_os = filter_dict.copy()
702 if self.api_version3 and "tenant_id" in filter_dict_os:
tierno1ec592d2020-06-16 15:29:47 +0000703 filter_dict_os['project_id'] = filter_dict_os.pop('tenant_id') # TODO check
tierno69b590e2018-03-13 18:52:23 +0100704 net_dict = self.neutron.list_networks(**filter_dict_os)
tierno00e3df72017-11-29 17:20:13 +0100705 net_list = net_dict["networks"]
tierno7edb6752016-03-21 17:37:52 +0100706 self.__net_os2mano(net_list)
tiernoae4a8d12016-07-08 12:30:39 +0200707 return net_list
tierno1ec592d2020-06-16 15:29:47 +0000708 except (neExceptions.ConnectionFailed, ksExceptions.ClientException, neExceptions.NeutronException,
709 ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200710 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100711
tiernoae4a8d12016-07-08 12:30:39 +0200712 def get_network(self, net_id):
tierno1ec592d2020-06-16 15:29:47 +0000713 """Obtain details of network from VIM
714 Returns the network information from a network id"""
tiernoae4a8d12016-07-08 12:30:39 +0200715 self.logger.debug(" Getting tenant network %s from VIM", net_id)
tierno1ec592d2020-06-16 15:29:47 +0000716 filter_dict = {"id": net_id}
tiernoae4a8d12016-07-08 12:30:39 +0200717 net_list = self.get_network_list(filter_dict)
tierno1ec592d2020-06-16 15:29:47 +0000718 if len(net_list) == 0:
tierno72774862020-05-04 11:44:15 +0000719 raise vimconn.VimConnNotFoundException("Network '{}' not found".format(net_id))
tierno1ec592d2020-06-16 15:29:47 +0000720 elif len(net_list) > 1:
tierno72774862020-05-04 11:44:15 +0000721 raise vimconn.VimConnConflictException("Found more than one network with this criteria")
tierno7edb6752016-03-21 17:37:52 +0100722 net = net_list[0]
tierno1ec592d2020-06-16 15:29:47 +0000723 subnets = []
724 for subnet_id in net.get("subnets", ()):
tierno7edb6752016-03-21 17:37:52 +0100725 try:
726 subnet = self.neutron.show_subnet(subnet_id)
727 except Exception as e:
tiernoae4a8d12016-07-08 12:30:39 +0200728 self.logger.error("osconnector.get_network(): Error getting subnet %s %s" % (net_id, str(e)))
729 subnet = {"id": subnet_id, "fault": str(e)}
tierno7edb6752016-03-21 17:37:52 +0100730 subnets.append(subnet)
731 net["subnets"] = subnets
Pablo Montes Moreno51e553b2017-03-23 16:39:12 +0100732 net["encapsulation"] = net.get('provider:network_type')
Anderson Bravalheri0fb70282018-12-16 19:28:37 +0000733 net["encapsulation_type"] = net.get('provider:network_type')
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100734 net["segmentation_id"] = net.get('provider:segmentation_id')
Anderson Bravalheri0fb70282018-12-16 19:28:37 +0000735 net["encapsulation_id"] = net.get('provider:segmentation_id')
tiernoae4a8d12016-07-08 12:30:39 +0200736 return net
tierno7edb6752016-03-21 17:37:52 +0100737
garciadeblasebd66722019-01-31 16:01:31 +0000738 def delete_network(self, net_id, created_items=None):
739 """
740 Removes a tenant network from VIM and its associated elements
741 :param net_id: VIM identifier of the network, provided by method new_network
742 :param created_items: dictionary with extra items to be deleted. provided by method new_network
743 Returns the network identifier or raises an exception upon error or when network is not found
744 """
tiernoae4a8d12016-07-08 12:30:39 +0200745 self.logger.debug("Deleting network '%s' from VIM", net_id)
tierno1ec592d2020-06-16 15:29:47 +0000746 if created_items is None:
garciadeblasebd66722019-01-31 16:01:31 +0000747 created_items = {}
tierno7edb6752016-03-21 17:37:52 +0100748 try:
749 self._reload_connection()
tierno1ec592d2020-06-16 15:29:47 +0000750 # delete l2gw connections (if any) before deleting the network
garciadeblasebd66722019-01-31 16:01:31 +0000751 for k, v in created_items.items():
752 if not v: # skip already deleted
753 continue
754 try:
755 k_item, _, k_id = k.partition(":")
756 if k_item == "l2gwconn":
757 self.neutron.delete_l2_gateway_connection(k_id)
758 except Exception as e:
759 self.logger.error("Error deleting l2 gateway connection: {}: {}".format(type(e).__name__, e))
tierno1ec592d2020-06-16 15:29:47 +0000760 # delete VM ports attached to this networks before the network
tierno7edb6752016-03-21 17:37:52 +0100761 ports = self.neutron.list_ports(network_id=net_id)
762 for p in ports['ports']:
763 try:
764 self.neutron.delete_port(p["id"])
765 except Exception as e:
tiernoae4a8d12016-07-08 12:30:39 +0200766 self.logger.error("Error deleting port %s: %s", p["id"], str(e))
tierno7edb6752016-03-21 17:37:52 +0100767 self.neutron.delete_network(net_id)
tiernoae4a8d12016-07-08 12:30:39 +0200768 return net_id
769 except (neExceptions.ConnectionFailed, neExceptions.NetworkNotFoundClient, neExceptions.NeutronException,
tierno8e995ce2016-09-22 08:13:00 +0000770 ksExceptions.ClientException, neExceptions.NeutronException, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200771 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100772
tiernoae4a8d12016-07-08 12:30:39 +0200773 def refresh_nets_status(self, net_list):
tierno1ec592d2020-06-16 15:29:47 +0000774 """Get the status of the networks
tiernoae4a8d12016-07-08 12:30:39 +0200775 Params: the list of network identifiers
776 Returns a dictionary with:
777 net_id: #VIM id of this network
778 status: #Mandatory. Text with one of:
779 # DELETED (not found at vim)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100780 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
tiernoae4a8d12016-07-08 12:30:39 +0200781 # OTHER (Vim reported other status not understood)
782 # ERROR (VIM indicates an ERROR status)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100783 # ACTIVE, INACTIVE, DOWN (admin down),
tiernoae4a8d12016-07-08 12:30:39 +0200784 # BUILD (on building process)
785 #
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100786 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
tiernoae4a8d12016-07-08 12:30:39 +0200787 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
788
tierno1ec592d2020-06-16 15:29:47 +0000789 """
790 net_dict = {}
tiernoae4a8d12016-07-08 12:30:39 +0200791 for net_id in net_list:
792 net = {}
793 try:
794 net_vim = self.get_network(net_id)
795 if net_vim['status'] in netStatus2manoFormat:
tierno1ec592d2020-06-16 15:29:47 +0000796 net["status"] = netStatus2manoFormat[net_vim['status']]
tiernoae4a8d12016-07-08 12:30:39 +0200797 else:
798 net["status"] = "OTHER"
799 net["error_msg"] = "VIM status reported " + net_vim['status']
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000800
tierno8e995ce2016-09-22 08:13:00 +0000801 if net['status'] == "ACTIVE" and not net_vim['admin_state_up']:
tiernoae4a8d12016-07-08 12:30:39 +0200802 net['status'] = 'DOWN'
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100803
804 net['vim_info'] = self.serialize(net_vim)
805
tierno1ec592d2020-06-16 15:29:47 +0000806 if net_vim.get('fault'): # TODO
tiernoae4a8d12016-07-08 12:30:39 +0200807 net['error_msg'] = str(net_vim['fault'])
tierno72774862020-05-04 11:44:15 +0000808 except vimconn.VimConnNotFoundException as e:
tiernoae4a8d12016-07-08 12:30:39 +0200809 self.logger.error("Exception getting net status: %s", str(e))
810 net['status'] = "DELETED"
811 net['error_msg'] = str(e)
tierno72774862020-05-04 11:44:15 +0000812 except vimconn.VimConnException as e:
tiernoae4a8d12016-07-08 12:30:39 +0200813 self.logger.error("Exception getting net status: %s", str(e))
814 net['status'] = "VIM_ERROR"
815 net['error_msg'] = str(e)
816 net_dict[net_id] = net
817 return net_dict
818
819 def get_flavor(self, flavor_id):
tierno1ec592d2020-06-16 15:29:47 +0000820 """Obtain flavor details from the VIM. Returns the flavor dict details"""
tiernoae4a8d12016-07-08 12:30:39 +0200821 self.logger.debug("Getting flavor '%s'", flavor_id)
tierno7edb6752016-03-21 17:37:52 +0100822 try:
823 self._reload_connection()
824 flavor = self.nova.flavors.find(id=flavor_id)
tierno1ec592d2020-06-16 15:29:47 +0000825 # TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
tiernoae4a8d12016-07-08 12:30:39 +0200826 return flavor.to_dict()
tierno1ec592d2020-06-16 15:29:47 +0000827 except (nvExceptions.NotFound, nvExceptions.ClientException, ksExceptions.ClientException,
828 ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200829 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100830
tiernocf157a82017-01-30 14:07:06 +0100831 def get_flavor_id_from_data(self, flavor_dict):
832 """Obtain flavor id that match the flavor description
833 Returns the flavor_id or raises a vimconnNotFoundException
tiernoe26fc7a2017-05-30 14:43:03 +0200834 flavor_dict: contains the required ram, vcpus, disk
835 If 'use_existing_flavors' is set to True at config, the closer flavor that provides same or more ram, vcpus
836 and disk is returned. Otherwise a flavor with exactly same ram, vcpus and disk is returned or a
837 vimconnNotFoundException is raised
tiernocf157a82017-01-30 14:07:06 +0100838 """
tiernoe26fc7a2017-05-30 14:43:03 +0200839 exact_match = False if self.config.get('use_existing_flavors') else True
tiernocf157a82017-01-30 14:07:06 +0100840 try:
841 self._reload_connection()
tiernoe26fc7a2017-05-30 14:43:03 +0200842 flavor_candidate_id = None
843 flavor_candidate_data = (10000, 10000, 10000)
844 flavor_target = (flavor_dict["ram"], flavor_dict["vcpus"], flavor_dict["disk"])
845 # numa=None
anwarsae5f52c2019-04-22 10:35:27 +0530846 extended = flavor_dict.get("extended", {})
847 if extended:
tierno1ec592d2020-06-16 15:29:47 +0000848 # TODO
tierno72774862020-05-04 11:44:15 +0000849 raise vimconn.VimConnNotFoundException("Flavor with EPA still not implemented")
tiernocf157a82017-01-30 14:07:06 +0100850 # if len(numas) > 1:
tierno72774862020-05-04 11:44:15 +0000851 # raise vimconn.VimConnNotFoundException("Cannot find any flavor with more than one numa")
tiernocf157a82017-01-30 14:07:06 +0100852 # numa=numas[0]
853 # numas = extended.get("numas")
854 for flavor in self.nova.flavors.list():
855 epa = flavor.get_keys()
856 if epa:
857 continue
tiernoe26fc7a2017-05-30 14:43:03 +0200858 # TODO
859 flavor_data = (flavor.ram, flavor.vcpus, flavor.disk)
860 if flavor_data == flavor_target:
861 return flavor.id
862 elif not exact_match and flavor_target < flavor_data < flavor_candidate_data:
863 flavor_candidate_id = flavor.id
864 flavor_candidate_data = flavor_data
865 if not exact_match and flavor_candidate_id:
866 return flavor_candidate_id
tierno1ec592d2020-06-16 15:29:47 +0000867 raise vimconn.VimConnNotFoundException("Cannot find any flavor matching '{}'".format(flavor_dict))
868 except (nvExceptions.NotFound, nvExceptions.ClientException, ksExceptions.ClientException,
869 ConnectionError) as e:
tiernocf157a82017-01-30 14:07:06 +0100870 self._format_exception(e)
871
anwarsae5f52c2019-04-22 10:35:27 +0530872 def process_resource_quota(self, quota, prefix, extra_specs):
873 """
874 :param prefix:
borsatti8a2dda32019-12-18 15:08:57 +0000875 :param extra_specs:
anwarsae5f52c2019-04-22 10:35:27 +0530876 :return:
877 """
878 if 'limit' in quota:
879 extra_specs["quota:" + prefix + "_limit"] = quota['limit']
880 if 'reserve' in quota:
881 extra_specs["quota:" + prefix + "_reservation"] = quota['reserve']
882 if 'shares' in quota:
883 extra_specs["quota:" + prefix + "_shares_level"] = "custom"
884 extra_specs["quota:" + prefix + "_shares_share"] = quota['shares']
885
tiernoae4a8d12016-07-08 12:30:39 +0200886 def new_flavor(self, flavor_data, change_name_if_used=True):
tierno1ec592d2020-06-16 15:29:47 +0000887 """Adds a tenant flavor to openstack VIM
888 if change_name_if_used is True, it will change name in case of conflict, because it is not supported name
889 repetition
tierno7edb6752016-03-21 17:37:52 +0100890 Returns the flavor identifier
tierno1ec592d2020-06-16 15:29:47 +0000891 """
tiernoae4a8d12016-07-08 12:30:39 +0200892 self.logger.debug("Adding flavor '%s'", str(flavor_data))
tierno1ec592d2020-06-16 15:29:47 +0000893 retry = 0
894 max_retries = 3
tierno7edb6752016-03-21 17:37:52 +0100895 name_suffix = 0
anwarsc76a3ee2018-10-04 14:05:32 +0530896 try:
tierno1ec592d2020-06-16 15:29:47 +0000897 name = flavor_data['name']
898 while retry < max_retries:
899 retry += 1
anwarsc76a3ee2018-10-04 14:05:32 +0530900 try:
901 self._reload_connection()
902 if change_name_if_used:
tierno1ec592d2020-06-16 15:29:47 +0000903 # get used names
904 fl_names = []
905 fl = self.nova.flavors.list()
anwarsc76a3ee2018-10-04 14:05:32 +0530906 for f in fl:
907 fl_names.append(f.name)
908 while name in fl_names:
909 name_suffix += 1
910 name = flavor_data['name']+"-" + str(name_suffix)
kate721d79b2017-06-24 04:21:38 -0700911
tierno1ec592d2020-06-16 15:29:47 +0000912 ram = flavor_data.get('ram', 64)
913 vcpus = flavor_data.get('vcpus', 1)
914 extra_specs = {}
tierno7edb6752016-03-21 17:37:52 +0100915
anwarsc76a3ee2018-10-04 14:05:32 +0530916 extended = flavor_data.get("extended")
917 if extended:
tierno1ec592d2020-06-16 15:29:47 +0000918 numas = extended.get("numas")
anwarsc76a3ee2018-10-04 14:05:32 +0530919 if numas:
920 numa_nodes = len(numas)
921 if numa_nodes > 1:
922 return -1, "Can not add flavor with more than one numa"
anwarsae5f52c2019-04-22 10:35:27 +0530923 extra_specs["hw:numa_nodes"] = str(numa_nodes)
924 extra_specs["hw:mem_page_size"] = "large"
925 extra_specs["hw:cpu_policy"] = "dedicated"
926 extra_specs["hw:numa_mempolicy"] = "strict"
anwarsc76a3ee2018-10-04 14:05:32 +0530927 if self.vim_type == "VIO":
anwarsae5f52c2019-04-22 10:35:27 +0530928 extra_specs["vmware:extra_config"] = '{"numa.nodeAffinity":"0"}'
929 extra_specs["vmware:latency_sensitivity_level"] = "high"
anwarsc76a3ee2018-10-04 14:05:32 +0530930 for numa in numas:
tierno1ec592d2020-06-16 15:29:47 +0000931 # overwrite ram and vcpus
932 # check if key 'memory' is present in numa else use ram value at flavor
anwarsc76a3ee2018-10-04 14:05:32 +0530933 if 'memory' in numa:
934 ram = numa['memory']*1024
tierno1ec592d2020-06-16 15:29:47 +0000935 # See for reference: https://specs.openstack.org/openstack/nova-specs/specs/mitaka/
936 # implemented/virt-driver-cpu-thread-pinning.html
garciadeblasfa35a722019-04-11 19:15:49 +0200937 extra_specs["hw:cpu_sockets"] = 1
anwarsc76a3ee2018-10-04 14:05:32 +0530938 if 'paired-threads' in numa:
939 vcpus = numa['paired-threads']*2
tierno1ec592d2020-06-16 15:29:47 +0000940 # cpu_thread_policy "require" implies that the compute node must have an
941 # STM architecture
anwarsae5f52c2019-04-22 10:35:27 +0530942 extra_specs["hw:cpu_thread_policy"] = "require"
943 extra_specs["hw:cpu_policy"] = "dedicated"
anwarsc76a3ee2018-10-04 14:05:32 +0530944 elif 'cores' in numa:
945 vcpus = numa['cores']
tierno1ec592d2020-06-16 15:29:47 +0000946 # cpu_thread_policy "prefer" implies that the host must not have an SMT
947 # architecture, or a non-SMT architecture will be emulated
anwarsae5f52c2019-04-22 10:35:27 +0530948 extra_specs["hw:cpu_thread_policy"] = "isolate"
949 extra_specs["hw:cpu_policy"] = "dedicated"
anwarsc76a3ee2018-10-04 14:05:32 +0530950 elif 'threads' in numa:
951 vcpus = numa['threads']
tierno1ec592d2020-06-16 15:29:47 +0000952 # cpu_thread_policy "prefer" implies that the host may or may not have an SMT
953 # architecture
anwarsae5f52c2019-04-22 10:35:27 +0530954 extra_specs["hw:cpu_thread_policy"] = "prefer"
955 extra_specs["hw:cpu_policy"] = "dedicated"
anwarsc76a3ee2018-10-04 14:05:32 +0530956 # for interface in numa.get("interfaces",() ):
957 # if interface["dedicated"]=="yes":
tierno1ec592d2020-06-16 15:29:47 +0000958 # raise vimconn.VimConnException("Passthrough interfaces are not supported
959 # for the openstack connector", http_code=vimconn.HTTP_Service_Unavailable)
960 # #TODO, add the key 'pci_passthrough:alias"="<label at config>:<number ifaces>"'
961 # when a way to connect it is available
anwarsae5f52c2019-04-22 10:35:27 +0530962 elif extended.get("cpu-quota"):
963 self.process_resource_quota(extended.get("cpu-quota"), "cpu", extra_specs)
964 if extended.get("mem-quota"):
965 self.process_resource_quota(extended.get("mem-quota"), "memory", extra_specs)
966 if extended.get("vif-quota"):
967 self.process_resource_quota(extended.get("vif-quota"), "vif", extra_specs)
968 if extended.get("disk-io-quota"):
969 self.process_resource_quota(extended.get("disk-io-quota"), "disk_io", extra_specs)
tierno1ec592d2020-06-16 15:29:47 +0000970 # create flavor
971 new_flavor = self.nova.flavors.create(name,
972 ram,
973 vcpus,
974 flavor_data.get('disk', 0),
975 is_public=flavor_data.get('is_public', True)
976 )
977 # add metadata
anwarsae5f52c2019-04-22 10:35:27 +0530978 if extra_specs:
979 new_flavor.set_keys(extra_specs)
anwarsc76a3ee2018-10-04 14:05:32 +0530980 return new_flavor.id
981 except nvExceptions.Conflict as e:
982 if change_name_if_used and retry < max_retries:
983 continue
984 self._format_exception(e)
tierno1ec592d2020-06-16 15:29:47 +0000985 # except nvExceptions.BadRequest as e:
anwarsc76a3ee2018-10-04 14:05:32 +0530986 except (ksExceptions.ClientException, nvExceptions.ClientException, ConnectionError, KeyError) as e:
987 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100988
tierno1ec592d2020-06-16 15:29:47 +0000989 def delete_flavor(self, flavor_id):
990 """Deletes a tenant flavor from openstack VIM. Returns the old flavor_id
991 """
tiernoae4a8d12016-07-08 12:30:39 +0200992 try:
993 self._reload_connection()
994 self.nova.flavors.delete(flavor_id)
995 return flavor_id
tierno1ec592d2020-06-16 15:29:47 +0000996 # except nvExceptions.BadRequest as e:
997 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException,
998 ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200999 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001000
tierno1ec592d2020-06-16 15:29:47 +00001001 def new_image(self, image_dict):
1002 """
tiernoae4a8d12016-07-08 12:30:39 +02001003 Adds a tenant image to VIM. imge_dict is a dictionary with:
1004 name: name
1005 disk_format: qcow2, vhd, vmdk, raw (by default), ...
1006 location: path or URI
1007 public: "yes" or "no"
1008 metadata: metadata of the image
1009 Returns the image_id
tierno1ec592d2020-06-16 15:29:47 +00001010 """
1011 retry = 0
1012 max_retries = 3
1013 while retry < max_retries:
1014 retry += 1
tierno7edb6752016-03-21 17:37:52 +01001015 try:
1016 self._reload_connection()
tierno1ec592d2020-06-16 15:29:47 +00001017 # determine format http://docs.openstack.org/developer/glance/formats.html
tierno7edb6752016-03-21 17:37:52 +01001018 if "disk_format" in image_dict:
tierno1ec592d2020-06-16 15:29:47 +00001019 disk_format = image_dict["disk_format"]
1020 else: # autodiscover based on extension
tierno1beea862018-07-11 15:47:37 +02001021 if image_dict['location'].endswith(".qcow2"):
tierno1ec592d2020-06-16 15:29:47 +00001022 disk_format = "qcow2"
tierno1beea862018-07-11 15:47:37 +02001023 elif image_dict['location'].endswith(".vhd"):
tierno1ec592d2020-06-16 15:29:47 +00001024 disk_format = "vhd"
tierno1beea862018-07-11 15:47:37 +02001025 elif image_dict['location'].endswith(".vmdk"):
tierno1ec592d2020-06-16 15:29:47 +00001026 disk_format = "vmdk"
tierno1beea862018-07-11 15:47:37 +02001027 elif image_dict['location'].endswith(".vdi"):
tierno1ec592d2020-06-16 15:29:47 +00001028 disk_format = "vdi"
tierno1beea862018-07-11 15:47:37 +02001029 elif image_dict['location'].endswith(".iso"):
tierno1ec592d2020-06-16 15:29:47 +00001030 disk_format = "iso"
tierno1beea862018-07-11 15:47:37 +02001031 elif image_dict['location'].endswith(".aki"):
tierno1ec592d2020-06-16 15:29:47 +00001032 disk_format = "aki"
tierno1beea862018-07-11 15:47:37 +02001033 elif image_dict['location'].endswith(".ari"):
tierno1ec592d2020-06-16 15:29:47 +00001034 disk_format = "ari"
tierno1beea862018-07-11 15:47:37 +02001035 elif image_dict['location'].endswith(".ami"):
tierno1ec592d2020-06-16 15:29:47 +00001036 disk_format = "ami"
tierno7edb6752016-03-21 17:37:52 +01001037 else:
tierno1ec592d2020-06-16 15:29:47 +00001038 disk_format = "raw"
tiernoae4a8d12016-07-08 12:30:39 +02001039 self.logger.debug("new_image: '%s' loading from '%s'", image_dict['name'], image_dict['location'])
shashankjain3c83a212018-10-04 13:05:46 +05301040 if self.vim_type == "VIO":
1041 container_format = "bare"
1042 if 'container_format' in image_dict:
1043 container_format = image_dict['container_format']
1044 new_image = self.glance.images.create(name=image_dict['name'], container_format=container_format,
1045 disk_format=disk_format)
1046 else:
1047 new_image = self.glance.images.create(name=image_dict['name'])
tierno1beea862018-07-11 15:47:37 +02001048 if image_dict['location'].startswith("http"):
1049 # TODO there is not a method to direct download. It must be downloaded locally with requests
tierno72774862020-05-04 11:44:15 +00001050 raise vimconn.VimConnNotImplemented("Cannot create image from URL")
tierno1ec592d2020-06-16 15:29:47 +00001051 else: # local path
tierno7edb6752016-03-21 17:37:52 +01001052 with open(image_dict['location']) as fimage:
tierno1beea862018-07-11 15:47:37 +02001053 self.glance.images.upload(new_image.id, fimage)
tierno1ec592d2020-06-16 15:29:47 +00001054 # new_image = self.glancev1.images.create(name=image_dict['name'], is_public=
1055 # image_dict.get('public',"yes")=="yes",
tierno1beea862018-07-11 15:47:37 +02001056 # container_format="bare", data=fimage, disk_format=disk_format)
tierno7edb6752016-03-21 17:37:52 +01001057 metadata_to_load = image_dict.get('metadata')
tierno1ec592d2020-06-16 15:29:47 +00001058 # TODO location is a reserved word for current openstack versions. fixed for VIO please check
1059 # for openstack
shashankjain3c83a212018-10-04 13:05:46 +05301060 if self.vim_type == "VIO":
1061 metadata_to_load['upload_location'] = image_dict['location']
1062 else:
1063 metadata_to_load['location'] = image_dict['location']
tierno1beea862018-07-11 15:47:37 +02001064 self.glance.images.update(new_image.id, **metadata_to_load)
tiernoae4a8d12016-07-08 12:30:39 +02001065 return new_image.id
1066 except (nvExceptions.Conflict, ksExceptions.ClientException, nvExceptions.ClientException) as e:
1067 self._format_exception(e)
tierno8e995ce2016-09-22 08:13:00 +00001068 except (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError, ConnectionError) as e:
tierno1ec592d2020-06-16 15:29:47 +00001069 if retry == max_retries:
tiernoae4a8d12016-07-08 12:30:39 +02001070 continue
1071 self._format_exception(e)
tierno1ec592d2020-06-16 15:29:47 +00001072 except IOError as e: # can not open the file
1073 raise vimconn.VimConnConnectionException("{}: {} for {}".format(type(e).__name__, e,
1074 image_dict['location']),
tiernoae4a8d12016-07-08 12:30:39 +02001075 http_code=vimconn.HTTP_Bad_Request)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001076
tiernoae4a8d12016-07-08 12:30:39 +02001077 def delete_image(self, image_id):
tierno1ec592d2020-06-16 15:29:47 +00001078 """Deletes a tenant image from openstack VIM. Returns the old id
1079 """
tiernoae4a8d12016-07-08 12:30:39 +02001080 try:
1081 self._reload_connection()
tierno1beea862018-07-11 15:47:37 +02001082 self.glance.images.delete(image_id)
tiernoae4a8d12016-07-08 12:30:39 +02001083 return image_id
tierno1ec592d2020-06-16 15:29:47 +00001084 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException,
1085 gl1Exceptions.CommunicationError, gl1Exceptions.HTTPNotFound, ConnectionError) as e: # TODO remove
tiernoae4a8d12016-07-08 12:30:39 +02001086 self._format_exception(e)
1087
1088 def get_image_id_from_path(self, path):
tierno1ec592d2020-06-16 15:29:47 +00001089 """Get the image id from image path in the VIM database. Returns the image_id"""
tiernoae4a8d12016-07-08 12:30:39 +02001090 try:
1091 self._reload_connection()
tierno1beea862018-07-11 15:47:37 +02001092 images = self.glance.images.list()
tiernoae4a8d12016-07-08 12:30:39 +02001093 for image in images:
tierno1ec592d2020-06-16 15:29:47 +00001094 if image.metadata.get("location") == path:
tiernoae4a8d12016-07-08 12:30:39 +02001095 return image.id
tierno1ec592d2020-06-16 15:29:47 +00001096 raise vimconn.VimConnNotFoundException("image with location '{}' not found".format(path))
1097 except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError,
1098 ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001099 self._format_exception(e)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001100
garciadeblasb69fa9f2016-09-28 12:04:10 +02001101 def get_image_list(self, filter_dict={}):
tierno1ec592d2020-06-16 15:29:47 +00001102 """Obtain tenant images from VIM
garciadeblasb69fa9f2016-09-28 12:04:10 +02001103 Filter_dict can be:
1104 id: image id
1105 name: image name
1106 checksum: image checksum
1107 Returns the image list of dictionaries:
1108 [{<the fields at Filter_dict plus some VIM specific>}, ...]
1109 List can be empty
tierno1ec592d2020-06-16 15:29:47 +00001110 """
garciadeblasb69fa9f2016-09-28 12:04:10 +02001111 self.logger.debug("Getting image list from VIM filter: '%s'", str(filter_dict))
1112 try:
1113 self._reload_connection()
tierno1ec592d2020-06-16 15:29:47 +00001114 # filter_dict_os = filter_dict.copy()
1115 # First we filter by the available filter fields: name, id. The others are removed.
tierno1beea862018-07-11 15:47:37 +02001116 image_list = self.glance.images.list()
garciadeblasb69fa9f2016-09-28 12:04:10 +02001117 filtered_list = []
1118 for image in image_list:
tierno3cb8dc32017-10-24 18:13:19 +02001119 try:
tierno1beea862018-07-11 15:47:37 +02001120 if filter_dict.get("name") and image["name"] != filter_dict["name"]:
1121 continue
1122 if filter_dict.get("id") and image["id"] != filter_dict["id"]:
1123 continue
1124 if filter_dict.get("checksum") and image["checksum"] != filter_dict["checksum"]:
1125 continue
1126
1127 filtered_list.append(image.copy())
tierno3cb8dc32017-10-24 18:13:19 +02001128 except gl1Exceptions.HTTPNotFound:
1129 pass
garciadeblasb69fa9f2016-09-28 12:04:10 +02001130 return filtered_list
tierno1ec592d2020-06-16 15:29:47 +00001131 except (ksExceptions.ClientException, nvExceptions.ClientException, gl1Exceptions.CommunicationError,
1132 ConnectionError) as e:
garciadeblasb69fa9f2016-09-28 12:04:10 +02001133 self._format_exception(e)
1134
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001135 def __wait_for_vm(self, vm_id, status):
1136 """wait until vm is in the desired status and return True.
1137 If the VM gets in ERROR status, return false.
1138 If the timeout is reached generate an exception"""
1139 elapsed_time = 0
1140 while elapsed_time < server_timeout:
1141 vm_status = self.nova.servers.get(vm_id).status
1142 if vm_status == status:
1143 return True
1144 if vm_status == 'ERROR':
1145 return False
tierno1df468d2018-07-06 14:25:16 +02001146 time.sleep(5)
1147 elapsed_time += 5
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001148
1149 # if we exceeded the timeout rollback
1150 if elapsed_time >= server_timeout:
tierno72774862020-05-04 11:44:15 +00001151 raise vimconn.VimConnException('Timeout waiting for instance ' + vm_id + ' to get ' + status,
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001152 http_code=vimconn.HTTP_Request_Timeout)
1153
mirabal29356312017-07-27 12:21:22 +02001154 def _get_openstack_availablity_zones(self):
1155 """
1156 Get from openstack availability zones available
1157 :return:
1158 """
1159 try:
1160 openstack_availability_zone = self.nova.availability_zones.list()
1161 openstack_availability_zone = [str(zone.zoneName) for zone in openstack_availability_zone
1162 if zone.zoneName != 'internal']
1163 return openstack_availability_zone
tierno1ec592d2020-06-16 15:29:47 +00001164 except Exception:
mirabal29356312017-07-27 12:21:22 +02001165 return None
1166
1167 def _set_availablity_zones(self):
1168 """
1169 Set vim availablity zone
1170 :return:
1171 """
1172
1173 if 'availability_zone' in self.config:
1174 vim_availability_zones = self.config.get('availability_zone')
1175 if isinstance(vim_availability_zones, str):
1176 self.availability_zone = [vim_availability_zones]
1177 elif isinstance(vim_availability_zones, list):
1178 self.availability_zone = vim_availability_zones
1179 else:
1180 self.availability_zone = self._get_openstack_availablity_zones()
1181
tierno5a3273c2017-08-29 11:43:46 +02001182 def _get_vm_availability_zone(self, availability_zone_index, availability_zone_list):
mirabal29356312017-07-27 12:21:22 +02001183 """
tierno5a3273c2017-08-29 11:43:46 +02001184 Return thge availability zone to be used by the created VM.
1185 :return: The VIM availability zone to be used or None
mirabal29356312017-07-27 12:21:22 +02001186 """
tierno5a3273c2017-08-29 11:43:46 +02001187 if availability_zone_index is None:
1188 if not self.config.get('availability_zone'):
1189 return None
1190 elif isinstance(self.config.get('availability_zone'), str):
1191 return self.config['availability_zone']
1192 else:
1193 # TODO consider using a different parameter at config for default AV and AV list match
1194 return self.config['availability_zone'][0]
mirabal29356312017-07-27 12:21:22 +02001195
tierno5a3273c2017-08-29 11:43:46 +02001196 vim_availability_zones = self.availability_zone
1197 # check if VIM offer enough availability zones describe in the VNFD
1198 if vim_availability_zones and len(availability_zone_list) <= len(vim_availability_zones):
1199 # check if all the names of NFV AV match VIM AV names
1200 match_by_index = False
1201 for av in availability_zone_list:
1202 if av not in vim_availability_zones:
1203 match_by_index = True
1204 break
1205 if match_by_index:
1206 return vim_availability_zones[availability_zone_index]
1207 else:
1208 return availability_zone_list[availability_zone_index]
mirabal29356312017-07-27 12:21:22 +02001209 else:
tierno72774862020-05-04 11:44:15 +00001210 raise vimconn.VimConnConflictException("No enough availability zones at VIM for this deployment")
mirabal29356312017-07-27 12:21:22 +02001211
tierno5a3273c2017-08-29 11:43:46 +02001212 def new_vminstance(self, name, description, start, image_id, flavor_id, net_list, cloud_config=None, disk_list=None,
1213 availability_zone_index=None, availability_zone_list=None):
tierno98e909c2017-10-14 13:27:03 +02001214 """Adds a VM instance to VIM
tierno7edb6752016-03-21 17:37:52 +01001215 Params:
1216 start: indicates if VM must start or boot in pause mode. Ignored
1217 image_id,flavor_id: iamge and flavor uuid
1218 net_list: list of interfaces, each one is a dictionary with:
1219 name:
1220 net_id: network uuid to connect
1221 vpci: virtual vcpi to assign, ignored because openstack lack #TODO
1222 model: interface model, ignored #TODO
1223 mac_address: used for SR-IOV ifaces #TODO for other types
1224 use: 'data', 'bridge', 'mgmt'
tierno66eba6e2017-11-10 17:09:18 +01001225 type: 'virtual', 'PCI-PASSTHROUGH'('PF'), 'SR-IOV'('VF'), 'VFnotShared'
tierno7edb6752016-03-21 17:37:52 +01001226 vim_id: filled/added by this function
ahmadsaf853d452016-12-22 11:33:47 +05001227 floating_ip: True/False (or it can be None)
tierno41a69812018-02-16 14:34:33 +01001228 'cloud_config': (optional) dictionary with:
tierno1d213f42020-04-24 14:02:51 +00001229 'key-pairs': (optional) list of strings with the public key to be inserted to the default user
1230 'users': (optional) list of users to be inserted, each item is a dict with:
1231 'name': (mandatory) user name,
1232 'key-pairs': (optional) list of strings with the public key to be inserted to the user
1233 'user-data': (optional) string is a text script to be passed directly to cloud-init
1234 'config-files': (optional). List of files to be transferred. Each item is a dict with:
1235 'dest': (mandatory) string with the destination absolute path
1236 'encoding': (optional, by default text). Can be one of:
1237 'b64', 'base64', 'gz', 'gz+b64', 'gz+base64', 'gzip+b64', 'gzip+base64'
1238 'content' (mandatory): string with the content of the file
1239 'permissions': (optional) string with file permissions, typically octal notation '0644'
1240 'owner': (optional) file owner, string with the format 'owner:group'
1241 'boot-data-drive': boolean to indicate if user-data must be passed using a boot drive (hard disk)
mirabal29356312017-07-27 12:21:22 +02001242 'disk_list': (optional) list with additional disks to the VM. Each item is a dict with:
1243 'image_id': (optional). VIM id of an existing image. If not provided an empty disk must be mounted
1244 'size': (mandatory) string with the size of the disk in GB
tierno1df468d2018-07-06 14:25:16 +02001245 'vim_id' (optional) should use this existing volume id
tierno5a3273c2017-08-29 11:43:46 +02001246 availability_zone_index: Index of availability_zone_list to use for this this VM. None if not AV required
1247 availability_zone_list: list of availability zones given by user in the VNFD descriptor. Ignore if
1248 availability_zone_index is None
tierno7edb6752016-03-21 17:37:52 +01001249 #TODO ip, security groups
tierno98e909c2017-10-14 13:27:03 +02001250 Returns a tuple with the instance identifier and created_items or raises an exception on error
1251 created_items can be None or a dictionary where this method can include key-values that will be passed to
1252 the method delete_vminstance and action_vminstance. Can be used to store created ports, volumes, etc.
1253 Format is vimconnector dependent, but do not use nested dictionaries and a value of None should be the same
1254 as not present.
1255 """
tierno1ec592d2020-06-16 15:29:47 +00001256 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 +01001257 try:
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001258 server = None
tierno98e909c2017-10-14 13:27:03 +02001259 created_items = {}
tiernob0b9dab2017-10-14 14:25:20 +02001260 # metadata = {}
tierno98e909c2017-10-14 13:27:03 +02001261 net_list_vim = []
tierno1ec592d2020-06-16 15:29:47 +00001262 external_network = []
1263 # ^list of external networks to be connected to instance, later on used to create floating_ip
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001264 no_secured_ports = [] # List of port-is with port-security disabled
tierno7edb6752016-03-21 17:37:52 +01001265 self._reload_connection()
tiernob0b9dab2017-10-14 14:25:20 +02001266 # metadata_vpci = {} # For a specific neutron plugin
tiernob84cbdc2017-07-07 14:30:30 +02001267 block_device_mapping = None
tiernoa05b65a2019-02-01 12:30:27 +00001268
tierno7edb6752016-03-21 17:37:52 +01001269 for net in net_list:
tierno98e909c2017-10-14 13:27:03 +02001270 if not net.get("net_id"): # skip non connected iface
tierno7edb6752016-03-21 17:37:52 +01001271 continue
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001272
tiernoa05b65a2019-02-01 12:30:27 +00001273 port_dict = {
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001274 "network_id": net["net_id"],
1275 "name": net.get("name"),
1276 "admin_state_up": True
1277 }
tiernoa05b65a2019-02-01 12:30:27 +00001278 if self.config.get("security_groups") and net.get("port_security") is not False and \
1279 not self.config.get("no_port_security_extension"):
1280 if not self.security_groups_id:
1281 self._get_ids_from_name()
1282 port_dict["security_groups"] = self.security_groups_id
1283
tierno1ec592d2020-06-16 15:29:47 +00001284 if net["type"] == "virtual":
tiernob0b9dab2017-10-14 14:25:20 +02001285 pass
1286 # if "vpci" in net:
1287 # metadata_vpci[ net["net_id"] ] = [[ net["vpci"], "" ]]
tierno66eba6e2017-11-10 17:09:18 +01001288 elif net["type"] == "VF" or net["type"] == "SR-IOV": # for VF
tiernob0b9dab2017-10-14 14:25:20 +02001289 # if "vpci" in net:
1290 # if "VF" not in metadata_vpci:
1291 # metadata_vpci["VF"]=[]
1292 # metadata_vpci["VF"].append([ net["vpci"], "" ])
tierno1ec592d2020-06-16 15:29:47 +00001293 port_dict["binding:vnic_type"] = "direct"
tiernob0b9dab2017-10-14 14:25:20 +02001294 # VIO specific Changes
kate721d79b2017-06-24 04:21:38 -07001295 if self.vim_type == "VIO":
tiernob0b9dab2017-10-14 14:25:20 +02001296 # Need to create port with port_security_enabled = False and no-security-groups
tierno1ec592d2020-06-16 15:29:47 +00001297 port_dict["port_security_enabled"] = False
1298 port_dict["provider_security_groups"] = []
1299 port_dict["security_groups"] = []
tierno66eba6e2017-11-10 17:09:18 +01001300 else: # For PT PCI-PASSTHROUGH
tiernob0b9dab2017-10-14 14:25:20 +02001301 # if "vpci" in net:
1302 # if "PF" not in metadata_vpci:
1303 # metadata_vpci["PF"]=[]
1304 # metadata_vpci["PF"].append([ net["vpci"], "" ])
tierno1ec592d2020-06-16 15:29:47 +00001305 port_dict["binding:vnic_type"] = "direct-physical"
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001306 if not port_dict["name"]:
tierno1ec592d2020-06-16 15:29:47 +00001307 port_dict["name"] = name
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001308 if net.get("mac_address"):
tierno1ec592d2020-06-16 15:29:47 +00001309 port_dict["mac_address"] = net["mac_address"]
tierno41a69812018-02-16 14:34:33 +01001310 if net.get("ip_address"):
1311 port_dict["fixed_ips"] = [{'ip_address': net["ip_address"]}]
1312 # TODO add 'subnet_id': <subnet_id>
tierno1ec592d2020-06-16 15:29:47 +00001313 new_port = self.neutron.create_port({"port": port_dict})
tierno00e3df72017-11-29 17:20:13 +01001314 created_items["port:" + str(new_port["port"]["id"])] = True
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001315 net["mac_adress"] = new_port["port"]["mac_address"]
1316 net["vim_id"] = new_port["port"]["id"]
tiernob84cbdc2017-07-07 14:30:30 +02001317 # if try to use a network without subnetwork, it will return a emtpy list
1318 fixed_ips = new_port["port"].get("fixed_ips")
1319 if fixed_ips:
1320 net["ip"] = fixed_ips[0].get("ip_address")
1321 else:
1322 net["ip"] = None
montesmoreno994a29d2017-08-22 11:23:06 +02001323
1324 port = {"port-id": new_port["port"]["id"]}
1325 if float(self.nova.api_version.get_string()) >= 2.32:
1326 port["tag"] = new_port["port"]["name"]
1327 net_list_vim.append(port)
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001328
ahmadsaf853d452016-12-22 11:33:47 +05001329 if net.get('floating_ip', False):
tiernof8383b82017-01-18 15:49:48 +01001330 net['exit_on_floating_ip_error'] = True
ahmadsaf853d452016-12-22 11:33:47 +05001331 external_network.append(net)
tiernof8383b82017-01-18 15:49:48 +01001332 elif net['use'] == 'mgmt' and self.config.get('use_floating_ip'):
1333 net['exit_on_floating_ip_error'] = False
1334 external_network.append(net)
tierno326fd5e2018-02-22 11:58:59 +01001335 net['floating_ip'] = self.config.get('use_floating_ip')
tiernof8383b82017-01-18 15:49:48 +01001336
tierno1ec592d2020-06-16 15:29:47 +00001337 # If port security is disabled when the port has not yet been attached to the VM, then all vm traffic
1338 # is dropped.
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001339 # As a workaround we wait until the VM is active and then disable the port-security
tierno1ec592d2020-06-16 15:29:47 +00001340 if net.get("port_security") is False and not self.config.get("no_port_security_extension"):
bravof7a1f5252020-10-20 10:27:42 -03001341 no_secured_ports.append((new_port["port"]["id"], net.get("port_security_disable_strategy")))
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001342
tiernob0b9dab2017-10-14 14:25:20 +02001343 # if metadata_vpci:
1344 # metadata = {"pci_assignement": json.dumps(metadata_vpci)}
1345 # if len(metadata["pci_assignement"]) >255:
1346 # #limit the metadata size
1347 # #metadata["pci_assignement"] = metadata["pci_assignement"][0:255]
1348 # self.logger.warn("Metadata deleted since it exceeds the expected length (255) ")
1349 # metadata = {}
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001350
tiernob0b9dab2017-10-14 14:25:20 +02001351 self.logger.debug("name '%s' image_id '%s'flavor_id '%s' net_list_vim '%s' description '%s'",
1352 name, image_id, flavor_id, str(net_list_vim), description)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001353
tierno98e909c2017-10-14 13:27:03 +02001354 # cloud config
tierno0a1437e2017-10-02 00:17:43 +02001355 config_drive, userdata = self._create_user_data(cloud_config)
montesmoreno0c8def02016-12-22 12:16:23 +00001356
tierno98e909c2017-10-14 13:27:03 +02001357 # Create additional volumes in case these are present in disk_list
montesmoreno0c8def02016-12-22 12:16:23 +00001358 base_disk_index = ord('b')
tierno1df468d2018-07-06 14:25:16 +02001359 if disk_list:
tiernob84cbdc2017-07-07 14:30:30 +02001360 block_device_mapping = {}
montesmoreno0c8def02016-12-22 12:16:23 +00001361 for disk in disk_list:
tierno1df468d2018-07-06 14:25:16 +02001362 if disk.get('vim_id'):
1363 block_device_mapping['_vd' + chr(base_disk_index)] = disk['vim_id']
montesmoreno0c8def02016-12-22 12:16:23 +00001364 else:
tierno1df468d2018-07-06 14:25:16 +02001365 if 'image_id' in disk:
1366 volume = self.cinder.volumes.create(size=disk['size'], name=name + '_vd' +
1367 chr(base_disk_index), imageRef=disk['image_id'])
1368 else:
1369 volume = self.cinder.volumes.create(size=disk['size'], name=name + '_vd' +
1370 chr(base_disk_index))
1371 created_items["volume:" + str(volume.id)] = True
1372 block_device_mapping['_vd' + chr(base_disk_index)] = volume.id
montesmoreno0c8def02016-12-22 12:16:23 +00001373 base_disk_index += 1
1374
tierno1df468d2018-07-06 14:25:16 +02001375 # Wait until created volumes are with status available
montesmoreno0c8def02016-12-22 12:16:23 +00001376 elapsed_time = 0
tierno1df468d2018-07-06 14:25:16 +02001377 while elapsed_time < volume_timeout:
1378 for created_item in created_items:
1379 v, _, volume_id = created_item.partition(":")
1380 if v == 'volume':
1381 if self.cinder.volumes.get(volume_id).status != 'available':
1382 break
1383 else: # all ready: break from while
1384 break
1385 time.sleep(5)
1386 elapsed_time += 5
tiernob0b9dab2017-10-14 14:25:20 +02001387 # If we exceeded the timeout rollback
montesmoreno0c8def02016-12-22 12:16:23 +00001388 if elapsed_time >= volume_timeout:
tierno72774862020-05-04 11:44:15 +00001389 raise vimconn.VimConnException('Timeout creating volumes for instance ' + name,
montesmoreno0c8def02016-12-22 12:16:23 +00001390 http_code=vimconn.HTTP_Request_Timeout)
mirabal29356312017-07-27 12:21:22 +02001391 # get availability Zone
tierno5a3273c2017-08-29 11:43:46 +02001392 vm_av_zone = self._get_vm_availability_zone(availability_zone_index, availability_zone_list)
montesmoreno0c8def02016-12-22 12:16:23 +00001393
tiernob0b9dab2017-10-14 14:25:20 +02001394 self.logger.debug("nova.servers.create({}, {}, {}, nics={}, security_groups={}, "
mirabal29356312017-07-27 12:21:22 +02001395 "availability_zone={}, key_name={}, userdata={}, config_drive={}, "
tiernob0b9dab2017-10-14 14:25:20 +02001396 "block_device_mapping={})".format(name, image_id, flavor_id, net_list_vim,
tiernoa05b65a2019-02-01 12:30:27 +00001397 self.config.get("security_groups"), vm_av_zone,
1398 self.config.get('keypair'), userdata, config_drive,
1399 block_device_mapping))
tiernob0b9dab2017-10-14 14:25:20 +02001400 server = self.nova.servers.create(name, image_id, flavor_id, nics=net_list_vim,
tiernoa05b65a2019-02-01 12:30:27 +00001401 security_groups=self.config.get("security_groups"),
1402 # TODO remove security_groups in future versions. Already at neutron port
mirabal29356312017-07-27 12:21:22 +02001403 availability_zone=vm_av_zone,
montesmoreno0c8def02016-12-22 12:16:23 +00001404 key_name=self.config.get('keypair'),
1405 userdata=userdata,
tiernob84cbdc2017-07-07 14:30:30 +02001406 config_drive=config_drive,
1407 block_device_mapping=block_device_mapping
montesmoreno0c8def02016-12-22 12:16:23 +00001408 ) # , description=description)
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001409
tierno326fd5e2018-02-22 11:58:59 +01001410 vm_start_time = time.time()
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001411 # Previously mentioned workaround to wait until the VM is active and then disable the port-security
1412 if no_secured_ports:
1413 self.__wait_for_vm(server.id, 'ACTIVE')
1414
bravof7a1f5252020-10-20 10:27:42 -03001415 for port in no_secured_ports:
1416 port_update = {
1417 "port": {
1418 "port_security_enabled": False,
1419 "security_groups": None
1420 }
1421 }
1422
1423 if port[1] == "allow-address-pairs":
1424 port_update = {
1425 "port": {
1426 "allowed_address_pairs": [
1427 {
1428 "ip_address": "0.0.0.0/0"
1429 }
1430 ]
1431 }
1432 }
1433
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001434 try:
bravof7a1f5252020-10-20 10:27:42 -03001435 self.neutron.update_port(port[0], port_update)
tierno1ec592d2020-06-16 15:29:47 +00001436 except Exception:
bravof7a1f5252020-10-20 10:27:42 -03001437 raise vimconn.VimConnException(
1438 "It was not possible to disable port security for port {}"
1439 .format(port[0])
1440 )
1441
tierno98e909c2017-10-14 13:27:03 +02001442 # print "DONE :-)", server
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001443
tierno4d1ce222018-04-06 10:41:06 +02001444 # pool_id = None
ahmadsaf853d452016-12-22 11:33:47 +05001445 for floating_network in external_network:
tiernof8383b82017-01-18 15:49:48 +01001446 try:
tiernof8383b82017-01-18 15:49:48 +01001447 assigned = False
tiernocb66c7e2020-07-22 10:42:58 +00001448 floating_ip_retries = 3
1449 # In case of RO in HA there can be conflicts, two RO trying to assign same floating IP, so retry
1450 # several times
tierno98e909c2017-10-14 13:27:03 +02001451 while not assigned:
tiernocb66c7e2020-07-22 10:42:58 +00001452 floating_ips = self.neutron.list_floatingips().get("floatingips", ())
1453 random.shuffle(floating_ips) # randomize
1454 for fip in floating_ips:
1455 if fip.get("port_id") or fip.get('tenant_id') != server.tenant_id:
tierno326fd5e2018-02-22 11:58:59 +01001456 continue
1457 if isinstance(floating_network['floating_ip'], str):
tiernocb66c7e2020-07-22 10:42:58 +00001458 if fip.get("floating_network_id") != floating_network['floating_ip']:
tierno326fd5e2018-02-22 11:58:59 +01001459 continue
tiernocb66c7e2020-07-22 10:42:58 +00001460 free_floating_ip = fip["id"]
1461 break
tiernof8383b82017-01-18 15:49:48 +01001462 else:
tiernocb3cca22018-05-31 15:08:52 +02001463 if isinstance(floating_network['floating_ip'], str) and \
tierno1ec592d2020-06-16 15:29:47 +00001464 floating_network['floating_ip'].lower() != "true":
tierno326fd5e2018-02-22 11:58:59 +01001465 pool_id = floating_network['floating_ip']
1466 else:
tierno4d1ce222018-04-06 10:41:06 +02001467 # Find the external network
tierno326fd5e2018-02-22 11:58:59 +01001468 external_nets = list()
1469 for net in self.neutron.list_networks()['networks']:
1470 if net['router:external']:
tierno1ec592d2020-06-16 15:29:47 +00001471 external_nets.append(net)
tiernof8383b82017-01-18 15:49:48 +01001472
tierno326fd5e2018-02-22 11:58:59 +01001473 if len(external_nets) == 0:
tierno1ec592d2020-06-16 15:29:47 +00001474 raise vimconn.VimConnException(
1475 "Cannot create floating_ip automatically since no external network is present",
1476 http_code=vimconn.HTTP_Conflict)
tierno326fd5e2018-02-22 11:58:59 +01001477 if len(external_nets) > 1:
tierno1ec592d2020-06-16 15:29:47 +00001478 raise vimconn.VimConnException(
1479 "Cannot create floating_ip automatically since multiple external networks are"
1480 " present", http_code=vimconn.HTTP_Conflict)
tiernof8383b82017-01-18 15:49:48 +01001481
tierno326fd5e2018-02-22 11:58:59 +01001482 pool_id = external_nets[0].get('id')
tiernof8383b82017-01-18 15:49:48 +01001483 param = {'floatingip': {'floating_network_id': pool_id, 'tenant_id': server.tenant_id}}
ahmadsaf853d452016-12-22 11:33:47 +05001484 try:
tierno4d1ce222018-04-06 10:41:06 +02001485 # self.logger.debug("Creating floating IP")
tiernof8383b82017-01-18 15:49:48 +01001486 new_floating_ip = self.neutron.create_floatingip(param)
tierno7d782ef2019-10-04 12:56:31 +00001487 free_floating_ip = new_floating_ip['floatingip']['id']
tiernocb66c7e2020-07-22 10:42:58 +00001488 created_items["floating_ip:" + str(free_floating_ip)] = True
ahmadsaf853d452016-12-22 11:33:47 +05001489 except Exception as e:
tierno72774862020-05-04 11:44:15 +00001490 raise vimconn.VimConnException(type(e).__name__ + ": Cannot create new floating_ip " +
tierno326fd5e2018-02-22 11:58:59 +01001491 str(e), http_code=vimconn.HTTP_Conflict)
1492
tiernocb66c7e2020-07-22 10:42:58 +00001493 try:
1494 # for race condition ensure not already assigned
1495 fip = self.neutron.show_floatingip(free_floating_ip)
1496 if fip['floatingip']['port_id']:
1497 continue
1498 # the vim_id key contains the neutron.port_id
1499 self.neutron.update_floatingip(free_floating_ip,
1500 {"floatingip": {"port_id": floating_network["vim_id"]}})
1501 # for race condition ensure not re-assigned to other VM after 5 seconds
1502 time.sleep(5)
1503 fip = self.neutron.show_floatingip(free_floating_ip)
1504 if fip['floatingip']['port_id'] != floating_network["vim_id"]:
1505 self.logger.error("floating_ip {} re-assigned to other port".format(free_floating_ip))
1506 continue
1507 self.logger.debug("Assigned floating_ip {} to VM {}".format(free_floating_ip, server.id))
1508 assigned = True
1509 except Exception as e:
1510 # openstack need some time after VM creation to assign an IP. So retry if fails
1511 vm_status = self.nova.servers.get(server.id).status
1512 if vm_status not in ('ACTIVE', 'ERROR'):
1513 if time.time() - vm_start_time < server_timeout:
1514 time.sleep(5)
1515 continue
1516 elif floating_ip_retries > 0:
1517 floating_ip_retries -= 1
1518 continue
1519 raise vimconn.VimConnException(
1520 "Cannot create floating_ip: {} {}".format(type(e).__name__, e),
1521 http_code=vimconn.HTTP_Conflict)
tierno326fd5e2018-02-22 11:58:59 +01001522
tiernof8383b82017-01-18 15:49:48 +01001523 except Exception as e:
1524 if not floating_network['exit_on_floating_ip_error']:
tiernocb66c7e2020-07-22 10:42:58 +00001525 self.logger.error("Cannot create floating_ip. %s", str(e))
tiernof8383b82017-01-18 15:49:48 +01001526 continue
tiernof8383b82017-01-18 15:49:48 +01001527 raise
montesmoreno2a1fc4e2017-01-09 16:46:04 +00001528
tierno98e909c2017-10-14 13:27:03 +02001529 return server.id, created_items
tierno1ec592d2020-06-16 15:29:47 +00001530 # except nvExceptions.NotFound as e:
1531 # error_value=-vimconn.HTTP_Not_Found
1532 # error_text= "vm instance %s not found" % vm_id
1533 # except TypeError as e:
1534 # raise vimconn.VimConnException(type(e).__name__ + ": "+ str(e), http_code=vimconn.HTTP_Bad_Request)
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001535
1536 except Exception as e:
tierno98e909c2017-10-14 13:27:03 +02001537 server_id = None
1538 if server:
1539 server_id = server.id
1540 try:
1541 self.delete_vminstance(server_id, created_items)
1542 except Exception as e2:
1543 self.logger.error("new_vminstance rollback fail {}".format(e2))
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001544
tiernoae4a8d12016-07-08 12:30:39 +02001545 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001546
tierno1ec592d2020-06-16 15:29:47 +00001547 def get_vminstance(self, vm_id):
1548 """Returns the VM instance information from VIM"""
1549 # self.logger.debug("Getting VM from VIM")
tierno7edb6752016-03-21 17:37:52 +01001550 try:
1551 self._reload_connection()
1552 server = self.nova.servers.find(id=vm_id)
tierno1ec592d2020-06-16 15:29:47 +00001553 # TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
tiernoae4a8d12016-07-08 12:30:39 +02001554 return server.to_dict()
tierno1ec592d2020-06-16 15:29:47 +00001555 except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound,
1556 ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001557 self._format_exception(e)
1558
tierno1ec592d2020-06-16 15:29:47 +00001559 def get_vminstance_console(self, vm_id, console_type="vnc"):
1560 """
tierno7edb6752016-03-21 17:37:52 +01001561 Get a console for the virtual machine
1562 Params:
1563 vm_id: uuid of the VM
1564 console_type, can be:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001565 "novnc" (by default), "xvpvnc" for VNC types,
tierno7edb6752016-03-21 17:37:52 +01001566 "rdp-html5" for RDP types, "spice-html5" for SPICE types
tiernoae4a8d12016-07-08 12:30:39 +02001567 Returns dict with the console parameters:
1568 protocol: ssh, ftp, http, https, ...
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001569 server: usually ip address
1570 port: the http, ssh, ... port
1571 suffix: extra text, e.g. the http path and query string
tierno1ec592d2020-06-16 15:29:47 +00001572 """
tiernoae4a8d12016-07-08 12:30:39 +02001573 self.logger.debug("Getting VM CONSOLE from VIM")
tierno7edb6752016-03-21 17:37:52 +01001574 try:
1575 self._reload_connection()
1576 server = self.nova.servers.find(id=vm_id)
tierno1ec592d2020-06-16 15:29:47 +00001577 if console_type is None or console_type == "novnc":
tierno7edb6752016-03-21 17:37:52 +01001578 console_dict = server.get_vnc_console("novnc")
1579 elif console_type == "xvpvnc":
1580 console_dict = server.get_vnc_console(console_type)
1581 elif console_type == "rdp-html5":
1582 console_dict = server.get_rdp_console(console_type)
1583 elif console_type == "spice-html5":
1584 console_dict = server.get_spice_console(console_type)
1585 else:
tierno1ec592d2020-06-16 15:29:47 +00001586 raise vimconn.VimConnException("console type '{}' not allowed".format(console_type),
1587 http_code=vimconn.HTTP_Bad_Request)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001588
tierno7edb6752016-03-21 17:37:52 +01001589 console_dict1 = console_dict.get("console")
1590 if console_dict1:
1591 console_url = console_dict1.get("url")
1592 if console_url:
tierno1ec592d2020-06-16 15:29:47 +00001593 # parse console_url
tierno7edb6752016-03-21 17:37:52 +01001594 protocol_index = console_url.find("//")
1595 suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2
1596 port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2
tierno1ec592d2020-06-16 15:29:47 +00001597 if protocol_index < 0 or port_index < 0 or suffix_index < 0:
tierno7edb6752016-03-21 17:37:52 +01001598 return -vimconn.HTTP_Internal_Server_Error, "Unexpected response from VIM"
tierno1ec592d2020-06-16 15:29:47 +00001599 console_dict = {"protocol": console_url[0:protocol_index],
1600 "server": console_url[protocol_index+2:port_index],
1601 "port": console_url[port_index:suffix_index],
1602 "suffix": console_url[suffix_index+1:]
1603 }
tierno7edb6752016-03-21 17:37:52 +01001604 protocol_index += 2
tiernoae4a8d12016-07-08 12:30:39 +02001605 return console_dict
tierno72774862020-05-04 11:44:15 +00001606 raise vimconn.VimConnUnexpectedResponse("Unexpected response from VIM")
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001607
tierno1ec592d2020-06-16 15:29:47 +00001608 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException,
1609 nvExceptions.BadRequest, ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001610 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001611
tierno98e909c2017-10-14 13:27:03 +02001612 def delete_vminstance(self, vm_id, created_items=None):
tierno1ec592d2020-06-16 15:29:47 +00001613 """Removes a VM instance from VIM. Returns the old identifier
1614 """
1615 # print "osconnector: Getting VM from VIM"
1616 if created_items is None:
tierno98e909c2017-10-14 13:27:03 +02001617 created_items = {}
tierno7edb6752016-03-21 17:37:52 +01001618 try:
1619 self._reload_connection()
tierno98e909c2017-10-14 13:27:03 +02001620 # delete VM ports attached to this networks before the virtual machine
1621 for k, v in created_items.items():
1622 if not v: # skip already deleted
1623 continue
tierno7edb6752016-03-21 17:37:52 +01001624 try:
tiernoad6bdd42018-01-10 10:43:46 +01001625 k_item, _, k_id = k.partition(":")
1626 if k_item == "port":
1627 self.neutron.delete_port(k_id)
tierno7edb6752016-03-21 17:37:52 +01001628 except Exception as e:
tierno00e3df72017-11-29 17:20:13 +01001629 self.logger.error("Error deleting port: {}: {}".format(type(e).__name__, e))
montesmoreno0c8def02016-12-22 12:16:23 +00001630
tierno98e909c2017-10-14 13:27:03 +02001631 # #commented because detaching the volumes makes the servers.delete not work properly ?!?
1632 # #dettach volumes attached
1633 # server = self.nova.servers.get(vm_id)
1634 # volumes_attached_dict = server._info['os-extended-volumes:volumes_attached'] #volume['id']
1635 # #for volume in volumes_attached_dict:
1636 # # self.cinder.volumes.detach(volume['id'])
montesmoreno0c8def02016-12-22 12:16:23 +00001637
tierno98e909c2017-10-14 13:27:03 +02001638 if vm_id:
1639 self.nova.servers.delete(vm_id)
montesmoreno0c8def02016-12-22 12:16:23 +00001640
tierno98e909c2017-10-14 13:27:03 +02001641 # delete volumes. Although having detached, they should have in active status before deleting
1642 # we ensure in this loop
montesmoreno0c8def02016-12-22 12:16:23 +00001643 keep_waiting = True
1644 elapsed_time = 0
1645 while keep_waiting and elapsed_time < volume_timeout:
1646 keep_waiting = False
tierno98e909c2017-10-14 13:27:03 +02001647 for k, v in created_items.items():
1648 if not v: # skip already deleted
1649 continue
1650 try:
tiernoad6bdd42018-01-10 10:43:46 +01001651 k_item, _, k_id = k.partition(":")
1652 if k_item == "volume":
1653 if self.cinder.volumes.get(k_id).status != 'available':
tierno98e909c2017-10-14 13:27:03 +02001654 keep_waiting = True
1655 else:
tiernoad6bdd42018-01-10 10:43:46 +01001656 self.cinder.volumes.delete(k_id)
tiernocb66c7e2020-07-22 10:42:58 +00001657 created_items[k] = None
1658 elif k_item == "floating_ip": # floating ip
1659 self.neutron.delete_floatingip(k_id)
1660 created_items[k] = None
1661
tierno98e909c2017-10-14 13:27:03 +02001662 except Exception as e:
tiernocb66c7e2020-07-22 10:42:58 +00001663 self.logger.error("Error deleting {}: {}".format(k, e))
montesmoreno0c8def02016-12-22 12:16:23 +00001664 if keep_waiting:
1665 time.sleep(1)
1666 elapsed_time += 1
tierno98e909c2017-10-14 13:27:03 +02001667 return None
tierno1ec592d2020-06-16 15:29:47 +00001668 except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException,
1669 ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001670 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001671
tiernoae4a8d12016-07-08 12:30:39 +02001672 def refresh_vms_status(self, vm_list):
tierno1ec592d2020-06-16 15:29:47 +00001673 """Get the status of the virtual machines and their interfaces/ports
tiernoae4a8d12016-07-08 12:30:39 +02001674 Params: the list of VM identifiers
1675 Returns a dictionary with:
1676 vm_id: #VIM id of this Virtual Machine
1677 status: #Mandatory. Text with one of:
1678 # DELETED (not found at vim)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001679 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
tiernoae4a8d12016-07-08 12:30:39 +02001680 # OTHER (Vim reported other status not understood)
1681 # ERROR (VIM indicates an ERROR status)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001682 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
tiernoae4a8d12016-07-08 12:30:39 +02001683 # CREATING (on building process), ERROR
1684 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
1685 #
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001686 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
tiernoae4a8d12016-07-08 12:30:39 +02001687 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1688 interfaces:
1689 - vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1690 mac_address: #Text format XX:XX:XX:XX:XX:XX
1691 vim_net_id: #network id where this interface is connected
1692 vim_interface_id: #interface/port VIM id
1693 ip_address: #null, or text with IPv4, IPv6 address
tierno867ffe92017-03-27 12:50:34 +02001694 compute_node: #identification of compute node where PF,VF interface is allocated
1695 pci: #PCI address of the NIC that hosts the PF,VF
1696 vlan: #physical VLAN used for VF
tierno1ec592d2020-06-16 15:29:47 +00001697 """
1698 vm_dict = {}
tiernoae4a8d12016-07-08 12:30:39 +02001699 self.logger.debug("refresh_vms status: Getting tenant VM instance information from VIM")
1700 for vm_id in vm_list:
tierno1ec592d2020-06-16 15:29:47 +00001701 vm = {}
tiernoae4a8d12016-07-08 12:30:39 +02001702 try:
1703 vm_vim = self.get_vminstance(vm_id)
1704 if vm_vim['status'] in vmStatus2manoFormat:
tierno1ec592d2020-06-16 15:29:47 +00001705 vm['status'] = vmStatus2manoFormat[vm_vim['status']]
tierno7edb6752016-03-21 17:37:52 +01001706 else:
tierno1ec592d2020-06-16 15:29:47 +00001707 vm['status'] = "OTHER"
tiernoae4a8d12016-07-08 12:30:39 +02001708 vm['error_msg'] = "VIM status reported " + vm_vim['status']
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001709
1710 vm['vim_info'] = self.serialize(vm_vim)
1711
tiernoae4a8d12016-07-08 12:30:39 +02001712 vm["interfaces"] = []
1713 if vm_vim.get('fault'):
1714 vm['error_msg'] = str(vm_vim['fault'])
tierno1ec592d2020-06-16 15:29:47 +00001715 # get interfaces
tierno7edb6752016-03-21 17:37:52 +01001716 try:
tiernoae4a8d12016-07-08 12:30:39 +02001717 self._reload_connection()
tiernob42fd9b2018-06-20 10:44:32 +02001718 port_dict = self.neutron.list_ports(device_id=vm_id)
tiernoae4a8d12016-07-08 12:30:39 +02001719 for port in port_dict["ports"]:
tierno1ec592d2020-06-16 15:29:47 +00001720 interface = {}
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001721 interface['vim_info'] = self.serialize(port)
tiernoae4a8d12016-07-08 12:30:39 +02001722 interface["mac_address"] = port.get("mac_address")
1723 interface["vim_net_id"] = port["network_id"]
1724 interface["vim_interface_id"] = port["id"]
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001725 # check if OS-EXT-SRV-ATTR:host is there,
Mike Marchetti5b9da422017-05-02 15:35:47 -04001726 # in case of non-admin credentials, it will be missing
1727 if vm_vim.get('OS-EXT-SRV-ATTR:host'):
1728 interface["compute_node"] = vm_vim['OS-EXT-SRV-ATTR:host']
tierno867ffe92017-03-27 12:50:34 +02001729 interface["pci"] = None
Mike Marchetti5b9da422017-05-02 15:35:47 -04001730
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001731 # check if binding:profile is there,
Mike Marchetti5b9da422017-05-02 15:35:47 -04001732 # in case of non-admin credentials, it will be missing
1733 if port.get('binding:profile'):
1734 if port['binding:profile'].get('pci_slot'):
tierno1ec592d2020-06-16 15:29:47 +00001735 # TODO: At the moment sr-iov pci addresses are converted to PF pci addresses by setting
1736 # the slot to 0x00
Mike Marchetti5b9da422017-05-02 15:35:47 -04001737 # TODO: This is just a workaround valid for niantinc. Find a better way to do so
1738 # CHANGE DDDD:BB:SS.F to DDDD:BB:00.(F%2) assuming there are 2 ports per nic
1739 pci = port['binding:profile']['pci_slot']
1740 # interface["pci"] = pci[:-4] + "00." + str(int(pci[-1]) % 2)
1741 interface["pci"] = pci
tierno867ffe92017-03-27 12:50:34 +02001742 interface["vlan"] = None
tierno1dfe9932020-06-18 08:50:10 +00001743 if port.get('binding:vif_details'):
1744 interface["vlan"] = port['binding:vif_details'].get('vlan')
1745 # Get vlan from network in case not present in port for those old openstacks and cases where
1746 # it is needed vlan at PT
1747 if not interface["vlan"]:
1748 # if network is of type vlan and port is of type direct (sr-iov) then set vlan id
1749 network = self.neutron.show_network(port["network_id"])
1750 if network['network'].get('provider:network_type') == 'vlan':
1751 # and port.get("binding:vnic_type") in ("direct", "direct-physical"):
1752 interface["vlan"] = network['network'].get('provider:segmentation_id')
tierno1ec592d2020-06-16 15:29:47 +00001753 ips = []
1754 # look for floating ip address
tiernob42fd9b2018-06-20 10:44:32 +02001755 try:
1756 floating_ip_dict = self.neutron.list_floatingips(port_id=port["id"])
1757 if floating_ip_dict.get("floatingips"):
tierno1ec592d2020-06-16 15:29:47 +00001758 ips.append(floating_ip_dict["floatingips"][0].get("floating_ip_address"))
tiernob42fd9b2018-06-20 10:44:32 +02001759 except Exception:
1760 pass
tierno7edb6752016-03-21 17:37:52 +01001761
tiernoae4a8d12016-07-08 12:30:39 +02001762 for subnet in port["fixed_ips"]:
1763 ips.append(subnet["ip_address"])
1764 interface["ip_address"] = ";".join(ips)
1765 vm["interfaces"].append(interface)
1766 except Exception as e:
tiernob42fd9b2018-06-20 10:44:32 +02001767 self.logger.error("Error getting vm interface information {}: {}".format(type(e).__name__, e),
1768 exc_info=True)
tierno72774862020-05-04 11:44:15 +00001769 except vimconn.VimConnNotFoundException as e:
tiernoae4a8d12016-07-08 12:30:39 +02001770 self.logger.error("Exception getting vm status: %s", str(e))
1771 vm['status'] = "DELETED"
1772 vm['error_msg'] = str(e)
tierno72774862020-05-04 11:44:15 +00001773 except vimconn.VimConnException as e:
tiernoae4a8d12016-07-08 12:30:39 +02001774 self.logger.error("Exception getting vm status: %s", str(e))
1775 vm['status'] = "VIM_ERROR"
1776 vm['error_msg'] = str(e)
1777 vm_dict[vm_id] = vm
1778 return vm_dict
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001779
tierno98e909c2017-10-14 13:27:03 +02001780 def action_vminstance(self, vm_id, action_dict, created_items={}):
tierno1ec592d2020-06-16 15:29:47 +00001781 """Send and action over a VM instance from VIM
1782 Returns None or the console dict if the action was successfully sent to the VIM"""
tiernoae4a8d12016-07-08 12:30:39 +02001783 self.logger.debug("Action over VM '%s': %s", vm_id, str(action_dict))
tierno7edb6752016-03-21 17:37:52 +01001784 try:
1785 self._reload_connection()
1786 server = self.nova.servers.find(id=vm_id)
1787 if "start" in action_dict:
tierno1ec592d2020-06-16 15:29:47 +00001788 if action_dict["start"] == "rebuild":
tierno7edb6752016-03-21 17:37:52 +01001789 server.rebuild()
1790 else:
tierno1ec592d2020-06-16 15:29:47 +00001791 if server.status == "PAUSED":
tierno7edb6752016-03-21 17:37:52 +01001792 server.unpause()
tierno1ec592d2020-06-16 15:29:47 +00001793 elif server.status == "SUSPENDED":
tierno7edb6752016-03-21 17:37:52 +01001794 server.resume()
tierno1ec592d2020-06-16 15:29:47 +00001795 elif server.status == "SHUTOFF":
tierno7edb6752016-03-21 17:37:52 +01001796 server.start()
1797 elif "pause" in action_dict:
1798 server.pause()
1799 elif "resume" in action_dict:
1800 server.resume()
1801 elif "shutoff" in action_dict or "shutdown" in action_dict:
1802 server.stop()
1803 elif "forceOff" in action_dict:
tierno1ec592d2020-06-16 15:29:47 +00001804 server.stop() # TODO
tierno7edb6752016-03-21 17:37:52 +01001805 elif "terminate" in action_dict:
1806 server.delete()
1807 elif "createImage" in action_dict:
1808 server.create_image()
tierno1ec592d2020-06-16 15:29:47 +00001809 # "path":path_schema,
1810 # "description":description_schema,
1811 # "name":name_schema,
1812 # "metadata":metadata_schema,
1813 # "imageRef": id_schema,
1814 # "disk": {"oneOf":[{"type": "null"}, {"type":"string"}] },
tierno7edb6752016-03-21 17:37:52 +01001815 elif "rebuild" in action_dict:
1816 server.rebuild(server.image['id'])
1817 elif "reboot" in action_dict:
tierno1ec592d2020-06-16 15:29:47 +00001818 server.reboot() # reboot_type='SOFT'
tierno7edb6752016-03-21 17:37:52 +01001819 elif "console" in action_dict:
1820 console_type = action_dict["console"]
tierno1ec592d2020-06-16 15:29:47 +00001821 if console_type is None or console_type == "novnc":
tierno7edb6752016-03-21 17:37:52 +01001822 console_dict = server.get_vnc_console("novnc")
1823 elif console_type == "xvpvnc":
1824 console_dict = server.get_vnc_console(console_type)
1825 elif console_type == "rdp-html5":
1826 console_dict = server.get_rdp_console(console_type)
1827 elif console_type == "spice-html5":
1828 console_dict = server.get_spice_console(console_type)
1829 else:
tierno72774862020-05-04 11:44:15 +00001830 raise vimconn.VimConnException("console type '{}' not allowed".format(console_type),
tiernoae4a8d12016-07-08 12:30:39 +02001831 http_code=vimconn.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001832 try:
1833 console_url = console_dict["console"]["url"]
tierno1ec592d2020-06-16 15:29:47 +00001834 # parse console_url
tierno7edb6752016-03-21 17:37:52 +01001835 protocol_index = console_url.find("//")
1836 suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2
1837 port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2
tierno1ec592d2020-06-16 15:29:47 +00001838 if protocol_index < 0 or port_index < 0 or suffix_index < 0:
tierno72774862020-05-04 11:44:15 +00001839 raise vimconn.VimConnException("Unexpected response from VIM " + str(console_dict))
tierno1ec592d2020-06-16 15:29:47 +00001840 console_dict2 = {"protocol": console_url[0:protocol_index],
1841 "server": console_url[protocol_index+2: port_index],
1842 "port": int(console_url[port_index+1: suffix_index]),
1843 "suffix": console_url[suffix_index+1:]
1844 }
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001845 return console_dict2
tierno1ec592d2020-06-16 15:29:47 +00001846 except Exception:
tierno72774862020-05-04 11:44:15 +00001847 raise vimconn.VimConnException("Unexpected response from VIM " + str(console_dict))
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001848
tierno98e909c2017-10-14 13:27:03 +02001849 return None
tierno1ec592d2020-06-16 15:29:47 +00001850 except (ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.NotFound,
1851 ConnectionError) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001852 self._format_exception(e)
tierno1ec592d2020-06-16 15:29:47 +00001853 # TODO insert exception vimconn.HTTP_Unauthorized
tiernoae4a8d12016-07-08 12:30:39 +02001854
tierno1ec592d2020-06-16 15:29:47 +00001855 # ###### VIO Specific Changes #########
garciadeblasebd66722019-01-31 16:01:31 +00001856 def _generate_vlanID(self):
kate721d79b2017-06-24 04:21:38 -07001857 """
1858 Method to get unused vlanID
1859 Args:
1860 None
1861 Returns:
1862 vlanID
1863 """
tierno1ec592d2020-06-16 15:29:47 +00001864 # Get used VLAN IDs
kate721d79b2017-06-24 04:21:38 -07001865 usedVlanIDs = []
1866 networks = self.get_network_list()
1867 for net in networks:
1868 if net.get('provider:segmentation_id'):
1869 usedVlanIDs.append(net.get('provider:segmentation_id'))
1870 used_vlanIDs = set(usedVlanIDs)
1871
tierno1ec592d2020-06-16 15:29:47 +00001872 # find unused VLAN ID
kate721d79b2017-06-24 04:21:38 -07001873 for vlanID_range in self.config.get('dataplane_net_vlan_range'):
1874 try:
tierno1ec592d2020-06-16 15:29:47 +00001875 start_vlanid, end_vlanid = map(int, vlanID_range.replace(" ", "").split("-"))
tierno7d782ef2019-10-04 12:56:31 +00001876 for vlanID in range(start_vlanid, end_vlanid + 1):
kate721d79b2017-06-24 04:21:38 -07001877 if vlanID not in used_vlanIDs:
1878 return vlanID
1879 except Exception as exp:
tierno72774862020-05-04 11:44:15 +00001880 raise vimconn.VimConnException("Exception {} occurred while generating VLAN ID.".format(exp))
kate721d79b2017-06-24 04:21:38 -07001881 else:
tierno1ec592d2020-06-16 15:29:47 +00001882 raise vimconn.VimConnConflictException(
1883 "Unable to create the SRIOV VLAN network. All given Vlan IDs {} are in use.".format(
1884 self.config.get('dataplane_net_vlan_range')))
kate721d79b2017-06-24 04:21:38 -07001885
garciadeblasebd66722019-01-31 16:01:31 +00001886 def _generate_multisegment_vlanID(self):
1887 """
1888 Method to get unused vlanID
1889 Args:
1890 None
1891 Returns:
1892 vlanID
1893 """
tierno6869ae72020-01-09 17:37:34 +00001894 # Get used VLAN IDs
garciadeblasebd66722019-01-31 16:01:31 +00001895 usedVlanIDs = []
1896 networks = self.get_network_list()
1897 for net in networks:
1898 if net.get('provider:network_type') == "vlan" and net.get('provider:segmentation_id'):
1899 usedVlanIDs.append(net.get('provider:segmentation_id'))
1900 elif net.get('segments'):
1901 for segment in net.get('segments'):
1902 if segment.get('provider:network_type') == "vlan" and segment.get('provider:segmentation_id'):
1903 usedVlanIDs.append(segment.get('provider:segmentation_id'))
1904 used_vlanIDs = set(usedVlanIDs)
1905
tierno6869ae72020-01-09 17:37:34 +00001906 # find unused VLAN ID
garciadeblasebd66722019-01-31 16:01:31 +00001907 for vlanID_range in self.config.get('multisegment_vlan_range'):
1908 try:
tierno6869ae72020-01-09 17:37:34 +00001909 start_vlanid, end_vlanid = map(int, vlanID_range.replace(" ", "").split("-"))
tierno7d782ef2019-10-04 12:56:31 +00001910 for vlanID in range(start_vlanid, end_vlanid + 1):
garciadeblasebd66722019-01-31 16:01:31 +00001911 if vlanID not in used_vlanIDs:
1912 return vlanID
1913 except Exception as exp:
tierno72774862020-05-04 11:44:15 +00001914 raise vimconn.VimConnException("Exception {} occurred while generating VLAN ID.".format(exp))
garciadeblasebd66722019-01-31 16:01:31 +00001915 else:
tierno1ec592d2020-06-16 15:29:47 +00001916 raise vimconn.VimConnConflictException(
1917 "Unable to create the VLAN segment. All VLAN IDs {} are in use.".format(
1918 self.config.get('multisegment_vlan_range')))
garciadeblasebd66722019-01-31 16:01:31 +00001919
1920 def _validate_vlan_ranges(self, input_vlan_range, text_vlan_range):
kate721d79b2017-06-24 04:21:38 -07001921 """
1922 Method to validate user given vlanID ranges
1923 Args: None
1924 Returns: None
1925 """
garciadeblasebd66722019-01-31 16:01:31 +00001926 for vlanID_range in input_vlan_range:
kate721d79b2017-06-24 04:21:38 -07001927 vlan_range = vlanID_range.replace(" ", "")
tierno1ec592d2020-06-16 15:29:47 +00001928 # validate format
kate721d79b2017-06-24 04:21:38 -07001929 vlanID_pattern = r'(\d)*-(\d)*$'
1930 match_obj = re.match(vlanID_pattern, vlan_range)
1931 if not match_obj:
tierno1ec592d2020-06-16 15:29:47 +00001932 raise vimconn.VimConnConflictException(
1933 "Invalid VLAN range for {}: {}.You must provide '{}' in format [start_ID - end_ID].".format(
1934 text_vlan_range, vlanID_range, text_vlan_range))
kate721d79b2017-06-24 04:21:38 -07001935
tierno1ec592d2020-06-16 15:29:47 +00001936 start_vlanid, end_vlanid = map(int, vlan_range.split("-"))
1937 if start_vlanid <= 0:
1938 raise vimconn.VimConnConflictException(
1939 "Invalid VLAN range for {}: {}. Start ID can not be zero. For VLAN "
1940 "networks valid IDs are 1 to 4094 ".format(text_vlan_range, vlanID_range))
1941 if end_vlanid > 4094:
1942 raise vimconn.VimConnConflictException(
1943 "Invalid VLAN range for {}: {}. End VLAN ID can not be greater than 4094. For VLAN "
1944 "networks valid IDs are 1 to 4094 ".format(text_vlan_range, vlanID_range))
kate721d79b2017-06-24 04:21:38 -07001945
1946 if start_vlanid > end_vlanid:
tierno1ec592d2020-06-16 15:29:47 +00001947 raise vimconn.VimConnConflictException(
1948 "Invalid VLAN range for {}: {}. You must provide '{}' in format start_ID - end_ID and "
garciadeblasebd66722019-01-31 16:01:31 +00001949 "start_ID < end_ID ".format(text_vlan_range, vlanID_range, text_vlan_range))
kate721d79b2017-06-24 04:21:38 -07001950
tierno1ec592d2020-06-16 15:29:47 +00001951 # NOT USED FUNCTIONS
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001952
tiernoae4a8d12016-07-08 12:30:39 +02001953 def new_external_port(self, port_data):
tierno1ec592d2020-06-16 15:29:47 +00001954 """Adds a external port to VIM
1955 Returns the port identifier"""
1956 # TODO openstack if needed
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001957 return -vimconn.HTTP_Internal_Server_Error, "osconnector.new_external_port() not implemented"
1958
tiernoae4a8d12016-07-08 12:30:39 +02001959 def connect_port_network(self, port_id, network_id, admin=False):
tierno1ec592d2020-06-16 15:29:47 +00001960 """Connects a external port to a network
1961 Returns status code of the VIM response"""
1962 # TODO openstack if needed
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001963 return -vimconn.HTTP_Internal_Server_Error, "osconnector.connect_port_network() not implemented"
1964
tiernoae4a8d12016-07-08 12:30:39 +02001965 def new_user(self, user_name, user_passwd, tenant_id=None):
tierno1ec592d2020-06-16 15:29:47 +00001966 """Adds a new user to openstack VIM
1967 Returns the user identifier"""
tiernoae4a8d12016-07-08 12:30:39 +02001968 self.logger.debug("osconnector: Adding a new user to VIM")
1969 try:
1970 self._reload_connection()
tierno1ec592d2020-06-16 15:29:47 +00001971 user = self.keystone.users.create(user_name, password=user_passwd, default_project=tenant_id)
1972 # self.keystone.tenants.add_user(self.k_creds["username"], #role)
tiernoae4a8d12016-07-08 12:30:39 +02001973 return user.id
1974 except ksExceptions.ConnectionError as e:
tierno1ec592d2020-06-16 15:29:47 +00001975 error_value = -vimconn.HTTP_Bad_Request
1976 error_text = type(e).__name__ + ": " + (str(e) if len(e.args) == 0 else str(e.args[0]))
1977 except ksExceptions.ClientException as e: # TODO remove
1978 error_value = -vimconn.HTTP_Bad_Request
1979 error_text = type(e).__name__ + ": " + (str(e) if len(e.args) == 0 else str(e.args[0]))
1980 # TODO insert exception vimconn.HTTP_Unauthorized
1981 # if reaching here is because an exception
tierno9c5c8322018-03-23 15:44:03 +01001982 self.logger.debug("new_user " + error_text)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001983 return error_value, error_text
tiernoae4a8d12016-07-08 12:30:39 +02001984
1985 def delete_user(self, user_id):
tierno1ec592d2020-06-16 15:29:47 +00001986 """Delete a user from openstack VIM
1987 Returns the user identifier"""
tiernoae4a8d12016-07-08 12:30:39 +02001988 if self.debug:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001989 print("osconnector: Deleting a user from VIM")
tiernoae4a8d12016-07-08 12:30:39 +02001990 try:
1991 self._reload_connection()
1992 self.keystone.users.delete(user_id)
1993 return 1, user_id
1994 except ksExceptions.ConnectionError as e:
tierno1ec592d2020-06-16 15:29:47 +00001995 error_value = -vimconn.HTTP_Bad_Request
1996 error_text = type(e).__name__ + ": " + (str(e) if len(e.args) == 0 else str(e.args[0]))
tiernoae4a8d12016-07-08 12:30:39 +02001997 except ksExceptions.NotFound as e:
tierno1ec592d2020-06-16 15:29:47 +00001998 error_value = -vimconn.HTTP_Not_Found
1999 error_text = type(e).__name__ + ": " + (str(e) if len(e.args) == 0 else str(e.args[0]))
2000 except ksExceptions.ClientException as e: # TODO remove
2001 error_value = -vimconn.HTTP_Bad_Request
2002 error_text = type(e).__name__ + ": " + (str(e) if len(e.args) == 0 else str(e.args[0]))
2003 # TODO insert exception vimconn.HTTP_Unauthorized
2004 # if reaching here is because an exception
2005 self.logger.debug("delete_tenant " + error_text)
tiernoae4a8d12016-07-08 12:30:39 +02002006 return error_value, error_text
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002007
tierno7edb6752016-03-21 17:37:52 +01002008 def get_hosts_info(self):
tierno1ec592d2020-06-16 15:29:47 +00002009 """Get the information of deployed hosts
2010 Returns the hosts content"""
tierno7edb6752016-03-21 17:37:52 +01002011 if self.debug:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002012 print("osconnector: Getting Host info from VIM")
tierno7edb6752016-03-21 17:37:52 +01002013 try:
tierno1ec592d2020-06-16 15:29:47 +00002014 h_list = []
tierno7edb6752016-03-21 17:37:52 +01002015 self._reload_connection()
2016 hypervisors = self.nova.hypervisors.list()
2017 for hype in hypervisors:
tierno1ec592d2020-06-16 15:29:47 +00002018 h_list.append(hype.to_dict())
2019 return 1, {"hosts": h_list}
tierno7edb6752016-03-21 17:37:52 +01002020 except nvExceptions.NotFound as e:
tierno1ec592d2020-06-16 15:29:47 +00002021 error_value = -vimconn.HTTP_Not_Found
2022 error_text = (str(e) if len(e.args) == 0 else str(e.args[0]))
tierno7edb6752016-03-21 17:37:52 +01002023 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
tierno1ec592d2020-06-16 15:29:47 +00002024 error_value = -vimconn.HTTP_Bad_Request
2025 error_text = type(e).__name__ + ": " + (str(e) if len(e.args) == 0 else str(e.args[0]))
2026 # TODO insert exception vimconn.HTTP_Unauthorized
2027 # if reaching here is because an exception
tierno9c5c8322018-03-23 15:44:03 +01002028 self.logger.debug("get_hosts_info " + error_text)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002029 return error_value, error_text
tierno7edb6752016-03-21 17:37:52 +01002030
2031 def get_hosts(self, vim_tenant):
tierno1ec592d2020-06-16 15:29:47 +00002032 """Get the hosts and deployed instances
2033 Returns the hosts content"""
tierno7edb6752016-03-21 17:37:52 +01002034 r, hype_dict = self.get_hosts_info()
tierno1ec592d2020-06-16 15:29:47 +00002035 if r < 0:
tierno7edb6752016-03-21 17:37:52 +01002036 return r, hype_dict
2037 hypervisors = hype_dict["hosts"]
2038 try:
2039 servers = self.nova.servers.list()
2040 for hype in hypervisors:
2041 for server in servers:
tierno1ec592d2020-06-16 15:29:47 +00002042 if server.to_dict()['OS-EXT-SRV-ATTR:hypervisor_hostname'] == hype['hypervisor_hostname']:
tierno7edb6752016-03-21 17:37:52 +01002043 if 'vm' in hype:
2044 hype['vm'].append(server.id)
2045 else:
2046 hype['vm'] = [server.id]
2047 return 1, hype_dict
2048 except nvExceptions.NotFound as e:
tierno1ec592d2020-06-16 15:29:47 +00002049 error_value = -vimconn.HTTP_Not_Found
2050 error_text = (str(e) if len(e.args) == 0 else str(e.args[0]))
tierno7edb6752016-03-21 17:37:52 +01002051 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
tierno1ec592d2020-06-16 15:29:47 +00002052 error_value = -vimconn.HTTP_Bad_Request
2053 error_text = type(e).__name__ + ": " + (str(e) if len(e.args) == 0 else str(e.args[0]))
2054 # TODO insert exception vimconn.HTTP_Unauthorized
2055 # if reaching here is because an exception
tierno9c5c8322018-03-23 15:44:03 +01002056 self.logger.debug("get_hosts " + error_text)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002057 return error_value, error_text
tierno7edb6752016-03-21 17:37:52 +01002058
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002059 def new_classification(self, name, ctype, definition):
tierno7d782ef2019-10-04 12:56:31 +00002060 self.logger.debug('Adding a new (Traffic) Classification to VIM, named %s', name)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002061 try:
2062 new_class = None
2063 self._reload_connection()
2064 if ctype not in supportedClassificationTypes:
tierno72774862020-05-04 11:44:15 +00002065 raise vimconn.VimConnNotSupportedException(
tierno1ec592d2020-06-16 15:29:47 +00002066 'OpenStack VIM connector does not support provided Classification Type {}, supported ones are: '
2067 '{}'.format(ctype, supportedClassificationTypes))
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002068 if not self._validate_classification(ctype, definition):
tierno72774862020-05-04 11:44:15 +00002069 raise vimconn.VimConnException(
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002070 'Incorrect Classification definition '
2071 'for the type specified.')
2072 classification_dict = definition
2073 classification_dict['name'] = name
tierno7edb6752016-03-21 17:37:52 +01002074
Igor D.Ccaadc442017-11-06 12:48:48 +00002075 new_class = self.neutron.create_sfc_flow_classifier(
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002076 {'flow_classifier': classification_dict})
2077 return new_class['flow_classifier']['id']
2078 except (neExceptions.ConnectionFailed, ksExceptions.ClientException,
2079 neExceptions.NeutronException, ConnectionError) as e:
2080 self.logger.error(
2081 'Creation of Classification failed.')
2082 self._format_exception(e)
2083
2084 def get_classification(self, class_id):
2085 self.logger.debug(" Getting Classification %s from VIM", class_id)
2086 filter_dict = {"id": class_id}
2087 class_list = self.get_classification_list(filter_dict)
2088 if len(class_list) == 0:
tierno72774862020-05-04 11:44:15 +00002089 raise vimconn.VimConnNotFoundException(
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002090 "Classification '{}' not found".format(class_id))
2091 elif len(class_list) > 1:
tierno72774862020-05-04 11:44:15 +00002092 raise vimconn.VimConnConflictException(
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002093 "Found more than one Classification with this criteria")
2094 classification = class_list[0]
2095 return classification
2096
2097 def get_classification_list(self, filter_dict={}):
2098 self.logger.debug("Getting Classifications from VIM filter: '%s'",
2099 str(filter_dict))
2100 try:
tierno69b590e2018-03-13 18:52:23 +01002101 filter_dict_os = filter_dict.copy()
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002102 self._reload_connection()
tierno69b590e2018-03-13 18:52:23 +01002103 if self.api_version3 and "tenant_id" in filter_dict_os:
2104 filter_dict_os['project_id'] = filter_dict_os.pop('tenant_id')
Igor D.Ccaadc442017-11-06 12:48:48 +00002105 classification_dict = self.neutron.list_sfc_flow_classifiers(
tierno69b590e2018-03-13 18:52:23 +01002106 **filter_dict_os)
2107 classification_list = classification_dict["flow_classifiers"]
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002108 self.__classification_os2mano(classification_list)
2109 return classification_list
2110 except (neExceptions.ConnectionFailed, ksExceptions.ClientException,
2111 neExceptions.NeutronException, ConnectionError) as e:
2112 self._format_exception(e)
2113
2114 def delete_classification(self, class_id):
2115 self.logger.debug("Deleting Classification '%s' from VIM", class_id)
2116 try:
2117 self._reload_connection()
Igor D.Ccaadc442017-11-06 12:48:48 +00002118 self.neutron.delete_sfc_flow_classifier(class_id)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002119 return class_id
2120 except (neExceptions.ConnectionFailed, neExceptions.NeutronException,
2121 ksExceptions.ClientException, neExceptions.NeutronException,
2122 ConnectionError) as e:
2123 self._format_exception(e)
2124
2125 def new_sfi(self, name, ingress_ports, egress_ports, sfc_encap=True):
tierno7d782ef2019-10-04 12:56:31 +00002126 self.logger.debug("Adding a new Service Function Instance to VIM, named '%s'", name)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002127 try:
2128 new_sfi = None
2129 self._reload_connection()
2130 correlation = None
2131 if sfc_encap:
Igor D.Ccaadc442017-11-06 12:48:48 +00002132 correlation = 'nsh'
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002133 if len(ingress_ports) != 1:
tierno72774862020-05-04 11:44:15 +00002134 raise vimconn.VimConnNotSupportedException(
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002135 "OpenStack VIM connector can only have "
2136 "1 ingress port per SFI")
2137 if len(egress_ports) != 1:
tierno72774862020-05-04 11:44:15 +00002138 raise vimconn.VimConnNotSupportedException(
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002139 "OpenStack VIM connector can only have "
2140 "1 egress port per SFI")
2141 sfi_dict = {'name': name,
2142 'ingress': ingress_ports[0],
2143 'egress': egress_ports[0],
2144 'service_function_parameters': {
2145 'correlation': correlation}}
Igor D.Ccaadc442017-11-06 12:48:48 +00002146 new_sfi = self.neutron.create_sfc_port_pair({'port_pair': sfi_dict})
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002147 return new_sfi['port_pair']['id']
2148 except (neExceptions.ConnectionFailed, ksExceptions.ClientException,
2149 neExceptions.NeutronException, ConnectionError) as e:
2150 if new_sfi:
2151 try:
Igor D.Ccaadc442017-11-06 12:48:48 +00002152 self.neutron.delete_sfc_port_pair(
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002153 new_sfi['port_pair']['id'])
2154 except Exception:
2155 self.logger.error(
2156 'Creation of Service Function Instance failed, with '
2157 'subsequent deletion failure as well.')
2158 self._format_exception(e)
2159
2160 def get_sfi(self, sfi_id):
tierno7d782ef2019-10-04 12:56:31 +00002161 self.logger.debug('Getting Service Function Instance %s from VIM', sfi_id)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002162 filter_dict = {"id": sfi_id}
2163 sfi_list = self.get_sfi_list(filter_dict)
2164 if len(sfi_list) == 0:
tierno72774862020-05-04 11:44:15 +00002165 raise vimconn.VimConnNotFoundException("Service Function Instance '{}' not found".format(sfi_id))
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002166 elif len(sfi_list) > 1:
tierno72774862020-05-04 11:44:15 +00002167 raise vimconn.VimConnConflictException(
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002168 'Found more than one Service Function Instance '
2169 'with this criteria')
2170 sfi = sfi_list[0]
2171 return sfi
2172
2173 def get_sfi_list(self, filter_dict={}):
tierno7d782ef2019-10-04 12:56:31 +00002174 self.logger.debug("Getting Service Function Instances from VIM filter: '%s'", str(filter_dict))
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002175 try:
2176 self._reload_connection()
tierno69b590e2018-03-13 18:52:23 +01002177 filter_dict_os = filter_dict.copy()
2178 if self.api_version3 and "tenant_id" in filter_dict_os:
2179 filter_dict_os['project_id'] = filter_dict_os.pop('tenant_id')
2180 sfi_dict = self.neutron.list_sfc_port_pairs(**filter_dict_os)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002181 sfi_list = sfi_dict["port_pairs"]
2182 self.__sfi_os2mano(sfi_list)
2183 return sfi_list
2184 except (neExceptions.ConnectionFailed, ksExceptions.ClientException,
2185 neExceptions.NeutronException, ConnectionError) as e:
2186 self._format_exception(e)
2187
2188 def delete_sfi(self, sfi_id):
2189 self.logger.debug("Deleting Service Function Instance '%s' "
2190 "from VIM", sfi_id)
2191 try:
2192 self._reload_connection()
Igor D.Ccaadc442017-11-06 12:48:48 +00002193 self.neutron.delete_sfc_port_pair(sfi_id)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002194 return sfi_id
2195 except (neExceptions.ConnectionFailed, neExceptions.NeutronException,
2196 ksExceptions.ClientException, neExceptions.NeutronException,
2197 ConnectionError) as e:
2198 self._format_exception(e)
2199
2200 def new_sf(self, name, sfis, sfc_encap=True):
tierno7d782ef2019-10-04 12:56:31 +00002201 self.logger.debug("Adding a new Service Function to VIM, named '%s'", name)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002202 try:
2203 new_sf = None
2204 self._reload_connection()
tierno9c5c8322018-03-23 15:44:03 +01002205 # correlation = None
2206 # if sfc_encap:
2207 # correlation = 'nsh'
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002208 for instance in sfis:
2209 sfi = self.get_sfi(instance)
Igor D.Ccaadc442017-11-06 12:48:48 +00002210 if sfi.get('sfc_encap') != sfc_encap:
tierno72774862020-05-04 11:44:15 +00002211 raise vimconn.VimConnNotSupportedException(
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002212 "OpenStack VIM connector requires all SFIs of the "
2213 "same SF to share the same SFC Encapsulation")
2214 sf_dict = {'name': name,
2215 'port_pairs': sfis}
Igor D.Ccaadc442017-11-06 12:48:48 +00002216 new_sf = self.neutron.create_sfc_port_pair_group({
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002217 'port_pair_group': sf_dict})
2218 return new_sf['port_pair_group']['id']
2219 except (neExceptions.ConnectionFailed, ksExceptions.ClientException,
2220 neExceptions.NeutronException, ConnectionError) as e:
2221 if new_sf:
2222 try:
Igor D.Ccaadc442017-11-06 12:48:48 +00002223 self.neutron.delete_sfc_port_pair_group(
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002224 new_sf['port_pair_group']['id'])
2225 except Exception:
2226 self.logger.error(
2227 'Creation of Service Function failed, with '
2228 'subsequent deletion failure as well.')
2229 self._format_exception(e)
2230
2231 def get_sf(self, sf_id):
2232 self.logger.debug("Getting Service Function %s from VIM", sf_id)
2233 filter_dict = {"id": sf_id}
2234 sf_list = self.get_sf_list(filter_dict)
2235 if len(sf_list) == 0:
tierno72774862020-05-04 11:44:15 +00002236 raise vimconn.VimConnNotFoundException(
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002237 "Service Function '{}' not found".format(sf_id))
2238 elif len(sf_list) > 1:
tierno72774862020-05-04 11:44:15 +00002239 raise vimconn.VimConnConflictException(
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002240 "Found more than one Service Function with this criteria")
2241 sf = sf_list[0]
2242 return sf
2243
2244 def get_sf_list(self, filter_dict={}):
2245 self.logger.debug("Getting Service Function from VIM filter: '%s'",
2246 str(filter_dict))
2247 try:
2248 self._reload_connection()
tierno69b590e2018-03-13 18:52:23 +01002249 filter_dict_os = filter_dict.copy()
2250 if self.api_version3 and "tenant_id" in filter_dict_os:
2251 filter_dict_os['project_id'] = filter_dict_os.pop('tenant_id')
2252 sf_dict = self.neutron.list_sfc_port_pair_groups(**filter_dict_os)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002253 sf_list = sf_dict["port_pair_groups"]
2254 self.__sf_os2mano(sf_list)
2255 return sf_list
2256 except (neExceptions.ConnectionFailed, ksExceptions.ClientException,
2257 neExceptions.NeutronException, ConnectionError) as e:
2258 self._format_exception(e)
2259
2260 def delete_sf(self, sf_id):
2261 self.logger.debug("Deleting Service Function '%s' from VIM", sf_id)
2262 try:
2263 self._reload_connection()
Igor D.Ccaadc442017-11-06 12:48:48 +00002264 self.neutron.delete_sfc_port_pair_group(sf_id)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002265 return sf_id
2266 except (neExceptions.ConnectionFailed, neExceptions.NeutronException,
2267 ksExceptions.ClientException, neExceptions.NeutronException,
2268 ConnectionError) as e:
2269 self._format_exception(e)
2270
2271 def new_sfp(self, name, classifications, sfs, sfc_encap=True, spi=None):
tierno7d782ef2019-10-04 12:56:31 +00002272 self.logger.debug("Adding a new Service Function Path to VIM, named '%s'", name)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002273 try:
2274 new_sfp = None
2275 self._reload_connection()
Igor D.Ccaadc442017-11-06 12:48:48 +00002276 # In networking-sfc the MPLS encapsulation is legacy
2277 # should be used when no full SFC Encapsulation is intended
schillinge981df9a2019-01-24 09:25:11 +01002278 correlation = 'mpls'
Igor D.Ccaadc442017-11-06 12:48:48 +00002279 if sfc_encap:
2280 correlation = 'nsh'
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002281 sfp_dict = {'name': name,
2282 'flow_classifiers': classifications,
2283 'port_pair_groups': sfs,
2284 'chain_parameters': {'correlation': correlation}}
2285 if spi:
2286 sfp_dict['chain_id'] = spi
Igor D.Ccaadc442017-11-06 12:48:48 +00002287 new_sfp = self.neutron.create_sfc_port_chain({'port_chain': sfp_dict})
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002288 return new_sfp["port_chain"]["id"]
2289 except (neExceptions.ConnectionFailed, ksExceptions.ClientException,
2290 neExceptions.NeutronException, ConnectionError) as e:
2291 if new_sfp:
2292 try:
Igor D.Ccaadc442017-11-06 12:48:48 +00002293 self.neutron.delete_sfc_port_chain(new_sfp['port_chain']['id'])
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002294 except Exception:
2295 self.logger.error(
2296 'Creation of Service Function Path failed, with '
2297 'subsequent deletion failure as well.')
2298 self._format_exception(e)
2299
2300 def get_sfp(self, sfp_id):
2301 self.logger.debug(" Getting Service Function Path %s from VIM", sfp_id)
2302 filter_dict = {"id": sfp_id}
2303 sfp_list = self.get_sfp_list(filter_dict)
2304 if len(sfp_list) == 0:
tierno72774862020-05-04 11:44:15 +00002305 raise vimconn.VimConnNotFoundException(
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002306 "Service Function Path '{}' not found".format(sfp_id))
2307 elif len(sfp_list) > 1:
tierno72774862020-05-04 11:44:15 +00002308 raise vimconn.VimConnConflictException(
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002309 "Found more than one Service Function Path with this criteria")
2310 sfp = sfp_list[0]
2311 return sfp
2312
2313 def get_sfp_list(self, filter_dict={}):
tierno7d782ef2019-10-04 12:56:31 +00002314 self.logger.debug("Getting Service Function Paths from VIM filter: '%s'", str(filter_dict))
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002315 try:
2316 self._reload_connection()
tierno69b590e2018-03-13 18:52:23 +01002317 filter_dict_os = filter_dict.copy()
2318 if self.api_version3 and "tenant_id" in filter_dict_os:
2319 filter_dict_os['project_id'] = filter_dict_os.pop('tenant_id')
2320 sfp_dict = self.neutron.list_sfc_port_chains(**filter_dict_os)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002321 sfp_list = sfp_dict["port_chains"]
2322 self.__sfp_os2mano(sfp_list)
2323 return sfp_list
2324 except (neExceptions.ConnectionFailed, ksExceptions.ClientException,
2325 neExceptions.NeutronException, ConnectionError) as e:
2326 self._format_exception(e)
2327
2328 def delete_sfp(self, sfp_id):
tierno7d782ef2019-10-04 12:56:31 +00002329 self.logger.debug("Deleting Service Function Path '%s' from VIM", sfp_id)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002330 try:
2331 self._reload_connection()
Igor D.Ccaadc442017-11-06 12:48:48 +00002332 self.neutron.delete_sfc_port_chain(sfp_id)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002333 return sfp_id
2334 except (neExceptions.ConnectionFailed, neExceptions.NeutronException,
2335 ksExceptions.ClientException, neExceptions.NeutronException,
2336 ConnectionError) as e:
2337 self._format_exception(e)
borsatti8a2dda32019-12-18 15:08:57 +00002338
borsatti8a2dda32019-12-18 15:08:57 +00002339 def refresh_sfps_status(self, sfp_list):
tierno1ec592d2020-06-16 15:29:47 +00002340 """Get the status of the service function path
borsatti8a2dda32019-12-18 15:08:57 +00002341 Params: the list of sfp identifiers
2342 Returns a dictionary with:
2343 vm_id: #VIM id of this service function path
2344 status: #Mandatory. Text with one of:
2345 # DELETED (not found at vim)
2346 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
2347 # OTHER (Vim reported other status not understood)
2348 # ERROR (VIM indicates an ERROR status)
2349 # ACTIVE,
2350 # CREATING (on building process)
2351 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
2352 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)F
tierno1ec592d2020-06-16 15:29:47 +00002353 """
2354 sfp_dict = {}
borsatti8a2dda32019-12-18 15:08:57 +00002355 self.logger.debug("refresh_sfps status: Getting tenant SFP information from VIM")
2356 for sfp_id in sfp_list:
tierno1ec592d2020-06-16 15:29:47 +00002357 sfp = {}
borsatti8a2dda32019-12-18 15:08:57 +00002358 try:
2359 sfp_vim = self.get_sfp(sfp_id)
2360 if sfp_vim['spi']:
tierno1ec592d2020-06-16 15:29:47 +00002361 sfp['status'] = vmStatus2manoFormat['ACTIVE']
borsatti8a2dda32019-12-18 15:08:57 +00002362 else:
tierno1ec592d2020-06-16 15:29:47 +00002363 sfp['status'] = "OTHER"
2364 sfp['error_msg'] = "VIM status reported " + sfp['status']
borsatti8a2dda32019-12-18 15:08:57 +00002365
2366 sfp['vim_info'] = self.serialize(sfp_vim)
2367
2368 if sfp_vim.get('fault'):
2369 sfp['error_msg'] = str(sfp_vim['fault'])
2370
tierno72774862020-05-04 11:44:15 +00002371 except vimconn.VimConnNotFoundException as e:
borsatti8a2dda32019-12-18 15:08:57 +00002372 self.logger.error("Exception getting sfp status: %s", str(e))
2373 sfp['status'] = "DELETED"
2374 sfp['error_msg'] = str(e)
tierno72774862020-05-04 11:44:15 +00002375 except vimconn.VimConnException as e:
borsatti8a2dda32019-12-18 15:08:57 +00002376 self.logger.error("Exception getting sfp status: %s", str(e))
2377 sfp['status'] = "VIM_ERROR"
2378 sfp['error_msg'] = str(e)
2379 sfp_dict[sfp_id] = sfp
2380 return sfp_dict
2381
borsatti8a2dda32019-12-18 15:08:57 +00002382 def refresh_sfis_status(self, sfi_list):
tierno1ec592d2020-06-16 15:29:47 +00002383 """Get the status of the service function instances
borsatti8a2dda32019-12-18 15:08:57 +00002384 Params: the list of sfi identifiers
2385 Returns a dictionary with:
2386 vm_id: #VIM id of this service function instance
2387 status: #Mandatory. Text with one of:
2388 # DELETED (not found at vim)
2389 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
2390 # OTHER (Vim reported other status not understood)
2391 # ERROR (VIM indicates an ERROR status)
2392 # ACTIVE,
2393 # CREATING (on building process)
2394 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
2395 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
tierno1ec592d2020-06-16 15:29:47 +00002396 """
2397 sfi_dict = {}
borsatti8a2dda32019-12-18 15:08:57 +00002398 self.logger.debug("refresh_sfis status: Getting tenant sfi information from VIM")
2399 for sfi_id in sfi_list:
tierno1ec592d2020-06-16 15:29:47 +00002400 sfi = {}
borsatti8a2dda32019-12-18 15:08:57 +00002401 try:
2402 sfi_vim = self.get_sfi(sfi_id)
2403 if sfi_vim:
tierno1ec592d2020-06-16 15:29:47 +00002404 sfi['status'] = vmStatus2manoFormat['ACTIVE']
borsatti8a2dda32019-12-18 15:08:57 +00002405 else:
tierno1ec592d2020-06-16 15:29:47 +00002406 sfi['status'] = "OTHER"
2407 sfi['error_msg'] = "VIM status reported " + sfi['status']
borsatti8a2dda32019-12-18 15:08:57 +00002408
2409 sfi['vim_info'] = self.serialize(sfi_vim)
2410
2411 if sfi_vim.get('fault'):
2412 sfi['error_msg'] = str(sfi_vim['fault'])
2413
tierno72774862020-05-04 11:44:15 +00002414 except vimconn.VimConnNotFoundException as e:
borsatti8a2dda32019-12-18 15:08:57 +00002415 self.logger.error("Exception getting sfi status: %s", str(e))
2416 sfi['status'] = "DELETED"
2417 sfi['error_msg'] = str(e)
tierno72774862020-05-04 11:44:15 +00002418 except vimconn.VimConnException as e:
borsatti8a2dda32019-12-18 15:08:57 +00002419 self.logger.error("Exception getting sfi status: %s", str(e))
2420 sfi['status'] = "VIM_ERROR"
2421 sfi['error_msg'] = str(e)
2422 sfi_dict[sfi_id] = sfi
2423 return sfi_dict
2424
borsatti8a2dda32019-12-18 15:08:57 +00002425 def refresh_sfs_status(self, sf_list):
tierno1ec592d2020-06-16 15:29:47 +00002426 """Get the status of the service functions
borsatti8a2dda32019-12-18 15:08:57 +00002427 Params: the list of sf identifiers
2428 Returns a dictionary with:
2429 vm_id: #VIM id of this service function
2430 status: #Mandatory. Text with one of:
2431 # DELETED (not found at vim)
2432 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
2433 # OTHER (Vim reported other status not understood)
2434 # ERROR (VIM indicates an ERROR status)
2435 # ACTIVE,
2436 # CREATING (on building process)
2437 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
2438 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
tierno1ec592d2020-06-16 15:29:47 +00002439 """
2440 sf_dict = {}
borsatti8a2dda32019-12-18 15:08:57 +00002441 self.logger.debug("refresh_sfs status: Getting tenant sf information from VIM")
2442 for sf_id in sf_list:
tierno1ec592d2020-06-16 15:29:47 +00002443 sf = {}
borsatti8a2dda32019-12-18 15:08:57 +00002444 try:
2445 sf_vim = self.get_sf(sf_id)
2446 if sf_vim:
tierno1ec592d2020-06-16 15:29:47 +00002447 sf['status'] = vmStatus2manoFormat['ACTIVE']
borsatti8a2dda32019-12-18 15:08:57 +00002448 else:
tierno1ec592d2020-06-16 15:29:47 +00002449 sf['status'] = "OTHER"
2450 sf['error_msg'] = "VIM status reported " + sf_vim['status']
borsatti8a2dda32019-12-18 15:08:57 +00002451
2452 sf['vim_info'] = self.serialize(sf_vim)
2453
2454 if sf_vim.get('fault'):
2455 sf['error_msg'] = str(sf_vim['fault'])
2456
tierno72774862020-05-04 11:44:15 +00002457 except vimconn.VimConnNotFoundException as e:
borsatti8a2dda32019-12-18 15:08:57 +00002458 self.logger.error("Exception getting sf status: %s", str(e))
2459 sf['status'] = "DELETED"
2460 sf['error_msg'] = str(e)
tierno72774862020-05-04 11:44:15 +00002461 except vimconn.VimConnException as e:
borsatti8a2dda32019-12-18 15:08:57 +00002462 self.logger.error("Exception getting sf status: %s", str(e))
2463 sf['status'] = "VIM_ERROR"
2464 sf['error_msg'] = str(e)
2465 sf_dict[sf_id] = sf
2466 return sf_dict
2467
borsatti8a2dda32019-12-18 15:08:57 +00002468 def refresh_classifications_status(self, classification_list):
tierno1ec592d2020-06-16 15:29:47 +00002469 """Get the status of the classifications
borsatti8a2dda32019-12-18 15:08:57 +00002470 Params: the list of classification identifiers
2471 Returns a dictionary with:
2472 vm_id: #VIM id of this classifier
2473 status: #Mandatory. Text with one of:
2474 # DELETED (not found at vim)
2475 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
2476 # OTHER (Vim reported other status not understood)
2477 # ERROR (VIM indicates an ERROR status)
2478 # ACTIVE,
2479 # CREATING (on building process)
2480 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
2481 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
tierno1ec592d2020-06-16 15:29:47 +00002482 """
2483 classification_dict = {}
borsatti8a2dda32019-12-18 15:08:57 +00002484 self.logger.debug("refresh_classifications status: Getting tenant classification information from VIM")
2485 for classification_id in classification_list:
tierno1ec592d2020-06-16 15:29:47 +00002486 classification = {}
borsatti8a2dda32019-12-18 15:08:57 +00002487 try:
2488 classification_vim = self.get_classification(classification_id)
2489 if classification_vim:
tierno1ec592d2020-06-16 15:29:47 +00002490 classification['status'] = vmStatus2manoFormat['ACTIVE']
borsatti8a2dda32019-12-18 15:08:57 +00002491 else:
tierno1ec592d2020-06-16 15:29:47 +00002492 classification['status'] = "OTHER"
2493 classification['error_msg'] = "VIM status reported " + classification['status']
borsatti8a2dda32019-12-18 15:08:57 +00002494
2495 classification['vim_info'] = self.serialize(classification_vim)
2496
2497 if classification_vim.get('fault'):
2498 classification['error_msg'] = str(classification_vim['fault'])
2499
tierno72774862020-05-04 11:44:15 +00002500 except vimconn.VimConnNotFoundException as e:
borsatti8a2dda32019-12-18 15:08:57 +00002501 self.logger.error("Exception getting classification status: %s", str(e))
2502 classification['status'] = "DELETED"
2503 classification['error_msg'] = str(e)
tierno72774862020-05-04 11:44:15 +00002504 except vimconn.VimConnException as e:
borsatti8a2dda32019-12-18 15:08:57 +00002505 self.logger.error("Exception getting classification status: %s", str(e))
2506 classification['status'] = "VIM_ERROR"
2507 classification['error_msg'] = str(e)
2508 classification_dict[classification_id] = classification
2509 return classification_dict