blob: 9f7499c6b7fbf954eff5cb23800df683f9835ba3 [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
Gulsum Atici4415c4c2023-01-19 12:44:06 +030041from typing import Dict, List, Optional, Tuple
sousaedu049cbb12022-01-05 11:39:35 +000042
43from cinderclient import client as cClient
tiernob5cef372017-06-19 15:52:22 +020044from glanceclient import client as glClient
tierno7edb6752016-03-21 17:37:52 +010045import glanceclient.exc as gl1Exceptions
sousaedu049cbb12022-01-05 11:39:35 +000046from keystoneauth1 import session
47from keystoneauth1.identity import v2, v3
48import keystoneclient.exceptions as ksExceptions
49import keystoneclient.v2_0.client as ksClient_v2
50import keystoneclient.v3.client as ksClient_v3
51import netaddr
tierno7edb6752016-03-21 17:37:52 +010052from neutronclient.common import exceptions as neExceptions
sousaedu049cbb12022-01-05 11:39:35 +000053from neutronclient.neutron import client as neClient
54from novaclient import client as nClient, exceptions as nvExceptions
55from osm_ro_plugin import vimconn
tierno7edb6752016-03-21 17:37:52 +010056from requests.exceptions import ConnectionError
sousaedu049cbb12022-01-05 11:39:35 +000057import yaml
tierno7edb6752016-03-21 17:37:52 +010058
tierno1ec592d2020-06-16 15:29:47 +000059__author__ = "Alfonso Tierno, Gerardo Garcia, Pablo Montes, xFlow Research, Igor D.C., Eduardo Sousa"
60__date__ = "$22-sep-2017 23:59:59$"
tierno40e1bce2017-08-09 09:12:04 +020061
62"""contain the openstack virtual machine status to openmano status"""
sousaedu80135b92021-02-17 15:05:18 +010063vmStatus2manoFormat = {
64 "ACTIVE": "ACTIVE",
65 "PAUSED": "PAUSED",
66 "SUSPENDED": "SUSPENDED",
67 "SHUTOFF": "INACTIVE",
68 "BUILD": "BUILD",
69 "ERROR": "ERROR",
70 "DELETED": "DELETED",
71}
72netStatus2manoFormat = {
73 "ACTIVE": "ACTIVE",
74 "PAUSED": "PAUSED",
75 "INACTIVE": "INACTIVE",
76 "BUILD": "BUILD",
77 "ERROR": "ERROR",
78 "DELETED": "DELETED",
79}
tierno7edb6752016-03-21 17:37:52 +010080
sousaedu80135b92021-02-17 15:05:18 +010081supportedClassificationTypes = ["legacy_flow_classifier"]
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +000082
tierno1ec592d2020-06-16 15:29:47 +000083# global var to have a timeout creating and deleting volumes
garciadeblas64b39c52020-05-21 08:07:25 +000084volume_timeout = 1800
85server_timeout = 1800
montesmoreno0c8def02016-12-22 12:16:23 +000086
Anderson Bravalheri0446cd52018-08-17 15:26:19 +010087
88class SafeDumper(yaml.SafeDumper):
89 def represent_data(self, data):
90 # Openstack APIs use custom subclasses of dict and YAML safe dumper
91 # is designed to not handle that (reference issue 142 of pyyaml)
92 if isinstance(data, dict) and data.__class__ != dict:
93 # A simple solution is to convert those items back to dicts
94 data = dict(data.items())
95
96 return super(SafeDumper, self).represent_data(data)
97
98
tierno72774862020-05-04 11:44:15 +000099class vimconnector(vimconn.VimConnector):
sousaedu80135b92021-02-17 15:05:18 +0100100 def __init__(
101 self,
102 uuid,
103 name,
104 tenant_id,
105 tenant_name,
106 url,
107 url_admin=None,
108 user=None,
109 passwd=None,
110 log_level=None,
111 config={},
112 persistent_info={},
113 ):
tierno1ec592d2020-06-16 15:29:47 +0000114 """using common constructor parameters. In this case
tierno7edb6752016-03-21 17:37:52 +0100115 'url' is the keystone authorization url,
116 'url_admin' is not use
tierno1ec592d2020-06-16 15:29:47 +0000117 """
sousaedu80135b92021-02-17 15:05:18 +0100118 api_version = config.get("APIversion")
kate721d79b2017-06-24 04:21:38 -0700119
sousaedu80135b92021-02-17 15:05:18 +0100120 if api_version and api_version not in ("v3.3", "v2.0", "2", "3"):
121 raise vimconn.VimConnException(
122 "Invalid value '{}' for config:APIversion. "
123 "Allowed values are 'v3.3', 'v2.0', '2' or '3'".format(api_version)
124 )
125
126 vim_type = config.get("vim_type")
127
128 if vim_type and vim_type not in ("vio", "VIO"):
129 raise vimconn.VimConnException(
130 "Invalid value '{}' for config:vim_type."
131 "Allowed values are 'vio' or 'VIO'".format(vim_type)
132 )
133
134 if config.get("dataplane_net_vlan_range") is not None:
tierno1ec592d2020-06-16 15:29:47 +0000135 # validate vlan ranges provided by user
sousaedu80135b92021-02-17 15:05:18 +0100136 self._validate_vlan_ranges(
137 config.get("dataplane_net_vlan_range"), "dataplane_net_vlan_range"
138 )
garciadeblasebd66722019-01-31 16:01:31 +0000139
sousaedu80135b92021-02-17 15:05:18 +0100140 if config.get("multisegment_vlan_range") is not None:
tierno1ec592d2020-06-16 15:29:47 +0000141 # validate vlan ranges provided by user
sousaedu80135b92021-02-17 15:05:18 +0100142 self._validate_vlan_ranges(
143 config.get("multisegment_vlan_range"), "multisegment_vlan_range"
144 )
kate721d79b2017-06-24 04:21:38 -0700145
sousaedu80135b92021-02-17 15:05:18 +0100146 vimconn.VimConnector.__init__(
147 self,
148 uuid,
149 name,
150 tenant_id,
151 tenant_name,
152 url,
153 url_admin,
154 user,
155 passwd,
156 log_level,
157 config,
158 )
tiernob3d36742017-03-03 23:51:05 +0100159
tierno4d1ce222018-04-06 10:41:06 +0200160 if self.config.get("insecure") and self.config.get("ca_cert"):
sousaedu80135b92021-02-17 15:05:18 +0100161 raise vimconn.VimConnException(
162 "options insecure and ca_cert are mutually exclusive"
163 )
164
tierno4d1ce222018-04-06 10:41:06 +0200165 self.verify = True
sousaedu80135b92021-02-17 15:05:18 +0100166
tierno4d1ce222018-04-06 10:41:06 +0200167 if self.config.get("insecure"):
168 self.verify = False
sousaedu80135b92021-02-17 15:05:18 +0100169
tierno4d1ce222018-04-06 10:41:06 +0200170 if self.config.get("ca_cert"):
171 self.verify = self.config.get("ca_cert")
tierno4d1ce222018-04-06 10:41:06 +0200172
tierno7edb6752016-03-21 17:37:52 +0100173 if not url:
sousaedu80135b92021-02-17 15:05:18 +0100174 raise TypeError("url param can not be NoneType")
175
tiernob5cef372017-06-19 15:52:22 +0200176 self.persistent_info = persistent_info
sousaedu80135b92021-02-17 15:05:18 +0100177 self.availability_zone = persistent_info.get("availability_zone", None)
178 self.session = persistent_info.get("session", {"reload_client": True})
179 self.my_tenant_id = self.session.get("my_tenant_id")
180 self.nova = self.session.get("nova")
181 self.neutron = self.session.get("neutron")
182 self.cinder = self.session.get("cinder")
183 self.glance = self.session.get("glance")
184 # self.glancev1 = self.session.get("glancev1")
185 self.keystone = self.session.get("keystone")
186 self.api_version3 = self.session.get("api_version3")
kate721d79b2017-06-24 04:21:38 -0700187 self.vim_type = self.config.get("vim_type")
sousaedu80135b92021-02-17 15:05:18 +0100188
kate721d79b2017-06-24 04:21:38 -0700189 if self.vim_type:
190 self.vim_type = self.vim_type.upper()
sousaedu80135b92021-02-17 15:05:18 +0100191
kate721d79b2017-06-24 04:21:38 -0700192 if self.config.get("use_internal_endpoint"):
193 self.endpoint_type = "internalURL"
194 else:
195 self.endpoint_type = None
montesmoreno0c8def02016-12-22 12:16:23 +0000196
sousaedu80135b92021-02-17 15:05:18 +0100197 logging.getLogger("urllib3").setLevel(logging.WARNING)
198 logging.getLogger("keystoneauth").setLevel(logging.WARNING)
199 logging.getLogger("novaclient").setLevel(logging.WARNING)
200 self.logger = logging.getLogger("ro.vim.openstack")
kate721d79b2017-06-24 04:21:38 -0700201
tiernoa05b65a2019-02-01 12:30:27 +0000202 # allow security_groups to be a list or a single string
sousaedu80135b92021-02-17 15:05:18 +0100203 if isinstance(self.config.get("security_groups"), str):
204 self.config["security_groups"] = [self.config["security_groups"]]
205
tiernoa05b65a2019-02-01 12:30:27 +0000206 self.security_groups_id = None
207
tierno1ec592d2020-06-16 15:29:47 +0000208 # ###### VIO Specific Changes #########
kate721d79b2017-06-24 04:21:38 -0700209 if self.vim_type == "VIO":
sousaedu80135b92021-02-17 15:05:18 +0100210 self.logger = logging.getLogger("ro.vim.vio")
kate721d79b2017-06-24 04:21:38 -0700211
tiernofe789902016-09-29 14:20:44 +0000212 if log_level:
tierno1ec592d2020-06-16 15:29:47 +0000213 self.logger.setLevel(getattr(logging, log_level))
tiernof716aea2017-06-21 18:01:40 +0200214
215 def __getitem__(self, index):
216 """Get individuals parameters.
217 Throw KeyError"""
sousaedu80135b92021-02-17 15:05:18 +0100218 if index == "project_domain_id":
tiernof716aea2017-06-21 18:01:40 +0200219 return self.config.get("project_domain_id")
sousaedu80135b92021-02-17 15:05:18 +0100220 elif index == "user_domain_id":
tiernof716aea2017-06-21 18:01:40 +0200221 return self.config.get("user_domain_id")
222 else:
tierno72774862020-05-04 11:44:15 +0000223 return vimconn.VimConnector.__getitem__(self, index)
tiernof716aea2017-06-21 18:01:40 +0200224
225 def __setitem__(self, index, value):
226 """Set individuals parameters and it is marked as dirty so to force connection reload.
227 Throw KeyError"""
sousaedu80135b92021-02-17 15:05:18 +0100228 if index == "project_domain_id":
tiernof716aea2017-06-21 18:01:40 +0200229 self.config["project_domain_id"] = value
sousaedu80135b92021-02-17 15:05:18 +0100230 elif index == "user_domain_id":
tierno1ec592d2020-06-16 15:29:47 +0000231 self.config["user_domain_id"] = value
tiernof716aea2017-06-21 18:01:40 +0200232 else:
tierno72774862020-05-04 11:44:15 +0000233 vimconn.VimConnector.__setitem__(self, index, value)
sousaedu80135b92021-02-17 15:05:18 +0100234
235 self.session["reload_client"] = True
tiernof716aea2017-06-21 18:01:40 +0200236
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100237 def serialize(self, value):
238 """Serialization of python basic types.
239
240 In the case value is not serializable a message will be logged and a
241 simple representation of the data that cannot be converted back to
242 python is returned.
243 """
tierno7d782ef2019-10-04 12:56:31 +0000244 if isinstance(value, str):
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100245 return value
246
247 try:
sousaedu80135b92021-02-17 15:05:18 +0100248 return yaml.dump(
249 value, Dumper=SafeDumper, default_flow_style=True, width=256
250 )
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100251 except yaml.representer.RepresenterError:
sousaedu80135b92021-02-17 15:05:18 +0100252 self.logger.debug(
253 "The following entity cannot be serialized in YAML:\n\n%s\n\n",
254 pformat(value),
255 exc_info=True,
256 )
257
tierno1ec592d2020-06-16 15:29:47 +0000258 return str(value)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100259
tierno7edb6752016-03-21 17:37:52 +0100260 def _reload_connection(self):
tierno1ec592d2020-06-16 15:29:47 +0000261 """Called before any operation, it check if credentials has changed
tierno7edb6752016-03-21 17:37:52 +0100262 Throw keystoneclient.apiclient.exceptions.AuthorizationFailure
tierno1ec592d2020-06-16 15:29:47 +0000263 """
264 # 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 +0100265 if self.session["reload_client"]:
266 if self.config.get("APIversion"):
267 self.api_version3 = (
268 self.config["APIversion"] == "v3.3"
269 or self.config["APIversion"] == "3"
270 )
tiernof716aea2017-06-21 18:01:40 +0200271 else: # get from ending auth_url that end with v3 or with v2.0
sousaedu80135b92021-02-17 15:05:18 +0100272 self.api_version3 = self.url.endswith("/v3") or self.url.endswith(
273 "/v3/"
274 )
275
276 self.session["api_version3"] = self.api_version3
277
tiernof716aea2017-06-21 18:01:40 +0200278 if self.api_version3:
sousaedu80135b92021-02-17 15:05:18 +0100279 if self.config.get("project_domain_id") or self.config.get(
280 "project_domain_name"
281 ):
tierno3cb8dc32017-10-24 18:13:19 +0200282 project_domain_id_default = None
283 else:
sousaedu80135b92021-02-17 15:05:18 +0100284 project_domain_id_default = "default"
285
286 if self.config.get("user_domain_id") or self.config.get(
287 "user_domain_name"
288 ):
tierno3cb8dc32017-10-24 18:13:19 +0200289 user_domain_id_default = None
290 else:
sousaedu80135b92021-02-17 15:05:18 +0100291 user_domain_id_default = "default"
292 auth = v3.Password(
293 auth_url=self.url,
294 username=self.user,
295 password=self.passwd,
296 project_name=self.tenant_name,
297 project_id=self.tenant_id,
298 project_domain_id=self.config.get(
299 "project_domain_id", project_domain_id_default
300 ),
301 user_domain_id=self.config.get(
302 "user_domain_id", user_domain_id_default
303 ),
304 project_domain_name=self.config.get("project_domain_name"),
305 user_domain_name=self.config.get("user_domain_name"),
306 )
ahmadsa95baa272016-11-30 09:14:11 +0500307 else:
sousaedu80135b92021-02-17 15:05:18 +0100308 auth = v2.Password(
309 auth_url=self.url,
310 username=self.user,
311 password=self.passwd,
312 tenant_name=self.tenant_name,
313 tenant_id=self.tenant_id,
314 )
315
tierno4d1ce222018-04-06 10:41:06 +0200316 sess = session.Session(auth=auth, verify=self.verify)
garciadeblas08b8a462024-11-28 17:46:13 +0100317 # added region_name to keystone, nova, neutron and cinder to support distributed cloud for Wind River
tierno1ec592d2020-06-16 15:29:47 +0000318 # Titanium cloud and StarlingX
sousaedu80135b92021-02-17 15:05:18 +0100319 region_name = self.config.get("region_name")
320
tiernof716aea2017-06-21 18:01:40 +0200321 if self.api_version3:
garciadeblas08b8a462024-11-28 17:46:13 +0100322 self.logger.debug(f"Using Keystone client v3 for VIM {self.id}")
sousaedu80135b92021-02-17 15:05:18 +0100323 self.keystone = ksClient_v3.Client(
324 session=sess,
325 endpoint_type=self.endpoint_type,
326 region_name=region_name,
327 )
tiernof716aea2017-06-21 18:01:40 +0200328 else:
garciadeblas08b8a462024-11-28 17:46:13 +0100329 self.logger.debug(f"Using Keystone client v2 for VIM {self.id}")
sousaedu80135b92021-02-17 15:05:18 +0100330 self.keystone = ksClient_v2.Client(
331 session=sess, endpoint_type=self.endpoint_type
332 )
333
334 self.session["keystone"] = self.keystone
335 # In order to enable microversion functionality an explicit microversion must be specified in "config".
montesmoreno9317d302017-08-16 12:48:23 +0200336 # This implementation approach is due to the warning message in
337 # https://developer.openstack.org/api-guide/compute/microversions.html
338 # where it is stated that microversion backwards compatibility is not guaranteed and clients should
339 # always require an specific microversion.
sousaedu80135b92021-02-17 15:05:18 +0100340 # To be able to use "device role tagging" functionality define "microversion: 2.32" in datacenter config
montesmoreno9317d302017-08-16 12:48:23 +0200341 version = self.config.get("microversion")
sousaedu80135b92021-02-17 15:05:18 +0100342
montesmoreno9317d302017-08-16 12:48:23 +0200343 if not version:
vegallc53829d2023-06-01 00:47:44 -0500344 version = "2.60"
sousaedu80135b92021-02-17 15:05:18 +0100345
tierno1ec592d2020-06-16 15:29:47 +0000346 # addedd region_name to keystone, nova, neutron and cinder to support distributed cloud for Wind River
347 # Titanium cloud and StarlingX
sousaedu80135b92021-02-17 15:05:18 +0100348 self.nova = self.session["nova"] = nClient.Client(
349 str(version),
350 session=sess,
351 endpoint_type=self.endpoint_type,
352 region_name=region_name,
353 )
354 self.neutron = self.session["neutron"] = neClient.Client(
355 "2.0",
356 session=sess,
357 endpoint_type=self.endpoint_type,
358 region_name=region_name,
359 )
Lovejeet Singh778f3cc2023-02-13 16:15:40 +0530360
garciadeblas08b8a462024-11-28 17:46:13 +0100361 if sess.get_all_version_data(service_type="volumev3"):
362 self.logger.debug(f"Using Cinder client v3 for VIM {self.id}")
363 self.cinder = self.session["cinder"] = cClient.Client(
364 3,
365 session=sess,
366 endpoint_type=self.endpoint_type,
367 region_name=region_name,
368 )
369 elif sess.get_all_version_data(service_type="volumev2"):
370 self.logger.debug(
371 f"Service type volumev3 not found. Using Cinder client v2 for VIM {self.id}"
372 )
Lovejeet Singh778f3cc2023-02-13 16:15:40 +0530373 self.cinder = self.session["cinder"] = cClient.Client(
374 2,
375 session=sess,
376 endpoint_type=self.endpoint_type,
377 region_name=region_name,
378 )
379 else:
garciadeblas08b8a462024-11-28 17:46:13 +0100380 self.logger.debug(
381 f"Service type not found. Using Cinder client v3 for VIM {self.id}"
382 )
Lovejeet Singh778f3cc2023-02-13 16:15:40 +0530383 self.cinder = self.session["cinder"] = cClient.Client(
384 3,
385 session=sess,
386 endpoint_type=self.endpoint_type,
387 region_name=region_name,
388 )
sousaedu80135b92021-02-17 15:05:18 +0100389
tiernoa05b65a2019-02-01 12:30:27 +0000390 try:
sousaedu80135b92021-02-17 15:05:18 +0100391 self.my_tenant_id = self.session["my_tenant_id"] = sess.get_project_id()
tierno1ec592d2020-06-16 15:29:47 +0000392 except Exception:
tiernoa05b65a2019-02-01 12:30:27 +0000393 self.logger.error("Cannot get project_id from session", exc_info=True)
sousaedu80135b92021-02-17 15:05:18 +0100394
kate721d79b2017-06-24 04:21:38 -0700395 if self.endpoint_type == "internalURL":
396 glance_service_id = self.keystone.services.list(name="glance")[0].id
sousaedu80135b92021-02-17 15:05:18 +0100397 glance_endpoint = self.keystone.endpoints.list(
398 glance_service_id, interface="internal"
399 )[0].url
kate721d79b2017-06-24 04:21:38 -0700400 else:
401 glance_endpoint = None
sousaedu80135b92021-02-17 15:05:18 +0100402
403 self.glance = self.session["glance"] = glClient.Client(
404 2, session=sess, endpoint=glance_endpoint
405 )
tiernoa05b65a2019-02-01 12:30:27 +0000406 # using version 1 of glance client in new_image()
sousaedu80135b92021-02-17 15:05:18 +0100407 # self.glancev1 = self.session["glancev1"] = glClient.Client("1", session=sess,
tierno1beea862018-07-11 15:47:37 +0200408 # endpoint=glance_endpoint)
sousaedu80135b92021-02-17 15:05:18 +0100409 self.session["reload_client"] = False
410 self.persistent_info["session"] = self.session
mirabal29356312017-07-27 12:21:22 +0200411 # add availablity zone info inside self.persistent_info
412 self._set_availablity_zones()
sousaedu80135b92021-02-17 15:05:18 +0100413 self.persistent_info["availability_zone"] = self.availability_zone
414 # force to get again security_groups_ids next time they are needed
415 self.security_groups_id = None
ahmadsa95baa272016-11-30 09:14:11 +0500416
tierno7edb6752016-03-21 17:37:52 +0100417 def __net_os2mano(self, net_list_dict):
tierno1ec592d2020-06-16 15:29:47 +0000418 """Transform the net openstack format to mano format
419 net_list_dict can be a list of dict or a single dict"""
tierno7edb6752016-03-21 17:37:52 +0100420 if type(net_list_dict) is dict:
tierno1ec592d2020-06-16 15:29:47 +0000421 net_list_ = (net_list_dict,)
tierno7edb6752016-03-21 17:37:52 +0100422 elif type(net_list_dict) is list:
tierno1ec592d2020-06-16 15:29:47 +0000423 net_list_ = net_list_dict
tierno7edb6752016-03-21 17:37:52 +0100424 else:
425 raise TypeError("param net_list_dict must be a list or a dictionary")
426 for net in net_list_:
sousaedu80135b92021-02-17 15:05:18 +0100427 if net.get("provider:network_type") == "vlan":
428 net["type"] = "data"
tierno7edb6752016-03-21 17:37:52 +0100429 else:
sousaedu80135b92021-02-17 15:05:18 +0100430 net["type"] = "bridge"
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +0200431
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000432 def __classification_os2mano(self, class_list_dict):
433 """Transform the openstack format (Flow Classifier) to mano format
434 (Classification) class_list_dict can be a list of dict or a single dict
435 """
436 if isinstance(class_list_dict, dict):
437 class_list_ = [class_list_dict]
438 elif isinstance(class_list_dict, list):
439 class_list_ = class_list_dict
440 else:
tierno1ec592d2020-06-16 15:29:47 +0000441 raise TypeError("param class_list_dict must be a list or a dictionary")
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000442 for classification in class_list_:
sousaedu80135b92021-02-17 15:05:18 +0100443 id = classification.pop("id")
444 name = classification.pop("name")
445 description = classification.pop("description")
446 project_id = classification.pop("project_id")
447 tenant_id = classification.pop("tenant_id")
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000448 original_classification = copy.deepcopy(classification)
449 classification.clear()
sousaedu80135b92021-02-17 15:05:18 +0100450 classification["ctype"] = "legacy_flow_classifier"
451 classification["definition"] = original_classification
452 classification["id"] = id
453 classification["name"] = name
454 classification["description"] = description
455 classification["project_id"] = project_id
456 classification["tenant_id"] = tenant_id
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000457
458 def __sfi_os2mano(self, sfi_list_dict):
459 """Transform the openstack format (Port Pair) to mano format (SFI)
460 sfi_list_dict can be a list of dict or a single dict
461 """
462 if isinstance(sfi_list_dict, dict):
463 sfi_list_ = [sfi_list_dict]
464 elif isinstance(sfi_list_dict, list):
465 sfi_list_ = sfi_list_dict
466 else:
sousaedu80135b92021-02-17 15:05:18 +0100467 raise TypeError("param sfi_list_dict must be a list or a dictionary")
468
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000469 for sfi in sfi_list_:
sousaedu80135b92021-02-17 15:05:18 +0100470 sfi["ingress_ports"] = []
471 sfi["egress_ports"] = []
472
473 if sfi.get("ingress"):
474 sfi["ingress_ports"].append(sfi["ingress"])
475
476 if sfi.get("egress"):
477 sfi["egress_ports"].append(sfi["egress"])
478
479 del sfi["ingress"]
480 del sfi["egress"]
481 params = sfi.get("service_function_parameters")
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000482 sfc_encap = False
sousaedu80135b92021-02-17 15:05:18 +0100483
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000484 if params:
sousaedu80135b92021-02-17 15:05:18 +0100485 correlation = params.get("correlation")
486
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000487 if correlation:
488 sfc_encap = True
sousaedu80135b92021-02-17 15:05:18 +0100489
490 sfi["sfc_encap"] = sfc_encap
491 del sfi["service_function_parameters"]
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000492
493 def __sf_os2mano(self, sf_list_dict):
494 """Transform the openstack format (Port Pair Group) to mano format (SF)
495 sf_list_dict can be a list of dict or a single dict
496 """
497 if isinstance(sf_list_dict, dict):
498 sf_list_ = [sf_list_dict]
499 elif isinstance(sf_list_dict, list):
500 sf_list_ = sf_list_dict
501 else:
sousaedu80135b92021-02-17 15:05:18 +0100502 raise TypeError("param sf_list_dict must be a list or a dictionary")
503
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000504 for sf in sf_list_:
sousaedu80135b92021-02-17 15:05:18 +0100505 del sf["port_pair_group_parameters"]
506 sf["sfis"] = sf["port_pairs"]
507 del sf["port_pairs"]
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000508
509 def __sfp_os2mano(self, sfp_list_dict):
510 """Transform the openstack format (Port Chain) to mano format (SFP)
511 sfp_list_dict can be a list of dict or a single dict
512 """
513 if isinstance(sfp_list_dict, dict):
514 sfp_list_ = [sfp_list_dict]
515 elif isinstance(sfp_list_dict, list):
516 sfp_list_ = sfp_list_dict
517 else:
sousaedu80135b92021-02-17 15:05:18 +0100518 raise TypeError("param sfp_list_dict must be a list or a dictionary")
519
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000520 for sfp in sfp_list_:
sousaedu80135b92021-02-17 15:05:18 +0100521 params = sfp.pop("chain_parameters")
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000522 sfc_encap = False
sousaedu80135b92021-02-17 15:05:18 +0100523
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000524 if params:
sousaedu80135b92021-02-17 15:05:18 +0100525 correlation = params.get("correlation")
526
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000527 if correlation:
528 sfc_encap = True
sousaedu80135b92021-02-17 15:05:18 +0100529
530 sfp["sfc_encap"] = sfc_encap
531 sfp["spi"] = sfp.pop("chain_id")
532 sfp["classifications"] = sfp.pop("flow_classifiers")
533 sfp["service_functions"] = sfp.pop("port_pair_groups")
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +0000534
535 # placeholder for now; read TODO note below
536 def _validate_classification(self, type, definition):
537 # only legacy_flow_classifier Type is supported at this point
538 return True
539 # TODO(igordcard): this method should be an abstract method of an
540 # abstract Classification class to be implemented by the specific
541 # Types. Also, abstract vimconnector should call the validation
542 # method before the implemented VIM connectors are called.
543
tiernoae4a8d12016-07-08 12:30:39 +0200544 def _format_exception(self, exception):
tierno69647792020-03-05 16:45:48 +0000545 """Transform a keystone, nova, neutron exception into a vimconn exception discovering the cause"""
tierno69647792020-03-05 16:45:48 +0000546 message_error = str(exception)
tierno5ad826a2020-08-11 11:19:44 +0000547 tip = ""
tiernode12f782019-04-05 12:46:42 +0000548
sousaedu80135b92021-02-17 15:05:18 +0100549 if isinstance(
550 exception,
551 (
552 neExceptions.NetworkNotFoundClient,
553 nvExceptions.NotFound,
554 ksExceptions.NotFound,
555 gl1Exceptions.HTTPNotFound,
556 ),
557 ):
558 raise vimconn.VimConnNotFoundException(
559 type(exception).__name__ + ": " + message_error
560 )
561 elif isinstance(
562 exception,
563 (
564 HTTPException,
565 gl1Exceptions.HTTPException,
566 gl1Exceptions.CommunicationError,
567 ConnectionError,
568 ksExceptions.ConnectionError,
569 neExceptions.ConnectionFailed,
570 ),
571 ):
tierno5ad826a2020-08-11 11:19:44 +0000572 if type(exception).__name__ == "SSLError":
573 tip = " (maybe option 'insecure' must be added to the VIM)"
sousaedu80135b92021-02-17 15:05:18 +0100574
575 raise vimconn.VimConnConnectionException(
576 "Invalid URL or credentials{}: {}".format(tip, message_error)
577 )
578 elif isinstance(
579 exception,
580 (
581 KeyError,
582 nvExceptions.BadRequest,
583 ksExceptions.BadRequest,
584 ),
585 ):
Patricia Reinoso17852162023-06-15 07:33:04 +0000586 if message_error == "OS-EXT-SRV-ATTR:host":
587 tip = " (If the user does not have non-admin credentials, this attribute will be missing)"
588 raise vimconn.VimConnInsufficientCredentials(
589 type(exception).__name__ + ": " + message_error + tip
590 )
sousaedu80135b92021-02-17 15:05:18 +0100591 raise vimconn.VimConnException(
592 type(exception).__name__ + ": " + message_error
593 )
Patricia Reinoso17852162023-06-15 07:33:04 +0000594
sousaedu80135b92021-02-17 15:05:18 +0100595 elif isinstance(
596 exception,
597 (
598 nvExceptions.ClientException,
599 ksExceptions.ClientException,
600 neExceptions.NeutronException,
601 ),
602 ):
603 raise vimconn.VimConnUnexpectedResponse(
604 type(exception).__name__ + ": " + message_error
605 )
tiernoae4a8d12016-07-08 12:30:39 +0200606 elif isinstance(exception, nvExceptions.Conflict):
sousaedu80135b92021-02-17 15:05:18 +0100607 raise vimconn.VimConnConflictException(
608 type(exception).__name__ + ": " + message_error
609 )
tierno72774862020-05-04 11:44:15 +0000610 elif isinstance(exception, vimconn.VimConnException):
tierno41a69812018-02-16 14:34:33 +0100611 raise exception
tiernof716aea2017-06-21 18:01:40 +0200612 else: # ()
tiernode12f782019-04-05 12:46:42 +0000613 self.logger.error("General Exception " + message_error, exc_info=True)
sousaedu80135b92021-02-17 15:05:18 +0100614
615 raise vimconn.VimConnConnectionException(
616 type(exception).__name__ + ": " + message_error
617 )
tiernoae4a8d12016-07-08 12:30:39 +0200618
tiernoa05b65a2019-02-01 12:30:27 +0000619 def _get_ids_from_name(self):
620 """
621 Obtain ids from name of tenant and security_groups. Store at self .security_groups_id"
622 :return: None
623 """
624 # get tenant_id if only tenant_name is supplied
625 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +0100626
tiernoa05b65a2019-02-01 12:30:27 +0000627 if not self.my_tenant_id:
sousaedu80135b92021-02-17 15:05:18 +0100628 raise vimconn.VimConnConnectionException(
629 "Error getting tenant information from name={} id={}".format(
630 self.tenant_name, self.tenant_id
631 )
632 )
633
634 if self.config.get("security_groups") and not self.security_groups_id:
tiernoa05b65a2019-02-01 12:30:27 +0000635 # convert from name to id
sousaedu80135b92021-02-17 15:05:18 +0100636 neutron_sg_list = self.neutron.list_security_groups(
637 tenant_id=self.my_tenant_id
638 )["security_groups"]
tiernoa05b65a2019-02-01 12:30:27 +0000639
640 self.security_groups_id = []
sousaedu80135b92021-02-17 15:05:18 +0100641 for sg in self.config.get("security_groups"):
tiernoa05b65a2019-02-01 12:30:27 +0000642 for neutron_sg in neutron_sg_list:
643 if sg in (neutron_sg["id"], neutron_sg["name"]):
644 self.security_groups_id.append(neutron_sg["id"])
645 break
646 else:
647 self.security_groups_id = None
sousaedu80135b92021-02-17 15:05:18 +0100648
649 raise vimconn.VimConnConnectionException(
650 "Not found security group {} for this tenant".format(sg)
651 )
tiernoa05b65a2019-02-01 12:30:27 +0000652
vegallc53829d2023-06-01 00:47:44 -0500653 def _find_nova_server(self, vm_id):
654 """
655 Returns the VM instance from Openstack and completes it with flavor ID
656 Do not call nova.servers.find directly, as it does not return flavor ID with microversion>=2.47
657 """
658 try:
659 self._reload_connection()
660 server = self.nova.servers.find(id=vm_id)
661 # TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
662 server_dict = server.to_dict()
663 try:
Luis Vega6bb1afe2023-07-26 20:49:12 +0000664 if server_dict["flavor"].get("original_name"):
665 server_dict["flavor"]["id"] = self.nova.flavors.find(
666 name=server_dict["flavor"]["original_name"]
667 ).id
vegallc53829d2023-06-01 00:47:44 -0500668 except nClient.exceptions.NotFound as e:
669 self.logger.warning(str(e.message))
670 return server_dict
671 except (
672 ksExceptions.ClientException,
673 nvExceptions.ClientException,
674 nvExceptions.NotFound,
675 ConnectionError,
676 ) as e:
677 self._format_exception(e)
678
tierno5509c2e2019-07-04 16:23:20 +0000679 def check_vim_connectivity(self):
680 # just get network list to check connectivity and credentials
681 self.get_network_list(filter_dict={})
682
tiernoae4a8d12016-07-08 12:30:39 +0200683 def get_tenant_list(self, filter_dict={}):
tierno1ec592d2020-06-16 15:29:47 +0000684 """Obtain tenants of VIM
tiernoae4a8d12016-07-08 12:30:39 +0200685 filter_dict can contain the following keys:
686 name: filter by tenant name
687 id: filter by tenant uuid/id
688 <other VIM specific>
689 Returns the tenant list of dictionaries: [{'name':'<name>, 'id':'<id>, ...}, ...]
tierno1ec592d2020-06-16 15:29:47 +0000690 """
ahmadsa95baa272016-11-30 09:14:11 +0500691 self.logger.debug("Getting tenants from VIM filter: '%s'", str(filter_dict))
sousaedu80135b92021-02-17 15:05:18 +0100692
tiernoae4a8d12016-07-08 12:30:39 +0200693 try:
694 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +0100695
tiernof716aea2017-06-21 18:01:40 +0200696 if self.api_version3:
sousaedu80135b92021-02-17 15:05:18 +0100697 project_class_list = self.keystone.projects.list(
698 name=filter_dict.get("name")
699 )
ahmadsa95baa272016-11-30 09:14:11 +0500700 else:
tiernof716aea2017-06-21 18:01:40 +0200701 project_class_list = self.keystone.tenants.findall(**filter_dict)
sousaedu80135b92021-02-17 15:05:18 +0100702
tierno1ec592d2020-06-16 15:29:47 +0000703 project_list = []
sousaedu80135b92021-02-17 15:05:18 +0100704
ahmadsa95baa272016-11-30 09:14:11 +0500705 for project in project_class_list:
sousaedu80135b92021-02-17 15:05:18 +0100706 if filter_dict.get("id") and filter_dict["id"] != project.id:
tiernof716aea2017-06-21 18:01:40 +0200707 continue
sousaedu80135b92021-02-17 15:05:18 +0100708
ahmadsa95baa272016-11-30 09:14:11 +0500709 project_list.append(project.to_dict())
sousaedu80135b92021-02-17 15:05:18 +0100710
ahmadsa95baa272016-11-30 09:14:11 +0500711 return project_list
sousaedu80135b92021-02-17 15:05:18 +0100712 except (
713 ksExceptions.ConnectionError,
714 ksExceptions.ClientException,
715 ConnectionError,
716 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200717 self._format_exception(e)
718
719 def new_tenant(self, tenant_name, tenant_description):
tierno1ec592d2020-06-16 15:29:47 +0000720 """Adds a new tenant to openstack VIM. Returns the tenant identifier"""
tiernoae4a8d12016-07-08 12:30:39 +0200721 self.logger.debug("Adding a new tenant name: %s", tenant_name)
sousaedu80135b92021-02-17 15:05:18 +0100722
tiernoae4a8d12016-07-08 12:30:39 +0200723 try:
724 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +0100725
tiernof716aea2017-06-21 18:01:40 +0200726 if self.api_version3:
sousaedu80135b92021-02-17 15:05:18 +0100727 project = self.keystone.projects.create(
728 tenant_name,
729 self.config.get("project_domain_id", "default"),
730 description=tenant_description,
731 is_domain=False,
732 )
ahmadsa95baa272016-11-30 09:14:11 +0500733 else:
tiernof716aea2017-06-21 18:01:40 +0200734 project = self.keystone.tenants.create(tenant_name, tenant_description)
sousaedu80135b92021-02-17 15:05:18 +0100735
ahmadsa95baa272016-11-30 09:14:11 +0500736 return project.id
sousaedu80135b92021-02-17 15:05:18 +0100737 except (
738 ksExceptions.ConnectionError,
739 ksExceptions.ClientException,
740 ksExceptions.BadRequest,
741 ConnectionError,
742 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200743 self._format_exception(e)
744
745 def delete_tenant(self, tenant_id):
tierno1ec592d2020-06-16 15:29:47 +0000746 """Delete a tenant from openstack VIM. Returns the old tenant identifier"""
tiernoae4a8d12016-07-08 12:30:39 +0200747 self.logger.debug("Deleting tenant %s from VIM", tenant_id)
sousaedu80135b92021-02-17 15:05:18 +0100748
tiernoae4a8d12016-07-08 12:30:39 +0200749 try:
750 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +0100751
tiernof716aea2017-06-21 18:01:40 +0200752 if self.api_version3:
ahmadsa95baa272016-11-30 09:14:11 +0500753 self.keystone.projects.delete(tenant_id)
754 else:
755 self.keystone.tenants.delete(tenant_id)
sousaedu80135b92021-02-17 15:05:18 +0100756
tiernoae4a8d12016-07-08 12:30:39 +0200757 return tenant_id
sousaedu80135b92021-02-17 15:05:18 +0100758 except (
759 ksExceptions.ConnectionError,
760 ksExceptions.ClientException,
761 ksExceptions.NotFound,
762 ConnectionError,
763 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +0200764 self._format_exception(e)
ahmadsa95baa272016-11-30 09:14:11 +0500765
sousaedu80135b92021-02-17 15:05:18 +0100766 def new_network(
767 self,
768 net_name,
769 net_type,
770 ip_profile=None,
771 shared=False,
772 provider_network_profile=None,
773 ):
garciadeblasebd66722019-01-31 16:01:31 +0000774 """Adds a tenant network to VIM
775 Params:
776 'net_name': name of the network
777 'net_type': one of:
778 'bridge': overlay isolated network
779 'data': underlay E-LAN network for Passthrough and SRIOV interfaces
780 'ptp': underlay E-LINE network for Passthrough and SRIOV interfaces.
781 'ip_profile': is a dict containing the IP parameters of the network
782 'ip_version': can be "IPv4" or "IPv6" (Currently only IPv4 is implemented)
783 'subnet_address': ip_prefix_schema, that is X.X.X.X/Y
784 'gateway_address': (Optional) ip_schema, that is X.X.X.X
785 'dns_address': (Optional) comma separated list of ip_schema, e.g. X.X.X.X[,X,X,X,X]
786 'dhcp_enabled': True or False
787 'dhcp_start_address': ip_schema, first IP to grant
788 'dhcp_count': number of IPs to grant.
789 'shared': if this network can be seen/use by other tenants/organization
garciadeblas4af0d542020-02-18 16:01:13 +0100790 'provider_network_profile': (optional) contains {segmentation-id: vlan, network-type: vlan|vxlan,
791 physical-network: physnet-label}
garciadeblasebd66722019-01-31 16:01:31 +0000792 Returns a tuple with the network identifier and created_items, or raises an exception on error
793 created_items can be None or a dictionary where this method can include key-values that will be passed to
794 the method delete_network. Can be used to store created segments, created l2gw connections, etc.
795 Format is vimconnector dependent, but do not use nested dictionaries and a value of None should be the same
796 as not present.
797 """
sousaedu80135b92021-02-17 15:05:18 +0100798 self.logger.debug(
799 "Adding a new network to VIM name '%s', type '%s'", net_name, net_type
800 )
garciadeblasebd66722019-01-31 16:01:31 +0000801 # self.logger.debug(">>>>>>>>>>>>>>>>>> IP profile %s", str(ip_profile))
kbsuba85c54d2019-10-17 16:30:32 +0000802
tierno7edb6752016-03-21 17:37:52 +0100803 try:
kbsuba85c54d2019-10-17 16:30:32 +0000804 vlan = None
sousaedu80135b92021-02-17 15:05:18 +0100805
kbsuba85c54d2019-10-17 16:30:32 +0000806 if provider_network_profile:
807 vlan = provider_network_profile.get("segmentation-id")
sousaedu80135b92021-02-17 15:05:18 +0100808
garciadeblasedca7b32016-09-29 14:01:52 +0000809 new_net = None
garciadeblasebd66722019-01-31 16:01:31 +0000810 created_items = {}
tierno7edb6752016-03-21 17:37:52 +0100811 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +0100812 network_dict = {"name": net_name, "admin_state_up": True}
813
Gabriel Cuba0d8ce072022-12-14 18:33:50 -0500814 if net_type in ("data", "ptp") or provider_network_profile:
tierno6869ae72020-01-09 17:37:34 +0000815 provider_physical_network = None
sousaedu80135b92021-02-17 15:05:18 +0100816
817 if provider_network_profile and provider_network_profile.get(
818 "physical-network"
819 ):
820 provider_physical_network = provider_network_profile.get(
821 "physical-network"
822 )
823
tierno6869ae72020-01-09 17:37:34 +0000824 # provider-network must be one of the dataplane_physcial_netowrk if this is a list. If it is string
825 # or not declared, just ignore the checking
sousaedu80135b92021-02-17 15:05:18 +0100826 if (
827 isinstance(
828 self.config.get("dataplane_physical_net"), (tuple, list)
829 )
830 and provider_physical_network
831 not in self.config["dataplane_physical_net"]
832 ):
tierno72774862020-05-04 11:44:15 +0000833 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +0100834 "Invalid parameter 'provider-network:physical-network' "
835 "for network creation. '{}' is not one of the declared "
836 "list at VIM_config:dataplane_physical_net".format(
837 provider_physical_network
838 )
839 )
840
841 # use the default dataplane_physical_net
842 if not provider_physical_network:
843 provider_physical_network = self.config.get(
844 "dataplane_physical_net"
845 )
846
tierno6869ae72020-01-09 17:37:34 +0000847 # 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 +0100848 if (
849 isinstance(provider_physical_network, (tuple, list))
850 and provider_physical_network
851 ):
tierno6869ae72020-01-09 17:37:34 +0000852 provider_physical_network = provider_physical_network[0]
853
854 if not provider_physical_network:
tierno5ad826a2020-08-11 11:19:44 +0000855 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +0100856 "missing information needed for underlay networks. Provide "
857 "'dataplane_physical_net' configuration at VIM or use the NS "
858 "instantiation parameter 'provider-network.physical-network'"
859 " for the VLD"
860 )
tierno6869ae72020-01-09 17:37:34 +0000861
sousaedu80135b92021-02-17 15:05:18 +0100862 if not self.config.get("multisegment_support"):
863 network_dict[
864 "provider:physical_network"
865 ] = provider_physical_network
866
867 if (
868 provider_network_profile
869 and "network-type" in provider_network_profile
870 ):
871 network_dict[
872 "provider:network_type"
873 ] = provider_network_profile["network-type"]
garciadeblas4af0d542020-02-18 16:01:13 +0100874 else:
sousaedu80135b92021-02-17 15:05:18 +0100875 network_dict["provider:network_type"] = self.config.get(
876 "dataplane_network_type", "vlan"
877 )
878
tierno6869ae72020-01-09 17:37:34 +0000879 if vlan:
880 network_dict["provider:segmentation_id"] = vlan
garciadeblasebd66722019-01-31 16:01:31 +0000881 else:
tierno6869ae72020-01-09 17:37:34 +0000882 # Multi-segment case
garciadeblasebd66722019-01-31 16:01:31 +0000883 segment_list = []
tierno6869ae72020-01-09 17:37:34 +0000884 segment1_dict = {
sousaedu80135b92021-02-17 15:05:18 +0100885 "provider:physical_network": "",
886 "provider:network_type": "vxlan",
tierno6869ae72020-01-09 17:37:34 +0000887 }
garciadeblasebd66722019-01-31 16:01:31 +0000888 segment_list.append(segment1_dict)
tierno6869ae72020-01-09 17:37:34 +0000889 segment2_dict = {
890 "provider:physical_network": provider_physical_network,
sousaedu80135b92021-02-17 15:05:18 +0100891 "provider:network_type": "vlan",
tierno6869ae72020-01-09 17:37:34 +0000892 }
sousaedu80135b92021-02-17 15:05:18 +0100893
tierno6869ae72020-01-09 17:37:34 +0000894 if vlan:
895 segment2_dict["provider:segmentation_id"] = vlan
sousaedu80135b92021-02-17 15:05:18 +0100896 elif self.config.get("multisegment_vlan_range"):
garciadeblasebd66722019-01-31 16:01:31 +0000897 vlanID = self._generate_multisegment_vlanID()
898 segment2_dict["provider:segmentation_id"] = vlanID
sousaedu80135b92021-02-17 15:05:18 +0100899
garciadeblasebd66722019-01-31 16:01:31 +0000900 # else
tierno72774862020-05-04 11:44:15 +0000901 # raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +0100902 # "You must provide "multisegment_vlan_range" at config dict before creating a multisegment
tierno1ec592d2020-06-16 15:29:47 +0000903 # network")
garciadeblasebd66722019-01-31 16:01:31 +0000904 segment_list.append(segment2_dict)
905 network_dict["segments"] = segment_list
kate721d79b2017-06-24 04:21:38 -0700906
tierno6869ae72020-01-09 17:37:34 +0000907 # VIO Specific Changes. It needs a concrete VLAN
908 if self.vim_type == "VIO" and vlan is None:
sousaedu80135b92021-02-17 15:05:18 +0100909 if self.config.get("dataplane_net_vlan_range") is None:
tierno72774862020-05-04 11:44:15 +0000910 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +0100911 "You must provide 'dataplane_net_vlan_range' in format "
912 "[start_ID - end_ID] at VIM_config for creating underlay "
913 "networks"
914 )
915
tierno6869ae72020-01-09 17:37:34 +0000916 network_dict["provider:segmentation_id"] = self._generate_vlanID()
kate721d79b2017-06-24 04:21:38 -0700917
garciadeblasebd66722019-01-31 16:01:31 +0000918 network_dict["shared"] = shared
sousaedu80135b92021-02-17 15:05:18 +0100919
anwarsff168192019-05-06 11:23:07 +0530920 if self.config.get("disable_network_port_security"):
921 network_dict["port_security_enabled"] = False
sousaedu80135b92021-02-17 15:05:18 +0100922
sousaedu2aa5f802021-06-17 15:39:29 +0100923 if self.config.get("neutron_availability_zone_hints"):
924 hints = self.config.get("neutron_availability_zone_hints")
925
926 if isinstance(hints, str):
927 hints = [hints]
928
929 network_dict["availability_zone_hints"] = hints
930
sousaedu80135b92021-02-17 15:05:18 +0100931 new_net = self.neutron.create_network({"network": network_dict})
garciadeblasebd66722019-01-31 16:01:31 +0000932 # print new_net
933 # create subnetwork, even if there is no profile
sousaedu80135b92021-02-17 15:05:18 +0100934
garciadeblas9f8456e2016-09-05 05:02:59 +0200935 if not ip_profile:
936 ip_profile = {}
sousaedu80135b92021-02-17 15:05:18 +0100937
938 if not ip_profile.get("subnet_address"):
tierno1ec592d2020-06-16 15:29:47 +0000939 # Fake subnet is required
elumalai51e72a02023-04-28 19:41:49 +0530940 subnet_rand = random.SystemRandom().randint(0, 255)
sousaedu80135b92021-02-17 15:05:18 +0100941 ip_profile["subnet_address"] = "192.168.{}.0/24".format(subnet_rand)
942
943 if "ip_version" not in ip_profile:
944 ip_profile["ip_version"] = "IPv4"
945
946 subnet = {
947 "name": net_name + "-subnet",
948 "network_id": new_net["network"]["id"],
949 "ip_version": 4 if ip_profile["ip_version"] == "IPv4" else 6,
950 "cidr": ip_profile["subnet_address"],
951 }
952
tiernoa1fb4462017-06-30 12:25:50 +0200953 # Gateway should be set to None if not needed. Otherwise openstack assigns one by default
sousaedu80135b92021-02-17 15:05:18 +0100954 if ip_profile.get("gateway_address"):
955 subnet["gateway_ip"] = ip_profile["gateway_address"]
tierno55d234c2018-07-04 18:29:21 +0200956 else:
sousaedu80135b92021-02-17 15:05:18 +0100957 subnet["gateway_ip"] = None
958
959 if ip_profile.get("dns_address"):
960 subnet["dns_nameservers"] = ip_profile["dns_address"].split(";")
961
962 if "dhcp_enabled" in ip_profile:
963 subnet["enable_dhcp"] = (
964 False
965 if ip_profile["dhcp_enabled"] == "false"
966 or ip_profile["dhcp_enabled"] is False
967 else True
968 )
969
970 if ip_profile.get("dhcp_start_address"):
971 subnet["allocation_pools"] = []
972 subnet["allocation_pools"].append(dict())
973 subnet["allocation_pools"][0]["start"] = ip_profile[
974 "dhcp_start_address"
975 ]
976
977 if ip_profile.get("dhcp_count"):
978 # parts = ip_profile["dhcp_start_address"].split(".")
tierno1ec592d2020-06-16 15:29:47 +0000979 # ip_int = (int(parts[0]) << 24) + (int(parts[1]) << 16) + (int(parts[2]) << 8) + int(parts[3])
sousaedu80135b92021-02-17 15:05:18 +0100980 ip_int = int(netaddr.IPAddress(ip_profile["dhcp_start_address"]))
981 ip_int += ip_profile["dhcp_count"] - 1
garciadeblas9f8456e2016-09-05 05:02:59 +0200982 ip_str = str(netaddr.IPAddress(ip_int))
sousaedu80135b92021-02-17 15:05:18 +0100983 subnet["allocation_pools"][0]["end"] = ip_str
984
Gabriel Cubab3dbfca2023-03-14 10:58:39 -0500985 if (
986 ip_profile.get("ipv6_address_mode")
987 and ip_profile["ip_version"] != "IPv4"
988 ):
989 subnet["ipv6_address_mode"] = ip_profile["ipv6_address_mode"]
990 # ipv6_ra_mode can be set to the same value for most use cases, see documentation:
991 # https://docs.openstack.org/neutron/latest/admin/config-ipv6.html#ipv6-ra-mode-and-ipv6-address-mode-combinations
992 subnet["ipv6_ra_mode"] = ip_profile["ipv6_address_mode"]
993
tierno1ec592d2020-06-16 15:29:47 +0000994 # self.logger.debug(">>>>>>>>>>>>>>>>>> Subnet: %s", str(subnet))
995 self.neutron.create_subnet({"subnet": subnet})
garciadeblasebd66722019-01-31 16:01:31 +0000996
sousaedu80135b92021-02-17 15:05:18 +0100997 if net_type == "data" and self.config.get("multisegment_support"):
998 if self.config.get("l2gw_support"):
garciadeblasebd66722019-01-31 16:01:31 +0000999 l2gw_list = self.neutron.list_l2_gateways().get("l2_gateways", ())
1000 for l2gw in l2gw_list:
tierno1ec592d2020-06-16 15:29:47 +00001001 l2gw_conn = {
1002 "l2_gateway_id": l2gw["id"],
1003 "network_id": new_net["network"]["id"],
1004 "segmentation_id": str(vlanID),
1005 }
sousaedu80135b92021-02-17 15:05:18 +01001006 new_l2gw_conn = self.neutron.create_l2_gateway_connection(
1007 {"l2_gateway_connection": l2gw_conn}
1008 )
1009 created_items[
1010 "l2gwconn:"
1011 + str(new_l2gw_conn["l2_gateway_connection"]["id"])
1012 ] = True
1013
garciadeblasebd66722019-01-31 16:01:31 +00001014 return new_net["network"]["id"], created_items
tierno41a69812018-02-16 14:34:33 +01001015 except Exception as e:
tierno1ec592d2020-06-16 15:29:47 +00001016 # delete l2gw connections (if any) before deleting the network
garciadeblasebd66722019-01-31 16:01:31 +00001017 for k, v in created_items.items():
1018 if not v: # skip already deleted
1019 continue
sousaedu80135b92021-02-17 15:05:18 +01001020
garciadeblasebd66722019-01-31 16:01:31 +00001021 try:
1022 k_item, _, k_id = k.partition(":")
sousaedu80135b92021-02-17 15:05:18 +01001023
garciadeblasebd66722019-01-31 16:01:31 +00001024 if k_item == "l2gwconn":
1025 self.neutron.delete_l2_gateway_connection(k_id)
1026 except Exception as e2:
sousaedu80135b92021-02-17 15:05:18 +01001027 self.logger.error(
1028 "Error deleting l2 gateway connection: {}: {}".format(
1029 type(e2).__name__, e2
1030 )
1031 )
1032
garciadeblasedca7b32016-09-29 14:01:52 +00001033 if new_net:
sousaedu80135b92021-02-17 15:05:18 +01001034 self.neutron.delete_network(new_net["network"]["id"])
1035
tiernoae4a8d12016-07-08 12:30:39 +02001036 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001037
1038 def get_network_list(self, filter_dict={}):
tierno1ec592d2020-06-16 15:29:47 +00001039 """Obtain tenant networks of VIM
tierno7edb6752016-03-21 17:37:52 +01001040 Filter_dict can be:
1041 name: network name
1042 id: network uuid
1043 shared: boolean
1044 tenant_id: tenant
1045 admin_state_up: boolean
1046 status: 'ACTIVE'
1047 Returns the network list of dictionaries
tierno1ec592d2020-06-16 15:29:47 +00001048 """
tiernoae4a8d12016-07-08 12:30:39 +02001049 self.logger.debug("Getting network from VIM filter: '%s'", str(filter_dict))
sousaedu80135b92021-02-17 15:05:18 +01001050
tierno7edb6752016-03-21 17:37:52 +01001051 try:
1052 self._reload_connection()
tierno69b590e2018-03-13 18:52:23 +01001053 filter_dict_os = filter_dict.copy()
sousaedu80135b92021-02-17 15:05:18 +01001054
tierno69b590e2018-03-13 18:52:23 +01001055 if self.api_version3 and "tenant_id" in filter_dict_os:
sousaedu80135b92021-02-17 15:05:18 +01001056 # TODO check
1057 filter_dict_os["project_id"] = filter_dict_os.pop("tenant_id")
1058
tierno69b590e2018-03-13 18:52:23 +01001059 net_dict = self.neutron.list_networks(**filter_dict_os)
tierno00e3df72017-11-29 17:20:13 +01001060 net_list = net_dict["networks"]
tierno7edb6752016-03-21 17:37:52 +01001061 self.__net_os2mano(net_list)
sousaedu80135b92021-02-17 15:05:18 +01001062
tiernoae4a8d12016-07-08 12:30:39 +02001063 return net_list
sousaedu80135b92021-02-17 15:05:18 +01001064 except (
1065 neExceptions.ConnectionFailed,
1066 ksExceptions.ClientException,
1067 neExceptions.NeutronException,
1068 ConnectionError,
1069 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001070 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001071
tiernoae4a8d12016-07-08 12:30:39 +02001072 def get_network(self, net_id):
tierno1ec592d2020-06-16 15:29:47 +00001073 """Obtain details of network from VIM
1074 Returns the network information from a network id"""
tiernoae4a8d12016-07-08 12:30:39 +02001075 self.logger.debug(" Getting tenant network %s from VIM", net_id)
tierno1ec592d2020-06-16 15:29:47 +00001076 filter_dict = {"id": net_id}
tiernoae4a8d12016-07-08 12:30:39 +02001077 net_list = self.get_network_list(filter_dict)
sousaedu80135b92021-02-17 15:05:18 +01001078
tierno1ec592d2020-06-16 15:29:47 +00001079 if len(net_list) == 0:
sousaedu80135b92021-02-17 15:05:18 +01001080 raise vimconn.VimConnNotFoundException(
1081 "Network '{}' not found".format(net_id)
1082 )
tierno1ec592d2020-06-16 15:29:47 +00001083 elif len(net_list) > 1:
sousaedu80135b92021-02-17 15:05:18 +01001084 raise vimconn.VimConnConflictException(
1085 "Found more than one network with this criteria"
1086 )
1087
tierno7edb6752016-03-21 17:37:52 +01001088 net = net_list[0]
tierno1ec592d2020-06-16 15:29:47 +00001089 subnets = []
1090 for subnet_id in net.get("subnets", ()):
tierno7edb6752016-03-21 17:37:52 +01001091 try:
1092 subnet = self.neutron.show_subnet(subnet_id)
1093 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01001094 self.logger.error(
1095 "osconnector.get_network(): Error getting subnet %s %s"
1096 % (net_id, str(e))
1097 )
tiernoae4a8d12016-07-08 12:30:39 +02001098 subnet = {"id": subnet_id, "fault": str(e)}
sousaedu80135b92021-02-17 15:05:18 +01001099
tierno7edb6752016-03-21 17:37:52 +01001100 subnets.append(subnet)
sousaedu80135b92021-02-17 15:05:18 +01001101
tierno7edb6752016-03-21 17:37:52 +01001102 net["subnets"] = subnets
sousaedu80135b92021-02-17 15:05:18 +01001103 net["encapsulation"] = net.get("provider:network_type")
1104 net["encapsulation_type"] = net.get("provider:network_type")
1105 net["segmentation_id"] = net.get("provider:segmentation_id")
1106 net["encapsulation_id"] = net.get("provider:segmentation_id")
1107
tiernoae4a8d12016-07-08 12:30:39 +02001108 return net
tierno7edb6752016-03-21 17:37:52 +01001109
garciadeblasebd66722019-01-31 16:01:31 +00001110 def delete_network(self, net_id, created_items=None):
1111 """
1112 Removes a tenant network from VIM and its associated elements
1113 :param net_id: VIM identifier of the network, provided by method new_network
1114 :param created_items: dictionary with extra items to be deleted. provided by method new_network
1115 Returns the network identifier or raises an exception upon error or when network is not found
1116 """
tiernoae4a8d12016-07-08 12:30:39 +02001117 self.logger.debug("Deleting network '%s' from VIM", net_id)
sousaedu80135b92021-02-17 15:05:18 +01001118
tierno1ec592d2020-06-16 15:29:47 +00001119 if created_items is None:
garciadeblasebd66722019-01-31 16:01:31 +00001120 created_items = {}
sousaedu80135b92021-02-17 15:05:18 +01001121
tierno7edb6752016-03-21 17:37:52 +01001122 try:
1123 self._reload_connection()
tierno1ec592d2020-06-16 15:29:47 +00001124 # delete l2gw connections (if any) before deleting the network
garciadeblasebd66722019-01-31 16:01:31 +00001125 for k, v in created_items.items():
1126 if not v: # skip already deleted
1127 continue
sousaedu80135b92021-02-17 15:05:18 +01001128
garciadeblasebd66722019-01-31 16:01:31 +00001129 try:
1130 k_item, _, k_id = k.partition(":")
1131 if k_item == "l2gwconn":
1132 self.neutron.delete_l2_gateway_connection(k_id)
1133 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01001134 self.logger.error(
1135 "Error deleting l2 gateway connection: {}: {}".format(
1136 type(e).__name__, e
1137 )
1138 )
1139
tierno1ec592d2020-06-16 15:29:47 +00001140 # delete VM ports attached to this networks before the network
tierno7edb6752016-03-21 17:37:52 +01001141 ports = self.neutron.list_ports(network_id=net_id)
sousaedu80135b92021-02-17 15:05:18 +01001142 for p in ports["ports"]:
tierno7edb6752016-03-21 17:37:52 +01001143 try:
1144 self.neutron.delete_port(p["id"])
1145 except Exception as e:
tiernoae4a8d12016-07-08 12:30:39 +02001146 self.logger.error("Error deleting port %s: %s", p["id"], str(e))
sousaedu80135b92021-02-17 15:05:18 +01001147
tierno7edb6752016-03-21 17:37:52 +01001148 self.neutron.delete_network(net_id)
sousaedu80135b92021-02-17 15:05:18 +01001149
tiernoae4a8d12016-07-08 12:30:39 +02001150 return net_id
sousaedu80135b92021-02-17 15:05:18 +01001151 except (
1152 neExceptions.ConnectionFailed,
1153 neExceptions.NetworkNotFoundClient,
1154 neExceptions.NeutronException,
1155 ksExceptions.ClientException,
1156 neExceptions.NeutronException,
1157 ConnectionError,
1158 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001159 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001160
tiernoae4a8d12016-07-08 12:30:39 +02001161 def refresh_nets_status(self, net_list):
tierno1ec592d2020-06-16 15:29:47 +00001162 """Get the status of the networks
sousaedu80135b92021-02-17 15:05:18 +01001163 Params: the list of network identifiers
1164 Returns a dictionary with:
1165 net_id: #VIM id of this network
1166 status: #Mandatory. Text with one of:
1167 # DELETED (not found at vim)
1168 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
1169 # OTHER (Vim reported other status not understood)
1170 # ERROR (VIM indicates an ERROR status)
1171 # ACTIVE, INACTIVE, DOWN (admin down),
1172 # BUILD (on building process)
1173 #
1174 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
1175 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
tierno1ec592d2020-06-16 15:29:47 +00001176 """
1177 net_dict = {}
sousaedu80135b92021-02-17 15:05:18 +01001178
tiernoae4a8d12016-07-08 12:30:39 +02001179 for net_id in net_list:
1180 net = {}
sousaedu80135b92021-02-17 15:05:18 +01001181
tiernoae4a8d12016-07-08 12:30:39 +02001182 try:
1183 net_vim = self.get_network(net_id)
sousaedu80135b92021-02-17 15:05:18 +01001184
1185 if net_vim["status"] in netStatus2manoFormat:
1186 net["status"] = netStatus2manoFormat[net_vim["status"]]
tiernoae4a8d12016-07-08 12:30:39 +02001187 else:
1188 net["status"] = "OTHER"
sousaedu80135b92021-02-17 15:05:18 +01001189 net["error_msg"] = "VIM status reported " + net_vim["status"]
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001190
sousaedu80135b92021-02-17 15:05:18 +01001191 if net["status"] == "ACTIVE" and not net_vim["admin_state_up"]:
1192 net["status"] = "DOWN"
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001193
sousaedu80135b92021-02-17 15:05:18 +01001194 net["vim_info"] = self.serialize(net_vim)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001195
sousaedu80135b92021-02-17 15:05:18 +01001196 if net_vim.get("fault"): # TODO
1197 net["error_msg"] = str(net_vim["fault"])
tierno72774862020-05-04 11:44:15 +00001198 except vimconn.VimConnNotFoundException as e:
tiernoae4a8d12016-07-08 12:30:39 +02001199 self.logger.error("Exception getting net status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01001200 net["status"] = "DELETED"
1201 net["error_msg"] = str(e)
tierno72774862020-05-04 11:44:15 +00001202 except vimconn.VimConnException as e:
tiernoae4a8d12016-07-08 12:30:39 +02001203 self.logger.error("Exception getting net status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01001204 net["status"] = "VIM_ERROR"
1205 net["error_msg"] = str(e)
tiernoae4a8d12016-07-08 12:30:39 +02001206 net_dict[net_id] = net
1207 return net_dict
1208
1209 def get_flavor(self, flavor_id):
tierno1ec592d2020-06-16 15:29:47 +00001210 """Obtain flavor details from the VIM. Returns the flavor dict details"""
tiernoae4a8d12016-07-08 12:30:39 +02001211 self.logger.debug("Getting flavor '%s'", flavor_id)
sousaedu80135b92021-02-17 15:05:18 +01001212
tierno7edb6752016-03-21 17:37:52 +01001213 try:
1214 self._reload_connection()
1215 flavor = self.nova.flavors.find(id=flavor_id)
tierno1ec592d2020-06-16 15:29:47 +00001216 # TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
sousaedu80135b92021-02-17 15:05:18 +01001217
tiernoae4a8d12016-07-08 12:30:39 +02001218 return flavor.to_dict()
sousaedu80135b92021-02-17 15:05:18 +01001219 except (
1220 nvExceptions.NotFound,
1221 nvExceptions.ClientException,
1222 ksExceptions.ClientException,
1223 ConnectionError,
1224 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001225 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001226
tiernocf157a82017-01-30 14:07:06 +01001227 def get_flavor_id_from_data(self, flavor_dict):
1228 """Obtain flavor id that match the flavor description
sousaedu80135b92021-02-17 15:05:18 +01001229 Returns the flavor_id or raises a vimconnNotFoundException
1230 flavor_dict: contains the required ram, vcpus, disk
1231 If 'use_existing_flavors' is set to True at config, the closer flavor that provides same or more ram, vcpus
1232 and disk is returned. Otherwise a flavor with exactly same ram, vcpus and disk is returned or a
1233 vimconnNotFoundException is raised
tiernocf157a82017-01-30 14:07:06 +01001234 """
sousaedu80135b92021-02-17 15:05:18 +01001235 exact_match = False if self.config.get("use_existing_flavors") else True
1236
tiernocf157a82017-01-30 14:07:06 +01001237 try:
1238 self._reload_connection()
tiernoe26fc7a2017-05-30 14:43:03 +02001239 flavor_candidate_id = None
1240 flavor_candidate_data = (10000, 10000, 10000)
sousaedu80135b92021-02-17 15:05:18 +01001241 flavor_target = (
1242 flavor_dict["ram"],
1243 flavor_dict["vcpus"],
1244 flavor_dict["disk"],
sousaedu648ee3d2021-11-22 14:09:15 +00001245 flavor_dict.get("ephemeral", 0),
1246 flavor_dict.get("swap", 0),
sousaedu80135b92021-02-17 15:05:18 +01001247 )
tiernoe26fc7a2017-05-30 14:43:03 +02001248 # numa=None
anwarsae5f52c2019-04-22 10:35:27 +05301249 extended = flavor_dict.get("extended", {})
1250 if extended:
tierno1ec592d2020-06-16 15:29:47 +00001251 # TODO
sousaedu80135b92021-02-17 15:05:18 +01001252 raise vimconn.VimConnNotFoundException(
1253 "Flavor with EPA still not implemented"
1254 )
tiernocf157a82017-01-30 14:07:06 +01001255 # if len(numas) > 1:
tierno72774862020-05-04 11:44:15 +00001256 # raise vimconn.VimConnNotFoundException("Cannot find any flavor with more than one numa")
tiernocf157a82017-01-30 14:07:06 +01001257 # numa=numas[0]
1258 # numas = extended.get("numas")
1259 for flavor in self.nova.flavors.list():
1260 epa = flavor.get_keys()
sousaedu80135b92021-02-17 15:05:18 +01001261
tiernocf157a82017-01-30 14:07:06 +01001262 if epa:
1263 continue
tiernoe26fc7a2017-05-30 14:43:03 +02001264 # TODO
sousaedu80135b92021-02-17 15:05:18 +01001265
sousaedu648ee3d2021-11-22 14:09:15 +00001266 flavor_data = (
1267 flavor.ram,
1268 flavor.vcpus,
1269 flavor.disk,
1270 flavor.ephemeral,
preethika.pebaba1f2022-01-20 07:24:18 +00001271 flavor.swap if isinstance(flavor.swap, int) else 0,
sousaedu648ee3d2021-11-22 14:09:15 +00001272 )
tiernoe26fc7a2017-05-30 14:43:03 +02001273 if flavor_data == flavor_target:
1274 return flavor.id
sousaedu80135b92021-02-17 15:05:18 +01001275 elif (
1276 not exact_match
1277 and flavor_target < flavor_data < flavor_candidate_data
1278 ):
tiernoe26fc7a2017-05-30 14:43:03 +02001279 flavor_candidate_id = flavor.id
1280 flavor_candidate_data = flavor_data
sousaedu80135b92021-02-17 15:05:18 +01001281
tiernoe26fc7a2017-05-30 14:43:03 +02001282 if not exact_match and flavor_candidate_id:
1283 return flavor_candidate_id
sousaedu80135b92021-02-17 15:05:18 +01001284
1285 raise vimconn.VimConnNotFoundException(
1286 "Cannot find any flavor matching '{}'".format(flavor_dict)
1287 )
1288 except (
1289 nvExceptions.NotFound,
1290 nvExceptions.ClientException,
1291 ksExceptions.ClientException,
1292 ConnectionError,
1293 ) as e:
tiernocf157a82017-01-30 14:07:06 +01001294 self._format_exception(e)
1295
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001296 @staticmethod
1297 def process_resource_quota(quota: dict, prefix: str, extra_specs: dict) -> None:
1298 """Process resource quota and fill up extra_specs.
1299 Args:
1300 quota (dict): Keeping the quota of resurces
1301 prefix (str) Prefix
1302 extra_specs (dict) Dict to be filled to be used during flavor creation
1303
anwarsae5f52c2019-04-22 10:35:27 +05301304 """
sousaedu80135b92021-02-17 15:05:18 +01001305 if "limit" in quota:
1306 extra_specs["quota:" + prefix + "_limit"] = quota["limit"]
1307
1308 if "reserve" in quota:
1309 extra_specs["quota:" + prefix + "_reservation"] = quota["reserve"]
1310
1311 if "shares" in quota:
anwarsae5f52c2019-04-22 10:35:27 +05301312 extra_specs["quota:" + prefix + "_shares_level"] = "custom"
sousaedu80135b92021-02-17 15:05:18 +01001313 extra_specs["quota:" + prefix + "_shares_share"] = quota["shares"]
anwarsae5f52c2019-04-22 10:35:27 +05301314
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001315 @staticmethod
1316 def process_numa_memory(
1317 numa: dict, node_id: Optional[int], extra_specs: dict
1318 ) -> None:
1319 """Set the memory in extra_specs.
1320 Args:
1321 numa (dict): A dictionary which includes numa information
1322 node_id (int): ID of numa node
1323 extra_specs (dict): To be filled.
1324
1325 """
1326 if not numa.get("memory"):
1327 return
1328 memory_mb = numa["memory"] * 1024
1329 memory = "hw:numa_mem.{}".format(node_id)
1330 extra_specs[memory] = int(memory_mb)
1331
1332 @staticmethod
1333 def process_numa_vcpu(numa: dict, node_id: int, extra_specs: dict) -> None:
1334 """Set the cpu in extra_specs.
1335 Args:
1336 numa (dict): A dictionary which includes numa information
1337 node_id (int): ID of numa node
1338 extra_specs (dict): To be filled.
1339
1340 """
1341 if not numa.get("vcpu"):
1342 return
1343 vcpu = numa["vcpu"]
1344 cpu = "hw:numa_cpus.{}".format(node_id)
1345 vcpu = ",".join(map(str, vcpu))
1346 extra_specs[cpu] = vcpu
1347
1348 @staticmethod
1349 def process_numa_paired_threads(numa: dict, extra_specs: dict) -> Optional[int]:
1350 """Fill up extra_specs if numa has paired-threads.
1351 Args:
1352 numa (dict): A dictionary which includes numa information
1353 extra_specs (dict): To be filled.
1354
1355 Returns:
Gulsum Atici6a6e3342023-01-23 16:22:59 +03001356 threads (int) Number of virtual cpus
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001357
1358 """
1359 if not numa.get("paired-threads"):
1360 return
Gulsum Atici6a6e3342023-01-23 16:22:59 +03001361
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001362 # cpu_thread_policy "require" implies that compute node must have an STM architecture
Gulsum Atici6a6e3342023-01-23 16:22:59 +03001363 threads = numa["paired-threads"] * 2
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001364 extra_specs["hw:cpu_thread_policy"] = "require"
1365 extra_specs["hw:cpu_policy"] = "dedicated"
Gulsum Atici6a6e3342023-01-23 16:22:59 +03001366 return threads
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001367
1368 @staticmethod
1369 def process_numa_cores(numa: dict, extra_specs: dict) -> Optional[int]:
1370 """Fill up extra_specs if numa has cores.
1371 Args:
1372 numa (dict): A dictionary which includes numa information
1373 extra_specs (dict): To be filled.
1374
1375 Returns:
Gulsum Atici6a6e3342023-01-23 16:22:59 +03001376 cores (int) Number of virtual cpus
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001377
1378 """
1379 # cpu_thread_policy "isolate" implies that the host must not have an SMT
1380 # architecture, or a non-SMT architecture will be emulated
1381 if not numa.get("cores"):
1382 return
Gulsum Atici6a6e3342023-01-23 16:22:59 +03001383 cores = numa["cores"]
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001384 extra_specs["hw:cpu_thread_policy"] = "isolate"
1385 extra_specs["hw:cpu_policy"] = "dedicated"
Gulsum Atici6a6e3342023-01-23 16:22:59 +03001386 return cores
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001387
1388 @staticmethod
1389 def process_numa_threads(numa: dict, extra_specs: dict) -> Optional[int]:
1390 """Fill up extra_specs if numa has threads.
1391 Args:
1392 numa (dict): A dictionary which includes numa information
1393 extra_specs (dict): To be filled.
1394
1395 Returns:
Gulsum Atici6a6e3342023-01-23 16:22:59 +03001396 threads (int) Number of virtual cpus
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001397
1398 """
1399 # cpu_thread_policy "prefer" implies that the host may or may not have an SMT architecture
1400 if not numa.get("threads"):
1401 return
Gulsum Atici6a6e3342023-01-23 16:22:59 +03001402 threads = numa["threads"]
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001403 extra_specs["hw:cpu_thread_policy"] = "prefer"
1404 extra_specs["hw:cpu_policy"] = "dedicated"
Gulsum Atici6a6e3342023-01-23 16:22:59 +03001405 return threads
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001406
1407 def _process_numa_parameters_of_flavor(
Gulsum Atici6a6e3342023-01-23 16:22:59 +03001408 self, numas: List, extra_specs: Dict
1409 ) -> None:
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001410 """Process numa parameters and fill up extra_specs.
1411
1412 Args:
1413 numas (list): List of dictionary which includes numa information
1414 extra_specs (dict): To be filled.
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001415
1416 """
1417 numa_nodes = len(numas)
1418 extra_specs["hw:numa_nodes"] = str(numa_nodes)
Gulsum Atici6a6e3342023-01-23 16:22:59 +03001419 cpu_cores, cpu_threads = 0, 0
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001420
1421 if self.vim_type == "VIO":
Gulsum Aticid0571fe2022-11-14 13:06:06 +03001422 self.process_vio_numa_nodes(numa_nodes, extra_specs)
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001423
1424 for numa in numas:
1425 if "id" in numa:
1426 node_id = numa["id"]
1427 # overwrite ram and vcpus
1428 # check if key "memory" is present in numa else use ram value at flavor
1429 self.process_numa_memory(numa, node_id, extra_specs)
1430 self.process_numa_vcpu(numa, node_id, extra_specs)
1431
1432 # See for reference: https://specs.openstack.org/openstack/nova-specs/specs/mitaka/implemented/virt-driver-cpu-thread-pinning.html
1433 extra_specs["hw:cpu_sockets"] = str(numa_nodes)
1434
1435 if "paired-threads" in numa:
Gulsum Atici6a6e3342023-01-23 16:22:59 +03001436 threads = self.process_numa_paired_threads(numa, extra_specs)
1437 cpu_threads += threads
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001438
1439 elif "cores" in numa:
Gulsum Atici6a6e3342023-01-23 16:22:59 +03001440 cores = self.process_numa_cores(numa, extra_specs)
1441 cpu_cores += cores
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001442
1443 elif "threads" in numa:
Gulsum Atici6a6e3342023-01-23 16:22:59 +03001444 threads = self.process_numa_threads(numa, extra_specs)
1445 cpu_threads += threads
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001446
Gulsum Atici6a6e3342023-01-23 16:22:59 +03001447 if cpu_cores:
1448 extra_specs["hw:cpu_cores"] = str(cpu_cores)
1449 if cpu_threads:
1450 extra_specs["hw:cpu_threads"] = str(cpu_threads)
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001451
Gulsum Aticid0571fe2022-11-14 13:06:06 +03001452 @staticmethod
1453 def process_vio_numa_nodes(numa_nodes: int, extra_specs: Dict) -> None:
1454 """According to number of numa nodes, updates the extra_specs for VIO.
1455
1456 Args:
1457
1458 numa_nodes (int): List keeps the numa node numbers
1459 extra_specs (dict): Extra specs dict to be updated
1460
1461 """
Gulsum Aticid0571fe2022-11-14 13:06:06 +03001462 # If there are several numas, we do not define specific affinity.
1463 extra_specs["vmware:latency_sensitivity_level"] = "high"
1464
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001465 def _change_flavor_name(
1466 self, name: str, name_suffix: int, flavor_data: dict
1467 ) -> str:
1468 """Change the flavor name if the name already exists.
1469
1470 Args:
1471 name (str): Flavor name to be checked
1472 name_suffix (int): Suffix to be appended to name
1473 flavor_data (dict): Flavor dict
1474
1475 Returns:
1476 name (str): New flavor name to be used
1477
1478 """
1479 # Get used names
1480 fl = self.nova.flavors.list()
1481 fl_names = [f.name for f in fl]
1482
1483 while name in fl_names:
1484 name_suffix += 1
1485 name = flavor_data["name"] + "-" + str(name_suffix)
1486
1487 return name
1488
1489 def _process_extended_config_of_flavor(
Gulsum Atici6a6e3342023-01-23 16:22:59 +03001490 self, extended: dict, extra_specs: dict
1491 ) -> None:
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001492 """Process the extended dict to fill up extra_specs.
1493 Args:
1494
Gulsum Atici6a6e3342023-01-23 16:22:59 +03001495 extended (dict): Keeping the extra specification of flavor
1496 extra_specs (dict) Dict to be filled to be used during flavor creation
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001497
1498 """
1499 quotas = {
1500 "cpu-quota": "cpu",
1501 "mem-quota": "memory",
1502 "vif-quota": "vif",
1503 "disk-io-quota": "disk_io",
1504 }
1505
1506 page_sizes = {
1507 "LARGE": "large",
1508 "SMALL": "small",
1509 "SIZE_2MB": "2MB",
1510 "SIZE_1GB": "1GB",
1511 "PREFER_LARGE": "any",
1512 }
1513
1514 policies = {
1515 "cpu-pinning-policy": "hw:cpu_policy",
1516 "cpu-thread-pinning-policy": "hw:cpu_thread_policy",
1517 "mem-policy": "hw:numa_mempolicy",
1518 }
1519
1520 numas = extended.get("numas")
1521 if numas:
Gulsum Atici6a6e3342023-01-23 16:22:59 +03001522 self._process_numa_parameters_of_flavor(numas, extra_specs)
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001523
1524 for quota, item in quotas.items():
1525 if quota in extended.keys():
1526 self.process_resource_quota(extended.get(quota), item, extra_specs)
1527
1528 # Set the mempage size as specified in the descriptor
1529 if extended.get("mempage-size"):
1530 if extended["mempage-size"] in page_sizes.keys():
1531 extra_specs["hw:mem_page_size"] = page_sizes[extended["mempage-size"]]
1532 else:
1533 # Normally, validations in NBI should not allow to this condition.
1534 self.logger.debug(
1535 "Invalid mempage-size %s. Will be ignored",
1536 extended.get("mempage-size"),
1537 )
1538
1539 for policy, hw_policy in policies.items():
1540 if extended.get(policy):
1541 extra_specs[hw_policy] = extended[policy].lower()
1542
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001543 @staticmethod
1544 def _get_flavor_details(flavor_data: dict) -> Tuple:
1545 """Returns the details of flavor
1546 Args:
1547 flavor_data (dict): Dictionary that includes required flavor details
1548
1549 Returns:
1550 ram, vcpus, extra_specs, extended (tuple): Main items of required flavor
1551
1552 """
1553 return (
1554 flavor_data.get("ram", 64),
1555 flavor_data.get("vcpus", 1),
1556 {},
1557 flavor_data.get("extended"),
1558 )
1559
1560 def new_flavor(self, flavor_data: dict, change_name_if_used: bool = True) -> str:
1561 """Adds a tenant flavor to openstack VIM.
1562 if change_name_if_used is True, it will change name in case of conflict,
1563 because it is not supported name repetition.
1564
1565 Args:
1566 flavor_data (dict): Flavor details to be processed
1567 change_name_if_used (bool): Change name in case of conflict
1568
1569 Returns:
1570 flavor_id (str): flavor identifier
1571
tierno1ec592d2020-06-16 15:29:47 +00001572 """
tiernoae4a8d12016-07-08 12:30:39 +02001573 self.logger.debug("Adding flavor '%s'", str(flavor_data))
tierno1ec592d2020-06-16 15:29:47 +00001574 retry = 0
1575 max_retries = 3
tierno7edb6752016-03-21 17:37:52 +01001576 name_suffix = 0
sousaedu80135b92021-02-17 15:05:18 +01001577
anwarsc76a3ee2018-10-04 14:05:32 +05301578 try:
sousaedu80135b92021-02-17 15:05:18 +01001579 name = flavor_data["name"]
tierno1ec592d2020-06-16 15:29:47 +00001580 while retry < max_retries:
1581 retry += 1
anwarsc76a3ee2018-10-04 14:05:32 +05301582 try:
1583 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +01001584
anwarsc76a3ee2018-10-04 14:05:32 +05301585 if change_name_if_used:
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001586 name = self._change_flavor_name(name, name_suffix, flavor_data)
sousaedu80135b92021-02-17 15:05:18 +01001587
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001588 ram, vcpus, extra_specs, extended = self._get_flavor_details(
1589 flavor_data
1590 )
anwarsc76a3ee2018-10-04 14:05:32 +05301591 if extended:
Gulsum Atici6a6e3342023-01-23 16:22:59 +03001592 self._process_extended_config_of_flavor(extended, extra_specs)
sousaedu80135b92021-02-17 15:05:18 +01001593
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001594 # Create flavor
sousaedu80135b92021-02-17 15:05:18 +01001595
sousaedu80135b92021-02-17 15:05:18 +01001596 new_flavor = self.nova.flavors.create(
sousaeduf524da82021-11-22 14:02:17 +00001597 name=name,
1598 ram=ram,
1599 vcpus=vcpus,
1600 disk=flavor_data.get("disk", 0),
1601 ephemeral=flavor_data.get("ephemeral", 0),
sousaedu648ee3d2021-11-22 14:09:15 +00001602 swap=flavor_data.get("swap", 0),
sousaedu80135b92021-02-17 15:05:18 +01001603 is_public=flavor_data.get("is_public", True),
1604 )
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001605
1606 # Add metadata
anwarsae5f52c2019-04-22 10:35:27 +05301607 if extra_specs:
1608 new_flavor.set_keys(extra_specs)
sousaedu80135b92021-02-17 15:05:18 +01001609
anwarsc76a3ee2018-10-04 14:05:32 +05301610 return new_flavor.id
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001611
anwarsc76a3ee2018-10-04 14:05:32 +05301612 except nvExceptions.Conflict as e:
1613 if change_name_if_used and retry < max_retries:
1614 continue
sousaedu80135b92021-02-17 15:05:18 +01001615
anwarsc76a3ee2018-10-04 14:05:32 +05301616 self._format_exception(e)
Gulsum Atici4415c4c2023-01-19 12:44:06 +03001617
sousaedu80135b92021-02-17 15:05:18 +01001618 except (
1619 ksExceptions.ClientException,
1620 nvExceptions.ClientException,
1621 ConnectionError,
1622 KeyError,
1623 ) as e:
anwarsc76a3ee2018-10-04 14:05:32 +05301624 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001625
tierno1ec592d2020-06-16 15:29:47 +00001626 def delete_flavor(self, flavor_id):
sousaedu80135b92021-02-17 15:05:18 +01001627 """Deletes a tenant flavor from openstack VIM. Returns the old flavor_id"""
tiernoae4a8d12016-07-08 12:30:39 +02001628 try:
1629 self._reload_connection()
1630 self.nova.flavors.delete(flavor_id)
sousaedu80135b92021-02-17 15:05:18 +01001631
tiernoae4a8d12016-07-08 12:30:39 +02001632 return flavor_id
tierno1ec592d2020-06-16 15:29:47 +00001633 # except nvExceptions.BadRequest as e:
sousaedu80135b92021-02-17 15:05:18 +01001634 except (
1635 nvExceptions.NotFound,
1636 ksExceptions.ClientException,
1637 nvExceptions.ClientException,
1638 ConnectionError,
1639 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001640 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01001641
tierno1ec592d2020-06-16 15:29:47 +00001642 def new_image(self, image_dict):
1643 """
tiernoae4a8d12016-07-08 12:30:39 +02001644 Adds a tenant image to VIM. imge_dict is a dictionary with:
1645 name: name
1646 disk_format: qcow2, vhd, vmdk, raw (by default), ...
1647 location: path or URI
1648 public: "yes" or "no"
1649 metadata: metadata of the image
1650 Returns the image_id
tierno1ec592d2020-06-16 15:29:47 +00001651 """
1652 retry = 0
1653 max_retries = 3
sousaedu80135b92021-02-17 15:05:18 +01001654
tierno1ec592d2020-06-16 15:29:47 +00001655 while retry < max_retries:
1656 retry += 1
tierno7edb6752016-03-21 17:37:52 +01001657 try:
1658 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +01001659
tierno1ec592d2020-06-16 15:29:47 +00001660 # determine format http://docs.openstack.org/developer/glance/formats.html
tierno7edb6752016-03-21 17:37:52 +01001661 if "disk_format" in image_dict:
tierno1ec592d2020-06-16 15:29:47 +00001662 disk_format = image_dict["disk_format"]
1663 else: # autodiscover based on extension
sousaedu80135b92021-02-17 15:05:18 +01001664 if image_dict["location"].endswith(".qcow2"):
tierno1ec592d2020-06-16 15:29:47 +00001665 disk_format = "qcow2"
sousaedu80135b92021-02-17 15:05:18 +01001666 elif image_dict["location"].endswith(".vhd"):
tierno1ec592d2020-06-16 15:29:47 +00001667 disk_format = "vhd"
sousaedu80135b92021-02-17 15:05:18 +01001668 elif image_dict["location"].endswith(".vmdk"):
tierno1ec592d2020-06-16 15:29:47 +00001669 disk_format = "vmdk"
sousaedu80135b92021-02-17 15:05:18 +01001670 elif image_dict["location"].endswith(".vdi"):
tierno1ec592d2020-06-16 15:29:47 +00001671 disk_format = "vdi"
sousaedu80135b92021-02-17 15:05:18 +01001672 elif image_dict["location"].endswith(".iso"):
tierno1ec592d2020-06-16 15:29:47 +00001673 disk_format = "iso"
sousaedu80135b92021-02-17 15:05:18 +01001674 elif image_dict["location"].endswith(".aki"):
tierno1ec592d2020-06-16 15:29:47 +00001675 disk_format = "aki"
sousaedu80135b92021-02-17 15:05:18 +01001676 elif image_dict["location"].endswith(".ari"):
tierno1ec592d2020-06-16 15:29:47 +00001677 disk_format = "ari"
sousaedu80135b92021-02-17 15:05:18 +01001678 elif image_dict["location"].endswith(".ami"):
tierno1ec592d2020-06-16 15:29:47 +00001679 disk_format = "ami"
tierno7edb6752016-03-21 17:37:52 +01001680 else:
tierno1ec592d2020-06-16 15:29:47 +00001681 disk_format = "raw"
sousaedu80135b92021-02-17 15:05:18 +01001682
1683 self.logger.debug(
1684 "new_image: '%s' loading from '%s'",
1685 image_dict["name"],
1686 image_dict["location"],
1687 )
shashankjain3c83a212018-10-04 13:05:46 +05301688 if self.vim_type == "VIO":
1689 container_format = "bare"
sousaedu80135b92021-02-17 15:05:18 +01001690 if "container_format" in image_dict:
1691 container_format = image_dict["container_format"]
1692
1693 new_image = self.glance.images.create(
1694 name=image_dict["name"],
1695 container_format=container_format,
1696 disk_format=disk_format,
1697 )
shashankjain3c83a212018-10-04 13:05:46 +05301698 else:
sousaedu80135b92021-02-17 15:05:18 +01001699 new_image = self.glance.images.create(name=image_dict["name"])
1700
1701 if image_dict["location"].startswith("http"):
tierno1beea862018-07-11 15:47:37 +02001702 # TODO there is not a method to direct download. It must be downloaded locally with requests
tierno72774862020-05-04 11:44:15 +00001703 raise vimconn.VimConnNotImplemented("Cannot create image from URL")
tierno1ec592d2020-06-16 15:29:47 +00001704 else: # local path
sousaedu80135b92021-02-17 15:05:18 +01001705 with open(image_dict["location"]) as fimage:
tierno1beea862018-07-11 15:47:37 +02001706 self.glance.images.upload(new_image.id, fimage)
sousaedu80135b92021-02-17 15:05:18 +01001707 # new_image = self.glancev1.images.create(name=image_dict["name"], is_public=
1708 # image_dict.get("public","yes")=="yes",
tierno1beea862018-07-11 15:47:37 +02001709 # container_format="bare", data=fimage, disk_format=disk_format)
sousaedu80135b92021-02-17 15:05:18 +01001710
1711 metadata_to_load = image_dict.get("metadata")
1712
1713 # TODO location is a reserved word for current openstack versions. fixed for VIO please check
tierno1ec592d2020-06-16 15:29:47 +00001714 # for openstack
shashankjain3c83a212018-10-04 13:05:46 +05301715 if self.vim_type == "VIO":
sousaedu80135b92021-02-17 15:05:18 +01001716 metadata_to_load["upload_location"] = image_dict["location"]
shashankjain3c83a212018-10-04 13:05:46 +05301717 else:
sousaedu80135b92021-02-17 15:05:18 +01001718 metadata_to_load["location"] = image_dict["location"]
1719
tierno1beea862018-07-11 15:47:37 +02001720 self.glance.images.update(new_image.id, **metadata_to_load)
sousaedu80135b92021-02-17 15:05:18 +01001721
tiernoae4a8d12016-07-08 12:30:39 +02001722 return new_image.id
sousaedu80135b92021-02-17 15:05:18 +01001723 except (
1724 nvExceptions.Conflict,
1725 ksExceptions.ClientException,
1726 nvExceptions.ClientException,
1727 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001728 self._format_exception(e)
sousaedu80135b92021-02-17 15:05:18 +01001729 except (
1730 HTTPException,
1731 gl1Exceptions.HTTPException,
1732 gl1Exceptions.CommunicationError,
1733 ConnectionError,
1734 ) as e:
tierno1ec592d2020-06-16 15:29:47 +00001735 if retry == max_retries:
tiernoae4a8d12016-07-08 12:30:39 +02001736 continue
sousaedu80135b92021-02-17 15:05:18 +01001737
tiernoae4a8d12016-07-08 12:30:39 +02001738 self._format_exception(e)
tierno1ec592d2020-06-16 15:29:47 +00001739 except IOError as e: # can not open the file
sousaedu80135b92021-02-17 15:05:18 +01001740 raise vimconn.VimConnConnectionException(
1741 "{}: {} for {}".format(type(e).__name__, e, image_dict["location"]),
1742 http_code=vimconn.HTTP_Bad_Request,
1743 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001744
tiernoae4a8d12016-07-08 12:30:39 +02001745 def delete_image(self, image_id):
sousaedu80135b92021-02-17 15:05:18 +01001746 """Deletes a tenant image from openstack VIM. Returns the old id"""
tiernoae4a8d12016-07-08 12:30:39 +02001747 try:
1748 self._reload_connection()
tierno1beea862018-07-11 15:47:37 +02001749 self.glance.images.delete(image_id)
sousaedu80135b92021-02-17 15:05:18 +01001750
tiernoae4a8d12016-07-08 12:30:39 +02001751 return image_id
sousaedu80135b92021-02-17 15:05:18 +01001752 except (
1753 nvExceptions.NotFound,
1754 ksExceptions.ClientException,
1755 nvExceptions.ClientException,
1756 gl1Exceptions.CommunicationError,
1757 gl1Exceptions.HTTPNotFound,
1758 ConnectionError,
1759 ) as e: # TODO remove
tiernoae4a8d12016-07-08 12:30:39 +02001760 self._format_exception(e)
1761
1762 def get_image_id_from_path(self, path):
tierno1ec592d2020-06-16 15:29:47 +00001763 """Get the image id from image path in the VIM database. Returns the image_id"""
tiernoae4a8d12016-07-08 12:30:39 +02001764 try:
1765 self._reload_connection()
tierno1beea862018-07-11 15:47:37 +02001766 images = self.glance.images.list()
sousaedu80135b92021-02-17 15:05:18 +01001767
tiernoae4a8d12016-07-08 12:30:39 +02001768 for image in images:
tierno1ec592d2020-06-16 15:29:47 +00001769 if image.metadata.get("location") == path:
tiernoae4a8d12016-07-08 12:30:39 +02001770 return image.id
sousaedu80135b92021-02-17 15:05:18 +01001771
1772 raise vimconn.VimConnNotFoundException(
1773 "image with location '{}' not found".format(path)
1774 )
1775 except (
1776 ksExceptions.ClientException,
1777 nvExceptions.ClientException,
1778 gl1Exceptions.CommunicationError,
1779 ConnectionError,
1780 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001781 self._format_exception(e)
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00001782
garciadeblasb69fa9f2016-09-28 12:04:10 +02001783 def get_image_list(self, filter_dict={}):
tierno1ec592d2020-06-16 15:29:47 +00001784 """Obtain tenant images from VIM
garciadeblasb69fa9f2016-09-28 12:04:10 +02001785 Filter_dict can be:
1786 id: image id
1787 name: image name
1788 checksum: image checksum
1789 Returns the image list of dictionaries:
1790 [{<the fields at Filter_dict plus some VIM specific>}, ...]
1791 List can be empty
tierno1ec592d2020-06-16 15:29:47 +00001792 """
garciadeblasb69fa9f2016-09-28 12:04:10 +02001793 self.logger.debug("Getting image list from VIM filter: '%s'", str(filter_dict))
sousaedu80135b92021-02-17 15:05:18 +01001794
garciadeblasb69fa9f2016-09-28 12:04:10 +02001795 try:
1796 self._reload_connection()
tierno1ec592d2020-06-16 15:29:47 +00001797 # filter_dict_os = filter_dict.copy()
1798 # First we filter by the available filter fields: name, id. The others are removed.
tierno1beea862018-07-11 15:47:37 +02001799 image_list = self.glance.images.list()
garciadeblasb69fa9f2016-09-28 12:04:10 +02001800 filtered_list = []
sousaedu80135b92021-02-17 15:05:18 +01001801
garciadeblasb69fa9f2016-09-28 12:04:10 +02001802 for image in image_list:
tierno3cb8dc32017-10-24 18:13:19 +02001803 try:
tierno1beea862018-07-11 15:47:37 +02001804 if filter_dict.get("name") and image["name"] != filter_dict["name"]:
1805 continue
sousaedu80135b92021-02-17 15:05:18 +01001806
tierno1beea862018-07-11 15:47:37 +02001807 if filter_dict.get("id") and image["id"] != filter_dict["id"]:
1808 continue
sousaedu80135b92021-02-17 15:05:18 +01001809
1810 if (
1811 filter_dict.get("checksum")
1812 and image["checksum"] != filter_dict["checksum"]
1813 ):
tierno1beea862018-07-11 15:47:37 +02001814 continue
1815
1816 filtered_list.append(image.copy())
tierno3cb8dc32017-10-24 18:13:19 +02001817 except gl1Exceptions.HTTPNotFound:
1818 pass
sousaedu80135b92021-02-17 15:05:18 +01001819
garciadeblasb69fa9f2016-09-28 12:04:10 +02001820 return filtered_list
sousaedu80135b92021-02-17 15:05:18 +01001821 except (
1822 ksExceptions.ClientException,
1823 nvExceptions.ClientException,
1824 gl1Exceptions.CommunicationError,
1825 ConnectionError,
1826 ) as e:
garciadeblasb69fa9f2016-09-28 12:04:10 +02001827 self._format_exception(e)
1828
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001829 def __wait_for_vm(self, vm_id, status):
1830 """wait until vm is in the desired status and return True.
1831 If the VM gets in ERROR status, return false.
1832 If the timeout is reached generate an exception"""
1833 elapsed_time = 0
1834 while elapsed_time < server_timeout:
1835 vm_status = self.nova.servers.get(vm_id).status
sousaedu80135b92021-02-17 15:05:18 +01001836
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001837 if vm_status == status:
1838 return True
sousaedu80135b92021-02-17 15:05:18 +01001839
1840 if vm_status == "ERROR":
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001841 return False
sousaedu80135b92021-02-17 15:05:18 +01001842
tierno1df468d2018-07-06 14:25:16 +02001843 time.sleep(5)
1844 elapsed_time += 5
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001845
1846 # if we exceeded the timeout rollback
1847 if elapsed_time >= server_timeout:
sousaedu80135b92021-02-17 15:05:18 +01001848 raise vimconn.VimConnException(
1849 "Timeout waiting for instance " + vm_id + " to get " + status,
1850 http_code=vimconn.HTTP_Request_Timeout,
1851 )
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02001852
mirabal29356312017-07-27 12:21:22 +02001853 def _get_openstack_availablity_zones(self):
1854 """
1855 Get from openstack availability zones available
1856 :return:
1857 """
1858 try:
1859 openstack_availability_zone = self.nova.availability_zones.list()
sousaedu80135b92021-02-17 15:05:18 +01001860 openstack_availability_zone = [
1861 str(zone.zoneName)
1862 for zone in openstack_availability_zone
1863 if zone.zoneName != "internal"
1864 ]
1865
mirabal29356312017-07-27 12:21:22 +02001866 return openstack_availability_zone
tierno1ec592d2020-06-16 15:29:47 +00001867 except Exception:
mirabal29356312017-07-27 12:21:22 +02001868 return None
1869
1870 def _set_availablity_zones(self):
1871 """
1872 Set vim availablity zone
1873 :return:
1874 """
sousaedu80135b92021-02-17 15:05:18 +01001875 if "availability_zone" in self.config:
1876 vim_availability_zones = self.config.get("availability_zone")
mirabal29356312017-07-27 12:21:22 +02001877
mirabal29356312017-07-27 12:21:22 +02001878 if isinstance(vim_availability_zones, str):
1879 self.availability_zone = [vim_availability_zones]
1880 elif isinstance(vim_availability_zones, list):
1881 self.availability_zone = vim_availability_zones
1882 else:
1883 self.availability_zone = self._get_openstack_availablity_zones()
1884
sousaedu80135b92021-02-17 15:05:18 +01001885 def _get_vm_availability_zone(
1886 self, availability_zone_index, availability_zone_list
1887 ):
mirabal29356312017-07-27 12:21:22 +02001888 """
tierno5a3273c2017-08-29 11:43:46 +02001889 Return thge availability zone to be used by the created VM.
1890 :return: The VIM availability zone to be used or None
mirabal29356312017-07-27 12:21:22 +02001891 """
tierno5a3273c2017-08-29 11:43:46 +02001892 if availability_zone_index is None:
sousaedu80135b92021-02-17 15:05:18 +01001893 if not self.config.get("availability_zone"):
tierno5a3273c2017-08-29 11:43:46 +02001894 return None
sousaedu80135b92021-02-17 15:05:18 +01001895 elif isinstance(self.config.get("availability_zone"), str):
1896 return self.config["availability_zone"]
tierno5a3273c2017-08-29 11:43:46 +02001897 else:
1898 # TODO consider using a different parameter at config for default AV and AV list match
sousaedu80135b92021-02-17 15:05:18 +01001899 return self.config["availability_zone"][0]
mirabal29356312017-07-27 12:21:22 +02001900
tierno5a3273c2017-08-29 11:43:46 +02001901 vim_availability_zones = self.availability_zone
1902 # check if VIM offer enough availability zones describe in the VNFD
sousaedu80135b92021-02-17 15:05:18 +01001903 if vim_availability_zones and len(availability_zone_list) <= len(
1904 vim_availability_zones
1905 ):
tierno5a3273c2017-08-29 11:43:46 +02001906 # check if all the names of NFV AV match VIM AV names
1907 match_by_index = False
1908 for av in availability_zone_list:
1909 if av not in vim_availability_zones:
1910 match_by_index = True
1911 break
sousaedu80135b92021-02-17 15:05:18 +01001912
tierno5a3273c2017-08-29 11:43:46 +02001913 if match_by_index:
1914 return vim_availability_zones[availability_zone_index]
1915 else:
1916 return availability_zone_list[availability_zone_index]
mirabal29356312017-07-27 12:21:22 +02001917 else:
sousaedu80135b92021-02-17 15:05:18 +01001918 raise vimconn.VimConnConflictException(
1919 "No enough availability zones at VIM for this deployment"
1920 )
mirabal29356312017-07-27 12:21:22 +02001921
Gulsum Atici26f73662022-10-27 15:18:27 +03001922 def _prepare_port_dict_security_groups(self, net: dict, port_dict: dict) -> None:
1923 """Fill up the security_groups in the port_dict.
1924
1925 Args:
1926 net (dict): Network details
1927 port_dict (dict): Port details
1928
1929 """
1930 if (
1931 self.config.get("security_groups")
1932 and net.get("port_security") is not False
1933 and not self.config.get("no_port_security_extension")
1934 ):
1935 if not self.security_groups_id:
1936 self._get_ids_from_name()
1937
1938 port_dict["security_groups"] = self.security_groups_id
1939
1940 def _prepare_port_dict_binding(self, net: dict, port_dict: dict) -> None:
1941 """Fill up the network binding depending on network type in the port_dict.
1942
1943 Args:
1944 net (dict): Network details
1945 port_dict (dict): Port details
1946
1947 """
1948 if not net.get("type"):
1949 raise vimconn.VimConnException("Type is missing in the network details.")
1950
1951 if net["type"] == "virtual":
1952 pass
1953
1954 # For VF
1955 elif net["type"] == "VF" or net["type"] == "SR-IOV":
Gulsum Atici26f73662022-10-27 15:18:27 +03001956 port_dict["binding:vnic_type"] = "direct"
1957
1958 # VIO specific Changes
1959 if self.vim_type == "VIO":
1960 # Need to create port with port_security_enabled = False and no-security-groups
1961 port_dict["port_security_enabled"] = False
1962 port_dict["provider_security_groups"] = []
1963 port_dict["security_groups"] = []
1964
1965 else:
1966 # For PT PCI-PASSTHROUGH
1967 port_dict["binding:vnic_type"] = "direct-physical"
1968
1969 @staticmethod
1970 def _set_fixed_ip(new_port: dict, net: dict) -> None:
1971 """Set the "ip" parameter in net dictionary.
1972
1973 Args:
1974 new_port (dict): New created port
1975 net (dict): Network details
1976
1977 """
1978 fixed_ips = new_port["port"].get("fixed_ips")
1979
1980 if fixed_ips:
1981 net["ip"] = fixed_ips[0].get("ip_address")
1982 else:
1983 net["ip"] = None
1984
1985 @staticmethod
1986 def _prepare_port_dict_mac_ip_addr(net: dict, port_dict: dict) -> None:
1987 """Fill up the mac_address and fixed_ips in port_dict.
1988
1989 Args:
1990 net (dict): Network details
1991 port_dict (dict): Port details
1992
1993 """
1994 if net.get("mac_address"):
1995 port_dict["mac_address"] = net["mac_address"]
1996
elumalai370e36b2023-04-25 16:22:56 +05301997 ip_dual_list = []
1998 if ip_list := net.get("ip_address"):
1999 if not isinstance(ip_list, list):
2000 ip_list = [ip_list]
2001 for ip in ip_list:
2002 ip_dict = {"ip_address": ip}
2003 ip_dual_list.append(ip_dict)
2004 port_dict["fixed_ips"] = ip_dual_list
Gulsum Atici26f73662022-10-27 15:18:27 +03002005 # TODO add "subnet_id": <subnet_id>
2006
2007 def _create_new_port(self, port_dict: dict, created_items: dict, net: dict) -> Dict:
2008 """Create new port using neutron.
2009
2010 Args:
2011 port_dict (dict): Port details
2012 created_items (dict): All created items
2013 net (dict): Network details
2014
2015 Returns:
2016 new_port (dict): New created port
2017
2018 """
2019 new_port = self.neutron.create_port({"port": port_dict})
2020 created_items["port:" + str(new_port["port"]["id"])] = True
elumalaie17cd942023-04-28 18:04:24 +05302021 net["mac_address"] = new_port["port"]["mac_address"]
Gulsum Atici26f73662022-10-27 15:18:27 +03002022 net["vim_id"] = new_port["port"]["id"]
2023
2024 return new_port
2025
2026 def _create_port(
2027 self, net: dict, name: str, created_items: dict
2028 ) -> Tuple[dict, dict]:
2029 """Create port using net details.
2030
2031 Args:
2032 net (dict): Network details
2033 name (str): Name to be used as network name if net dict does not include name
2034 created_items (dict): All created items
2035
2036 Returns:
2037 new_port, port New created port, port dictionary
2038
2039 """
2040
2041 port_dict = {
2042 "network_id": net["net_id"],
2043 "name": net.get("name"),
2044 "admin_state_up": True,
2045 }
2046
2047 if not port_dict["name"]:
2048 port_dict["name"] = name
2049
2050 self._prepare_port_dict_security_groups(net, port_dict)
2051
2052 self._prepare_port_dict_binding(net, port_dict)
2053
2054 vimconnector._prepare_port_dict_mac_ip_addr(net, port_dict)
2055
2056 new_port = self._create_new_port(port_dict, created_items, net)
2057
2058 vimconnector._set_fixed_ip(new_port, net)
2059
2060 port = {"port-id": new_port["port"]["id"]}
2061
2062 if float(self.nova.api_version.get_string()) >= 2.32:
2063 port["tag"] = new_port["port"]["name"]
2064
2065 return new_port, port
2066
2067 def _prepare_network_for_vminstance(
2068 self,
2069 name: str,
2070 net_list: list,
2071 created_items: dict,
2072 net_list_vim: list,
2073 external_network: list,
2074 no_secured_ports: list,
2075 ) -> None:
2076 """Create port and fill up net dictionary for new VM instance creation.
2077
2078 Args:
2079 name (str): Name of network
2080 net_list (list): List of networks
2081 created_items (dict): All created items belongs to a VM
2082 net_list_vim (list): List of ports
2083 external_network (list): List of external-networks
2084 no_secured_ports (list): Port security disabled ports
2085 """
2086
2087 self._reload_connection()
2088
2089 for net in net_list:
2090 # Skip non-connected iface
2091 if not net.get("net_id"):
2092 continue
2093
2094 new_port, port = self._create_port(net, name, created_items)
2095
2096 net_list_vim.append(port)
2097
2098 if net.get("floating_ip", False):
2099 net["exit_on_floating_ip_error"] = True
2100 external_network.append(net)
2101
2102 elif net["use"] == "mgmt" and self.config.get("use_floating_ip"):
2103 net["exit_on_floating_ip_error"] = False
2104 external_network.append(net)
2105 net["floating_ip"] = self.config.get("use_floating_ip")
2106
2107 # If port security is disabled when the port has not yet been attached to the VM, then all vm traffic
2108 # is dropped. As a workaround we wait until the VM is active and then disable the port-security
2109 if net.get("port_security") is False and not self.config.get(
2110 "no_port_security_extension"
2111 ):
2112 no_secured_ports.append(
2113 (
2114 new_port["port"]["id"],
2115 net.get("port_security_disable_strategy"),
2116 )
2117 )
2118
2119 def _prepare_persistent_root_volumes(
2120 self,
2121 name: str,
2122 vm_av_zone: list,
2123 disk: dict,
2124 base_disk_index: int,
2125 block_device_mapping: dict,
2126 existing_vim_volumes: list,
2127 created_items: dict,
2128 ) -> Optional[str]:
2129 """Prepare persistent root volumes for new VM instance.
2130
2131 Args:
2132 name (str): Name of VM instance
2133 vm_av_zone (list): List of availability zones
2134 disk (dict): Disk details
2135 base_disk_index (int): Disk index
2136 block_device_mapping (dict): Block device details
2137 existing_vim_volumes (list): Existing disk details
2138 created_items (dict): All created items belongs to VM
2139
2140 Returns:
2141 boot_volume_id (str): ID of boot volume
2142
2143 """
2144 # Disk may include only vim_volume_id or only vim_id."
2145 # Use existing persistent root volume finding with volume_id or vim_id
2146 key_id = "vim_volume_id" if "vim_volume_id" in disk.keys() else "vim_id"
2147
2148 if disk.get(key_id):
Gulsum Atici26f73662022-10-27 15:18:27 +03002149 block_device_mapping["vd" + chr(base_disk_index)] = disk[key_id]
2150 existing_vim_volumes.append({"id": disk[key_id]})
2151
2152 else:
2153 # Create persistent root volume
2154 volume = self.cinder.volumes.create(
2155 size=disk["size"],
2156 name=name + "vd" + chr(base_disk_index),
2157 imageRef=disk["image_id"],
2158 # Make sure volume is in the same AZ as the VM to be attached to
2159 availability_zone=vm_av_zone,
2160 )
2161 boot_volume_id = volume.id
aticig2f4ab6c2022-09-03 18:15:20 +03002162 self.update_block_device_mapping(
2163 volume=volume,
2164 block_device_mapping=block_device_mapping,
2165 base_disk_index=base_disk_index,
2166 disk=disk,
2167 created_items=created_items,
2168 )
Gulsum Atici26f73662022-10-27 15:18:27 +03002169
2170 return boot_volume_id
2171
aticig2f4ab6c2022-09-03 18:15:20 +03002172 @staticmethod
2173 def update_block_device_mapping(
2174 volume: object,
2175 block_device_mapping: dict,
2176 base_disk_index: int,
2177 disk: dict,
2178 created_items: dict,
2179 ) -> None:
2180 """Add volume information to block device mapping dict.
2181 Args:
2182 volume (object): Created volume object
2183 block_device_mapping (dict): Block device details
2184 base_disk_index (int): Disk index
2185 disk (dict): Disk details
2186 created_items (dict): All created items belongs to VM
2187 """
2188 if not volume:
2189 raise vimconn.VimConnException("Volume is empty.")
2190
2191 if not hasattr(volume, "id"):
2192 raise vimconn.VimConnException(
2193 "Created volume is not valid, does not have id attribute."
2194 )
2195
Gabriel Cuba1fd411b2023-06-14 00:50:57 -05002196 block_device_mapping["vd" + chr(base_disk_index)] = volume.id
2197 if disk.get("multiattach"): # multiattach volumes do not belong to VDUs
2198 return
aticig2f4ab6c2022-09-03 18:15:20 +03002199 volume_txt = "volume:" + str(volume.id)
2200 if disk.get("keep"):
2201 volume_txt += ":keep"
2202 created_items[volume_txt] = True
aticig2f4ab6c2022-09-03 18:15:20 +03002203
vegall364627c2023-03-17 15:09:50 +00002204 def new_shared_volumes(self, shared_volume_data) -> (str, str):
2205 try:
2206 volume = self.cinder.volumes.create(
2207 size=shared_volume_data["size"],
2208 name=shared_volume_data["name"],
2209 volume_type="multiattach",
2210 )
2211 return (volume.name, volume.id)
2212 except (ConnectionError, KeyError) as e:
2213 self._format_exception(e)
2214
2215 def _prepare_shared_volumes(
2216 self,
2217 name: str,
2218 disk: dict,
2219 base_disk_index: int,
2220 block_device_mapping: dict,
2221 existing_vim_volumes: list,
2222 created_items: dict,
2223 ):
2224 volumes = {volume.name: volume.id for volume in self.cinder.volumes.list()}
2225 if volumes.get(disk["name"]):
2226 sv_id = volumes[disk["name"]]
Gabriel Cuba1fd411b2023-06-14 00:50:57 -05002227 max_retries = 3
2228 vol_status = ""
2229 # If this is not the first VM to attach the volume, volume status may be "reserved" for a short time
2230 while max_retries:
2231 max_retries -= 1
2232 volume = self.cinder.volumes.get(sv_id)
2233 vol_status = volume.status
2234 if volume.status not in ("in-use", "available"):
2235 time.sleep(5)
2236 continue
2237 self.update_block_device_mapping(
2238 volume=volume,
2239 block_device_mapping=block_device_mapping,
2240 base_disk_index=base_disk_index,
2241 disk=disk,
2242 created_items=created_items,
2243 )
2244 return
2245 raise vimconn.VimConnException(
2246 "Shared volume is not prepared, status is: {}".format(vol_status),
2247 http_code=vimconn.HTTP_Internal_Server_Error,
vegall364627c2023-03-17 15:09:50 +00002248 )
2249
Gulsum Atici26f73662022-10-27 15:18:27 +03002250 def _prepare_non_root_persistent_volumes(
2251 self,
2252 name: str,
2253 disk: dict,
2254 vm_av_zone: list,
2255 block_device_mapping: dict,
2256 base_disk_index: int,
2257 existing_vim_volumes: list,
2258 created_items: dict,
2259 ) -> None:
2260 """Prepare persistent volumes for new VM instance.
2261
2262 Args:
2263 name (str): Name of VM instance
2264 disk (dict): Disk details
2265 vm_av_zone (list): List of availability zones
2266 block_device_mapping (dict): Block device details
2267 base_disk_index (int): Disk index
2268 existing_vim_volumes (list): Existing disk details
2269 created_items (dict): All created items belongs to VM
2270 """
2271 # Non-root persistent volumes
2272 # Disk may include only vim_volume_id or only vim_id."
2273 key_id = "vim_volume_id" if "vim_volume_id" in disk.keys() else "vim_id"
Gulsum Atici26f73662022-10-27 15:18:27 +03002274 if disk.get(key_id):
Gulsum Atici26f73662022-10-27 15:18:27 +03002275 # Use existing persistent volume
2276 block_device_mapping["vd" + chr(base_disk_index)] = disk[key_id]
2277 existing_vim_volumes.append({"id": disk[key_id]})
Gulsum Atici26f73662022-10-27 15:18:27 +03002278 else:
vegall364627c2023-03-17 15:09:50 +00002279 volume_name = f"{name}vd{chr(base_disk_index)}"
Gulsum Atici26f73662022-10-27 15:18:27 +03002280 volume = self.cinder.volumes.create(
2281 size=disk["size"],
vegall364627c2023-03-17 15:09:50 +00002282 name=volume_name,
Gulsum Atici26f73662022-10-27 15:18:27 +03002283 # Make sure volume is in the same AZ as the VM to be attached to
2284 availability_zone=vm_av_zone,
2285 )
aticig2f4ab6c2022-09-03 18:15:20 +03002286 self.update_block_device_mapping(
2287 volume=volume,
2288 block_device_mapping=block_device_mapping,
2289 base_disk_index=base_disk_index,
2290 disk=disk,
2291 created_items=created_items,
2292 )
Gulsum Atici26f73662022-10-27 15:18:27 +03002293
2294 def _wait_for_created_volumes_availability(
2295 self, elapsed_time: int, created_items: dict
2296 ) -> Optional[int]:
2297 """Wait till created volumes become available.
2298
2299 Args:
2300 elapsed_time (int): Passed time while waiting
2301 created_items (dict): All created items belongs to VM
2302
2303 Returns:
2304 elapsed_time (int): Time spent while waiting
2305
2306 """
Gulsum Atici26f73662022-10-27 15:18:27 +03002307 while elapsed_time < volume_timeout:
2308 for created_item in created_items:
aticig2f4ab6c2022-09-03 18:15:20 +03002309 v, volume_id = (
2310 created_item.split(":")[0],
2311 created_item.split(":")[1],
2312 )
Gulsum Atici26f73662022-10-27 15:18:27 +03002313 if v == "volume":
vegall364627c2023-03-17 15:09:50 +00002314 volume = self.cinder.volumes.get(volume_id)
2315 if (
2316 volume.volume_type == "multiattach"
2317 and volume.status == "in-use"
2318 ):
2319 return elapsed_time
2320 elif volume.status != "available":
Gulsum Atici26f73662022-10-27 15:18:27 +03002321 break
2322 else:
2323 # All ready: break from while
2324 break
2325
2326 time.sleep(5)
2327 elapsed_time += 5
2328
2329 return elapsed_time
2330
2331 def _wait_for_existing_volumes_availability(
2332 self, elapsed_time: int, existing_vim_volumes: list
2333 ) -> Optional[int]:
2334 """Wait till existing volumes become available.
2335
2336 Args:
2337 elapsed_time (int): Passed time while waiting
2338 existing_vim_volumes (list): Existing volume details
2339
2340 Returns:
2341 elapsed_time (int): Time spent while waiting
2342
2343 """
2344
2345 while elapsed_time < volume_timeout:
2346 for volume in existing_vim_volumes:
vegall364627c2023-03-17 15:09:50 +00002347 v = self.cinder.volumes.get(volume["id"])
2348 if v.volume_type == "multiattach" and v.status == "in-use":
2349 return elapsed_time
2350 elif v.status != "available":
Gulsum Atici26f73662022-10-27 15:18:27 +03002351 break
2352 else: # all ready: break from while
2353 break
2354
2355 time.sleep(5)
2356 elapsed_time += 5
2357
2358 return elapsed_time
2359
2360 def _prepare_disk_for_vminstance(
2361 self,
2362 name: str,
2363 existing_vim_volumes: list,
2364 created_items: dict,
2365 vm_av_zone: list,
Gulsum Atici13d02322022-11-18 00:10:15 +03002366 block_device_mapping: dict,
Gulsum Atici26f73662022-10-27 15:18:27 +03002367 disk_list: list = None,
2368 ) -> None:
2369 """Prepare all volumes for new VM instance.
2370
2371 Args:
2372 name (str): Name of Instance
2373 existing_vim_volumes (list): List of existing volumes
2374 created_items (dict): All created items belongs to VM
2375 vm_av_zone (list): VM availability zone
Gulsum Atici13d02322022-11-18 00:10:15 +03002376 block_device_mapping (dict): Block devices to be attached to VM
Gulsum Atici26f73662022-10-27 15:18:27 +03002377 disk_list (list): List of disks
2378
2379 """
2380 # Create additional volumes in case these are present in disk_list
2381 base_disk_index = ord("b")
2382 boot_volume_id = None
2383 elapsed_time = 0
Gulsum Atici26f73662022-10-27 15:18:27 +03002384 for disk in disk_list:
2385 if "image_id" in disk:
2386 # Root persistent volume
2387 base_disk_index = ord("a")
2388 boot_volume_id = self._prepare_persistent_root_volumes(
2389 name=name,
2390 vm_av_zone=vm_av_zone,
2391 disk=disk,
2392 base_disk_index=base_disk_index,
2393 block_device_mapping=block_device_mapping,
2394 existing_vim_volumes=existing_vim_volumes,
2395 created_items=created_items,
2396 )
vegall364627c2023-03-17 15:09:50 +00002397 elif disk.get("multiattach"):
2398 self._prepare_shared_volumes(
2399 name=name,
2400 disk=disk,
2401 base_disk_index=base_disk_index,
2402 block_device_mapping=block_device_mapping,
2403 existing_vim_volumes=existing_vim_volumes,
2404 created_items=created_items,
2405 )
Gulsum Atici26f73662022-10-27 15:18:27 +03002406 else:
2407 # Non-root persistent volume
2408 self._prepare_non_root_persistent_volumes(
2409 name=name,
2410 disk=disk,
2411 vm_av_zone=vm_av_zone,
2412 block_device_mapping=block_device_mapping,
2413 base_disk_index=base_disk_index,
2414 existing_vim_volumes=existing_vim_volumes,
2415 created_items=created_items,
2416 )
2417 base_disk_index += 1
2418
2419 # Wait until created volumes are with status available
2420 elapsed_time = self._wait_for_created_volumes_availability(
2421 elapsed_time, created_items
2422 )
2423 # Wait until existing volumes in vim are with status available
2424 elapsed_time = self._wait_for_existing_volumes_availability(
2425 elapsed_time, existing_vim_volumes
2426 )
2427 # If we exceeded the timeout rollback
2428 if elapsed_time >= volume_timeout:
2429 raise vimconn.VimConnException(
2430 "Timeout creating volumes for instance " + name,
2431 http_code=vimconn.HTTP_Request_Timeout,
2432 )
2433 if boot_volume_id:
2434 self.cinder.volumes.set_bootable(boot_volume_id, True)
2435
2436 def _find_the_external_network_for_floating_ip(self):
2437 """Get the external network ip in order to create floating IP.
2438
2439 Returns:
2440 pool_id (str): External network pool ID
2441
2442 """
2443
2444 # Find the external network
2445 external_nets = list()
2446
2447 for net in self.neutron.list_networks()["networks"]:
2448 if net["router:external"]:
2449 external_nets.append(net)
2450
2451 if len(external_nets) == 0:
2452 raise vimconn.VimConnException(
2453 "Cannot create floating_ip automatically since "
2454 "no external network is present",
2455 http_code=vimconn.HTTP_Conflict,
2456 )
2457
2458 if len(external_nets) > 1:
2459 raise vimconn.VimConnException(
2460 "Cannot create floating_ip automatically since "
2461 "multiple external networks are present",
2462 http_code=vimconn.HTTP_Conflict,
2463 )
2464
2465 # Pool ID
2466 return external_nets[0].get("id")
2467
2468 def _neutron_create_float_ip(self, param: dict, created_items: dict) -> None:
2469 """Trigger neutron to create a new floating IP using external network ID.
2470
2471 Args:
2472 param (dict): Input parameters to create a floating IP
2473 created_items (dict): All created items belongs to new VM instance
2474
2475 Raises:
2476
2477 VimConnException
2478 """
2479 try:
2480 self.logger.debug("Creating floating IP")
2481 new_floating_ip = self.neutron.create_floatingip(param)
2482 free_floating_ip = new_floating_ip["floatingip"]["id"]
2483 created_items["floating_ip:" + str(free_floating_ip)] = True
2484
2485 except Exception as e:
2486 raise vimconn.VimConnException(
2487 type(e).__name__ + ": Cannot create new floating_ip " + str(e),
2488 http_code=vimconn.HTTP_Conflict,
2489 )
2490
2491 def _create_floating_ip(
2492 self, floating_network: dict, server: object, created_items: dict
2493 ) -> None:
2494 """Get the available Pool ID and create a new floating IP.
2495
2496 Args:
2497 floating_network (dict): Dict including external network ID
2498 server (object): Server object
2499 created_items (dict): All created items belongs to new VM instance
2500
2501 """
2502
2503 # Pool_id is available
2504 if (
2505 isinstance(floating_network["floating_ip"], str)
2506 and floating_network["floating_ip"].lower() != "true"
2507 ):
2508 pool_id = floating_network["floating_ip"]
2509
2510 # Find the Pool_id
2511 else:
2512 pool_id = self._find_the_external_network_for_floating_ip()
2513
2514 param = {
2515 "floatingip": {
2516 "floating_network_id": pool_id,
2517 "tenant_id": server.tenant_id,
2518 }
2519 }
2520
2521 self._neutron_create_float_ip(param, created_items)
2522
2523 def _find_floating_ip(
2524 self,
2525 server: object,
2526 floating_ips: list,
2527 floating_network: dict,
2528 ) -> Optional[str]:
2529 """Find the available free floating IPs if there are.
2530
2531 Args:
2532 server (object): Server object
2533 floating_ips (list): List of floating IPs
2534 floating_network (dict): Details of floating network such as ID
2535
2536 Returns:
2537 free_floating_ip (str): Free floating ip address
2538
2539 """
2540 for fip in floating_ips:
2541 if fip.get("port_id") or fip.get("tenant_id") != server.tenant_id:
2542 continue
2543
2544 if isinstance(floating_network["floating_ip"], str):
2545 if fip.get("floating_network_id") != floating_network["floating_ip"]:
2546 continue
2547
2548 return fip["id"]
2549
2550 def _assign_floating_ip(
2551 self, free_floating_ip: str, floating_network: dict
2552 ) -> Dict:
2553 """Assign the free floating ip address to port.
2554
2555 Args:
2556 free_floating_ip (str): Floating IP to be assigned
2557 floating_network (dict): ID of floating network
2558
2559 Returns:
2560 fip (dict) (dict): Floating ip details
2561
2562 """
2563 # The vim_id key contains the neutron.port_id
2564 self.neutron.update_floatingip(
2565 free_floating_ip,
2566 {"floatingip": {"port_id": floating_network["vim_id"]}},
2567 )
2568 # For race condition ensure not re-assigned to other VM after 5 seconds
2569 time.sleep(5)
2570
2571 return self.neutron.show_floatingip(free_floating_ip)
2572
2573 def _get_free_floating_ip(
Gulsum Atici9e76ebb2022-12-12 19:21:25 +03002574 self, server: object, floating_network: dict
Gulsum Atici26f73662022-10-27 15:18:27 +03002575 ) -> Optional[str]:
2576 """Get the free floating IP address.
2577
2578 Args:
2579 server (object): Server Object
2580 floating_network (dict): Floating network details
Gulsum Atici26f73662022-10-27 15:18:27 +03002581
2582 Returns:
2583 free_floating_ip (str): Free floating ip addr
2584
2585 """
2586
2587 floating_ips = self.neutron.list_floatingips().get("floatingips", ())
2588
2589 # Randomize
2590 random.shuffle(floating_ips)
2591
Gulsum Atici9e76ebb2022-12-12 19:21:25 +03002592 return self._find_floating_ip(server, floating_ips, floating_network)
Gulsum Atici26f73662022-10-27 15:18:27 +03002593
2594 def _prepare_external_network_for_vminstance(
2595 self,
2596 external_network: list,
2597 server: object,
2598 created_items: dict,
2599 vm_start_time: float,
2600 ) -> None:
2601 """Assign floating IP address for VM instance.
2602
2603 Args:
2604 external_network (list): ID of External network
2605 server (object): Server Object
2606 created_items (dict): All created items belongs to new VM instance
2607 vm_start_time (float): Time as a floating point number expressed in seconds since the epoch, in UTC
2608
2609 Raises:
2610 VimConnException
2611
2612 """
2613 for floating_network in external_network:
2614 try:
2615 assigned = False
2616 floating_ip_retries = 3
2617 # In case of RO in HA there can be conflicts, two RO trying to assign same floating IP, so retry
2618 # several times
2619 while not assigned:
Gulsum Atici26f73662022-10-27 15:18:27 +03002620 free_floating_ip = self._get_free_floating_ip(
Gulsum Atici9e76ebb2022-12-12 19:21:25 +03002621 server, floating_network
Gulsum Atici26f73662022-10-27 15:18:27 +03002622 )
2623
2624 if not free_floating_ip:
2625 self._create_floating_ip(
2626 floating_network, server, created_items
2627 )
2628
2629 try:
2630 # For race condition ensure not already assigned
2631 fip = self.neutron.show_floatingip(free_floating_ip)
2632
2633 if fip["floatingip"].get("port_id"):
2634 continue
2635
2636 # Assign floating ip
2637 fip = self._assign_floating_ip(
2638 free_floating_ip, floating_network
2639 )
2640
2641 if fip["floatingip"]["port_id"] != floating_network["vim_id"]:
2642 self.logger.warning(
2643 "floating_ip {} re-assigned to other port".format(
2644 free_floating_ip
2645 )
2646 )
2647 continue
2648
2649 self.logger.debug(
2650 "Assigned floating_ip {} to VM {}".format(
2651 free_floating_ip, server.id
2652 )
2653 )
2654
2655 assigned = True
2656
2657 except Exception as e:
2658 # Openstack need some time after VM creation to assign an IP. So retry if fails
2659 vm_status = self.nova.servers.get(server.id).status
2660
2661 if vm_status not in ("ACTIVE", "ERROR"):
2662 if time.time() - vm_start_time < server_timeout:
2663 time.sleep(5)
2664 continue
2665 elif floating_ip_retries > 0:
2666 floating_ip_retries -= 1
2667 continue
2668
2669 raise vimconn.VimConnException(
2670 "Cannot create floating_ip: {} {}".format(
2671 type(e).__name__, e
2672 ),
2673 http_code=vimconn.HTTP_Conflict,
2674 )
2675
2676 except Exception as e:
2677 if not floating_network["exit_on_floating_ip_error"]:
2678 self.logger.error("Cannot create floating_ip. %s", str(e))
2679 continue
2680
2681 raise
2682
2683 def _update_port_security_for_vminstance(
2684 self,
2685 no_secured_ports: list,
2686 server: object,
2687 ) -> None:
2688 """Updates the port security according to no_secured_ports list.
2689
2690 Args:
2691 no_secured_ports (list): List of ports that security will be disabled
2692 server (object): Server Object
2693
2694 Raises:
2695 VimConnException
2696
2697 """
2698 # Wait until the VM is active and then disable the port-security
2699 if no_secured_ports:
2700 self.__wait_for_vm(server.id, "ACTIVE")
2701
2702 for port in no_secured_ports:
2703 port_update = {
2704 "port": {"port_security_enabled": False, "security_groups": None}
2705 }
2706
2707 if port[1] == "allow-address-pairs":
2708 port_update = {
2709 "port": {"allowed_address_pairs": [{"ip_address": "0.0.0.0/0"}]}
2710 }
2711
2712 try:
2713 self.neutron.update_port(port[0], port_update)
2714
2715 except Exception:
Gulsum Atici26f73662022-10-27 15:18:27 +03002716 raise vimconn.VimConnException(
2717 "It was not possible to disable port security for port {}".format(
2718 port[0]
2719 )
2720 )
2721
sousaedu80135b92021-02-17 15:05:18 +01002722 def new_vminstance(
2723 self,
Gulsum Atici26f73662022-10-27 15:18:27 +03002724 name: str,
2725 description: str,
2726 start: bool,
2727 image_id: str,
2728 flavor_id: str,
2729 affinity_group_list: list,
2730 net_list: list,
sousaedu80135b92021-02-17 15:05:18 +01002731 cloud_config=None,
2732 disk_list=None,
2733 availability_zone_index=None,
2734 availability_zone_list=None,
Gulsum Atici26f73662022-10-27 15:18:27 +03002735 ) -> tuple:
2736 """Adds a VM instance to VIM.
2737
2738 Args:
2739 name (str): name of VM
2740 description (str): description
2741 start (bool): indicates if VM must start or boot in pause mode. Ignored
2742 image_id (str) image uuid
2743 flavor_id (str) flavor uuid
2744 affinity_group_list (list): list of affinity groups, each one is a dictionary.Ignore if empty.
2745 net_list (list): list of interfaces, each one is a dictionary with:
2746 name: name of network
2747 net_id: network uuid to connect
2748 vpci: virtual vcpi to assign, ignored because openstack lack #TODO
2749 model: interface model, ignored #TODO
2750 mac_address: used for SR-IOV ifaces #TODO for other types
2751 use: 'data', 'bridge', 'mgmt'
2752 type: 'virtual', 'PCI-PASSTHROUGH'('PF'), 'SR-IOV'('VF'), 'VFnotShared'
2753 vim_id: filled/added by this function
2754 floating_ip: True/False (or it can be None)
2755 port_security: True/False
2756 cloud_config (dict): (optional) dictionary with:
2757 key-pairs: (optional) list of strings with the public key to be inserted to the default user
2758 users: (optional) list of users to be inserted, each item is a dict with:
2759 name: (mandatory) user name,
2760 key-pairs: (optional) list of strings with the public key to be inserted to the user
2761 user-data: (optional) string is a text script to be passed directly to cloud-init
2762 config-files: (optional). List of files to be transferred. Each item is a dict with:
2763 dest: (mandatory) string with the destination absolute path
2764 encoding: (optional, by default text). Can be one of:
tierno1d213f42020-04-24 14:02:51 +00002765 'b64', 'base64', 'gz', 'gz+b64', 'gz+base64', 'gzip+b64', 'gzip+base64'
Gulsum Atici26f73662022-10-27 15:18:27 +03002766 content : (mandatory) string with the content of the file
2767 permissions: (optional) string with file permissions, typically octal notation '0644'
2768 owner: (optional) file owner, string with the format 'owner:group'
2769 boot-data-drive: boolean to indicate if user-data must be passed using a boot drive (hard disk)
2770 disk_list: (optional) list with additional disks to the VM. Each item is a dict with:
2771 image_id: (optional). VIM id of an existing image. If not provided an empty disk must be mounted
2772 size: (mandatory) string with the size of the disk in GB
2773 vim_id: (optional) should use this existing volume id
2774 availability_zone_index: Index of availability_zone_list to use for this this VM. None if not AV required
2775 availability_zone_list: list of availability zones given by user in the VNFD descriptor. Ignore if
tierno5a3273c2017-08-29 11:43:46 +02002776 availability_zone_index is None
tierno7edb6752016-03-21 17:37:52 +01002777 #TODO ip, security groups
Gulsum Atici26f73662022-10-27 15:18:27 +03002778
2779 Returns:
2780 A tuple with the instance identifier and created_items or raises an exception on error
tierno98e909c2017-10-14 13:27:03 +02002781 created_items can be None or a dictionary where this method can include key-values that will be passed to
2782 the method delete_vminstance and action_vminstance. Can be used to store created ports, volumes, etc.
2783 Format is vimconnector dependent, but do not use nested dictionaries and a value of None should be the same
2784 as not present.
aticig2f4ab6c2022-09-03 18:15:20 +03002785
tierno98e909c2017-10-14 13:27:03 +02002786 """
sousaedu80135b92021-02-17 15:05:18 +01002787 self.logger.debug(
2788 "new_vminstance input: image='%s' flavor='%s' nics='%s'",
2789 image_id,
2790 flavor_id,
2791 str(net_list),
2792 )
2793
tierno7edb6752016-03-21 17:37:52 +01002794 try:
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02002795 server = None
tierno98e909c2017-10-14 13:27:03 +02002796 created_items = {}
tierno98e909c2017-10-14 13:27:03 +02002797 net_list_vim = []
Gulsum Atici26f73662022-10-27 15:18:27 +03002798 # list of external networks to be connected to instance, later on used to create floating_ip
tierno1ec592d2020-06-16 15:29:47 +00002799 external_network = []
Gulsum Atici26f73662022-10-27 15:18:27 +03002800 # List of ports with port-security disabled
2801 no_secured_ports = []
Gulsum Atici13d02322022-11-18 00:10:15 +03002802 block_device_mapping = {}
Gulsum Atici26f73662022-10-27 15:18:27 +03002803 existing_vim_volumes = []
2804 server_group_id = None
2805 scheduller_hints = {}
tiernoa05b65a2019-02-01 12:30:27 +00002806
Gulsum Atici26f73662022-10-27 15:18:27 +03002807 # Check the Openstack Connection
2808 self._reload_connection()
Pablo Montes Moreno3be0b2a2017-03-30 13:22:15 +02002809
Gulsum Atici26f73662022-10-27 15:18:27 +03002810 # Prepare network list
2811 self._prepare_network_for_vminstance(
2812 name=name,
2813 net_list=net_list,
2814 created_items=created_items,
2815 net_list_vim=net_list_vim,
2816 external_network=external_network,
2817 no_secured_ports=no_secured_ports,
sousaedu80135b92021-02-17 15:05:18 +01002818 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002819
Gulsum Atici26f73662022-10-27 15:18:27 +03002820 # Cloud config
tierno0a1437e2017-10-02 00:17:43 +02002821 config_drive, userdata = self._create_user_data(cloud_config)
montesmoreno0c8def02016-12-22 12:16:23 +00002822
Gulsum Atici26f73662022-10-27 15:18:27 +03002823 # Get availability Zone
Alexis Romero247cc432022-05-12 13:23:25 +02002824 vm_av_zone = self._get_vm_availability_zone(
2825 availability_zone_index, availability_zone_list
2826 )
2827
tierno1df468d2018-07-06 14:25:16 +02002828 if disk_list:
Gulsum Atici26f73662022-10-27 15:18:27 +03002829 # Prepare disks
2830 self._prepare_disk_for_vminstance(
2831 name=name,
2832 existing_vim_volumes=existing_vim_volumes,
2833 created_items=created_items,
2834 vm_av_zone=vm_av_zone,
Gulsum Atici13d02322022-11-18 00:10:15 +03002835 block_device_mapping=block_device_mapping,
Gulsum Atici26f73662022-10-27 15:18:27 +03002836 disk_list=disk_list,
2837 )
Alexis Romerob70f4ed2022-03-11 18:00:49 +01002838
2839 if affinity_group_list:
2840 # Only first id on the list will be used. Openstack restriction
2841 server_group_id = affinity_group_list[0]["affinity_group_id"]
2842 scheduller_hints["group"] = server_group_id
2843
sousaedu80135b92021-02-17 15:05:18 +01002844 self.logger.debug(
2845 "nova.servers.create({}, {}, {}, nics={}, security_groups={}, "
2846 "availability_zone={}, key_name={}, userdata={}, config_drive={}, "
Alexis Romerob70f4ed2022-03-11 18:00:49 +01002847 "block_device_mapping={}, server_group={})".format(
sousaedu80135b92021-02-17 15:05:18 +01002848 name,
2849 image_id,
2850 flavor_id,
2851 net_list_vim,
2852 self.config.get("security_groups"),
2853 vm_av_zone,
2854 self.config.get("keypair"),
2855 userdata,
2856 config_drive,
2857 block_device_mapping,
Alexis Romerob70f4ed2022-03-11 18:00:49 +01002858 server_group_id,
sousaedu80135b92021-02-17 15:05:18 +01002859 )
2860 )
Gulsum Atici26f73662022-10-27 15:18:27 +03002861 # Create VM
sousaedu80135b92021-02-17 15:05:18 +01002862 server = self.nova.servers.create(
aticigcf14bb12022-05-19 13:03:17 +03002863 name=name,
2864 image=image_id,
2865 flavor=flavor_id,
sousaedu80135b92021-02-17 15:05:18 +01002866 nics=net_list_vim,
2867 security_groups=self.config.get("security_groups"),
2868 # TODO remove security_groups in future versions. Already at neutron port
2869 availability_zone=vm_av_zone,
2870 key_name=self.config.get("keypair"),
2871 userdata=userdata,
2872 config_drive=config_drive,
2873 block_device_mapping=block_device_mapping,
Alexis Romerob70f4ed2022-03-11 18:00:49 +01002874 scheduler_hints=scheduller_hints,
Gulsum Atici26f73662022-10-27 15:18:27 +03002875 )
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02002876
tierno326fd5e2018-02-22 11:58:59 +01002877 vm_start_time = time.time()
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02002878
Gulsum Atici26f73662022-10-27 15:18:27 +03002879 self._update_port_security_for_vminstance(no_secured_ports, server)
bravof7a1f5252020-10-20 10:27:42 -03002880
Gulsum Atici26f73662022-10-27 15:18:27 +03002881 self._prepare_external_network_for_vminstance(
2882 external_network=external_network,
2883 server=server,
2884 created_items=created_items,
2885 vm_start_time=vm_start_time,
2886 )
montesmoreno2a1fc4e2017-01-09 16:46:04 +00002887
tierno98e909c2017-10-14 13:27:03 +02002888 return server.id, created_items
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02002889
2890 except Exception as e:
tierno98e909c2017-10-14 13:27:03 +02002891 server_id = None
2892 if server:
2893 server_id = server.id
sousaedu80135b92021-02-17 15:05:18 +01002894
tierno98e909c2017-10-14 13:27:03 +02002895 try:
aticig2f4ab6c2022-09-03 18:15:20 +03002896 created_items = self.remove_keep_tag_from_persistent_volumes(
2897 created_items
2898 )
2899
tierno98e909c2017-10-14 13:27:03 +02002900 self.delete_vminstance(server_id, created_items)
Gulsum Atici26f73662022-10-27 15:18:27 +03002901
tierno98e909c2017-10-14 13:27:03 +02002902 except Exception as e2:
2903 self.logger.error("new_vminstance rollback fail {}".format(e2))
Pablo Montes Moreno6a7785b2017-07-03 10:44:30 +02002904
tiernoae4a8d12016-07-08 12:30:39 +02002905 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01002906
aticig2f4ab6c2022-09-03 18:15:20 +03002907 @staticmethod
2908 def remove_keep_tag_from_persistent_volumes(created_items: Dict) -> Dict:
2909 """Removes the keep flag from persistent volumes. So, those volumes could be removed.
2910
2911 Args:
2912 created_items (dict): All created items belongs to VM
2913
2914 Returns:
2915 updated_created_items (dict): Dict which does not include keep flag for volumes.
2916
2917 """
2918 return {
2919 key.replace(":keep", ""): value for (key, value) in created_items.items()
2920 }
2921
tierno1ec592d2020-06-16 15:29:47 +00002922 def get_vminstance(self, vm_id):
2923 """Returns the VM instance information from VIM"""
vegallc53829d2023-06-01 00:47:44 -05002924 return self._find_nova_server(vm_id)
tiernoae4a8d12016-07-08 12:30:39 +02002925
tierno1ec592d2020-06-16 15:29:47 +00002926 def get_vminstance_console(self, vm_id, console_type="vnc"):
2927 """
tierno7edb6752016-03-21 17:37:52 +01002928 Get a console for the virtual machine
2929 Params:
2930 vm_id: uuid of the VM
2931 console_type, can be:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002932 "novnc" (by default), "xvpvnc" for VNC types,
tierno7edb6752016-03-21 17:37:52 +01002933 "rdp-html5" for RDP types, "spice-html5" for SPICE types
tiernoae4a8d12016-07-08 12:30:39 +02002934 Returns dict with the console parameters:
2935 protocol: ssh, ftp, http, https, ...
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002936 server: usually ip address
2937 port: the http, ssh, ... port
2938 suffix: extra text, e.g. the http path and query string
tierno1ec592d2020-06-16 15:29:47 +00002939 """
tiernoae4a8d12016-07-08 12:30:39 +02002940 self.logger.debug("Getting VM CONSOLE from VIM")
sousaedu80135b92021-02-17 15:05:18 +01002941
tierno7edb6752016-03-21 17:37:52 +01002942 try:
2943 self._reload_connection()
2944 server = self.nova.servers.find(id=vm_id)
sousaedu80135b92021-02-17 15:05:18 +01002945
tierno1ec592d2020-06-16 15:29:47 +00002946 if console_type is None or console_type == "novnc":
tierno7edb6752016-03-21 17:37:52 +01002947 console_dict = server.get_vnc_console("novnc")
2948 elif console_type == "xvpvnc":
2949 console_dict = server.get_vnc_console(console_type)
2950 elif console_type == "rdp-html5":
2951 console_dict = server.get_rdp_console(console_type)
2952 elif console_type == "spice-html5":
2953 console_dict = server.get_spice_console(console_type)
2954 else:
sousaedu80135b92021-02-17 15:05:18 +01002955 raise vimconn.VimConnException(
2956 "console type '{}' not allowed".format(console_type),
2957 http_code=vimconn.HTTP_Bad_Request,
2958 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00002959
tierno7edb6752016-03-21 17:37:52 +01002960 console_dict1 = console_dict.get("console")
sousaedu80135b92021-02-17 15:05:18 +01002961
tierno7edb6752016-03-21 17:37:52 +01002962 if console_dict1:
2963 console_url = console_dict1.get("url")
sousaedu80135b92021-02-17 15:05:18 +01002964
tierno7edb6752016-03-21 17:37:52 +01002965 if console_url:
tierno1ec592d2020-06-16 15:29:47 +00002966 # parse console_url
tierno7edb6752016-03-21 17:37:52 +01002967 protocol_index = console_url.find("//")
sousaedu80135b92021-02-17 15:05:18 +01002968 suffix_index = (
2969 console_url[protocol_index + 2 :].find("/") + protocol_index + 2
2970 )
2971 port_index = (
2972 console_url[protocol_index + 2 : suffix_index].find(":")
2973 + protocol_index
2974 + 2
2975 )
2976
tierno1ec592d2020-06-16 15:29:47 +00002977 if protocol_index < 0 or port_index < 0 or suffix_index < 0:
sousaedu80135b92021-02-17 15:05:18 +01002978 return (
2979 -vimconn.HTTP_Internal_Server_Error,
2980 "Unexpected response from VIM",
2981 )
2982
2983 console_dict = {
2984 "protocol": console_url[0:protocol_index],
2985 "server": console_url[protocol_index + 2 : port_index],
2986 "port": console_url[port_index:suffix_index],
2987 "suffix": console_url[suffix_index + 1 :],
2988 }
tierno7edb6752016-03-21 17:37:52 +01002989 protocol_index += 2
sousaedu80135b92021-02-17 15:05:18 +01002990
tiernoae4a8d12016-07-08 12:30:39 +02002991 return console_dict
tierno72774862020-05-04 11:44:15 +00002992 raise vimconn.VimConnUnexpectedResponse("Unexpected response from VIM")
sousaedu80135b92021-02-17 15:05:18 +01002993 except (
2994 nvExceptions.NotFound,
2995 ksExceptions.ClientException,
2996 nvExceptions.ClientException,
2997 nvExceptions.BadRequest,
2998 ConnectionError,
2999 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02003000 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01003001
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03003002 def _delete_ports_by_id_wth_neutron(self, k_id: str) -> None:
3003 """Neutron delete ports by id.
3004 Args:
3005 k_id (str): Port id in the VIM
3006 """
3007 try:
limon81d093c2023-07-24 15:53:41 +02003008 self.neutron.delete_port(k_id)
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03003009
3010 except Exception as e:
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03003011 self.logger.error("Error deleting port: {}: {}".format(type(e).__name__, e))
3012
vegall364627c2023-03-17 15:09:50 +00003013 def delete_shared_volumes(self, shared_volume_vim_id: str) -> bool:
3014 """Cinder delete volume by id.
3015 Args:
3016 shared_volume_vim_id (str): ID of shared volume in VIM
3017 """
Gabriel Cuba1fd411b2023-06-14 00:50:57 -05003018 elapsed_time = 0
vegall364627c2023-03-17 15:09:50 +00003019 try:
Gabriel Cuba1fd411b2023-06-14 00:50:57 -05003020 while elapsed_time < server_timeout:
3021 vol_status = self.cinder.volumes.get(shared_volume_vim_id).status
3022 if vol_status == "available":
3023 self.cinder.volumes.delete(shared_volume_vim_id)
3024 return True
vegall364627c2023-03-17 15:09:50 +00003025
Gabriel Cuba1fd411b2023-06-14 00:50:57 -05003026 time.sleep(5)
3027 elapsed_time += 5
3028
3029 if elapsed_time >= server_timeout:
3030 raise vimconn.VimConnException(
3031 "Timeout waiting for volume "
3032 + shared_volume_vim_id
3033 + " to be available",
3034 http_code=vimconn.HTTP_Request_Timeout,
3035 )
vegall364627c2023-03-17 15:09:50 +00003036
3037 except Exception as e:
3038 self.logger.error(
3039 "Error deleting volume: {}: {}".format(type(e).__name__, e)
3040 )
Gabriel Cuba1fd411b2023-06-14 00:50:57 -05003041 self._format_exception(e)
vegall364627c2023-03-17 15:09:50 +00003042
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03003043 def _delete_volumes_by_id_wth_cinder(
3044 self, k: str, k_id: str, volumes_to_hold: list, created_items: dict
3045 ) -> bool:
3046 """Cinder delete volume by id.
3047 Args:
3048 k (str): Full item name in created_items
3049 k_id (str): ID of floating ip in VIM
3050 volumes_to_hold (list): Volumes not to delete
3051 created_items (dict): All created items belongs to VM
3052 """
3053 try:
3054 if k_id in volumes_to_hold:
3055 return
3056
3057 if self.cinder.volumes.get(k_id).status != "available":
3058 return True
3059
3060 else:
3061 self.cinder.volumes.delete(k_id)
3062 created_items[k] = None
3063
3064 except Exception as e:
3065 self.logger.error(
3066 "Error deleting volume: {}: {}".format(type(e).__name__, e)
3067 )
3068
3069 def _delete_floating_ip_by_id(self, k: str, k_id: str, created_items: dict) -> None:
3070 """Neutron delete floating ip by id.
3071 Args:
3072 k (str): Full item name in created_items
3073 k_id (str): ID of floating ip in VIM
3074 created_items (dict): All created items belongs to VM
3075 """
3076 try:
3077 self.neutron.delete_floatingip(k_id)
3078 created_items[k] = None
3079
3080 except Exception as e:
3081 self.logger.error(
3082 "Error deleting floating ip: {}: {}".format(type(e).__name__, e)
3083 )
3084
3085 @staticmethod
3086 def _get_item_name_id(k: str) -> Tuple[str, str]:
3087 k_item, _, k_id = k.partition(":")
3088 return k_item, k_id
3089
3090 def _delete_vm_ports_attached_to_network(self, created_items: dict) -> None:
3091 """Delete VM ports attached to the networks before deleting virtual machine.
3092 Args:
3093 created_items (dict): All created items belongs to VM
3094 """
3095
3096 for k, v in created_items.items():
3097 if not v: # skip already deleted
3098 continue
3099
3100 try:
3101 k_item, k_id = self._get_item_name_id(k)
3102 if k_item == "port":
3103 self._delete_ports_by_id_wth_neutron(k_id)
3104
3105 except Exception as e:
3106 self.logger.error(
3107 "Error deleting port: {}: {}".format(type(e).__name__, e)
3108 )
3109
3110 def _delete_created_items(
3111 self, created_items: dict, volumes_to_hold: list, keep_waiting: bool
3112 ) -> bool:
3113 """Delete Volumes and floating ip if they exist in created_items."""
3114 for k, v in created_items.items():
3115 if not v: # skip already deleted
3116 continue
3117
3118 try:
3119 k_item, k_id = self._get_item_name_id(k)
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03003120 if k_item == "volume":
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03003121 unavailable_vol = self._delete_volumes_by_id_wth_cinder(
3122 k, k_id, volumes_to_hold, created_items
3123 )
3124
3125 if unavailable_vol:
3126 keep_waiting = True
3127
3128 elif k_item == "floating_ip":
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03003129 self._delete_floating_ip_by_id(k, k_id, created_items)
3130
3131 except Exception as e:
3132 self.logger.error("Error deleting {}: {}".format(k, e))
3133
3134 return keep_waiting
3135
aticig2f4ab6c2022-09-03 18:15:20 +03003136 @staticmethod
3137 def _extract_items_wth_keep_flag_from_created_items(created_items: dict) -> dict:
3138 """Remove the volumes which has key flag from created_items
3139
3140 Args:
3141 created_items (dict): All created items belongs to VM
3142
3143 Returns:
3144 created_items (dict): Persistent volumes eliminated created_items
3145 """
3146 return {
3147 key: value
3148 for (key, value) in created_items.items()
3149 if len(key.split(":")) == 2
3150 }
3151
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03003152 def delete_vminstance(
3153 self, vm_id: str, created_items: dict = None, volumes_to_hold: list = None
3154 ) -> None:
3155 """Removes a VM instance from VIM. Returns the old identifier.
3156 Args:
3157 vm_id (str): Identifier of VM instance
3158 created_items (dict): All created items belongs to VM
3159 volumes_to_hold (list): Volumes_to_hold
3160 """
tierno1ec592d2020-06-16 15:29:47 +00003161 if created_items is None:
tierno98e909c2017-10-14 13:27:03 +02003162 created_items = {}
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03003163 if volumes_to_hold is None:
3164 volumes_to_hold = []
sousaedu80135b92021-02-17 15:05:18 +01003165
tierno7edb6752016-03-21 17:37:52 +01003166 try:
aticig2f4ab6c2022-09-03 18:15:20 +03003167 created_items = self._extract_items_wth_keep_flag_from_created_items(
3168 created_items
3169 )
3170
tierno7edb6752016-03-21 17:37:52 +01003171 self._reload_connection()
sousaedu80135b92021-02-17 15:05:18 +01003172
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03003173 # Delete VM ports attached to the networks before the virtual machine
3174 if created_items:
3175 self._delete_vm_ports_attached_to_network(created_items)
montesmoreno0c8def02016-12-22 12:16:23 +00003176
tierno98e909c2017-10-14 13:27:03 +02003177 if vm_id:
3178 self.nova.servers.delete(vm_id)
montesmoreno0c8def02016-12-22 12:16:23 +00003179
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03003180 # Although having detached, volumes should have in active status before deleting.
3181 # We ensure in this loop
montesmoreno0c8def02016-12-22 12:16:23 +00003182 keep_waiting = True
3183 elapsed_time = 0
sousaedu80135b92021-02-17 15:05:18 +01003184
montesmoreno0c8def02016-12-22 12:16:23 +00003185 while keep_waiting and elapsed_time < volume_timeout:
3186 keep_waiting = False
sousaedu80135b92021-02-17 15:05:18 +01003187
Gulsum Atici4bc8eb92022-11-21 14:11:02 +03003188 # Delete volumes and floating IP.
3189 keep_waiting = self._delete_created_items(
3190 created_items, volumes_to_hold, keep_waiting
3191 )
sousaedu80135b92021-02-17 15:05:18 +01003192
montesmoreno0c8def02016-12-22 12:16:23 +00003193 if keep_waiting:
3194 time.sleep(1)
3195 elapsed_time += 1
sousaedu80135b92021-02-17 15:05:18 +01003196
sousaedu80135b92021-02-17 15:05:18 +01003197 except (
3198 nvExceptions.NotFound,
3199 ksExceptions.ClientException,
3200 nvExceptions.ClientException,
3201 ConnectionError,
3202 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02003203 self._format_exception(e)
tierno7edb6752016-03-21 17:37:52 +01003204
tiernoae4a8d12016-07-08 12:30:39 +02003205 def refresh_vms_status(self, vm_list):
tierno1ec592d2020-06-16 15:29:47 +00003206 """Get the status of the virtual machines and their interfaces/ports
sousaedu80135b92021-02-17 15:05:18 +01003207 Params: the list of VM identifiers
3208 Returns a dictionary with:
3209 vm_id: #VIM id of this Virtual Machine
3210 status: #Mandatory. Text with one of:
3211 # DELETED (not found at vim)
3212 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
3213 # OTHER (Vim reported other status not understood)
3214 # ERROR (VIM indicates an ERROR status)
3215 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
3216 # CREATING (on building process), ERROR
3217 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
3218 #
3219 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
3220 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
3221 interfaces:
3222 - vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
3223 mac_address: #Text format XX:XX:XX:XX:XX:XX
3224 vim_net_id: #network id where this interface is connected
3225 vim_interface_id: #interface/port VIM id
3226 ip_address: #null, or text with IPv4, IPv6 address
3227 compute_node: #identification of compute node where PF,VF interface is allocated
3228 pci: #PCI address of the NIC that hosts the PF,VF
3229 vlan: #physical VLAN used for VF
tierno1ec592d2020-06-16 15:29:47 +00003230 """
3231 vm_dict = {}
sousaedu80135b92021-02-17 15:05:18 +01003232 self.logger.debug(
3233 "refresh_vms status: Getting tenant VM instance information from VIM"
3234 )
3235
tiernoae4a8d12016-07-08 12:30:39 +02003236 for vm_id in vm_list:
tierno1ec592d2020-06-16 15:29:47 +00003237 vm = {}
sousaedu80135b92021-02-17 15:05:18 +01003238
tiernoae4a8d12016-07-08 12:30:39 +02003239 try:
3240 vm_vim = self.get_vminstance(vm_id)
sousaedu80135b92021-02-17 15:05:18 +01003241
3242 if vm_vim["status"] in vmStatus2manoFormat:
3243 vm["status"] = vmStatus2manoFormat[vm_vim["status"]]
tierno7edb6752016-03-21 17:37:52 +01003244 else:
sousaedu80135b92021-02-17 15:05:18 +01003245 vm["status"] = "OTHER"
3246 vm["error_msg"] = "VIM status reported " + vm_vim["status"]
3247
tierno70eeb182020-10-19 16:38:00 +00003248 vm_vim.pop("OS-EXT-SRV-ATTR:user_data", None)
3249 vm_vim.pop("user_data", None)
sousaedu80135b92021-02-17 15:05:18 +01003250 vm["vim_info"] = self.serialize(vm_vim)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003251
tiernoae4a8d12016-07-08 12:30:39 +02003252 vm["interfaces"] = []
sousaedu80135b92021-02-17 15:05:18 +01003253 if vm_vim.get("fault"):
3254 vm["error_msg"] = str(vm_vim["fault"])
3255
tierno1ec592d2020-06-16 15:29:47 +00003256 # get interfaces
tierno7edb6752016-03-21 17:37:52 +01003257 try:
tiernoae4a8d12016-07-08 12:30:39 +02003258 self._reload_connection()
tiernob42fd9b2018-06-20 10:44:32 +02003259 port_dict = self.neutron.list_ports(device_id=vm_id)
sousaedu80135b92021-02-17 15:05:18 +01003260
tiernoae4a8d12016-07-08 12:30:39 +02003261 for port in port_dict["ports"]:
tierno1ec592d2020-06-16 15:29:47 +00003262 interface = {}
sousaedu80135b92021-02-17 15:05:18 +01003263 interface["vim_info"] = self.serialize(port)
tiernoae4a8d12016-07-08 12:30:39 +02003264 interface["mac_address"] = port.get("mac_address")
3265 interface["vim_net_id"] = port["network_id"]
3266 interface["vim_interface_id"] = port["id"]
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003267 # check if OS-EXT-SRV-ATTR:host is there,
Mike Marchetti5b9da422017-05-02 15:35:47 -04003268 # in case of non-admin credentials, it will be missing
sousaedu80135b92021-02-17 15:05:18 +01003269
3270 if vm_vim.get("OS-EXT-SRV-ATTR:host"):
3271 interface["compute_node"] = vm_vim["OS-EXT-SRV-ATTR:host"]
3272
tierno867ffe92017-03-27 12:50:34 +02003273 interface["pci"] = None
Mike Marchetti5b9da422017-05-02 15:35:47 -04003274
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003275 # check if binding:profile is there,
Mike Marchetti5b9da422017-05-02 15:35:47 -04003276 # in case of non-admin credentials, it will be missing
sousaedu80135b92021-02-17 15:05:18 +01003277 if port.get("binding:profile"):
3278 if port["binding:profile"].get("pci_slot"):
tierno1ec592d2020-06-16 15:29:47 +00003279 # TODO: At the moment sr-iov pci addresses are converted to PF pci addresses by setting
3280 # the slot to 0x00
Mike Marchetti5b9da422017-05-02 15:35:47 -04003281 # TODO: This is just a workaround valid for niantinc. Find a better way to do so
3282 # CHANGE DDDD:BB:SS.F to DDDD:BB:00.(F%2) assuming there are 2 ports per nic
sousaedu80135b92021-02-17 15:05:18 +01003283 pci = port["binding:profile"]["pci_slot"]
Mike Marchetti5b9da422017-05-02 15:35:47 -04003284 # interface["pci"] = pci[:-4] + "00." + str(int(pci[-1]) % 2)
3285 interface["pci"] = pci
sousaedu80135b92021-02-17 15:05:18 +01003286
tierno867ffe92017-03-27 12:50:34 +02003287 interface["vlan"] = None
sousaedu80135b92021-02-17 15:05:18 +01003288
3289 if port.get("binding:vif_details"):
3290 interface["vlan"] = port["binding:vif_details"].get("vlan")
3291
tierno1dfe9932020-06-18 08:50:10 +00003292 # Get vlan from network in case not present in port for those old openstacks and cases where
3293 # it is needed vlan at PT
3294 if not interface["vlan"]:
3295 # if network is of type vlan and port is of type direct (sr-iov) then set vlan id
3296 network = self.neutron.show_network(port["network_id"])
sousaedu80135b92021-02-17 15:05:18 +01003297
3298 if (
3299 network["network"].get("provider:network_type")
3300 == "vlan"
3301 ):
tierno1dfe9932020-06-18 08:50:10 +00003302 # and port.get("binding:vnic_type") in ("direct", "direct-physical"):
sousaedu80135b92021-02-17 15:05:18 +01003303 interface["vlan"] = network["network"].get(
3304 "provider:segmentation_id"
3305 )
3306
tierno1ec592d2020-06-16 15:29:47 +00003307 ips = []
3308 # look for floating ip address
tiernob42fd9b2018-06-20 10:44:32 +02003309 try:
sousaedu80135b92021-02-17 15:05:18 +01003310 floating_ip_dict = self.neutron.list_floatingips(
3311 port_id=port["id"]
3312 )
3313
tiernob42fd9b2018-06-20 10:44:32 +02003314 if floating_ip_dict.get("floatingips"):
sousaedu80135b92021-02-17 15:05:18 +01003315 ips.append(
3316 floating_ip_dict["floatingips"][0].get(
3317 "floating_ip_address"
3318 )
3319 )
tiernob42fd9b2018-06-20 10:44:32 +02003320 except Exception:
3321 pass
tierno7edb6752016-03-21 17:37:52 +01003322
tiernoae4a8d12016-07-08 12:30:39 +02003323 for subnet in port["fixed_ips"]:
3324 ips.append(subnet["ip_address"])
sousaedu80135b92021-02-17 15:05:18 +01003325
tiernoae4a8d12016-07-08 12:30:39 +02003326 interface["ip_address"] = ";".join(ips)
3327 vm["interfaces"].append(interface)
3328 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01003329 self.logger.error(
3330 "Error getting vm interface information {}: {}".format(
3331 type(e).__name__, e
3332 ),
3333 exc_info=True,
3334 )
tierno72774862020-05-04 11:44:15 +00003335 except vimconn.VimConnNotFoundException as e:
tiernoae4a8d12016-07-08 12:30:39 +02003336 self.logger.error("Exception getting vm status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01003337 vm["status"] = "DELETED"
3338 vm["error_msg"] = str(e)
tierno72774862020-05-04 11:44:15 +00003339 except vimconn.VimConnException as e:
tiernoae4a8d12016-07-08 12:30:39 +02003340 self.logger.error("Exception getting vm status: %s", str(e))
sousaedu80135b92021-02-17 15:05:18 +01003341 vm["status"] = "VIM_ERROR"
3342 vm["error_msg"] = str(e)
3343
tiernoae4a8d12016-07-08 12:30:39 +02003344 vm_dict[vm_id] = vm
sousaedu80135b92021-02-17 15:05:18 +01003345
tiernoae4a8d12016-07-08 12:30:39 +02003346 return vm_dict
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003347
tierno98e909c2017-10-14 13:27:03 +02003348 def action_vminstance(self, vm_id, action_dict, created_items={}):
tierno1ec592d2020-06-16 15:29:47 +00003349 """Send and action over a VM instance from VIM
Gulsum Atici21c55d62023-02-02 20:41:00 +03003350 Returns None or the console dict if the action was successfully sent to the VIM
3351 """
tiernoae4a8d12016-07-08 12:30:39 +02003352 self.logger.debug("Action over VM '%s': %s", vm_id, str(action_dict))
sousaedu80135b92021-02-17 15:05:18 +01003353
tierno7edb6752016-03-21 17:37:52 +01003354 try:
3355 self._reload_connection()
3356 server = self.nova.servers.find(id=vm_id)
sousaedu80135b92021-02-17 15:05:18 +01003357
tierno7edb6752016-03-21 17:37:52 +01003358 if "start" in action_dict:
tierno1ec592d2020-06-16 15:29:47 +00003359 if action_dict["start"] == "rebuild":
tierno7edb6752016-03-21 17:37:52 +01003360 server.rebuild()
3361 else:
tierno1ec592d2020-06-16 15:29:47 +00003362 if server.status == "PAUSED":
tierno7edb6752016-03-21 17:37:52 +01003363 server.unpause()
tierno1ec592d2020-06-16 15:29:47 +00003364 elif server.status == "SUSPENDED":
tierno7edb6752016-03-21 17:37:52 +01003365 server.resume()
tierno1ec592d2020-06-16 15:29:47 +00003366 elif server.status == "SHUTOFF":
tierno7edb6752016-03-21 17:37:52 +01003367 server.start()
k4.rahul78f474e2022-05-02 15:47:57 +00003368 else:
3369 self.logger.debug(
3370 "ERROR : Instance is not in SHUTOFF/PAUSE/SUSPEND state"
3371 )
3372 raise vimconn.VimConnException(
3373 "Cannot 'start' instance while it is in active state",
3374 http_code=vimconn.HTTP_Bad_Request,
3375 )
3376
tierno7edb6752016-03-21 17:37:52 +01003377 elif "pause" in action_dict:
3378 server.pause()
3379 elif "resume" in action_dict:
3380 server.resume()
3381 elif "shutoff" in action_dict or "shutdown" in action_dict:
k4.rahul78f474e2022-05-02 15:47:57 +00003382 self.logger.debug("server status %s", server.status)
3383 if server.status == "ACTIVE":
3384 server.stop()
3385 else:
3386 self.logger.debug("ERROR: VM is not in Active state")
3387 raise vimconn.VimConnException(
3388 "VM is not in active state, stop operation is not allowed",
3389 http_code=vimconn.HTTP_Bad_Request,
3390 )
tierno7edb6752016-03-21 17:37:52 +01003391 elif "forceOff" in action_dict:
tierno1ec592d2020-06-16 15:29:47 +00003392 server.stop() # TODO
tierno7edb6752016-03-21 17:37:52 +01003393 elif "terminate" in action_dict:
3394 server.delete()
3395 elif "createImage" in action_dict:
3396 server.create_image()
tierno1ec592d2020-06-16 15:29:47 +00003397 # "path":path_schema,
3398 # "description":description_schema,
3399 # "name":name_schema,
3400 # "metadata":metadata_schema,
3401 # "imageRef": id_schema,
3402 # "disk": {"oneOf":[{"type": "null"}, {"type":"string"}] },
tierno7edb6752016-03-21 17:37:52 +01003403 elif "rebuild" in action_dict:
sousaedu80135b92021-02-17 15:05:18 +01003404 server.rebuild(server.image["id"])
tierno7edb6752016-03-21 17:37:52 +01003405 elif "reboot" in action_dict:
sousaedu80135b92021-02-17 15:05:18 +01003406 server.reboot() # reboot_type="SOFT"
tierno7edb6752016-03-21 17:37:52 +01003407 elif "console" in action_dict:
3408 console_type = action_dict["console"]
sousaedu80135b92021-02-17 15:05:18 +01003409
tierno1ec592d2020-06-16 15:29:47 +00003410 if console_type is None or console_type == "novnc":
tierno7edb6752016-03-21 17:37:52 +01003411 console_dict = server.get_vnc_console("novnc")
3412 elif console_type == "xvpvnc":
3413 console_dict = server.get_vnc_console(console_type)
3414 elif console_type == "rdp-html5":
3415 console_dict = server.get_rdp_console(console_type)
3416 elif console_type == "spice-html5":
3417 console_dict = server.get_spice_console(console_type)
3418 else:
sousaedu80135b92021-02-17 15:05:18 +01003419 raise vimconn.VimConnException(
3420 "console type '{}' not allowed".format(console_type),
3421 http_code=vimconn.HTTP_Bad_Request,
3422 )
3423
tierno7edb6752016-03-21 17:37:52 +01003424 try:
3425 console_url = console_dict["console"]["url"]
tierno1ec592d2020-06-16 15:29:47 +00003426 # parse console_url
tierno7edb6752016-03-21 17:37:52 +01003427 protocol_index = console_url.find("//")
sousaedu80135b92021-02-17 15:05:18 +01003428 suffix_index = (
3429 console_url[protocol_index + 2 :].find("/") + protocol_index + 2
3430 )
3431 port_index = (
3432 console_url[protocol_index + 2 : suffix_index].find(":")
3433 + protocol_index
3434 + 2
3435 )
3436
tierno1ec592d2020-06-16 15:29:47 +00003437 if protocol_index < 0 or port_index < 0 or suffix_index < 0:
sousaedu80135b92021-02-17 15:05:18 +01003438 raise vimconn.VimConnException(
3439 "Unexpected response from VIM " + str(console_dict)
3440 )
3441
3442 console_dict2 = {
3443 "protocol": console_url[0:protocol_index],
3444 "server": console_url[protocol_index + 2 : port_index],
3445 "port": int(console_url[port_index + 1 : suffix_index]),
3446 "suffix": console_url[suffix_index + 1 :],
3447 }
3448
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003449 return console_dict2
tierno1ec592d2020-06-16 15:29:47 +00003450 except Exception:
sousaedu80135b92021-02-17 15:05:18 +01003451 raise vimconn.VimConnException(
3452 "Unexpected response from VIM " + str(console_dict)
3453 )
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003454
tierno98e909c2017-10-14 13:27:03 +02003455 return None
sousaedu80135b92021-02-17 15:05:18 +01003456 except (
3457 ksExceptions.ClientException,
3458 nvExceptions.ClientException,
3459 nvExceptions.NotFound,
3460 ConnectionError,
3461 ) as e:
tiernoae4a8d12016-07-08 12:30:39 +02003462 self._format_exception(e)
tierno1ec592d2020-06-16 15:29:47 +00003463 # TODO insert exception vimconn.HTTP_Unauthorized
tiernoae4a8d12016-07-08 12:30:39 +02003464
tierno1ec592d2020-06-16 15:29:47 +00003465 # ###### VIO Specific Changes #########
garciadeblasebd66722019-01-31 16:01:31 +00003466 def _generate_vlanID(self):
kate721d79b2017-06-24 04:21:38 -07003467 """
sousaedu80135b92021-02-17 15:05:18 +01003468 Method to get unused vlanID
kate721d79b2017-06-24 04:21:38 -07003469 Args:
3470 None
3471 Returns:
3472 vlanID
3473 """
tierno1ec592d2020-06-16 15:29:47 +00003474 # Get used VLAN IDs
kate721d79b2017-06-24 04:21:38 -07003475 usedVlanIDs = []
3476 networks = self.get_network_list()
sousaedu80135b92021-02-17 15:05:18 +01003477
kate721d79b2017-06-24 04:21:38 -07003478 for net in networks:
sousaedu80135b92021-02-17 15:05:18 +01003479 if net.get("provider:segmentation_id"):
3480 usedVlanIDs.append(net.get("provider:segmentation_id"))
3481
kate721d79b2017-06-24 04:21:38 -07003482 used_vlanIDs = set(usedVlanIDs)
3483
tierno1ec592d2020-06-16 15:29:47 +00003484 # find unused VLAN ID
sousaedu80135b92021-02-17 15:05:18 +01003485 for vlanID_range in self.config.get("dataplane_net_vlan_range"):
kate721d79b2017-06-24 04:21:38 -07003486 try:
sousaedu80135b92021-02-17 15:05:18 +01003487 start_vlanid, end_vlanid = map(
3488 int, vlanID_range.replace(" ", "").split("-")
3489 )
3490
tierno7d782ef2019-10-04 12:56:31 +00003491 for vlanID in range(start_vlanid, end_vlanid + 1):
kate721d79b2017-06-24 04:21:38 -07003492 if vlanID not in used_vlanIDs:
3493 return vlanID
3494 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01003495 raise vimconn.VimConnException(
3496 "Exception {} occurred while generating VLAN ID.".format(exp)
3497 )
kate721d79b2017-06-24 04:21:38 -07003498 else:
tierno1ec592d2020-06-16 15:29:47 +00003499 raise vimconn.VimConnConflictException(
3500 "Unable to create the SRIOV VLAN network. All given Vlan IDs {} are in use.".format(
sousaedu80135b92021-02-17 15:05:18 +01003501 self.config.get("dataplane_net_vlan_range")
3502 )
3503 )
kate721d79b2017-06-24 04:21:38 -07003504
garciadeblasebd66722019-01-31 16:01:31 +00003505 def _generate_multisegment_vlanID(self):
3506 """
sousaedu80135b92021-02-17 15:05:18 +01003507 Method to get unused vlanID
3508 Args:
3509 None
3510 Returns:
3511 vlanID
garciadeblasebd66722019-01-31 16:01:31 +00003512 """
tierno6869ae72020-01-09 17:37:34 +00003513 # Get used VLAN IDs
garciadeblasebd66722019-01-31 16:01:31 +00003514 usedVlanIDs = []
3515 networks = self.get_network_list()
3516 for net in networks:
sousaedu80135b92021-02-17 15:05:18 +01003517 if net.get("provider:network_type") == "vlan" and net.get(
3518 "provider:segmentation_id"
3519 ):
3520 usedVlanIDs.append(net.get("provider:segmentation_id"))
3521 elif net.get("segments"):
3522 for segment in net.get("segments"):
3523 if segment.get("provider:network_type") == "vlan" and segment.get(
3524 "provider:segmentation_id"
3525 ):
3526 usedVlanIDs.append(segment.get("provider:segmentation_id"))
3527
garciadeblasebd66722019-01-31 16:01:31 +00003528 used_vlanIDs = set(usedVlanIDs)
3529
tierno6869ae72020-01-09 17:37:34 +00003530 # find unused VLAN ID
sousaedu80135b92021-02-17 15:05:18 +01003531 for vlanID_range in self.config.get("multisegment_vlan_range"):
garciadeblasebd66722019-01-31 16:01:31 +00003532 try:
sousaedu80135b92021-02-17 15:05:18 +01003533 start_vlanid, end_vlanid = map(
3534 int, vlanID_range.replace(" ", "").split("-")
3535 )
3536
tierno7d782ef2019-10-04 12:56:31 +00003537 for vlanID in range(start_vlanid, end_vlanid + 1):
garciadeblasebd66722019-01-31 16:01:31 +00003538 if vlanID not in used_vlanIDs:
3539 return vlanID
3540 except Exception as exp:
sousaedu80135b92021-02-17 15:05:18 +01003541 raise vimconn.VimConnException(
3542 "Exception {} occurred while generating VLAN ID.".format(exp)
3543 )
garciadeblasebd66722019-01-31 16:01:31 +00003544 else:
tierno1ec592d2020-06-16 15:29:47 +00003545 raise vimconn.VimConnConflictException(
3546 "Unable to create the VLAN segment. All VLAN IDs {} are in use.".format(
sousaedu80135b92021-02-17 15:05:18 +01003547 self.config.get("multisegment_vlan_range")
3548 )
3549 )
garciadeblasebd66722019-01-31 16:01:31 +00003550
3551 def _validate_vlan_ranges(self, input_vlan_range, text_vlan_range):
kate721d79b2017-06-24 04:21:38 -07003552 """
3553 Method to validate user given vlanID ranges
3554 Args: None
3555 Returns: None
3556 """
garciadeblasebd66722019-01-31 16:01:31 +00003557 for vlanID_range in input_vlan_range:
kate721d79b2017-06-24 04:21:38 -07003558 vlan_range = vlanID_range.replace(" ", "")
tierno1ec592d2020-06-16 15:29:47 +00003559 # validate format
sousaedu80135b92021-02-17 15:05:18 +01003560 vlanID_pattern = r"(\d)*-(\d)*$"
kate721d79b2017-06-24 04:21:38 -07003561 match_obj = re.match(vlanID_pattern, vlan_range)
3562 if not match_obj:
tierno1ec592d2020-06-16 15:29:47 +00003563 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +01003564 "Invalid VLAN range for {}: {}.You must provide "
3565 "'{}' in format [start_ID - end_ID].".format(
3566 text_vlan_range, vlanID_range, text_vlan_range
3567 )
3568 )
kate721d79b2017-06-24 04:21:38 -07003569
tierno1ec592d2020-06-16 15:29:47 +00003570 start_vlanid, end_vlanid = map(int, vlan_range.split("-"))
3571 if start_vlanid <= 0:
3572 raise vimconn.VimConnConflictException(
3573 "Invalid VLAN range for {}: {}. Start ID can not be zero. For VLAN "
sousaedu80135b92021-02-17 15:05:18 +01003574 "networks valid IDs are 1 to 4094 ".format(
3575 text_vlan_range, vlanID_range
3576 )
3577 )
3578
tierno1ec592d2020-06-16 15:29:47 +00003579 if end_vlanid > 4094:
3580 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +01003581 "Invalid VLAN range for {}: {}. End VLAN ID can not be "
3582 "greater than 4094. For VLAN networks valid IDs are 1 to 4094 ".format(
3583 text_vlan_range, vlanID_range
3584 )
3585 )
kate721d79b2017-06-24 04:21:38 -07003586
3587 if start_vlanid > end_vlanid:
tierno1ec592d2020-06-16 15:29:47 +00003588 raise vimconn.VimConnConflictException(
sousaedu80135b92021-02-17 15:05:18 +01003589 "Invalid VLAN range for {}: {}. You must provide '{}'"
3590 " in format start_ID - end_ID and start_ID < end_ID ".format(
3591 text_vlan_range, vlanID_range, text_vlan_range
3592 )
3593 )
kate721d79b2017-06-24 04:21:38 -07003594
tierno7edb6752016-03-21 17:37:52 +01003595 def get_hosts_info(self):
tierno1ec592d2020-06-16 15:29:47 +00003596 """Get the information of deployed hosts
3597 Returns the hosts content"""
tierno7edb6752016-03-21 17:37:52 +01003598 if self.debug:
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003599 print("osconnector: Getting Host info from VIM")
sousaedu80135b92021-02-17 15:05:18 +01003600
tierno7edb6752016-03-21 17:37:52 +01003601 try:
tierno1ec592d2020-06-16 15:29:47 +00003602 h_list = []
tierno7edb6752016-03-21 17:37:52 +01003603 self._reload_connection()
3604 hypervisors = self.nova.hypervisors.list()
sousaedu80135b92021-02-17 15:05:18 +01003605
tierno7edb6752016-03-21 17:37:52 +01003606 for hype in hypervisors:
tierno1ec592d2020-06-16 15:29:47 +00003607 h_list.append(hype.to_dict())
sousaedu80135b92021-02-17 15:05:18 +01003608
tierno1ec592d2020-06-16 15:29:47 +00003609 return 1, {"hosts": h_list}
tierno7edb6752016-03-21 17:37:52 +01003610 except nvExceptions.NotFound as e:
tierno1ec592d2020-06-16 15:29:47 +00003611 error_value = -vimconn.HTTP_Not_Found
sousaedu80135b92021-02-17 15:05:18 +01003612 error_text = str(e) if len(e.args) == 0 else str(e.args[0])
tierno7edb6752016-03-21 17:37:52 +01003613 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
tierno1ec592d2020-06-16 15:29:47 +00003614 error_value = -vimconn.HTTP_Bad_Request
sousaedu80135b92021-02-17 15:05:18 +01003615 error_text = (
3616 type(e).__name__
3617 + ": "
3618 + (str(e) if len(e.args) == 0 else str(e.args[0]))
3619 )
3620
tierno1ec592d2020-06-16 15:29:47 +00003621 # TODO insert exception vimconn.HTTP_Unauthorized
3622 # if reaching here is because an exception
tierno9c5c8322018-03-23 15:44:03 +01003623 self.logger.debug("get_hosts_info " + error_text)
sousaedu80135b92021-02-17 15:05:18 +01003624
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003625 return error_value, error_text
tierno7edb6752016-03-21 17:37:52 +01003626
3627 def get_hosts(self, vim_tenant):
tierno1ec592d2020-06-16 15:29:47 +00003628 """Get the hosts and deployed instances
3629 Returns the hosts content"""
tierno7edb6752016-03-21 17:37:52 +01003630 r, hype_dict = self.get_hosts_info()
sousaedu80135b92021-02-17 15:05:18 +01003631
tierno1ec592d2020-06-16 15:29:47 +00003632 if r < 0:
tierno7edb6752016-03-21 17:37:52 +01003633 return r, hype_dict
sousaedu80135b92021-02-17 15:05:18 +01003634
tierno7edb6752016-03-21 17:37:52 +01003635 hypervisors = hype_dict["hosts"]
sousaedu80135b92021-02-17 15:05:18 +01003636
tierno7edb6752016-03-21 17:37:52 +01003637 try:
3638 servers = self.nova.servers.list()
3639 for hype in hypervisors:
3640 for server in servers:
sousaedu80135b92021-02-17 15:05:18 +01003641 if (
3642 server.to_dict()["OS-EXT-SRV-ATTR:hypervisor_hostname"]
3643 == hype["hypervisor_hostname"]
3644 ):
3645 if "vm" in hype:
3646 hype["vm"].append(server.id)
tierno7edb6752016-03-21 17:37:52 +01003647 else:
sousaedu80135b92021-02-17 15:05:18 +01003648 hype["vm"] = [server.id]
3649
tierno7edb6752016-03-21 17:37:52 +01003650 return 1, hype_dict
3651 except nvExceptions.NotFound as e:
tierno1ec592d2020-06-16 15:29:47 +00003652 error_value = -vimconn.HTTP_Not_Found
sousaedu80135b92021-02-17 15:05:18 +01003653 error_text = str(e) if len(e.args) == 0 else str(e.args[0])
tierno7edb6752016-03-21 17:37:52 +01003654 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
tierno1ec592d2020-06-16 15:29:47 +00003655 error_value = -vimconn.HTTP_Bad_Request
sousaedu80135b92021-02-17 15:05:18 +01003656 error_text = (
3657 type(e).__name__
3658 + ": "
3659 + (str(e) if len(e.args) == 0 else str(e.args[0]))
3660 )
3661
tierno1ec592d2020-06-16 15:29:47 +00003662 # TODO insert exception vimconn.HTTP_Unauthorized
3663 # if reaching here is because an exception
tierno9c5c8322018-03-23 15:44:03 +01003664 self.logger.debug("get_hosts " + error_text)
sousaedu80135b92021-02-17 15:05:18 +01003665
Igor Duarte Cardoso3cf9bcd2017-08-14 16:39:34 +00003666 return error_value, error_text
tierno7edb6752016-03-21 17:37:52 +01003667
Alexis Romerob70f4ed2022-03-11 18:00:49 +01003668 def new_affinity_group(self, affinity_group_data):
3669 """Adds a server group to VIM
3670 affinity_group_data contains a dictionary with information, keys:
3671 name: name in VIM for the server group
3672 type: affinity or anti-affinity
3673 scope: Only nfvi-node allowed
3674 Returns the server group identifier"""
3675 self.logger.debug("Adding Server Group '%s'", str(affinity_group_data))
3676
3677 try:
3678 name = affinity_group_data["name"]
3679 policy = affinity_group_data["type"]
3680
3681 self._reload_connection()
3682 new_server_group = self.nova.server_groups.create(name, policy)
3683
3684 return new_server_group.id
3685 except (
3686 ksExceptions.ClientException,
3687 nvExceptions.ClientException,
3688 ConnectionError,
3689 KeyError,
3690 ) as e:
3691 self._format_exception(e)
3692
3693 def get_affinity_group(self, affinity_group_id):
3694 """Obtain server group details from the VIM. Returns the server group detais as a dict"""
3695 self.logger.debug("Getting flavor '%s'", affinity_group_id)
3696 try:
3697 self._reload_connection()
3698 server_group = self.nova.server_groups.find(id=affinity_group_id)
3699
3700 return server_group.to_dict()
3701 except (
3702 nvExceptions.NotFound,
3703 nvExceptions.ClientException,
3704 ksExceptions.ClientException,
3705 ConnectionError,
3706 ) as e:
3707 self._format_exception(e)
3708
3709 def delete_affinity_group(self, affinity_group_id):
3710 """Deletes a server group from the VIM. Returns the old affinity_group_id"""
3711 self.logger.debug("Getting server group '%s'", affinity_group_id)
3712 try:
3713 self._reload_connection()
3714 self.nova.server_groups.delete(affinity_group_id)
3715
3716 return affinity_group_id
3717 except (
3718 nvExceptions.NotFound,
3719 ksExceptions.ClientException,
3720 nvExceptions.ClientException,
3721 ConnectionError,
3722 ) as e:
3723 self._format_exception(e)
elumalai8658c2c2022-04-28 19:09:31 +05303724
Patricia Reinoso17852162023-06-15 07:33:04 +00003725 def get_vdu_state(self, vm_id, host_is_required=False) -> list:
3726 """Getting the state of a VDU.
3727 Args:
3728 vm_id (str): ID of an instance
3729 host_is_required (Boolean): If the VIM account is non-admin, host info does not appear in server_dict
3730 and if this is set to True, it raises KeyError.
3731 Returns:
3732 vdu_data (list): VDU details including state, flavor, host_info, AZ
elumalai8658c2c2022-04-28 19:09:31 +05303733 """
3734 self.logger.debug("Getting the status of VM")
3735 self.logger.debug("VIM VM ID %s", vm_id)
Patricia Reinoso17852162023-06-15 07:33:04 +00003736 try:
3737 self._reload_connection()
3738 server_dict = self._find_nova_server(vm_id)
3739 srv_attr = "OS-EXT-SRV-ATTR:host"
3740 host_info = (
3741 server_dict[srv_attr] if host_is_required else server_dict.get(srv_attr)
3742 )
3743 vdu_data = [
3744 server_dict["status"],
3745 server_dict["flavor"]["id"],
3746 host_info,
3747 server_dict["OS-EXT-AZ:availability_zone"],
3748 ]
3749 self.logger.debug("vdu_data %s", vdu_data)
3750 return vdu_data
3751
3752 except Exception as e:
3753 self._format_exception(e)
elumalai8658c2c2022-04-28 19:09:31 +05303754
3755 def check_compute_availability(self, host, server_flavor_details):
3756 self._reload_connection()
3757 hypervisor_search = self.nova.hypervisors.search(
3758 hypervisor_match=host, servers=True
3759 )
3760 for hypervisor in hypervisor_search:
3761 hypervisor_id = hypervisor.to_dict()["id"]
3762 hypervisor_details = self.nova.hypervisors.get(hypervisor=hypervisor_id)
3763 hypervisor_dict = hypervisor_details.to_dict()
3764 hypervisor_temp = json.dumps(hypervisor_dict)
3765 hypervisor_json = json.loads(hypervisor_temp)
3766 resources_available = [
3767 hypervisor_json["free_ram_mb"],
3768 hypervisor_json["disk_available_least"],
3769 hypervisor_json["vcpus"] - hypervisor_json["vcpus_used"],
3770 ]
3771 compute_available = all(
3772 x > y for x, y in zip(resources_available, server_flavor_details)
3773 )
3774 if compute_available:
3775 return host
3776
3777 def check_availability_zone(
3778 self, old_az, server_flavor_details, old_host, host=None
3779 ):
3780 self._reload_connection()
3781 az_check = {"zone_check": False, "compute_availability": None}
3782 aggregates_list = self.nova.aggregates.list()
3783 for aggregate in aggregates_list:
3784 aggregate_details = aggregate.to_dict()
3785 aggregate_temp = json.dumps(aggregate_details)
3786 aggregate_json = json.loads(aggregate_temp)
3787 if aggregate_json["availability_zone"] == old_az:
3788 hosts_list = aggregate_json["hosts"]
3789 if host is not None:
3790 if host in hosts_list:
3791 az_check["zone_check"] = True
3792 available_compute_id = self.check_compute_availability(
3793 host, server_flavor_details
3794 )
3795 if available_compute_id is not None:
3796 az_check["compute_availability"] = available_compute_id
3797 else:
3798 for check_host in hosts_list:
3799 if check_host != old_host:
3800 available_compute_id = self.check_compute_availability(
3801 check_host, server_flavor_details
3802 )
3803 if available_compute_id is not None:
3804 az_check["zone_check"] = True
3805 az_check["compute_availability"] = available_compute_id
3806 break
3807 else:
3808 az_check["zone_check"] = True
3809 return az_check
3810
3811 def migrate_instance(self, vm_id, compute_host=None):
3812 """
3813 Migrate a vdu
3814 param:
3815 vm_id: ID of an instance
3816 compute_host: Host to migrate the vdu to
3817 """
3818 self._reload_connection()
3819 vm_state = False
Patricia Reinoso17852162023-06-15 07:33:04 +00003820 instance_state = self.get_vdu_state(vm_id, host_is_required=True)
elumalai8658c2c2022-04-28 19:09:31 +05303821 server_flavor_id = instance_state[1]
3822 server_hypervisor_name = instance_state[2]
3823 server_availability_zone = instance_state[3]
3824 try:
3825 server_flavor = self.nova.flavors.find(id=server_flavor_id).to_dict()
3826 server_flavor_details = [
3827 server_flavor["ram"],
3828 server_flavor["disk"],
3829 server_flavor["vcpus"],
3830 ]
3831 if compute_host == server_hypervisor_name:
3832 raise vimconn.VimConnException(
3833 "Unable to migrate instance '{}' to the same host '{}'".format(
3834 vm_id, compute_host
3835 ),
3836 http_code=vimconn.HTTP_Bad_Request,
3837 )
3838 az_status = self.check_availability_zone(
3839 server_availability_zone,
3840 server_flavor_details,
3841 server_hypervisor_name,
3842 compute_host,
3843 )
3844 availability_zone_check = az_status["zone_check"]
3845 available_compute_id = az_status.get("compute_availability")
3846
3847 if availability_zone_check is False:
3848 raise vimconn.VimConnException(
3849 "Unable to migrate instance '{}' to a different availability zone".format(
3850 vm_id
3851 ),
3852 http_code=vimconn.HTTP_Bad_Request,
3853 )
3854 if available_compute_id is not None:
Patricia Reinoso17852162023-06-15 07:33:04 +00003855 # disk_over_commit parameter for live_migrate method is not valid for Nova API version >= 2.25
elumalai8658c2c2022-04-28 19:09:31 +05303856 self.nova.servers.live_migrate(
3857 server=vm_id,
3858 host=available_compute_id,
3859 block_migration=True,
elumalai8658c2c2022-04-28 19:09:31 +05303860 )
3861 state = "MIGRATING"
3862 changed_compute_host = ""
3863 if state == "MIGRATING":
3864 vm_state = self.__wait_for_vm(vm_id, "ACTIVE")
Patricia Reinoso17852162023-06-15 07:33:04 +00003865 changed_compute_host = self.get_vdu_state(
3866 vm_id, host_is_required=True
3867 )[2]
elumalai8658c2c2022-04-28 19:09:31 +05303868 if vm_state and changed_compute_host == available_compute_id:
3869 self.logger.debug(
3870 "Instance '{}' migrated to the new compute host '{}'".format(
3871 vm_id, changed_compute_host
3872 )
3873 )
3874 return state, available_compute_id
3875 else:
3876 raise vimconn.VimConnException(
3877 "Migration Failed. Instance '{}' not moved to the new host {}".format(
3878 vm_id, available_compute_id
3879 ),
3880 http_code=vimconn.HTTP_Bad_Request,
3881 )
3882 else:
3883 raise vimconn.VimConnException(
3884 "Compute '{}' not available or does not have enough resources to migrate the instance".format(
3885 available_compute_id
3886 ),
3887 http_code=vimconn.HTTP_Bad_Request,
3888 )
3889 except (
3890 nvExceptions.BadRequest,
3891 nvExceptions.ClientException,
3892 nvExceptions.NotFound,
3893 ) as e:
3894 self._format_exception(e)
sritharan29a4c1a2022-05-05 12:15:04 +00003895
3896 def resize_instance(self, vm_id, new_flavor_id):
3897 """
3898 For resizing the vm based on the given
3899 flavor details
3900 param:
3901 vm_id : ID of an instance
3902 new_flavor_id : Flavor id to be resized
3903 Return the status of a resized instance
3904 """
3905 self._reload_connection()
3906 self.logger.debug("resize the flavor of an instance")
3907 instance_status, old_flavor_id, compute_host, az = self.get_vdu_state(vm_id)
3908 old_flavor_disk = self.nova.flavors.find(id=old_flavor_id).to_dict()["disk"]
3909 new_flavor_disk = self.nova.flavors.find(id=new_flavor_id).to_dict()["disk"]
3910 try:
3911 if instance_status == "ACTIVE" or instance_status == "SHUTOFF":
3912 if old_flavor_disk > new_flavor_disk:
3913 raise nvExceptions.BadRequest(
3914 400,
3915 message="Server disk resize failed. Resize to lower disk flavor is not allowed",
3916 )
3917 else:
3918 self.nova.servers.resize(server=vm_id, flavor=new_flavor_id)
3919 vm_state = self.__wait_for_vm(vm_id, "VERIFY_RESIZE")
3920 if vm_state:
elumalai15478f62023-11-14 22:49:08 +05303921 instance_resized_status = self.confirm_resize(
3922 vm_id, instance_status
3923 )
sritharan29a4c1a2022-05-05 12:15:04 +00003924 return instance_resized_status
3925 else:
3926 raise nvExceptions.BadRequest(
3927 409,
3928 message="Cannot 'resize' vm_state is in ERROR",
3929 )
3930
3931 else:
3932 self.logger.debug("ERROR : Instance is not in ACTIVE or SHUTOFF state")
3933 raise nvExceptions.BadRequest(
3934 409,
3935 message="Cannot 'resize' instance while it is in vm_state resized",
3936 )
3937 except (
3938 nvExceptions.BadRequest,
3939 nvExceptions.ClientException,
3940 nvExceptions.NotFound,
3941 ) as e:
3942 self._format_exception(e)
3943
elumalai15478f62023-11-14 22:49:08 +05303944 def confirm_resize(self, vm_id, instance_state):
sritharan29a4c1a2022-05-05 12:15:04 +00003945 """
3946 Confirm the resize of an instance
3947 param:
3948 vm_id: ID of an instance
3949 """
3950 self._reload_connection()
3951 self.nova.servers.confirm_resize(server=vm_id)
3952 if self.get_vdu_state(vm_id)[0] == "VERIFY_RESIZE":
elumalai15478f62023-11-14 22:49:08 +05303953 self.__wait_for_vm(vm_id, instance_state)
sritharan29a4c1a2022-05-05 12:15:04 +00003954 instance_status = self.get_vdu_state(vm_id)[0]
3955 return instance_status
Gulsum Aticid586d892023-02-13 18:40:03 +03003956
3957 def get_monitoring_data(self):
3958 try:
3959 self.logger.debug("Getting servers and ports data from Openstack VIMs.")
3960 self._reload_connection()
3961 all_servers = self.nova.servers.list(detailed=True)
vegallc53829d2023-06-01 00:47:44 -05003962 try:
3963 for server in all_servers:
Luis Vega6bb1afe2023-07-26 20:49:12 +00003964 if server.flavor.get("original_name"):
3965 server.flavor["id"] = self.nova.flavors.find(
3966 name=server.flavor["original_name"]
3967 ).id
vegallc53829d2023-06-01 00:47:44 -05003968 except nClient.exceptions.NotFound as e:
3969 self.logger.warning(str(e.message))
Gulsum Aticid586d892023-02-13 18:40:03 +03003970 all_ports = self.neutron.list_ports()
3971 return all_servers, all_ports
3972 except (
3973 vimconn.VimConnException,
3974 vimconn.VimConnNotFoundException,
3975 vimconn.VimConnConnectionException,
3976 ) as e:
3977 raise vimconn.VimConnException(
3978 f"Exception in monitoring while getting VMs and ports status: {str(e)}"
3979 )