blob: 02d7e85f1c58d7baa02be72f45567457b60d5c0e [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
elumalai8658c2c2022-04-28 19:09:31 +053035import json
tiernoae4a8d12016-07-08 12:30:39 +020036import logging
sousaedu049cbb12022-01-05 11:39:35 +000037from pprint import pformat
garciadeblas2299e3b2017-01-26 14:35:55 +000038import random
kate721d79b2017-06-24 04:21:38 -070039import re
sousaedu049cbb12022-01-05 11:39:35 +000040import time
41
42from cinderclient import client as cClient
tiernob5cef372017-06-19 15:52:22 +020043from glanceclient import client as glClient
tierno7edb6752016-03-21 17:37:52 +010044import glanceclient.exc as gl1Exceptions
sousaedu049cbb12022-01-05 11:39:35 +000045from keystoneauth1 import session
46from keystoneauth1.identity import v2, v3
47import keystoneclient.exceptions as ksExceptions
48import keystoneclient.v2_0.client as ksClient_v2
49import keystoneclient.v3.client as ksClient_v3
50import netaddr
tierno7edb6752016-03-21 17:37:52 +010051from neutronclient.common import exceptions as neExceptions
sousaedu049cbb12022-01-05 11:39:35 +000052from neutronclient.neutron import client as neClient
53from novaclient import client as nClient, exceptions as nvExceptions
54from osm_ro_plugin import vimconn
tierno7edb6752016-03-21 17:37:52 +010055from requests.exceptions import ConnectionError
sousaedu049cbb12022-01-05 11:39:35 +000056import yaml
tierno7edb6752016-03-21 17:37:52 +010057
tierno1ec592d2020-06-16 15:29:47 +000058__author__ = "Alfonso Tierno, Gerardo Garcia, Pablo Montes, xFlow Research, Igor D.C., Eduardo Sousa"
59__date__ = "$22-sep-2017 23:59:59$"
tierno40e1bce2017-08-09 09:12:04 +020060
61"""contain the openstack virtual machine status to openmano status"""
sousaedu80135b92021-02-17 15:05:18 +010062vmStatus2manoFormat = {
63 "ACTIVE": "ACTIVE",
64 "PAUSED": "PAUSED",
65 "SUSPENDED": "SUSPENDED",
66 "SHUTOFF": "INACTIVE",
67 "BUILD": "BUILD",
68 "ERROR": "ERROR",
69 "DELETED": "DELETED",
70}
71netStatus2manoFormat = {
72 "ACTIVE": "ACTIVE",
73 "PAUSED": "PAUSED",
74 "INACTIVE": "INACTIVE",
75 "BUILD": "BUILD",
76 "ERROR": "ERROR",
77 "DELETED": "DELETED",
78}
tierno7edb6752016-03-21 17:37:52 +010079
sousaedu80135b92021-02-17 15:05:18 +010080supportedClassificationTypes = ["legacy_flow_classifier"]
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +000081
tierno1ec592d2020-06-16 15:29:47 +000082# global var to have a timeout creating and deleting volumes
garciadeblas64b39c52020-05-21 08:07:25 +000083volume_timeout = 1800
84server_timeout = 1800
montesmoreno0c8def02016-12-22 12:16:23 +000085
Anderson Bravalheri0446cd52018-08-17 15:26:19 +010086
87class SafeDumper(yaml.SafeDumper):
88 def represent_data(self, data):
89 # Openstack APIs use custom subclasses of dict and YAML safe dumper
90 # is designed to not handle that (reference issue 142 of pyyaml)
91 if isinstance(data, dict) and data.__class__ != dict:
92 # A simple solution is to convert those items back to dicts
93 data = dict(data.items())
94
95 return super(SafeDumper, self).represent_data(data)
96
97
tierno72774862020-05-04 11:44:15 +000098class vimconnector(vimconn.VimConnector):
sousaedu80135b92021-02-17 15:05:18 +010099 def __init__(
100 self,
101 uuid,
102 name,
103 tenant_id,
104 tenant_name,
105 url,
106 url_admin=None,
107 user=None,
108 passwd=None,
109 log_level=None,
110 config={},
111 persistent_info={},
112 ):
tierno1ec592d2020-06-16 15:29:47 +0000113 """using common constructor parameters. In this case
tierno7edb6752016-03-21 17:37:52 +0100114 'url' is the keystone authorization url,
115 'url_admin' is not use
tierno1ec592d2020-06-16 15:29:47 +0000116 """
sousaedu80135b92021-02-17 15:05:18 +0100117 api_version = config.get("APIversion")
kate721d79b2017-06-24 04:21:38 -0700118
sousaedu80135b92021-02-17 15:05:18 +0100119 if api_version and api_version not in ("v3.3", "v2.0", "2", "3"):
120 raise vimconn.VimConnException(
121 "Invalid value '{}' for config:APIversion. "
122 "Allowed values are 'v3.3', 'v2.0', '2' or '3'".format(api_version)
123 )
124
125 vim_type = config.get("vim_type")
126
127 if vim_type and vim_type not in ("vio", "VIO"):
128 raise vimconn.VimConnException(
129 "Invalid value '{}' for config:vim_type."
130 "Allowed values are 'vio' or 'VIO'".format(vim_type)
131 )
132
133 if config.get("dataplane_net_vlan_range") is not None:
tierno1ec592d2020-06-16 15:29:47 +0000134 # validate vlan ranges provided by user
sousaedu80135b92021-02-17 15:05:18 +0100135 self._validate_vlan_ranges(
136 config.get("dataplane_net_vlan_range"), "dataplane_net_vlan_range"
137 )
garciadeblasebd66722019-01-31 16:01:31 +0000138
sousaedu80135b92021-02-17 15:05:18 +0100139 if config.get("multisegment_vlan_range") is not None:
tierno1ec592d2020-06-16 15:29:47 +0000140 # validate vlan ranges provided by user
sousaedu80135b92021-02-17 15:05:18 +0100141 self._validate_vlan_ranges(
142 config.get("multisegment_vlan_range"), "multisegment_vlan_range"
143 )
kate721d79b2017-06-24 04:21:38 -0700144
sousaedu80135b92021-02-17 15:05:18 +0100145 vimconn.VimConnector.__init__(
146 self,
147 uuid,
148 name,
149 tenant_id,
150 tenant_name,
151 url,
152 url_admin,
153 user,
154 passwd,
155 log_level,
156 config,
157 )
tiernob3d36742017-03-03 23:51:05 +0100158
tierno4d1ce222018-04-06 10:41:06 +0200159 if self.config.get("insecure") and self.config.get("ca_cert"):
sousaedu80135b92021-02-17 15:05:18 +0100160 raise vimconn.VimConnException(
161 "options insecure and ca_cert are mutually exclusive"
162 )
163
tierno4d1ce222018-04-06 10:41:06 +0200164 self.verify = True
sousaedu80135b92021-02-17 15:05:18 +0100165
tierno4d1ce222018-04-06 10:41:06 +0200166 if self.config.get("insecure"):
167 self.verify = False
sousaedu80135b92021-02-17 15:05:18 +0100168
tierno4d1ce222018-04-06 10:41:06 +0200169 if self.config.get("ca_cert"):
170 self.verify = self.config.get("ca_cert")
tierno4d1ce222018-04-06 10:41:06 +0200171
tierno7edb6752016-03-21 17:37:52 +0100172 if not url:
sousaedu80135b92021-02-17 15:05:18 +0100173 raise TypeError("url param can not be NoneType")
174
tiernob5cef372017-06-19 15:52:22 +0200175 self.persistent_info = persistent_info
sousaedu80135b92021-02-17 15:05:18 +0100176 self.availability_zone = persistent_info.get("availability_zone", None)
177 self.session = persistent_info.get("session", {"reload_client": True})
178 self.my_tenant_id = self.session.get("my_tenant_id")
179 self.nova = self.session.get("nova")
180 self.neutron = self.session.get("neutron")
181 self.cinder = self.session.get("cinder")
182 self.glance = self.session.get("glance")
183 # self.glancev1 = self.session.get("glancev1")
184 self.keystone = self.session.get("keystone")
185 self.api_version3 = self.session.get("api_version3")
kate721d79b2017-06-24 04:21:38 -0700186 self.vim_type = self.config.get("vim_type")
sousaedu80135b92021-02-17 15:05:18 +0100187
kate721d79b2017-06-24 04:21:38 -0700188 if self.vim_type:
189 self.vim_type = self.vim_type.upper()
sousaedu80135b92021-02-17 15:05:18 +0100190
kate721d79b2017-06-24 04:21:38 -0700191 if self.config.get("use_internal_endpoint"):
192 self.endpoint_type = "internalURL"
193 else:
194 self.endpoint_type = None
montesmoreno0c8def02016-12-22 12:16:23 +0000195
sousaedu80135b92021-02-17 15:05:18 +0100196 logging.getLogger("urllib3").setLevel(logging.WARNING)
197 logging.getLogger("keystoneauth").setLevel(logging.WARNING)
198 logging.getLogger("novaclient").setLevel(logging.WARNING)
199 self.logger = logging.getLogger("ro.vim.openstack")
kate721d79b2017-06-24 04:21:38 -0700200
tiernoa05b65a2019-02-01 12:30:27 +0000201 # allow security_groups to be a list or a single string
sousaedu80135b92021-02-17 15:05:18 +0100202 if isinstance(self.config.get("security_groups"), str):
203 self.config["security_groups"] = [self.config["security_groups"]]
204
tiernoa05b65a2019-02-01 12:30:27 +0000205 self.security_groups_id = None
206
tierno1ec592d2020-06-16 15:29:47 +0000207 # ###### VIO Specific Changes #########
kate721d79b2017-06-24 04:21:38 -0700208 if self.vim_type == "VIO":
sousaedu80135b92021-02-17 15:05:18 +0100209 self.logger = logging.getLogger("ro.vim.vio")
kate721d79b2017-06-24 04:21:38 -0700210
tiernofe789902016-09-29 14:20:44 +0000211 if log_level:
tierno1ec592d2020-06-16 15:29:47 +0000212 self.logger.setLevel(getattr(logging, log_level))
tiernof716aea2017-06-21 18:01:40 +0200213
214 def __getitem__(self, index):
215 """Get individuals parameters.
216 Throw KeyError"""
sousaedu80135b92021-02-17 15:05:18 +0100217 if index == "project_domain_id":
tiernof716aea2017-06-21 18:01:40 +0200218 return self.config.get("project_domain_id")
sousaedu80135b92021-02-17 15:05:18 +0100219 elif index == "user_domain_id":
tiernof716aea2017-06-21 18:01:40 +0200220 return self.config.get("user_domain_id")
221 else:
tierno72774862020-05-04 11:44:15 +0000222 return vimconn.VimConnector.__getitem__(self, index)
tiernof716aea2017-06-21 18:01:40 +0200223
224 def __setitem__(self, index, value):
225 """Set individuals parameters and it is marked as dirty so to force connection reload.
226 Throw KeyError"""
sousaedu80135b92021-02-17 15:05:18 +0100227 if index == "project_domain_id":
tiernof716aea2017-06-21 18:01:40 +0200228 self.config["project_domain_id"] = value
sousaedu80135b92021-02-17 15:05:18 +0100229 elif index == "user_domain_id":
tierno1ec592d2020-06-16 15:29:47 +0000230 self.config["user_domain_id"] = value
tiernof716aea2017-06-21 18:01:40 +0200231 else:
tierno72774862020-05-04 11:44:15 +0000232 vimconn.VimConnector.__setitem__(self, index, value)
sousaedu80135b92021-02-17 15:05:18 +0100233
234 self.session["reload_client"] = True
tiernof716aea2017-06-21 18:01:40 +0200235
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100236 def serialize(self, value):
237 """Serialization of python basic types.
238
239 In the case value is not serializable a message will be logged and a
240 simple representation of the data that cannot be converted back to
241 python is returned.
242 """
tierno7d782ef2019-10-04 12:56:31 +0000243 if isinstance(value, str):
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100244 return value
245
246 try:
sousaedu80135b92021-02-17 15:05:18 +0100247 return yaml.dump(
248 value, Dumper=SafeDumper, default_flow_style=True, width=256
249 )
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100250 except yaml.representer.RepresenterError:
sousaedu80135b92021-02-17 15:05:18 +0100251 self.logger.debug(
252 "The following entity cannot be serialized in YAML:\n\n%s\n\n",
253 pformat(value),
254 exc_info=True,
255 )
256
tierno1ec592d2020-06-16 15:29:47 +0000257 return str(value)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100258
tierno7edb6752016-03-21 17:37:52 +0100259 def _reload_connection(self):
tierno1ec592d2020-06-16 15:29:47 +0000260 """Called before any operation, it check if credentials has changed
tierno7edb6752016-03-21 17:37:52 +0100261 Throw keystoneclient.apiclient.exceptions.AuthorizationFailure
tierno1ec592d2020-06-16 15:29:47 +0000262 """
263 # 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 +0100264 if self.session["reload_client"]:
265 if self.config.get("APIversion"):
266 self.api_version3 = (
267 self.config["APIversion"] == "v3.3"
268 or self.config["APIversion"] == "3"
269 )
tiernof716aea2017-06-21 18:01:40 +0200270 else: # get from ending auth_url that end with v3 or with v2.0
sousaedu80135b92021-02-17 15:05:18 +0100271 self.api_version3 = self.url.endswith("/v3") or self.url.endswith(
272 "/v3/"
273 )
274
275 self.session["api_version3"] = self.api_version3
276
tiernof716aea2017-06-21 18:01:40 +0200277 if self.api_version3:
sousaedu80135b92021-02-17 15:05:18 +0100278 if self.config.get("project_domain_id") or self.config.get(
279 "project_domain_name"
280 ):
tierno3cb8dc32017-10-24 18:13:19 +0200281 project_domain_id_default = None
282 else:
sousaedu80135b92021-02-17 15:05:18 +0100283 project_domain_id_default = "default"
284
285 if self.config.get("user_domain_id") or self.config.get(
286 "user_domain_name"
287 ):
tierno3cb8dc32017-10-24 18:13:19 +0200288 user_domain_id_default = None
289 else:
sousaedu80135b92021-02-17 15:05:18 +0100290 user_domain_id_default = "default"
291 auth = v3.Password(
292 auth_url=self.url,
293 username=self.user,
294 password=self.passwd,
295 project_name=self.tenant_name,
296 project_id=self.tenant_id,
297 project_domain_id=self.config.get(
298 "project_domain_id", project_domain_id_default
299 ),
300 user_domain_id=self.config.get(
301 "user_domain_id", user_domain_id_default
302 ),
303 project_domain_name=self.config.get("project_domain_name"),
304 user_domain_name=self.config.get("user_domain_name"),
305 )
ahmadsa95baa272016-11-30 09:14:11 +0500306 else:
sousaedu80135b92021-02-17 15:05:18 +0100307 auth = v2.Password(
308 auth_url=self.url,
309 username=self.user,
310 password=self.passwd,
311 tenant_name=self.tenant_name,
312 tenant_id=self.tenant_id,
313 )
314
tierno4d1ce222018-04-06 10:41:06 +0200315 sess = session.Session(auth=auth, verify=self.verify)
tierno1ec592d2020-06-16 15:29:47 +0000316 # addedd region_name to keystone, nova, neutron and cinder to support distributed cloud for Wind River
317 # Titanium cloud and StarlingX
sousaedu80135b92021-02-17 15:05:18 +0100318 region_name = self.config.get("region_name")
319
tiernof716aea2017-06-21 18:01:40 +0200320 if self.api_version3:
sousaedu80135b92021-02-17 15:05:18 +0100321 self.keystone = ksClient_v3.Client(
322 session=sess,
323 endpoint_type=self.endpoint_type,
324 region_name=region_name,
325 )
tiernof716aea2017-06-21 18:01:40 +0200326 else:
sousaedu80135b92021-02-17 15:05:18 +0100327 self.keystone = ksClient_v2.Client(
328 session=sess, endpoint_type=self.endpoint_type
329 )
330
331 self.session["keystone"] = self.keystone
332 # In order to enable microversion functionality an explicit microversion must be specified in "config".
montesmoreno9317d302017-08-16 12:48:23 +0200333 # This implementation approach is due to the warning message in
334 # https://developer.openstack.org/api-guide/compute/microversions.html
335 # where it is stated that microversion backwards compatibility is not guaranteed and clients should
336 # always require an specific microversion.
sousaedu80135b92021-02-17 15:05:18 +0100337 # To be able to use "device role tagging" functionality define "microversion: 2.32" in datacenter config
montesmoreno9317d302017-08-16 12:48:23 +0200338 version = self.config.get("microversion")
sousaedu80135b92021-02-17 15:05:18 +0100339
montesmoreno9317d302017-08-16 12:48:23 +0200340 if not version:
341 version = "2.1"
sousaedu80135b92021-02-17 15:05:18 +0100342
tierno1ec592d2020-06-16 15:29:47 +0000343 # addedd region_name to keystone, nova, neutron and cinder to support distributed cloud for Wind River
344 # Titanium cloud and StarlingX
sousaedu80135b92021-02-17 15:05:18 +0100345 self.nova = self.session["nova"] = nClient.Client(
346 str(version),
347 session=sess,
348 endpoint_type=self.endpoint_type,
349 region_name=region_name,
350 )
351 self.neutron = self.session["neutron"] = neClient.Client(
352 "2.0",
353 session=sess,
354 endpoint_type=self.endpoint_type,
355 region_name=region_name,
356 )
357 self.cinder = self.session["cinder"] = cClient.Client(
358 2,
359 session=sess,
360 endpoint_type=self.endpoint_type,
361 region_name=region_name,
362 )
363
tiernoa05b65a2019-02-01 12:30:27 +0000364 try:
sousaedu80135b92021-02-17 15:05:18 +0100365 self.my_tenant_id = self.session["my_tenant_id"] = sess.get_project_id()
tierno1ec592d2020-06-16 15:29:47 +0000366 except Exception:
tiernoa05b65a2019-02-01 12:30:27 +0000367 self.logger.error("Cannot get project_id from session", exc_info=True)
sousaedu80135b92021-02-17 15:05:18 +0100368
kate721d79b2017-06-24 04:21:38 -0700369 if self.endpoint_type == "internalURL":
370 glance_service_id = self.keystone.services.list(name="glance")[0].id
sousaedu80135b92021-02-17 15:05:18 +0100371 glance_endpoint = self.keystone.endpoints.list(
372 glance_service_id, interface="internal"
373 )[0].url
kate721d79b2017-06-24 04:21:38 -0700374 else:
375 glance_endpoint = None
sousaedu80135b92021-02-17 15:05:18 +0100376
377 self.glance = self.session["glance"] = glClient.Client(
378 2, session=sess, endpoint=glance_endpoint
379 )
tiernoa05b65a2019-02-01 12:30:27 +0000380 # using version 1 of glance client in new_image()
sousaedu80135b92021-02-17 15:05:18 +0100381 # self.glancev1 = self.session["glancev1"] = glClient.Client("1", session=sess,
tierno1beea862018-07-11 15:47:37 +0200382 # endpoint=glance_endpoint)
sousaedu80135b92021-02-17 15:05:18 +0100383 self.session["reload_client"] = False
384 self.persistent_info["session"] = self.session
mirabal29356312017-07-27 12:21:22 +0200385 # add availablity zone info inside self.persistent_info
386 self._set_availablity_zones()
sousaedu80135b92021-02-17 15:05:18 +0100387 self.persistent_info["availability_zone"] = self.availability_zone
388 # force to get again security_groups_ids next time they are needed
389 self.security_groups_id = None
ahmadsa95baa272016-11-30 09:14:11 +0500390
tierno7edb6752016-03-21 17:37:52 +0100391 def __net_os2mano(self, net_list_dict):
tierno1ec592d2020-06-16 15:29:47 +0000392 """Transform the net openstack format to mano format
393 net_list_dict can be a list of dict or a single dict"""
tierno7edb6752016-03-21 17:37:52 +0100394 if type(net_list_dict) is dict:
tierno1ec592d2020-06-16 15:29:47 +0000395 net_list_ = (net_list_dict,)
tierno7edb6752016-03-21 17:37:52 +0100396 elif type(net_list_dict) is list:
tierno1ec592d2020-06-16 15:29:47 +0000397 net_list_ = net_list_dict
tierno7edb6752016-03-21 17:37:52 +0100398 else:
399 raise TypeError("param net_list_dict must be a list or a dictionary")
400 for net in net_list_:
sousaedu80135b92021-02-17 15:05:18 +0100401 if net.get("provider:network_type") == "vlan":
402 net["type"] = "data"
tierno7edb6752016-03-21 17:37:52 +0100403 else:
sousaedu80135b92021-02-17 15:05:18 +0100404 net["type"] = "bridge"
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +0200405
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000406 def __classification_os2mano(self, class_list_dict):
407 """Transform the openstack format (Flow Classifier) to mano format
408 (Classification) class_list_dict can be a list of dict or a single dict
409 """
410 if isinstance(class_list_dict, dict):
411 class_list_ = [class_list_dict]
412 elif isinstance(class_list_dict, list):
413 class_list_ = class_list_dict
414 else:
tierno1ec592d2020-06-16 15:29:47 +0000415 raise TypeError("param class_list_dict must be a list or a dictionary")
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000416 for classification in class_list_:
sousaedu80135b92021-02-17 15:05:18 +0100417 id = classification.pop("id")
418 name = classification.pop("name")
419 description = classification.pop("description")
420 project_id = classification.pop("project_id")
421 tenant_id = classification.pop("tenant_id")
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000422 original_classification = copy.deepcopy(classification)
423 classification.clear()
sousaedu80135b92021-02-17 15:05:18 +0100424 classification["ctype"] = "legacy_flow_classifier"
425 classification["definition"] = original_classification
426 classification["id"] = id
427 classification["name"] = name
428 classification["description"] = description
429 classification["project_id"] = project_id
430 classification["tenant_id"] = tenant_id
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000431
432 def __sfi_os2mano(self, sfi_list_dict):
433 """Transform the openstack format (Port Pair) to mano format (SFI)
434 sfi_list_dict can be a list of dict or a single dict
435 """
436 if isinstance(sfi_list_dict, dict):
437 sfi_list_ = [sfi_list_dict]
438 elif isinstance(sfi_list_dict, list):
439 sfi_list_ = sfi_list_dict
440 else:
sousaedu80135b92021-02-17 15:05:18 +0100441 raise TypeError("param sfi_list_dict must be a list or a dictionary")
442
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000443 for sfi in sfi_list_:
sousaedu80135b92021-02-17 15:05:18 +0100444 sfi["ingress_ports"] = []
445 sfi["egress_ports"] = []
446
447 if sfi.get("ingress"):
448 sfi["ingress_ports"].append(sfi["ingress"])
449
450 if sfi.get("egress"):
451 sfi["egress_ports"].append(sfi["egress"])
452
453 del sfi["ingress"]
454 del sfi["egress"]
455 params = sfi.get("service_function_parameters")
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000456 sfc_encap = False
sousaedu80135b92021-02-17 15:05:18 +0100457
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000458 if params:
sousaedu80135b92021-02-17 15:05:18 +0100459 correlation = params.get("correlation")
460
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000461 if correlation:
462 sfc_encap = True
sousaedu80135b92021-02-17 15:05:18 +0100463
464 sfi["sfc_encap"] = sfc_encap
465 del sfi["service_function_parameters"]
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000466
467 def __sf_os2mano(self, sf_list_dict):
468 """Transform the openstack format (Port Pair Group) to mano format (SF)
469 sf_list_dict can be a list of dict or a single dict
470 """
471 if isinstance(sf_list_dict, dict):
472 sf_list_ = [sf_list_dict]
473 elif isinstance(sf_list_dict, list):
474 sf_list_ = sf_list_dict
475 else:
sousaedu80135b92021-02-17 15:05:18 +0100476 raise TypeError("param sf_list_dict must be a list or a dictionary")
477
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000478 for sf in sf_list_:
sousaedu80135b92021-02-17 15:05:18 +0100479 del sf["port_pair_group_parameters"]
480 sf["sfis"] = sf["port_pairs"]
481 del sf["port_pairs"]
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000482
483 def __sfp_os2mano(self, sfp_list_dict):
484 """Transform the openstack format (Port Chain) to mano format (SFP)
485 sfp_list_dict can be a list of dict or a single dict
486 """
487 if isinstance(sfp_list_dict, dict):
488 sfp_list_ = [sfp_list_dict]
489 elif isinstance(sfp_list_dict, list):
490 sfp_list_ = sfp_list_dict
491 else:
sousaedu80135b92021-02-17 15:05:18 +0100492 raise TypeError("param sfp_list_dict must be a list or a dictionary")
493
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000494 for sfp in sfp_list_:
sousaedu80135b92021-02-17 15:05:18 +0100495 params = sfp.pop("chain_parameters")
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000496 sfc_encap = False
sousaedu80135b92021-02-17 15:05:18 +0100497
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000498 if params:
sousaedu80135b92021-02-17 15:05:18 +0100499 correlation = params.get("correlation")
500
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000501 if correlation:
502 sfc_encap = True
sousaedu80135b92021-02-17 15:05:18 +0100503
504 sfp["sfc_encap"] = sfc_encap
505 sfp["spi"] = sfp.pop("chain_id")
506 sfp["classifications"] = sfp.pop("flow_classifiers")
507 sfp["service_functions"] = sfp.pop("port_pair_groups")
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000508
509 # placeholder for now; read TODO note below
510 def _validate_classification(self, type, definition):
511 # only legacy_flow_classifier Type is supported at this point
512 return True
513 # TODO(igordcard): this method should be an abstract method of an
514 # abstract Classification class to be implemented by the specific
515 # Types. Also, abstract vimconnector should call the validation
516 # method before the implemented VIM connectors are called.
517
tiernoae4a8d12016-07-08 12:30:39 +0200518 def _format_exception(self, exception):
tierno69647792020-03-05 16:45:48 +0000519 """Transform a keystone, nova, neutron exception into a vimconn exception discovering the cause"""
tierno69647792020-03-05 16:45:48 +0000520 message_error = str(exception)
tierno5ad826a2020-08-11 11:19:44 +0000521 tip = ""
tiernode12f782019-04-05 12:46:42 +0000522
sousaedu80135b92021-02-17 15:05:18 +0100523 if isinstance(
524 exception,
525 (
526 neExceptions.NetworkNotFoundClient,
527 nvExceptions.NotFound,
528 ksExceptions.NotFound,
529 gl1Exceptions.HTTPNotFound,
530 ),
531 ):
532 raise vimconn.VimConnNotFoundException(
533 type(exception).__name__ + ": " + message_error
534 )
535 elif isinstance(
536 exception,
537 (
538 HTTPException,
539 gl1Exceptions.HTTPException,
540 gl1Exceptions.CommunicationError,
541 ConnectionError,
542 ksExceptions.ConnectionError,
543 neExceptions.ConnectionFailed,
544 ),
545 ):
tierno5ad826a2020-08-11 11:19:44 +0000546 if type(exception).__name__ == "SSLError":
547 tip = " (maybe option 'insecure' must be added to the VIM)"
sousaedu80135b92021-02-17 15:05:18 +0100548
549 raise vimconn.VimConnConnectionException(
550 "Invalid URL or credentials{}: {}".format(tip, message_error)
551 )
552 elif isinstance(
553 exception,
554 (
555 KeyError,
556 nvExceptions.BadRequest,
557 ksExceptions.BadRequest,
558 ),
559 ):
560 raise vimconn.VimConnException(
561 type(exception).__name__ + ": " + message_error
562 )
563 elif isinstance(
564 exception,
565 (
566 nvExceptions.ClientException,
567 ksExceptions.ClientException,
568 neExceptions.NeutronException,
569 ),
570 ):
571 raise vimconn.VimConnUnexpectedResponse(
572 type(exception).__name__ + ": " + message_error
573 )
tiernoae4a8d12016-07-08 12:30:39 +0200574 elif isinstance(exception, nvExceptions.Conflict):
sousaedu80135b92021-02-17 15:05:18 +0100575 raise vimconn.VimConnConflictException(
576 type(exception).__name__ + ": " + message_error
577 )
tierno72774862020-05-04 11:44:15 +0000578 elif isinstance(exception, vimconn.VimConnException):
tierno41a69812018-02-16 14:34:33 +0100579 raise exception
tiernof716aea2017-06-21 18:01:40 +0200580 else: # ()
tiernode12f782019-04-05 12:46:42 +0000581 self.logger.error("General Exception " + message_error, exc_info=True)
sousaedu80135b92021-02-17 15:05:18 +0100582
583 raise vimconn.VimConnConnectionException(
584 type(exception).__name__ + ": " + message_error
585 )
tiernoae4a8d12016-07-08 12:30:39 +0200586
tiernoa05b65a2019-02-01 12:30:27 +0000587 def _get_ids_from_name(self):
588 """
589 Obtain ids from name of tenant and security_groups. Store at self .security_groups_id"
590 :return: None
591 """
592 # get tenant_id if only tenant_name is supplied
593 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +0100594
tiernoa05b65a2019-02-01 12:30:27 +0000595 if not self.my_tenant_id:
sousaedu80135b92021-02-17 15:05:18 +0100596 raise vimconn.VimConnConnectionException(
597 "Error getting tenant information from name={} id={}".format(
598 self.tenant_name, self.tenant_id
599 )
600 )
601
602 if self.config.get("security_groups") and not self.security_groups_id:
tiernoa05b65a2019-02-01 12:30:27 +0000603 # convert from name to id
sousaedu80135b92021-02-17 15:05:18 +0100604 neutron_sg_list = self.neutron.list_security_groups(
605 tenant_id=self.my_tenant_id
606 )["security_groups"]
tiernoa05b65a2019-02-01 12:30:27 +0000607
608 self.security_groups_id = []
sousaedu80135b92021-02-17 15:05:18 +0100609 for sg in self.config.get("security_groups"):
tiernoa05b65a2019-02-01 12:30:27 +0000610 for neutron_sg in neutron_sg_list:
611 if sg in (neutron_sg["id"], neutron_sg["name"]):
612 self.security_groups_id.append(neutron_sg["id"])
613 break
614 else:
615 self.security_groups_id = None
sousaedu80135b92021-02-17 15:05:18 +0100616
617 raise vimconn.VimConnConnectionException(
618 "Not found security group {} for this tenant".format(sg)
619 )
tiernoa05b65a2019-02-01 12:30:27 +0000620
tierno5509c2e2019-07-04 16:23:20 +0000621 def check_vim_connectivity(self):
622 # just get network list to check connectivity and credentials
623 self.get_network_list(filter_dict={})
624
tiernoae4a8d12016-07-08 12:30:39 +0200625 def get_tenant_list(self, filter_dict={}):
tierno1ec592d2020-06-16 15:29:47 +0000626 """Obtain tenants of VIM
tiernoae4a8d12016-07-08 12:30:39 +0200627 filter_dict can contain the following keys:
628 name: filter by tenant name
629 id: filter by tenant uuid/id
630 <other VIM specific>
631 Returns the tenant list of dictionaries: [{'name':'<name>, 'id':'<id>, ...}, ...]
tierno1ec592d2020-06-16 15:29:47 +0000632 """
ahmadsa95baa272016-11-30 09:14:11 +0500633 self.logger.debug("Getting tenants from VIM filter: '%s'", str(filter_dict))
sousaedu80135b92021-02-17 15:05:18 +0100634
tiernoae4a8d12016-07-08 12:30:39 +0200635 try:
636 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +0100637
tiernof716aea2017-06-21 18:01:40 +0200638 if self.api_version3:
sousaedu80135b92021-02-17 15:05:18 +0100639 project_class_list = self.keystone.projects.list(
640 name=filter_dict.get("name")
641 )
ahmadsa95baa272016-11-30 09:14:11 +0500642 else:
tiernof716aea2017-06-21 18:01:40 +0200643 project_class_list = self.keystone.tenants.findall(**filter_dict)
sousaedu80135b92021-02-17 15:05:18 +0100644
tierno1ec592d2020-06-16 15:29:47 +0000645 project_list = []
sousaedu80135b92021-02-17 15:05:18 +0100646
ahmadsa95baa272016-11-30 09:14:11 +0500647 for project in project_class_list:
sousaedu80135b92021-02-17 15:05:18 +0100648 if filter_dict.get("id") and filter_dict["id"] != project.id:
tiernof716aea2017-06-21 18:01:40 +0200649 continue
sousaedu80135b92021-02-17 15:05:18 +0100650
ahmadsa95baa272016-11-30 09:14:11 +0500651 project_list.append(project.to_dict())
sousaedu80135b92021-02-17 15:05:18 +0100652
ahmadsa95baa272016-11-30 09:14:11 +0500653 return project_list
sousaedu80135b92021-02-17 15:05:18 +0100654 except (
655 ksExceptions.ConnectionError,
656 ksExceptions.ClientException,
657 ConnectionError,
658 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200659 self._format_exception(e)
660
661 def new_tenant(self, tenant_name, tenant_description):
tierno1ec592d2020-06-16 15:29:47 +0000662 """Adds a new tenant to openstack VIM. Returns the tenant identifier"""
tiernoae4a8d12016-07-08 12:30:39 +0200663 self.logger.debug("Adding a new tenant name: %s", tenant_name)
sousaedu80135b92021-02-17 15:05:18 +0100664
tiernoae4a8d12016-07-08 12:30:39 +0200665 try:
666 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +0100667
tiernof716aea2017-06-21 18:01:40 +0200668 if self.api_version3:
sousaedu80135b92021-02-17 15:05:18 +0100669 project = self.keystone.projects.create(
670 tenant_name,
671 self.config.get("project_domain_id", "default"),
672 description=tenant_description,
673 is_domain=False,
674 )
ahmadsa95baa272016-11-30 09:14:11 +0500675 else:
tiernof716aea2017-06-21 18:01:40 +0200676 project = self.keystone.tenants.create(tenant_name, tenant_description)
sousaedu80135b92021-02-17 15:05:18 +0100677
ahmadsa95baa272016-11-30 09:14:11 +0500678 return project.id
sousaedu80135b92021-02-17 15:05:18 +0100679 except (
680 ksExceptions.ConnectionError,
681 ksExceptions.ClientException,
682 ksExceptions.BadRequest,
683 ConnectionError,
684 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200685 self._format_exception(e)
686
687 def delete_tenant(self, tenant_id):
tierno1ec592d2020-06-16 15:29:47 +0000688 """Delete a tenant from openstack VIM. Returns the old tenant identifier"""
tiernoae4a8d12016-07-08 12:30:39 +0200689 self.logger.debug("Deleting tenant %s from VIM", tenant_id)
sousaedu80135b92021-02-17 15:05:18 +0100690
tiernoae4a8d12016-07-08 12:30:39 +0200691 try:
692 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +0100693
tiernof716aea2017-06-21 18:01:40 +0200694 if self.api_version3:
ahmadsa95baa272016-11-30 09:14:11 +0500695 self.keystone.projects.delete(tenant_id)
696 else:
697 self.keystone.tenants.delete(tenant_id)
sousaedu80135b92021-02-17 15:05:18 +0100698
tiernoae4a8d12016-07-08 12:30:39 +0200699 return tenant_id
sousaedu80135b92021-02-17 15:05:18 +0100700 except (
701 ksExceptions.ConnectionError,
702 ksExceptions.ClientException,
703 ksExceptions.NotFound,
704 ConnectionError,
705 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200706 self._format_exception(e)
ahmadsa95baa272016-11-30 09:14:11 +0500707
sousaedu80135b92021-02-17 15:05:18 +0100708 def new_network(
709 self,
710 net_name,
711 net_type,
712 ip_profile=None,
713 shared=False,
714 provider_network_profile=None,
715 ):
garciadeblasebd66722019-01-31 16:01:31 +0000716 """Adds a tenant network to VIM
717 Params:
718 'net_name': name of the network
719 'net_type': one of:
720 'bridge': overlay isolated network
721 'data': underlay E-LAN network for Passthrough and SRIOV interfaces
722 'ptp': underlay E-LINE network for Passthrough and SRIOV interfaces.
723 'ip_profile': is a dict containing the IP parameters of the network
724 'ip_version': can be "IPv4" or "IPv6" (Currently only IPv4 is implemented)
725 'subnet_address': ip_prefix_schema, that is X.X.X.X/Y
726 'gateway_address': (Optional) ip_schema, that is X.X.X.X
727 'dns_address': (Optional) comma separated list of ip_schema, e.g. X.X.X.X[,X,X,X,X]
728 'dhcp_enabled': True or False
729 'dhcp_start_address': ip_schema, first IP to grant
730 'dhcp_count': number of IPs to grant.
731 'shared': if this network can be seen/use by other tenants/organization
garciadeblas4af0d542020-02-18 16:01:13 +0100732 'provider_network_profile': (optional) contains {segmentation-id: vlan, network-type: vlan|vxlan,
733 physical-network: physnet-label}
garciadeblasebd66722019-01-31 16:01:31 +0000734 Returns a tuple with the network identifier and created_items, or raises an exception on error
735 created_items can be None or a dictionary where this method can include key-values that will be passed to
736 the method delete_network. Can be used to store created segments, created l2gw connections, etc.
737 Format is vimconnector dependent, but do not use nested dictionaries and a value of None should be the same
738 as not present.
739 """
sousaedu80135b92021-02-17 15:05:18 +0100740 self.logger.debug(
741 "Adding a new network to VIM name '%s', type '%s'", net_name, net_type
742 )
garciadeblasebd66722019-01-31 16:01:31 +0000743 # self.logger.debug(">>>>>>>>>>>>>>>>>> IP profile %s", str(ip_profile))
kbsuba85c54d2019-10-17 16:30:32 +0000744
tierno7edb6752016-03-21 17:37:52 +0100745 try:
kbsuba85c54d2019-10-17 16:30:32 +0000746 vlan = None
sousaedu80135b92021-02-17 15:05:18 +0100747
kbsuba85c54d2019-10-17 16:30:32 +0000748 if provider_network_profile:
749 vlan = provider_network_profile.get("segmentation-id")
sousaedu80135b92021-02-17 15:05:18 +0100750
garciadeblasedca7b32016-09-29 14:01:52 +0000751 new_net = None
garciadeblasebd66722019-01-31 16:01:31 +0000752 created_items = {}
tierno7edb6752016-03-21 17:37:52 +0100753 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +0100754 network_dict = {"name": net_name, "admin_state_up": True}
755
Gabriel Cubab22d91e2022-12-14 18:33:50 -0500756 if net_type in ("data", "ptp") or provider_network_profile:
tierno6869ae72020-01-09 17:37:34 +0000757 provider_physical_network = None
sousaedu80135b92021-02-17 15:05:18 +0100758
759 if provider_network_profile and provider_network_profile.get(
760 "physical-network"
761 ):
762 provider_physical_network = provider_network_profile.get(
763 "physical-network"
764 )
765
tierno6869ae72020-01-09 17:37:34 +0000766 # provider-network must be one of the dataplane_physcial_netowrk if this is a list. If it is string
767 # or not declared, just ignore the checking
sousaedu80135b92021-02-17 15:05:18 +0100768 if (
769 isinstance(
770 self.config.get("dataplane_physical_net"), (tuple, list)
771 )
772 and provider_physical_network
773 not in self.config["dataplane_physical_net"]
774 ):
tierno72774862020-05-04 11:44:15 +0000775 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +0100776 "Invalid parameter 'provider-network:physical-network' "
777 "for network creation. '{}' is not one of the declared "
778 "list at VIM_config:dataplane_physical_net".format(
779 provider_physical_network
780 )
781 )
782
783 # use the default dataplane_physical_net
784 if not provider_physical_network:
785 provider_physical_network = self.config.get(
786 "dataplane_physical_net"
787 )
788
tierno6869ae72020-01-09 17:37:34 +0000789 # 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 +0100790 if (
791 isinstance(provider_physical_network, (tuple, list))
792 and provider_physical_network
793 ):
tierno6869ae72020-01-09 17:37:34 +0000794 provider_physical_network = provider_physical_network[0]
795
796 if not provider_physical_network:
tierno5ad826a2020-08-11 11:19:44 +0000797 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +0100798 "missing information needed for underlay networks. Provide "
799 "'dataplane_physical_net' configuration at VIM or use the NS "
800 "instantiation parameter 'provider-network.physical-network'"
801 " for the VLD"
802 )
tierno6869ae72020-01-09 17:37:34 +0000803
sousaedu80135b92021-02-17 15:05:18 +0100804 if not self.config.get("multisegment_support"):
805 network_dict[
806 "provider:physical_network"
807 ] = provider_physical_network
808
809 if (
810 provider_network_profile
811 and "network-type" in provider_network_profile
812 ):
813 network_dict[
814 "provider:network_type"
815 ] = provider_network_profile["network-type"]
garciadeblas4af0d542020-02-18 16:01:13 +0100816 else:
sousaedu80135b92021-02-17 15:05:18 +0100817 network_dict["provider:network_type"] = self.config.get(
818 "dataplane_network_type", "vlan"
819 )
820
tierno6869ae72020-01-09 17:37:34 +0000821 if vlan:
822 network_dict["provider:segmentation_id"] = vlan
garciadeblasebd66722019-01-31 16:01:31 +0000823 else:
tierno6869ae72020-01-09 17:37:34 +0000824 # Multi-segment case
garciadeblasebd66722019-01-31 16:01:31 +0000825 segment_list = []
tierno6869ae72020-01-09 17:37:34 +0000826 segment1_dict = {
sousaedu80135b92021-02-17 15:05:18 +0100827 "provider:physical_network": "",
828 "provider:network_type": "vxlan",
tierno6869ae72020-01-09 17:37:34 +0000829 }
garciadeblasebd66722019-01-31 16:01:31 +0000830 segment_list.append(segment1_dict)
tierno6869ae72020-01-09 17:37:34 +0000831 segment2_dict = {
832 "provider:physical_network": provider_physical_network,
sousaedu80135b92021-02-17 15:05:18 +0100833 "provider:network_type": "vlan",
tierno6869ae72020-01-09 17:37:34 +0000834 }
sousaedu80135b92021-02-17 15:05:18 +0100835
tierno6869ae72020-01-09 17:37:34 +0000836 if vlan:
837 segment2_dict["provider:segmentation_id"] = vlan
sousaedu80135b92021-02-17 15:05:18 +0100838 elif self.config.get("multisegment_vlan_range"):
garciadeblasebd66722019-01-31 16:01:31 +0000839 vlanID = self._generate_multisegment_vlanID()
840 segment2_dict["provider:segmentation_id"] = vlanID
sousaedu80135b92021-02-17 15:05:18 +0100841
garciadeblasebd66722019-01-31 16:01:31 +0000842 # else
tierno72774862020-05-04 11:44:15 +0000843 # raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +0100844 # "You must provide "multisegment_vlan_range" at config dict before creating a multisegment
tierno1ec592d2020-06-16 15:29:47 +0000845 # network")
garciadeblasebd66722019-01-31 16:01:31 +0000846 segment_list.append(segment2_dict)
847 network_dict["segments"] = segment_list
kate721d79b2017-06-24 04:21:38 -0700848
tierno6869ae72020-01-09 17:37:34 +0000849 # VIO Specific Changes. It needs a concrete VLAN
850 if self.vim_type == "VIO" and vlan is None:
sousaedu80135b92021-02-17 15:05:18 +0100851 if self.config.get("dataplane_net_vlan_range") is None:
tierno72774862020-05-04 11:44:15 +0000852 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +0100853 "You must provide 'dataplane_net_vlan_range' in format "
854 "[start_ID - end_ID] at VIM_config for creating underlay "
855 "networks"
856 )
857
tierno6869ae72020-01-09 17:37:34 +0000858 network_dict["provider:segmentation_id"] = self._generate_vlanID()
kate721d79b2017-06-24 04:21:38 -0700859
garciadeblasebd66722019-01-31 16:01:31 +0000860 network_dict["shared"] = shared
sousaedu80135b92021-02-17 15:05:18 +0100861
anwarsff168192019-05-06 11:23:07 +0530862 if self.config.get("disable_network_port_security"):
863 network_dict["port_security_enabled"] = False
sousaedu80135b92021-02-17 15:05:18 +0100864
sousaedu2aa5f802021-06-17 15:39:29 +0100865 if self.config.get("neutron_availability_zone_hints"):
866 hints = self.config.get("neutron_availability_zone_hints")
867
868 if isinstance(hints, str):
869 hints = [hints]
870
871 network_dict["availability_zone_hints"] = hints
872
sousaedu80135b92021-02-17 15:05:18 +0100873 new_net = self.neutron.create_network({"network": network_dict})
garciadeblasebd66722019-01-31 16:01:31 +0000874 # print new_net
875 # create subnetwork, even if there is no profile
sousaedu80135b92021-02-17 15:05:18 +0100876
garciadeblas9f8456e2016-09-05 05:02:59 +0200877 if not ip_profile:
878 ip_profile = {}
sousaedu80135b92021-02-17 15:05:18 +0100879
880 if not ip_profile.get("subnet_address"):
tierno1ec592d2020-06-16 15:29:47 +0000881 # Fake subnet is required
garciadeblas2299e3b2017-01-26 14:35:55 +0000882 subnet_rand = random.randint(0, 255)
sousaedu80135b92021-02-17 15:05:18 +0100883 ip_profile["subnet_address"] = "192.168.{}.0/24".format(subnet_rand)
884
885 if "ip_version" not in ip_profile:
886 ip_profile["ip_version"] = "IPv4"
887
888 subnet = {
889 "name": net_name + "-subnet",
890 "network_id": new_net["network"]["id"],
891 "ip_version": 4 if ip_profile["ip_version"] == "IPv4" else 6,
892 "cidr": ip_profile["subnet_address"],
893 }
894
tiernoa1fb4462017-06-30 12:25:50 +0200895 # Gateway should be set to None if not needed. Otherwise openstack assigns one by default
sousaedu80135b92021-02-17 15:05:18 +0100896 if ip_profile.get("gateway_address"):
897 subnet["gateway_ip"] = ip_profile["gateway_address"]
tierno55d234c2018-07-04 18:29:21 +0200898 else:
sousaedu80135b92021-02-17 15:05:18 +0100899 subnet["gateway_ip"] = None
900
901 if ip_profile.get("dns_address"):
902 subnet["dns_nameservers"] = ip_profile["dns_address"].split(";")
903
904 if "dhcp_enabled" in ip_profile:
905 subnet["enable_dhcp"] = (
906 False
907 if ip_profile["dhcp_enabled"] == "false"
908 or ip_profile["dhcp_enabled"] is False
909 else True
910 )
911
912 if ip_profile.get("dhcp_start_address"):
913 subnet["allocation_pools"] = []
914 subnet["allocation_pools"].append(dict())
915 subnet["allocation_pools"][0]["start"] = ip_profile[
916 "dhcp_start_address"
917 ]
918
919 if ip_profile.get("dhcp_count"):
920 # parts = ip_profile["dhcp_start_address"].split(".")
tierno1ec592d2020-06-16 15:29:47 +0000921 # ip_int = (int(parts[0]) << 24) + (int(parts[1]) << 16) + (int(parts[2]) << 8) + int(parts[3])
sousaedu80135b92021-02-17 15:05:18 +0100922 ip_int = int(netaddr.IPAddress(ip_profile["dhcp_start_address"]))
923 ip_int += ip_profile["dhcp_count"] - 1
garciadeblas9f8456e2016-09-05 05:02:59 +0200924 ip_str = str(netaddr.IPAddress(ip_int))
sousaedu80135b92021-02-17 15:05:18 +0100925 subnet["allocation_pools"][0]["end"] = ip_str
926
tierno1ec592d2020-06-16 15:29:47 +0000927 # self.logger.debug(">>>>>>>>>>>>>>>>>> Subnet: %s", str(subnet))
928 self.neutron.create_subnet({"subnet": subnet})
garciadeblasebd66722019-01-31 16:01:31 +0000929
sousaedu80135b92021-02-17 15:05:18 +0100930 if net_type == "data" and self.config.get("multisegment_support"):
931 if self.config.get("l2gw_support"):
garciadeblasebd66722019-01-31 16:01:31 +0000932 l2gw_list = self.neutron.list_l2_gateways().get("l2_gateways", ())
933 for l2gw in l2gw_list:
tierno1ec592d2020-06-16 15:29:47 +0000934 l2gw_conn = {
935 "l2_gateway_id": l2gw["id"],
936 "network_id": new_net["network"]["id"],
937 "segmentation_id": str(vlanID),
938 }
sousaedu80135b92021-02-17 15:05:18 +0100939 new_l2gw_conn = self.neutron.create_l2_gateway_connection(
940 {"l2_gateway_connection": l2gw_conn}
941 )
942 created_items[
943 "l2gwconn:"
944 + str(new_l2gw_conn["l2_gateway_connection"]["id"])
945 ] = True
946
garciadeblasebd66722019-01-31 16:01:31 +0000947 return new_net["network"]["id"], created_items
tierno41a69812018-02-16 14:34:33 +0100948 except Exception as e:
tierno1ec592d2020-06-16 15:29:47 +0000949 # delete l2gw connections (if any) before deleting the network
garciadeblasebd66722019-01-31 16:01:31 +0000950 for k, v in created_items.items():
951 if not v: # skip already deleted
952 continue
sousaedu80135b92021-02-17 15:05:18 +0100953
garciadeblasebd66722019-01-31 16:01:31 +0000954 try:
955 k_item, _, k_id = k.partition(":")
sousaedu80135b92021-02-17 15:05:18 +0100956
garciadeblasebd66722019-01-31 16:01:31 +0000957 if k_item == "l2gwconn":
958 self.neutron.delete_l2_gateway_connection(k_id)
959 except Exception as e2:
sousaedu80135b92021-02-17 15:05:18 +0100960 self.logger.error(
961 "Error deleting l2 gateway connection: {}: {}".format(
962 type(e2).__name__, e2
963 )
964 )
965
garciadeblasedca7b32016-09-29 14:01:52 +0000966 if new_net:
sousaedu80135b92021-02-17 15:05:18 +0100967 self.neutron.delete_network(new_net["network"]["id"])
968
tiernoae4a8d12016-07-08 12:30:39 +0200969 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +0100970
971 def get_network_list(self, filter_dict={}):
tierno1ec592d2020-06-16 15:29:47 +0000972 """Obtain tenant networks of VIM
tierno7edb6752016-03-21 17:37:52 +0100973 Filter_dict can be:
974 name: network name
975 id: network uuid
976 shared: boolean
977 tenant_id: tenant
978 admin_state_up: boolean
979 status: 'ACTIVE'
980 Returns the network list of dictionaries
tierno1ec592d2020-06-16 15:29:47 +0000981 """
tiernoae4a8d12016-07-08 12:30:39 +0200982 self.logger.debug("Getting network from VIM filter: '%s'", str(filter_dict))
sousaedu80135b92021-02-17 15:05:18 +0100983
tierno7edb6752016-03-21 17:37:52 +0100984 try:
985 self._reload_connection()
tierno69b590e2018-03-13 18:52:23 +0100986 filter_dict_os = filter_dict.copy()
sousaedu80135b92021-02-17 15:05:18 +0100987
tierno69b590e2018-03-13 18:52:23 +0100988 if self.api_version3 and "tenant_id" in filter_dict_os:
sousaedu80135b92021-02-17 15:05:18 +0100989 # TODO check
990 filter_dict_os["project_id"] = filter_dict_os.pop("tenant_id")
991
tierno69b590e2018-03-13 18:52:23 +0100992 net_dict = self.neutron.list_networks(**filter_dict_os)
tierno00e3df72017-11-29 17:20:13 +0100993 net_list = net_dict["networks"]
tierno7edb6752016-03-21 17:37:52 +0100994 self.__net_os2mano(net_list)
sousaedu80135b92021-02-17 15:05:18 +0100995
tiernoae4a8d12016-07-08 12:30:39 +0200996 return net_list
sousaedu80135b92021-02-17 15:05:18 +0100997 except (
998 neExceptions.ConnectionFailed,
999 ksExceptions.ClientException,
1000 neExceptions.NeutronException,
1001 ConnectionError,
1002 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001003 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001004
tiernoae4a8d12016-07-08 12:30:39 +02001005 def get_network(self, net_id):
tierno1ec592d2020-06-16 15:29:47 +00001006 """Obtain details of network from VIM
1007 Returns the network information from a network id"""
tiernoae4a8d12016-07-08 12:30:39 +02001008 self.logger.debug(" Getting tenant network %s from VIM", net_id)
tierno1ec592d2020-06-16 15:29:47 +00001009 filter_dict = {"id": net_id}
tiernoae4a8d12016-07-08 12:30:39 +02001010 net_list = self.get_network_list(filter_dict)
sousaedu80135b92021-02-17 15:05:18 +01001011
tierno1ec592d2020-06-16 15:29:47 +00001012 if len(net_list) == 0:
sousaedu80135b92021-02-17 15:05:18 +01001013 raise vimconn.VimConnNotFoundException(
1014 "Network '{}' not found".format(net_id)
1015 )
tierno1ec592d2020-06-16 15:29:47 +00001016 elif len(net_list) > 1:
sousaedu80135b92021-02-17 15:05:18 +01001017 raise vimconn.VimConnConflictException(
1018 "Found more than one network with this criteria"
1019 )
1020
tierno7edb6752016-03-21 17:37:52 +01001021 net = net_list[0]
tierno1ec592d2020-06-16 15:29:47 +00001022 subnets = []
1023 for subnet_id in net.get("subnets", ()):
tierno7edb6752016-03-21 17:37:52 +01001024 try:
1025 subnet = self.neutron.show_subnet(subnet_id)
1026 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01001027 self.logger.error(
1028 "osconnector.get_network(): Error getting subnet %s %s"
1029 % (net_id, str(e))
1030 )
tiernoae4a8d12016-07-08 12:30:39 +02001031 subnet = {"id": subnet_id, "fault": str(e)}
sousaedu80135b92021-02-17 15:05:18 +01001032
tierno7edb6752016-03-21 17:37:52 +01001033 subnets.append(subnet)
sousaedu80135b92021-02-17 15:05:18 +01001034
tierno7edb6752016-03-21 17:37:52 +01001035 net["subnets"] = subnets
sousaedu80135b92021-02-17 15:05:18 +01001036 net["encapsulation"] = net.get("provider:network_type")
1037 net["encapsulation_type"] = net.get("provider:network_type")
1038 net["segmentation_id"] = net.get("provider:segmentation_id")
1039 net["encapsulation_id"] = net.get("provider:segmentation_id")
1040
tiernoae4a8d12016-07-08 12:30:39 +02001041 return net
tierno7edb6752016-03-21 17:37:52 +01001042
garciadeblasebd66722019-01-31 16:01:31 +00001043 def delete_network(self, net_id, created_items=None):
1044 """
1045 Removes a tenant network from VIM and its associated elements
1046 :param net_id: VIM identifier of the network, provided by method new_network
1047 :param created_items: dictionary with extra items to be deleted. provided by method new_network
1048 Returns the network identifier or raises an exception upon error or when network is not found
1049 """
tiernoae4a8d12016-07-08 12:30:39 +02001050 self.logger.debug("Deleting network '%s' from VIM", net_id)
sousaedu80135b92021-02-17 15:05:18 +01001051
tierno1ec592d2020-06-16 15:29:47 +00001052 if created_items is None:
garciadeblasebd66722019-01-31 16:01:31 +00001053 created_items = {}
sousaedu80135b92021-02-17 15:05:18 +01001054
tierno7edb6752016-03-21 17:37:52 +01001055 try:
1056 self._reload_connection()
tierno1ec592d2020-06-16 15:29:47 +00001057 # delete l2gw connections (if any) before deleting the network
garciadeblasebd66722019-01-31 16:01:31 +00001058 for k, v in created_items.items():
1059 if not v: # skip already deleted
1060 continue
sousaedu80135b92021-02-17 15:05:18 +01001061
garciadeblasebd66722019-01-31 16:01:31 +00001062 try:
1063 k_item, _, k_id = k.partition(":")
1064 if k_item == "l2gwconn":
1065 self.neutron.delete_l2_gateway_connection(k_id)
1066 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01001067 self.logger.error(
1068 "Error deleting l2 gateway connection: {}: {}".format(
1069 type(e).__name__, e
1070 )
1071 )
1072
tierno1ec592d2020-06-16 15:29:47 +00001073 # delete VM ports attached to this networks before the network
tierno7edb6752016-03-21 17:37:52 +01001074 ports = self.neutron.list_ports(network_id=net_id)
sousaedu80135b92021-02-17 15:05:18 +01001075 for p in ports["ports"]:
tierno7edb6752016-03-21 17:37:52 +01001076 try:
1077 self.neutron.delete_port(p["id"])
1078 except Exception as e:
tiernoae4a8d12016-07-08 12:30:39 +02001079 self.logger.error("Error deleting port %s: %s", p["id"], str(e))
sousaedu80135b92021-02-17 15:05:18 +01001080
tierno7edb6752016-03-21 17:37:52 +01001081 self.neutron.delete_network(net_id)
sousaedu80135b92021-02-17 15:05:18 +01001082
tiernoae4a8d12016-07-08 12:30:39 +02001083 return net_id
sousaedu80135b92021-02-17 15:05:18 +01001084 except (
1085 neExceptions.ConnectionFailed,
1086 neExceptions.NetworkNotFoundClient,
1087 neExceptions.NeutronException,
1088 ksExceptions.ClientException,
1089 neExceptions.NeutronException,
1090 ConnectionError,
1091 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001092 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001093
tiernoae4a8d12016-07-08 12:30:39 +02001094 def refresh_nets_status(self, net_list):
tierno1ec592d2020-06-16 15:29:47 +00001095 """Get the status of the networks
sousaedu80135b92021-02-17 15:05:18 +01001096 Params: the list of network identifiers
1097 Returns a dictionary with:
1098 net_id: #VIM id of this network
1099 status: #Mandatory. Text with one of:
1100 # DELETED (not found at vim)
1101 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
1102 # OTHER (Vim reported other status not understood)
1103 # ERROR (VIM indicates an ERROR status)
1104 # ACTIVE, INACTIVE, DOWN (admin down),
1105 # BUILD (on building process)
1106 #
1107 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
1108 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
tierno1ec592d2020-06-16 15:29:47 +00001109 """
1110 net_dict = {}
sousaedu80135b92021-02-17 15:05:18 +01001111
tiernoae4a8d12016-07-08 12:30:39 +02001112 for net_id in net_list:
1113 net = {}
sousaedu80135b92021-02-17 15:05:18 +01001114
tiernoae4a8d12016-07-08 12:30:39 +02001115 try:
1116 net_vim = self.get_network(net_id)
sousaedu80135b92021-02-17 15:05:18 +01001117
1118 if net_vim["status"] in netStatus2manoFormat:
1119 net["status"] = netStatus2manoFormat[net_vim["status"]]
tiernoae4a8d12016-07-08 12:30:39 +02001120 else:
1121 net["status"] = "OTHER"
sousaedu80135b92021-02-17 15:05:18 +01001122 net["error_msg"] = "VIM status reported " + net_vim["status"]
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001123
sousaedu80135b92021-02-17 15:05:18 +01001124 if net["status"] == "ACTIVE" and not net_vim["admin_state_up"]:
1125 net["status"] = "DOWN"
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001126
sousaedu80135b92021-02-17 15:05:18 +01001127 net["vim_info"] = self.serialize(net_vim)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001128
sousaedu80135b92021-02-17 15:05:18 +01001129 if net_vim.get("fault"): # TODO
1130 net["error_msg"] = str(net_vim["fault"])
tierno72774862020-05-04 11:44:15 +00001131 except vimconn.VimConnNotFoundException as e:
tiernoae4a8d12016-07-08 12:30:39 +02001132 self.logger.error("Exception getting net status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01001133 net["status"] = "DELETED"
1134 net["error_msg"] = str(e)
tierno72774862020-05-04 11:44:15 +00001135 except vimconn.VimConnException as e:
tiernoae4a8d12016-07-08 12:30:39 +02001136 self.logger.error("Exception getting net status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01001137 net["status"] = "VIM_ERROR"
1138 net["error_msg"] = str(e)
tiernoae4a8d12016-07-08 12:30:39 +02001139 net_dict[net_id] = net
1140 return net_dict
1141
1142 def get_flavor(self, flavor_id):
tierno1ec592d2020-06-16 15:29:47 +00001143 """Obtain flavor details from the VIM. Returns the flavor dict details"""
tiernoae4a8d12016-07-08 12:30:39 +02001144 self.logger.debug("Getting flavor '%s'", flavor_id)
sousaedu80135b92021-02-17 15:05:18 +01001145
tierno7edb6752016-03-21 17:37:52 +01001146 try:
1147 self._reload_connection()
1148 flavor = self.nova.flavors.find(id=flavor_id)
tierno1ec592d2020-06-16 15:29:47 +00001149 # TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
sousaedu80135b92021-02-17 15:05:18 +01001150
tiernoae4a8d12016-07-08 12:30:39 +02001151 return flavor.to_dict()
sousaedu80135b92021-02-17 15:05:18 +01001152 except (
1153 nvExceptions.NotFound,
1154 nvExceptions.ClientException,
1155 ksExceptions.ClientException,
1156 ConnectionError,
1157 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001158 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001159
tiernocf157a82017-01-30 14:07:06 +01001160 def get_flavor_id_from_data(self, flavor_dict):
1161 """Obtain flavor id that match the flavor description
sousaedu80135b92021-02-17 15:05:18 +01001162 Returns the flavor_id or raises a vimconnNotFoundException
1163 flavor_dict: contains the required ram, vcpus, disk
1164 If 'use_existing_flavors' is set to True at config, the closer flavor that provides same or more ram, vcpus
1165 and disk is returned. Otherwise a flavor with exactly same ram, vcpus and disk is returned or a
1166 vimconnNotFoundException is raised
tiernocf157a82017-01-30 14:07:06 +01001167 """
sousaedu80135b92021-02-17 15:05:18 +01001168 exact_match = False if self.config.get("use_existing_flavors") else True
1169
tiernocf157a82017-01-30 14:07:06 +01001170 try:
1171 self._reload_connection()
tiernoe26fc7a2017-05-30 14:43:03 +02001172 flavor_candidate_id = None
1173 flavor_candidate_data = (10000, 10000, 10000)
sousaedu80135b92021-02-17 15:05:18 +01001174 flavor_target = (
1175 flavor_dict["ram"],
1176 flavor_dict["vcpus"],
1177 flavor_dict["disk"],
sousaedu648ee3d2021-11-22 14:09:15 +00001178 flavor_dict.get("ephemeral", 0),
1179 flavor_dict.get("swap", 0),
sousaedu80135b92021-02-17 15:05:18 +01001180 )
tiernoe26fc7a2017-05-30 14:43:03 +02001181 # numa=None
anwarsae5f52c2019-04-22 10:35:27 +05301182 extended = flavor_dict.get("extended", {})
1183 if extended:
tierno1ec592d2020-06-16 15:29:47 +00001184 # TODO
sousaedu80135b92021-02-17 15:05:18 +01001185 raise vimconn.VimConnNotFoundException(
1186 "Flavor with EPA still not implemented"
1187 )
tiernocf157a82017-01-30 14:07:06 +01001188 # if len(numas) > 1:
tierno72774862020-05-04 11:44:15 +00001189 # raise vimconn.VimConnNotFoundException("Cannot find any flavor with more than one numa")
tiernocf157a82017-01-30 14:07:06 +01001190 # numa=numas[0]
1191 # numas = extended.get("numas")
1192 for flavor in self.nova.flavors.list():
1193 epa = flavor.get_keys()
sousaedu80135b92021-02-17 15:05:18 +01001194
tiernocf157a82017-01-30 14:07:06 +01001195 if epa:
1196 continue
tiernoe26fc7a2017-05-30 14:43:03 +02001197 # TODO
sousaedu80135b92021-02-17 15:05:18 +01001198
sousaedu648ee3d2021-11-22 14:09:15 +00001199 flavor_data = (
1200 flavor.ram,
1201 flavor.vcpus,
1202 flavor.disk,
1203 flavor.ephemeral,
preethika.pebaba1f2022-01-20 07:24:18 +00001204 flavor.swap if isinstance(flavor.swap, int) else 0,
sousaedu648ee3d2021-11-22 14:09:15 +00001205 )
tiernoe26fc7a2017-05-30 14:43:03 +02001206 if flavor_data == flavor_target:
1207 return flavor.id
sousaedu80135b92021-02-17 15:05:18 +01001208 elif (
1209 not exact_match
1210 and flavor_target < flavor_data < flavor_candidate_data
1211 ):
tiernoe26fc7a2017-05-30 14:43:03 +02001212 flavor_candidate_id = flavor.id
1213 flavor_candidate_data = flavor_data
sousaedu80135b92021-02-17 15:05:18 +01001214
tiernoe26fc7a2017-05-30 14:43:03 +02001215 if not exact_match and flavor_candidate_id:
1216 return flavor_candidate_id
sousaedu80135b92021-02-17 15:05:18 +01001217
1218 raise vimconn.VimConnNotFoundException(
1219 "Cannot find any flavor matching '{}'".format(flavor_dict)
1220 )
1221 except (
1222 nvExceptions.NotFound,
1223 nvExceptions.ClientException,
1224 ksExceptions.ClientException,
1225 ConnectionError,
1226 ) as e:
tiernocf157a82017-01-30 14:07:06 +01001227 self._format_exception(e)
1228
anwarsae5f52c2019-04-22 10:35:27 +05301229 def process_resource_quota(self, quota, prefix, extra_specs):
1230 """
1231 :param prefix:
borsatti8a2dda32019-12-18 15:08:57 +00001232 :param extra_specs:
anwarsae5f52c2019-04-22 10:35:27 +05301233 :return:
1234 """
sousaedu80135b92021-02-17 15:05:18 +01001235 if "limit" in quota:
1236 extra_specs["quota:" + prefix + "_limit"] = quota["limit"]
1237
1238 if "reserve" in quota:
1239 extra_specs["quota:" + prefix + "_reservation"] = quota["reserve"]
1240
1241 if "shares" in quota:
anwarsae5f52c2019-04-22 10:35:27 +05301242 extra_specs["quota:" + prefix + "_shares_level"] = "custom"
sousaedu80135b92021-02-17 15:05:18 +01001243 extra_specs["quota:" + prefix + "_shares_share"] = quota["shares"]
anwarsae5f52c2019-04-22 10:35:27 +05301244
tiernoae4a8d12016-07-08 12:30:39 +02001245 def new_flavor(self, flavor_data, change_name_if_used=True):
tierno1ec592d2020-06-16 15:29:47 +00001246 """Adds a tenant flavor to openstack VIM
1247 if change_name_if_used is True, it will change name in case of conflict, because it is not supported name
1248 repetition
tierno7edb6752016-03-21 17:37:52 +01001249 Returns the flavor identifier
tierno1ec592d2020-06-16 15:29:47 +00001250 """
tiernoae4a8d12016-07-08 12:30:39 +02001251 self.logger.debug("Adding flavor '%s'", str(flavor_data))
tierno1ec592d2020-06-16 15:29:47 +00001252 retry = 0
1253 max_retries = 3
tierno7edb6752016-03-21 17:37:52 +01001254 name_suffix = 0
sousaedu80135b92021-02-17 15:05:18 +01001255
anwarsc76a3ee2018-10-04 14:05:32 +05301256 try:
sousaedu80135b92021-02-17 15:05:18 +01001257 name = flavor_data["name"]
tierno1ec592d2020-06-16 15:29:47 +00001258 while retry < max_retries:
1259 retry += 1
anwarsc76a3ee2018-10-04 14:05:32 +05301260 try:
1261 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +01001262
anwarsc76a3ee2018-10-04 14:05:32 +05301263 if change_name_if_used:
tierno1ec592d2020-06-16 15:29:47 +00001264 # get used names
1265 fl_names = []
1266 fl = self.nova.flavors.list()
sousaedu80135b92021-02-17 15:05:18 +01001267
anwarsc76a3ee2018-10-04 14:05:32 +05301268 for f in fl:
1269 fl_names.append(f.name)
sousaedu80135b92021-02-17 15:05:18 +01001270
anwarsc76a3ee2018-10-04 14:05:32 +05301271 while name in fl_names:
1272 name_suffix += 1
sousaedu80135b92021-02-17 15:05:18 +01001273 name = flavor_data["name"] + "-" + str(name_suffix)
kate721d79b2017-06-24 04:21:38 -07001274
sousaedu80135b92021-02-17 15:05:18 +01001275 ram = flavor_data.get("ram", 64)
1276 vcpus = flavor_data.get("vcpus", 1)
tierno1ec592d2020-06-16 15:29:47 +00001277 extra_specs = {}
tierno7edb6752016-03-21 17:37:52 +01001278
anwarsc76a3ee2018-10-04 14:05:32 +05301279 extended = flavor_data.get("extended")
1280 if extended:
tierno1ec592d2020-06-16 15:29:47 +00001281 numas = extended.get("numas")
sousaedu80135b92021-02-17 15:05:18 +01001282
anwarsc76a3ee2018-10-04 14:05:32 +05301283 if numas:
1284 numa_nodes = len(numas)
sousaedu80135b92021-02-17 15:05:18 +01001285
anwarsae5f52c2019-04-22 10:35:27 +05301286 extra_specs["hw:numa_nodes"] = str(numa_nodes)
sousaedu80135b92021-02-17 15:05:18 +01001287
anwarsc76a3ee2018-10-04 14:05:32 +05301288 if self.vim_type == "VIO":
sousaedu80135b92021-02-17 15:05:18 +01001289 extra_specs[
1290 "vmware:extra_config"
1291 ] = '{"numa.nodeAffinity":"0"}'
anwarsae5f52c2019-04-22 10:35:27 +05301292 extra_specs["vmware:latency_sensitivity_level"] = "high"
sousaedu80135b92021-02-17 15:05:18 +01001293
anwarsc76a3ee2018-10-04 14:05:32 +05301294 for numa in numas:
sritharan1d129842022-10-13 05:43:13 +00001295 if "id" in numa:
1296 node_id = numa["id"]
1297
1298 if "memory" in numa:
1299 memory_mb = numa["memory"] * 1024
1300 memory = "hw:numa_mem.{}".format(node_id)
1301 extra_specs[memory] = int(memory_mb)
1302
1303 if "vcpu" in numa:
1304 vcpu = numa["vcpu"]
1305 cpu = "hw:numa_cpus.{}".format(node_id)
1306 vcpu = ",".join(map(str, vcpu))
1307 extra_specs[cpu] = vcpu
1308
tierno1ec592d2020-06-16 15:29:47 +00001309 # overwrite ram and vcpus
sousaedu80135b92021-02-17 15:05:18 +01001310 # check if key "memory" is present in numa else use ram value at flavor
tierno1ec592d2020-06-16 15:29:47 +00001311 # See for reference: https://specs.openstack.org/openstack/nova-specs/specs/mitaka/
1312 # implemented/virt-driver-cpu-thread-pinning.html
sritharan1d129842022-10-13 05:43:13 +00001313 extra_specs["hw:cpu_sockets"] = str(numa_nodes)
sousaedu80135b92021-02-17 15:05:18 +01001314
1315 if "paired-threads" in numa:
1316 vcpus = numa["paired-threads"] * 2
1317 # cpu_thread_policy "require" implies that the compute node must have an
tierno1ec592d2020-06-16 15:29:47 +00001318 # STM architecture
anwarsae5f52c2019-04-22 10:35:27 +05301319 extra_specs["hw:cpu_thread_policy"] = "require"
1320 extra_specs["hw:cpu_policy"] = "dedicated"
sousaedu80135b92021-02-17 15:05:18 +01001321 elif "cores" in numa:
1322 vcpus = numa["cores"]
1323 # cpu_thread_policy "prefer" implies that the host must not have an SMT
tierno1ec592d2020-06-16 15:29:47 +00001324 # architecture, or a non-SMT architecture will be emulated
anwarsae5f52c2019-04-22 10:35:27 +05301325 extra_specs["hw:cpu_thread_policy"] = "isolate"
1326 extra_specs["hw:cpu_policy"] = "dedicated"
sousaedu80135b92021-02-17 15:05:18 +01001327 elif "threads" in numa:
1328 vcpus = numa["threads"]
tierno1ec592d2020-06-16 15:29:47 +00001329 # cpu_thread_policy "prefer" implies that the host may or may not have an SMT
1330 # architecture
anwarsae5f52c2019-04-22 10:35:27 +05301331 extra_specs["hw:cpu_thread_policy"] = "prefer"
1332 extra_specs["hw:cpu_policy"] = "dedicated"
anwarsc76a3ee2018-10-04 14:05:32 +05301333 # for interface in numa.get("interfaces",() ):
1334 # if interface["dedicated"]=="yes":
tierno1ec592d2020-06-16 15:29:47 +00001335 # raise vimconn.VimConnException("Passthrough interfaces are not supported
1336 # for the openstack connector", http_code=vimconn.HTTP_Service_Unavailable)
sousaedu80135b92021-02-17 15:05:18 +01001337 # #TODO, add the key 'pci_passthrough:alias"="<label at config>:<number ifaces>"'
tierno1ec592d2020-06-16 15:29:47 +00001338 # when a way to connect it is available
anwarsae5f52c2019-04-22 10:35:27 +05301339 elif extended.get("cpu-quota"):
sousaedu80135b92021-02-17 15:05:18 +01001340 self.process_resource_quota(
1341 extended.get("cpu-quota"), "cpu", extra_specs
1342 )
1343
anwarsae5f52c2019-04-22 10:35:27 +05301344 if extended.get("mem-quota"):
sousaedu80135b92021-02-17 15:05:18 +01001345 self.process_resource_quota(
1346 extended.get("mem-quota"), "memory", extra_specs
1347 )
1348
anwarsae5f52c2019-04-22 10:35:27 +05301349 if extended.get("vif-quota"):
sousaedu80135b92021-02-17 15:05:18 +01001350 self.process_resource_quota(
1351 extended.get("vif-quota"), "vif", extra_specs
1352 )
1353
anwarsae5f52c2019-04-22 10:35:27 +05301354 if extended.get("disk-io-quota"):
sousaedu80135b92021-02-17 15:05:18 +01001355 self.process_resource_quota(
1356 extended.get("disk-io-quota"), "disk_io", extra_specs
1357 )
1358
rodriguezgar0dd83fd2022-05-15 00:42:45 +02001359 # Set the mempage size as specified in the descriptor
1360 if extended.get("mempage-size"):
1361 if extended.get("mempage-size") == "LARGE":
1362 extra_specs["hw:mem_page_size"] = "large"
1363 elif extended.get("mempage-size") == "SMALL":
1364 extra_specs["hw:mem_page_size"] = "small"
1365 elif extended.get("mempage-size") == "SIZE_2MB":
1366 extra_specs["hw:mem_page_size"] = "2MB"
1367 elif extended.get("mempage-size") == "SIZE_1GB":
1368 extra_specs["hw:mem_page_size"] = "1GB"
1369 elif extended.get("mempage-size") == "PREFER_LARGE":
1370 extra_specs["hw:mem_page_size"] = "any"
1371 else:
1372 # The validations in NBI should make reaching here not possible.
1373 # If this message is shown, check validations
1374 self.logger.debug(
1375 "Invalid mempage-size %s. Will be ignored",
1376 extended.get("mempage-size"),
1377 )
sritharan1d129842022-10-13 05:43:13 +00001378 if extended.get("cpu-pinning-policy"):
1379 extra_specs["hw:cpu_policy"] = extended.get(
1380 "cpu-pinning-policy"
1381 ).lower()
1382
1383 # Set the cpu thread pinning policy as specified in the descriptor
1384 if extended.get("cpu-thread-pinning-policy"):
1385 extra_specs["hw:cpu_thread_policy"] = extended.get(
1386 "cpu-thread-pinning-policy"
1387 ).lower()
1388
1389 # Set the mem policy as specified in the descriptor
1390 if extended.get("mem-policy"):
1391 extra_specs["hw:numa_mempolicy"] = extended.get(
1392 "mem-policy"
1393 ).lower()
1394
tierno1ec592d2020-06-16 15:29:47 +00001395 # create flavor
sousaedu80135b92021-02-17 15:05:18 +01001396 new_flavor = self.nova.flavors.create(
sousaeduf524da82021-11-22 14:02:17 +00001397 name=name,
1398 ram=ram,
1399 vcpus=vcpus,
1400 disk=flavor_data.get("disk", 0),
1401 ephemeral=flavor_data.get("ephemeral", 0),
sousaedu648ee3d2021-11-22 14:09:15 +00001402 swap=flavor_data.get("swap", 0),
sousaedu80135b92021-02-17 15:05:18 +01001403 is_public=flavor_data.get("is_public", True),
1404 )
tierno1ec592d2020-06-16 15:29:47 +00001405 # add metadata
anwarsae5f52c2019-04-22 10:35:27 +05301406 if extra_specs:
1407 new_flavor.set_keys(extra_specs)
sousaedu80135b92021-02-17 15:05:18 +01001408
anwarsc76a3ee2018-10-04 14:05:32 +05301409 return new_flavor.id
1410 except nvExceptions.Conflict as e:
1411 if change_name_if_used and retry < max_retries:
1412 continue
sousaedu80135b92021-02-17 15:05:18 +01001413
anwarsc76a3ee2018-10-04 14:05:32 +05301414 self._format_exception(e)
tierno1ec592d2020-06-16 15:29:47 +00001415 # except nvExceptions.BadRequest as e:
sousaedu80135b92021-02-17 15:05:18 +01001416 except (
1417 ksExceptions.ClientException,
1418 nvExceptions.ClientException,
1419 ConnectionError,
1420 KeyError,
1421 ) as e:
anwarsc76a3ee2018-10-04 14:05:32 +05301422 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001423
tierno1ec592d2020-06-16 15:29:47 +00001424 def delete_flavor(self, flavor_id):
sousaedu80135b92021-02-17 15:05:18 +01001425 """Deletes a tenant flavor from openstack VIM. Returns the old flavor_id"""
tiernoae4a8d12016-07-08 12:30:39 +02001426 try:
1427 self._reload_connection()
1428 self.nova.flavors.delete(flavor_id)
sousaedu80135b92021-02-17 15:05:18 +01001429
tiernoae4a8d12016-07-08 12:30:39 +02001430 return flavor_id
tierno1ec592d2020-06-16 15:29:47 +00001431 # except nvExceptions.BadRequest as e:
sousaedu80135b92021-02-17 15:05:18 +01001432 except (
1433 nvExceptions.NotFound,
1434 ksExceptions.ClientException,
1435 nvExceptions.ClientException,
1436 ConnectionError,
1437 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001438 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001439
tierno1ec592d2020-06-16 15:29:47 +00001440 def new_image(self, image_dict):
1441 """
tiernoae4a8d12016-07-08 12:30:39 +02001442 Adds a tenant image to VIM. imge_dict is a dictionary with:
1443 name: name
1444 disk_format: qcow2, vhd, vmdk, raw (by default), ...
1445 location: path or URI
1446 public: "yes" or "no"
1447 metadata: metadata of the image
1448 Returns the image_id
tierno1ec592d2020-06-16 15:29:47 +00001449 """
1450 retry = 0
1451 max_retries = 3
sousaedu80135b92021-02-17 15:05:18 +01001452
tierno1ec592d2020-06-16 15:29:47 +00001453 while retry < max_retries:
1454 retry += 1
tierno7edb6752016-03-21 17:37:52 +01001455 try:
1456 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +01001457
tierno1ec592d2020-06-16 15:29:47 +00001458 # determine format http://docs.openstack.org/developer/glance/formats.html
tierno7edb6752016-03-21 17:37:52 +01001459 if "disk_format" in image_dict:
tierno1ec592d2020-06-16 15:29:47 +00001460 disk_format = image_dict["disk_format"]
1461 else: # autodiscover based on extension
sousaedu80135b92021-02-17 15:05:18 +01001462 if image_dict["location"].endswith(".qcow2"):
tierno1ec592d2020-06-16 15:29:47 +00001463 disk_format = "qcow2"
sousaedu80135b92021-02-17 15:05:18 +01001464 elif image_dict["location"].endswith(".vhd"):
tierno1ec592d2020-06-16 15:29:47 +00001465 disk_format = "vhd"
sousaedu80135b92021-02-17 15:05:18 +01001466 elif image_dict["location"].endswith(".vmdk"):
tierno1ec592d2020-06-16 15:29:47 +00001467 disk_format = "vmdk"
sousaedu80135b92021-02-17 15:05:18 +01001468 elif image_dict["location"].endswith(".vdi"):
tierno1ec592d2020-06-16 15:29:47 +00001469 disk_format = "vdi"
sousaedu80135b92021-02-17 15:05:18 +01001470 elif image_dict["location"].endswith(".iso"):
tierno1ec592d2020-06-16 15:29:47 +00001471 disk_format = "iso"
sousaedu80135b92021-02-17 15:05:18 +01001472 elif image_dict["location"].endswith(".aki"):
tierno1ec592d2020-06-16 15:29:47 +00001473 disk_format = "aki"
sousaedu80135b92021-02-17 15:05:18 +01001474 elif image_dict["location"].endswith(".ari"):
tierno1ec592d2020-06-16 15:29:47 +00001475 disk_format = "ari"
sousaedu80135b92021-02-17 15:05:18 +01001476 elif image_dict["location"].endswith(".ami"):
tierno1ec592d2020-06-16 15:29:47 +00001477 disk_format = "ami"
tierno7edb6752016-03-21 17:37:52 +01001478 else:
tierno1ec592d2020-06-16 15:29:47 +00001479 disk_format = "raw"
sousaedu80135b92021-02-17 15:05:18 +01001480
1481 self.logger.debug(
1482 "new_image: '%s' loading from '%s'",
1483 image_dict["name"],
1484 image_dict["location"],
1485 )
shashankjain3c83a212018-10-04 13:05:46 +05301486 if self.vim_type == "VIO":
1487 container_format = "bare"
sousaedu80135b92021-02-17 15:05:18 +01001488 if "container_format" in image_dict:
1489 container_format = image_dict["container_format"]
1490
1491 new_image = self.glance.images.create(
1492 name=image_dict["name"],
1493 container_format=container_format,
1494 disk_format=disk_format,
1495 )
shashankjain3c83a212018-10-04 13:05:46 +05301496 else:
sousaedu80135b92021-02-17 15:05:18 +01001497 new_image = self.glance.images.create(name=image_dict["name"])
1498
1499 if image_dict["location"].startswith("http"):
tierno1beea862018-07-11 15:47:37 +02001500 # TODO there is not a method to direct download. It must be downloaded locally with requests
tierno72774862020-05-04 11:44:15 +00001501 raise vimconn.VimConnNotImplemented("Cannot create image from URL")
tierno1ec592d2020-06-16 15:29:47 +00001502 else: # local path
sousaedu80135b92021-02-17 15:05:18 +01001503 with open(image_dict["location"]) as fimage:
tierno1beea862018-07-11 15:47:37 +02001504 self.glance.images.upload(new_image.id, fimage)
sousaedu80135b92021-02-17 15:05:18 +01001505 # new_image = self.glancev1.images.create(name=image_dict["name"], is_public=
1506 # image_dict.get("public","yes")=="yes",
tierno1beea862018-07-11 15:47:37 +02001507 # container_format="bare", data=fimage, disk_format=disk_format)
sousaedu80135b92021-02-17 15:05:18 +01001508
1509 metadata_to_load = image_dict.get("metadata")
1510
1511 # TODO location is a reserved word for current openstack versions. fixed for VIO please check
tierno1ec592d2020-06-16 15:29:47 +00001512 # for openstack
shashankjain3c83a212018-10-04 13:05:46 +05301513 if self.vim_type == "VIO":
sousaedu80135b92021-02-17 15:05:18 +01001514 metadata_to_load["upload_location"] = image_dict["location"]
shashankjain3c83a212018-10-04 13:05:46 +05301515 else:
sousaedu80135b92021-02-17 15:05:18 +01001516 metadata_to_load["location"] = image_dict["location"]
1517
tierno1beea862018-07-11 15:47:37 +02001518 self.glance.images.update(new_image.id, **metadata_to_load)
sousaedu80135b92021-02-17 15:05:18 +01001519
tiernoae4a8d12016-07-08 12:30:39 +02001520 return new_image.id
sousaedu80135b92021-02-17 15:05:18 +01001521 except (
1522 nvExceptions.Conflict,
1523 ksExceptions.ClientException,
1524 nvExceptions.ClientException,
1525 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001526 self._format_exception(e)
sousaedu80135b92021-02-17 15:05:18 +01001527 except (
1528 HTTPException,
1529 gl1Exceptions.HTTPException,
1530 gl1Exceptions.CommunicationError,
1531 ConnectionError,
1532 ) as e:
tierno1ec592d2020-06-16 15:29:47 +00001533 if retry == max_retries:
tiernoae4a8d12016-07-08 12:30:39 +02001534 continue
sousaedu80135b92021-02-17 15:05:18 +01001535
tiernoae4a8d12016-07-08 12:30:39 +02001536 self._format_exception(e)
tierno1ec592d2020-06-16 15:29:47 +00001537 except IOError as e: # can not open the file
sousaedu80135b92021-02-17 15:05:18 +01001538 raise vimconn.VimConnConnectionException(
1539 "{}: {} for {}".format(type(e).__name__, e, image_dict["location"]),
1540 http_code=vimconn.HTTP_Bad_Request,
1541 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001542
tiernoae4a8d12016-07-08 12:30:39 +02001543 def delete_image(self, image_id):
sousaedu80135b92021-02-17 15:05:18 +01001544 """Deletes a tenant image from openstack VIM. Returns the old id"""
tiernoae4a8d12016-07-08 12:30:39 +02001545 try:
1546 self._reload_connection()
tierno1beea862018-07-11 15:47:37 +02001547 self.glance.images.delete(image_id)
sousaedu80135b92021-02-17 15:05:18 +01001548
tiernoae4a8d12016-07-08 12:30:39 +02001549 return image_id
sousaedu80135b92021-02-17 15:05:18 +01001550 except (
1551 nvExceptions.NotFound,
1552 ksExceptions.ClientException,
1553 nvExceptions.ClientException,
1554 gl1Exceptions.CommunicationError,
1555 gl1Exceptions.HTTPNotFound,
1556 ConnectionError,
1557 ) as e: # TODO remove
tiernoae4a8d12016-07-08 12:30:39 +02001558 self._format_exception(e)
1559
1560 def get_image_id_from_path(self, path):
tierno1ec592d2020-06-16 15:29:47 +00001561 """Get the image id from image path in the VIM database. Returns the image_id"""
tiernoae4a8d12016-07-08 12:30:39 +02001562 try:
1563 self._reload_connection()
tierno1beea862018-07-11 15:47:37 +02001564 images = self.glance.images.list()
sousaedu80135b92021-02-17 15:05:18 +01001565
tiernoae4a8d12016-07-08 12:30:39 +02001566 for image in images:
tierno1ec592d2020-06-16 15:29:47 +00001567 if image.metadata.get("location") == path:
tiernoae4a8d12016-07-08 12:30:39 +02001568 return image.id
sousaedu80135b92021-02-17 15:05:18 +01001569
1570 raise vimconn.VimConnNotFoundException(
1571 "image with location '{}' not found".format(path)
1572 )
1573 except (
1574 ksExceptions.ClientException,
1575 nvExceptions.ClientException,
1576 gl1Exceptions.CommunicationError,
1577 ConnectionError,
1578 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001579 self._format_exception(e)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001580
garciadeblasb69fa9f2016-09-28 12:04:10 +02001581 def get_image_list(self, filter_dict={}):
tierno1ec592d2020-06-16 15:29:47 +00001582 """Obtain tenant images from VIM
garciadeblasb69fa9f2016-09-28 12:04:10 +02001583 Filter_dict can be:
1584 id: image id
1585 name: image name
1586 checksum: image checksum
1587 Returns the image list of dictionaries:
1588 [{<the fields at Filter_dict plus some VIM specific>}, ...]
1589 List can be empty
tierno1ec592d2020-06-16 15:29:47 +00001590 """
garciadeblasb69fa9f2016-09-28 12:04:10 +02001591 self.logger.debug("Getting image list from VIM filter: '%s'", str(filter_dict))
sousaedu80135b92021-02-17 15:05:18 +01001592
garciadeblasb69fa9f2016-09-28 12:04:10 +02001593 try:
1594 self._reload_connection()
tierno1ec592d2020-06-16 15:29:47 +00001595 # filter_dict_os = filter_dict.copy()
1596 # First we filter by the available filter fields: name, id. The others are removed.
tierno1beea862018-07-11 15:47:37 +02001597 image_list = self.glance.images.list()
garciadeblasb69fa9f2016-09-28 12:04:10 +02001598 filtered_list = []
sousaedu80135b92021-02-17 15:05:18 +01001599
garciadeblasb69fa9f2016-09-28 12:04:10 +02001600 for image in image_list:
tierno3cb8dc32017-10-24 18:13:19 +02001601 try:
tierno1beea862018-07-11 15:47:37 +02001602 if filter_dict.get("name") and image["name"] != filter_dict["name"]:
1603 continue
sousaedu80135b92021-02-17 15:05:18 +01001604
tierno1beea862018-07-11 15:47:37 +02001605 if filter_dict.get("id") and image["id"] != filter_dict["id"]:
1606 continue
sousaedu80135b92021-02-17 15:05:18 +01001607
1608 if (
1609 filter_dict.get("checksum")
1610 and image["checksum"] != filter_dict["checksum"]
1611 ):
tierno1beea862018-07-11 15:47:37 +02001612 continue
1613
1614 filtered_list.append(image.copy())
tierno3cb8dc32017-10-24 18:13:19 +02001615 except gl1Exceptions.HTTPNotFound:
1616 pass
sousaedu80135b92021-02-17 15:05:18 +01001617
garciadeblasb69fa9f2016-09-28 12:04:10 +02001618 return filtered_list
sousaedu80135b92021-02-17 15:05:18 +01001619 except (
1620 ksExceptions.ClientException,
1621 nvExceptions.ClientException,
1622 gl1Exceptions.CommunicationError,
1623 ConnectionError,
1624 ) as e:
garciadeblasb69fa9f2016-09-28 12:04:10 +02001625 self._format_exception(e)
1626
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001627 def __wait_for_vm(self, vm_id, status):
1628 """wait until vm is in the desired status and return True.
1629 If the VM gets in ERROR status, return false.
1630 If the timeout is reached generate an exception"""
1631 elapsed_time = 0
1632 while elapsed_time < server_timeout:
1633 vm_status = self.nova.servers.get(vm_id).status
sousaedu80135b92021-02-17 15:05:18 +01001634
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001635 if vm_status == status:
1636 return True
sousaedu80135b92021-02-17 15:05:18 +01001637
1638 if vm_status == "ERROR":
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001639 return False
sousaedu80135b92021-02-17 15:05:18 +01001640
tierno1df468d2018-07-06 14:25:16 +02001641 time.sleep(5)
1642 elapsed_time += 5
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001643
1644 # if we exceeded the timeout rollback
1645 if elapsed_time >= server_timeout:
sousaedu80135b92021-02-17 15:05:18 +01001646 raise vimconn.VimConnException(
1647 "Timeout waiting for instance " + vm_id + " to get " + status,
1648 http_code=vimconn.HTTP_Request_Timeout,
1649 )
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001650
mirabal29356312017-07-27 12:21:22 +02001651 def _get_openstack_availablity_zones(self):
1652 """
1653 Get from openstack availability zones available
1654 :return:
1655 """
1656 try:
1657 openstack_availability_zone = self.nova.availability_zones.list()
sousaedu80135b92021-02-17 15:05:18 +01001658 openstack_availability_zone = [
1659 str(zone.zoneName)
1660 for zone in openstack_availability_zone
1661 if zone.zoneName != "internal"
1662 ]
1663
mirabal29356312017-07-27 12:21:22 +02001664 return openstack_availability_zone
tierno1ec592d2020-06-16 15:29:47 +00001665 except Exception:
mirabal29356312017-07-27 12:21:22 +02001666 return None
1667
1668 def _set_availablity_zones(self):
1669 """
1670 Set vim availablity zone
1671 :return:
1672 """
sousaedu80135b92021-02-17 15:05:18 +01001673 if "availability_zone" in self.config:
1674 vim_availability_zones = self.config.get("availability_zone")
mirabal29356312017-07-27 12:21:22 +02001675
mirabal29356312017-07-27 12:21:22 +02001676 if isinstance(vim_availability_zones, str):
1677 self.availability_zone = [vim_availability_zones]
1678 elif isinstance(vim_availability_zones, list):
1679 self.availability_zone = vim_availability_zones
1680 else:
1681 self.availability_zone = self._get_openstack_availablity_zones()
1682
sousaedu80135b92021-02-17 15:05:18 +01001683 def _get_vm_availability_zone(
1684 self, availability_zone_index, availability_zone_list
1685 ):
mirabal29356312017-07-27 12:21:22 +02001686 """
tierno5a3273c2017-08-29 11:43:46 +02001687 Return thge availability zone to be used by the created VM.
1688 :return: The VIM availability zone to be used or None
mirabal29356312017-07-27 12:21:22 +02001689 """
tierno5a3273c2017-08-29 11:43:46 +02001690 if availability_zone_index is None:
sousaedu80135b92021-02-17 15:05:18 +01001691 if not self.config.get("availability_zone"):
tierno5a3273c2017-08-29 11:43:46 +02001692 return None
sousaedu80135b92021-02-17 15:05:18 +01001693 elif isinstance(self.config.get("availability_zone"), str):
1694 return self.config["availability_zone"]
tierno5a3273c2017-08-29 11:43:46 +02001695 else:
1696 # TODO consider using a different parameter at config for default AV and AV list match
sousaedu80135b92021-02-17 15:05:18 +01001697 return self.config["availability_zone"][0]
mirabal29356312017-07-27 12:21:22 +02001698
tierno5a3273c2017-08-29 11:43:46 +02001699 vim_availability_zones = self.availability_zone
1700 # check if VIM offer enough availability zones describe in the VNFD
sousaedu80135b92021-02-17 15:05:18 +01001701 if vim_availability_zones and len(availability_zone_list) <= len(
1702 vim_availability_zones
1703 ):
tierno5a3273c2017-08-29 11:43:46 +02001704 # check if all the names of NFV AV match VIM AV names
1705 match_by_index = False
1706 for av in availability_zone_list:
1707 if av not in vim_availability_zones:
1708 match_by_index = True
1709 break
sousaedu80135b92021-02-17 15:05:18 +01001710
tierno5a3273c2017-08-29 11:43:46 +02001711 if match_by_index:
1712 return vim_availability_zones[availability_zone_index]
1713 else:
1714 return availability_zone_list[availability_zone_index]
mirabal29356312017-07-27 12:21:22 +02001715 else:
sousaedu80135b92021-02-17 15:05:18 +01001716 raise vimconn.VimConnConflictException(
1717 "No enough availability zones at VIM for this deployment"
1718 )
mirabal29356312017-07-27 12:21:22 +02001719
sousaedu80135b92021-02-17 15:05:18 +01001720 def new_vminstance(
1721 self,
1722 name,
1723 description,
1724 start,
1725 image_id,
1726 flavor_id,
Alexis Romerob70f4ed2022-03-11 18:00:49 +01001727 affinity_group_list,
sousaedu80135b92021-02-17 15:05:18 +01001728 net_list,
1729 cloud_config=None,
1730 disk_list=None,
1731 availability_zone_index=None,
1732 availability_zone_list=None,
1733 ):
tierno98e909c2017-10-14 13:27:03 +02001734 """Adds a VM instance to VIM
tierno7edb6752016-03-21 17:37:52 +01001735 Params:
1736 start: indicates if VM must start or boot in pause mode. Ignored
Alexis Romerob70f4ed2022-03-11 18:00:49 +01001737 image_id,flavor_id: image and flavor uuid
1738 affinity_group_list: list of affinity groups, each one is a dictionary.
1739 Ignore if empty.
tierno7edb6752016-03-21 17:37:52 +01001740 net_list: list of interfaces, each one is a dictionary with:
1741 name:
1742 net_id: network uuid to connect
1743 vpci: virtual vcpi to assign, ignored because openstack lack #TODO
1744 model: interface model, ignored #TODO
1745 mac_address: used for SR-IOV ifaces #TODO for other types
1746 use: 'data', 'bridge', 'mgmt'
tierno66eba6e2017-11-10 17:09:18 +01001747 type: 'virtual', 'PCI-PASSTHROUGH'('PF'), 'SR-IOV'('VF'), 'VFnotShared'
tierno7edb6752016-03-21 17:37:52 +01001748 vim_id: filled/added by this function
ahmadsaf853d452016-12-22 11:33:47 +05001749 floating_ip: True/False (or it can be None)
tierno70eeb182020-10-19 16:38:00 +00001750 port_security: True/False
tierno41a69812018-02-16 14:34:33 +01001751 'cloud_config': (optional) dictionary with:
tierno1d213f42020-04-24 14:02:51 +00001752 'key-pairs': (optional) list of strings with the public key to be inserted to the default user
1753 'users': (optional) list of users to be inserted, each item is a dict with:
1754 'name': (mandatory) user name,
1755 'key-pairs': (optional) list of strings with the public key to be inserted to the user
1756 'user-data': (optional) string is a text script to be passed directly to cloud-init
1757 'config-files': (optional). List of files to be transferred. Each item is a dict with:
1758 'dest': (mandatory) string with the destination absolute path
1759 'encoding': (optional, by default text). Can be one of:
1760 'b64', 'base64', 'gz', 'gz+b64', 'gz+base64', 'gzip+b64', 'gzip+base64'
1761 'content' (mandatory): string with the content of the file
1762 'permissions': (optional) string with file permissions, typically octal notation '0644'
1763 'owner': (optional) file owner, string with the format 'owner:group'
1764 'boot-data-drive': boolean to indicate if user-data must be passed using a boot drive (hard disk)
mirabal29356312017-07-27 12:21:22 +02001765 'disk_list': (optional) list with additional disks to the VM. Each item is a dict with:
1766 'image_id': (optional). VIM id of an existing image. If not provided an empty disk must be mounted
1767 'size': (mandatory) string with the size of the disk in GB
tierno1df468d2018-07-06 14:25:16 +02001768 'vim_id' (optional) should use this existing volume id
tierno5a3273c2017-08-29 11:43:46 +02001769 availability_zone_index: Index of availability_zone_list to use for this this VM. None if not AV required
1770 availability_zone_list: list of availability zones given by user in the VNFD descriptor. Ignore if
1771 availability_zone_index is None
tierno7edb6752016-03-21 17:37:52 +01001772 #TODO ip, security groups
tierno98e909c2017-10-14 13:27:03 +02001773 Returns a tuple with the instance identifier and created_items or raises an exception on error
1774 created_items can be None or a dictionary where this method can include key-values that will be passed to
1775 the method delete_vminstance and action_vminstance. Can be used to store created ports, volumes, etc.
1776 Format is vimconnector dependent, but do not use nested dictionaries and a value of None should be the same
1777 as not present.
1778 """
sousaedu80135b92021-02-17 15:05:18 +01001779 self.logger.debug(
1780 "new_vminstance input: image='%s' flavor='%s' nics='%s'",
1781 image_id,
1782 flavor_id,
1783 str(net_list),
1784 )
1785
tierno7edb6752016-03-21 17:37:52 +01001786 try:
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001787 server = None
tierno98e909c2017-10-14 13:27:03 +02001788 created_items = {}
tiernob0b9dab2017-10-14 14:25:20 +02001789 # metadata = {}
tierno98e909c2017-10-14 13:27:03 +02001790 net_list_vim = []
tierno1ec592d2020-06-16 15:29:47 +00001791 external_network = []
1792 # ^list of external networks to be connected to instance, later on used to create floating_ip
sousaedu80135b92021-02-17 15:05:18 +01001793 no_secured_ports = [] # List of port-is with port-security disabled
tierno7edb6752016-03-21 17:37:52 +01001794 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +01001795 # metadata_vpci = {} # For a specific neutron plugin
tiernob84cbdc2017-07-07 14:30:30 +02001796 block_device_mapping = None
tiernoa05b65a2019-02-01 12:30:27 +00001797
tierno7edb6752016-03-21 17:37:52 +01001798 for net in net_list:
sousaedu80135b92021-02-17 15:05:18 +01001799 if not net.get("net_id"): # skip non connected iface
tierno7edb6752016-03-21 17:37:52 +01001800 continue
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001801
tiernoa05b65a2019-02-01 12:30:27 +00001802 port_dict = {
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001803 "network_id": net["net_id"],
1804 "name": net.get("name"),
sousaedu80135b92021-02-17 15:05:18 +01001805 "admin_state_up": True,
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001806 }
sousaedu80135b92021-02-17 15:05:18 +01001807
1808 if (
1809 self.config.get("security_groups")
1810 and net.get("port_security") is not False
1811 and not self.config.get("no_port_security_extension")
1812 ):
tiernoa05b65a2019-02-01 12:30:27 +00001813 if not self.security_groups_id:
1814 self._get_ids_from_name()
sousaedu80135b92021-02-17 15:05:18 +01001815
tiernoa05b65a2019-02-01 12:30:27 +00001816 port_dict["security_groups"] = self.security_groups_id
1817
tierno1ec592d2020-06-16 15:29:47 +00001818 if net["type"] == "virtual":
tiernob0b9dab2017-10-14 14:25:20 +02001819 pass
1820 # if "vpci" in net:
1821 # metadata_vpci[ net["net_id"] ] = [[ net["vpci"], "" ]]
tierno66eba6e2017-11-10 17:09:18 +01001822 elif net["type"] == "VF" or net["type"] == "SR-IOV": # for VF
tiernob0b9dab2017-10-14 14:25:20 +02001823 # if "vpci" in net:
1824 # if "VF" not in metadata_vpci:
1825 # metadata_vpci["VF"]=[]
1826 # metadata_vpci["VF"].append([ net["vpci"], "" ])
tierno1ec592d2020-06-16 15:29:47 +00001827 port_dict["binding:vnic_type"] = "direct"
sousaedu80135b92021-02-17 15:05:18 +01001828
tiernob0b9dab2017-10-14 14:25:20 +02001829 # VIO specific Changes
kate721d79b2017-06-24 04:21:38 -07001830 if self.vim_type == "VIO":
tiernob0b9dab2017-10-14 14:25:20 +02001831 # Need to create port with port_security_enabled = False and no-security-groups
tierno1ec592d2020-06-16 15:29:47 +00001832 port_dict["port_security_enabled"] = False
1833 port_dict["provider_security_groups"] = []
1834 port_dict["security_groups"] = []
sousaedu80135b92021-02-17 15:05:18 +01001835 else: # For PT PCI-PASSTHROUGH
tiernob0b9dab2017-10-14 14:25:20 +02001836 # if "vpci" in net:
1837 # if "PF" not in metadata_vpci:
1838 # metadata_vpci["PF"]=[]
1839 # metadata_vpci["PF"].append([ net["vpci"], "" ])
tierno1ec592d2020-06-16 15:29:47 +00001840 port_dict["binding:vnic_type"] = "direct-physical"
sousaedu80135b92021-02-17 15:05:18 +01001841
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001842 if not port_dict["name"]:
tierno1ec592d2020-06-16 15:29:47 +00001843 port_dict["name"] = name
sousaedu80135b92021-02-17 15:05:18 +01001844
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001845 if net.get("mac_address"):
tierno1ec592d2020-06-16 15:29:47 +00001846 port_dict["mac_address"] = net["mac_address"]
sousaedu80135b92021-02-17 15:05:18 +01001847
tierno41a69812018-02-16 14:34:33 +01001848 if net.get("ip_address"):
sousaedu80135b92021-02-17 15:05:18 +01001849 port_dict["fixed_ips"] = [{"ip_address": net["ip_address"]}]
1850 # TODO add "subnet_id": <subnet_id>
1851
tierno1ec592d2020-06-16 15:29:47 +00001852 new_port = self.neutron.create_port({"port": port_dict})
tierno00e3df72017-11-29 17:20:13 +01001853 created_items["port:" + str(new_port["port"]["id"])] = True
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001854 net["mac_adress"] = new_port["port"]["mac_address"]
1855 net["vim_id"] = new_port["port"]["id"]
tiernob84cbdc2017-07-07 14:30:30 +02001856 # if try to use a network without subnetwork, it will return a emtpy list
1857 fixed_ips = new_port["port"].get("fixed_ips")
sousaedu80135b92021-02-17 15:05:18 +01001858
tiernob84cbdc2017-07-07 14:30:30 +02001859 if fixed_ips:
1860 net["ip"] = fixed_ips[0].get("ip_address")
1861 else:
1862 net["ip"] = None
montesmoreno994a29d2017-08-22 11:23:06 +02001863
1864 port = {"port-id": new_port["port"]["id"]}
1865 if float(self.nova.api_version.get_string()) >= 2.32:
1866 port["tag"] = new_port["port"]["name"]
sousaedu80135b92021-02-17 15:05:18 +01001867
montesmoreno994a29d2017-08-22 11:23:06 +02001868 net_list_vim.append(port)
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02001869
sousaedu80135b92021-02-17 15:05:18 +01001870 if net.get("floating_ip", False):
1871 net["exit_on_floating_ip_error"] = True
ahmadsaf853d452016-12-22 11:33:47 +05001872 external_network.append(net)
sousaedu80135b92021-02-17 15:05:18 +01001873 elif net["use"] == "mgmt" and self.config.get("use_floating_ip"):
1874 net["exit_on_floating_ip_error"] = False
tiernof8383b82017-01-18 15:49:48 +01001875 external_network.append(net)
sousaedu80135b92021-02-17 15:05:18 +01001876 net["floating_ip"] = self.config.get("use_floating_ip")
tiernof8383b82017-01-18 15:49:48 +01001877
tierno1ec592d2020-06-16 15:29:47 +00001878 # If port security is disabled when the port has not yet been attached to the VM, then all vm traffic
1879 # is dropped.
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001880 # As a workaround we wait until the VM is active and then disable the port-security
sousaedu80135b92021-02-17 15:05:18 +01001881 if net.get("port_security") is False and not self.config.get(
1882 "no_port_security_extension"
1883 ):
1884 no_secured_ports.append(
1885 (
1886 new_port["port"]["id"],
1887 net.get("port_security_disable_strategy"),
1888 )
1889 )
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001890
tiernob0b9dab2017-10-14 14:25:20 +02001891 # if metadata_vpci:
1892 # metadata = {"pci_assignement": json.dumps(metadata_vpci)}
1893 # if len(metadata["pci_assignement"]) >255:
1894 # #limit the metadata size
1895 # #metadata["pci_assignement"] = metadata["pci_assignement"][0:255]
1896 # self.logger.warn("Metadata deleted since it exceeds the expected length (255) ")
1897 # metadata = {}
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001898
sousaedu80135b92021-02-17 15:05:18 +01001899 self.logger.debug(
1900 "name '%s' image_id '%s'flavor_id '%s' net_list_vim '%s' description '%s'",
1901 name,
1902 image_id,
1903 flavor_id,
1904 str(net_list_vim),
1905 description,
1906 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001907
tierno98e909c2017-10-14 13:27:03 +02001908 # cloud config
tierno0a1437e2017-10-02 00:17:43 +02001909 config_drive, userdata = self._create_user_data(cloud_config)
montesmoreno0c8def02016-12-22 12:16:23 +00001910
Alexis Romero247cc432022-05-12 13:23:25 +02001911 # get availability Zone
1912 vm_av_zone = self._get_vm_availability_zone(
1913 availability_zone_index, availability_zone_list
1914 )
1915
tierno98e909c2017-10-14 13:27:03 +02001916 # Create additional volumes in case these are present in disk_list
palaciosj8f2060b2022-02-24 12:05:59 +00001917 existing_vim_volumes = []
sousaedu80135b92021-02-17 15:05:18 +01001918 base_disk_index = ord("b")
aticig179e0022022-03-29 13:15:45 +03001919 boot_volume_id = None
tierno1df468d2018-07-06 14:25:16 +02001920 if disk_list:
tiernob84cbdc2017-07-07 14:30:30 +02001921 block_device_mapping = {}
montesmoreno0c8def02016-12-22 12:16:23 +00001922 for disk in disk_list:
aticigcf14bb12022-05-19 13:03:17 +03001923 if "image_id" in disk:
1924 # persistent root volume
1925 base_disk_index = ord("a")
1926 image_id = ""
aticig343c5202022-06-25 23:31:19 +03001927 # use existing persistent root volume
aticigcf14bb12022-05-19 13:03:17 +03001928 if disk.get("vim_volume_id"):
aticigcf14bb12022-05-19 13:03:17 +03001929 block_device_mapping["vd" + chr(base_disk_index)] = disk[
1930 "vim_volume_id"
1931 ]
1932 existing_vim_volumes.append({"id": disk["vim_volume_id"]})
aticig343c5202022-06-25 23:31:19 +03001933 # use existing persistent root volume
1934 elif disk.get("vim_id"):
1935 block_device_mapping["vd" + chr(base_disk_index)] = disk[
1936 "vim_id"
1937 ]
1938 existing_vim_volumes.append({"id": disk["vim_id"]})
aticigcf14bb12022-05-19 13:03:17 +03001939 else:
1940 # create persistent root volume
sousaedu80135b92021-02-17 15:05:18 +01001941 volume = self.cinder.volumes.create(
1942 size=disk["size"],
aticigcf14bb12022-05-19 13:03:17 +03001943 name=name + "vd" + chr(base_disk_index),
sousaedu80135b92021-02-17 15:05:18 +01001944 imageRef=disk["image_id"],
Alexis Romero247cc432022-05-12 13:23:25 +02001945 # Make sure volume is in the same AZ as the VM to be attached to
1946 availability_zone=vm_av_zone,
sousaedu80135b92021-02-17 15:05:18 +01001947 )
aticig179e0022022-03-29 13:15:45 +03001948 boot_volume_id = volume.id
aticigcf14bb12022-05-19 13:03:17 +03001949 created_items["volume:" + str(volume.id)] = True
1950 block_device_mapping[
1951 "vd" + chr(base_disk_index)
1952 ] = volume.id
1953 else:
1954 # non-root persistent volume
aticig343c5202022-06-25 23:31:19 +03001955 key_id = (
1956 "vim_volume_id"
1957 if "vim_volume_id" in disk.keys()
1958 else "vim_id"
1959 )
1960 if disk.get(key_id):
aticigcf14bb12022-05-19 13:03:17 +03001961 # use existing persistent volume
1962 block_device_mapping["vd" + chr(base_disk_index)] = disk[
aticig343c5202022-06-25 23:31:19 +03001963 key_id
aticigcf14bb12022-05-19 13:03:17 +03001964 ]
aticig343c5202022-06-25 23:31:19 +03001965 existing_vim_volumes.append({"id": disk[key_id]})
tierno1df468d2018-07-06 14:25:16 +02001966 else:
aticigcf14bb12022-05-19 13:03:17 +03001967 # create persistent volume
sousaedu80135b92021-02-17 15:05:18 +01001968 volume = self.cinder.volumes.create(
1969 size=disk["size"],
aticigcf14bb12022-05-19 13:03:17 +03001970 name=name + "vd" + chr(base_disk_index),
Alexis Romero247cc432022-05-12 13:23:25 +02001971 # Make sure volume is in the same AZ as the VM to be attached to
1972 availability_zone=vm_av_zone,
sousaedu80135b92021-02-17 15:05:18 +01001973 )
aticigcf14bb12022-05-19 13:03:17 +03001974 created_items["volume:" + str(volume.id)] = True
1975 block_device_mapping[
1976 "vd" + chr(base_disk_index)
1977 ] = volume.id
sousaedu80135b92021-02-17 15:05:18 +01001978
montesmoreno0c8def02016-12-22 12:16:23 +00001979 base_disk_index += 1
1980
tierno1df468d2018-07-06 14:25:16 +02001981 # Wait until created volumes are with status available
montesmoreno0c8def02016-12-22 12:16:23 +00001982 elapsed_time = 0
tierno1df468d2018-07-06 14:25:16 +02001983 while elapsed_time < volume_timeout:
1984 for created_item in created_items:
1985 v, _, volume_id = created_item.partition(":")
sousaedu80135b92021-02-17 15:05:18 +01001986 if v == "volume":
1987 if self.cinder.volumes.get(volume_id).status != "available":
tierno1df468d2018-07-06 14:25:16 +02001988 break
1989 else: # all ready: break from while
1990 break
sousaedu80135b92021-02-17 15:05:18 +01001991
tierno1df468d2018-07-06 14:25:16 +02001992 time.sleep(5)
1993 elapsed_time += 5
sousaedu80135b92021-02-17 15:05:18 +01001994
palaciosj8f2060b2022-02-24 12:05:59 +00001995 # Wait until existing volumes in vim are with status available
1996 while elapsed_time < volume_timeout:
1997 for volume in existing_vim_volumes:
1998 if self.cinder.volumes.get(volume["id"]).status != "available":
1999 break
2000 else: # all ready: break from while
2001 break
2002
2003 time.sleep(5)
2004 elapsed_time += 5
2005
tiernob0b9dab2017-10-14 14:25:20 +02002006 # If we exceeded the timeout rollback
montesmoreno0c8def02016-12-22 12:16:23 +00002007 if elapsed_time >= volume_timeout:
sousaedu80135b92021-02-17 15:05:18 +01002008 raise vimconn.VimConnException(
2009 "Timeout creating volumes for instance " + name,
2010 http_code=vimconn.HTTP_Request_Timeout,
2011 )
aticig179e0022022-03-29 13:15:45 +03002012 if boot_volume_id:
2013 self.cinder.volumes.set_bootable(boot_volume_id, True)
montesmoreno0c8def02016-12-22 12:16:23 +00002014
Alexis Romerob70f4ed2022-03-11 18:00:49 +01002015 # Manage affinity groups/server groups
2016 server_group_id = None
2017 scheduller_hints = {}
2018
2019 if affinity_group_list:
2020 # Only first id on the list will be used. Openstack restriction
2021 server_group_id = affinity_group_list[0]["affinity_group_id"]
2022 scheduller_hints["group"] = server_group_id
2023
sousaedu80135b92021-02-17 15:05:18 +01002024 self.logger.debug(
2025 "nova.servers.create({}, {}, {}, nics={}, security_groups={}, "
2026 "availability_zone={}, key_name={}, userdata={}, config_drive={}, "
Alexis Romerob70f4ed2022-03-11 18:00:49 +01002027 "block_device_mapping={}, server_group={})".format(
sousaedu80135b92021-02-17 15:05:18 +01002028 name,
2029 image_id,
2030 flavor_id,
2031 net_list_vim,
2032 self.config.get("security_groups"),
2033 vm_av_zone,
2034 self.config.get("keypair"),
2035 userdata,
2036 config_drive,
2037 block_device_mapping,
Alexis Romerob70f4ed2022-03-11 18:00:49 +01002038 server_group_id,
sousaedu80135b92021-02-17 15:05:18 +01002039 )
2040 )
2041 server = self.nova.servers.create(
aticigcf14bb12022-05-19 13:03:17 +03002042 name=name,
2043 image=image_id,
2044 flavor=flavor_id,
sousaedu80135b92021-02-17 15:05:18 +01002045 nics=net_list_vim,
2046 security_groups=self.config.get("security_groups"),
2047 # TODO remove security_groups in future versions. Already at neutron port
2048 availability_zone=vm_av_zone,
2049 key_name=self.config.get("keypair"),
2050 userdata=userdata,
2051 config_drive=config_drive,
2052 block_device_mapping=block_device_mapping,
Alexis Romerob70f4ed2022-03-11 18:00:49 +01002053 scheduler_hints=scheduller_hints,
sousaedu80135b92021-02-17 15:05:18 +01002054 ) # , description=description)
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02002055
tierno326fd5e2018-02-22 11:58:59 +01002056 vm_start_time = time.time()
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02002057 # Previously mentioned workaround to wait until the VM is active and then disable the port-security
2058 if no_secured_ports:
sousaedu80135b92021-02-17 15:05:18 +01002059 self.__wait_for_vm(server.id, "ACTIVE")
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02002060
bravof7a1f5252020-10-20 10:27:42 -03002061 for port in no_secured_ports:
2062 port_update = {
sousaedu80135b92021-02-17 15:05:18 +01002063 "port": {"port_security_enabled": False, "security_groups": None}
bravof7a1f5252020-10-20 10:27:42 -03002064 }
2065
2066 if port[1] == "allow-address-pairs":
2067 port_update = {
sousaedu80135b92021-02-17 15:05:18 +01002068 "port": {"allowed_address_pairs": [{"ip_address": "0.0.0.0/0"}]}
bravof7a1f5252020-10-20 10:27:42 -03002069 }
2070
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02002071 try:
bravof7a1f5252020-10-20 10:27:42 -03002072 self.neutron.update_port(port[0], port_update)
tierno1ec592d2020-06-16 15:29:47 +00002073 except Exception:
bravof7a1f5252020-10-20 10:27:42 -03002074 raise vimconn.VimConnException(
sousaedu80135b92021-02-17 15:05:18 +01002075 "It was not possible to disable port security for port {}".format(
2076 port[0]
2077 )
bravof7a1f5252020-10-20 10:27:42 -03002078 )
2079
tierno98e909c2017-10-14 13:27:03 +02002080 # print "DONE :-)", server
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02002081
tierno4d1ce222018-04-06 10:41:06 +02002082 # pool_id = None
ahmadsaf853d452016-12-22 11:33:47 +05002083 for floating_network in external_network:
tiernof8383b82017-01-18 15:49:48 +01002084 try:
tiernof8383b82017-01-18 15:49:48 +01002085 assigned = False
tiernocb66c7e2020-07-22 10:42:58 +00002086 floating_ip_retries = 3
2087 # In case of RO in HA there can be conflicts, two RO trying to assign same floating IP, so retry
2088 # several times
tierno98e909c2017-10-14 13:27:03 +02002089 while not assigned:
sousaedu80135b92021-02-17 15:05:18 +01002090 floating_ips = self.neutron.list_floatingips().get(
2091 "floatingips", ()
2092 )
2093 random.shuffle(floating_ips) # randomize
tiernocb66c7e2020-07-22 10:42:58 +00002094 for fip in floating_ips:
sousaedu80135b92021-02-17 15:05:18 +01002095 if (
2096 fip.get("port_id")
2097 or fip.get("tenant_id") != server.tenant_id
2098 ):
tierno326fd5e2018-02-22 11:58:59 +01002099 continue
sousaedu80135b92021-02-17 15:05:18 +01002100
2101 if isinstance(floating_network["floating_ip"], str):
2102 if (
2103 fip.get("floating_network_id")
2104 != floating_network["floating_ip"]
2105 ):
tierno326fd5e2018-02-22 11:58:59 +01002106 continue
sousaedu80135b92021-02-17 15:05:18 +01002107
tiernocb66c7e2020-07-22 10:42:58 +00002108 free_floating_ip = fip["id"]
2109 break
tiernof8383b82017-01-18 15:49:48 +01002110 else:
sousaedu80135b92021-02-17 15:05:18 +01002111 if (
2112 isinstance(floating_network["floating_ip"], str)
2113 and floating_network["floating_ip"].lower() != "true"
2114 ):
2115 pool_id = floating_network["floating_ip"]
tierno326fd5e2018-02-22 11:58:59 +01002116 else:
tierno4d1ce222018-04-06 10:41:06 +02002117 # Find the external network
tierno326fd5e2018-02-22 11:58:59 +01002118 external_nets = list()
sousaedu80135b92021-02-17 15:05:18 +01002119
2120 for net in self.neutron.list_networks()["networks"]:
2121 if net["router:external"]:
tierno1ec592d2020-06-16 15:29:47 +00002122 external_nets.append(net)
tiernof8383b82017-01-18 15:49:48 +01002123
tierno326fd5e2018-02-22 11:58:59 +01002124 if len(external_nets) == 0:
tierno1ec592d2020-06-16 15:29:47 +00002125 raise vimconn.VimConnException(
sousaedu80135b92021-02-17 15:05:18 +01002126 "Cannot create floating_ip automatically since "
2127 "no external network is present",
2128 http_code=vimconn.HTTP_Conflict,
2129 )
2130
tierno326fd5e2018-02-22 11:58:59 +01002131 if len(external_nets) > 1:
tierno1ec592d2020-06-16 15:29:47 +00002132 raise vimconn.VimConnException(
sousaedu80135b92021-02-17 15:05:18 +01002133 "Cannot create floating_ip automatically since "
2134 "multiple external networks are present",
2135 http_code=vimconn.HTTP_Conflict,
2136 )
tiernof8383b82017-01-18 15:49:48 +01002137
sousaedu80135b92021-02-17 15:05:18 +01002138 pool_id = external_nets[0].get("id")
2139
2140 param = {
2141 "floatingip": {
2142 "floating_network_id": pool_id,
2143 "tenant_id": server.tenant_id,
2144 }
2145 }
2146
ahmadsaf853d452016-12-22 11:33:47 +05002147 try:
tierno4d1ce222018-04-06 10:41:06 +02002148 # self.logger.debug("Creating floating IP")
tiernof8383b82017-01-18 15:49:48 +01002149 new_floating_ip = self.neutron.create_floatingip(param)
sousaedu80135b92021-02-17 15:05:18 +01002150 free_floating_ip = new_floating_ip["floatingip"]["id"]
2151 created_items[
2152 "floating_ip:" + str(free_floating_ip)
2153 ] = True
ahmadsaf853d452016-12-22 11:33:47 +05002154 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01002155 raise vimconn.VimConnException(
2156 type(e).__name__
2157 + ": Cannot create new floating_ip "
2158 + str(e),
2159 http_code=vimconn.HTTP_Conflict,
2160 )
tierno326fd5e2018-02-22 11:58:59 +01002161
tiernocb66c7e2020-07-22 10:42:58 +00002162 try:
2163 # for race condition ensure not already assigned
2164 fip = self.neutron.show_floatingip(free_floating_ip)
sousaedu80135b92021-02-17 15:05:18 +01002165
2166 if fip["floatingip"]["port_id"]:
tiernocb66c7e2020-07-22 10:42:58 +00002167 continue
sousaedu80135b92021-02-17 15:05:18 +01002168
tiernocb66c7e2020-07-22 10:42:58 +00002169 # the vim_id key contains the neutron.port_id
sousaedu80135b92021-02-17 15:05:18 +01002170 self.neutron.update_floatingip(
2171 free_floating_ip,
2172 {"floatingip": {"port_id": floating_network["vim_id"]}},
2173 )
tiernocb66c7e2020-07-22 10:42:58 +00002174 # for race condition ensure not re-assigned to other VM after 5 seconds
2175 time.sleep(5)
2176 fip = self.neutron.show_floatingip(free_floating_ip)
sousaedu80135b92021-02-17 15:05:18 +01002177
2178 if (
2179 fip["floatingip"]["port_id"]
2180 != floating_network["vim_id"]
2181 ):
2182 self.logger.error(
2183 "floating_ip {} re-assigned to other port".format(
2184 free_floating_ip
2185 )
2186 )
tiernocb66c7e2020-07-22 10:42:58 +00002187 continue
sousaedu80135b92021-02-17 15:05:18 +01002188
2189 self.logger.debug(
2190 "Assigned floating_ip {} to VM {}".format(
2191 free_floating_ip, server.id
2192 )
2193 )
tiernocb66c7e2020-07-22 10:42:58 +00002194 assigned = True
2195 except Exception as e:
2196 # openstack need some time after VM creation to assign an IP. So retry if fails
2197 vm_status = self.nova.servers.get(server.id).status
sousaedu80135b92021-02-17 15:05:18 +01002198
2199 if vm_status not in ("ACTIVE", "ERROR"):
tiernocb66c7e2020-07-22 10:42:58 +00002200 if time.time() - vm_start_time < server_timeout:
2201 time.sleep(5)
2202 continue
2203 elif floating_ip_retries > 0:
2204 floating_ip_retries -= 1
2205 continue
sousaedu80135b92021-02-17 15:05:18 +01002206
tiernocb66c7e2020-07-22 10:42:58 +00002207 raise vimconn.VimConnException(
sousaedu80135b92021-02-17 15:05:18 +01002208 "Cannot create floating_ip: {} {}".format(
2209 type(e).__name__, e
2210 ),
2211 http_code=vimconn.HTTP_Conflict,
2212 )
tierno326fd5e2018-02-22 11:58:59 +01002213
tiernof8383b82017-01-18 15:49:48 +01002214 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01002215 if not floating_network["exit_on_floating_ip_error"]:
tiernocb66c7e2020-07-22 10:42:58 +00002216 self.logger.error("Cannot create floating_ip. %s", str(e))
tiernof8383b82017-01-18 15:49:48 +01002217 continue
sousaedu80135b92021-02-17 15:05:18 +01002218
tiernof8383b82017-01-18 15:49:48 +01002219 raise
montesmoreno2a1fc4e2017-01-09 16:46:04 +00002220
tierno98e909c2017-10-14 13:27:03 +02002221 return server.id, created_items
tierno1ec592d2020-06-16 15:29:47 +00002222 # except nvExceptions.NotFound as e:
2223 # error_value=-vimconn.HTTP_Not_Found
2224 # error_text= "vm instance %s not found" % vm_id
2225 # except TypeError as e:
2226 # raise vimconn.VimConnException(type(e).__name__ + ": "+ str(e), http_code=vimconn.HTTP_Bad_Request)
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02002227
2228 except Exception as e:
tierno98e909c2017-10-14 13:27:03 +02002229 server_id = None
2230 if server:
2231 server_id = server.id
sousaedu80135b92021-02-17 15:05:18 +01002232
tierno98e909c2017-10-14 13:27:03 +02002233 try:
2234 self.delete_vminstance(server_id, created_items)
2235 except Exception as e2:
2236 self.logger.error("new_vminstance rollback fail {}".format(e2))
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02002237
tiernoae4a8d12016-07-08 12:30:39 +02002238 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01002239
tierno1ec592d2020-06-16 15:29:47 +00002240 def get_vminstance(self, vm_id):
2241 """Returns the VM instance information from VIM"""
2242 # self.logger.debug("Getting VM from VIM")
tierno7edb6752016-03-21 17:37:52 +01002243 try:
2244 self._reload_connection()
2245 server = self.nova.servers.find(id=vm_id)
tierno1ec592d2020-06-16 15:29:47 +00002246 # TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
sousaedu80135b92021-02-17 15:05:18 +01002247
tiernoae4a8d12016-07-08 12:30:39 +02002248 return server.to_dict()
sousaedu80135b92021-02-17 15:05:18 +01002249 except (
2250 ksExceptions.ClientException,
2251 nvExceptions.ClientException,
2252 nvExceptions.NotFound,
2253 ConnectionError,
2254 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02002255 self._format_exception(e)
2256
tierno1ec592d2020-06-16 15:29:47 +00002257 def get_vminstance_console(self, vm_id, console_type="vnc"):
2258 """
tierno7edb6752016-03-21 17:37:52 +01002259 Get a console for the virtual machine
2260 Params:
2261 vm_id: uuid of the VM
2262 console_type, can be:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002263 "novnc" (by default), "xvpvnc" for VNC types,
tierno7edb6752016-03-21 17:37:52 +01002264 "rdp-html5" for RDP types, "spice-html5" for SPICE types
tiernoae4a8d12016-07-08 12:30:39 +02002265 Returns dict with the console parameters:
2266 protocol: ssh, ftp, http, https, ...
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002267 server: usually ip address
2268 port: the http, ssh, ... port
2269 suffix: extra text, e.g. the http path and query string
tierno1ec592d2020-06-16 15:29:47 +00002270 """
tiernoae4a8d12016-07-08 12:30:39 +02002271 self.logger.debug("Getting VM CONSOLE from VIM")
sousaedu80135b92021-02-17 15:05:18 +01002272
tierno7edb6752016-03-21 17:37:52 +01002273 try:
2274 self._reload_connection()
2275 server = self.nova.servers.find(id=vm_id)
sousaedu80135b92021-02-17 15:05:18 +01002276
tierno1ec592d2020-06-16 15:29:47 +00002277 if console_type is None or console_type == "novnc":
tierno7edb6752016-03-21 17:37:52 +01002278 console_dict = server.get_vnc_console("novnc")
2279 elif console_type == "xvpvnc":
2280 console_dict = server.get_vnc_console(console_type)
2281 elif console_type == "rdp-html5":
2282 console_dict = server.get_rdp_console(console_type)
2283 elif console_type == "spice-html5":
2284 console_dict = server.get_spice_console(console_type)
2285 else:
sousaedu80135b92021-02-17 15:05:18 +01002286 raise vimconn.VimConnException(
2287 "console type '{}' not allowed".format(console_type),
2288 http_code=vimconn.HTTP_Bad_Request,
2289 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002290
tierno7edb6752016-03-21 17:37:52 +01002291 console_dict1 = console_dict.get("console")
sousaedu80135b92021-02-17 15:05:18 +01002292
tierno7edb6752016-03-21 17:37:52 +01002293 if console_dict1:
2294 console_url = console_dict1.get("url")
sousaedu80135b92021-02-17 15:05:18 +01002295
tierno7edb6752016-03-21 17:37:52 +01002296 if console_url:
tierno1ec592d2020-06-16 15:29:47 +00002297 # parse console_url
tierno7edb6752016-03-21 17:37:52 +01002298 protocol_index = console_url.find("//")
sousaedu80135b92021-02-17 15:05:18 +01002299 suffix_index = (
2300 console_url[protocol_index + 2 :].find("/") + protocol_index + 2
2301 )
2302 port_index = (
2303 console_url[protocol_index + 2 : suffix_index].find(":")
2304 + protocol_index
2305 + 2
2306 )
2307
tierno1ec592d2020-06-16 15:29:47 +00002308 if protocol_index < 0 or port_index < 0 or suffix_index < 0:
sousaedu80135b92021-02-17 15:05:18 +01002309 return (
2310 -vimconn.HTTP_Internal_Server_Error,
2311 "Unexpected response from VIM",
2312 )
2313
2314 console_dict = {
2315 "protocol": console_url[0:protocol_index],
2316 "server": console_url[protocol_index + 2 : port_index],
2317 "port": console_url[port_index:suffix_index],
2318 "suffix": console_url[suffix_index + 1 :],
2319 }
tierno7edb6752016-03-21 17:37:52 +01002320 protocol_index += 2
sousaedu80135b92021-02-17 15:05:18 +01002321
tiernoae4a8d12016-07-08 12:30:39 +02002322 return console_dict
tierno72774862020-05-04 11:44:15 +00002323 raise vimconn.VimConnUnexpectedResponse("Unexpected response from VIM")
sousaedu80135b92021-02-17 15:05:18 +01002324 except (
2325 nvExceptions.NotFound,
2326 ksExceptions.ClientException,
2327 nvExceptions.ClientException,
2328 nvExceptions.BadRequest,
2329 ConnectionError,
2330 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02002331 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01002332
palaciosj8f2060b2022-02-24 12:05:59 +00002333 def delete_vminstance(self, vm_id, created_items=None, volumes_to_hold=None):
sousaedu80135b92021-02-17 15:05:18 +01002334 """Removes a VM instance from VIM. Returns the old identifier"""
tierno1ec592d2020-06-16 15:29:47 +00002335 # print "osconnector: Getting VM from VIM"
2336 if created_items is None:
tierno98e909c2017-10-14 13:27:03 +02002337 created_items = {}
sousaedu80135b92021-02-17 15:05:18 +01002338
tierno7edb6752016-03-21 17:37:52 +01002339 try:
2340 self._reload_connection()
tierno98e909c2017-10-14 13:27:03 +02002341 # delete VM ports attached to this networks before the virtual machine
2342 for k, v in created_items.items():
2343 if not v: # skip already deleted
2344 continue
sousaedu80135b92021-02-17 15:05:18 +01002345
tierno7edb6752016-03-21 17:37:52 +01002346 try:
tiernoad6bdd42018-01-10 10:43:46 +01002347 k_item, _, k_id = k.partition(":")
2348 if k_item == "port":
aticig36cad662022-06-22 22:03:37 +03002349 port_dict = self.neutron.list_ports()
aticigfe575722022-06-07 15:00:35 +03002350 existing_ports = [
2351 port["id"] for port in port_dict["ports"] if port_dict
2352 ]
2353 if k_id in existing_ports:
2354 self.neutron.delete_port(k_id)
tierno7edb6752016-03-21 17:37:52 +01002355 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01002356 self.logger.error(
2357 "Error deleting port: {}: {}".format(type(e).__name__, e)
2358 )
montesmoreno0c8def02016-12-22 12:16:23 +00002359
tierno98e909c2017-10-14 13:27:03 +02002360 # #commented because detaching the volumes makes the servers.delete not work properly ?!?
2361 # #dettach volumes attached
2362 # server = self.nova.servers.get(vm_id)
sousaedu80135b92021-02-17 15:05:18 +01002363 # volumes_attached_dict = server._info["os-extended-volumes:volumes_attached"] #volume["id"]
tierno98e909c2017-10-14 13:27:03 +02002364 # #for volume in volumes_attached_dict:
sousaedu80135b92021-02-17 15:05:18 +01002365 # # self.cinder.volumes.detach(volume["id"])
montesmoreno0c8def02016-12-22 12:16:23 +00002366
tierno98e909c2017-10-14 13:27:03 +02002367 if vm_id:
2368 self.nova.servers.delete(vm_id)
montesmoreno0c8def02016-12-22 12:16:23 +00002369
tierno98e909c2017-10-14 13:27:03 +02002370 # delete volumes. Although having detached, they should have in active status before deleting
2371 # we ensure in this loop
montesmoreno0c8def02016-12-22 12:16:23 +00002372 keep_waiting = True
2373 elapsed_time = 0
sousaedu80135b92021-02-17 15:05:18 +01002374
montesmoreno0c8def02016-12-22 12:16:23 +00002375 while keep_waiting and elapsed_time < volume_timeout:
2376 keep_waiting = False
sousaedu80135b92021-02-17 15:05:18 +01002377
tierno98e909c2017-10-14 13:27:03 +02002378 for k, v in created_items.items():
2379 if not v: # skip already deleted
2380 continue
sousaedu80135b92021-02-17 15:05:18 +01002381
tierno98e909c2017-10-14 13:27:03 +02002382 try:
tiernoad6bdd42018-01-10 10:43:46 +01002383 k_item, _, k_id = k.partition(":")
2384 if k_item == "volume":
sousaedu80135b92021-02-17 15:05:18 +01002385 if self.cinder.volumes.get(k_id).status != "available":
tierno98e909c2017-10-14 13:27:03 +02002386 keep_waiting = True
2387 else:
palaciosj8f2060b2022-02-24 12:05:59 +00002388 if k_id not in volumes_to_hold:
2389 self.cinder.volumes.delete(k_id)
2390 created_items[k] = None
tiernocb66c7e2020-07-22 10:42:58 +00002391 elif k_item == "floating_ip": # floating ip
2392 self.neutron.delete_floatingip(k_id)
2393 created_items[k] = None
2394
tierno98e909c2017-10-14 13:27:03 +02002395 except Exception as e:
tiernocb66c7e2020-07-22 10:42:58 +00002396 self.logger.error("Error deleting {}: {}".format(k, e))
sousaedu80135b92021-02-17 15:05:18 +01002397
montesmoreno0c8def02016-12-22 12:16:23 +00002398 if keep_waiting:
2399 time.sleep(1)
2400 elapsed_time += 1
sousaedu80135b92021-02-17 15:05:18 +01002401
tierno98e909c2017-10-14 13:27:03 +02002402 return None
sousaedu80135b92021-02-17 15:05:18 +01002403 except (
2404 nvExceptions.NotFound,
2405 ksExceptions.ClientException,
2406 nvExceptions.ClientException,
2407 ConnectionError,
2408 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02002409 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01002410
tiernoae4a8d12016-07-08 12:30:39 +02002411 def refresh_vms_status(self, vm_list):
tierno1ec592d2020-06-16 15:29:47 +00002412 """Get the status of the virtual machines and their interfaces/ports
sousaedu80135b92021-02-17 15:05:18 +01002413 Params: the list of VM identifiers
2414 Returns a dictionary with:
2415 vm_id: #VIM id of this Virtual Machine
2416 status: #Mandatory. Text with one of:
2417 # DELETED (not found at vim)
2418 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
2419 # OTHER (Vim reported other status not understood)
2420 # ERROR (VIM indicates an ERROR status)
2421 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
2422 # CREATING (on building process), ERROR
2423 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
2424 #
2425 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
2426 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
2427 interfaces:
2428 - vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
2429 mac_address: #Text format XX:XX:XX:XX:XX:XX
2430 vim_net_id: #network id where this interface is connected
2431 vim_interface_id: #interface/port VIM id
2432 ip_address: #null, or text with IPv4, IPv6 address
2433 compute_node: #identification of compute node where PF,VF interface is allocated
2434 pci: #PCI address of the NIC that hosts the PF,VF
2435 vlan: #physical VLAN used for VF
tierno1ec592d2020-06-16 15:29:47 +00002436 """
2437 vm_dict = {}
sousaedu80135b92021-02-17 15:05:18 +01002438 self.logger.debug(
2439 "refresh_vms status: Getting tenant VM instance information from VIM"
2440 )
2441
tiernoae4a8d12016-07-08 12:30:39 +02002442 for vm_id in vm_list:
tierno1ec592d2020-06-16 15:29:47 +00002443 vm = {}
sousaedu80135b92021-02-17 15:05:18 +01002444
tiernoae4a8d12016-07-08 12:30:39 +02002445 try:
2446 vm_vim = self.get_vminstance(vm_id)
sousaedu80135b92021-02-17 15:05:18 +01002447
2448 if vm_vim["status"] in vmStatus2manoFormat:
2449 vm["status"] = vmStatus2manoFormat[vm_vim["status"]]
tierno7edb6752016-03-21 17:37:52 +01002450 else:
sousaedu80135b92021-02-17 15:05:18 +01002451 vm["status"] = "OTHER"
2452 vm["error_msg"] = "VIM status reported " + vm_vim["status"]
2453
tierno70eeb182020-10-19 16:38:00 +00002454 vm_vim.pop("OS-EXT-SRV-ATTR:user_data", None)
2455 vm_vim.pop("user_data", None)
sousaedu80135b92021-02-17 15:05:18 +01002456 vm["vim_info"] = self.serialize(vm_vim)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002457
tiernoae4a8d12016-07-08 12:30:39 +02002458 vm["interfaces"] = []
sousaedu80135b92021-02-17 15:05:18 +01002459 if vm_vim.get("fault"):
2460 vm["error_msg"] = str(vm_vim["fault"])
2461
tierno1ec592d2020-06-16 15:29:47 +00002462 # get interfaces
tierno7edb6752016-03-21 17:37:52 +01002463 try:
tiernoae4a8d12016-07-08 12:30:39 +02002464 self._reload_connection()
tiernob42fd9b2018-06-20 10:44:32 +02002465 port_dict = self.neutron.list_ports(device_id=vm_id)
sousaedu80135b92021-02-17 15:05:18 +01002466
tiernoae4a8d12016-07-08 12:30:39 +02002467 for port in port_dict["ports"]:
tierno1ec592d2020-06-16 15:29:47 +00002468 interface = {}
sousaedu80135b92021-02-17 15:05:18 +01002469 interface["vim_info"] = self.serialize(port)
tiernoae4a8d12016-07-08 12:30:39 +02002470 interface["mac_address"] = port.get("mac_address")
2471 interface["vim_net_id"] = port["network_id"]
2472 interface["vim_interface_id"] = port["id"]
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002473 # check if OS-EXT-SRV-ATTR:host is there,
Mike Marchetti5b9da422017-05-02 15:35:47 -04002474 # in case of non-admin credentials, it will be missing
sousaedu80135b92021-02-17 15:05:18 +01002475
2476 if vm_vim.get("OS-EXT-SRV-ATTR:host"):
2477 interface["compute_node"] = vm_vim["OS-EXT-SRV-ATTR:host"]
2478
tierno867ffe92017-03-27 12:50:34 +02002479 interface["pci"] = None
Mike Marchetti5b9da422017-05-02 15:35:47 -04002480
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002481 # check if binding:profile is there,
Mike Marchetti5b9da422017-05-02 15:35:47 -04002482 # in case of non-admin credentials, it will be missing
sousaedu80135b92021-02-17 15:05:18 +01002483 if port.get("binding:profile"):
2484 if port["binding:profile"].get("pci_slot"):
tierno1ec592d2020-06-16 15:29:47 +00002485 # TODO: At the moment sr-iov pci addresses are converted to PF pci addresses by setting
2486 # the slot to 0x00
Mike Marchetti5b9da422017-05-02 15:35:47 -04002487 # TODO: This is just a workaround valid for niantinc. Find a better way to do so
2488 # CHANGE DDDD:BB:SS.F to DDDD:BB:00.(F%2) assuming there are 2 ports per nic
sousaedu80135b92021-02-17 15:05:18 +01002489 pci = port["binding:profile"]["pci_slot"]
Mike Marchetti5b9da422017-05-02 15:35:47 -04002490 # interface["pci"] = pci[:-4] + "00." + str(int(pci[-1]) % 2)
2491 interface["pci"] = pci
sousaedu80135b92021-02-17 15:05:18 +01002492
tierno867ffe92017-03-27 12:50:34 +02002493 interface["vlan"] = None
sousaedu80135b92021-02-17 15:05:18 +01002494
2495 if port.get("binding:vif_details"):
2496 interface["vlan"] = port["binding:vif_details"].get("vlan")
2497
tierno1dfe9932020-06-18 08:50:10 +00002498 # Get vlan from network in case not present in port for those old openstacks and cases where
2499 # it is needed vlan at PT
2500 if not interface["vlan"]:
2501 # if network is of type vlan and port is of type direct (sr-iov) then set vlan id
2502 network = self.neutron.show_network(port["network_id"])
sousaedu80135b92021-02-17 15:05:18 +01002503
2504 if (
2505 network["network"].get("provider:network_type")
2506 == "vlan"
2507 ):
tierno1dfe9932020-06-18 08:50:10 +00002508 # and port.get("binding:vnic_type") in ("direct", "direct-physical"):
sousaedu80135b92021-02-17 15:05:18 +01002509 interface["vlan"] = network["network"].get(
2510 "provider:segmentation_id"
2511 )
2512
tierno1ec592d2020-06-16 15:29:47 +00002513 ips = []
2514 # look for floating ip address
tiernob42fd9b2018-06-20 10:44:32 +02002515 try:
sousaedu80135b92021-02-17 15:05:18 +01002516 floating_ip_dict = self.neutron.list_floatingips(
2517 port_id=port["id"]
2518 )
2519
tiernob42fd9b2018-06-20 10:44:32 +02002520 if floating_ip_dict.get("floatingips"):
sousaedu80135b92021-02-17 15:05:18 +01002521 ips.append(
2522 floating_ip_dict["floatingips"][0].get(
2523 "floating_ip_address"
2524 )
2525 )
tiernob42fd9b2018-06-20 10:44:32 +02002526 except Exception:
2527 pass
tierno7edb6752016-03-21 17:37:52 +01002528
tiernoae4a8d12016-07-08 12:30:39 +02002529 for subnet in port["fixed_ips"]:
2530 ips.append(subnet["ip_address"])
sousaedu80135b92021-02-17 15:05:18 +01002531
tiernoae4a8d12016-07-08 12:30:39 +02002532 interface["ip_address"] = ";".join(ips)
2533 vm["interfaces"].append(interface)
2534 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01002535 self.logger.error(
2536 "Error getting vm interface information {}: {}".format(
2537 type(e).__name__, e
2538 ),
2539 exc_info=True,
2540 )
tierno72774862020-05-04 11:44:15 +00002541 except vimconn.VimConnNotFoundException as e:
tiernoae4a8d12016-07-08 12:30:39 +02002542 self.logger.error("Exception getting vm status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01002543 vm["status"] = "DELETED"
2544 vm["error_msg"] = str(e)
tierno72774862020-05-04 11:44:15 +00002545 except vimconn.VimConnException as e:
tiernoae4a8d12016-07-08 12:30:39 +02002546 self.logger.error("Exception getting vm status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01002547 vm["status"] = "VIM_ERROR"
2548 vm["error_msg"] = str(e)
2549
tiernoae4a8d12016-07-08 12:30:39 +02002550 vm_dict[vm_id] = vm
sousaedu80135b92021-02-17 15:05:18 +01002551
tiernoae4a8d12016-07-08 12:30:39 +02002552 return vm_dict
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002553
tierno98e909c2017-10-14 13:27:03 +02002554 def action_vminstance(self, vm_id, action_dict, created_items={}):
tierno1ec592d2020-06-16 15:29:47 +00002555 """Send and action over a VM instance from VIM
Gulsum Aticibb0b7b92023-02-13 21:45:08 +03002556 Returns None or the console dict if the action was successfully sent to the VIM
2557 """
tiernoae4a8d12016-07-08 12:30:39 +02002558 self.logger.debug("Action over VM '%s': %s", vm_id, str(action_dict))
sousaedu80135b92021-02-17 15:05:18 +01002559
tierno7edb6752016-03-21 17:37:52 +01002560 try:
2561 self._reload_connection()
2562 server = self.nova.servers.find(id=vm_id)
sousaedu80135b92021-02-17 15:05:18 +01002563
tierno7edb6752016-03-21 17:37:52 +01002564 if "start" in action_dict:
tierno1ec592d2020-06-16 15:29:47 +00002565 if action_dict["start"] == "rebuild":
tierno7edb6752016-03-21 17:37:52 +01002566 server.rebuild()
2567 else:
tierno1ec592d2020-06-16 15:29:47 +00002568 if server.status == "PAUSED":
tierno7edb6752016-03-21 17:37:52 +01002569 server.unpause()
tierno1ec592d2020-06-16 15:29:47 +00002570 elif server.status == "SUSPENDED":
tierno7edb6752016-03-21 17:37:52 +01002571 server.resume()
tierno1ec592d2020-06-16 15:29:47 +00002572 elif server.status == "SHUTOFF":
tierno7edb6752016-03-21 17:37:52 +01002573 server.start()
k4.rahul78f474e2022-05-02 15:47:57 +00002574 else:
2575 self.logger.debug(
2576 "ERROR : Instance is not in SHUTOFF/PAUSE/SUSPEND state"
2577 )
2578 raise vimconn.VimConnException(
2579 "Cannot 'start' instance while it is in active state",
2580 http_code=vimconn.HTTP_Bad_Request,
2581 )
2582
tierno7edb6752016-03-21 17:37:52 +01002583 elif "pause" in action_dict:
2584 server.pause()
2585 elif "resume" in action_dict:
2586 server.resume()
2587 elif "shutoff" in action_dict or "shutdown" in action_dict:
k4.rahul78f474e2022-05-02 15:47:57 +00002588 self.logger.debug("server status %s", server.status)
2589 if server.status == "ACTIVE":
2590 server.stop()
2591 else:
2592 self.logger.debug("ERROR: VM is not in Active state")
2593 raise vimconn.VimConnException(
2594 "VM is not in active state, stop operation is not allowed",
2595 http_code=vimconn.HTTP_Bad_Request,
2596 )
tierno7edb6752016-03-21 17:37:52 +01002597 elif "forceOff" in action_dict:
tierno1ec592d2020-06-16 15:29:47 +00002598 server.stop() # TODO
tierno7edb6752016-03-21 17:37:52 +01002599 elif "terminate" in action_dict:
2600 server.delete()
2601 elif "createImage" in action_dict:
2602 server.create_image()
tierno1ec592d2020-06-16 15:29:47 +00002603 # "path":path_schema,
2604 # "description":description_schema,
2605 # "name":name_schema,
2606 # "metadata":metadata_schema,
2607 # "imageRef": id_schema,
2608 # "disk": {"oneOf":[{"type": "null"}, {"type":"string"}] },
tierno7edb6752016-03-21 17:37:52 +01002609 elif "rebuild" in action_dict:
sousaedu80135b92021-02-17 15:05:18 +01002610 server.rebuild(server.image["id"])
tierno7edb6752016-03-21 17:37:52 +01002611 elif "reboot" in action_dict:
sousaedu80135b92021-02-17 15:05:18 +01002612 server.reboot() # reboot_type="SOFT"
tierno7edb6752016-03-21 17:37:52 +01002613 elif "console" in action_dict:
2614 console_type = action_dict["console"]
sousaedu80135b92021-02-17 15:05:18 +01002615
tierno1ec592d2020-06-16 15:29:47 +00002616 if console_type is None or console_type == "novnc":
tierno7edb6752016-03-21 17:37:52 +01002617 console_dict = server.get_vnc_console("novnc")
2618 elif console_type == "xvpvnc":
2619 console_dict = server.get_vnc_console(console_type)
2620 elif console_type == "rdp-html5":
2621 console_dict = server.get_rdp_console(console_type)
2622 elif console_type == "spice-html5":
2623 console_dict = server.get_spice_console(console_type)
2624 else:
sousaedu80135b92021-02-17 15:05:18 +01002625 raise vimconn.VimConnException(
2626 "console type '{}' not allowed".format(console_type),
2627 http_code=vimconn.HTTP_Bad_Request,
2628 )
2629
tierno7edb6752016-03-21 17:37:52 +01002630 try:
2631 console_url = console_dict["console"]["url"]
tierno1ec592d2020-06-16 15:29:47 +00002632 # parse console_url
tierno7edb6752016-03-21 17:37:52 +01002633 protocol_index = console_url.find("//")
sousaedu80135b92021-02-17 15:05:18 +01002634 suffix_index = (
2635 console_url[protocol_index + 2 :].find("/") + protocol_index + 2
2636 )
2637 port_index = (
2638 console_url[protocol_index + 2 : suffix_index].find(":")
2639 + protocol_index
2640 + 2
2641 )
2642
tierno1ec592d2020-06-16 15:29:47 +00002643 if protocol_index < 0 or port_index < 0 or suffix_index < 0:
sousaedu80135b92021-02-17 15:05:18 +01002644 raise vimconn.VimConnException(
2645 "Unexpected response from VIM " + str(console_dict)
2646 )
2647
2648 console_dict2 = {
2649 "protocol": console_url[0:protocol_index],
2650 "server": console_url[protocol_index + 2 : port_index],
2651 "port": int(console_url[port_index + 1 : suffix_index]),
2652 "suffix": console_url[suffix_index + 1 :],
2653 }
2654
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002655 return console_dict2
tierno1ec592d2020-06-16 15:29:47 +00002656 except Exception:
sousaedu80135b92021-02-17 15:05:18 +01002657 raise vimconn.VimConnException(
2658 "Unexpected response from VIM " + str(console_dict)
2659 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002660
tierno98e909c2017-10-14 13:27:03 +02002661 return None
sousaedu80135b92021-02-17 15:05:18 +01002662 except (
2663 ksExceptions.ClientException,
2664 nvExceptions.ClientException,
2665 nvExceptions.NotFound,
2666 ConnectionError,
2667 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02002668 self._format_exception(e)
tierno1ec592d2020-06-16 15:29:47 +00002669 # TODO insert exception vimconn.HTTP_Unauthorized
tiernoae4a8d12016-07-08 12:30:39 +02002670
tierno1ec592d2020-06-16 15:29:47 +00002671 # ###### VIO Specific Changes #########
garciadeblasebd66722019-01-31 16:01:31 +00002672 def _generate_vlanID(self):
kate721d79b2017-06-24 04:21:38 -07002673 """
sousaedu80135b92021-02-17 15:05:18 +01002674 Method to get unused vlanID
kate721d79b2017-06-24 04:21:38 -07002675 Args:
2676 None
2677 Returns:
2678 vlanID
2679 """
tierno1ec592d2020-06-16 15:29:47 +00002680 # Get used VLAN IDs
kate721d79b2017-06-24 04:21:38 -07002681 usedVlanIDs = []
2682 networks = self.get_network_list()
sousaedu80135b92021-02-17 15:05:18 +01002683
kate721d79b2017-06-24 04:21:38 -07002684 for net in networks:
sousaedu80135b92021-02-17 15:05:18 +01002685 if net.get("provider:segmentation_id"):
2686 usedVlanIDs.append(net.get("provider:segmentation_id"))
2687
kate721d79b2017-06-24 04:21:38 -07002688 used_vlanIDs = set(usedVlanIDs)
2689
tierno1ec592d2020-06-16 15:29:47 +00002690 # find unused VLAN ID
sousaedu80135b92021-02-17 15:05:18 +01002691 for vlanID_range in self.config.get("dataplane_net_vlan_range"):
kate721d79b2017-06-24 04:21:38 -07002692 try:
sousaedu80135b92021-02-17 15:05:18 +01002693 start_vlanid, end_vlanid = map(
2694 int, vlanID_range.replace(" ", "").split("-")
2695 )
2696
tierno7d782ef2019-10-04 12:56:31 +00002697 for vlanID in range(start_vlanid, end_vlanid + 1):
kate721d79b2017-06-24 04:21:38 -07002698 if vlanID not in used_vlanIDs:
2699 return vlanID
2700 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01002701 raise vimconn.VimConnException(
2702 "Exception {} occurred while generating VLAN ID.".format(exp)
2703 )
kate721d79b2017-06-24 04:21:38 -07002704 else:
tierno1ec592d2020-06-16 15:29:47 +00002705 raise vimconn.VimConnConflictException(
2706 "Unable to create the SRIOV VLAN network. All given Vlan IDs {} are in use.".format(
sousaedu80135b92021-02-17 15:05:18 +01002707 self.config.get("dataplane_net_vlan_range")
2708 )
2709 )
kate721d79b2017-06-24 04:21:38 -07002710
garciadeblasebd66722019-01-31 16:01:31 +00002711 def _generate_multisegment_vlanID(self):
2712 """
sousaedu80135b92021-02-17 15:05:18 +01002713 Method to get unused vlanID
2714 Args:
2715 None
2716 Returns:
2717 vlanID
garciadeblasebd66722019-01-31 16:01:31 +00002718 """
tierno6869ae72020-01-09 17:37:34 +00002719 # Get used VLAN IDs
garciadeblasebd66722019-01-31 16:01:31 +00002720 usedVlanIDs = []
2721 networks = self.get_network_list()
2722 for net in networks:
sousaedu80135b92021-02-17 15:05:18 +01002723 if net.get("provider:network_type") == "vlan" and net.get(
2724 "provider:segmentation_id"
2725 ):
2726 usedVlanIDs.append(net.get("provider:segmentation_id"))
2727 elif net.get("segments"):
2728 for segment in net.get("segments"):
2729 if segment.get("provider:network_type") == "vlan" and segment.get(
2730 "provider:segmentation_id"
2731 ):
2732 usedVlanIDs.append(segment.get("provider:segmentation_id"))
2733
garciadeblasebd66722019-01-31 16:01:31 +00002734 used_vlanIDs = set(usedVlanIDs)
2735
tierno6869ae72020-01-09 17:37:34 +00002736 # find unused VLAN ID
sousaedu80135b92021-02-17 15:05:18 +01002737 for vlanID_range in self.config.get("multisegment_vlan_range"):
garciadeblasebd66722019-01-31 16:01:31 +00002738 try:
sousaedu80135b92021-02-17 15:05:18 +01002739 start_vlanid, end_vlanid = map(
2740 int, vlanID_range.replace(" ", "").split("-")
2741 )
2742
tierno7d782ef2019-10-04 12:56:31 +00002743 for vlanID in range(start_vlanid, end_vlanid + 1):
garciadeblasebd66722019-01-31 16:01:31 +00002744 if vlanID not in used_vlanIDs:
2745 return vlanID
2746 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01002747 raise vimconn.VimConnException(
2748 "Exception {} occurred while generating VLAN ID.".format(exp)
2749 )
garciadeblasebd66722019-01-31 16:01:31 +00002750 else:
tierno1ec592d2020-06-16 15:29:47 +00002751 raise vimconn.VimConnConflictException(
2752 "Unable to create the VLAN segment. All VLAN IDs {} are in use.".format(
sousaedu80135b92021-02-17 15:05:18 +01002753 self.config.get("multisegment_vlan_range")
2754 )
2755 )
garciadeblasebd66722019-01-31 16:01:31 +00002756
2757 def _validate_vlan_ranges(self, input_vlan_range, text_vlan_range):
kate721d79b2017-06-24 04:21:38 -07002758 """
2759 Method to validate user given vlanID ranges
2760 Args: None
2761 Returns: None
2762 """
garciadeblasebd66722019-01-31 16:01:31 +00002763 for vlanID_range in input_vlan_range:
kate721d79b2017-06-24 04:21:38 -07002764 vlan_range = vlanID_range.replace(" ", "")
tierno1ec592d2020-06-16 15:29:47 +00002765 # validate format
sousaedu80135b92021-02-17 15:05:18 +01002766 vlanID_pattern = r"(\d)*-(\d)*$"
kate721d79b2017-06-24 04:21:38 -07002767 match_obj = re.match(vlanID_pattern, vlan_range)
2768 if not match_obj:
tierno1ec592d2020-06-16 15:29:47 +00002769 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +01002770 "Invalid VLAN range for {}: {}.You must provide "
2771 "'{}' in format [start_ID - end_ID].".format(
2772 text_vlan_range, vlanID_range, text_vlan_range
2773 )
2774 )
kate721d79b2017-06-24 04:21:38 -07002775
tierno1ec592d2020-06-16 15:29:47 +00002776 start_vlanid, end_vlanid = map(int, vlan_range.split("-"))
2777 if start_vlanid <= 0:
2778 raise vimconn.VimConnConflictException(
2779 "Invalid VLAN range for {}: {}. Start ID can not be zero. For VLAN "
sousaedu80135b92021-02-17 15:05:18 +01002780 "networks valid IDs are 1 to 4094 ".format(
2781 text_vlan_range, vlanID_range
2782 )
2783 )
2784
tierno1ec592d2020-06-16 15:29:47 +00002785 if end_vlanid > 4094:
2786 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +01002787 "Invalid VLAN range for {}: {}. End VLAN ID can not be "
2788 "greater than 4094. For VLAN networks valid IDs are 1 to 4094 ".format(
2789 text_vlan_range, vlanID_range
2790 )
2791 )
kate721d79b2017-06-24 04:21:38 -07002792
2793 if start_vlanid > end_vlanid:
tierno1ec592d2020-06-16 15:29:47 +00002794 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +01002795 "Invalid VLAN range for {}: {}. You must provide '{}'"
2796 " in format start_ID - end_ID and start_ID < end_ID ".format(
2797 text_vlan_range, vlanID_range, text_vlan_range
2798 )
2799 )
kate721d79b2017-06-24 04:21:38 -07002800
tierno1ec592d2020-06-16 15:29:47 +00002801 # NOT USED FUNCTIONS
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002802
tiernoae4a8d12016-07-08 12:30:39 +02002803 def new_external_port(self, port_data):
tierno1ec592d2020-06-16 15:29:47 +00002804 """Adds a external port to VIM
sousaedu80135b92021-02-17 15:05:18 +01002805 Returns the port identifier"""
tierno1ec592d2020-06-16 15:29:47 +00002806 # TODO openstack if needed
sousaedu80135b92021-02-17 15:05:18 +01002807 return (
2808 -vimconn.HTTP_Internal_Server_Error,
2809 "osconnector.new_external_port() not implemented",
2810 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002811
tiernoae4a8d12016-07-08 12:30:39 +02002812 def connect_port_network(self, port_id, network_id, admin=False):
tierno1ec592d2020-06-16 15:29:47 +00002813 """Connects a external port to a network
sousaedu80135b92021-02-17 15:05:18 +01002814 Returns status code of the VIM response"""
tierno1ec592d2020-06-16 15:29:47 +00002815 # TODO openstack if needed
sousaedu80135b92021-02-17 15:05:18 +01002816 return (
2817 -vimconn.HTTP_Internal_Server_Error,
2818 "osconnector.connect_port_network() not implemented",
2819 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002820
tiernoae4a8d12016-07-08 12:30:39 +02002821 def new_user(self, user_name, user_passwd, tenant_id=None):
tierno1ec592d2020-06-16 15:29:47 +00002822 """Adds a new user to openstack VIM
sousaedu80135b92021-02-17 15:05:18 +01002823 Returns the user identifier"""
tiernoae4a8d12016-07-08 12:30:39 +02002824 self.logger.debug("osconnector: Adding a new user to VIM")
sousaedu80135b92021-02-17 15:05:18 +01002825
tiernoae4a8d12016-07-08 12:30:39 +02002826 try:
2827 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +01002828 user = self.keystone.users.create(
2829 user_name, password=user_passwd, default_project=tenant_id
2830 )
tierno1ec592d2020-06-16 15:29:47 +00002831 # self.keystone.tenants.add_user(self.k_creds["username"], #role)
sousaedu80135b92021-02-17 15:05:18 +01002832
tiernoae4a8d12016-07-08 12:30:39 +02002833 return user.id
2834 except ksExceptions.ConnectionError as e:
tierno1ec592d2020-06-16 15:29:47 +00002835 error_value = -vimconn.HTTP_Bad_Request
sousaedu80135b92021-02-17 15:05:18 +01002836 error_text = (
2837 type(e).__name__
2838 + ": "
2839 + (str(e) if len(e.args) == 0 else str(e.args[0]))
2840 )
tierno1ec592d2020-06-16 15:29:47 +00002841 except ksExceptions.ClientException as e: # TODO remove
2842 error_value = -vimconn.HTTP_Bad_Request
sousaedu80135b92021-02-17 15:05:18 +01002843 error_text = (
2844 type(e).__name__
2845 + ": "
2846 + (str(e) if len(e.args) == 0 else str(e.args[0]))
2847 )
2848
tierno1ec592d2020-06-16 15:29:47 +00002849 # TODO insert exception vimconn.HTTP_Unauthorized
2850 # if reaching here is because an exception
tierno9c5c8322018-03-23 15:44:03 +01002851 self.logger.debug("new_user " + error_text)
sousaedu80135b92021-02-17 15:05:18 +01002852
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002853 return error_value, error_text
tiernoae4a8d12016-07-08 12:30:39 +02002854
2855 def delete_user(self, user_id):
tierno1ec592d2020-06-16 15:29:47 +00002856 """Delete a user from openstack VIM
sousaedu80135b92021-02-17 15:05:18 +01002857 Returns the user identifier"""
tiernoae4a8d12016-07-08 12:30:39 +02002858 if self.debug:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002859 print("osconnector: Deleting a user from VIM")
sousaedu80135b92021-02-17 15:05:18 +01002860
tiernoae4a8d12016-07-08 12:30:39 +02002861 try:
2862 self._reload_connection()
2863 self.keystone.users.delete(user_id)
sousaedu80135b92021-02-17 15:05:18 +01002864
tiernoae4a8d12016-07-08 12:30:39 +02002865 return 1, user_id
2866 except ksExceptions.ConnectionError as e:
tierno1ec592d2020-06-16 15:29:47 +00002867 error_value = -vimconn.HTTP_Bad_Request
sousaedu80135b92021-02-17 15:05:18 +01002868 error_text = (
2869 type(e).__name__
2870 + ": "
2871 + (str(e) if len(e.args) == 0 else str(e.args[0]))
2872 )
tiernoae4a8d12016-07-08 12:30:39 +02002873 except ksExceptions.NotFound as e:
tierno1ec592d2020-06-16 15:29:47 +00002874 error_value = -vimconn.HTTP_Not_Found
sousaedu80135b92021-02-17 15:05:18 +01002875 error_text = (
2876 type(e).__name__
2877 + ": "
2878 + (str(e) if len(e.args) == 0 else str(e.args[0]))
2879 )
tierno1ec592d2020-06-16 15:29:47 +00002880 except ksExceptions.ClientException as e: # TODO remove
2881 error_value = -vimconn.HTTP_Bad_Request
sousaedu80135b92021-02-17 15:05:18 +01002882 error_text = (
2883 type(e).__name__
2884 + ": "
2885 + (str(e) if len(e.args) == 0 else str(e.args[0]))
2886 )
2887
tierno1ec592d2020-06-16 15:29:47 +00002888 # TODO insert exception vimconn.HTTP_Unauthorized
2889 # if reaching here is because an exception
2890 self.logger.debug("delete_tenant " + error_text)
sousaedu80135b92021-02-17 15:05:18 +01002891
tiernoae4a8d12016-07-08 12:30:39 +02002892 return error_value, error_text
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002893
tierno7edb6752016-03-21 17:37:52 +01002894 def get_hosts_info(self):
tierno1ec592d2020-06-16 15:29:47 +00002895 """Get the information of deployed hosts
2896 Returns the hosts content"""
tierno7edb6752016-03-21 17:37:52 +01002897 if self.debug:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002898 print("osconnector: Getting Host info from VIM")
sousaedu80135b92021-02-17 15:05:18 +01002899
tierno7edb6752016-03-21 17:37:52 +01002900 try:
tierno1ec592d2020-06-16 15:29:47 +00002901 h_list = []
tierno7edb6752016-03-21 17:37:52 +01002902 self._reload_connection()
2903 hypervisors = self.nova.hypervisors.list()
sousaedu80135b92021-02-17 15:05:18 +01002904
tierno7edb6752016-03-21 17:37:52 +01002905 for hype in hypervisors:
tierno1ec592d2020-06-16 15:29:47 +00002906 h_list.append(hype.to_dict())
sousaedu80135b92021-02-17 15:05:18 +01002907
tierno1ec592d2020-06-16 15:29:47 +00002908 return 1, {"hosts": h_list}
tierno7edb6752016-03-21 17:37:52 +01002909 except nvExceptions.NotFound as e:
tierno1ec592d2020-06-16 15:29:47 +00002910 error_value = -vimconn.HTTP_Not_Found
sousaedu80135b92021-02-17 15:05:18 +01002911 error_text = str(e) if len(e.args) == 0 else str(e.args[0])
tierno7edb6752016-03-21 17:37:52 +01002912 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
tierno1ec592d2020-06-16 15:29:47 +00002913 error_value = -vimconn.HTTP_Bad_Request
sousaedu80135b92021-02-17 15:05:18 +01002914 error_text = (
2915 type(e).__name__
2916 + ": "
2917 + (str(e) if len(e.args) == 0 else str(e.args[0]))
2918 )
2919
tierno1ec592d2020-06-16 15:29:47 +00002920 # TODO insert exception vimconn.HTTP_Unauthorized
2921 # if reaching here is because an exception
tierno9c5c8322018-03-23 15:44:03 +01002922 self.logger.debug("get_hosts_info " + error_text)
sousaedu80135b92021-02-17 15:05:18 +01002923
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002924 return error_value, error_text
tierno7edb6752016-03-21 17:37:52 +01002925
2926 def get_hosts(self, vim_tenant):
tierno1ec592d2020-06-16 15:29:47 +00002927 """Get the hosts and deployed instances
2928 Returns the hosts content"""
tierno7edb6752016-03-21 17:37:52 +01002929 r, hype_dict = self.get_hosts_info()
sousaedu80135b92021-02-17 15:05:18 +01002930
tierno1ec592d2020-06-16 15:29:47 +00002931 if r < 0:
tierno7edb6752016-03-21 17:37:52 +01002932 return r, hype_dict
sousaedu80135b92021-02-17 15:05:18 +01002933
tierno7edb6752016-03-21 17:37:52 +01002934 hypervisors = hype_dict["hosts"]
sousaedu80135b92021-02-17 15:05:18 +01002935
tierno7edb6752016-03-21 17:37:52 +01002936 try:
2937 servers = self.nova.servers.list()
2938 for hype in hypervisors:
2939 for server in servers:
sousaedu80135b92021-02-17 15:05:18 +01002940 if (
2941 server.to_dict()["OS-EXT-SRV-ATTR:hypervisor_hostname"]
2942 == hype["hypervisor_hostname"]
2943 ):
2944 if "vm" in hype:
2945 hype["vm"].append(server.id)
tierno7edb6752016-03-21 17:37:52 +01002946 else:
sousaedu80135b92021-02-17 15:05:18 +01002947 hype["vm"] = [server.id]
2948
tierno7edb6752016-03-21 17:37:52 +01002949 return 1, hype_dict
2950 except nvExceptions.NotFound as e:
tierno1ec592d2020-06-16 15:29:47 +00002951 error_value = -vimconn.HTTP_Not_Found
sousaedu80135b92021-02-17 15:05:18 +01002952 error_text = str(e) if len(e.args) == 0 else str(e.args[0])
tierno7edb6752016-03-21 17:37:52 +01002953 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
tierno1ec592d2020-06-16 15:29:47 +00002954 error_value = -vimconn.HTTP_Bad_Request
sousaedu80135b92021-02-17 15:05:18 +01002955 error_text = (
2956 type(e).__name__
2957 + ": "
2958 + (str(e) if len(e.args) == 0 else str(e.args[0]))
2959 )
2960
tierno1ec592d2020-06-16 15:29:47 +00002961 # TODO insert exception vimconn.HTTP_Unauthorized
2962 # if reaching here is because an exception
tierno9c5c8322018-03-23 15:44:03 +01002963 self.logger.debug("get_hosts " + error_text)
sousaedu80135b92021-02-17 15:05:18 +01002964
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002965 return error_value, error_text
tierno7edb6752016-03-21 17:37:52 +01002966
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002967 def new_classification(self, name, ctype, definition):
sousaedu80135b92021-02-17 15:05:18 +01002968 self.logger.debug(
2969 "Adding a new (Traffic) Classification to VIM, named %s", name
2970 )
2971
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002972 try:
2973 new_class = None
2974 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +01002975
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002976 if ctype not in supportedClassificationTypes:
tierno72774862020-05-04 11:44:15 +00002977 raise vimconn.VimConnNotSupportedException(
sousaedu80135b92021-02-17 15:05:18 +01002978 "OpenStack VIM connector does not support provided "
2979 "Classification Type {}, supported ones are: {}".format(
2980 ctype, supportedClassificationTypes
2981 )
2982 )
2983
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002984 if not self._validate_classification(ctype, definition):
tierno72774862020-05-04 11:44:15 +00002985 raise vimconn.VimConnException(
sousaedu80135b92021-02-17 15:05:18 +01002986 "Incorrect Classification definition for the type specified."
2987 )
tierno7edb6752016-03-21 17:37:52 +01002988
sousaedu80135b92021-02-17 15:05:18 +01002989 classification_dict = definition
2990 classification_dict["name"] = name
Igor D.Ccaadc442017-11-06 12:48:48 +00002991 new_class = self.neutron.create_sfc_flow_classifier(
sousaedu80135b92021-02-17 15:05:18 +01002992 {"flow_classifier": classification_dict}
2993 )
2994
2995 return new_class["flow_classifier"]["id"]
2996 except (
2997 neExceptions.ConnectionFailed,
2998 ksExceptions.ClientException,
2999 neExceptions.NeutronException,
3000 ConnectionError,
3001 ) as e:
3002 self.logger.error("Creation of Classification failed.")
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003003 self._format_exception(e)
3004
3005 def get_classification(self, class_id):
3006 self.logger.debug(" Getting Classification %s from VIM", class_id)
3007 filter_dict = {"id": class_id}
3008 class_list = self.get_classification_list(filter_dict)
sousaedu80135b92021-02-17 15:05:18 +01003009
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003010 if len(class_list) == 0:
tierno72774862020-05-04 11:44:15 +00003011 raise vimconn.VimConnNotFoundException(
sousaedu80135b92021-02-17 15:05:18 +01003012 "Classification '{}' not found".format(class_id)
3013 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003014 elif len(class_list) > 1:
tierno72774862020-05-04 11:44:15 +00003015 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +01003016 "Found more than one Classification with this criteria"
3017 )
3018
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003019 classification = class_list[0]
sousaedu80135b92021-02-17 15:05:18 +01003020
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003021 return classification
3022
3023 def get_classification_list(self, filter_dict={}):
sousaedu80135b92021-02-17 15:05:18 +01003024 self.logger.debug(
3025 "Getting Classifications from VIM filter: '%s'", str(filter_dict)
3026 )
3027
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003028 try:
tierno69b590e2018-03-13 18:52:23 +01003029 filter_dict_os = filter_dict.copy()
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003030 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +01003031
tierno69b590e2018-03-13 18:52:23 +01003032 if self.api_version3 and "tenant_id" in filter_dict_os:
sousaedu80135b92021-02-17 15:05:18 +01003033 filter_dict_os["project_id"] = filter_dict_os.pop("tenant_id")
3034
Igor D.Ccaadc442017-11-06 12:48:48 +00003035 classification_dict = self.neutron.list_sfc_flow_classifiers(
sousaedu80135b92021-02-17 15:05:18 +01003036 **filter_dict_os
3037 )
tierno69b590e2018-03-13 18:52:23 +01003038 classification_list = classification_dict["flow_classifiers"]
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003039 self.__classification_os2mano(classification_list)
sousaedu80135b92021-02-17 15:05:18 +01003040
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003041 return classification_list
sousaedu80135b92021-02-17 15:05:18 +01003042 except (
3043 neExceptions.ConnectionFailed,
3044 ksExceptions.ClientException,
3045 neExceptions.NeutronException,
3046 ConnectionError,
3047 ) as e:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003048 self._format_exception(e)
3049
3050 def delete_classification(self, class_id):
3051 self.logger.debug("Deleting Classification '%s' from VIM", class_id)
sousaedu80135b92021-02-17 15:05:18 +01003052
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003053 try:
3054 self._reload_connection()
Igor D.Ccaadc442017-11-06 12:48:48 +00003055 self.neutron.delete_sfc_flow_classifier(class_id)
sousaedu80135b92021-02-17 15:05:18 +01003056
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003057 return class_id
sousaedu80135b92021-02-17 15:05:18 +01003058 except (
3059 neExceptions.ConnectionFailed,
3060 neExceptions.NeutronException,
3061 ksExceptions.ClientException,
3062 neExceptions.NeutronException,
3063 ConnectionError,
3064 ) as e:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003065 self._format_exception(e)
3066
3067 def new_sfi(self, name, ingress_ports, egress_ports, sfc_encap=True):
sousaedu80135b92021-02-17 15:05:18 +01003068 self.logger.debug(
3069 "Adding a new Service Function Instance to VIM, named '%s'", name
3070 )
3071
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003072 try:
3073 new_sfi = None
3074 self._reload_connection()
3075 correlation = None
sousaedu80135b92021-02-17 15:05:18 +01003076
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003077 if sfc_encap:
sousaedu80135b92021-02-17 15:05:18 +01003078 correlation = "nsh"
3079
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003080 if len(ingress_ports) != 1:
tierno72774862020-05-04 11:44:15 +00003081 raise vimconn.VimConnNotSupportedException(
sousaedu80135b92021-02-17 15:05:18 +01003082 "OpenStack VIM connector can only have 1 ingress port per SFI"
3083 )
3084
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003085 if len(egress_ports) != 1:
tierno72774862020-05-04 11:44:15 +00003086 raise vimconn.VimConnNotSupportedException(
sousaedu80135b92021-02-17 15:05:18 +01003087 "OpenStack VIM connector can only have 1 egress port per SFI"
3088 )
3089
3090 sfi_dict = {
3091 "name": name,
3092 "ingress": ingress_ports[0],
3093 "egress": egress_ports[0],
3094 "service_function_parameters": {"correlation": correlation},
3095 }
3096 new_sfi = self.neutron.create_sfc_port_pair({"port_pair": sfi_dict})
3097
3098 return new_sfi["port_pair"]["id"]
3099 except (
3100 neExceptions.ConnectionFailed,
3101 ksExceptions.ClientException,
3102 neExceptions.NeutronException,
3103 ConnectionError,
3104 ) as e:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003105 if new_sfi:
3106 try:
sousaedu80135b92021-02-17 15:05:18 +01003107 self.neutron.delete_sfc_port_pair(new_sfi["port_pair"]["id"])
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003108 except Exception:
3109 self.logger.error(
sousaedu80135b92021-02-17 15:05:18 +01003110 "Creation of Service Function Instance failed, with "
3111 "subsequent deletion failure as well."
3112 )
3113
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003114 self._format_exception(e)
3115
3116 def get_sfi(self, sfi_id):
sousaedu80135b92021-02-17 15:05:18 +01003117 self.logger.debug("Getting Service Function Instance %s from VIM", sfi_id)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003118 filter_dict = {"id": sfi_id}
3119 sfi_list = self.get_sfi_list(filter_dict)
sousaedu80135b92021-02-17 15:05:18 +01003120
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003121 if len(sfi_list) == 0:
sousaedu80135b92021-02-17 15:05:18 +01003122 raise vimconn.VimConnNotFoundException(
3123 "Service Function Instance '{}' not found".format(sfi_id)
3124 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003125 elif len(sfi_list) > 1:
tierno72774862020-05-04 11:44:15 +00003126 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +01003127 "Found more than one Service Function Instance with this criteria"
3128 )
3129
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003130 sfi = sfi_list[0]
sousaedu80135b92021-02-17 15:05:18 +01003131
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003132 return sfi
3133
3134 def get_sfi_list(self, filter_dict={}):
sousaedu80135b92021-02-17 15:05:18 +01003135 self.logger.debug(
3136 "Getting Service Function Instances from VIM filter: '%s'", str(filter_dict)
3137 )
3138
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003139 try:
3140 self._reload_connection()
tierno69b590e2018-03-13 18:52:23 +01003141 filter_dict_os = filter_dict.copy()
sousaedu80135b92021-02-17 15:05:18 +01003142
tierno69b590e2018-03-13 18:52:23 +01003143 if self.api_version3 and "tenant_id" in filter_dict_os:
sousaedu80135b92021-02-17 15:05:18 +01003144 filter_dict_os["project_id"] = filter_dict_os.pop("tenant_id")
3145
tierno69b590e2018-03-13 18:52:23 +01003146 sfi_dict = self.neutron.list_sfc_port_pairs(**filter_dict_os)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003147 sfi_list = sfi_dict["port_pairs"]
3148 self.__sfi_os2mano(sfi_list)
sousaedu80135b92021-02-17 15:05:18 +01003149
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003150 return sfi_list
sousaedu80135b92021-02-17 15:05:18 +01003151 except (
3152 neExceptions.ConnectionFailed,
3153 ksExceptions.ClientException,
3154 neExceptions.NeutronException,
3155 ConnectionError,
3156 ) as e:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003157 self._format_exception(e)
3158
3159 def delete_sfi(self, sfi_id):
sousaedu80135b92021-02-17 15:05:18 +01003160 self.logger.debug("Deleting Service Function Instance '%s' from VIM", sfi_id)
3161
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003162 try:
3163 self._reload_connection()
Igor D.Ccaadc442017-11-06 12:48:48 +00003164 self.neutron.delete_sfc_port_pair(sfi_id)
sousaedu80135b92021-02-17 15:05:18 +01003165
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003166 return sfi_id
sousaedu80135b92021-02-17 15:05:18 +01003167 except (
3168 neExceptions.ConnectionFailed,
3169 neExceptions.NeutronException,
3170 ksExceptions.ClientException,
3171 neExceptions.NeutronException,
3172 ConnectionError,
3173 ) as e:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003174 self._format_exception(e)
3175
3176 def new_sf(self, name, sfis, sfc_encap=True):
tierno7d782ef2019-10-04 12:56:31 +00003177 self.logger.debug("Adding a new Service Function to VIM, named '%s'", name)
sousaedu80135b92021-02-17 15:05:18 +01003178
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003179 try:
3180 new_sf = None
3181 self._reload_connection()
tierno9c5c8322018-03-23 15:44:03 +01003182 # correlation = None
3183 # if sfc_encap:
sousaedu80135b92021-02-17 15:05:18 +01003184 # correlation = "nsh"
3185
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003186 for instance in sfis:
3187 sfi = self.get_sfi(instance)
sousaedu80135b92021-02-17 15:05:18 +01003188
3189 if sfi.get("sfc_encap") != sfc_encap:
tierno72774862020-05-04 11:44:15 +00003190 raise vimconn.VimConnNotSupportedException(
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003191 "OpenStack VIM connector requires all SFIs of the "
sousaedu80135b92021-02-17 15:05:18 +01003192 "same SF to share the same SFC Encapsulation"
3193 )
3194
3195 sf_dict = {"name": name, "port_pairs": sfis}
3196 new_sf = self.neutron.create_sfc_port_pair_group(
3197 {"port_pair_group": sf_dict}
3198 )
3199
3200 return new_sf["port_pair_group"]["id"]
3201 except (
3202 neExceptions.ConnectionFailed,
3203 ksExceptions.ClientException,
3204 neExceptions.NeutronException,
3205 ConnectionError,
3206 ) as e:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003207 if new_sf:
3208 try:
Igor D.Ccaadc442017-11-06 12:48:48 +00003209 self.neutron.delete_sfc_port_pair_group(
sousaedu80135b92021-02-17 15:05:18 +01003210 new_sf["port_pair_group"]["id"]
3211 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003212 except Exception:
3213 self.logger.error(
sousaedu80135b92021-02-17 15:05:18 +01003214 "Creation of Service Function failed, with "
3215 "subsequent deletion failure as well."
3216 )
3217
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003218 self._format_exception(e)
3219
3220 def get_sf(self, sf_id):
3221 self.logger.debug("Getting Service Function %s from VIM", sf_id)
3222 filter_dict = {"id": sf_id}
3223 sf_list = self.get_sf_list(filter_dict)
sousaedu80135b92021-02-17 15:05:18 +01003224
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003225 if len(sf_list) == 0:
tierno72774862020-05-04 11:44:15 +00003226 raise vimconn.VimConnNotFoundException(
sousaedu80135b92021-02-17 15:05:18 +01003227 "Service Function '{}' not found".format(sf_id)
3228 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003229 elif len(sf_list) > 1:
tierno72774862020-05-04 11:44:15 +00003230 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +01003231 "Found more than one Service Function with this criteria"
3232 )
3233
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003234 sf = sf_list[0]
sousaedu80135b92021-02-17 15:05:18 +01003235
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003236 return sf
3237
3238 def get_sf_list(self, filter_dict={}):
sousaedu80135b92021-02-17 15:05:18 +01003239 self.logger.debug(
3240 "Getting Service Function from VIM filter: '%s'", str(filter_dict)
3241 )
3242
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003243 try:
3244 self._reload_connection()
tierno69b590e2018-03-13 18:52:23 +01003245 filter_dict_os = filter_dict.copy()
sousaedu80135b92021-02-17 15:05:18 +01003246
tierno69b590e2018-03-13 18:52:23 +01003247 if self.api_version3 and "tenant_id" in filter_dict_os:
sousaedu80135b92021-02-17 15:05:18 +01003248 filter_dict_os["project_id"] = filter_dict_os.pop("tenant_id")
3249
tierno69b590e2018-03-13 18:52:23 +01003250 sf_dict = self.neutron.list_sfc_port_pair_groups(**filter_dict_os)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003251 sf_list = sf_dict["port_pair_groups"]
3252 self.__sf_os2mano(sf_list)
sousaedu80135b92021-02-17 15:05:18 +01003253
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003254 return sf_list
sousaedu80135b92021-02-17 15:05:18 +01003255 except (
3256 neExceptions.ConnectionFailed,
3257 ksExceptions.ClientException,
3258 neExceptions.NeutronException,
3259 ConnectionError,
3260 ) as e:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003261 self._format_exception(e)
3262
3263 def delete_sf(self, sf_id):
3264 self.logger.debug("Deleting Service Function '%s' from VIM", sf_id)
sousaedu80135b92021-02-17 15:05:18 +01003265
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003266 try:
3267 self._reload_connection()
Igor D.Ccaadc442017-11-06 12:48:48 +00003268 self.neutron.delete_sfc_port_pair_group(sf_id)
sousaedu80135b92021-02-17 15:05:18 +01003269
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003270 return sf_id
sousaedu80135b92021-02-17 15:05:18 +01003271 except (
3272 neExceptions.ConnectionFailed,
3273 neExceptions.NeutronException,
3274 ksExceptions.ClientException,
3275 neExceptions.NeutronException,
3276 ConnectionError,
3277 ) as e:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003278 self._format_exception(e)
3279
3280 def new_sfp(self, name, classifications, sfs, sfc_encap=True, spi=None):
tierno7d782ef2019-10-04 12:56:31 +00003281 self.logger.debug("Adding a new Service Function Path to VIM, named '%s'", name)
sousaedu80135b92021-02-17 15:05:18 +01003282
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003283 try:
3284 new_sfp = None
3285 self._reload_connection()
Igor D.Ccaadc442017-11-06 12:48:48 +00003286 # In networking-sfc the MPLS encapsulation is legacy
3287 # should be used when no full SFC Encapsulation is intended
sousaedu80135b92021-02-17 15:05:18 +01003288 correlation = "mpls"
3289
Igor D.Ccaadc442017-11-06 12:48:48 +00003290 if sfc_encap:
sousaedu80135b92021-02-17 15:05:18 +01003291 correlation = "nsh"
3292
3293 sfp_dict = {
3294 "name": name,
3295 "flow_classifiers": classifications,
3296 "port_pair_groups": sfs,
3297 "chain_parameters": {"correlation": correlation},
3298 }
3299
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003300 if spi:
sousaedu80135b92021-02-17 15:05:18 +01003301 sfp_dict["chain_id"] = spi
3302
3303 new_sfp = self.neutron.create_sfc_port_chain({"port_chain": sfp_dict})
3304
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003305 return new_sfp["port_chain"]["id"]
sousaedu80135b92021-02-17 15:05:18 +01003306 except (
3307 neExceptions.ConnectionFailed,
3308 ksExceptions.ClientException,
3309 neExceptions.NeutronException,
3310 ConnectionError,
3311 ) as e:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003312 if new_sfp:
3313 try:
sousaedu80135b92021-02-17 15:05:18 +01003314 self.neutron.delete_sfc_port_chain(new_sfp["port_chain"]["id"])
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003315 except Exception:
3316 self.logger.error(
sousaedu80135b92021-02-17 15:05:18 +01003317 "Creation of Service Function Path failed, with "
3318 "subsequent deletion failure as well."
3319 )
3320
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003321 self._format_exception(e)
3322
3323 def get_sfp(self, sfp_id):
3324 self.logger.debug(" Getting Service Function Path %s from VIM", sfp_id)
sousaedu80135b92021-02-17 15:05:18 +01003325
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003326 filter_dict = {"id": sfp_id}
3327 sfp_list = self.get_sfp_list(filter_dict)
sousaedu80135b92021-02-17 15:05:18 +01003328
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003329 if len(sfp_list) == 0:
tierno72774862020-05-04 11:44:15 +00003330 raise vimconn.VimConnNotFoundException(
sousaedu80135b92021-02-17 15:05:18 +01003331 "Service Function Path '{}' not found".format(sfp_id)
3332 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003333 elif len(sfp_list) > 1:
tierno72774862020-05-04 11:44:15 +00003334 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +01003335 "Found more than one Service Function Path with this criteria"
3336 )
3337
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003338 sfp = sfp_list[0]
sousaedu80135b92021-02-17 15:05:18 +01003339
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003340 return sfp
3341
3342 def get_sfp_list(self, filter_dict={}):
sousaedu80135b92021-02-17 15:05:18 +01003343 self.logger.debug(
3344 "Getting Service Function Paths from VIM filter: '%s'", str(filter_dict)
3345 )
3346
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003347 try:
3348 self._reload_connection()
tierno69b590e2018-03-13 18:52:23 +01003349 filter_dict_os = filter_dict.copy()
sousaedu80135b92021-02-17 15:05:18 +01003350
tierno69b590e2018-03-13 18:52:23 +01003351 if self.api_version3 and "tenant_id" in filter_dict_os:
sousaedu80135b92021-02-17 15:05:18 +01003352 filter_dict_os["project_id"] = filter_dict_os.pop("tenant_id")
3353
tierno69b590e2018-03-13 18:52:23 +01003354 sfp_dict = self.neutron.list_sfc_port_chains(**filter_dict_os)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003355 sfp_list = sfp_dict["port_chains"]
3356 self.__sfp_os2mano(sfp_list)
sousaedu80135b92021-02-17 15:05:18 +01003357
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003358 return sfp_list
sousaedu80135b92021-02-17 15:05:18 +01003359 except (
3360 neExceptions.ConnectionFailed,
3361 ksExceptions.ClientException,
3362 neExceptions.NeutronException,
3363 ConnectionError,
3364 ) as e:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003365 self._format_exception(e)
3366
3367 def delete_sfp(self, sfp_id):
tierno7d782ef2019-10-04 12:56:31 +00003368 self.logger.debug("Deleting Service Function Path '%s' from VIM", sfp_id)
sousaedu80135b92021-02-17 15:05:18 +01003369
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003370 try:
3371 self._reload_connection()
Igor D.Ccaadc442017-11-06 12:48:48 +00003372 self.neutron.delete_sfc_port_chain(sfp_id)
sousaedu80135b92021-02-17 15:05:18 +01003373
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003374 return sfp_id
sousaedu80135b92021-02-17 15:05:18 +01003375 except (
3376 neExceptions.ConnectionFailed,
3377 neExceptions.NeutronException,
3378 ksExceptions.ClientException,
3379 neExceptions.NeutronException,
3380 ConnectionError,
3381 ) as e:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003382 self._format_exception(e)
borsatti8a2dda32019-12-18 15:08:57 +00003383
borsatti8a2dda32019-12-18 15:08:57 +00003384 def refresh_sfps_status(self, sfp_list):
tierno1ec592d2020-06-16 15:29:47 +00003385 """Get the status of the service function path
sousaedu80135b92021-02-17 15:05:18 +01003386 Params: the list of sfp identifiers
3387 Returns a dictionary with:
3388 vm_id: #VIM id of this service function path
3389 status: #Mandatory. Text with one of:
3390 # DELETED (not found at vim)
3391 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
3392 # OTHER (Vim reported other status not understood)
3393 # ERROR (VIM indicates an ERROR status)
3394 # ACTIVE,
3395 # CREATING (on building process)
3396 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
3397 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)F
tierno1ec592d2020-06-16 15:29:47 +00003398 """
3399 sfp_dict = {}
sousaedu80135b92021-02-17 15:05:18 +01003400 self.logger.debug(
3401 "refresh_sfps status: Getting tenant SFP information from VIM"
3402 )
3403
borsatti8a2dda32019-12-18 15:08:57 +00003404 for sfp_id in sfp_list:
tierno1ec592d2020-06-16 15:29:47 +00003405 sfp = {}
sousaedu80135b92021-02-17 15:05:18 +01003406
borsatti8a2dda32019-12-18 15:08:57 +00003407 try:
3408 sfp_vim = self.get_sfp(sfp_id)
sousaedu80135b92021-02-17 15:05:18 +01003409
3410 if sfp_vim["spi"]:
3411 sfp["status"] = vmStatus2manoFormat["ACTIVE"]
borsatti8a2dda32019-12-18 15:08:57 +00003412 else:
sousaedu80135b92021-02-17 15:05:18 +01003413 sfp["status"] = "OTHER"
3414 sfp["error_msg"] = "VIM status reported " + sfp["status"]
borsatti8a2dda32019-12-18 15:08:57 +00003415
sousaedu80135b92021-02-17 15:05:18 +01003416 sfp["vim_info"] = self.serialize(sfp_vim)
borsatti8a2dda32019-12-18 15:08:57 +00003417
sousaedu80135b92021-02-17 15:05:18 +01003418 if sfp_vim.get("fault"):
3419 sfp["error_msg"] = str(sfp_vim["fault"])
tierno72774862020-05-04 11:44:15 +00003420 except vimconn.VimConnNotFoundException as e:
borsatti8a2dda32019-12-18 15:08:57 +00003421 self.logger.error("Exception getting sfp status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01003422 sfp["status"] = "DELETED"
3423 sfp["error_msg"] = str(e)
tierno72774862020-05-04 11:44:15 +00003424 except vimconn.VimConnException as e:
borsatti8a2dda32019-12-18 15:08:57 +00003425 self.logger.error("Exception getting sfp status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01003426 sfp["status"] = "VIM_ERROR"
3427 sfp["error_msg"] = str(e)
3428
borsatti8a2dda32019-12-18 15:08:57 +00003429 sfp_dict[sfp_id] = sfp
sousaedu80135b92021-02-17 15:05:18 +01003430
borsatti8a2dda32019-12-18 15:08:57 +00003431 return sfp_dict
3432
borsatti8a2dda32019-12-18 15:08:57 +00003433 def refresh_sfis_status(self, sfi_list):
tierno1ec592d2020-06-16 15:29:47 +00003434 """Get the status of the service function instances
sousaedu80135b92021-02-17 15:05:18 +01003435 Params: the list of sfi identifiers
3436 Returns a dictionary with:
3437 vm_id: #VIM id of this service function instance
3438 status: #Mandatory. Text with one of:
3439 # DELETED (not found at vim)
3440 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
3441 # OTHER (Vim reported other status not understood)
3442 # ERROR (VIM indicates an ERROR status)
3443 # ACTIVE,
3444 # CREATING (on building process)
3445 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
3446 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
tierno1ec592d2020-06-16 15:29:47 +00003447 """
3448 sfi_dict = {}
sousaedu80135b92021-02-17 15:05:18 +01003449 self.logger.debug(
3450 "refresh_sfis status: Getting tenant sfi information from VIM"
3451 )
3452
borsatti8a2dda32019-12-18 15:08:57 +00003453 for sfi_id in sfi_list:
tierno1ec592d2020-06-16 15:29:47 +00003454 sfi = {}
sousaedu80135b92021-02-17 15:05:18 +01003455
borsatti8a2dda32019-12-18 15:08:57 +00003456 try:
3457 sfi_vim = self.get_sfi(sfi_id)
sousaedu80135b92021-02-17 15:05:18 +01003458
borsatti8a2dda32019-12-18 15:08:57 +00003459 if sfi_vim:
sousaedu80135b92021-02-17 15:05:18 +01003460 sfi["status"] = vmStatus2manoFormat["ACTIVE"]
borsatti8a2dda32019-12-18 15:08:57 +00003461 else:
sousaedu80135b92021-02-17 15:05:18 +01003462 sfi["status"] = "OTHER"
3463 sfi["error_msg"] = "VIM status reported " + sfi["status"]
borsatti8a2dda32019-12-18 15:08:57 +00003464
sousaedu80135b92021-02-17 15:05:18 +01003465 sfi["vim_info"] = self.serialize(sfi_vim)
borsatti8a2dda32019-12-18 15:08:57 +00003466
sousaedu80135b92021-02-17 15:05:18 +01003467 if sfi_vim.get("fault"):
3468 sfi["error_msg"] = str(sfi_vim["fault"])
tierno72774862020-05-04 11:44:15 +00003469 except vimconn.VimConnNotFoundException as e:
borsatti8a2dda32019-12-18 15:08:57 +00003470 self.logger.error("Exception getting sfi status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01003471 sfi["status"] = "DELETED"
3472 sfi["error_msg"] = str(e)
tierno72774862020-05-04 11:44:15 +00003473 except vimconn.VimConnException as e:
borsatti8a2dda32019-12-18 15:08:57 +00003474 self.logger.error("Exception getting sfi status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01003475 sfi["status"] = "VIM_ERROR"
3476 sfi["error_msg"] = str(e)
3477
borsatti8a2dda32019-12-18 15:08:57 +00003478 sfi_dict[sfi_id] = sfi
sousaedu80135b92021-02-17 15:05:18 +01003479
borsatti8a2dda32019-12-18 15:08:57 +00003480 return sfi_dict
3481
borsatti8a2dda32019-12-18 15:08:57 +00003482 def refresh_sfs_status(self, sf_list):
tierno1ec592d2020-06-16 15:29:47 +00003483 """Get the status of the service functions
sousaedu80135b92021-02-17 15:05:18 +01003484 Params: the list of sf identifiers
3485 Returns a dictionary with:
3486 vm_id: #VIM id of this service function
3487 status: #Mandatory. Text with one of:
3488 # DELETED (not found at vim)
3489 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
3490 # OTHER (Vim reported other status not understood)
3491 # ERROR (VIM indicates an ERROR status)
3492 # ACTIVE,
3493 # CREATING (on building process)
3494 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
3495 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
tierno1ec592d2020-06-16 15:29:47 +00003496 """
3497 sf_dict = {}
borsatti8a2dda32019-12-18 15:08:57 +00003498 self.logger.debug("refresh_sfs status: Getting tenant sf information from VIM")
sousaedu80135b92021-02-17 15:05:18 +01003499
borsatti8a2dda32019-12-18 15:08:57 +00003500 for sf_id in sf_list:
tierno1ec592d2020-06-16 15:29:47 +00003501 sf = {}
sousaedu80135b92021-02-17 15:05:18 +01003502
borsatti8a2dda32019-12-18 15:08:57 +00003503 try:
3504 sf_vim = self.get_sf(sf_id)
sousaedu80135b92021-02-17 15:05:18 +01003505
borsatti8a2dda32019-12-18 15:08:57 +00003506 if sf_vim:
sousaedu80135b92021-02-17 15:05:18 +01003507 sf["status"] = vmStatus2manoFormat["ACTIVE"]
borsatti8a2dda32019-12-18 15:08:57 +00003508 else:
sousaedu80135b92021-02-17 15:05:18 +01003509 sf["status"] = "OTHER"
3510 sf["error_msg"] = "VIM status reported " + sf_vim["status"]
borsatti8a2dda32019-12-18 15:08:57 +00003511
sousaedu80135b92021-02-17 15:05:18 +01003512 sf["vim_info"] = self.serialize(sf_vim)
borsatti8a2dda32019-12-18 15:08:57 +00003513
sousaedu80135b92021-02-17 15:05:18 +01003514 if sf_vim.get("fault"):
3515 sf["error_msg"] = str(sf_vim["fault"])
tierno72774862020-05-04 11:44:15 +00003516 except vimconn.VimConnNotFoundException as e:
borsatti8a2dda32019-12-18 15:08:57 +00003517 self.logger.error("Exception getting sf status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01003518 sf["status"] = "DELETED"
3519 sf["error_msg"] = str(e)
tierno72774862020-05-04 11:44:15 +00003520 except vimconn.VimConnException as e:
borsatti8a2dda32019-12-18 15:08:57 +00003521 self.logger.error("Exception getting sf status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01003522 sf["status"] = "VIM_ERROR"
3523 sf["error_msg"] = str(e)
3524
borsatti8a2dda32019-12-18 15:08:57 +00003525 sf_dict[sf_id] = sf
sousaedu80135b92021-02-17 15:05:18 +01003526
borsatti8a2dda32019-12-18 15:08:57 +00003527 return sf_dict
3528
borsatti8a2dda32019-12-18 15:08:57 +00003529 def refresh_classifications_status(self, classification_list):
tierno1ec592d2020-06-16 15:29:47 +00003530 """Get the status of the classifications
sousaedu80135b92021-02-17 15:05:18 +01003531 Params: the list of classification identifiers
3532 Returns a dictionary with:
3533 vm_id: #VIM id of this classifier
3534 status: #Mandatory. Text with one of:
3535 # DELETED (not found at vim)
3536 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
3537 # OTHER (Vim reported other status not understood)
3538 # ERROR (VIM indicates an ERROR status)
3539 # ACTIVE,
3540 # CREATING (on building process)
3541 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
3542 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
tierno1ec592d2020-06-16 15:29:47 +00003543 """
3544 classification_dict = {}
sousaedu80135b92021-02-17 15:05:18 +01003545 self.logger.debug(
3546 "refresh_classifications status: Getting tenant classification information from VIM"
3547 )
3548
borsatti8a2dda32019-12-18 15:08:57 +00003549 for classification_id in classification_list:
tierno1ec592d2020-06-16 15:29:47 +00003550 classification = {}
sousaedu80135b92021-02-17 15:05:18 +01003551
borsatti8a2dda32019-12-18 15:08:57 +00003552 try:
3553 classification_vim = self.get_classification(classification_id)
sousaedu80135b92021-02-17 15:05:18 +01003554
borsatti8a2dda32019-12-18 15:08:57 +00003555 if classification_vim:
sousaedu80135b92021-02-17 15:05:18 +01003556 classification["status"] = vmStatus2manoFormat["ACTIVE"]
borsatti8a2dda32019-12-18 15:08:57 +00003557 else:
sousaedu80135b92021-02-17 15:05:18 +01003558 classification["status"] = "OTHER"
3559 classification["error_msg"] = (
3560 "VIM status reported " + classification["status"]
3561 )
borsatti8a2dda32019-12-18 15:08:57 +00003562
sousaedu80135b92021-02-17 15:05:18 +01003563 classification["vim_info"] = self.serialize(classification_vim)
borsatti8a2dda32019-12-18 15:08:57 +00003564
sousaedu80135b92021-02-17 15:05:18 +01003565 if classification_vim.get("fault"):
3566 classification["error_msg"] = str(classification_vim["fault"])
tierno72774862020-05-04 11:44:15 +00003567 except vimconn.VimConnNotFoundException as e:
borsatti8a2dda32019-12-18 15:08:57 +00003568 self.logger.error("Exception getting classification status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01003569 classification["status"] = "DELETED"
3570 classification["error_msg"] = str(e)
tierno72774862020-05-04 11:44:15 +00003571 except vimconn.VimConnException as e:
borsatti8a2dda32019-12-18 15:08:57 +00003572 self.logger.error("Exception getting classification status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01003573 classification["status"] = "VIM_ERROR"
3574 classification["error_msg"] = str(e)
3575
borsatti8a2dda32019-12-18 15:08:57 +00003576 classification_dict[classification_id] = classification
sousaedu80135b92021-02-17 15:05:18 +01003577
borsatti8a2dda32019-12-18 15:08:57 +00003578 return classification_dict
Alexis Romerob70f4ed2022-03-11 18:00:49 +01003579
3580 def new_affinity_group(self, affinity_group_data):
3581 """Adds a server group to VIM
3582 affinity_group_data contains a dictionary with information, keys:
3583 name: name in VIM for the server group
3584 type: affinity or anti-affinity
3585 scope: Only nfvi-node allowed
3586 Returns the server group identifier"""
3587 self.logger.debug("Adding Server Group '%s'", str(affinity_group_data))
3588
3589 try:
3590 name = affinity_group_data["name"]
3591 policy = affinity_group_data["type"]
3592
3593 self._reload_connection()
3594 new_server_group = self.nova.server_groups.create(name, policy)
3595
3596 return new_server_group.id
3597 except (
3598 ksExceptions.ClientException,
3599 nvExceptions.ClientException,
3600 ConnectionError,
3601 KeyError,
3602 ) as e:
3603 self._format_exception(e)
3604
3605 def get_affinity_group(self, affinity_group_id):
3606 """Obtain server group details from the VIM. Returns the server group detais as a dict"""
3607 self.logger.debug("Getting flavor '%s'", affinity_group_id)
3608 try:
3609 self._reload_connection()
3610 server_group = self.nova.server_groups.find(id=affinity_group_id)
3611
3612 return server_group.to_dict()
3613 except (
3614 nvExceptions.NotFound,
3615 nvExceptions.ClientException,
3616 ksExceptions.ClientException,
3617 ConnectionError,
3618 ) as e:
3619 self._format_exception(e)
3620
3621 def delete_affinity_group(self, affinity_group_id):
3622 """Deletes a server group from the VIM. Returns the old affinity_group_id"""
3623 self.logger.debug("Getting server group '%s'", affinity_group_id)
3624 try:
3625 self._reload_connection()
3626 self.nova.server_groups.delete(affinity_group_id)
3627
3628 return affinity_group_id
3629 except (
3630 nvExceptions.NotFound,
3631 ksExceptions.ClientException,
3632 nvExceptions.ClientException,
3633 ConnectionError,
3634 ) as e:
3635 self._format_exception(e)
elumalai8658c2c2022-04-28 19:09:31 +05303636
3637 def get_vdu_state(self, vm_id):
3638 """
3639 Getting the state of a vdu
3640 param:
3641 vm_id: ID of an instance
3642 """
3643 self.logger.debug("Getting the status of VM")
3644 self.logger.debug("VIM VM ID %s", vm_id)
3645 self._reload_connection()
3646 server = self.nova.servers.find(id=vm_id)
3647 server_dict = server.to_dict()
3648 vdu_data = [
3649 server_dict["status"],
3650 server_dict["flavor"]["id"],
3651 server_dict["OS-EXT-SRV-ATTR:host"],
3652 server_dict["OS-EXT-AZ:availability_zone"],
3653 ]
3654 self.logger.debug("vdu_data %s", vdu_data)
3655 return vdu_data
3656
3657 def check_compute_availability(self, host, server_flavor_details):
3658 self._reload_connection()
3659 hypervisor_search = self.nova.hypervisors.search(
3660 hypervisor_match=host, servers=True
3661 )
3662 for hypervisor in hypervisor_search:
3663 hypervisor_id = hypervisor.to_dict()["id"]
3664 hypervisor_details = self.nova.hypervisors.get(hypervisor=hypervisor_id)
3665 hypervisor_dict = hypervisor_details.to_dict()
3666 hypervisor_temp = json.dumps(hypervisor_dict)
3667 hypervisor_json = json.loads(hypervisor_temp)
3668 resources_available = [
3669 hypervisor_json["free_ram_mb"],
3670 hypervisor_json["disk_available_least"],
3671 hypervisor_json["vcpus"] - hypervisor_json["vcpus_used"],
3672 ]
3673 compute_available = all(
3674 x > y for x, y in zip(resources_available, server_flavor_details)
3675 )
3676 if compute_available:
3677 return host
3678
3679 def check_availability_zone(
3680 self, old_az, server_flavor_details, old_host, host=None
3681 ):
3682 self._reload_connection()
3683 az_check = {"zone_check": False, "compute_availability": None}
3684 aggregates_list = self.nova.aggregates.list()
3685 for aggregate in aggregates_list:
3686 aggregate_details = aggregate.to_dict()
3687 aggregate_temp = json.dumps(aggregate_details)
3688 aggregate_json = json.loads(aggregate_temp)
3689 if aggregate_json["availability_zone"] == old_az:
3690 hosts_list = aggregate_json["hosts"]
3691 if host is not None:
3692 if host in hosts_list:
3693 az_check["zone_check"] = True
3694 available_compute_id = self.check_compute_availability(
3695 host, server_flavor_details
3696 )
3697 if available_compute_id is not None:
3698 az_check["compute_availability"] = available_compute_id
3699 else:
3700 for check_host in hosts_list:
3701 if check_host != old_host:
3702 available_compute_id = self.check_compute_availability(
3703 check_host, server_flavor_details
3704 )
3705 if available_compute_id is not None:
3706 az_check["zone_check"] = True
3707 az_check["compute_availability"] = available_compute_id
3708 break
3709 else:
3710 az_check["zone_check"] = True
3711 return az_check
3712
3713 def migrate_instance(self, vm_id, compute_host=None):
3714 """
3715 Migrate a vdu
3716 param:
3717 vm_id: ID of an instance
3718 compute_host: Host to migrate the vdu to
3719 """
3720 self._reload_connection()
3721 vm_state = False
3722 instance_state = self.get_vdu_state(vm_id)
3723 server_flavor_id = instance_state[1]
3724 server_hypervisor_name = instance_state[2]
3725 server_availability_zone = instance_state[3]
3726 try:
3727 server_flavor = self.nova.flavors.find(id=server_flavor_id).to_dict()
3728 server_flavor_details = [
3729 server_flavor["ram"],
3730 server_flavor["disk"],
3731 server_flavor["vcpus"],
3732 ]
3733 if compute_host == server_hypervisor_name:
3734 raise vimconn.VimConnException(
3735 "Unable to migrate instance '{}' to the same host '{}'".format(
3736 vm_id, compute_host
3737 ),
3738 http_code=vimconn.HTTP_Bad_Request,
3739 )
3740 az_status = self.check_availability_zone(
3741 server_availability_zone,
3742 server_flavor_details,
3743 server_hypervisor_name,
3744 compute_host,
3745 )
3746 availability_zone_check = az_status["zone_check"]
3747 available_compute_id = az_status.get("compute_availability")
3748
3749 if availability_zone_check is False:
3750 raise vimconn.VimConnException(
3751 "Unable to migrate instance '{}' to a different availability zone".format(
3752 vm_id
3753 ),
3754 http_code=vimconn.HTTP_Bad_Request,
3755 )
3756 if available_compute_id is not None:
3757 self.nova.servers.live_migrate(
3758 server=vm_id,
3759 host=available_compute_id,
3760 block_migration=True,
3761 disk_over_commit=False,
3762 )
3763 state = "MIGRATING"
3764 changed_compute_host = ""
3765 if state == "MIGRATING":
3766 vm_state = self.__wait_for_vm(vm_id, "ACTIVE")
3767 changed_compute_host = self.get_vdu_state(vm_id)[2]
3768 if vm_state and changed_compute_host == available_compute_id:
3769 self.logger.debug(
3770 "Instance '{}' migrated to the new compute host '{}'".format(
3771 vm_id, changed_compute_host
3772 )
3773 )
3774 return state, available_compute_id
3775 else:
3776 raise vimconn.VimConnException(
3777 "Migration Failed. Instance '{}' not moved to the new host {}".format(
3778 vm_id, available_compute_id
3779 ),
3780 http_code=vimconn.HTTP_Bad_Request,
3781 )
3782 else:
3783 raise vimconn.VimConnException(
3784 "Compute '{}' not available or does not have enough resources to migrate the instance".format(
3785 available_compute_id
3786 ),
3787 http_code=vimconn.HTTP_Bad_Request,
3788 )
3789 except (
3790 nvExceptions.BadRequest,
3791 nvExceptions.ClientException,
3792 nvExceptions.NotFound,
3793 ) as e:
3794 self._format_exception(e)
sritharan29a4c1a2022-05-05 12:15:04 +00003795
3796 def resize_instance(self, vm_id, new_flavor_id):
3797 """
3798 For resizing the vm based on the given
3799 flavor details
3800 param:
3801 vm_id : ID of an instance
3802 new_flavor_id : Flavor id to be resized
3803 Return the status of a resized instance
3804 """
3805 self._reload_connection()
3806 self.logger.debug("resize the flavor of an instance")
3807 instance_status, old_flavor_id, compute_host, az = self.get_vdu_state(vm_id)
3808 old_flavor_disk = self.nova.flavors.find(id=old_flavor_id).to_dict()["disk"]
3809 new_flavor_disk = self.nova.flavors.find(id=new_flavor_id).to_dict()["disk"]
3810 try:
3811 if instance_status == "ACTIVE" or instance_status == "SHUTOFF":
3812 if old_flavor_disk > new_flavor_disk:
3813 raise nvExceptions.BadRequest(
3814 400,
3815 message="Server disk resize failed. Resize to lower disk flavor is not allowed",
3816 )
3817 else:
3818 self.nova.servers.resize(server=vm_id, flavor=new_flavor_id)
3819 vm_state = self.__wait_for_vm(vm_id, "VERIFY_RESIZE")
3820 if vm_state:
3821 instance_resized_status = self.confirm_resize(vm_id)
3822 return instance_resized_status
3823 else:
3824 raise nvExceptions.BadRequest(
3825 409,
3826 message="Cannot 'resize' vm_state is in ERROR",
3827 )
3828
3829 else:
3830 self.logger.debug("ERROR : Instance is not in ACTIVE or SHUTOFF state")
3831 raise nvExceptions.BadRequest(
3832 409,
3833 message="Cannot 'resize' instance while it is in vm_state resized",
3834 )
3835 except (
3836 nvExceptions.BadRequest,
3837 nvExceptions.ClientException,
3838 nvExceptions.NotFound,
3839 ) as e:
3840 self._format_exception(e)
3841
3842 def confirm_resize(self, vm_id):
3843 """
3844 Confirm the resize of an instance
3845 param:
3846 vm_id: ID of an instance
3847 """
3848 self._reload_connection()
3849 self.nova.servers.confirm_resize(server=vm_id)
3850 if self.get_vdu_state(vm_id)[0] == "VERIFY_RESIZE":
3851 self.__wait_for_vm(vm_id, "ACTIVE")
3852 instance_status = self.get_vdu_state(vm_id)[0]
3853 return instance_status