blob: ab9ef3065c2c9fcf2ae3f48ef66e8637e0721d3e [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
sousaedu049cbb12022-01-05 11:39:35 +000033import copy
34from http.client import HTTPException
tiernoae4a8d12016-07-08 12:30:39 +020035import logging
sousaedu049cbb12022-01-05 11:39:35 +000036from pprint import pformat
garciadeblas2299e3b2017-01-26 14:35:55 +000037import random
kate721d79b2017-06-24 04:21:38 -070038import re
sousaedu049cbb12022-01-05 11:39:35 +000039import time
40
41from cinderclient import client as cClient
tiernob5cef372017-06-19 15:52:22 +020042from glanceclient import client as glClient
tierno7edb6752016-03-21 17:37:52 +010043import glanceclient.exc as gl1Exceptions
sousaedu049cbb12022-01-05 11:39:35 +000044from keystoneauth1 import session
45from keystoneauth1.identity import v2, v3
46import keystoneclient.exceptions as ksExceptions
47import keystoneclient.v2_0.client as ksClient_v2
48import keystoneclient.v3.client as ksClient_v3
49import netaddr
tierno7edb6752016-03-21 17:37:52 +010050from neutronclient.common import exceptions as neExceptions
sousaedu049cbb12022-01-05 11:39:35 +000051from neutronclient.neutron import client as neClient
52from novaclient import client as nClient, exceptions as nvExceptions
53from osm_ro_plugin import vimconn
tierno7edb6752016-03-21 17:37:52 +010054from requests.exceptions import ConnectionError
sousaedu049cbb12022-01-05 11:39:35 +000055import yaml
tierno7edb6752016-03-21 17:37:52 +010056
tierno1ec592d2020-06-16 15:29:47 +000057__author__ = "Alfonso Tierno, Gerardo Garcia, Pablo Montes, xFlow Research, Igor D.C., Eduardo Sousa"
58__date__ = "$22-sep-2017 23:59:59$"
tierno40e1bce2017-08-09 09:12:04 +020059
60"""contain the openstack virtual machine status to openmano status"""
sousaedu80135b92021-02-17 15:05:18 +010061vmStatus2manoFormat = {
62 "ACTIVE": "ACTIVE",
63 "PAUSED": "PAUSED",
64 "SUSPENDED": "SUSPENDED",
65 "SHUTOFF": "INACTIVE",
66 "BUILD": "BUILD",
67 "ERROR": "ERROR",
68 "DELETED": "DELETED",
69}
70netStatus2manoFormat = {
71 "ACTIVE": "ACTIVE",
72 "PAUSED": "PAUSED",
73 "INACTIVE": "INACTIVE",
74 "BUILD": "BUILD",
75 "ERROR": "ERROR",
76 "DELETED": "DELETED",
77}
tierno7edb6752016-03-21 17:37:52 +010078
sousaedu80135b92021-02-17 15:05:18 +010079supportedClassificationTypes = ["legacy_flow_classifier"]
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +000080
tierno1ec592d2020-06-16 15:29:47 +000081# global var to have a timeout creating and deleting volumes
garciadeblas64b39c52020-05-21 08:07:25 +000082volume_timeout = 1800
83server_timeout = 1800
montesmoreno0c8def02016-12-22 12:16:23 +000084
Anderson Bravalheri0446cd52018-08-17 15:26:19 +010085
86class SafeDumper(yaml.SafeDumper):
87 def represent_data(self, data):
88 # Openstack APIs use custom subclasses of dict and YAML safe dumper
89 # is designed to not handle that (reference issue 142 of pyyaml)
90 if isinstance(data, dict) and data.__class__ != dict:
91 # A simple solution is to convert those items back to dicts
92 data = dict(data.items())
93
94 return super(SafeDumper, self).represent_data(data)
95
96
tierno72774862020-05-04 11:44:15 +000097class vimconnector(vimconn.VimConnector):
sousaedu80135b92021-02-17 15:05:18 +010098 def __init__(
99 self,
100 uuid,
101 name,
102 tenant_id,
103 tenant_name,
104 url,
105 url_admin=None,
106 user=None,
107 passwd=None,
108 log_level=None,
109 config={},
110 persistent_info={},
111 ):
tierno1ec592d2020-06-16 15:29:47 +0000112 """using common constructor parameters. In this case
tierno7edb6752016-03-21 17:37:52 +0100113 'url' is the keystone authorization url,
114 'url_admin' is not use
tierno1ec592d2020-06-16 15:29:47 +0000115 """
sousaedu80135b92021-02-17 15:05:18 +0100116 api_version = config.get("APIversion")
kate721d79b2017-06-24 04:21:38 -0700117
sousaedu80135b92021-02-17 15:05:18 +0100118 if api_version and api_version not in ("v3.3", "v2.0", "2", "3"):
119 raise vimconn.VimConnException(
120 "Invalid value '{}' for config:APIversion. "
121 "Allowed values are 'v3.3', 'v2.0', '2' or '3'".format(api_version)
122 )
123
124 vim_type = config.get("vim_type")
125
126 if vim_type and vim_type not in ("vio", "VIO"):
127 raise vimconn.VimConnException(
128 "Invalid value '{}' for config:vim_type."
129 "Allowed values are 'vio' or 'VIO'".format(vim_type)
130 )
131
132 if config.get("dataplane_net_vlan_range") is not None:
tierno1ec592d2020-06-16 15:29:47 +0000133 # validate vlan ranges provided by user
sousaedu80135b92021-02-17 15:05:18 +0100134 self._validate_vlan_ranges(
135 config.get("dataplane_net_vlan_range"), "dataplane_net_vlan_range"
136 )
garciadeblasebd66722019-01-31 16:01:31 +0000137
sousaedu80135b92021-02-17 15:05:18 +0100138 if config.get("multisegment_vlan_range") is not None:
tierno1ec592d2020-06-16 15:29:47 +0000139 # validate vlan ranges provided by user
sousaedu80135b92021-02-17 15:05:18 +0100140 self._validate_vlan_ranges(
141 config.get("multisegment_vlan_range"), "multisegment_vlan_range"
142 )
kate721d79b2017-06-24 04:21:38 -0700143
sousaedu80135b92021-02-17 15:05:18 +0100144 vimconn.VimConnector.__init__(
145 self,
146 uuid,
147 name,
148 tenant_id,
149 tenant_name,
150 url,
151 url_admin,
152 user,
153 passwd,
154 log_level,
155 config,
156 )
tiernob3d36742017-03-03 23:51:05 +0100157
tierno4d1ce222018-04-06 10:41:06 +0200158 if self.config.get("insecure") and self.config.get("ca_cert"):
sousaedu80135b92021-02-17 15:05:18 +0100159 raise vimconn.VimConnException(
160 "options insecure and ca_cert are mutually exclusive"
161 )
162
tierno4d1ce222018-04-06 10:41:06 +0200163 self.verify = True
sousaedu80135b92021-02-17 15:05:18 +0100164
tierno4d1ce222018-04-06 10:41:06 +0200165 if self.config.get("insecure"):
166 self.verify = False
sousaedu80135b92021-02-17 15:05:18 +0100167
tierno4d1ce222018-04-06 10:41:06 +0200168 if self.config.get("ca_cert"):
169 self.verify = self.config.get("ca_cert")
tierno4d1ce222018-04-06 10:41:06 +0200170
tierno7edb6752016-03-21 17:37:52 +0100171 if not url:
sousaedu80135b92021-02-17 15:05:18 +0100172 raise TypeError("url param can not be NoneType")
173
tiernob5cef372017-06-19 15:52:22 +0200174 self.persistent_info = persistent_info
sousaedu80135b92021-02-17 15:05:18 +0100175 self.availability_zone = persistent_info.get("availability_zone", None)
176 self.session = persistent_info.get("session", {"reload_client": True})
177 self.my_tenant_id = self.session.get("my_tenant_id")
178 self.nova = self.session.get("nova")
179 self.neutron = self.session.get("neutron")
180 self.cinder = self.session.get("cinder")
181 self.glance = self.session.get("glance")
182 # self.glancev1 = self.session.get("glancev1")
183 self.keystone = self.session.get("keystone")
184 self.api_version3 = self.session.get("api_version3")
kate721d79b2017-06-24 04:21:38 -0700185 self.vim_type = self.config.get("vim_type")
sousaedu80135b92021-02-17 15:05:18 +0100186
kate721d79b2017-06-24 04:21:38 -0700187 if self.vim_type:
188 self.vim_type = self.vim_type.upper()
sousaedu80135b92021-02-17 15:05:18 +0100189
kate721d79b2017-06-24 04:21:38 -0700190 if self.config.get("use_internal_endpoint"):
191 self.endpoint_type = "internalURL"
192 else:
193 self.endpoint_type = None
montesmoreno0c8def02016-12-22 12:16:23 +0000194
sousaedu80135b92021-02-17 15:05:18 +0100195 logging.getLogger("urllib3").setLevel(logging.WARNING)
196 logging.getLogger("keystoneauth").setLevel(logging.WARNING)
197 logging.getLogger("novaclient").setLevel(logging.WARNING)
198 self.logger = logging.getLogger("ro.vim.openstack")
kate721d79b2017-06-24 04:21:38 -0700199
tiernoa05b65a2019-02-01 12:30:27 +0000200 # allow security_groups to be a list or a single string
sousaedu80135b92021-02-17 15:05:18 +0100201 if isinstance(self.config.get("security_groups"), str):
202 self.config["security_groups"] = [self.config["security_groups"]]
203
tiernoa05b65a2019-02-01 12:30:27 +0000204 self.security_groups_id = None
205
tierno1ec592d2020-06-16 15:29:47 +0000206 # ###### VIO Specific Changes #########
kate721d79b2017-06-24 04:21:38 -0700207 if self.vim_type == "VIO":
sousaedu80135b92021-02-17 15:05:18 +0100208 self.logger = logging.getLogger("ro.vim.vio")
kate721d79b2017-06-24 04:21:38 -0700209
tiernofe789902016-09-29 14:20:44 +0000210 if log_level:
tierno1ec592d2020-06-16 15:29:47 +0000211 self.logger.setLevel(getattr(logging, log_level))
tiernof716aea2017-06-21 18:01:40 +0200212
213 def __getitem__(self, index):
214 """Get individuals parameters.
215 Throw KeyError"""
sousaedu80135b92021-02-17 15:05:18 +0100216 if index == "project_domain_id":
tiernof716aea2017-06-21 18:01:40 +0200217 return self.config.get("project_domain_id")
sousaedu80135b92021-02-17 15:05:18 +0100218 elif index == "user_domain_id":
tiernof716aea2017-06-21 18:01:40 +0200219 return self.config.get("user_domain_id")
220 else:
tierno72774862020-05-04 11:44:15 +0000221 return vimconn.VimConnector.__getitem__(self, index)
tiernof716aea2017-06-21 18:01:40 +0200222
223 def __setitem__(self, index, value):
224 """Set individuals parameters and it is marked as dirty so to force connection reload.
225 Throw KeyError"""
sousaedu80135b92021-02-17 15:05:18 +0100226 if index == "project_domain_id":
tiernof716aea2017-06-21 18:01:40 +0200227 self.config["project_domain_id"] = value
sousaedu80135b92021-02-17 15:05:18 +0100228 elif index == "user_domain_id":
tierno1ec592d2020-06-16 15:29:47 +0000229 self.config["user_domain_id"] = value
tiernof716aea2017-06-21 18:01:40 +0200230 else:
tierno72774862020-05-04 11:44:15 +0000231 vimconn.VimConnector.__setitem__(self, index, value)
sousaedu80135b92021-02-17 15:05:18 +0100232
233 self.session["reload_client"] = True
tiernof716aea2017-06-21 18:01:40 +0200234
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100235 def serialize(self, value):
236 """Serialization of python basic types.
237
238 In the case value is not serializable a message will be logged and a
239 simple representation of the data that cannot be converted back to
240 python is returned.
241 """
tierno7d782ef2019-10-04 12:56:31 +0000242 if isinstance(value, str):
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100243 return value
244
245 try:
sousaedu80135b92021-02-17 15:05:18 +0100246 return yaml.dump(
247 value, Dumper=SafeDumper, default_flow_style=True, width=256
248 )
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100249 except yaml.representer.RepresenterError:
sousaedu80135b92021-02-17 15:05:18 +0100250 self.logger.debug(
251 "The following entity cannot be serialized in YAML:\n\n%s\n\n",
252 pformat(value),
253 exc_info=True,
254 )
255
tierno1ec592d2020-06-16 15:29:47 +0000256 return str(value)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100257
tierno7edb6752016-03-21 17:37:52 +0100258 def _reload_connection(self):
tierno1ec592d2020-06-16 15:29:47 +0000259 """Called before any operation, it check if credentials has changed
tierno7edb6752016-03-21 17:37:52 +0100260 Throw keystoneclient.apiclient.exceptions.AuthorizationFailure
tierno1ec592d2020-06-16 15:29:47 +0000261 """
262 # TODO control the timing and possible token timeout, but it seams that python client does this task for us :-)
sousaedu80135b92021-02-17 15:05:18 +0100263 if self.session["reload_client"]:
264 if self.config.get("APIversion"):
265 self.api_version3 = (
266 self.config["APIversion"] == "v3.3"
267 or self.config["APIversion"] == "3"
268 )
tiernof716aea2017-06-21 18:01:40 +0200269 else: # get from ending auth_url that end with v3 or with v2.0
sousaedu80135b92021-02-17 15:05:18 +0100270 self.api_version3 = self.url.endswith("/v3") or self.url.endswith(
271 "/v3/"
272 )
273
274 self.session["api_version3"] = self.api_version3
275
tiernof716aea2017-06-21 18:01:40 +0200276 if self.api_version3:
sousaedu80135b92021-02-17 15:05:18 +0100277 if self.config.get("project_domain_id") or self.config.get(
278 "project_domain_name"
279 ):
tierno3cb8dc32017-10-24 18:13:19 +0200280 project_domain_id_default = None
281 else:
sousaedu80135b92021-02-17 15:05:18 +0100282 project_domain_id_default = "default"
283
284 if self.config.get("user_domain_id") or self.config.get(
285 "user_domain_name"
286 ):
tierno3cb8dc32017-10-24 18:13:19 +0200287 user_domain_id_default = None
288 else:
sousaedu80135b92021-02-17 15:05:18 +0100289 user_domain_id_default = "default"
290 auth = v3.Password(
291 auth_url=self.url,
292 username=self.user,
293 password=self.passwd,
294 project_name=self.tenant_name,
295 project_id=self.tenant_id,
296 project_domain_id=self.config.get(
297 "project_domain_id", project_domain_id_default
298 ),
299 user_domain_id=self.config.get(
300 "user_domain_id", user_domain_id_default
301 ),
302 project_domain_name=self.config.get("project_domain_name"),
303 user_domain_name=self.config.get("user_domain_name"),
304 )
ahmadsa95baa272016-11-30 09:14:11 +0500305 else:
sousaedu80135b92021-02-17 15:05:18 +0100306 auth = v2.Password(
307 auth_url=self.url,
308 username=self.user,
309 password=self.passwd,
310 tenant_name=self.tenant_name,
311 tenant_id=self.tenant_id,
312 )
313
tierno4d1ce222018-04-06 10:41:06 +0200314 sess = session.Session(auth=auth, verify=self.verify)
tierno1ec592d2020-06-16 15:29:47 +0000315 # addedd region_name to keystone, nova, neutron and cinder to support distributed cloud for Wind River
316 # Titanium cloud and StarlingX
sousaedu80135b92021-02-17 15:05:18 +0100317 region_name = self.config.get("region_name")
318
tiernof716aea2017-06-21 18:01:40 +0200319 if self.api_version3:
sousaedu80135b92021-02-17 15:05:18 +0100320 self.keystone = ksClient_v3.Client(
321 session=sess,
322 endpoint_type=self.endpoint_type,
323 region_name=region_name,
324 )
tiernof716aea2017-06-21 18:01:40 +0200325 else:
sousaedu80135b92021-02-17 15:05:18 +0100326 self.keystone = ksClient_v2.Client(
327 session=sess, endpoint_type=self.endpoint_type
328 )
329
330 self.session["keystone"] = self.keystone
331 # In order to enable microversion functionality an explicit microversion must be specified in "config".
montesmoreno9317d302017-08-16 12:48:23 +0200332 # This implementation approach is due to the warning message in
333 # https://developer.openstack.org/api-guide/compute/microversions.html
334 # where it is stated that microversion backwards compatibility is not guaranteed and clients should
335 # always require an specific microversion.
sousaedu80135b92021-02-17 15:05:18 +0100336 # To be able to use "device role tagging" functionality define "microversion: 2.32" in datacenter config
montesmoreno9317d302017-08-16 12:48:23 +0200337 version = self.config.get("microversion")
sousaedu80135b92021-02-17 15:05:18 +0100338
montesmoreno9317d302017-08-16 12:48:23 +0200339 if not version:
340 version = "2.1"
sousaedu80135b92021-02-17 15:05:18 +0100341
tierno1ec592d2020-06-16 15:29:47 +0000342 # addedd region_name to keystone, nova, neutron and cinder to support distributed cloud for Wind River
343 # Titanium cloud and StarlingX
sousaedu80135b92021-02-17 15:05:18 +0100344 self.nova = self.session["nova"] = nClient.Client(
345 str(version),
346 session=sess,
347 endpoint_type=self.endpoint_type,
348 region_name=region_name,
349 )
350 self.neutron = self.session["neutron"] = neClient.Client(
351 "2.0",
352 session=sess,
353 endpoint_type=self.endpoint_type,
354 region_name=region_name,
355 )
356 self.cinder = self.session["cinder"] = cClient.Client(
357 2,
358 session=sess,
359 endpoint_type=self.endpoint_type,
360 region_name=region_name,
361 )
362
tiernoa05b65a2019-02-01 12:30:27 +0000363 try:
sousaedu80135b92021-02-17 15:05:18 +0100364 self.my_tenant_id = self.session["my_tenant_id"] = sess.get_project_id()
tierno1ec592d2020-06-16 15:29:47 +0000365 except Exception:
tiernoa05b65a2019-02-01 12:30:27 +0000366 self.logger.error("Cannot get project_id from session", exc_info=True)
sousaedu80135b92021-02-17 15:05:18 +0100367
kate721d79b2017-06-24 04:21:38 -0700368 if self.endpoint_type == "internalURL":
369 glance_service_id = self.keystone.services.list(name="glance")[0].id
sousaedu80135b92021-02-17 15:05:18 +0100370 glance_endpoint = self.keystone.endpoints.list(
371 glance_service_id, interface="internal"
372 )[0].url
kate721d79b2017-06-24 04:21:38 -0700373 else:
374 glance_endpoint = None
sousaedu80135b92021-02-17 15:05:18 +0100375
376 self.glance = self.session["glance"] = glClient.Client(
377 2, session=sess, endpoint=glance_endpoint
378 )
tiernoa05b65a2019-02-01 12:30:27 +0000379 # using version 1 of glance client in new_image()
sousaedu80135b92021-02-17 15:05:18 +0100380 # self.glancev1 = self.session["glancev1"] = glClient.Client("1", session=sess,
tierno1beea862018-07-11 15:47:37 +0200381 # endpoint=glance_endpoint)
sousaedu80135b92021-02-17 15:05:18 +0100382 self.session["reload_client"] = False
383 self.persistent_info["session"] = self.session
mirabal29356312017-07-27 12:21:22 +0200384 # add availablity zone info inside self.persistent_info
385 self._set_availablity_zones()
sousaedu80135b92021-02-17 15:05:18 +0100386 self.persistent_info["availability_zone"] = self.availability_zone
387 # force to get again security_groups_ids next time they are needed
388 self.security_groups_id = None
ahmadsa95baa272016-11-30 09:14:11 +0500389
tierno7edb6752016-03-21 17:37:52 +0100390 def __net_os2mano(self, net_list_dict):
tierno1ec592d2020-06-16 15:29:47 +0000391 """Transform the net openstack format to mano format
392 net_list_dict can be a list of dict or a single dict"""
tierno7edb6752016-03-21 17:37:52 +0100393 if type(net_list_dict) is dict:
tierno1ec592d2020-06-16 15:29:47 +0000394 net_list_ = (net_list_dict,)
tierno7edb6752016-03-21 17:37:52 +0100395 elif type(net_list_dict) is list:
tierno1ec592d2020-06-16 15:29:47 +0000396 net_list_ = net_list_dict
tierno7edb6752016-03-21 17:37:52 +0100397 else:
398 raise TypeError("param net_list_dict must be a list or a dictionary")
399 for net in net_list_:
sousaedu80135b92021-02-17 15:05:18 +0100400 if net.get("provider:network_type") == "vlan":
401 net["type"] = "data"
tierno7edb6752016-03-21 17:37:52 +0100402 else:
sousaedu80135b92021-02-17 15:05:18 +0100403 net["type"] = "bridge"
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +0200404
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000405 def __classification_os2mano(self, class_list_dict):
406 """Transform the openstack format (Flow Classifier) to mano format
407 (Classification) class_list_dict can be a list of dict or a single dict
408 """
409 if isinstance(class_list_dict, dict):
410 class_list_ = [class_list_dict]
411 elif isinstance(class_list_dict, list):
412 class_list_ = class_list_dict
413 else:
tierno1ec592d2020-06-16 15:29:47 +0000414 raise TypeError("param class_list_dict must be a list or a dictionary")
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000415 for classification in class_list_:
sousaedu80135b92021-02-17 15:05:18 +0100416 id = classification.pop("id")
417 name = classification.pop("name")
418 description = classification.pop("description")
419 project_id = classification.pop("project_id")
420 tenant_id = classification.pop("tenant_id")
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000421 original_classification = copy.deepcopy(classification)
422 classification.clear()
sousaedu80135b92021-02-17 15:05:18 +0100423 classification["ctype"] = "legacy_flow_classifier"
424 classification["definition"] = original_classification
425 classification["id"] = id
426 classification["name"] = name
427 classification["description"] = description
428 classification["project_id"] = project_id
429 classification["tenant_id"] = tenant_id
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000430
431 def __sfi_os2mano(self, sfi_list_dict):
432 """Transform the openstack format (Port Pair) to mano format (SFI)
433 sfi_list_dict can be a list of dict or a single dict
434 """
435 if isinstance(sfi_list_dict, dict):
436 sfi_list_ = [sfi_list_dict]
437 elif isinstance(sfi_list_dict, list):
438 sfi_list_ = sfi_list_dict
439 else:
sousaedu80135b92021-02-17 15:05:18 +0100440 raise TypeError("param sfi_list_dict must be a list or a dictionary")
441
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000442 for sfi in sfi_list_:
sousaedu80135b92021-02-17 15:05:18 +0100443 sfi["ingress_ports"] = []
444 sfi["egress_ports"] = []
445
446 if sfi.get("ingress"):
447 sfi["ingress_ports"].append(sfi["ingress"])
448
449 if sfi.get("egress"):
450 sfi["egress_ports"].append(sfi["egress"])
451
452 del sfi["ingress"]
453 del sfi["egress"]
454 params = sfi.get("service_function_parameters")
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000455 sfc_encap = False
sousaedu80135b92021-02-17 15:05:18 +0100456
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000457 if params:
sousaedu80135b92021-02-17 15:05:18 +0100458 correlation = params.get("correlation")
459
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000460 if correlation:
461 sfc_encap = True
sousaedu80135b92021-02-17 15:05:18 +0100462
463 sfi["sfc_encap"] = sfc_encap
464 del sfi["service_function_parameters"]
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000465
466 def __sf_os2mano(self, sf_list_dict):
467 """Transform the openstack format (Port Pair Group) to mano format (SF)
468 sf_list_dict can be a list of dict or a single dict
469 """
470 if isinstance(sf_list_dict, dict):
471 sf_list_ = [sf_list_dict]
472 elif isinstance(sf_list_dict, list):
473 sf_list_ = sf_list_dict
474 else:
sousaedu80135b92021-02-17 15:05:18 +0100475 raise TypeError("param sf_list_dict must be a list or a dictionary")
476
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000477 for sf in sf_list_:
sousaedu80135b92021-02-17 15:05:18 +0100478 del sf["port_pair_group_parameters"]
479 sf["sfis"] = sf["port_pairs"]
480 del sf["port_pairs"]
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000481
482 def __sfp_os2mano(self, sfp_list_dict):
483 """Transform the openstack format (Port Chain) to mano format (SFP)
484 sfp_list_dict can be a list of dict or a single dict
485 """
486 if isinstance(sfp_list_dict, dict):
487 sfp_list_ = [sfp_list_dict]
488 elif isinstance(sfp_list_dict, list):
489 sfp_list_ = sfp_list_dict
490 else:
sousaedu80135b92021-02-17 15:05:18 +0100491 raise TypeError("param sfp_list_dict must be a list or a dictionary")
492
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000493 for sfp in sfp_list_:
sousaedu80135b92021-02-17 15:05:18 +0100494 params = sfp.pop("chain_parameters")
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000495 sfc_encap = False
sousaedu80135b92021-02-17 15:05:18 +0100496
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000497 if params:
sousaedu80135b92021-02-17 15:05:18 +0100498 correlation = params.get("correlation")
499
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000500 if correlation:
501 sfc_encap = True
sousaedu80135b92021-02-17 15:05:18 +0100502
503 sfp["sfc_encap"] = sfc_encap
504 sfp["spi"] = sfp.pop("chain_id")
505 sfp["classifications"] = sfp.pop("flow_classifiers")
506 sfp["service_functions"] = sfp.pop("port_pair_groups")
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000507
508 # placeholder for now; read TODO note below
509 def _validate_classification(self, type, definition):
510 # only legacy_flow_classifier Type is supported at this point
511 return True
512 # TODO(igordcard): this method should be an abstract method of an
513 # abstract Classification class to be implemented by the specific
514 # Types. Also, abstract vimconnector should call the validation
515 # method before the implemented VIM connectors are called.
516
tiernoae4a8d12016-07-08 12:30:39 +0200517 def _format_exception(self, exception):
tierno69647792020-03-05 16:45:48 +0000518 """Transform a keystone, nova, neutron exception into a vimconn exception discovering the cause"""
tierno69647792020-03-05 16:45:48 +0000519 message_error = str(exception)
tierno5ad826a2020-08-11 11:19:44 +0000520 tip = ""
tiernode12f782019-04-05 12:46:42 +0000521
sousaedu80135b92021-02-17 15:05:18 +0100522 if isinstance(
523 exception,
524 (
525 neExceptions.NetworkNotFoundClient,
526 nvExceptions.NotFound,
527 ksExceptions.NotFound,
528 gl1Exceptions.HTTPNotFound,
529 ),
530 ):
531 raise vimconn.VimConnNotFoundException(
532 type(exception).__name__ + ": " + message_error
533 )
534 elif isinstance(
535 exception,
536 (
537 HTTPException,
538 gl1Exceptions.HTTPException,
539 gl1Exceptions.CommunicationError,
540 ConnectionError,
541 ksExceptions.ConnectionError,
542 neExceptions.ConnectionFailed,
543 ),
544 ):
tierno5ad826a2020-08-11 11:19:44 +0000545 if type(exception).__name__ == "SSLError":
546 tip = " (maybe option 'insecure' must be added to the VIM)"
sousaedu80135b92021-02-17 15:05:18 +0100547
548 raise vimconn.VimConnConnectionException(
549 "Invalid URL or credentials{}: {}".format(tip, message_error)
550 )
551 elif isinstance(
552 exception,
553 (
554 KeyError,
555 nvExceptions.BadRequest,
556 ksExceptions.BadRequest,
557 ),
558 ):
559 raise vimconn.VimConnException(
560 type(exception).__name__ + ": " + message_error
561 )
562 elif isinstance(
563 exception,
564 (
565 nvExceptions.ClientException,
566 ksExceptions.ClientException,
567 neExceptions.NeutronException,
568 ),
569 ):
570 raise vimconn.VimConnUnexpectedResponse(
571 type(exception).__name__ + ": " + message_error
572 )
tiernoae4a8d12016-07-08 12:30:39 +0200573 elif isinstance(exception, nvExceptions.Conflict):
sousaedu80135b92021-02-17 15:05:18 +0100574 raise vimconn.VimConnConflictException(
575 type(exception).__name__ + ": " + message_error
576 )
tierno72774862020-05-04 11:44:15 +0000577 elif isinstance(exception, vimconn.VimConnException):
tierno41a69812018-02-16 14:34:33 +0100578 raise exception
tiernof716aea2017-06-21 18:01:40 +0200579 else: # ()
tiernode12f782019-04-05 12:46:42 +0000580 self.logger.error("General Exception " + message_error, exc_info=True)
sousaedu80135b92021-02-17 15:05:18 +0100581
582 raise vimconn.VimConnConnectionException(
583 type(exception).__name__ + ": " + message_error
584 )
tiernoae4a8d12016-07-08 12:30:39 +0200585
tiernoa05b65a2019-02-01 12:30:27 +0000586 def _get_ids_from_name(self):
587 """
588 Obtain ids from name of tenant and security_groups. Store at self .security_groups_id"
589 :return: None
590 """
591 # get tenant_id if only tenant_name is supplied
592 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +0100593
tiernoa05b65a2019-02-01 12:30:27 +0000594 if not self.my_tenant_id:
sousaedu80135b92021-02-17 15:05:18 +0100595 raise vimconn.VimConnConnectionException(
596 "Error getting tenant information from name={} id={}".format(
597 self.tenant_name, self.tenant_id
598 )
599 )
600
601 if self.config.get("security_groups") and not self.security_groups_id:
tiernoa05b65a2019-02-01 12:30:27 +0000602 # convert from name to id
sousaedu80135b92021-02-17 15:05:18 +0100603 neutron_sg_list = self.neutron.list_security_groups(
604 tenant_id=self.my_tenant_id
605 )["security_groups"]
tiernoa05b65a2019-02-01 12:30:27 +0000606
607 self.security_groups_id = []
sousaedu80135b92021-02-17 15:05:18 +0100608 for sg in self.config.get("security_groups"):
tiernoa05b65a2019-02-01 12:30:27 +0000609 for neutron_sg in neutron_sg_list:
610 if sg in (neutron_sg["id"], neutron_sg["name"]):
611 self.security_groups_id.append(neutron_sg["id"])
612 break
613 else:
614 self.security_groups_id = None
sousaedu80135b92021-02-17 15:05:18 +0100615
616 raise vimconn.VimConnConnectionException(
617 "Not found security group {} for this tenant".format(sg)
618 )
tiernoa05b65a2019-02-01 12:30:27 +0000619
tierno5509c2e2019-07-04 16:23:20 +0000620 def check_vim_connectivity(self):
621 # just get network list to check connectivity and credentials
622 self.get_network_list(filter_dict={})
623
tiernoae4a8d12016-07-08 12:30:39 +0200624 def get_tenant_list(self, filter_dict={}):
tierno1ec592d2020-06-16 15:29:47 +0000625 """Obtain tenants of VIM
tiernoae4a8d12016-07-08 12:30:39 +0200626 filter_dict can contain the following keys:
627 name: filter by tenant name
628 id: filter by tenant uuid/id
629 <other VIM specific>
630 Returns the tenant list of dictionaries: [{'name':'<name>, 'id':'<id>, ...}, ...]
tierno1ec592d2020-06-16 15:29:47 +0000631 """
ahmadsa95baa272016-11-30 09:14:11 +0500632 self.logger.debug("Getting tenants from VIM filter: '%s'", str(filter_dict))
sousaedu80135b92021-02-17 15:05:18 +0100633
tiernoae4a8d12016-07-08 12:30:39 +0200634 try:
635 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +0100636
tiernof716aea2017-06-21 18:01:40 +0200637 if self.api_version3:
sousaedu80135b92021-02-17 15:05:18 +0100638 project_class_list = self.keystone.projects.list(
639 name=filter_dict.get("name")
640 )
ahmadsa95baa272016-11-30 09:14:11 +0500641 else:
tiernof716aea2017-06-21 18:01:40 +0200642 project_class_list = self.keystone.tenants.findall(**filter_dict)
sousaedu80135b92021-02-17 15:05:18 +0100643
tierno1ec592d2020-06-16 15:29:47 +0000644 project_list = []
sousaedu80135b92021-02-17 15:05:18 +0100645
ahmadsa95baa272016-11-30 09:14:11 +0500646 for project in project_class_list:
sousaedu80135b92021-02-17 15:05:18 +0100647 if filter_dict.get("id") and filter_dict["id"] != project.id:
tiernof716aea2017-06-21 18:01:40 +0200648 continue
sousaedu80135b92021-02-17 15:05:18 +0100649
ahmadsa95baa272016-11-30 09:14:11 +0500650 project_list.append(project.to_dict())
sousaedu80135b92021-02-17 15:05:18 +0100651
ahmadsa95baa272016-11-30 09:14:11 +0500652 return project_list
sousaedu80135b92021-02-17 15:05:18 +0100653 except (
654 ksExceptions.ConnectionError,
655 ksExceptions.ClientException,
656 ConnectionError,
657 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200658 self._format_exception(e)
659
660 def new_tenant(self, tenant_name, tenant_description):
tierno1ec592d2020-06-16 15:29:47 +0000661 """Adds a new tenant to openstack VIM. Returns the tenant identifier"""
tiernoae4a8d12016-07-08 12:30:39 +0200662 self.logger.debug("Adding a new tenant name: %s", tenant_name)
sousaedu80135b92021-02-17 15:05:18 +0100663
tiernoae4a8d12016-07-08 12:30:39 +0200664 try:
665 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +0100666
tiernof716aea2017-06-21 18:01:40 +0200667 if self.api_version3:
sousaedu80135b92021-02-17 15:05:18 +0100668 project = self.keystone.projects.create(
669 tenant_name,
670 self.config.get("project_domain_id", "default"),
671 description=tenant_description,
672 is_domain=False,
673 )
ahmadsa95baa272016-11-30 09:14:11 +0500674 else:
tiernof716aea2017-06-21 18:01:40 +0200675 project = self.keystone.tenants.create(tenant_name, tenant_description)
sousaedu80135b92021-02-17 15:05:18 +0100676
ahmadsa95baa272016-11-30 09:14:11 +0500677 return project.id
sousaedu80135b92021-02-17 15:05:18 +0100678 except (
679 ksExceptions.ConnectionError,
680 ksExceptions.ClientException,
681 ksExceptions.BadRequest,
682 ConnectionError,
683 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200684 self._format_exception(e)
685
686 def delete_tenant(self, tenant_id):
tierno1ec592d2020-06-16 15:29:47 +0000687 """Delete a tenant from openstack VIM. Returns the old tenant identifier"""
tiernoae4a8d12016-07-08 12:30:39 +0200688 self.logger.debug("Deleting tenant %s from VIM", tenant_id)
sousaedu80135b92021-02-17 15:05:18 +0100689
tiernoae4a8d12016-07-08 12:30:39 +0200690 try:
691 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +0100692
tiernof716aea2017-06-21 18:01:40 +0200693 if self.api_version3:
ahmadsa95baa272016-11-30 09:14:11 +0500694 self.keystone.projects.delete(tenant_id)
695 else:
696 self.keystone.tenants.delete(tenant_id)
sousaedu80135b92021-02-17 15:05:18 +0100697
tiernoae4a8d12016-07-08 12:30:39 +0200698 return tenant_id
sousaedu80135b92021-02-17 15:05:18 +0100699 except (
700 ksExceptions.ConnectionError,
701 ksExceptions.ClientException,
702 ksExceptions.NotFound,
703 ConnectionError,
704 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200705 self._format_exception(e)
ahmadsa95baa272016-11-30 09:14:11 +0500706
sousaedu80135b92021-02-17 15:05:18 +0100707 def new_network(
708 self,
709 net_name,
710 net_type,
711 ip_profile=None,
712 shared=False,
713 provider_network_profile=None,
714 ):
garciadeblasebd66722019-01-31 16:01:31 +0000715 """Adds a tenant network to VIM
716 Params:
717 'net_name': name of the network
718 'net_type': one of:
719 'bridge': overlay isolated network
720 'data': underlay E-LAN network for Passthrough and SRIOV interfaces
721 'ptp': underlay E-LINE network for Passthrough and SRIOV interfaces.
722 'ip_profile': is a dict containing the IP parameters of the network
723 'ip_version': can be "IPv4" or "IPv6" (Currently only IPv4 is implemented)
724 'subnet_address': ip_prefix_schema, that is X.X.X.X/Y
725 'gateway_address': (Optional) ip_schema, that is X.X.X.X
726 'dns_address': (Optional) comma separated list of ip_schema, e.g. X.X.X.X[,X,X,X,X]
727 'dhcp_enabled': True or False
728 'dhcp_start_address': ip_schema, first IP to grant
729 'dhcp_count': number of IPs to grant.
730 'shared': if this network can be seen/use by other tenants/organization
garciadeblas4af0d542020-02-18 16:01:13 +0100731 'provider_network_profile': (optional) contains {segmentation-id: vlan, network-type: vlan|vxlan,
732 physical-network: physnet-label}
garciadeblasebd66722019-01-31 16:01:31 +0000733 Returns a tuple with the network identifier and created_items, or raises an exception on error
734 created_items can be None or a dictionary where this method can include key-values that will be passed to
735 the method delete_network. Can be used to store created segments, created l2gw connections, etc.
736 Format is vimconnector dependent, but do not use nested dictionaries and a value of None should be the same
737 as not present.
738 """
sousaedu80135b92021-02-17 15:05:18 +0100739 self.logger.debug(
740 "Adding a new network to VIM name '%s', type '%s'", net_name, net_type
741 )
garciadeblasebd66722019-01-31 16:01:31 +0000742 # self.logger.debug(">>>>>>>>>>>>>>>>>> IP profile %s", str(ip_profile))
kbsuba85c54d2019-10-17 16:30:32 +0000743
tierno7edb6752016-03-21 17:37:52 +0100744 try:
kbsuba85c54d2019-10-17 16:30:32 +0000745 vlan = None
sousaedu80135b92021-02-17 15:05:18 +0100746
kbsuba85c54d2019-10-17 16:30:32 +0000747 if provider_network_profile:
748 vlan = provider_network_profile.get("segmentation-id")
sousaedu80135b92021-02-17 15:05:18 +0100749
garciadeblasedca7b32016-09-29 14:01:52 +0000750 new_net = None
garciadeblasebd66722019-01-31 16:01:31 +0000751 created_items = {}
tierno7edb6752016-03-21 17:37:52 +0100752 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +0100753 network_dict = {"name": net_name, "admin_state_up": True}
754
tierno6869ae72020-01-09 17:37:34 +0000755 if net_type in ("data", "ptp"):
756 provider_physical_network = None
sousaedu80135b92021-02-17 15:05:18 +0100757
758 if provider_network_profile and provider_network_profile.get(
759 "physical-network"
760 ):
761 provider_physical_network = provider_network_profile.get(
762 "physical-network"
763 )
764
tierno6869ae72020-01-09 17:37:34 +0000765 # provider-network must be one of the dataplane_physcial_netowrk if this is a list. If it is string
766 # or not declared, just ignore the checking
sousaedu80135b92021-02-17 15:05:18 +0100767 if (
768 isinstance(
769 self.config.get("dataplane_physical_net"), (tuple, list)
770 )
771 and provider_physical_network
772 not in self.config["dataplane_physical_net"]
773 ):
tierno72774862020-05-04 11:44:15 +0000774 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +0100775 "Invalid parameter 'provider-network:physical-network' "
776 "for network creation. '{}' is not one of the declared "
777 "list at VIM_config:dataplane_physical_net".format(
778 provider_physical_network
779 )
780 )
781
782 # use the default dataplane_physical_net
783 if not provider_physical_network:
784 provider_physical_network = self.config.get(
785 "dataplane_physical_net"
786 )
787
tierno6869ae72020-01-09 17:37:34 +0000788 # if it is non empty list, use the first value. If it is a string use the value directly
sousaedu80135b92021-02-17 15:05:18 +0100789 if (
790 isinstance(provider_physical_network, (tuple, list))
791 and provider_physical_network
792 ):
tierno6869ae72020-01-09 17:37:34 +0000793 provider_physical_network = provider_physical_network[0]
794
795 if not provider_physical_network:
tierno5ad826a2020-08-11 11:19:44 +0000796 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +0100797 "missing information needed for underlay networks. Provide "
798 "'dataplane_physical_net' configuration at VIM or use the NS "
799 "instantiation parameter 'provider-network.physical-network'"
800 " for the VLD"
801 )
tierno6869ae72020-01-09 17:37:34 +0000802
sousaedu80135b92021-02-17 15:05:18 +0100803 if not self.config.get("multisegment_support"):
804 network_dict[
805 "provider:physical_network"
806 ] = provider_physical_network
807
808 if (
809 provider_network_profile
810 and "network-type" in provider_network_profile
811 ):
812 network_dict[
813 "provider:network_type"
814 ] = provider_network_profile["network-type"]
garciadeblas4af0d542020-02-18 16:01:13 +0100815 else:
sousaedu80135b92021-02-17 15:05:18 +0100816 network_dict["provider:network_type"] = self.config.get(
817 "dataplane_network_type", "vlan"
818 )
819
tierno6869ae72020-01-09 17:37:34 +0000820 if vlan:
821 network_dict["provider:segmentation_id"] = vlan
garciadeblasebd66722019-01-31 16:01:31 +0000822 else:
tierno6869ae72020-01-09 17:37:34 +0000823 # Multi-segment case
garciadeblasebd66722019-01-31 16:01:31 +0000824 segment_list = []
tierno6869ae72020-01-09 17:37:34 +0000825 segment1_dict = {
sousaedu80135b92021-02-17 15:05:18 +0100826 "provider:physical_network": "",
827 "provider:network_type": "vxlan",
tierno6869ae72020-01-09 17:37:34 +0000828 }
garciadeblasebd66722019-01-31 16:01:31 +0000829 segment_list.append(segment1_dict)
tierno6869ae72020-01-09 17:37:34 +0000830 segment2_dict = {
831 "provider:physical_network": provider_physical_network,
sousaedu80135b92021-02-17 15:05:18 +0100832 "provider:network_type": "vlan",
tierno6869ae72020-01-09 17:37:34 +0000833 }
sousaedu80135b92021-02-17 15:05:18 +0100834
tierno6869ae72020-01-09 17:37:34 +0000835 if vlan:
836 segment2_dict["provider:segmentation_id"] = vlan
sousaedu80135b92021-02-17 15:05:18 +0100837 elif self.config.get("multisegment_vlan_range"):
garciadeblasebd66722019-01-31 16:01:31 +0000838 vlanID = self._generate_multisegment_vlanID()
839 segment2_dict["provider:segmentation_id"] = vlanID
sousaedu80135b92021-02-17 15:05:18 +0100840
garciadeblasebd66722019-01-31 16:01:31 +0000841 # else
tierno72774862020-05-04 11:44:15 +0000842 # raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +0100843 # "You must provide "multisegment_vlan_range" at config dict before creating a multisegment
tierno1ec592d2020-06-16 15:29:47 +0000844 # network")
garciadeblasebd66722019-01-31 16:01:31 +0000845 segment_list.append(segment2_dict)
846 network_dict["segments"] = segment_list
kate721d79b2017-06-24 04:21:38 -0700847
tierno6869ae72020-01-09 17:37:34 +0000848 # VIO Specific Changes. It needs a concrete VLAN
849 if self.vim_type == "VIO" and vlan is None:
sousaedu80135b92021-02-17 15:05:18 +0100850 if self.config.get("dataplane_net_vlan_range") is None:
tierno72774862020-05-04 11:44:15 +0000851 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +0100852 "You must provide 'dataplane_net_vlan_range' in format "
853 "[start_ID - end_ID] at VIM_config for creating underlay "
854 "networks"
855 )
856
tierno6869ae72020-01-09 17:37:34 +0000857 network_dict["provider:segmentation_id"] = self._generate_vlanID()
kate721d79b2017-06-24 04:21:38 -0700858
garciadeblasebd66722019-01-31 16:01:31 +0000859 network_dict["shared"] = shared
sousaedu80135b92021-02-17 15:05:18 +0100860
anwarsff168192019-05-06 11:23:07 +0530861 if self.config.get("disable_network_port_security"):
862 network_dict["port_security_enabled"] = False
sousaedu80135b92021-02-17 15:05:18 +0100863
sousaedu2aa5f802021-06-17 15:39:29 +0100864 if self.config.get("neutron_availability_zone_hints"):
865 hints = self.config.get("neutron_availability_zone_hints")
866
867 if isinstance(hints, str):
868 hints = [hints]
869
870 network_dict["availability_zone_hints"] = hints
871
sousaedu80135b92021-02-17 15:05:18 +0100872 new_net = self.neutron.create_network({"network": network_dict})
garciadeblasebd66722019-01-31 16:01:31 +0000873 # print new_net
874 # create subnetwork, even if there is no profile
sousaedu80135b92021-02-17 15:05:18 +0100875
garciadeblas9f8456e2016-09-05 05:02:59 +0200876 if not ip_profile:
877 ip_profile = {}
sousaedu80135b92021-02-17 15:05:18 +0100878
879 if not ip_profile.get("subnet_address"):
tierno1ec592d2020-06-16 15:29:47 +0000880 # Fake subnet is required
garciadeblas2299e3b2017-01-26 14:35:55 +0000881 subnet_rand = random.randint(0, 255)
sousaedu80135b92021-02-17 15:05:18 +0100882 ip_profile["subnet_address"] = "192.168.{}.0/24".format(subnet_rand)
883
884 if "ip_version" not in ip_profile:
885 ip_profile["ip_version"] = "IPv4"
886
887 subnet = {
888 "name": net_name + "-subnet",
889 "network_id": new_net["network"]["id"],
890 "ip_version": 4 if ip_profile["ip_version"] == "IPv4" else 6,
891 "cidr": ip_profile["subnet_address"],
892 }
893
tiernoa1fb4462017-06-30 12:25:50 +0200894 # Gateway should be set to None if not needed. Otherwise openstack assigns one by default
sousaedu80135b92021-02-17 15:05:18 +0100895 if ip_profile.get("gateway_address"):
896 subnet["gateway_ip"] = ip_profile["gateway_address"]
tierno55d234c2018-07-04 18:29:21 +0200897 else:
sousaedu80135b92021-02-17 15:05:18 +0100898 subnet["gateway_ip"] = None
899
900 if ip_profile.get("dns_address"):
901 subnet["dns_nameservers"] = ip_profile["dns_address"].split(";")
902
903 if "dhcp_enabled" in ip_profile:
904 subnet["enable_dhcp"] = (
905 False
906 if ip_profile["dhcp_enabled"] == "false"
907 or ip_profile["dhcp_enabled"] is False
908 else True
909 )
910
911 if ip_profile.get("dhcp_start_address"):
912 subnet["allocation_pools"] = []
913 subnet["allocation_pools"].append(dict())
914 subnet["allocation_pools"][0]["start"] = ip_profile[
915 "dhcp_start_address"
916 ]
917
918 if ip_profile.get("dhcp_count"):
919 # parts = ip_profile["dhcp_start_address"].split(".")
tierno1ec592d2020-06-16 15:29:47 +0000920 # ip_int = (int(parts[0]) << 24) + (int(parts[1]) << 16) + (int(parts[2]) << 8) + int(parts[3])
sousaedu80135b92021-02-17 15:05:18 +0100921 ip_int = int(netaddr.IPAddress(ip_profile["dhcp_start_address"]))
922 ip_int += ip_profile["dhcp_count"] - 1
garciadeblas9f8456e2016-09-05 05:02:59 +0200923 ip_str = str(netaddr.IPAddress(ip_int))
sousaedu80135b92021-02-17 15:05:18 +0100924 subnet["allocation_pools"][0]["end"] = ip_str
925
tierno1ec592d2020-06-16 15:29:47 +0000926 # self.logger.debug(">>>>>>>>>>>>>>>>>> Subnet: %s", str(subnet))
927 self.neutron.create_subnet({"subnet": subnet})
garciadeblasebd66722019-01-31 16:01:31 +0000928
sousaedu80135b92021-02-17 15:05:18 +0100929 if net_type == "data" and self.config.get("multisegment_support"):
930 if self.config.get("l2gw_support"):
garciadeblasebd66722019-01-31 16:01:31 +0000931 l2gw_list = self.neutron.list_l2_gateways().get("l2_gateways", ())
932 for l2gw in l2gw_list:
tierno1ec592d2020-06-16 15:29:47 +0000933 l2gw_conn = {
934 "l2_gateway_id": l2gw["id"],
935 "network_id": new_net["network"]["id"],
936 "segmentation_id": str(vlanID),
937 }
sousaedu80135b92021-02-17 15:05:18 +0100938 new_l2gw_conn = self.neutron.create_l2_gateway_connection(
939 {"l2_gateway_connection": l2gw_conn}
940 )
941 created_items[
942 "l2gwconn:"
943 + str(new_l2gw_conn["l2_gateway_connection"]["id"])
944 ] = True
945
garciadeblasebd66722019-01-31 16:01:31 +0000946 return new_net["network"]["id"], created_items
tierno41a69812018-02-16 14:34:33 +0100947 except Exception as e:
tierno1ec592d2020-06-16 15:29:47 +0000948 # delete l2gw connections (if any) before deleting the network
garciadeblasebd66722019-01-31 16:01:31 +0000949 for k, v in created_items.items():
950 if not v: # skip already deleted
951 continue
sousaedu80135b92021-02-17 15:05:18 +0100952
garciadeblasebd66722019-01-31 16:01:31 +0000953 try:
954 k_item, _, k_id = k.partition(":")
sousaedu80135b92021-02-17 15:05:18 +0100955
garciadeblasebd66722019-01-31 16:01:31 +0000956 if k_item == "l2gwconn":
957 self.neutron.delete_l2_gateway_connection(k_id)
958 except Exception as e2:
sousaedu80135b92021-02-17 15:05:18 +0100959 self.logger.error(
960 "Error deleting l2 gateway connection: {}: {}".format(
961 type(e2).__name__, e2
962 )
963 )
964
garciadeblasedca7b32016-09-29 14:01:52 +0000965 if new_net:
sousaedu80135b92021-02-17 15:05:18 +0100966 self.neutron.delete_network(new_net["network"]["id"])
967
tiernoae4a8d12016-07-08 12:30:39 +0200968 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100969
970 def get_network_list(self, filter_dict={}):
tierno1ec592d2020-06-16 15:29:47 +0000971 """Obtain tenant networks of VIM
tierno7edb6752016-03-21 17:37:52 +0100972 Filter_dict can be:
973 name: network name
974 id: network uuid
975 shared: boolean
976 tenant_id: tenant
977 admin_state_up: boolean
978 status: 'ACTIVE'
979 Returns the network list of dictionaries
tierno1ec592d2020-06-16 15:29:47 +0000980 """
tiernoae4a8d12016-07-08 12:30:39 +0200981 self.logger.debug("Getting network from VIM filter: '%s'", str(filter_dict))
sousaedu80135b92021-02-17 15:05:18 +0100982
tierno7edb6752016-03-21 17:37:52 +0100983 try:
984 self._reload_connection()
tierno69b590e2018-03-13 18:52:23 +0100985 filter_dict_os = filter_dict.copy()
sousaedu80135b92021-02-17 15:05:18 +0100986
tierno69b590e2018-03-13 18:52:23 +0100987 if self.api_version3 and "tenant_id" in filter_dict_os:
sousaedu80135b92021-02-17 15:05:18 +0100988 # TODO check
989 filter_dict_os["project_id"] = filter_dict_os.pop("tenant_id")
990
tierno69b590e2018-03-13 18:52:23 +0100991 net_dict = self.neutron.list_networks(**filter_dict_os)
tierno00e3df72017-11-29 17:20:13 +0100992 net_list = net_dict["networks"]
tierno7edb6752016-03-21 17:37:52 +0100993 self.__net_os2mano(net_list)
sousaedu80135b92021-02-17 15:05:18 +0100994
tiernoae4a8d12016-07-08 12:30:39 +0200995 return net_list
sousaedu80135b92021-02-17 15:05:18 +0100996 except (
997 neExceptions.ConnectionFailed,
998 ksExceptions.ClientException,
999 neExceptions.NeutronException,
1000 ConnectionError,
1001 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001002 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001003
tiernoae4a8d12016-07-08 12:30:39 +02001004 def get_network(self, net_id):
tierno1ec592d2020-06-16 15:29:47 +00001005 """Obtain details of network from VIM
1006 Returns the network information from a network id"""
tiernoae4a8d12016-07-08 12:30:39 +02001007 self.logger.debug(" Getting tenant network %s from VIM", net_id)
tierno1ec592d2020-06-16 15:29:47 +00001008 filter_dict = {"id": net_id}
tiernoae4a8d12016-07-08 12:30:39 +02001009 net_list = self.get_network_list(filter_dict)
sousaedu80135b92021-02-17 15:05:18 +01001010
tierno1ec592d2020-06-16 15:29:47 +00001011 if len(net_list) == 0:
sousaedu80135b92021-02-17 15:05:18 +01001012 raise vimconn.VimConnNotFoundException(
1013 "Network '{}' not found".format(net_id)
1014 )
tierno1ec592d2020-06-16 15:29:47 +00001015 elif len(net_list) > 1:
sousaedu80135b92021-02-17 15:05:18 +01001016 raise vimconn.VimConnConflictException(
1017 "Found more than one network with this criteria"
1018 )
1019
tierno7edb6752016-03-21 17:37:52 +01001020 net = net_list[0]
tierno1ec592d2020-06-16 15:29:47 +00001021 subnets = []
1022 for subnet_id in net.get("subnets", ()):
tierno7edb6752016-03-21 17:37:52 +01001023 try:
1024 subnet = self.neutron.show_subnet(subnet_id)
1025 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01001026 self.logger.error(
1027 "osconnector.get_network(): Error getting subnet %s %s"
1028 % (net_id, str(e))
1029 )
tiernoae4a8d12016-07-08 12:30:39 +02001030 subnet = {"id": subnet_id, "fault": str(e)}
sousaedu80135b92021-02-17 15:05:18 +01001031
tierno7edb6752016-03-21 17:37:52 +01001032 subnets.append(subnet)
sousaedu80135b92021-02-17 15:05:18 +01001033
tierno7edb6752016-03-21 17:37:52 +01001034 net["subnets"] = subnets
sousaedu80135b92021-02-17 15:05:18 +01001035 net["encapsulation"] = net.get("provider:network_type")
1036 net["encapsulation_type"] = net.get("provider:network_type")
1037 net["segmentation_id"] = net.get("provider:segmentation_id")
1038 net["encapsulation_id"] = net.get("provider:segmentation_id")
1039
tiernoae4a8d12016-07-08 12:30:39 +02001040 return net
tierno7edb6752016-03-21 17:37:52 +01001041
garciadeblasebd66722019-01-31 16:01:31 +00001042 def delete_network(self, net_id, created_items=None):
1043 """
1044 Removes a tenant network from VIM and its associated elements
1045 :param net_id: VIM identifier of the network, provided by method new_network
1046 :param created_items: dictionary with extra items to be deleted. provided by method new_network
1047 Returns the network identifier or raises an exception upon error or when network is not found
1048 """
tiernoae4a8d12016-07-08 12:30:39 +02001049 self.logger.debug("Deleting network '%s' from VIM", net_id)
sousaedu80135b92021-02-17 15:05:18 +01001050
tierno1ec592d2020-06-16 15:29:47 +00001051 if created_items is None:
garciadeblasebd66722019-01-31 16:01:31 +00001052 created_items = {}
sousaedu80135b92021-02-17 15:05:18 +01001053
tierno7edb6752016-03-21 17:37:52 +01001054 try:
1055 self._reload_connection()
tierno1ec592d2020-06-16 15:29:47 +00001056 # delete l2gw connections (if any) before deleting the network
garciadeblasebd66722019-01-31 16:01:31 +00001057 for k, v in created_items.items():
1058 if not v: # skip already deleted
1059 continue
sousaedu80135b92021-02-17 15:05:18 +01001060
garciadeblasebd66722019-01-31 16:01:31 +00001061 try:
1062 k_item, _, k_id = k.partition(":")
1063 if k_item == "l2gwconn":
1064 self.neutron.delete_l2_gateway_connection(k_id)
1065 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01001066 self.logger.error(
1067 "Error deleting l2 gateway connection: {}: {}".format(
1068 type(e).__name__, e
1069 )
1070 )
1071
tierno1ec592d2020-06-16 15:29:47 +00001072 # delete VM ports attached to this networks before the network
tierno7edb6752016-03-21 17:37:52 +01001073 ports = self.neutron.list_ports(network_id=net_id)
sousaedu80135b92021-02-17 15:05:18 +01001074 for p in ports["ports"]:
tierno7edb6752016-03-21 17:37:52 +01001075 try:
1076 self.neutron.delete_port(p["id"])
1077 except Exception as e:
tiernoae4a8d12016-07-08 12:30:39 +02001078 self.logger.error("Error deleting port %s: %s", p["id"], str(e))
sousaedu80135b92021-02-17 15:05:18 +01001079
tierno7edb6752016-03-21 17:37:52 +01001080 self.neutron.delete_network(net_id)
sousaedu80135b92021-02-17 15:05:18 +01001081
tiernoae4a8d12016-07-08 12:30:39 +02001082 return net_id
sousaedu80135b92021-02-17 15:05:18 +01001083 except (
1084 neExceptions.ConnectionFailed,
1085 neExceptions.NetworkNotFoundClient,
1086 neExceptions.NeutronException,
1087 ksExceptions.ClientException,
1088 neExceptions.NeutronException,
1089 ConnectionError,
1090 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001091 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001092
tiernoae4a8d12016-07-08 12:30:39 +02001093 def refresh_nets_status(self, net_list):
tierno1ec592d2020-06-16 15:29:47 +00001094 """Get the status of the networks
sousaedu80135b92021-02-17 15:05:18 +01001095 Params: the list of network identifiers
1096 Returns a dictionary with:
1097 net_id: #VIM id of this network
1098 status: #Mandatory. Text with one of:
1099 # DELETED (not found at vim)
1100 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
1101 # OTHER (Vim reported other status not understood)
1102 # ERROR (VIM indicates an ERROR status)
1103 # ACTIVE, INACTIVE, DOWN (admin down),
1104 # BUILD (on building process)
1105 #
1106 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
1107 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
tierno1ec592d2020-06-16 15:29:47 +00001108 """
1109 net_dict = {}
sousaedu80135b92021-02-17 15:05:18 +01001110
tiernoae4a8d12016-07-08 12:30:39 +02001111 for net_id in net_list:
1112 net = {}
sousaedu80135b92021-02-17 15:05:18 +01001113
tiernoae4a8d12016-07-08 12:30:39 +02001114 try:
1115 net_vim = self.get_network(net_id)
sousaedu80135b92021-02-17 15:05:18 +01001116
1117 if net_vim["status"] in netStatus2manoFormat:
1118 net["status"] = netStatus2manoFormat[net_vim["status"]]
tiernoae4a8d12016-07-08 12:30:39 +02001119 else:
1120 net["status"] = "OTHER"
sousaedu80135b92021-02-17 15:05:18 +01001121 net["error_msg"] = "VIM status reported " + net_vim["status"]
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001122
sousaedu80135b92021-02-17 15:05:18 +01001123 if net["status"] == "ACTIVE" and not net_vim["admin_state_up"]:
1124 net["status"] = "DOWN"
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001125
sousaedu80135b92021-02-17 15:05:18 +01001126 net["vim_info"] = self.serialize(net_vim)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001127
sousaedu80135b92021-02-17 15:05:18 +01001128 if net_vim.get("fault"): # TODO
1129 net["error_msg"] = str(net_vim["fault"])
tierno72774862020-05-04 11:44:15 +00001130 except vimconn.VimConnNotFoundException as e:
tiernoae4a8d12016-07-08 12:30:39 +02001131 self.logger.error("Exception getting net status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01001132 net["status"] = "DELETED"
1133 net["error_msg"] = str(e)
tierno72774862020-05-04 11:44:15 +00001134 except vimconn.VimConnException as e:
tiernoae4a8d12016-07-08 12:30:39 +02001135 self.logger.error("Exception getting net status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01001136 net["status"] = "VIM_ERROR"
1137 net["error_msg"] = str(e)
tiernoae4a8d12016-07-08 12:30:39 +02001138 net_dict[net_id] = net
1139 return net_dict
1140
1141 def get_flavor(self, flavor_id):
tierno1ec592d2020-06-16 15:29:47 +00001142 """Obtain flavor details from the VIM. Returns the flavor dict details"""
tiernoae4a8d12016-07-08 12:30:39 +02001143 self.logger.debug("Getting flavor '%s'", flavor_id)
sousaedu80135b92021-02-17 15:05:18 +01001144
tierno7edb6752016-03-21 17:37:52 +01001145 try:
1146 self._reload_connection()
1147 flavor = self.nova.flavors.find(id=flavor_id)
tierno1ec592d2020-06-16 15:29:47 +00001148 # TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
sousaedu80135b92021-02-17 15:05:18 +01001149
tiernoae4a8d12016-07-08 12:30:39 +02001150 return flavor.to_dict()
sousaedu80135b92021-02-17 15:05:18 +01001151 except (
1152 nvExceptions.NotFound,
1153 nvExceptions.ClientException,
1154 ksExceptions.ClientException,
1155 ConnectionError,
1156 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001157 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001158
tiernocf157a82017-01-30 14:07:06 +01001159 def get_flavor_id_from_data(self, flavor_dict):
1160 """Obtain flavor id that match the flavor description
sousaedu80135b92021-02-17 15:05:18 +01001161 Returns the flavor_id or raises a vimconnNotFoundException
1162 flavor_dict: contains the required ram, vcpus, disk
1163 If 'use_existing_flavors' is set to True at config, the closer flavor that provides same or more ram, vcpus
1164 and disk is returned. Otherwise a flavor with exactly same ram, vcpus and disk is returned or a
1165 vimconnNotFoundException is raised
tiernocf157a82017-01-30 14:07:06 +01001166 """
sousaedu80135b92021-02-17 15:05:18 +01001167 exact_match = False if self.config.get("use_existing_flavors") else True
1168
tiernocf157a82017-01-30 14:07:06 +01001169 try:
1170 self._reload_connection()
tiernoe26fc7a2017-05-30 14:43:03 +02001171 flavor_candidate_id = None
1172 flavor_candidate_data = (10000, 10000, 10000)
sousaedu80135b92021-02-17 15:05:18 +01001173 flavor_target = (
1174 flavor_dict["ram"],
1175 flavor_dict["vcpus"],
1176 flavor_dict["disk"],
sousaedu648ee3d2021-11-22 14:09:15 +00001177 flavor_dict.get("ephemeral", 0),
1178 flavor_dict.get("swap", 0),
sousaedu80135b92021-02-17 15:05:18 +01001179 )
tiernoe26fc7a2017-05-30 14:43:03 +02001180 # numa=None
anwarsae5f52c2019-04-22 10:35:27 +05301181 extended = flavor_dict.get("extended", {})
1182 if extended:
tierno1ec592d2020-06-16 15:29:47 +00001183 # TODO
sousaedu80135b92021-02-17 15:05:18 +01001184 raise vimconn.VimConnNotFoundException(
1185 "Flavor with EPA still not implemented"
1186 )
tiernocf157a82017-01-30 14:07:06 +01001187 # if len(numas) > 1:
tierno72774862020-05-04 11:44:15 +00001188 # raise vimconn.VimConnNotFoundException("Cannot find any flavor with more than one numa")
tiernocf157a82017-01-30 14:07:06 +01001189 # numa=numas[0]
1190 # numas = extended.get("numas")
1191 for flavor in self.nova.flavors.list():
1192 epa = flavor.get_keys()
sousaedu80135b92021-02-17 15:05:18 +01001193
tiernocf157a82017-01-30 14:07:06 +01001194 if epa:
1195 continue
tiernoe26fc7a2017-05-30 14:43:03 +02001196 # TODO
sousaedu80135b92021-02-17 15:05:18 +01001197
sousaedu648ee3d2021-11-22 14:09:15 +00001198 flavor_data = (
1199 flavor.ram,
1200 flavor.vcpus,
1201 flavor.disk,
1202 flavor.ephemeral,
preethika.pebaba1f2022-01-20 07:24:18 +00001203 flavor.swap if isinstance(flavor.swap, int) else 0,
sousaedu648ee3d2021-11-22 14:09:15 +00001204 )
tiernoe26fc7a2017-05-30 14:43:03 +02001205 if flavor_data == flavor_target:
1206 return flavor.id
sousaedu80135b92021-02-17 15:05:18 +01001207 elif (
1208 not exact_match
1209 and flavor_target < flavor_data < flavor_candidate_data
1210 ):
tiernoe26fc7a2017-05-30 14:43:03 +02001211 flavor_candidate_id = flavor.id
1212 flavor_candidate_data = flavor_data
sousaedu80135b92021-02-17 15:05:18 +01001213
tiernoe26fc7a2017-05-30 14:43:03 +02001214 if not exact_match and flavor_candidate_id:
1215 return flavor_candidate_id
sousaedu80135b92021-02-17 15:05:18 +01001216
1217 raise vimconn.VimConnNotFoundException(
1218 "Cannot find any flavor matching '{}'".format(flavor_dict)
1219 )
1220 except (
1221 nvExceptions.NotFound,
1222 nvExceptions.ClientException,
1223 ksExceptions.ClientException,
1224 ConnectionError,
1225 ) as e:
tiernocf157a82017-01-30 14:07:06 +01001226 self._format_exception(e)
1227
anwarsae5f52c2019-04-22 10:35:27 +05301228 def process_resource_quota(self, quota, prefix, extra_specs):
1229 """
1230 :param prefix:
borsatti8a2dda32019-12-18 15:08:57 +00001231 :param extra_specs:
anwarsae5f52c2019-04-22 10:35:27 +05301232 :return:
1233 """
sousaedu80135b92021-02-17 15:05:18 +01001234 if "limit" in quota:
1235 extra_specs["quota:" + prefix + "_limit"] = quota["limit"]
1236
1237 if "reserve" in quota:
1238 extra_specs["quota:" + prefix + "_reservation"] = quota["reserve"]
1239
1240 if "shares" in quota:
anwarsae5f52c2019-04-22 10:35:27 +05301241 extra_specs["quota:" + prefix + "_shares_level"] = "custom"
sousaedu80135b92021-02-17 15:05:18 +01001242 extra_specs["quota:" + prefix + "_shares_share"] = quota["shares"]
anwarsae5f52c2019-04-22 10:35:27 +05301243
tiernoae4a8d12016-07-08 12:30:39 +02001244 def new_flavor(self, flavor_data, change_name_if_used=True):
tierno1ec592d2020-06-16 15:29:47 +00001245 """Adds a tenant flavor to openstack VIM
1246 if change_name_if_used is True, it will change name in case of conflict, because it is not supported name
1247 repetition
tierno7edb6752016-03-21 17:37:52 +01001248 Returns the flavor identifier
tierno1ec592d2020-06-16 15:29:47 +00001249 """
tiernoae4a8d12016-07-08 12:30:39 +02001250 self.logger.debug("Adding flavor '%s'", str(flavor_data))
tierno1ec592d2020-06-16 15:29:47 +00001251 retry = 0
1252 max_retries = 3
tierno7edb6752016-03-21 17:37:52 +01001253 name_suffix = 0
sousaedu80135b92021-02-17 15:05:18 +01001254
anwarsc76a3ee2018-10-04 14:05:32 +05301255 try:
sousaedu80135b92021-02-17 15:05:18 +01001256 name = flavor_data["name"]
tierno1ec592d2020-06-16 15:29:47 +00001257 while retry < max_retries:
1258 retry += 1
anwarsc76a3ee2018-10-04 14:05:32 +05301259 try:
1260 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +01001261
anwarsc76a3ee2018-10-04 14:05:32 +05301262 if change_name_if_used:
tierno1ec592d2020-06-16 15:29:47 +00001263 # get used names
1264 fl_names = []
1265 fl = self.nova.flavors.list()
sousaedu80135b92021-02-17 15:05:18 +01001266
anwarsc76a3ee2018-10-04 14:05:32 +05301267 for f in fl:
1268 fl_names.append(f.name)
sousaedu80135b92021-02-17 15:05:18 +01001269
anwarsc76a3ee2018-10-04 14:05:32 +05301270 while name in fl_names:
1271 name_suffix += 1
sousaedu80135b92021-02-17 15:05:18 +01001272 name = flavor_data["name"] + "-" + str(name_suffix)
kate721d79b2017-06-24 04:21:38 -07001273
sousaedu80135b92021-02-17 15:05:18 +01001274 ram = flavor_data.get("ram", 64)
1275 vcpus = flavor_data.get("vcpus", 1)
tierno1ec592d2020-06-16 15:29:47 +00001276 extra_specs = {}
tierno7edb6752016-03-21 17:37:52 +01001277
anwarsc76a3ee2018-10-04 14:05:32 +05301278 extended = flavor_data.get("extended")
1279 if extended:
tierno1ec592d2020-06-16 15:29:47 +00001280 numas = extended.get("numas")
sousaedu80135b92021-02-17 15:05:18 +01001281
anwarsc76a3ee2018-10-04 14:05:32 +05301282 if numas:
1283 numa_nodes = len(numas)
sousaedu80135b92021-02-17 15:05:18 +01001284
anwarsc76a3ee2018-10-04 14:05:32 +05301285 if numa_nodes > 1:
1286 return -1, "Can not add flavor with more than one numa"
sousaedu80135b92021-02-17 15:05:18 +01001287
anwarsae5f52c2019-04-22 10:35:27 +05301288 extra_specs["hw:numa_nodes"] = str(numa_nodes)
1289 extra_specs["hw:mem_page_size"] = "large"
1290 extra_specs["hw:cpu_policy"] = "dedicated"
1291 extra_specs["hw:numa_mempolicy"] = "strict"
sousaedu80135b92021-02-17 15:05:18 +01001292
anwarsc76a3ee2018-10-04 14:05:32 +05301293 if self.vim_type == "VIO":
sousaedu80135b92021-02-17 15:05:18 +01001294 extra_specs[
1295 "vmware:extra_config"
1296 ] = '{"numa.nodeAffinity":"0"}'
anwarsae5f52c2019-04-22 10:35:27 +05301297 extra_specs["vmware:latency_sensitivity_level"] = "high"
sousaedu80135b92021-02-17 15:05:18 +01001298
anwarsc76a3ee2018-10-04 14:05:32 +05301299 for numa in numas:
tierno1ec592d2020-06-16 15:29:47 +00001300 # overwrite ram and vcpus
sousaedu80135b92021-02-17 15:05:18 +01001301 # check if key "memory" is present in numa else use ram value at flavor
1302 if "memory" in numa:
1303 ram = numa["memory"] * 1024
tierno1ec592d2020-06-16 15:29:47 +00001304 # See for reference: https://specs.openstack.org/openstack/nova-specs/specs/mitaka/
1305 # implemented/virt-driver-cpu-thread-pinning.html
garciadeblasfa35a722019-04-11 19:15:49 +02001306 extra_specs["hw:cpu_sockets"] = 1
sousaedu80135b92021-02-17 15:05:18 +01001307
1308 if "paired-threads" in numa:
1309 vcpus = numa["paired-threads"] * 2
1310 # cpu_thread_policy "require" implies that the compute node must have an
tierno1ec592d2020-06-16 15:29:47 +00001311 # STM architecture
anwarsae5f52c2019-04-22 10:35:27 +05301312 extra_specs["hw:cpu_thread_policy"] = "require"
1313 extra_specs["hw:cpu_policy"] = "dedicated"
sousaedu80135b92021-02-17 15:05:18 +01001314 elif "cores" in numa:
1315 vcpus = numa["cores"]
1316 # cpu_thread_policy "prefer" implies that the host must not have an SMT
tierno1ec592d2020-06-16 15:29:47 +00001317 # architecture, or a non-SMT architecture will be emulated
anwarsae5f52c2019-04-22 10:35:27 +05301318 extra_specs["hw:cpu_thread_policy"] = "isolate"
1319 extra_specs["hw:cpu_policy"] = "dedicated"
sousaedu80135b92021-02-17 15:05:18 +01001320 elif "threads" in numa:
1321 vcpus = numa["threads"]
tierno1ec592d2020-06-16 15:29:47 +00001322 # cpu_thread_policy "prefer" implies that the host may or may not have an SMT
1323 # architecture
anwarsae5f52c2019-04-22 10:35:27 +05301324 extra_specs["hw:cpu_thread_policy"] = "prefer"
1325 extra_specs["hw:cpu_policy"] = "dedicated"
anwarsc76a3ee2018-10-04 14:05:32 +05301326 # for interface in numa.get("interfaces",() ):
1327 # if interface["dedicated"]=="yes":
tierno1ec592d2020-06-16 15:29:47 +00001328 # raise vimconn.VimConnException("Passthrough interfaces are not supported
1329 # for the openstack connector", http_code=vimconn.HTTP_Service_Unavailable)
sousaedu80135b92021-02-17 15:05:18 +01001330 # #TODO, add the key 'pci_passthrough:alias"="<label at config>:<number ifaces>"'
tierno1ec592d2020-06-16 15:29:47 +00001331 # when a way to connect it is available
anwarsae5f52c2019-04-22 10:35:27 +05301332 elif extended.get("cpu-quota"):
sousaedu80135b92021-02-17 15:05:18 +01001333 self.process_resource_quota(
1334 extended.get("cpu-quota"), "cpu", extra_specs
1335 )
1336
anwarsae5f52c2019-04-22 10:35:27 +05301337 if extended.get("mem-quota"):
sousaedu80135b92021-02-17 15:05:18 +01001338 self.process_resource_quota(
1339 extended.get("mem-quota"), "memory", extra_specs
1340 )
1341
anwarsae5f52c2019-04-22 10:35:27 +05301342 if extended.get("vif-quota"):
sousaedu80135b92021-02-17 15:05:18 +01001343 self.process_resource_quota(
1344 extended.get("vif-quota"), "vif", extra_specs
1345 )
1346
anwarsae5f52c2019-04-22 10:35:27 +05301347 if extended.get("disk-io-quota"):
sousaedu80135b92021-02-17 15:05:18 +01001348 self.process_resource_quota(
1349 extended.get("disk-io-quota"), "disk_io", extra_specs
1350 )
1351
rodriguezgar0dd83fd2022-05-15 00:42:45 +02001352 # Set the mempage size as specified in the descriptor
1353 if extended.get("mempage-size"):
1354 if extended.get("mempage-size") == "LARGE":
1355 extra_specs["hw:mem_page_size"] = "large"
1356 elif extended.get("mempage-size") == "SMALL":
1357 extra_specs["hw:mem_page_size"] = "small"
1358 elif extended.get("mempage-size") == "SIZE_2MB":
1359 extra_specs["hw:mem_page_size"] = "2MB"
1360 elif extended.get("mempage-size") == "SIZE_1GB":
1361 extra_specs["hw:mem_page_size"] = "1GB"
1362 elif extended.get("mempage-size") == "PREFER_LARGE":
1363 extra_specs["hw:mem_page_size"] = "any"
1364 else:
1365 # The validations in NBI should make reaching here not possible.
1366 # If this message is shown, check validations
1367 self.logger.debug(
1368 "Invalid mempage-size %s. Will be ignored",
1369 extended.get("mempage-size"),
1370 )
1371
tierno1ec592d2020-06-16 15:29:47 +00001372 # create flavor
sousaedu80135b92021-02-17 15:05:18 +01001373 new_flavor = self.nova.flavors.create(
sousaeduf524da82021-11-22 14:02:17 +00001374 name=name,
1375 ram=ram,
1376 vcpus=vcpus,
1377 disk=flavor_data.get("disk", 0),
1378 ephemeral=flavor_data.get("ephemeral", 0),
sousaedu648ee3d2021-11-22 14:09:15 +00001379 swap=flavor_data.get("swap", 0),
sousaedu80135b92021-02-17 15:05:18 +01001380 is_public=flavor_data.get("is_public", True),
1381 )
tierno1ec592d2020-06-16 15:29:47 +00001382 # add metadata
anwarsae5f52c2019-04-22 10:35:27 +05301383 if extra_specs:
1384 new_flavor.set_keys(extra_specs)
sousaedu80135b92021-02-17 15:05:18 +01001385
anwarsc76a3ee2018-10-04 14:05:32 +05301386 return new_flavor.id
1387 except nvExceptions.Conflict as e:
1388 if change_name_if_used and retry < max_retries:
1389 continue
sousaedu80135b92021-02-17 15:05:18 +01001390
anwarsc76a3ee2018-10-04 14:05:32 +05301391 self._format_exception(e)
tierno1ec592d2020-06-16 15:29:47 +00001392 # except nvExceptions.BadRequest as e:
sousaedu80135b92021-02-17 15:05:18 +01001393 except (
1394 ksExceptions.ClientException,
1395 nvExceptions.ClientException,
1396 ConnectionError,
1397 KeyError,
1398 ) as e:
anwarsc76a3ee2018-10-04 14:05:32 +05301399 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001400
tierno1ec592d2020-06-16 15:29:47 +00001401 def delete_flavor(self, flavor_id):
sousaedu80135b92021-02-17 15:05:18 +01001402 """Deletes a tenant flavor from openstack VIM. Returns the old flavor_id"""
tiernoae4a8d12016-07-08 12:30:39 +02001403 try:
1404 self._reload_connection()
1405 self.nova.flavors.delete(flavor_id)
sousaedu80135b92021-02-17 15:05:18 +01001406
tiernoae4a8d12016-07-08 12:30:39 +02001407 return flavor_id
tierno1ec592d2020-06-16 15:29:47 +00001408 # except nvExceptions.BadRequest as e:
sousaedu80135b92021-02-17 15:05:18 +01001409 except (
1410 nvExceptions.NotFound,
1411 ksExceptions.ClientException,
1412 nvExceptions.ClientException,
1413 ConnectionError,
1414 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001415 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001416
tierno1ec592d2020-06-16 15:29:47 +00001417 def new_image(self, image_dict):
1418 """
tiernoae4a8d12016-07-08 12:30:39 +02001419 Adds a tenant image to VIM. imge_dict is a dictionary with:
1420 name: name
1421 disk_format: qcow2, vhd, vmdk, raw (by default), ...
1422 location: path or URI
1423 public: "yes" or "no"
1424 metadata: metadata of the image
1425 Returns the image_id
tierno1ec592d2020-06-16 15:29:47 +00001426 """
1427 retry = 0
1428 max_retries = 3
sousaedu80135b92021-02-17 15:05:18 +01001429
tierno1ec592d2020-06-16 15:29:47 +00001430 while retry < max_retries:
1431 retry += 1
tierno7edb6752016-03-21 17:37:52 +01001432 try:
1433 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +01001434
tierno1ec592d2020-06-16 15:29:47 +00001435 # determine format http://docs.openstack.org/developer/glance/formats.html
tierno7edb6752016-03-21 17:37:52 +01001436 if "disk_format" in image_dict:
tierno1ec592d2020-06-16 15:29:47 +00001437 disk_format = image_dict["disk_format"]
1438 else: # autodiscover based on extension
sousaedu80135b92021-02-17 15:05:18 +01001439 if image_dict["location"].endswith(".qcow2"):
tierno1ec592d2020-06-16 15:29:47 +00001440 disk_format = "qcow2"
sousaedu80135b92021-02-17 15:05:18 +01001441 elif image_dict["location"].endswith(".vhd"):
tierno1ec592d2020-06-16 15:29:47 +00001442 disk_format = "vhd"
sousaedu80135b92021-02-17 15:05:18 +01001443 elif image_dict["location"].endswith(".vmdk"):
tierno1ec592d2020-06-16 15:29:47 +00001444 disk_format = "vmdk"
sousaedu80135b92021-02-17 15:05:18 +01001445 elif image_dict["location"].endswith(".vdi"):
tierno1ec592d2020-06-16 15:29:47 +00001446 disk_format = "vdi"
sousaedu80135b92021-02-17 15:05:18 +01001447 elif image_dict["location"].endswith(".iso"):
tierno1ec592d2020-06-16 15:29:47 +00001448 disk_format = "iso"
sousaedu80135b92021-02-17 15:05:18 +01001449 elif image_dict["location"].endswith(".aki"):
tierno1ec592d2020-06-16 15:29:47 +00001450 disk_format = "aki"
sousaedu80135b92021-02-17 15:05:18 +01001451 elif image_dict["location"].endswith(".ari"):
tierno1ec592d2020-06-16 15:29:47 +00001452 disk_format = "ari"
sousaedu80135b92021-02-17 15:05:18 +01001453 elif image_dict["location"].endswith(".ami"):
tierno1ec592d2020-06-16 15:29:47 +00001454 disk_format = "ami"
tierno7edb6752016-03-21 17:37:52 +01001455 else:
tierno1ec592d2020-06-16 15:29:47 +00001456 disk_format = "raw"
sousaedu80135b92021-02-17 15:05:18 +01001457
1458 self.logger.debug(
1459 "new_image: '%s' loading from '%s'",
1460 image_dict["name"],
1461 image_dict["location"],
1462 )
shashankjain3c83a212018-10-04 13:05:46 +05301463 if self.vim_type == "VIO":
1464 container_format = "bare"
sousaedu80135b92021-02-17 15:05:18 +01001465 if "container_format" in image_dict:
1466 container_format = image_dict["container_format"]
1467
1468 new_image = self.glance.images.create(
1469 name=image_dict["name"],
1470 container_format=container_format,
1471 disk_format=disk_format,
1472 )
shashankjain3c83a212018-10-04 13:05:46 +05301473 else:
sousaedu80135b92021-02-17 15:05:18 +01001474 new_image = self.glance.images.create(name=image_dict["name"])
1475
1476 if image_dict["location"].startswith("http"):
tierno1beea862018-07-11 15:47:37 +02001477 # TODO there is not a method to direct download. It must be downloaded locally with requests
tierno72774862020-05-04 11:44:15 +00001478 raise vimconn.VimConnNotImplemented("Cannot create image from URL")
tierno1ec592d2020-06-16 15:29:47 +00001479 else: # local path
sousaedu80135b92021-02-17 15:05:18 +01001480 with open(image_dict["location"]) as fimage:
tierno1beea862018-07-11 15:47:37 +02001481 self.glance.images.upload(new_image.id, fimage)
sousaedu80135b92021-02-17 15:05:18 +01001482 # new_image = self.glancev1.images.create(name=image_dict["name"], is_public=
1483 # image_dict.get("public","yes")=="yes",
tierno1beea862018-07-11 15:47:37 +02001484 # container_format="bare", data=fimage, disk_format=disk_format)
sousaedu80135b92021-02-17 15:05:18 +01001485
1486 metadata_to_load = image_dict.get("metadata")
1487
1488 # TODO location is a reserved word for current openstack versions. fixed for VIO please check
tierno1ec592d2020-06-16 15:29:47 +00001489 # for openstack
shashankjain3c83a212018-10-04 13:05:46 +05301490 if self.vim_type == "VIO":
sousaedu80135b92021-02-17 15:05:18 +01001491 metadata_to_load["upload_location"] = image_dict["location"]
shashankjain3c83a212018-10-04 13:05:46 +05301492 else:
sousaedu80135b92021-02-17 15:05:18 +01001493 metadata_to_load["location"] = image_dict["location"]
1494
tierno1beea862018-07-11 15:47:37 +02001495 self.glance.images.update(new_image.id, **metadata_to_load)
sousaedu80135b92021-02-17 15:05:18 +01001496
tiernoae4a8d12016-07-08 12:30:39 +02001497 return new_image.id
sousaedu80135b92021-02-17 15:05:18 +01001498 except (
1499 nvExceptions.Conflict,
1500 ksExceptions.ClientException,
1501 nvExceptions.ClientException,
1502 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001503 self._format_exception(e)
sousaedu80135b92021-02-17 15:05:18 +01001504 except (
1505 HTTPException,
1506 gl1Exceptions.HTTPException,
1507 gl1Exceptions.CommunicationError,
1508 ConnectionError,
1509 ) as e:
tierno1ec592d2020-06-16 15:29:47 +00001510 if retry == max_retries:
tiernoae4a8d12016-07-08 12:30:39 +02001511 continue
sousaedu80135b92021-02-17 15:05:18 +01001512
tiernoae4a8d12016-07-08 12:30:39 +02001513 self._format_exception(e)
tierno1ec592d2020-06-16 15:29:47 +00001514 except IOError as e: # can not open the file
sousaedu80135b92021-02-17 15:05:18 +01001515 raise vimconn.VimConnConnectionException(
1516 "{}: {} for {}".format(type(e).__name__, e, image_dict["location"]),
1517 http_code=vimconn.HTTP_Bad_Request,
1518 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001519
tiernoae4a8d12016-07-08 12:30:39 +02001520 def delete_image(self, image_id):
sousaedu80135b92021-02-17 15:05:18 +01001521 """Deletes a tenant image from openstack VIM. Returns the old id"""
tiernoae4a8d12016-07-08 12:30:39 +02001522 try:
1523 self._reload_connection()
tierno1beea862018-07-11 15:47:37 +02001524 self.glance.images.delete(image_id)
sousaedu80135b92021-02-17 15:05:18 +01001525
tiernoae4a8d12016-07-08 12:30:39 +02001526 return image_id
sousaedu80135b92021-02-17 15:05:18 +01001527 except (
1528 nvExceptions.NotFound,
1529 ksExceptions.ClientException,
1530 nvExceptions.ClientException,
1531 gl1Exceptions.CommunicationError,
1532 gl1Exceptions.HTTPNotFound,
1533 ConnectionError,
1534 ) as e: # TODO remove
tiernoae4a8d12016-07-08 12:30:39 +02001535 self._format_exception(e)
1536
1537 def get_image_id_from_path(self, path):
tierno1ec592d2020-06-16 15:29:47 +00001538 """Get the image id from image path in the VIM database. Returns the image_id"""
tiernoae4a8d12016-07-08 12:30:39 +02001539 try:
1540 self._reload_connection()
tierno1beea862018-07-11 15:47:37 +02001541 images = self.glance.images.list()
sousaedu80135b92021-02-17 15:05:18 +01001542
tiernoae4a8d12016-07-08 12:30:39 +02001543 for image in images:
tierno1ec592d2020-06-16 15:29:47 +00001544 if image.metadata.get("location") == path:
tiernoae4a8d12016-07-08 12:30:39 +02001545 return image.id
sousaedu80135b92021-02-17 15:05:18 +01001546
1547 raise vimconn.VimConnNotFoundException(
1548 "image with location '{}' not found".format(path)
1549 )
1550 except (
1551 ksExceptions.ClientException,
1552 nvExceptions.ClientException,
1553 gl1Exceptions.CommunicationError,
1554 ConnectionError,
1555 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001556 self._format_exception(e)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001557
garciadeblasb69fa9f2016-09-28 12:04:10 +02001558 def get_image_list(self, filter_dict={}):
tierno1ec592d2020-06-16 15:29:47 +00001559 """Obtain tenant images from VIM
garciadeblasb69fa9f2016-09-28 12:04:10 +02001560 Filter_dict can be:
1561 id: image id
1562 name: image name
1563 checksum: image checksum
1564 Returns the image list of dictionaries:
1565 [{<the fields at Filter_dict plus some VIM specific>}, ...]
1566 List can be empty
tierno1ec592d2020-06-16 15:29:47 +00001567 """
garciadeblasb69fa9f2016-09-28 12:04:10 +02001568 self.logger.debug("Getting image list from VIM filter: '%s'", str(filter_dict))
sousaedu80135b92021-02-17 15:05:18 +01001569
garciadeblasb69fa9f2016-09-28 12:04:10 +02001570 try:
1571 self._reload_connection()
tierno1ec592d2020-06-16 15:29:47 +00001572 # filter_dict_os = filter_dict.copy()
1573 # First we filter by the available filter fields: name, id. The others are removed.
tierno1beea862018-07-11 15:47:37 +02001574 image_list = self.glance.images.list()
garciadeblasb69fa9f2016-09-28 12:04:10 +02001575 filtered_list = []
sousaedu80135b92021-02-17 15:05:18 +01001576
garciadeblasb69fa9f2016-09-28 12:04:10 +02001577 for image in image_list:
tierno3cb8dc32017-10-24 18:13:19 +02001578 try:
tierno1beea862018-07-11 15:47:37 +02001579 if filter_dict.get("name") and image["name"] != filter_dict["name"]:
1580 continue
sousaedu80135b92021-02-17 15:05:18 +01001581
tierno1beea862018-07-11 15:47:37 +02001582 if filter_dict.get("id") and image["id"] != filter_dict["id"]:
1583 continue
sousaedu80135b92021-02-17 15:05:18 +01001584
1585 if (
1586 filter_dict.get("checksum")
1587 and image["checksum"] != filter_dict["checksum"]
1588 ):
tierno1beea862018-07-11 15:47:37 +02001589 continue
1590
1591 filtered_list.append(image.copy())
tierno3cb8dc32017-10-24 18:13:19 +02001592 except gl1Exceptions.HTTPNotFound:
1593 pass
sousaedu80135b92021-02-17 15:05:18 +01001594
garciadeblasb69fa9f2016-09-28 12:04:10 +02001595 return filtered_list
sousaedu80135b92021-02-17 15:05:18 +01001596 except (
1597 ksExceptions.ClientException,
1598 nvExceptions.ClientException,
1599 gl1Exceptions.CommunicationError,
1600 ConnectionError,
1601 ) as e:
garciadeblasb69fa9f2016-09-28 12:04:10 +02001602 self._format_exception(e)
1603
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001604 def __wait_for_vm(self, vm_id, status):
1605 """wait until vm is in the desired status and return True.
1606 If the VM gets in ERROR status, return false.
1607 If the timeout is reached generate an exception"""
1608 elapsed_time = 0
1609 while elapsed_time < server_timeout:
1610 vm_status = self.nova.servers.get(vm_id).status
sousaedu80135b92021-02-17 15:05:18 +01001611
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001612 if vm_status == status:
1613 return True
sousaedu80135b92021-02-17 15:05:18 +01001614
1615 if vm_status == "ERROR":
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001616 return False
sousaedu80135b92021-02-17 15:05:18 +01001617
tierno1df468d2018-07-06 14:25:16 +02001618 time.sleep(5)
1619 elapsed_time += 5
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001620
1621 # if we exceeded the timeout rollback
1622 if elapsed_time >= server_timeout:
sousaedu80135b92021-02-17 15:05:18 +01001623 raise vimconn.VimConnException(
1624 "Timeout waiting for instance " + vm_id + " to get " + status,
1625 http_code=vimconn.HTTP_Request_Timeout,
1626 )
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001627
mirabal29356312017-07-27 12:21:22 +02001628 def _get_openstack_availablity_zones(self):
1629 """
1630 Get from openstack availability zones available
1631 :return:
1632 """
1633 try:
1634 openstack_availability_zone = self.nova.availability_zones.list()
sousaedu80135b92021-02-17 15:05:18 +01001635 openstack_availability_zone = [
1636 str(zone.zoneName)
1637 for zone in openstack_availability_zone
1638 if zone.zoneName != "internal"
1639 ]
1640
mirabal29356312017-07-27 12:21:22 +02001641 return openstack_availability_zone
tierno1ec592d2020-06-16 15:29:47 +00001642 except Exception:
mirabal29356312017-07-27 12:21:22 +02001643 return None
1644
1645 def _set_availablity_zones(self):
1646 """
1647 Set vim availablity zone
1648 :return:
1649 """
sousaedu80135b92021-02-17 15:05:18 +01001650 if "availability_zone" in self.config:
1651 vim_availability_zones = self.config.get("availability_zone")
mirabal29356312017-07-27 12:21:22 +02001652
mirabal29356312017-07-27 12:21:22 +02001653 if isinstance(vim_availability_zones, str):
1654 self.availability_zone = [vim_availability_zones]
1655 elif isinstance(vim_availability_zones, list):
1656 self.availability_zone = vim_availability_zones
1657 else:
1658 self.availability_zone = self._get_openstack_availablity_zones()
1659
sousaedu80135b92021-02-17 15:05:18 +01001660 def _get_vm_availability_zone(
1661 self, availability_zone_index, availability_zone_list
1662 ):
mirabal29356312017-07-27 12:21:22 +02001663 """
tierno5a3273c2017-08-29 11:43:46 +02001664 Return thge availability zone to be used by the created VM.
1665 :return: The VIM availability zone to be used or None
mirabal29356312017-07-27 12:21:22 +02001666 """
tierno5a3273c2017-08-29 11:43:46 +02001667 if availability_zone_index is None:
sousaedu80135b92021-02-17 15:05:18 +01001668 if not self.config.get("availability_zone"):
tierno5a3273c2017-08-29 11:43:46 +02001669 return None
sousaedu80135b92021-02-17 15:05:18 +01001670 elif isinstance(self.config.get("availability_zone"), str):
1671 return self.config["availability_zone"]
tierno5a3273c2017-08-29 11:43:46 +02001672 else:
1673 # TODO consider using a different parameter at config for default AV and AV list match
sousaedu80135b92021-02-17 15:05:18 +01001674 return self.config["availability_zone"][0]
mirabal29356312017-07-27 12:21:22 +02001675
tierno5a3273c2017-08-29 11:43:46 +02001676 vim_availability_zones = self.availability_zone
1677 # check if VIM offer enough availability zones describe in the VNFD
sousaedu80135b92021-02-17 15:05:18 +01001678 if vim_availability_zones and len(availability_zone_list) <= len(
1679 vim_availability_zones
1680 ):
tierno5a3273c2017-08-29 11:43:46 +02001681 # check if all the names of NFV AV match VIM AV names
1682 match_by_index = False
1683 for av in availability_zone_list:
1684 if av not in vim_availability_zones:
1685 match_by_index = True
1686 break
sousaedu80135b92021-02-17 15:05:18 +01001687
tierno5a3273c2017-08-29 11:43:46 +02001688 if match_by_index:
1689 return vim_availability_zones[availability_zone_index]
1690 else:
1691 return availability_zone_list[availability_zone_index]
mirabal29356312017-07-27 12:21:22 +02001692 else:
sousaedu80135b92021-02-17 15:05:18 +01001693 raise vimconn.VimConnConflictException(
1694 "No enough availability zones at VIM for this deployment"
1695 )
mirabal29356312017-07-27 12:21:22 +02001696
sousaedu80135b92021-02-17 15:05:18 +01001697 def new_vminstance(
1698 self,
1699 name,
1700 description,
1701 start,
1702 image_id,
1703 flavor_id,
Alexis Romerob70f4ed2022-03-11 18:00:49 +01001704 affinity_group_list,
sousaedu80135b92021-02-17 15:05:18 +01001705 net_list,
1706 cloud_config=None,
1707 disk_list=None,
1708 availability_zone_index=None,
1709 availability_zone_list=None,
1710 ):
tierno98e909c2017-10-14 13:27:03 +02001711 """Adds a VM instance to VIM
tierno7edb6752016-03-21 17:37:52 +01001712 Params:
1713 start: indicates if VM must start or boot in pause mode. Ignored
Alexis Romerob70f4ed2022-03-11 18:00:49 +01001714 image_id,flavor_id: image and flavor uuid
1715 affinity_group_list: list of affinity groups, each one is a dictionary.
1716 Ignore if empty.
tierno7edb6752016-03-21 17:37:52 +01001717 net_list: list of interfaces, each one is a dictionary with:
1718 name:
1719 net_id: network uuid to connect
1720 vpci: virtual vcpi to assign, ignored because openstack lack #TODO
1721 model: interface model, ignored #TODO
1722 mac_address: used for SR-IOV ifaces #TODO for other types
1723 use: 'data', 'bridge', 'mgmt'
tierno66eba6e2017-11-10 17:09:18 +01001724 type: 'virtual', 'PCI-PASSTHROUGH'('PF'), 'SR-IOV'('VF'), 'VFnotShared'
tierno7edb6752016-03-21 17:37:52 +01001725 vim_id: filled/added by this function
ahmadsaf853d452016-12-22 11:33:47 +05001726 floating_ip: True/False (or it can be None)
tierno70eeb182020-10-19 16:38:00 +00001727 port_security: True/False
tierno41a69812018-02-16 14:34:33 +01001728 'cloud_config': (optional) dictionary with:
tierno1d213f42020-04-24 14:02:51 +00001729 'key-pairs': (optional) list of strings with the public key to be inserted to the default user
1730 'users': (optional) list of users to be inserted, each item is a dict with:
1731 'name': (mandatory) user name,
1732 'key-pairs': (optional) list of strings with the public key to be inserted to the user
1733 'user-data': (optional) string is a text script to be passed directly to cloud-init
1734 'config-files': (optional). List of files to be transferred. Each item is a dict with:
1735 'dest': (mandatory) string with the destination absolute path
1736 'encoding': (optional, by default text). Can be one of:
1737 'b64', 'base64', 'gz', 'gz+b64', 'gz+base64', 'gzip+b64', 'gzip+base64'
1738 'content' (mandatory): string with the content of the file
1739 'permissions': (optional) string with file permissions, typically octal notation '0644'
1740 'owner': (optional) file owner, string with the format 'owner:group'
1741 'boot-data-drive': boolean to indicate if user-data must be passed using a boot drive (hard disk)
mirabal29356312017-07-27 12:21:22 +02001742 'disk_list': (optional) list with additional disks to the VM. Each item is a dict with:
1743 'image_id': (optional). VIM id of an existing image. If not provided an empty disk must be mounted
1744 'size': (mandatory) string with the size of the disk in GB
tierno1df468d2018-07-06 14:25:16 +02001745 'vim_id' (optional) should use this existing volume id
tierno5a3273c2017-08-29 11:43:46 +02001746 availability_zone_index: Index of availability_zone_list to use for this this VM. None if not AV required
1747 availability_zone_list: list of availability zones given by user in the VNFD descriptor. Ignore if
1748 availability_zone_index is None
tierno7edb6752016-03-21 17:37:52 +01001749 #TODO ip, security groups
tierno98e909c2017-10-14 13:27:03 +02001750 Returns a tuple with the instance identifier and created_items or raises an exception on error
1751 created_items can be None or a dictionary where this method can include key-values that will be passed to
1752 the method delete_vminstance and action_vminstance. Can be used to store created ports, volumes, etc.
1753 Format is vimconnector dependent, but do not use nested dictionaries and a value of None should be the same
1754 as not present.
1755 """
sousaedu80135b92021-02-17 15:05:18 +01001756 self.logger.debug(
1757 "new_vminstance input: image='%s' flavor='%s' nics='%s'",
1758 image_id,
1759 flavor_id,
1760 str(net_list),
1761 )
1762
tierno7edb6752016-03-21 17:37:52 +01001763 try:
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001764 server = None
tierno98e909c2017-10-14 13:27:03 +02001765 created_items = {}
tiernob0b9dab2017-10-14 14:25:20 +02001766 # metadata = {}
tierno98e909c2017-10-14 13:27:03 +02001767 net_list_vim = []
tierno1ec592d2020-06-16 15:29:47 +00001768 external_network = []
1769 # ^list of external networks to be connected to instance, later on used to create floating_ip
sousaedu80135b92021-02-17 15:05:18 +01001770 no_secured_ports = [] # List of port-is with port-security disabled
tierno7edb6752016-03-21 17:37:52 +01001771 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +01001772 # metadata_vpci = {} # For a specific neutron plugin
tiernob84cbdc2017-07-07 14:30:30 +02001773 block_device_mapping = None
tiernoa05b65a2019-02-01 12:30:27 +00001774
tierno7edb6752016-03-21 17:37:52 +01001775 for net in net_list:
sousaedu80135b92021-02-17 15:05:18 +01001776 if not net.get("net_id"): # skip non connected iface
tierno7edb6752016-03-21 17:37:52 +01001777 continue
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001778
tiernoa05b65a2019-02-01 12:30:27 +00001779 port_dict = {
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001780 "network_id": net["net_id"],
1781 "name": net.get("name"),
sousaedu80135b92021-02-17 15:05:18 +01001782 "admin_state_up": True,
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001783 }
sousaedu80135b92021-02-17 15:05:18 +01001784
1785 if (
1786 self.config.get("security_groups")
1787 and net.get("port_security") is not False
1788 and not self.config.get("no_port_security_extension")
1789 ):
tiernoa05b65a2019-02-01 12:30:27 +00001790 if not self.security_groups_id:
1791 self._get_ids_from_name()
sousaedu80135b92021-02-17 15:05:18 +01001792
tiernoa05b65a2019-02-01 12:30:27 +00001793 port_dict["security_groups"] = self.security_groups_id
1794
tierno1ec592d2020-06-16 15:29:47 +00001795 if net["type"] == "virtual":
tiernob0b9dab2017-10-14 14:25:20 +02001796 pass
1797 # if "vpci" in net:
1798 # metadata_vpci[ net["net_id"] ] = [[ net["vpci"], "" ]]
tierno66eba6e2017-11-10 17:09:18 +01001799 elif net["type"] == "VF" or net["type"] == "SR-IOV": # for VF
tiernob0b9dab2017-10-14 14:25:20 +02001800 # if "vpci" in net:
1801 # if "VF" not in metadata_vpci:
1802 # metadata_vpci["VF"]=[]
1803 # metadata_vpci["VF"].append([ net["vpci"], "" ])
tierno1ec592d2020-06-16 15:29:47 +00001804 port_dict["binding:vnic_type"] = "direct"
sousaedu80135b92021-02-17 15:05:18 +01001805
tiernob0b9dab2017-10-14 14:25:20 +02001806 # VIO specific Changes
kate721d79b2017-06-24 04:21:38 -07001807 if self.vim_type == "VIO":
tiernob0b9dab2017-10-14 14:25:20 +02001808 # Need to create port with port_security_enabled = False and no-security-groups
tierno1ec592d2020-06-16 15:29:47 +00001809 port_dict["port_security_enabled"] = False
1810 port_dict["provider_security_groups"] = []
1811 port_dict["security_groups"] = []
sousaedu80135b92021-02-17 15:05:18 +01001812 else: # For PT PCI-PASSTHROUGH
tiernob0b9dab2017-10-14 14:25:20 +02001813 # if "vpci" in net:
1814 # if "PF" not in metadata_vpci:
1815 # metadata_vpci["PF"]=[]
1816 # metadata_vpci["PF"].append([ net["vpci"], "" ])
tierno1ec592d2020-06-16 15:29:47 +00001817 port_dict["binding:vnic_type"] = "direct-physical"
sousaedu80135b92021-02-17 15:05:18 +01001818
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001819 if not port_dict["name"]:
tierno1ec592d2020-06-16 15:29:47 +00001820 port_dict["name"] = name
sousaedu80135b92021-02-17 15:05:18 +01001821
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001822 if net.get("mac_address"):
tierno1ec592d2020-06-16 15:29:47 +00001823 port_dict["mac_address"] = net["mac_address"]
sousaedu80135b92021-02-17 15:05:18 +01001824
tierno41a69812018-02-16 14:34:33 +01001825 if net.get("ip_address"):
sousaedu80135b92021-02-17 15:05:18 +01001826 port_dict["fixed_ips"] = [{"ip_address": net["ip_address"]}]
1827 # TODO add "subnet_id": <subnet_id>
1828
tierno1ec592d2020-06-16 15:29:47 +00001829 new_port = self.neutron.create_port({"port": port_dict})
tierno00e3df72017-11-29 17:20:13 +01001830 created_items["port:" + str(new_port["port"]["id"])] = True
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001831 net["mac_adress"] = new_port["port"]["mac_address"]
1832 net["vim_id"] = new_port["port"]["id"]
tiernob84cbdc2017-07-07 14:30:30 +02001833 # if try to use a network without subnetwork, it will return a emtpy list
1834 fixed_ips = new_port["port"].get("fixed_ips")
sousaedu80135b92021-02-17 15:05:18 +01001835
tiernob84cbdc2017-07-07 14:30:30 +02001836 if fixed_ips:
1837 net["ip"] = fixed_ips[0].get("ip_address")
1838 else:
1839 net["ip"] = None
montesmoreno994a29d2017-08-22 11:23:06 +02001840
1841 port = {"port-id": new_port["port"]["id"]}
1842 if float(self.nova.api_version.get_string()) >= 2.32:
1843 port["tag"] = new_port["port"]["name"]
sousaedu80135b92021-02-17 15:05:18 +01001844
montesmoreno994a29d2017-08-22 11:23:06 +02001845 net_list_vim.append(port)
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001846
sousaedu80135b92021-02-17 15:05:18 +01001847 if net.get("floating_ip", False):
1848 net["exit_on_floating_ip_error"] = True
ahmadsaf853d452016-12-22 11:33:47 +05001849 external_network.append(net)
sousaedu80135b92021-02-17 15:05:18 +01001850 elif net["use"] == "mgmt" and self.config.get("use_floating_ip"):
1851 net["exit_on_floating_ip_error"] = False
tiernof8383b82017-01-18 15:49:48 +01001852 external_network.append(net)
sousaedu80135b92021-02-17 15:05:18 +01001853 net["floating_ip"] = self.config.get("use_floating_ip")
tiernof8383b82017-01-18 15:49:48 +01001854
tierno1ec592d2020-06-16 15:29:47 +00001855 # If port security is disabled when the port has not yet been attached to the VM, then all vm traffic
1856 # is dropped.
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001857 # As a workaround we wait until the VM is active and then disable the port-security
sousaedu80135b92021-02-17 15:05:18 +01001858 if net.get("port_security") is False and not self.config.get(
1859 "no_port_security_extension"
1860 ):
1861 no_secured_ports.append(
1862 (
1863 new_port["port"]["id"],
1864 net.get("port_security_disable_strategy"),
1865 )
1866 )
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001867
tiernob0b9dab2017-10-14 14:25:20 +02001868 # if metadata_vpci:
1869 # metadata = {"pci_assignement": json.dumps(metadata_vpci)}
1870 # if len(metadata["pci_assignement"]) >255:
1871 # #limit the metadata size
1872 # #metadata["pci_assignement"] = metadata["pci_assignement"][0:255]
1873 # self.logger.warn("Metadata deleted since it exceeds the expected length (255) ")
1874 # metadata = {}
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001875
sousaedu80135b92021-02-17 15:05:18 +01001876 self.logger.debug(
1877 "name '%s' image_id '%s'flavor_id '%s' net_list_vim '%s' description '%s'",
1878 name,
1879 image_id,
1880 flavor_id,
1881 str(net_list_vim),
1882 description,
1883 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001884
tierno98e909c2017-10-14 13:27:03 +02001885 # cloud config
tierno0a1437e2017-10-02 00:17:43 +02001886 config_drive, userdata = self._create_user_data(cloud_config)
montesmoreno0c8def02016-12-22 12:16:23 +00001887
Alexis Romero247cc432022-05-12 13:23:25 +02001888 # get availability Zone
1889 vm_av_zone = self._get_vm_availability_zone(
1890 availability_zone_index, availability_zone_list
1891 )
1892
tierno98e909c2017-10-14 13:27:03 +02001893 # Create additional volumes in case these are present in disk_list
palaciosj8f2060b2022-02-24 12:05:59 +00001894 existing_vim_volumes = []
sousaedu80135b92021-02-17 15:05:18 +01001895 base_disk_index = ord("b")
aticig179e0022022-03-29 13:15:45 +03001896 boot_volume_id = None
tierno1df468d2018-07-06 14:25:16 +02001897 if disk_list:
tiernob84cbdc2017-07-07 14:30:30 +02001898 block_device_mapping = {}
montesmoreno0c8def02016-12-22 12:16:23 +00001899 for disk in disk_list:
sousaedu80135b92021-02-17 15:05:18 +01001900 if disk.get("vim_id"):
1901 block_device_mapping["_vd" + chr(base_disk_index)] = disk[
1902 "vim_id"
1903 ]
palaciosj8f2060b2022-02-24 12:05:59 +00001904 existing_vim_volumes.append({"id": disk["vim_id"]})
montesmoreno0c8def02016-12-22 12:16:23 +00001905 else:
sousaedu80135b92021-02-17 15:05:18 +01001906 if "image_id" in disk:
aticig179e0022022-03-29 13:15:45 +03001907 base_disk_index = ord("a")
sousaedu80135b92021-02-17 15:05:18 +01001908 volume = self.cinder.volumes.create(
1909 size=disk["size"],
1910 name=name + "_vd" + chr(base_disk_index),
1911 imageRef=disk["image_id"],
Alexis Romero247cc432022-05-12 13:23:25 +02001912 # Make sure volume is in the same AZ as the VM to be attached to
1913 availability_zone=vm_av_zone,
sousaedu80135b92021-02-17 15:05:18 +01001914 )
aticig179e0022022-03-29 13:15:45 +03001915 boot_volume_id = volume.id
tierno1df468d2018-07-06 14:25:16 +02001916 else:
sousaedu80135b92021-02-17 15:05:18 +01001917 volume = self.cinder.volumes.create(
1918 size=disk["size"],
1919 name=name + "_vd" + chr(base_disk_index),
Alexis Romero247cc432022-05-12 13:23:25 +02001920 # Make sure volume is in the same AZ as the VM to be attached to
1921 availability_zone=vm_av_zone,
sousaedu80135b92021-02-17 15:05:18 +01001922 )
1923
tierno1df468d2018-07-06 14:25:16 +02001924 created_items["volume:" + str(volume.id)] = True
sousaedu80135b92021-02-17 15:05:18 +01001925 block_device_mapping["_vd" + chr(base_disk_index)] = volume.id
1926
montesmoreno0c8def02016-12-22 12:16:23 +00001927 base_disk_index += 1
1928
tierno1df468d2018-07-06 14:25:16 +02001929 # Wait until created volumes are with status available
montesmoreno0c8def02016-12-22 12:16:23 +00001930 elapsed_time = 0
tierno1df468d2018-07-06 14:25:16 +02001931 while elapsed_time < volume_timeout:
1932 for created_item in created_items:
1933 v, _, volume_id = created_item.partition(":")
sousaedu80135b92021-02-17 15:05:18 +01001934 if v == "volume":
1935 if self.cinder.volumes.get(volume_id).status != "available":
tierno1df468d2018-07-06 14:25:16 +02001936 break
1937 else: # all ready: break from while
1938 break
sousaedu80135b92021-02-17 15:05:18 +01001939
tierno1df468d2018-07-06 14:25:16 +02001940 time.sleep(5)
1941 elapsed_time += 5
sousaedu80135b92021-02-17 15:05:18 +01001942
palaciosj8f2060b2022-02-24 12:05:59 +00001943 # Wait until existing volumes in vim are with status available
1944 while elapsed_time < volume_timeout:
1945 for volume in existing_vim_volumes:
1946 if self.cinder.volumes.get(volume["id"]).status != "available":
1947 break
1948 else: # all ready: break from while
1949 break
1950
1951 time.sleep(5)
1952 elapsed_time += 5
1953
tiernob0b9dab2017-10-14 14:25:20 +02001954 # If we exceeded the timeout rollback
montesmoreno0c8def02016-12-22 12:16:23 +00001955 if elapsed_time >= volume_timeout:
sousaedu80135b92021-02-17 15:05:18 +01001956 raise vimconn.VimConnException(
1957 "Timeout creating volumes for instance " + name,
1958 http_code=vimconn.HTTP_Request_Timeout,
1959 )
aticig179e0022022-03-29 13:15:45 +03001960 if boot_volume_id:
1961 self.cinder.volumes.set_bootable(boot_volume_id, True)
montesmoreno0c8def02016-12-22 12:16:23 +00001962
Alexis Romerob70f4ed2022-03-11 18:00:49 +01001963 # Manage affinity groups/server groups
1964 server_group_id = None
1965 scheduller_hints = {}
1966
1967 if affinity_group_list:
1968 # Only first id on the list will be used. Openstack restriction
1969 server_group_id = affinity_group_list[0]["affinity_group_id"]
1970 scheduller_hints["group"] = server_group_id
1971
sousaedu80135b92021-02-17 15:05:18 +01001972 self.logger.debug(
1973 "nova.servers.create({}, {}, {}, nics={}, security_groups={}, "
1974 "availability_zone={}, key_name={}, userdata={}, config_drive={}, "
Alexis Romerob70f4ed2022-03-11 18:00:49 +01001975 "block_device_mapping={}, server_group={})".format(
sousaedu80135b92021-02-17 15:05:18 +01001976 name,
1977 image_id,
1978 flavor_id,
1979 net_list_vim,
1980 self.config.get("security_groups"),
1981 vm_av_zone,
1982 self.config.get("keypair"),
1983 userdata,
1984 config_drive,
1985 block_device_mapping,
Alexis Romerob70f4ed2022-03-11 18:00:49 +01001986 server_group_id,
sousaedu80135b92021-02-17 15:05:18 +01001987 )
1988 )
1989 server = self.nova.servers.create(
1990 name,
1991 image_id,
1992 flavor_id,
1993 nics=net_list_vim,
1994 security_groups=self.config.get("security_groups"),
1995 # TODO remove security_groups in future versions. Already at neutron port
1996 availability_zone=vm_av_zone,
1997 key_name=self.config.get("keypair"),
1998 userdata=userdata,
1999 config_drive=config_drive,
2000 block_device_mapping=block_device_mapping,
Alexis Romerob70f4ed2022-03-11 18:00:49 +01002001 scheduler_hints=scheduller_hints,
sousaedu80135b92021-02-17 15:05:18 +01002002 ) # , description=description)
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02002003
tierno326fd5e2018-02-22 11:58:59 +01002004 vm_start_time = time.time()
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02002005 # Previously mentioned workaround to wait until the VM is active and then disable the port-security
2006 if no_secured_ports:
sousaedu80135b92021-02-17 15:05:18 +01002007 self.__wait_for_vm(server.id, "ACTIVE")
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02002008
bravof7a1f5252020-10-20 10:27:42 -03002009 for port in no_secured_ports:
2010 port_update = {
sousaedu80135b92021-02-17 15:05:18 +01002011 "port": {"port_security_enabled": False, "security_groups": None}
bravof7a1f5252020-10-20 10:27:42 -03002012 }
2013
2014 if port[1] == "allow-address-pairs":
2015 port_update = {
sousaedu80135b92021-02-17 15:05:18 +01002016 "port": {"allowed_address_pairs": [{"ip_address": "0.0.0.0/0"}]}
bravof7a1f5252020-10-20 10:27:42 -03002017 }
2018
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02002019 try:
bravof7a1f5252020-10-20 10:27:42 -03002020 self.neutron.update_port(port[0], port_update)
tierno1ec592d2020-06-16 15:29:47 +00002021 except Exception:
bravof7a1f5252020-10-20 10:27:42 -03002022 raise vimconn.VimConnException(
sousaedu80135b92021-02-17 15:05:18 +01002023 "It was not possible to disable port security for port {}".format(
2024 port[0]
2025 )
bravof7a1f5252020-10-20 10:27:42 -03002026 )
2027
tierno98e909c2017-10-14 13:27:03 +02002028 # print "DONE :-)", server
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02002029
tierno4d1ce222018-04-06 10:41:06 +02002030 # pool_id = None
ahmadsaf853d452016-12-22 11:33:47 +05002031 for floating_network in external_network:
tiernof8383b82017-01-18 15:49:48 +01002032 try:
tiernof8383b82017-01-18 15:49:48 +01002033 assigned = False
tiernocb66c7e2020-07-22 10:42:58 +00002034 floating_ip_retries = 3
2035 # In case of RO in HA there can be conflicts, two RO trying to assign same floating IP, so retry
2036 # several times
tierno98e909c2017-10-14 13:27:03 +02002037 while not assigned:
sousaedu80135b92021-02-17 15:05:18 +01002038 floating_ips = self.neutron.list_floatingips().get(
2039 "floatingips", ()
2040 )
2041 random.shuffle(floating_ips) # randomize
tiernocb66c7e2020-07-22 10:42:58 +00002042 for fip in floating_ips:
sousaedu80135b92021-02-17 15:05:18 +01002043 if (
2044 fip.get("port_id")
2045 or fip.get("tenant_id") != server.tenant_id
2046 ):
tierno326fd5e2018-02-22 11:58:59 +01002047 continue
sousaedu80135b92021-02-17 15:05:18 +01002048
2049 if isinstance(floating_network["floating_ip"], str):
2050 if (
2051 fip.get("floating_network_id")
2052 != floating_network["floating_ip"]
2053 ):
tierno326fd5e2018-02-22 11:58:59 +01002054 continue
sousaedu80135b92021-02-17 15:05:18 +01002055
tiernocb66c7e2020-07-22 10:42:58 +00002056 free_floating_ip = fip["id"]
2057 break
tiernof8383b82017-01-18 15:49:48 +01002058 else:
sousaedu80135b92021-02-17 15:05:18 +01002059 if (
2060 isinstance(floating_network["floating_ip"], str)
2061 and floating_network["floating_ip"].lower() != "true"
2062 ):
2063 pool_id = floating_network["floating_ip"]
tierno326fd5e2018-02-22 11:58:59 +01002064 else:
tierno4d1ce222018-04-06 10:41:06 +02002065 # Find the external network
tierno326fd5e2018-02-22 11:58:59 +01002066 external_nets = list()
sousaedu80135b92021-02-17 15:05:18 +01002067
2068 for net in self.neutron.list_networks()["networks"]:
2069 if net["router:external"]:
tierno1ec592d2020-06-16 15:29:47 +00002070 external_nets.append(net)
tiernof8383b82017-01-18 15:49:48 +01002071
tierno326fd5e2018-02-22 11:58:59 +01002072 if len(external_nets) == 0:
tierno1ec592d2020-06-16 15:29:47 +00002073 raise vimconn.VimConnException(
sousaedu80135b92021-02-17 15:05:18 +01002074 "Cannot create floating_ip automatically since "
2075 "no external network is present",
2076 http_code=vimconn.HTTP_Conflict,
2077 )
2078
tierno326fd5e2018-02-22 11:58:59 +01002079 if len(external_nets) > 1:
tierno1ec592d2020-06-16 15:29:47 +00002080 raise vimconn.VimConnException(
sousaedu80135b92021-02-17 15:05:18 +01002081 "Cannot create floating_ip automatically since "
2082 "multiple external networks are present",
2083 http_code=vimconn.HTTP_Conflict,
2084 )
tiernof8383b82017-01-18 15:49:48 +01002085
sousaedu80135b92021-02-17 15:05:18 +01002086 pool_id = external_nets[0].get("id")
2087
2088 param = {
2089 "floatingip": {
2090 "floating_network_id": pool_id,
2091 "tenant_id": server.tenant_id,
2092 }
2093 }
2094
ahmadsaf853d452016-12-22 11:33:47 +05002095 try:
tierno4d1ce222018-04-06 10:41:06 +02002096 # self.logger.debug("Creating floating IP")
tiernof8383b82017-01-18 15:49:48 +01002097 new_floating_ip = self.neutron.create_floatingip(param)
sousaedu80135b92021-02-17 15:05:18 +01002098 free_floating_ip = new_floating_ip["floatingip"]["id"]
2099 created_items[
2100 "floating_ip:" + str(free_floating_ip)
2101 ] = True
ahmadsaf853d452016-12-22 11:33:47 +05002102 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01002103 raise vimconn.VimConnException(
2104 type(e).__name__
2105 + ": Cannot create new floating_ip "
2106 + str(e),
2107 http_code=vimconn.HTTP_Conflict,
2108 )
tierno326fd5e2018-02-22 11:58:59 +01002109
tiernocb66c7e2020-07-22 10:42:58 +00002110 try:
2111 # for race condition ensure not already assigned
2112 fip = self.neutron.show_floatingip(free_floating_ip)
sousaedu80135b92021-02-17 15:05:18 +01002113
2114 if fip["floatingip"]["port_id"]:
tiernocb66c7e2020-07-22 10:42:58 +00002115 continue
sousaedu80135b92021-02-17 15:05:18 +01002116
tiernocb66c7e2020-07-22 10:42:58 +00002117 # the vim_id key contains the neutron.port_id
sousaedu80135b92021-02-17 15:05:18 +01002118 self.neutron.update_floatingip(
2119 free_floating_ip,
2120 {"floatingip": {"port_id": floating_network["vim_id"]}},
2121 )
tiernocb66c7e2020-07-22 10:42:58 +00002122 # for race condition ensure not re-assigned to other VM after 5 seconds
2123 time.sleep(5)
2124 fip = self.neutron.show_floatingip(free_floating_ip)
sousaedu80135b92021-02-17 15:05:18 +01002125
2126 if (
2127 fip["floatingip"]["port_id"]
2128 != floating_network["vim_id"]
2129 ):
2130 self.logger.error(
2131 "floating_ip {} re-assigned to other port".format(
2132 free_floating_ip
2133 )
2134 )
tiernocb66c7e2020-07-22 10:42:58 +00002135 continue
sousaedu80135b92021-02-17 15:05:18 +01002136
2137 self.logger.debug(
2138 "Assigned floating_ip {} to VM {}".format(
2139 free_floating_ip, server.id
2140 )
2141 )
tiernocb66c7e2020-07-22 10:42:58 +00002142 assigned = True
2143 except Exception as e:
2144 # openstack need some time after VM creation to assign an IP. So retry if fails
2145 vm_status = self.nova.servers.get(server.id).status
sousaedu80135b92021-02-17 15:05:18 +01002146
2147 if vm_status not in ("ACTIVE", "ERROR"):
tiernocb66c7e2020-07-22 10:42:58 +00002148 if time.time() - vm_start_time < server_timeout:
2149 time.sleep(5)
2150 continue
2151 elif floating_ip_retries > 0:
2152 floating_ip_retries -= 1
2153 continue
sousaedu80135b92021-02-17 15:05:18 +01002154
tiernocb66c7e2020-07-22 10:42:58 +00002155 raise vimconn.VimConnException(
sousaedu80135b92021-02-17 15:05:18 +01002156 "Cannot create floating_ip: {} {}".format(
2157 type(e).__name__, e
2158 ),
2159 http_code=vimconn.HTTP_Conflict,
2160 )
tierno326fd5e2018-02-22 11:58:59 +01002161
tiernof8383b82017-01-18 15:49:48 +01002162 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01002163 if not floating_network["exit_on_floating_ip_error"]:
tiernocb66c7e2020-07-22 10:42:58 +00002164 self.logger.error("Cannot create floating_ip. %s", str(e))
tiernof8383b82017-01-18 15:49:48 +01002165 continue
sousaedu80135b92021-02-17 15:05:18 +01002166
tiernof8383b82017-01-18 15:49:48 +01002167 raise
montesmoreno2a1fc4e2017-01-09 16:46:04 +00002168
tierno98e909c2017-10-14 13:27:03 +02002169 return server.id, created_items
tierno1ec592d2020-06-16 15:29:47 +00002170 # except nvExceptions.NotFound as e:
2171 # error_value=-vimconn.HTTP_Not_Found
2172 # error_text= "vm instance %s not found" % vm_id
2173 # except TypeError as e:
2174 # raise vimconn.VimConnException(type(e).__name__ + ": "+ str(e), http_code=vimconn.HTTP_Bad_Request)
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02002175
2176 except Exception as e:
tierno98e909c2017-10-14 13:27:03 +02002177 server_id = None
2178 if server:
2179 server_id = server.id
sousaedu80135b92021-02-17 15:05:18 +01002180
tierno98e909c2017-10-14 13:27:03 +02002181 try:
2182 self.delete_vminstance(server_id, created_items)
2183 except Exception as e2:
2184 self.logger.error("new_vminstance rollback fail {}".format(e2))
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02002185
tiernoae4a8d12016-07-08 12:30:39 +02002186 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01002187
tierno1ec592d2020-06-16 15:29:47 +00002188 def get_vminstance(self, vm_id):
2189 """Returns the VM instance information from VIM"""
2190 # self.logger.debug("Getting VM from VIM")
tierno7edb6752016-03-21 17:37:52 +01002191 try:
2192 self._reload_connection()
2193 server = self.nova.servers.find(id=vm_id)
tierno1ec592d2020-06-16 15:29:47 +00002194 # TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
sousaedu80135b92021-02-17 15:05:18 +01002195
tiernoae4a8d12016-07-08 12:30:39 +02002196 return server.to_dict()
sousaedu80135b92021-02-17 15:05:18 +01002197 except (
2198 ksExceptions.ClientException,
2199 nvExceptions.ClientException,
2200 nvExceptions.NotFound,
2201 ConnectionError,
2202 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02002203 self._format_exception(e)
2204
tierno1ec592d2020-06-16 15:29:47 +00002205 def get_vminstance_console(self, vm_id, console_type="vnc"):
2206 """
tierno7edb6752016-03-21 17:37:52 +01002207 Get a console for the virtual machine
2208 Params:
2209 vm_id: uuid of the VM
2210 console_type, can be:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002211 "novnc" (by default), "xvpvnc" for VNC types,
tierno7edb6752016-03-21 17:37:52 +01002212 "rdp-html5" for RDP types, "spice-html5" for SPICE types
tiernoae4a8d12016-07-08 12:30:39 +02002213 Returns dict with the console parameters:
2214 protocol: ssh, ftp, http, https, ...
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002215 server: usually ip address
2216 port: the http, ssh, ... port
2217 suffix: extra text, e.g. the http path and query string
tierno1ec592d2020-06-16 15:29:47 +00002218 """
tiernoae4a8d12016-07-08 12:30:39 +02002219 self.logger.debug("Getting VM CONSOLE from VIM")
sousaedu80135b92021-02-17 15:05:18 +01002220
tierno7edb6752016-03-21 17:37:52 +01002221 try:
2222 self._reload_connection()
2223 server = self.nova.servers.find(id=vm_id)
sousaedu80135b92021-02-17 15:05:18 +01002224
tierno1ec592d2020-06-16 15:29:47 +00002225 if console_type is None or console_type == "novnc":
tierno7edb6752016-03-21 17:37:52 +01002226 console_dict = server.get_vnc_console("novnc")
2227 elif console_type == "xvpvnc":
2228 console_dict = server.get_vnc_console(console_type)
2229 elif console_type == "rdp-html5":
2230 console_dict = server.get_rdp_console(console_type)
2231 elif console_type == "spice-html5":
2232 console_dict = server.get_spice_console(console_type)
2233 else:
sousaedu80135b92021-02-17 15:05:18 +01002234 raise vimconn.VimConnException(
2235 "console type '{}' not allowed".format(console_type),
2236 http_code=vimconn.HTTP_Bad_Request,
2237 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002238
tierno7edb6752016-03-21 17:37:52 +01002239 console_dict1 = console_dict.get("console")
sousaedu80135b92021-02-17 15:05:18 +01002240
tierno7edb6752016-03-21 17:37:52 +01002241 if console_dict1:
2242 console_url = console_dict1.get("url")
sousaedu80135b92021-02-17 15:05:18 +01002243
tierno7edb6752016-03-21 17:37:52 +01002244 if console_url:
tierno1ec592d2020-06-16 15:29:47 +00002245 # parse console_url
tierno7edb6752016-03-21 17:37:52 +01002246 protocol_index = console_url.find("//")
sousaedu80135b92021-02-17 15:05:18 +01002247 suffix_index = (
2248 console_url[protocol_index + 2 :].find("/") + protocol_index + 2
2249 )
2250 port_index = (
2251 console_url[protocol_index + 2 : suffix_index].find(":")
2252 + protocol_index
2253 + 2
2254 )
2255
tierno1ec592d2020-06-16 15:29:47 +00002256 if protocol_index < 0 or port_index < 0 or suffix_index < 0:
sousaedu80135b92021-02-17 15:05:18 +01002257 return (
2258 -vimconn.HTTP_Internal_Server_Error,
2259 "Unexpected response from VIM",
2260 )
2261
2262 console_dict = {
2263 "protocol": console_url[0:protocol_index],
2264 "server": console_url[protocol_index + 2 : port_index],
2265 "port": console_url[port_index:suffix_index],
2266 "suffix": console_url[suffix_index + 1 :],
2267 }
tierno7edb6752016-03-21 17:37:52 +01002268 protocol_index += 2
sousaedu80135b92021-02-17 15:05:18 +01002269
tiernoae4a8d12016-07-08 12:30:39 +02002270 return console_dict
tierno72774862020-05-04 11:44:15 +00002271 raise vimconn.VimConnUnexpectedResponse("Unexpected response from VIM")
sousaedu80135b92021-02-17 15:05:18 +01002272 except (
2273 nvExceptions.NotFound,
2274 ksExceptions.ClientException,
2275 nvExceptions.ClientException,
2276 nvExceptions.BadRequest,
2277 ConnectionError,
2278 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02002279 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01002280
palaciosj8f2060b2022-02-24 12:05:59 +00002281 def delete_vminstance(self, vm_id, created_items=None, volumes_to_hold=None):
sousaedu80135b92021-02-17 15:05:18 +01002282 """Removes a VM instance from VIM. Returns the old identifier"""
tierno1ec592d2020-06-16 15:29:47 +00002283 # print "osconnector: Getting VM from VIM"
2284 if created_items is None:
tierno98e909c2017-10-14 13:27:03 +02002285 created_items = {}
sousaedu80135b92021-02-17 15:05:18 +01002286
tierno7edb6752016-03-21 17:37:52 +01002287 try:
2288 self._reload_connection()
tierno98e909c2017-10-14 13:27:03 +02002289 # delete VM ports attached to this networks before the virtual machine
2290 for k, v in created_items.items():
2291 if not v: # skip already deleted
2292 continue
sousaedu80135b92021-02-17 15:05:18 +01002293
tierno7edb6752016-03-21 17:37:52 +01002294 try:
tiernoad6bdd42018-01-10 10:43:46 +01002295 k_item, _, k_id = k.partition(":")
2296 if k_item == "port":
2297 self.neutron.delete_port(k_id)
tierno7edb6752016-03-21 17:37:52 +01002298 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01002299 self.logger.error(
2300 "Error deleting port: {}: {}".format(type(e).__name__, e)
2301 )
montesmoreno0c8def02016-12-22 12:16:23 +00002302
tierno98e909c2017-10-14 13:27:03 +02002303 # #commented because detaching the volumes makes the servers.delete not work properly ?!?
2304 # #dettach volumes attached
2305 # server = self.nova.servers.get(vm_id)
sousaedu80135b92021-02-17 15:05:18 +01002306 # volumes_attached_dict = server._info["os-extended-volumes:volumes_attached"] #volume["id"]
tierno98e909c2017-10-14 13:27:03 +02002307 # #for volume in volumes_attached_dict:
sousaedu80135b92021-02-17 15:05:18 +01002308 # # self.cinder.volumes.detach(volume["id"])
montesmoreno0c8def02016-12-22 12:16:23 +00002309
tierno98e909c2017-10-14 13:27:03 +02002310 if vm_id:
2311 self.nova.servers.delete(vm_id)
montesmoreno0c8def02016-12-22 12:16:23 +00002312
tierno98e909c2017-10-14 13:27:03 +02002313 # delete volumes. Although having detached, they should have in active status before deleting
2314 # we ensure in this loop
montesmoreno0c8def02016-12-22 12:16:23 +00002315 keep_waiting = True
2316 elapsed_time = 0
sousaedu80135b92021-02-17 15:05:18 +01002317
montesmoreno0c8def02016-12-22 12:16:23 +00002318 while keep_waiting and elapsed_time < volume_timeout:
2319 keep_waiting = False
sousaedu80135b92021-02-17 15:05:18 +01002320
tierno98e909c2017-10-14 13:27:03 +02002321 for k, v in created_items.items():
2322 if not v: # skip already deleted
2323 continue
sousaedu80135b92021-02-17 15:05:18 +01002324
tierno98e909c2017-10-14 13:27:03 +02002325 try:
tiernoad6bdd42018-01-10 10:43:46 +01002326 k_item, _, k_id = k.partition(":")
2327 if k_item == "volume":
sousaedu80135b92021-02-17 15:05:18 +01002328 if self.cinder.volumes.get(k_id).status != "available":
tierno98e909c2017-10-14 13:27:03 +02002329 keep_waiting = True
2330 else:
palaciosj8f2060b2022-02-24 12:05:59 +00002331 if k_id not in volumes_to_hold:
2332 self.cinder.volumes.delete(k_id)
2333 created_items[k] = None
tiernocb66c7e2020-07-22 10:42:58 +00002334 elif k_item == "floating_ip": # floating ip
2335 self.neutron.delete_floatingip(k_id)
2336 created_items[k] = None
2337
tierno98e909c2017-10-14 13:27:03 +02002338 except Exception as e:
tiernocb66c7e2020-07-22 10:42:58 +00002339 self.logger.error("Error deleting {}: {}".format(k, e))
sousaedu80135b92021-02-17 15:05:18 +01002340
montesmoreno0c8def02016-12-22 12:16:23 +00002341 if keep_waiting:
2342 time.sleep(1)
2343 elapsed_time += 1
sousaedu80135b92021-02-17 15:05:18 +01002344
tierno98e909c2017-10-14 13:27:03 +02002345 return None
sousaedu80135b92021-02-17 15:05:18 +01002346 except (
2347 nvExceptions.NotFound,
2348 ksExceptions.ClientException,
2349 nvExceptions.ClientException,
2350 ConnectionError,
2351 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02002352 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01002353
tiernoae4a8d12016-07-08 12:30:39 +02002354 def refresh_vms_status(self, vm_list):
tierno1ec592d2020-06-16 15:29:47 +00002355 """Get the status of the virtual machines and their interfaces/ports
sousaedu80135b92021-02-17 15:05:18 +01002356 Params: the list of VM identifiers
2357 Returns a dictionary with:
2358 vm_id: #VIM id of this Virtual Machine
2359 status: #Mandatory. Text with one of:
2360 # DELETED (not found at vim)
2361 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
2362 # OTHER (Vim reported other status not understood)
2363 # ERROR (VIM indicates an ERROR status)
2364 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
2365 # CREATING (on building process), ERROR
2366 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
2367 #
2368 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
2369 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
2370 interfaces:
2371 - vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
2372 mac_address: #Text format XX:XX:XX:XX:XX:XX
2373 vim_net_id: #network id where this interface is connected
2374 vim_interface_id: #interface/port VIM id
2375 ip_address: #null, or text with IPv4, IPv6 address
2376 compute_node: #identification of compute node where PF,VF interface is allocated
2377 pci: #PCI address of the NIC that hosts the PF,VF
2378 vlan: #physical VLAN used for VF
tierno1ec592d2020-06-16 15:29:47 +00002379 """
2380 vm_dict = {}
sousaedu80135b92021-02-17 15:05:18 +01002381 self.logger.debug(
2382 "refresh_vms status: Getting tenant VM instance information from VIM"
2383 )
2384
tiernoae4a8d12016-07-08 12:30:39 +02002385 for vm_id in vm_list:
tierno1ec592d2020-06-16 15:29:47 +00002386 vm = {}
sousaedu80135b92021-02-17 15:05:18 +01002387
tiernoae4a8d12016-07-08 12:30:39 +02002388 try:
2389 vm_vim = self.get_vminstance(vm_id)
sousaedu80135b92021-02-17 15:05:18 +01002390
2391 if vm_vim["status"] in vmStatus2manoFormat:
2392 vm["status"] = vmStatus2manoFormat[vm_vim["status"]]
tierno7edb6752016-03-21 17:37:52 +01002393 else:
sousaedu80135b92021-02-17 15:05:18 +01002394 vm["status"] = "OTHER"
2395 vm["error_msg"] = "VIM status reported " + vm_vim["status"]
2396
tierno70eeb182020-10-19 16:38:00 +00002397 vm_vim.pop("OS-EXT-SRV-ATTR:user_data", None)
2398 vm_vim.pop("user_data", None)
sousaedu80135b92021-02-17 15:05:18 +01002399 vm["vim_info"] = self.serialize(vm_vim)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002400
tiernoae4a8d12016-07-08 12:30:39 +02002401 vm["interfaces"] = []
sousaedu80135b92021-02-17 15:05:18 +01002402 if vm_vim.get("fault"):
2403 vm["error_msg"] = str(vm_vim["fault"])
2404
tierno1ec592d2020-06-16 15:29:47 +00002405 # get interfaces
tierno7edb6752016-03-21 17:37:52 +01002406 try:
tiernoae4a8d12016-07-08 12:30:39 +02002407 self._reload_connection()
tiernob42fd9b2018-06-20 10:44:32 +02002408 port_dict = self.neutron.list_ports(device_id=vm_id)
sousaedu80135b92021-02-17 15:05:18 +01002409
tiernoae4a8d12016-07-08 12:30:39 +02002410 for port in port_dict["ports"]:
tierno1ec592d2020-06-16 15:29:47 +00002411 interface = {}
sousaedu80135b92021-02-17 15:05:18 +01002412 interface["vim_info"] = self.serialize(port)
tiernoae4a8d12016-07-08 12:30:39 +02002413 interface["mac_address"] = port.get("mac_address")
2414 interface["vim_net_id"] = port["network_id"]
2415 interface["vim_interface_id"] = port["id"]
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002416 # check if OS-EXT-SRV-ATTR:host is there,
Mike Marchetti5b9da422017-05-02 15:35:47 -04002417 # in case of non-admin credentials, it will be missing
sousaedu80135b92021-02-17 15:05:18 +01002418
2419 if vm_vim.get("OS-EXT-SRV-ATTR:host"):
2420 interface["compute_node"] = vm_vim["OS-EXT-SRV-ATTR:host"]
2421
tierno867ffe92017-03-27 12:50:34 +02002422 interface["pci"] = None
Mike Marchetti5b9da422017-05-02 15:35:47 -04002423
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002424 # check if binding:profile is there,
Mike Marchetti5b9da422017-05-02 15:35:47 -04002425 # in case of non-admin credentials, it will be missing
sousaedu80135b92021-02-17 15:05:18 +01002426 if port.get("binding:profile"):
2427 if port["binding:profile"].get("pci_slot"):
tierno1ec592d2020-06-16 15:29:47 +00002428 # TODO: At the moment sr-iov pci addresses are converted to PF pci addresses by setting
2429 # the slot to 0x00
Mike Marchetti5b9da422017-05-02 15:35:47 -04002430 # TODO: This is just a workaround valid for niantinc. Find a better way to do so
2431 # CHANGE DDDD:BB:SS.F to DDDD:BB:00.(F%2) assuming there are 2 ports per nic
sousaedu80135b92021-02-17 15:05:18 +01002432 pci = port["binding:profile"]["pci_slot"]
Mike Marchetti5b9da422017-05-02 15:35:47 -04002433 # interface["pci"] = pci[:-4] + "00." + str(int(pci[-1]) % 2)
2434 interface["pci"] = pci
sousaedu80135b92021-02-17 15:05:18 +01002435
tierno867ffe92017-03-27 12:50:34 +02002436 interface["vlan"] = None
sousaedu80135b92021-02-17 15:05:18 +01002437
2438 if port.get("binding:vif_details"):
2439 interface["vlan"] = port["binding:vif_details"].get("vlan")
2440
tierno1dfe9932020-06-18 08:50:10 +00002441 # Get vlan from network in case not present in port for those old openstacks and cases where
2442 # it is needed vlan at PT
2443 if not interface["vlan"]:
2444 # if network is of type vlan and port is of type direct (sr-iov) then set vlan id
2445 network = self.neutron.show_network(port["network_id"])
sousaedu80135b92021-02-17 15:05:18 +01002446
2447 if (
2448 network["network"].get("provider:network_type")
2449 == "vlan"
2450 ):
tierno1dfe9932020-06-18 08:50:10 +00002451 # and port.get("binding:vnic_type") in ("direct", "direct-physical"):
sousaedu80135b92021-02-17 15:05:18 +01002452 interface["vlan"] = network["network"].get(
2453 "provider:segmentation_id"
2454 )
2455
tierno1ec592d2020-06-16 15:29:47 +00002456 ips = []
2457 # look for floating ip address
tiernob42fd9b2018-06-20 10:44:32 +02002458 try:
sousaedu80135b92021-02-17 15:05:18 +01002459 floating_ip_dict = self.neutron.list_floatingips(
2460 port_id=port["id"]
2461 )
2462
tiernob42fd9b2018-06-20 10:44:32 +02002463 if floating_ip_dict.get("floatingips"):
sousaedu80135b92021-02-17 15:05:18 +01002464 ips.append(
2465 floating_ip_dict["floatingips"][0].get(
2466 "floating_ip_address"
2467 )
2468 )
tiernob42fd9b2018-06-20 10:44:32 +02002469 except Exception:
2470 pass
tierno7edb6752016-03-21 17:37:52 +01002471
tiernoae4a8d12016-07-08 12:30:39 +02002472 for subnet in port["fixed_ips"]:
2473 ips.append(subnet["ip_address"])
sousaedu80135b92021-02-17 15:05:18 +01002474
tiernoae4a8d12016-07-08 12:30:39 +02002475 interface["ip_address"] = ";".join(ips)
2476 vm["interfaces"].append(interface)
2477 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01002478 self.logger.error(
2479 "Error getting vm interface information {}: {}".format(
2480 type(e).__name__, e
2481 ),
2482 exc_info=True,
2483 )
tierno72774862020-05-04 11:44:15 +00002484 except vimconn.VimConnNotFoundException as e:
tiernoae4a8d12016-07-08 12:30:39 +02002485 self.logger.error("Exception getting vm status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01002486 vm["status"] = "DELETED"
2487 vm["error_msg"] = str(e)
tierno72774862020-05-04 11:44:15 +00002488 except vimconn.VimConnException as e:
tiernoae4a8d12016-07-08 12:30:39 +02002489 self.logger.error("Exception getting vm status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01002490 vm["status"] = "VIM_ERROR"
2491 vm["error_msg"] = str(e)
2492
tiernoae4a8d12016-07-08 12:30:39 +02002493 vm_dict[vm_id] = vm
sousaedu80135b92021-02-17 15:05:18 +01002494
tiernoae4a8d12016-07-08 12:30:39 +02002495 return vm_dict
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002496
tierno98e909c2017-10-14 13:27:03 +02002497 def action_vminstance(self, vm_id, action_dict, created_items={}):
tierno1ec592d2020-06-16 15:29:47 +00002498 """Send and action over a VM instance from VIM
2499 Returns None or the console dict if the action was successfully sent to the VIM"""
tiernoae4a8d12016-07-08 12:30:39 +02002500 self.logger.debug("Action over VM '%s': %s", vm_id, str(action_dict))
sousaedu80135b92021-02-17 15:05:18 +01002501
tierno7edb6752016-03-21 17:37:52 +01002502 try:
2503 self._reload_connection()
2504 server = self.nova.servers.find(id=vm_id)
sousaedu80135b92021-02-17 15:05:18 +01002505
tierno7edb6752016-03-21 17:37:52 +01002506 if "start" in action_dict:
tierno1ec592d2020-06-16 15:29:47 +00002507 if action_dict["start"] == "rebuild":
tierno7edb6752016-03-21 17:37:52 +01002508 server.rebuild()
2509 else:
tierno1ec592d2020-06-16 15:29:47 +00002510 if server.status == "PAUSED":
tierno7edb6752016-03-21 17:37:52 +01002511 server.unpause()
tierno1ec592d2020-06-16 15:29:47 +00002512 elif server.status == "SUSPENDED":
tierno7edb6752016-03-21 17:37:52 +01002513 server.resume()
tierno1ec592d2020-06-16 15:29:47 +00002514 elif server.status == "SHUTOFF":
tierno7edb6752016-03-21 17:37:52 +01002515 server.start()
2516 elif "pause" in action_dict:
2517 server.pause()
2518 elif "resume" in action_dict:
2519 server.resume()
2520 elif "shutoff" in action_dict or "shutdown" in action_dict:
2521 server.stop()
2522 elif "forceOff" in action_dict:
tierno1ec592d2020-06-16 15:29:47 +00002523 server.stop() # TODO
tierno7edb6752016-03-21 17:37:52 +01002524 elif "terminate" in action_dict:
2525 server.delete()
2526 elif "createImage" in action_dict:
2527 server.create_image()
tierno1ec592d2020-06-16 15:29:47 +00002528 # "path":path_schema,
2529 # "description":description_schema,
2530 # "name":name_schema,
2531 # "metadata":metadata_schema,
2532 # "imageRef": id_schema,
2533 # "disk": {"oneOf":[{"type": "null"}, {"type":"string"}] },
tierno7edb6752016-03-21 17:37:52 +01002534 elif "rebuild" in action_dict:
sousaedu80135b92021-02-17 15:05:18 +01002535 server.rebuild(server.image["id"])
tierno7edb6752016-03-21 17:37:52 +01002536 elif "reboot" in action_dict:
sousaedu80135b92021-02-17 15:05:18 +01002537 server.reboot() # reboot_type="SOFT"
tierno7edb6752016-03-21 17:37:52 +01002538 elif "console" in action_dict:
2539 console_type = action_dict["console"]
sousaedu80135b92021-02-17 15:05:18 +01002540
tierno1ec592d2020-06-16 15:29:47 +00002541 if console_type is None or console_type == "novnc":
tierno7edb6752016-03-21 17:37:52 +01002542 console_dict = server.get_vnc_console("novnc")
2543 elif console_type == "xvpvnc":
2544 console_dict = server.get_vnc_console(console_type)
2545 elif console_type == "rdp-html5":
2546 console_dict = server.get_rdp_console(console_type)
2547 elif console_type == "spice-html5":
2548 console_dict = server.get_spice_console(console_type)
2549 else:
sousaedu80135b92021-02-17 15:05:18 +01002550 raise vimconn.VimConnException(
2551 "console type '{}' not allowed".format(console_type),
2552 http_code=vimconn.HTTP_Bad_Request,
2553 )
2554
tierno7edb6752016-03-21 17:37:52 +01002555 try:
2556 console_url = console_dict["console"]["url"]
tierno1ec592d2020-06-16 15:29:47 +00002557 # parse console_url
tierno7edb6752016-03-21 17:37:52 +01002558 protocol_index = console_url.find("//")
sousaedu80135b92021-02-17 15:05:18 +01002559 suffix_index = (
2560 console_url[protocol_index + 2 :].find("/") + protocol_index + 2
2561 )
2562 port_index = (
2563 console_url[protocol_index + 2 : suffix_index].find(":")
2564 + protocol_index
2565 + 2
2566 )
2567
tierno1ec592d2020-06-16 15:29:47 +00002568 if protocol_index < 0 or port_index < 0 or suffix_index < 0:
sousaedu80135b92021-02-17 15:05:18 +01002569 raise vimconn.VimConnException(
2570 "Unexpected response from VIM " + str(console_dict)
2571 )
2572
2573 console_dict2 = {
2574 "protocol": console_url[0:protocol_index],
2575 "server": console_url[protocol_index + 2 : port_index],
2576 "port": int(console_url[port_index + 1 : suffix_index]),
2577 "suffix": console_url[suffix_index + 1 :],
2578 }
2579
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002580 return console_dict2
tierno1ec592d2020-06-16 15:29:47 +00002581 except Exception:
sousaedu80135b92021-02-17 15:05:18 +01002582 raise vimconn.VimConnException(
2583 "Unexpected response from VIM " + str(console_dict)
2584 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002585
tierno98e909c2017-10-14 13:27:03 +02002586 return None
sousaedu80135b92021-02-17 15:05:18 +01002587 except (
2588 ksExceptions.ClientException,
2589 nvExceptions.ClientException,
2590 nvExceptions.NotFound,
2591 ConnectionError,
2592 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02002593 self._format_exception(e)
tierno1ec592d2020-06-16 15:29:47 +00002594 # TODO insert exception vimconn.HTTP_Unauthorized
tiernoae4a8d12016-07-08 12:30:39 +02002595
tierno1ec592d2020-06-16 15:29:47 +00002596 # ###### VIO Specific Changes #########
garciadeblasebd66722019-01-31 16:01:31 +00002597 def _generate_vlanID(self):
kate721d79b2017-06-24 04:21:38 -07002598 """
sousaedu80135b92021-02-17 15:05:18 +01002599 Method to get unused vlanID
kate721d79b2017-06-24 04:21:38 -07002600 Args:
2601 None
2602 Returns:
2603 vlanID
2604 """
tierno1ec592d2020-06-16 15:29:47 +00002605 # Get used VLAN IDs
kate721d79b2017-06-24 04:21:38 -07002606 usedVlanIDs = []
2607 networks = self.get_network_list()
sousaedu80135b92021-02-17 15:05:18 +01002608
kate721d79b2017-06-24 04:21:38 -07002609 for net in networks:
sousaedu80135b92021-02-17 15:05:18 +01002610 if net.get("provider:segmentation_id"):
2611 usedVlanIDs.append(net.get("provider:segmentation_id"))
2612
kate721d79b2017-06-24 04:21:38 -07002613 used_vlanIDs = set(usedVlanIDs)
2614
tierno1ec592d2020-06-16 15:29:47 +00002615 # find unused VLAN ID
sousaedu80135b92021-02-17 15:05:18 +01002616 for vlanID_range in self.config.get("dataplane_net_vlan_range"):
kate721d79b2017-06-24 04:21:38 -07002617 try:
sousaedu80135b92021-02-17 15:05:18 +01002618 start_vlanid, end_vlanid = map(
2619 int, vlanID_range.replace(" ", "").split("-")
2620 )
2621
tierno7d782ef2019-10-04 12:56:31 +00002622 for vlanID in range(start_vlanid, end_vlanid + 1):
kate721d79b2017-06-24 04:21:38 -07002623 if vlanID not in used_vlanIDs:
2624 return vlanID
2625 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01002626 raise vimconn.VimConnException(
2627 "Exception {} occurred while generating VLAN ID.".format(exp)
2628 )
kate721d79b2017-06-24 04:21:38 -07002629 else:
tierno1ec592d2020-06-16 15:29:47 +00002630 raise vimconn.VimConnConflictException(
2631 "Unable to create the SRIOV VLAN network. All given Vlan IDs {} are in use.".format(
sousaedu80135b92021-02-17 15:05:18 +01002632 self.config.get("dataplane_net_vlan_range")
2633 )
2634 )
kate721d79b2017-06-24 04:21:38 -07002635
garciadeblasebd66722019-01-31 16:01:31 +00002636 def _generate_multisegment_vlanID(self):
2637 """
sousaedu80135b92021-02-17 15:05:18 +01002638 Method to get unused vlanID
2639 Args:
2640 None
2641 Returns:
2642 vlanID
garciadeblasebd66722019-01-31 16:01:31 +00002643 """
tierno6869ae72020-01-09 17:37:34 +00002644 # Get used VLAN IDs
garciadeblasebd66722019-01-31 16:01:31 +00002645 usedVlanIDs = []
2646 networks = self.get_network_list()
2647 for net in networks:
sousaedu80135b92021-02-17 15:05:18 +01002648 if net.get("provider:network_type") == "vlan" and net.get(
2649 "provider:segmentation_id"
2650 ):
2651 usedVlanIDs.append(net.get("provider:segmentation_id"))
2652 elif net.get("segments"):
2653 for segment in net.get("segments"):
2654 if segment.get("provider:network_type") == "vlan" and segment.get(
2655 "provider:segmentation_id"
2656 ):
2657 usedVlanIDs.append(segment.get("provider:segmentation_id"))
2658
garciadeblasebd66722019-01-31 16:01:31 +00002659 used_vlanIDs = set(usedVlanIDs)
2660
tierno6869ae72020-01-09 17:37:34 +00002661 # find unused VLAN ID
sousaedu80135b92021-02-17 15:05:18 +01002662 for vlanID_range in self.config.get("multisegment_vlan_range"):
garciadeblasebd66722019-01-31 16:01:31 +00002663 try:
sousaedu80135b92021-02-17 15:05:18 +01002664 start_vlanid, end_vlanid = map(
2665 int, vlanID_range.replace(" ", "").split("-")
2666 )
2667
tierno7d782ef2019-10-04 12:56:31 +00002668 for vlanID in range(start_vlanid, end_vlanid + 1):
garciadeblasebd66722019-01-31 16:01:31 +00002669 if vlanID not in used_vlanIDs:
2670 return vlanID
2671 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01002672 raise vimconn.VimConnException(
2673 "Exception {} occurred while generating VLAN ID.".format(exp)
2674 )
garciadeblasebd66722019-01-31 16:01:31 +00002675 else:
tierno1ec592d2020-06-16 15:29:47 +00002676 raise vimconn.VimConnConflictException(
2677 "Unable to create the VLAN segment. All VLAN IDs {} are in use.".format(
sousaedu80135b92021-02-17 15:05:18 +01002678 self.config.get("multisegment_vlan_range")
2679 )
2680 )
garciadeblasebd66722019-01-31 16:01:31 +00002681
2682 def _validate_vlan_ranges(self, input_vlan_range, text_vlan_range):
kate721d79b2017-06-24 04:21:38 -07002683 """
2684 Method to validate user given vlanID ranges
2685 Args: None
2686 Returns: None
2687 """
garciadeblasebd66722019-01-31 16:01:31 +00002688 for vlanID_range in input_vlan_range:
kate721d79b2017-06-24 04:21:38 -07002689 vlan_range = vlanID_range.replace(" ", "")
tierno1ec592d2020-06-16 15:29:47 +00002690 # validate format
sousaedu80135b92021-02-17 15:05:18 +01002691 vlanID_pattern = r"(\d)*-(\d)*$"
kate721d79b2017-06-24 04:21:38 -07002692 match_obj = re.match(vlanID_pattern, vlan_range)
2693 if not match_obj:
tierno1ec592d2020-06-16 15:29:47 +00002694 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +01002695 "Invalid VLAN range for {}: {}.You must provide "
2696 "'{}' in format [start_ID - end_ID].".format(
2697 text_vlan_range, vlanID_range, text_vlan_range
2698 )
2699 )
kate721d79b2017-06-24 04:21:38 -07002700
tierno1ec592d2020-06-16 15:29:47 +00002701 start_vlanid, end_vlanid = map(int, vlan_range.split("-"))
2702 if start_vlanid <= 0:
2703 raise vimconn.VimConnConflictException(
2704 "Invalid VLAN range for {}: {}. Start ID can not be zero. For VLAN "
sousaedu80135b92021-02-17 15:05:18 +01002705 "networks valid IDs are 1 to 4094 ".format(
2706 text_vlan_range, vlanID_range
2707 )
2708 )
2709
tierno1ec592d2020-06-16 15:29:47 +00002710 if end_vlanid > 4094:
2711 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +01002712 "Invalid VLAN range for {}: {}. End VLAN ID can not be "
2713 "greater than 4094. For VLAN networks valid IDs are 1 to 4094 ".format(
2714 text_vlan_range, vlanID_range
2715 )
2716 )
kate721d79b2017-06-24 04:21:38 -07002717
2718 if start_vlanid > end_vlanid:
tierno1ec592d2020-06-16 15:29:47 +00002719 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +01002720 "Invalid VLAN range for {}: {}. You must provide '{}'"
2721 " in format start_ID - end_ID and start_ID < end_ID ".format(
2722 text_vlan_range, vlanID_range, text_vlan_range
2723 )
2724 )
kate721d79b2017-06-24 04:21:38 -07002725
tierno1ec592d2020-06-16 15:29:47 +00002726 # NOT USED FUNCTIONS
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002727
tiernoae4a8d12016-07-08 12:30:39 +02002728 def new_external_port(self, port_data):
tierno1ec592d2020-06-16 15:29:47 +00002729 """Adds a external port to VIM
sousaedu80135b92021-02-17 15:05:18 +01002730 Returns the port identifier"""
tierno1ec592d2020-06-16 15:29:47 +00002731 # TODO openstack if needed
sousaedu80135b92021-02-17 15:05:18 +01002732 return (
2733 -vimconn.HTTP_Internal_Server_Error,
2734 "osconnector.new_external_port() not implemented",
2735 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002736
tiernoae4a8d12016-07-08 12:30:39 +02002737 def connect_port_network(self, port_id, network_id, admin=False):
tierno1ec592d2020-06-16 15:29:47 +00002738 """Connects a external port to a network
sousaedu80135b92021-02-17 15:05:18 +01002739 Returns status code of the VIM response"""
tierno1ec592d2020-06-16 15:29:47 +00002740 # TODO openstack if needed
sousaedu80135b92021-02-17 15:05:18 +01002741 return (
2742 -vimconn.HTTP_Internal_Server_Error,
2743 "osconnector.connect_port_network() not implemented",
2744 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002745
tiernoae4a8d12016-07-08 12:30:39 +02002746 def new_user(self, user_name, user_passwd, tenant_id=None):
tierno1ec592d2020-06-16 15:29:47 +00002747 """Adds a new user to openstack VIM
sousaedu80135b92021-02-17 15:05:18 +01002748 Returns the user identifier"""
tiernoae4a8d12016-07-08 12:30:39 +02002749 self.logger.debug("osconnector: Adding a new user to VIM")
sousaedu80135b92021-02-17 15:05:18 +01002750
tiernoae4a8d12016-07-08 12:30:39 +02002751 try:
2752 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +01002753 user = self.keystone.users.create(
2754 user_name, password=user_passwd, default_project=tenant_id
2755 )
tierno1ec592d2020-06-16 15:29:47 +00002756 # self.keystone.tenants.add_user(self.k_creds["username"], #role)
sousaedu80135b92021-02-17 15:05:18 +01002757
tiernoae4a8d12016-07-08 12:30:39 +02002758 return user.id
2759 except ksExceptions.ConnectionError as e:
tierno1ec592d2020-06-16 15:29:47 +00002760 error_value = -vimconn.HTTP_Bad_Request
sousaedu80135b92021-02-17 15:05:18 +01002761 error_text = (
2762 type(e).__name__
2763 + ": "
2764 + (str(e) if len(e.args) == 0 else str(e.args[0]))
2765 )
tierno1ec592d2020-06-16 15:29:47 +00002766 except ksExceptions.ClientException as e: # TODO remove
2767 error_value = -vimconn.HTTP_Bad_Request
sousaedu80135b92021-02-17 15:05:18 +01002768 error_text = (
2769 type(e).__name__
2770 + ": "
2771 + (str(e) if len(e.args) == 0 else str(e.args[0]))
2772 )
2773
tierno1ec592d2020-06-16 15:29:47 +00002774 # TODO insert exception vimconn.HTTP_Unauthorized
2775 # if reaching here is because an exception
tierno9c5c8322018-03-23 15:44:03 +01002776 self.logger.debug("new_user " + error_text)
sousaedu80135b92021-02-17 15:05:18 +01002777
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002778 return error_value, error_text
tiernoae4a8d12016-07-08 12:30:39 +02002779
2780 def delete_user(self, user_id):
tierno1ec592d2020-06-16 15:29:47 +00002781 """Delete a user from openstack VIM
sousaedu80135b92021-02-17 15:05:18 +01002782 Returns the user identifier"""
tiernoae4a8d12016-07-08 12:30:39 +02002783 if self.debug:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002784 print("osconnector: Deleting a user from VIM")
sousaedu80135b92021-02-17 15:05:18 +01002785
tiernoae4a8d12016-07-08 12:30:39 +02002786 try:
2787 self._reload_connection()
2788 self.keystone.users.delete(user_id)
sousaedu80135b92021-02-17 15:05:18 +01002789
tiernoae4a8d12016-07-08 12:30:39 +02002790 return 1, user_id
2791 except ksExceptions.ConnectionError as e:
tierno1ec592d2020-06-16 15:29:47 +00002792 error_value = -vimconn.HTTP_Bad_Request
sousaedu80135b92021-02-17 15:05:18 +01002793 error_text = (
2794 type(e).__name__
2795 + ": "
2796 + (str(e) if len(e.args) == 0 else str(e.args[0]))
2797 )
tiernoae4a8d12016-07-08 12:30:39 +02002798 except ksExceptions.NotFound as e:
tierno1ec592d2020-06-16 15:29:47 +00002799 error_value = -vimconn.HTTP_Not_Found
sousaedu80135b92021-02-17 15:05:18 +01002800 error_text = (
2801 type(e).__name__
2802 + ": "
2803 + (str(e) if len(e.args) == 0 else str(e.args[0]))
2804 )
tierno1ec592d2020-06-16 15:29:47 +00002805 except ksExceptions.ClientException as e: # TODO remove
2806 error_value = -vimconn.HTTP_Bad_Request
sousaedu80135b92021-02-17 15:05:18 +01002807 error_text = (
2808 type(e).__name__
2809 + ": "
2810 + (str(e) if len(e.args) == 0 else str(e.args[0]))
2811 )
2812
tierno1ec592d2020-06-16 15:29:47 +00002813 # TODO insert exception vimconn.HTTP_Unauthorized
2814 # if reaching here is because an exception
2815 self.logger.debug("delete_tenant " + error_text)
sousaedu80135b92021-02-17 15:05:18 +01002816
tiernoae4a8d12016-07-08 12:30:39 +02002817 return error_value, error_text
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002818
tierno7edb6752016-03-21 17:37:52 +01002819 def get_hosts_info(self):
tierno1ec592d2020-06-16 15:29:47 +00002820 """Get the information of deployed hosts
2821 Returns the hosts content"""
tierno7edb6752016-03-21 17:37:52 +01002822 if self.debug:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002823 print("osconnector: Getting Host info from VIM")
sousaedu80135b92021-02-17 15:05:18 +01002824
tierno7edb6752016-03-21 17:37:52 +01002825 try:
tierno1ec592d2020-06-16 15:29:47 +00002826 h_list = []
tierno7edb6752016-03-21 17:37:52 +01002827 self._reload_connection()
2828 hypervisors = self.nova.hypervisors.list()
sousaedu80135b92021-02-17 15:05:18 +01002829
tierno7edb6752016-03-21 17:37:52 +01002830 for hype in hypervisors:
tierno1ec592d2020-06-16 15:29:47 +00002831 h_list.append(hype.to_dict())
sousaedu80135b92021-02-17 15:05:18 +01002832
tierno1ec592d2020-06-16 15:29:47 +00002833 return 1, {"hosts": h_list}
tierno7edb6752016-03-21 17:37:52 +01002834 except nvExceptions.NotFound as e:
tierno1ec592d2020-06-16 15:29:47 +00002835 error_value = -vimconn.HTTP_Not_Found
sousaedu80135b92021-02-17 15:05:18 +01002836 error_text = str(e) if len(e.args) == 0 else str(e.args[0])
tierno7edb6752016-03-21 17:37:52 +01002837 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
tierno1ec592d2020-06-16 15:29:47 +00002838 error_value = -vimconn.HTTP_Bad_Request
sousaedu80135b92021-02-17 15:05:18 +01002839 error_text = (
2840 type(e).__name__
2841 + ": "
2842 + (str(e) if len(e.args) == 0 else str(e.args[0]))
2843 )
2844
tierno1ec592d2020-06-16 15:29:47 +00002845 # TODO insert exception vimconn.HTTP_Unauthorized
2846 # if reaching here is because an exception
tierno9c5c8322018-03-23 15:44:03 +01002847 self.logger.debug("get_hosts_info " + error_text)
sousaedu80135b92021-02-17 15:05:18 +01002848
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002849 return error_value, error_text
tierno7edb6752016-03-21 17:37:52 +01002850
2851 def get_hosts(self, vim_tenant):
tierno1ec592d2020-06-16 15:29:47 +00002852 """Get the hosts and deployed instances
2853 Returns the hosts content"""
tierno7edb6752016-03-21 17:37:52 +01002854 r, hype_dict = self.get_hosts_info()
sousaedu80135b92021-02-17 15:05:18 +01002855
tierno1ec592d2020-06-16 15:29:47 +00002856 if r < 0:
tierno7edb6752016-03-21 17:37:52 +01002857 return r, hype_dict
sousaedu80135b92021-02-17 15:05:18 +01002858
tierno7edb6752016-03-21 17:37:52 +01002859 hypervisors = hype_dict["hosts"]
sousaedu80135b92021-02-17 15:05:18 +01002860
tierno7edb6752016-03-21 17:37:52 +01002861 try:
2862 servers = self.nova.servers.list()
2863 for hype in hypervisors:
2864 for server in servers:
sousaedu80135b92021-02-17 15:05:18 +01002865 if (
2866 server.to_dict()["OS-EXT-SRV-ATTR:hypervisor_hostname"]
2867 == hype["hypervisor_hostname"]
2868 ):
2869 if "vm" in hype:
2870 hype["vm"].append(server.id)
tierno7edb6752016-03-21 17:37:52 +01002871 else:
sousaedu80135b92021-02-17 15:05:18 +01002872 hype["vm"] = [server.id]
2873
tierno7edb6752016-03-21 17:37:52 +01002874 return 1, hype_dict
2875 except nvExceptions.NotFound as e:
tierno1ec592d2020-06-16 15:29:47 +00002876 error_value = -vimconn.HTTP_Not_Found
sousaedu80135b92021-02-17 15:05:18 +01002877 error_text = str(e) if len(e.args) == 0 else str(e.args[0])
tierno7edb6752016-03-21 17:37:52 +01002878 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
tierno1ec592d2020-06-16 15:29:47 +00002879 error_value = -vimconn.HTTP_Bad_Request
sousaedu80135b92021-02-17 15:05:18 +01002880 error_text = (
2881 type(e).__name__
2882 + ": "
2883 + (str(e) if len(e.args) == 0 else str(e.args[0]))
2884 )
2885
tierno1ec592d2020-06-16 15:29:47 +00002886 # TODO insert exception vimconn.HTTP_Unauthorized
2887 # if reaching here is because an exception
tierno9c5c8322018-03-23 15:44:03 +01002888 self.logger.debug("get_hosts " + error_text)
sousaedu80135b92021-02-17 15:05:18 +01002889
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002890 return error_value, error_text
tierno7edb6752016-03-21 17:37:52 +01002891
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002892 def new_classification(self, name, ctype, definition):
sousaedu80135b92021-02-17 15:05:18 +01002893 self.logger.debug(
2894 "Adding a new (Traffic) Classification to VIM, named %s", name
2895 )
2896
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002897 try:
2898 new_class = None
2899 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +01002900
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002901 if ctype not in supportedClassificationTypes:
tierno72774862020-05-04 11:44:15 +00002902 raise vimconn.VimConnNotSupportedException(
sousaedu80135b92021-02-17 15:05:18 +01002903 "OpenStack VIM connector does not support provided "
2904 "Classification Type {}, supported ones are: {}".format(
2905 ctype, supportedClassificationTypes
2906 )
2907 )
2908
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002909 if not self._validate_classification(ctype, definition):
tierno72774862020-05-04 11:44:15 +00002910 raise vimconn.VimConnException(
sousaedu80135b92021-02-17 15:05:18 +01002911 "Incorrect Classification definition for the type specified."
2912 )
tierno7edb6752016-03-21 17:37:52 +01002913
sousaedu80135b92021-02-17 15:05:18 +01002914 classification_dict = definition
2915 classification_dict["name"] = name
Igor D.Ccaadc442017-11-06 12:48:48 +00002916 new_class = self.neutron.create_sfc_flow_classifier(
sousaedu80135b92021-02-17 15:05:18 +01002917 {"flow_classifier": classification_dict}
2918 )
2919
2920 return new_class["flow_classifier"]["id"]
2921 except (
2922 neExceptions.ConnectionFailed,
2923 ksExceptions.ClientException,
2924 neExceptions.NeutronException,
2925 ConnectionError,
2926 ) as e:
2927 self.logger.error("Creation of Classification failed.")
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002928 self._format_exception(e)
2929
2930 def get_classification(self, class_id):
2931 self.logger.debug(" Getting Classification %s from VIM", class_id)
2932 filter_dict = {"id": class_id}
2933 class_list = self.get_classification_list(filter_dict)
sousaedu80135b92021-02-17 15:05:18 +01002934
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002935 if len(class_list) == 0:
tierno72774862020-05-04 11:44:15 +00002936 raise vimconn.VimConnNotFoundException(
sousaedu80135b92021-02-17 15:05:18 +01002937 "Classification '{}' not found".format(class_id)
2938 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002939 elif len(class_list) > 1:
tierno72774862020-05-04 11:44:15 +00002940 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +01002941 "Found more than one Classification with this criteria"
2942 )
2943
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002944 classification = class_list[0]
sousaedu80135b92021-02-17 15:05:18 +01002945
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002946 return classification
2947
2948 def get_classification_list(self, filter_dict={}):
sousaedu80135b92021-02-17 15:05:18 +01002949 self.logger.debug(
2950 "Getting Classifications from VIM filter: '%s'", str(filter_dict)
2951 )
2952
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002953 try:
tierno69b590e2018-03-13 18:52:23 +01002954 filter_dict_os = filter_dict.copy()
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002955 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +01002956
tierno69b590e2018-03-13 18:52:23 +01002957 if self.api_version3 and "tenant_id" in filter_dict_os:
sousaedu80135b92021-02-17 15:05:18 +01002958 filter_dict_os["project_id"] = filter_dict_os.pop("tenant_id")
2959
Igor D.Ccaadc442017-11-06 12:48:48 +00002960 classification_dict = self.neutron.list_sfc_flow_classifiers(
sousaedu80135b92021-02-17 15:05:18 +01002961 **filter_dict_os
2962 )
tierno69b590e2018-03-13 18:52:23 +01002963 classification_list = classification_dict["flow_classifiers"]
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002964 self.__classification_os2mano(classification_list)
sousaedu80135b92021-02-17 15:05:18 +01002965
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002966 return classification_list
sousaedu80135b92021-02-17 15:05:18 +01002967 except (
2968 neExceptions.ConnectionFailed,
2969 ksExceptions.ClientException,
2970 neExceptions.NeutronException,
2971 ConnectionError,
2972 ) as e:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002973 self._format_exception(e)
2974
2975 def delete_classification(self, class_id):
2976 self.logger.debug("Deleting Classification '%s' from VIM", class_id)
sousaedu80135b92021-02-17 15:05:18 +01002977
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002978 try:
2979 self._reload_connection()
Igor D.Ccaadc442017-11-06 12:48:48 +00002980 self.neutron.delete_sfc_flow_classifier(class_id)
sousaedu80135b92021-02-17 15:05:18 +01002981
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002982 return class_id
sousaedu80135b92021-02-17 15:05:18 +01002983 except (
2984 neExceptions.ConnectionFailed,
2985 neExceptions.NeutronException,
2986 ksExceptions.ClientException,
2987 neExceptions.NeutronException,
2988 ConnectionError,
2989 ) as e:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002990 self._format_exception(e)
2991
2992 def new_sfi(self, name, ingress_ports, egress_ports, sfc_encap=True):
sousaedu80135b92021-02-17 15:05:18 +01002993 self.logger.debug(
2994 "Adding a new Service Function Instance to VIM, named '%s'", name
2995 )
2996
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002997 try:
2998 new_sfi = None
2999 self._reload_connection()
3000 correlation = None
sousaedu80135b92021-02-17 15:05:18 +01003001
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003002 if sfc_encap:
sousaedu80135b92021-02-17 15:05:18 +01003003 correlation = "nsh"
3004
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003005 if len(ingress_ports) != 1:
tierno72774862020-05-04 11:44:15 +00003006 raise vimconn.VimConnNotSupportedException(
sousaedu80135b92021-02-17 15:05:18 +01003007 "OpenStack VIM connector can only have 1 ingress port per SFI"
3008 )
3009
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003010 if len(egress_ports) != 1:
tierno72774862020-05-04 11:44:15 +00003011 raise vimconn.VimConnNotSupportedException(
sousaedu80135b92021-02-17 15:05:18 +01003012 "OpenStack VIM connector can only have 1 egress port per SFI"
3013 )
3014
3015 sfi_dict = {
3016 "name": name,
3017 "ingress": ingress_ports[0],
3018 "egress": egress_ports[0],
3019 "service_function_parameters": {"correlation": correlation},
3020 }
3021 new_sfi = self.neutron.create_sfc_port_pair({"port_pair": sfi_dict})
3022
3023 return new_sfi["port_pair"]["id"]
3024 except (
3025 neExceptions.ConnectionFailed,
3026 ksExceptions.ClientException,
3027 neExceptions.NeutronException,
3028 ConnectionError,
3029 ) as e:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003030 if new_sfi:
3031 try:
sousaedu80135b92021-02-17 15:05:18 +01003032 self.neutron.delete_sfc_port_pair(new_sfi["port_pair"]["id"])
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003033 except Exception:
3034 self.logger.error(
sousaedu80135b92021-02-17 15:05:18 +01003035 "Creation of Service Function Instance failed, with "
3036 "subsequent deletion failure as well."
3037 )
3038
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003039 self._format_exception(e)
3040
3041 def get_sfi(self, sfi_id):
sousaedu80135b92021-02-17 15:05:18 +01003042 self.logger.debug("Getting Service Function Instance %s from VIM", sfi_id)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003043 filter_dict = {"id": sfi_id}
3044 sfi_list = self.get_sfi_list(filter_dict)
sousaedu80135b92021-02-17 15:05:18 +01003045
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003046 if len(sfi_list) == 0:
sousaedu80135b92021-02-17 15:05:18 +01003047 raise vimconn.VimConnNotFoundException(
3048 "Service Function Instance '{}' not found".format(sfi_id)
3049 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003050 elif len(sfi_list) > 1:
tierno72774862020-05-04 11:44:15 +00003051 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +01003052 "Found more than one Service Function Instance with this criteria"
3053 )
3054
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003055 sfi = sfi_list[0]
sousaedu80135b92021-02-17 15:05:18 +01003056
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003057 return sfi
3058
3059 def get_sfi_list(self, filter_dict={}):
sousaedu80135b92021-02-17 15:05:18 +01003060 self.logger.debug(
3061 "Getting Service Function Instances from VIM filter: '%s'", str(filter_dict)
3062 )
3063
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003064 try:
3065 self._reload_connection()
tierno69b590e2018-03-13 18:52:23 +01003066 filter_dict_os = filter_dict.copy()
sousaedu80135b92021-02-17 15:05:18 +01003067
tierno69b590e2018-03-13 18:52:23 +01003068 if self.api_version3 and "tenant_id" in filter_dict_os:
sousaedu80135b92021-02-17 15:05:18 +01003069 filter_dict_os["project_id"] = filter_dict_os.pop("tenant_id")
3070
tierno69b590e2018-03-13 18:52:23 +01003071 sfi_dict = self.neutron.list_sfc_port_pairs(**filter_dict_os)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003072 sfi_list = sfi_dict["port_pairs"]
3073 self.__sfi_os2mano(sfi_list)
sousaedu80135b92021-02-17 15:05:18 +01003074
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003075 return sfi_list
sousaedu80135b92021-02-17 15:05:18 +01003076 except (
3077 neExceptions.ConnectionFailed,
3078 ksExceptions.ClientException,
3079 neExceptions.NeutronException,
3080 ConnectionError,
3081 ) as e:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003082 self._format_exception(e)
3083
3084 def delete_sfi(self, sfi_id):
sousaedu80135b92021-02-17 15:05:18 +01003085 self.logger.debug("Deleting Service Function Instance '%s' from VIM", sfi_id)
3086
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003087 try:
3088 self._reload_connection()
Igor D.Ccaadc442017-11-06 12:48:48 +00003089 self.neutron.delete_sfc_port_pair(sfi_id)
sousaedu80135b92021-02-17 15:05:18 +01003090
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003091 return sfi_id
sousaedu80135b92021-02-17 15:05:18 +01003092 except (
3093 neExceptions.ConnectionFailed,
3094 neExceptions.NeutronException,
3095 ksExceptions.ClientException,
3096 neExceptions.NeutronException,
3097 ConnectionError,
3098 ) as e:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003099 self._format_exception(e)
3100
3101 def new_sf(self, name, sfis, sfc_encap=True):
tierno7d782ef2019-10-04 12:56:31 +00003102 self.logger.debug("Adding a new Service Function to VIM, named '%s'", name)
sousaedu80135b92021-02-17 15:05:18 +01003103
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003104 try:
3105 new_sf = None
3106 self._reload_connection()
tierno9c5c8322018-03-23 15:44:03 +01003107 # correlation = None
3108 # if sfc_encap:
sousaedu80135b92021-02-17 15:05:18 +01003109 # correlation = "nsh"
3110
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003111 for instance in sfis:
3112 sfi = self.get_sfi(instance)
sousaedu80135b92021-02-17 15:05:18 +01003113
3114 if sfi.get("sfc_encap") != sfc_encap:
tierno72774862020-05-04 11:44:15 +00003115 raise vimconn.VimConnNotSupportedException(
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003116 "OpenStack VIM connector requires all SFIs of the "
sousaedu80135b92021-02-17 15:05:18 +01003117 "same SF to share the same SFC Encapsulation"
3118 )
3119
3120 sf_dict = {"name": name, "port_pairs": sfis}
3121 new_sf = self.neutron.create_sfc_port_pair_group(
3122 {"port_pair_group": sf_dict}
3123 )
3124
3125 return new_sf["port_pair_group"]["id"]
3126 except (
3127 neExceptions.ConnectionFailed,
3128 ksExceptions.ClientException,
3129 neExceptions.NeutronException,
3130 ConnectionError,
3131 ) as e:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003132 if new_sf:
3133 try:
Igor D.Ccaadc442017-11-06 12:48:48 +00003134 self.neutron.delete_sfc_port_pair_group(
sousaedu80135b92021-02-17 15:05:18 +01003135 new_sf["port_pair_group"]["id"]
3136 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003137 except Exception:
3138 self.logger.error(
sousaedu80135b92021-02-17 15:05:18 +01003139 "Creation of Service Function failed, with "
3140 "subsequent deletion failure as well."
3141 )
3142
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003143 self._format_exception(e)
3144
3145 def get_sf(self, sf_id):
3146 self.logger.debug("Getting Service Function %s from VIM", sf_id)
3147 filter_dict = {"id": sf_id}
3148 sf_list = self.get_sf_list(filter_dict)
sousaedu80135b92021-02-17 15:05:18 +01003149
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003150 if len(sf_list) == 0:
tierno72774862020-05-04 11:44:15 +00003151 raise vimconn.VimConnNotFoundException(
sousaedu80135b92021-02-17 15:05:18 +01003152 "Service Function '{}' not found".format(sf_id)
3153 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003154 elif len(sf_list) > 1:
tierno72774862020-05-04 11:44:15 +00003155 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +01003156 "Found more than one Service Function with this criteria"
3157 )
3158
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003159 sf = sf_list[0]
sousaedu80135b92021-02-17 15:05:18 +01003160
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003161 return sf
3162
3163 def get_sf_list(self, filter_dict={}):
sousaedu80135b92021-02-17 15:05:18 +01003164 self.logger.debug(
3165 "Getting Service Function from VIM filter: '%s'", str(filter_dict)
3166 )
3167
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003168 try:
3169 self._reload_connection()
tierno69b590e2018-03-13 18:52:23 +01003170 filter_dict_os = filter_dict.copy()
sousaedu80135b92021-02-17 15:05:18 +01003171
tierno69b590e2018-03-13 18:52:23 +01003172 if self.api_version3 and "tenant_id" in filter_dict_os:
sousaedu80135b92021-02-17 15:05:18 +01003173 filter_dict_os["project_id"] = filter_dict_os.pop("tenant_id")
3174
tierno69b590e2018-03-13 18:52:23 +01003175 sf_dict = self.neutron.list_sfc_port_pair_groups(**filter_dict_os)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003176 sf_list = sf_dict["port_pair_groups"]
3177 self.__sf_os2mano(sf_list)
sousaedu80135b92021-02-17 15:05:18 +01003178
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003179 return sf_list
sousaedu80135b92021-02-17 15:05:18 +01003180 except (
3181 neExceptions.ConnectionFailed,
3182 ksExceptions.ClientException,
3183 neExceptions.NeutronException,
3184 ConnectionError,
3185 ) as e:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003186 self._format_exception(e)
3187
3188 def delete_sf(self, sf_id):
3189 self.logger.debug("Deleting Service Function '%s' from VIM", sf_id)
sousaedu80135b92021-02-17 15:05:18 +01003190
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003191 try:
3192 self._reload_connection()
Igor D.Ccaadc442017-11-06 12:48:48 +00003193 self.neutron.delete_sfc_port_pair_group(sf_id)
sousaedu80135b92021-02-17 15:05:18 +01003194
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003195 return sf_id
sousaedu80135b92021-02-17 15:05:18 +01003196 except (
3197 neExceptions.ConnectionFailed,
3198 neExceptions.NeutronException,
3199 ksExceptions.ClientException,
3200 neExceptions.NeutronException,
3201 ConnectionError,
3202 ) as e:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003203 self._format_exception(e)
3204
3205 def new_sfp(self, name, classifications, sfs, sfc_encap=True, spi=None):
tierno7d782ef2019-10-04 12:56:31 +00003206 self.logger.debug("Adding a new Service Function Path to VIM, named '%s'", name)
sousaedu80135b92021-02-17 15:05:18 +01003207
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003208 try:
3209 new_sfp = None
3210 self._reload_connection()
Igor D.Ccaadc442017-11-06 12:48:48 +00003211 # In networking-sfc the MPLS encapsulation is legacy
3212 # should be used when no full SFC Encapsulation is intended
sousaedu80135b92021-02-17 15:05:18 +01003213 correlation = "mpls"
3214
Igor D.Ccaadc442017-11-06 12:48:48 +00003215 if sfc_encap:
sousaedu80135b92021-02-17 15:05:18 +01003216 correlation = "nsh"
3217
3218 sfp_dict = {
3219 "name": name,
3220 "flow_classifiers": classifications,
3221 "port_pair_groups": sfs,
3222 "chain_parameters": {"correlation": correlation},
3223 }
3224
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003225 if spi:
sousaedu80135b92021-02-17 15:05:18 +01003226 sfp_dict["chain_id"] = spi
3227
3228 new_sfp = self.neutron.create_sfc_port_chain({"port_chain": sfp_dict})
3229
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003230 return new_sfp["port_chain"]["id"]
sousaedu80135b92021-02-17 15:05:18 +01003231 except (
3232 neExceptions.ConnectionFailed,
3233 ksExceptions.ClientException,
3234 neExceptions.NeutronException,
3235 ConnectionError,
3236 ) as e:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003237 if new_sfp:
3238 try:
sousaedu80135b92021-02-17 15:05:18 +01003239 self.neutron.delete_sfc_port_chain(new_sfp["port_chain"]["id"])
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003240 except Exception:
3241 self.logger.error(
sousaedu80135b92021-02-17 15:05:18 +01003242 "Creation of Service Function Path failed, with "
3243 "subsequent deletion failure as well."
3244 )
3245
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003246 self._format_exception(e)
3247
3248 def get_sfp(self, sfp_id):
3249 self.logger.debug(" Getting Service Function Path %s from VIM", sfp_id)
sousaedu80135b92021-02-17 15:05:18 +01003250
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003251 filter_dict = {"id": sfp_id}
3252 sfp_list = self.get_sfp_list(filter_dict)
sousaedu80135b92021-02-17 15:05:18 +01003253
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003254 if len(sfp_list) == 0:
tierno72774862020-05-04 11:44:15 +00003255 raise vimconn.VimConnNotFoundException(
sousaedu80135b92021-02-17 15:05:18 +01003256 "Service Function Path '{}' not found".format(sfp_id)
3257 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003258 elif len(sfp_list) > 1:
tierno72774862020-05-04 11:44:15 +00003259 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +01003260 "Found more than one Service Function Path with this criteria"
3261 )
3262
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003263 sfp = sfp_list[0]
sousaedu80135b92021-02-17 15:05:18 +01003264
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003265 return sfp
3266
3267 def get_sfp_list(self, filter_dict={}):
sousaedu80135b92021-02-17 15:05:18 +01003268 self.logger.debug(
3269 "Getting Service Function Paths from VIM filter: '%s'", str(filter_dict)
3270 )
3271
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003272 try:
3273 self._reload_connection()
tierno69b590e2018-03-13 18:52:23 +01003274 filter_dict_os = filter_dict.copy()
sousaedu80135b92021-02-17 15:05:18 +01003275
tierno69b590e2018-03-13 18:52:23 +01003276 if self.api_version3 and "tenant_id" in filter_dict_os:
sousaedu80135b92021-02-17 15:05:18 +01003277 filter_dict_os["project_id"] = filter_dict_os.pop("tenant_id")
3278
tierno69b590e2018-03-13 18:52:23 +01003279 sfp_dict = self.neutron.list_sfc_port_chains(**filter_dict_os)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003280 sfp_list = sfp_dict["port_chains"]
3281 self.__sfp_os2mano(sfp_list)
sousaedu80135b92021-02-17 15:05:18 +01003282
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003283 return sfp_list
sousaedu80135b92021-02-17 15:05:18 +01003284 except (
3285 neExceptions.ConnectionFailed,
3286 ksExceptions.ClientException,
3287 neExceptions.NeutronException,
3288 ConnectionError,
3289 ) as e:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003290 self._format_exception(e)
3291
3292 def delete_sfp(self, sfp_id):
tierno7d782ef2019-10-04 12:56:31 +00003293 self.logger.debug("Deleting Service Function Path '%s' from VIM", sfp_id)
sousaedu80135b92021-02-17 15:05:18 +01003294
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003295 try:
3296 self._reload_connection()
Igor D.Ccaadc442017-11-06 12:48:48 +00003297 self.neutron.delete_sfc_port_chain(sfp_id)
sousaedu80135b92021-02-17 15:05:18 +01003298
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003299 return sfp_id
sousaedu80135b92021-02-17 15:05:18 +01003300 except (
3301 neExceptions.ConnectionFailed,
3302 neExceptions.NeutronException,
3303 ksExceptions.ClientException,
3304 neExceptions.NeutronException,
3305 ConnectionError,
3306 ) as e:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003307 self._format_exception(e)
borsatti8a2dda32019-12-18 15:08:57 +00003308
borsatti8a2dda32019-12-18 15:08:57 +00003309 def refresh_sfps_status(self, sfp_list):
tierno1ec592d2020-06-16 15:29:47 +00003310 """Get the status of the service function path
sousaedu80135b92021-02-17 15:05:18 +01003311 Params: the list of sfp identifiers
3312 Returns a dictionary with:
3313 vm_id: #VIM id of this service function path
3314 status: #Mandatory. Text with one of:
3315 # DELETED (not found at vim)
3316 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
3317 # OTHER (Vim reported other status not understood)
3318 # ERROR (VIM indicates an ERROR status)
3319 # ACTIVE,
3320 # CREATING (on building process)
3321 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
3322 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)F
tierno1ec592d2020-06-16 15:29:47 +00003323 """
3324 sfp_dict = {}
sousaedu80135b92021-02-17 15:05:18 +01003325 self.logger.debug(
3326 "refresh_sfps status: Getting tenant SFP information from VIM"
3327 )
3328
borsatti8a2dda32019-12-18 15:08:57 +00003329 for sfp_id in sfp_list:
tierno1ec592d2020-06-16 15:29:47 +00003330 sfp = {}
sousaedu80135b92021-02-17 15:05:18 +01003331
borsatti8a2dda32019-12-18 15:08:57 +00003332 try:
3333 sfp_vim = self.get_sfp(sfp_id)
sousaedu80135b92021-02-17 15:05:18 +01003334
3335 if sfp_vim["spi"]:
3336 sfp["status"] = vmStatus2manoFormat["ACTIVE"]
borsatti8a2dda32019-12-18 15:08:57 +00003337 else:
sousaedu80135b92021-02-17 15:05:18 +01003338 sfp["status"] = "OTHER"
3339 sfp["error_msg"] = "VIM status reported " + sfp["status"]
borsatti8a2dda32019-12-18 15:08:57 +00003340
sousaedu80135b92021-02-17 15:05:18 +01003341 sfp["vim_info"] = self.serialize(sfp_vim)
borsatti8a2dda32019-12-18 15:08:57 +00003342
sousaedu80135b92021-02-17 15:05:18 +01003343 if sfp_vim.get("fault"):
3344 sfp["error_msg"] = str(sfp_vim["fault"])
tierno72774862020-05-04 11:44:15 +00003345 except vimconn.VimConnNotFoundException as e:
borsatti8a2dda32019-12-18 15:08:57 +00003346 self.logger.error("Exception getting sfp status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01003347 sfp["status"] = "DELETED"
3348 sfp["error_msg"] = str(e)
tierno72774862020-05-04 11:44:15 +00003349 except vimconn.VimConnException as e:
borsatti8a2dda32019-12-18 15:08:57 +00003350 self.logger.error("Exception getting sfp status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01003351 sfp["status"] = "VIM_ERROR"
3352 sfp["error_msg"] = str(e)
3353
borsatti8a2dda32019-12-18 15:08:57 +00003354 sfp_dict[sfp_id] = sfp
sousaedu80135b92021-02-17 15:05:18 +01003355
borsatti8a2dda32019-12-18 15:08:57 +00003356 return sfp_dict
3357
borsatti8a2dda32019-12-18 15:08:57 +00003358 def refresh_sfis_status(self, sfi_list):
tierno1ec592d2020-06-16 15:29:47 +00003359 """Get the status of the service function instances
sousaedu80135b92021-02-17 15:05:18 +01003360 Params: the list of sfi identifiers
3361 Returns a dictionary with:
3362 vm_id: #VIM id of this service function instance
3363 status: #Mandatory. Text with one of:
3364 # DELETED (not found at vim)
3365 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
3366 # OTHER (Vim reported other status not understood)
3367 # ERROR (VIM indicates an ERROR status)
3368 # ACTIVE,
3369 # CREATING (on building process)
3370 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
3371 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
tierno1ec592d2020-06-16 15:29:47 +00003372 """
3373 sfi_dict = {}
sousaedu80135b92021-02-17 15:05:18 +01003374 self.logger.debug(
3375 "refresh_sfis status: Getting tenant sfi information from VIM"
3376 )
3377
borsatti8a2dda32019-12-18 15:08:57 +00003378 for sfi_id in sfi_list:
tierno1ec592d2020-06-16 15:29:47 +00003379 sfi = {}
sousaedu80135b92021-02-17 15:05:18 +01003380
borsatti8a2dda32019-12-18 15:08:57 +00003381 try:
3382 sfi_vim = self.get_sfi(sfi_id)
sousaedu80135b92021-02-17 15:05:18 +01003383
borsatti8a2dda32019-12-18 15:08:57 +00003384 if sfi_vim:
sousaedu80135b92021-02-17 15:05:18 +01003385 sfi["status"] = vmStatus2manoFormat["ACTIVE"]
borsatti8a2dda32019-12-18 15:08:57 +00003386 else:
sousaedu80135b92021-02-17 15:05:18 +01003387 sfi["status"] = "OTHER"
3388 sfi["error_msg"] = "VIM status reported " + sfi["status"]
borsatti8a2dda32019-12-18 15:08:57 +00003389
sousaedu80135b92021-02-17 15:05:18 +01003390 sfi["vim_info"] = self.serialize(sfi_vim)
borsatti8a2dda32019-12-18 15:08:57 +00003391
sousaedu80135b92021-02-17 15:05:18 +01003392 if sfi_vim.get("fault"):
3393 sfi["error_msg"] = str(sfi_vim["fault"])
tierno72774862020-05-04 11:44:15 +00003394 except vimconn.VimConnNotFoundException as e:
borsatti8a2dda32019-12-18 15:08:57 +00003395 self.logger.error("Exception getting sfi status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01003396 sfi["status"] = "DELETED"
3397 sfi["error_msg"] = str(e)
tierno72774862020-05-04 11:44:15 +00003398 except vimconn.VimConnException as e:
borsatti8a2dda32019-12-18 15:08:57 +00003399 self.logger.error("Exception getting sfi status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01003400 sfi["status"] = "VIM_ERROR"
3401 sfi["error_msg"] = str(e)
3402
borsatti8a2dda32019-12-18 15:08:57 +00003403 sfi_dict[sfi_id] = sfi
sousaedu80135b92021-02-17 15:05:18 +01003404
borsatti8a2dda32019-12-18 15:08:57 +00003405 return sfi_dict
3406
borsatti8a2dda32019-12-18 15:08:57 +00003407 def refresh_sfs_status(self, sf_list):
tierno1ec592d2020-06-16 15:29:47 +00003408 """Get the status of the service functions
sousaedu80135b92021-02-17 15:05:18 +01003409 Params: the list of sf identifiers
3410 Returns a dictionary with:
3411 vm_id: #VIM id of this service function
3412 status: #Mandatory. Text with one of:
3413 # DELETED (not found at vim)
3414 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
3415 # OTHER (Vim reported other status not understood)
3416 # ERROR (VIM indicates an ERROR status)
3417 # ACTIVE,
3418 # CREATING (on building process)
3419 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
3420 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
tierno1ec592d2020-06-16 15:29:47 +00003421 """
3422 sf_dict = {}
borsatti8a2dda32019-12-18 15:08:57 +00003423 self.logger.debug("refresh_sfs status: Getting tenant sf information from VIM")
sousaedu80135b92021-02-17 15:05:18 +01003424
borsatti8a2dda32019-12-18 15:08:57 +00003425 for sf_id in sf_list:
tierno1ec592d2020-06-16 15:29:47 +00003426 sf = {}
sousaedu80135b92021-02-17 15:05:18 +01003427
borsatti8a2dda32019-12-18 15:08:57 +00003428 try:
3429 sf_vim = self.get_sf(sf_id)
sousaedu80135b92021-02-17 15:05:18 +01003430
borsatti8a2dda32019-12-18 15:08:57 +00003431 if sf_vim:
sousaedu80135b92021-02-17 15:05:18 +01003432 sf["status"] = vmStatus2manoFormat["ACTIVE"]
borsatti8a2dda32019-12-18 15:08:57 +00003433 else:
sousaedu80135b92021-02-17 15:05:18 +01003434 sf["status"] = "OTHER"
3435 sf["error_msg"] = "VIM status reported " + sf_vim["status"]
borsatti8a2dda32019-12-18 15:08:57 +00003436
sousaedu80135b92021-02-17 15:05:18 +01003437 sf["vim_info"] = self.serialize(sf_vim)
borsatti8a2dda32019-12-18 15:08:57 +00003438
sousaedu80135b92021-02-17 15:05:18 +01003439 if sf_vim.get("fault"):
3440 sf["error_msg"] = str(sf_vim["fault"])
tierno72774862020-05-04 11:44:15 +00003441 except vimconn.VimConnNotFoundException as e:
borsatti8a2dda32019-12-18 15:08:57 +00003442 self.logger.error("Exception getting sf status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01003443 sf["status"] = "DELETED"
3444 sf["error_msg"] = str(e)
tierno72774862020-05-04 11:44:15 +00003445 except vimconn.VimConnException as e:
borsatti8a2dda32019-12-18 15:08:57 +00003446 self.logger.error("Exception getting sf status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01003447 sf["status"] = "VIM_ERROR"
3448 sf["error_msg"] = str(e)
3449
borsatti8a2dda32019-12-18 15:08:57 +00003450 sf_dict[sf_id] = sf
sousaedu80135b92021-02-17 15:05:18 +01003451
borsatti8a2dda32019-12-18 15:08:57 +00003452 return sf_dict
3453
borsatti8a2dda32019-12-18 15:08:57 +00003454 def refresh_classifications_status(self, classification_list):
tierno1ec592d2020-06-16 15:29:47 +00003455 """Get the status of the classifications
sousaedu80135b92021-02-17 15:05:18 +01003456 Params: the list of classification identifiers
3457 Returns a dictionary with:
3458 vm_id: #VIM id of this classifier
3459 status: #Mandatory. Text with one of:
3460 # DELETED (not found at vim)
3461 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
3462 # OTHER (Vim reported other status not understood)
3463 # ERROR (VIM indicates an ERROR status)
3464 # ACTIVE,
3465 # CREATING (on building process)
3466 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
3467 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
tierno1ec592d2020-06-16 15:29:47 +00003468 """
3469 classification_dict = {}
sousaedu80135b92021-02-17 15:05:18 +01003470 self.logger.debug(
3471 "refresh_classifications status: Getting tenant classification information from VIM"
3472 )
3473
borsatti8a2dda32019-12-18 15:08:57 +00003474 for classification_id in classification_list:
tierno1ec592d2020-06-16 15:29:47 +00003475 classification = {}
sousaedu80135b92021-02-17 15:05:18 +01003476
borsatti8a2dda32019-12-18 15:08:57 +00003477 try:
3478 classification_vim = self.get_classification(classification_id)
sousaedu80135b92021-02-17 15:05:18 +01003479
borsatti8a2dda32019-12-18 15:08:57 +00003480 if classification_vim:
sousaedu80135b92021-02-17 15:05:18 +01003481 classification["status"] = vmStatus2manoFormat["ACTIVE"]
borsatti8a2dda32019-12-18 15:08:57 +00003482 else:
sousaedu80135b92021-02-17 15:05:18 +01003483 classification["status"] = "OTHER"
3484 classification["error_msg"] = (
3485 "VIM status reported " + classification["status"]
3486 )
borsatti8a2dda32019-12-18 15:08:57 +00003487
sousaedu80135b92021-02-17 15:05:18 +01003488 classification["vim_info"] = self.serialize(classification_vim)
borsatti8a2dda32019-12-18 15:08:57 +00003489
sousaedu80135b92021-02-17 15:05:18 +01003490 if classification_vim.get("fault"):
3491 classification["error_msg"] = str(classification_vim["fault"])
tierno72774862020-05-04 11:44:15 +00003492 except vimconn.VimConnNotFoundException as e:
borsatti8a2dda32019-12-18 15:08:57 +00003493 self.logger.error("Exception getting classification status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01003494 classification["status"] = "DELETED"
3495 classification["error_msg"] = str(e)
tierno72774862020-05-04 11:44:15 +00003496 except vimconn.VimConnException as e:
borsatti8a2dda32019-12-18 15:08:57 +00003497 self.logger.error("Exception getting classification status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01003498 classification["status"] = "VIM_ERROR"
3499 classification["error_msg"] = str(e)
3500
borsatti8a2dda32019-12-18 15:08:57 +00003501 classification_dict[classification_id] = classification
sousaedu80135b92021-02-17 15:05:18 +01003502
borsatti8a2dda32019-12-18 15:08:57 +00003503 return classification_dict
Alexis Romerob70f4ed2022-03-11 18:00:49 +01003504
3505 def new_affinity_group(self, affinity_group_data):
3506 """Adds a server group to VIM
3507 affinity_group_data contains a dictionary with information, keys:
3508 name: name in VIM for the server group
3509 type: affinity or anti-affinity
3510 scope: Only nfvi-node allowed
3511 Returns the server group identifier"""
3512 self.logger.debug("Adding Server Group '%s'", str(affinity_group_data))
3513
3514 try:
3515 name = affinity_group_data["name"]
3516 policy = affinity_group_data["type"]
3517
3518 self._reload_connection()
3519 new_server_group = self.nova.server_groups.create(name, policy)
3520
3521 return new_server_group.id
3522 except (
3523 ksExceptions.ClientException,
3524 nvExceptions.ClientException,
3525 ConnectionError,
3526 KeyError,
3527 ) as e:
3528 self._format_exception(e)
3529
3530 def get_affinity_group(self, affinity_group_id):
3531 """Obtain server group details from the VIM. Returns the server group detais as a dict"""
3532 self.logger.debug("Getting flavor '%s'", affinity_group_id)
3533 try:
3534 self._reload_connection()
3535 server_group = self.nova.server_groups.find(id=affinity_group_id)
3536
3537 return server_group.to_dict()
3538 except (
3539 nvExceptions.NotFound,
3540 nvExceptions.ClientException,
3541 ksExceptions.ClientException,
3542 ConnectionError,
3543 ) as e:
3544 self._format_exception(e)
3545
3546 def delete_affinity_group(self, affinity_group_id):
3547 """Deletes a server group from the VIM. Returns the old affinity_group_id"""
3548 self.logger.debug("Getting server group '%s'", affinity_group_id)
3549 try:
3550 self._reload_connection()
3551 self.nova.server_groups.delete(affinity_group_id)
3552
3553 return affinity_group_id
3554 except (
3555 nvExceptions.NotFound,
3556 ksExceptions.ClientException,
3557 nvExceptions.ClientException,
3558 ConnectionError,
3559 ) as e:
3560 self._format_exception(e)