blob: 22bc22626cfe697d23fb801807af4bb0054c7e97 [file] [log] [blame]
tierno59d22d22018-09-25 18:10:19 +02001# -*- coding: utf-8 -*-
2
tierno2e215512018-11-28 09:37:52 +00003##
4# Copyright 2018 Telefonica S.A.
5#
6# Licensed under the Apache License, Version 2.0 (the "License"); you may
7# not use this file except in compliance with the License. You may obtain
8# a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15# License for the specific language governing permissions and limitations
16# under the License.
17##
18
tierno59d22d22018-09-25 18:10:19 +020019import asyncio
David Garcia1f40aa92021-11-11 16:35:26 +010020from typing import Any, Dict, List
tierno59d22d22018-09-25 18:10:19 +020021import yaml
22import logging
23import logging.handlers
tierno59d22d22018-09-25 18:10:19 +020024import traceback
David Garciad4816682019-12-09 14:57:43 +010025import json
garciadeblas5697b8b2021-03-24 09:17:02 +010026from jinja2 import (
27 Environment,
28 TemplateError,
29 TemplateNotFound,
30 StrictUndefined,
31 UndefinedError,
32)
tierno59d22d22018-09-25 18:10:19 +020033
tierno77677d92019-08-22 13:46:35 +000034from osm_lcm import ROclient
David Garciab4ebcd02021-10-28 02:00:43 +020035from osm_lcm.data_utils.nsr import (
36 get_deployed_kdu,
37 get_deployed_vca,
38 get_deployed_vca_list,
39 get_nsd,
40)
41from osm_lcm.data_utils.vca import (
42 DeployedComponent,
43 DeployedK8sResource,
44 DeployedVCA,
45 EELevel,
46 Relation,
47 EERelation,
48 safe_get_ee_relation,
49)
tierno69f0d382020-05-07 13:08:09 +000050from osm_lcm.ng_ro import NgRoClient, NgRoException
garciadeblas5697b8b2021-03-24 09:17:02 +010051from osm_lcm.lcm_utils import (
52 LcmException,
53 LcmExceptionNoMgmtIP,
54 LcmBase,
55 deep_get,
56 get_iterable,
57 populate_dict,
58)
David Garciab4ebcd02021-10-28 02:00:43 +020059from osm_lcm.data_utils.nsd import (
60 get_ns_configuration_relation_list,
61 get_vnf_profile,
62 get_vnf_profiles,
63)
garciadeblas5697b8b2021-03-24 09:17:02 +010064from osm_lcm.data_utils.vnfd import (
David Garciab4ebcd02021-10-28 02:00:43 +020065 get_relation_list,
garciadeblas5697b8b2021-03-24 09:17:02 +010066 get_vdu_list,
67 get_vdu_profile,
68 get_ee_sorted_initial_config_primitive_list,
69 get_ee_sorted_terminate_config_primitive_list,
70 get_kdu_list,
71 get_virtual_link_profiles,
72 get_vdu,
73 get_configuration,
74 get_vdu_index,
75 get_scaling_aspect,
76 get_number_of_instances,
77 get_juju_ee_ref,
David Garciab4ebcd02021-10-28 02:00:43 +020078 get_kdu_resource_profile,
garciadeblas5697b8b2021-03-24 09:17:02 +010079)
bravof922c4172020-11-24 21:21:43 -030080from osm_lcm.data_utils.list_utils import find_in_list
aktas5f75f102021-03-15 11:26:10 +030081from osm_lcm.data_utils.vnfr import get_osm_params, get_vdur_index, get_kdur
bravof922c4172020-11-24 21:21:43 -030082from osm_lcm.data_utils.dict_utils import parse_yaml_strings
83from osm_lcm.data_utils.database.vim_account import VimAccountDB
David Garciab4ebcd02021-10-28 02:00:43 +020084from n2vc.definitions import RelationEndpoint
calvinosanch9f9c6f22019-11-04 13:37:39 +010085from n2vc.k8s_helm_conn import K8sHelmConnector
lloretgalleg18ebc3a2020-10-22 09:54:51 +000086from n2vc.k8s_helm3_conn import K8sHelm3Connector
Adam Israelbaacc302019-12-01 12:41:39 -050087from n2vc.k8s_juju_conn import K8sJujuConnector
tierno59d22d22018-09-25 18:10:19 +020088
tierno27246d82018-09-27 15:59:09 +020089from osm_common.dbbase import DbException
tierno59d22d22018-09-25 18:10:19 +020090from osm_common.fsbase import FsException
quilesj7e13aeb2019-10-08 13:34:55 +020091
bravof922c4172020-11-24 21:21:43 -030092from osm_lcm.data_utils.database.database import Database
93from osm_lcm.data_utils.filesystem.filesystem import Filesystem
94
quilesj7e13aeb2019-10-08 13:34:55 +020095from n2vc.n2vc_juju_conn import N2VCJujuConnector
tiernof59ad6c2020-04-08 12:50:52 +000096from n2vc.exceptions import N2VCException, N2VCNotFound, K8sException
tierno59d22d22018-09-25 18:10:19 +020097
tierno588547c2020-07-01 15:30:20 +000098from osm_lcm.lcm_helm_conn import LCMHelmConn
99
tierno27246d82018-09-27 15:59:09 +0200100from copy import copy, deepcopy
tierno59d22d22018-09-25 18:10:19 +0200101from time import time
tierno27246d82018-09-27 15:59:09 +0200102from uuid import uuid4
lloretgalleg7c121132020-07-08 07:53:22 +0000103
tiernob996d942020-07-03 14:52:28 +0000104from random import randint
tierno59d22d22018-09-25 18:10:19 +0200105
tierno69f0d382020-05-07 13:08:09 +0000106__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
tierno59d22d22018-09-25 18:10:19 +0200107
108
109class NsLcm(LcmBase):
garciadeblas5697b8b2021-03-24 09:17:02 +0100110 timeout_vca_on_error = (
111 5 * 60
112 ) # Time for charm from first time at blocked,error status to mark as failed
113 timeout_ns_deploy = 2 * 3600 # default global timeout for deployment a ns
114 timeout_ns_terminate = 1800 # default global timeout for un deployment a ns
garciadeblasf9b04952019-04-09 18:53:58 +0200115 timeout_charm_delete = 10 * 60
David Garciaf6919842020-05-21 16:41:07 +0200116 timeout_primitive = 30 * 60 # timeout for primitive execution
garciadeblas5697b8b2021-03-24 09:17:02 +0100117 timeout_progress_primitive = (
118 10 * 60
119 ) # timeout for some progress in a primitive execution
tierno59d22d22018-09-25 18:10:19 +0200120
kuuseac3a8882019-10-03 10:48:06 +0200121 SUBOPERATION_STATUS_NOT_FOUND = -1
122 SUBOPERATION_STATUS_NEW = -2
123 SUBOPERATION_STATUS_SKIP = -3
tiernoa2143262020-03-27 16:20:40 +0000124 task_name_deploy_vca = "Deploying VCA"
kuuseac3a8882019-10-03 10:48:06 +0200125
bravof922c4172020-11-24 21:21:43 -0300126 def __init__(self, msg, lcm_tasks, config, loop, prometheus=None):
tierno59d22d22018-09-25 18:10:19 +0200127 """
128 Init, Connect to database, filesystem storage, and messaging
129 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
130 :return: None
131 """
garciadeblas5697b8b2021-03-24 09:17:02 +0100132 super().__init__(msg=msg, logger=logging.getLogger("lcm.ns"))
quilesj7e13aeb2019-10-08 13:34:55 +0200133
bravof922c4172020-11-24 21:21:43 -0300134 self.db = Database().instance.db
135 self.fs = Filesystem().instance.fs
tierno59d22d22018-09-25 18:10:19 +0200136 self.loop = loop
137 self.lcm_tasks = lcm_tasks
tierno744303e2020-01-13 16:46:31 +0000138 self.timeout = config["timeout"]
139 self.ro_config = config["ro_config"]
tierno69f0d382020-05-07 13:08:09 +0000140 self.ng_ro = config["ro_config"].get("ng")
tierno744303e2020-01-13 16:46:31 +0000141 self.vca_config = config["VCA"].copy()
tierno59d22d22018-09-25 18:10:19 +0200142
quilesj7e13aeb2019-10-08 13:34:55 +0200143 # create N2VC connector
David Garciaaae391f2020-11-09 11:12:54 +0100144 self.n2vc = N2VCJujuConnector(
tierno59d22d22018-09-25 18:10:19 +0200145 log=self.logger,
quilesj7e13aeb2019-10-08 13:34:55 +0200146 loop=self.loop,
bravof922c4172020-11-24 21:21:43 -0300147 on_update_db=self._on_update_n2vc_db,
148 fs=self.fs,
garciadeblas5697b8b2021-03-24 09:17:02 +0100149 db=self.db,
tierno59d22d22018-09-25 18:10:19 +0200150 )
quilesj7e13aeb2019-10-08 13:34:55 +0200151
tierno588547c2020-07-01 15:30:20 +0000152 self.conn_helm_ee = LCMHelmConn(
tierno588547c2020-07-01 15:30:20 +0000153 log=self.logger,
154 loop=self.loop,
tierno588547c2020-07-01 15:30:20 +0000155 vca_config=self.vca_config,
garciadeblas5697b8b2021-03-24 09:17:02 +0100156 on_update_db=self._on_update_n2vc_db,
tierno588547c2020-07-01 15:30:20 +0000157 )
158
lloretgalleg18ebc3a2020-10-22 09:54:51 +0000159 self.k8sclusterhelm2 = K8sHelmConnector(
calvinosanch9f9c6f22019-11-04 13:37:39 +0100160 kubectl_command=self.vca_config.get("kubectlpath"),
161 helm_command=self.vca_config.get("helmpath"),
calvinosanch9f9c6f22019-11-04 13:37:39 +0100162 log=self.logger,
calvinosanch9f9c6f22019-11-04 13:37:39 +0100163 on_update_db=None,
bravof922c4172020-11-24 21:21:43 -0300164 fs=self.fs,
garciadeblas5697b8b2021-03-24 09:17:02 +0100165 db=self.db,
calvinosanch9f9c6f22019-11-04 13:37:39 +0100166 )
167
lloretgalleg18ebc3a2020-10-22 09:54:51 +0000168 self.k8sclusterhelm3 = K8sHelm3Connector(
169 kubectl_command=self.vca_config.get("kubectlpath"),
170 helm_command=self.vca_config.get("helm3path"),
171 fs=self.fs,
172 log=self.logger,
173 db=self.db,
174 on_update_db=None,
175 )
176
Adam Israelbaacc302019-12-01 12:41:39 -0500177 self.k8sclusterjuju = K8sJujuConnector(
178 kubectl_command=self.vca_config.get("kubectlpath"),
179 juju_command=self.vca_config.get("jujupath"),
Adam Israelbaacc302019-12-01 12:41:39 -0500180 log=self.logger,
David Garciaba89cbb2020-10-16 13:05:34 +0200181 loop=self.loop,
ksaikiranr656b6dd2021-02-19 10:25:18 +0530182 on_update_db=self._on_update_k8s_db,
bravof922c4172020-11-24 21:21:43 -0300183 fs=self.fs,
garciadeblas5697b8b2021-03-24 09:17:02 +0100184 db=self.db,
Adam Israelbaacc302019-12-01 12:41:39 -0500185 )
186
tiernoa2143262020-03-27 16:20:40 +0000187 self.k8scluster_map = {
lloretgalleg18ebc3a2020-10-22 09:54:51 +0000188 "helm-chart": self.k8sclusterhelm2,
189 "helm-chart-v3": self.k8sclusterhelm3,
190 "chart": self.k8sclusterhelm3,
tiernoa2143262020-03-27 16:20:40 +0000191 "juju-bundle": self.k8sclusterjuju,
192 "juju": self.k8sclusterjuju,
193 }
tierno588547c2020-07-01 15:30:20 +0000194
195 self.vca_map = {
196 "lxc_proxy_charm": self.n2vc,
197 "native_charm": self.n2vc,
198 "k8s_proxy_charm": self.n2vc,
lloretgalleg18ebc3a2020-10-22 09:54:51 +0000199 "helm": self.conn_helm_ee,
garciadeblas5697b8b2021-03-24 09:17:02 +0100200 "helm-v3": self.conn_helm_ee,
tierno588547c2020-07-01 15:30:20 +0000201 }
202
tiernob996d942020-07-03 14:52:28 +0000203 self.prometheus = prometheus
204
quilesj7e13aeb2019-10-08 13:34:55 +0200205 # create RO client
bravof922c4172020-11-24 21:21:43 -0300206 self.RO = NgRoClient(self.loop, **self.ro_config)
tierno59d22d22018-09-25 18:10:19 +0200207
tierno2357f4e2020-10-19 16:38:59 +0000208 @staticmethod
209 def increment_ip_mac(ip_mac, vm_index=1):
210 if not isinstance(ip_mac, str):
211 return ip_mac
212 try:
213 # try with ipv4 look for last dot
214 i = ip_mac.rfind(".")
215 if i > 0:
216 i += 1
217 return "{}{}".format(ip_mac[:i], int(ip_mac[i:]) + vm_index)
218 # try with ipv6 or mac look for last colon. Operate in hex
219 i = ip_mac.rfind(":")
220 if i > 0:
221 i += 1
222 # format in hex, len can be 2 for mac or 4 for ipv6
garciadeblas5697b8b2021-03-24 09:17:02 +0100223 return ("{}{:0" + str(len(ip_mac) - i) + "x}").format(
224 ip_mac[:i], int(ip_mac[i:], 16) + vm_index
225 )
tierno2357f4e2020-10-19 16:38:59 +0000226 except Exception:
227 pass
228 return None
229
quilesj3655ae02019-12-12 16:08:35 +0000230 def _on_update_ro_db(self, nsrs_id, ro_descriptor):
quilesj7e13aeb2019-10-08 13:34:55 +0200231
quilesj3655ae02019-12-12 16:08:35 +0000232 # self.logger.debug('_on_update_ro_db(nsrs_id={}'.format(nsrs_id))
233
234 try:
235 # TODO filter RO descriptor fields...
236
237 # write to database
238 db_dict = dict()
239 # db_dict['deploymentStatus'] = yaml.dump(ro_descriptor, default_flow_style=False, indent=2)
garciadeblas5697b8b2021-03-24 09:17:02 +0100240 db_dict["deploymentStatus"] = ro_descriptor
quilesj3655ae02019-12-12 16:08:35 +0000241 self.update_db_2("nsrs", nsrs_id, db_dict)
242
243 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100244 self.logger.warn(
245 "Cannot write database RO deployment for ns={} -> {}".format(nsrs_id, e)
246 )
quilesj3655ae02019-12-12 16:08:35 +0000247
David Garciac1fe90a2021-03-31 19:12:02 +0200248 async def _on_update_n2vc_db(self, table, filter, path, updated_data, vca_id=None):
quilesj3655ae02019-12-12 16:08:35 +0000249
quilesj69a722c2020-01-09 08:30:17 +0000250 # remove last dot from path (if exists)
garciadeblas5697b8b2021-03-24 09:17:02 +0100251 if path.endswith("."):
quilesj69a722c2020-01-09 08:30:17 +0000252 path = path[:-1]
253
quilesj3655ae02019-12-12 16:08:35 +0000254 # self.logger.debug('_on_update_n2vc_db(table={}, filter={}, path={}, updated_data={}'
255 # .format(table, filter, path, updated_data))
quilesj3655ae02019-12-12 16:08:35 +0000256 try:
257
garciadeblas5697b8b2021-03-24 09:17:02 +0100258 nsr_id = filter.get("_id")
quilesj3655ae02019-12-12 16:08:35 +0000259
260 # read ns record from database
garciadeblas5697b8b2021-03-24 09:17:02 +0100261 nsr = self.db.get_one(table="nsrs", q_filter=filter)
262 current_ns_status = nsr.get("nsState")
quilesj3655ae02019-12-12 16:08:35 +0000263
264 # get vca status for NS
garciadeblas5697b8b2021-03-24 09:17:02 +0100265 status_dict = await self.n2vc.get_status(
266 namespace="." + nsr_id, yaml_format=False, vca_id=vca_id
267 )
quilesj3655ae02019-12-12 16:08:35 +0000268
269 # vcaStatus
270 db_dict = dict()
garciadeblas5697b8b2021-03-24 09:17:02 +0100271 db_dict["vcaStatus"] = status_dict
272 await self.n2vc.update_vca_status(db_dict["vcaStatus"], vca_id=vca_id)
quilesj3655ae02019-12-12 16:08:35 +0000273
274 # update configurationStatus for this VCA
275 try:
garciadeblas5697b8b2021-03-24 09:17:02 +0100276 vca_index = int(path[path.rfind(".") + 1 :])
quilesj3655ae02019-12-12 16:08:35 +0000277
garciadeblas5697b8b2021-03-24 09:17:02 +0100278 vca_list = deep_get(
279 target_dict=nsr, key_list=("_admin", "deployed", "VCA")
280 )
281 vca_status = vca_list[vca_index].get("status")
quilesj3655ae02019-12-12 16:08:35 +0000282
garciadeblas5697b8b2021-03-24 09:17:02 +0100283 configuration_status_list = nsr.get("configurationStatus")
284 config_status = configuration_status_list[vca_index].get("status")
quilesj3655ae02019-12-12 16:08:35 +0000285
garciadeblas5697b8b2021-03-24 09:17:02 +0100286 if config_status == "BROKEN" and vca_status != "failed":
287 db_dict["configurationStatus"][vca_index] = "READY"
288 elif config_status != "BROKEN" and vca_status == "failed":
289 db_dict["configurationStatus"][vca_index] = "BROKEN"
quilesj3655ae02019-12-12 16:08:35 +0000290 except Exception as e:
291 # not update configurationStatus
garciadeblas5697b8b2021-03-24 09:17:02 +0100292 self.logger.debug("Error updating vca_index (ignore): {}".format(e))
quilesj3655ae02019-12-12 16:08:35 +0000293
294 # if nsState = 'READY' check if juju is reporting some error => nsState = 'DEGRADED'
295 # if nsState = 'DEGRADED' check if all is OK
296 is_degraded = False
garciadeblas5697b8b2021-03-24 09:17:02 +0100297 if current_ns_status in ("READY", "DEGRADED"):
298 error_description = ""
quilesj3655ae02019-12-12 16:08:35 +0000299 # check machines
garciadeblas5697b8b2021-03-24 09:17:02 +0100300 if status_dict.get("machines"):
301 for machine_id in status_dict.get("machines"):
302 machine = status_dict.get("machines").get(machine_id)
quilesj3655ae02019-12-12 16:08:35 +0000303 # check machine agent-status
garciadeblas5697b8b2021-03-24 09:17:02 +0100304 if machine.get("agent-status"):
305 s = machine.get("agent-status").get("status")
306 if s != "started":
quilesj3655ae02019-12-12 16:08:35 +0000307 is_degraded = True
garciadeblas5697b8b2021-03-24 09:17:02 +0100308 error_description += (
309 "machine {} agent-status={} ; ".format(
310 machine_id, s
311 )
312 )
quilesj3655ae02019-12-12 16:08:35 +0000313 # check machine instance status
garciadeblas5697b8b2021-03-24 09:17:02 +0100314 if machine.get("instance-status"):
315 s = machine.get("instance-status").get("status")
316 if s != "running":
quilesj3655ae02019-12-12 16:08:35 +0000317 is_degraded = True
garciadeblas5697b8b2021-03-24 09:17:02 +0100318 error_description += (
319 "machine {} instance-status={} ; ".format(
320 machine_id, s
321 )
322 )
quilesj3655ae02019-12-12 16:08:35 +0000323 # check applications
garciadeblas5697b8b2021-03-24 09:17:02 +0100324 if status_dict.get("applications"):
325 for app_id in status_dict.get("applications"):
326 app = status_dict.get("applications").get(app_id)
quilesj3655ae02019-12-12 16:08:35 +0000327 # check application status
garciadeblas5697b8b2021-03-24 09:17:02 +0100328 if app.get("status"):
329 s = app.get("status").get("status")
330 if s != "active":
quilesj3655ae02019-12-12 16:08:35 +0000331 is_degraded = True
garciadeblas5697b8b2021-03-24 09:17:02 +0100332 error_description += (
333 "application {} status={} ; ".format(app_id, s)
334 )
quilesj3655ae02019-12-12 16:08:35 +0000335
336 if error_description:
garciadeblas5697b8b2021-03-24 09:17:02 +0100337 db_dict["errorDescription"] = error_description
338 if current_ns_status == "READY" and is_degraded:
339 db_dict["nsState"] = "DEGRADED"
340 if current_ns_status == "DEGRADED" and not is_degraded:
341 db_dict["nsState"] = "READY"
quilesj3655ae02019-12-12 16:08:35 +0000342
343 # write to database
344 self.update_db_2("nsrs", nsr_id, db_dict)
345
tierno51183952020-04-03 15:48:18 +0000346 except (asyncio.CancelledError, asyncio.TimeoutError):
347 raise
quilesj3655ae02019-12-12 16:08:35 +0000348 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100349 self.logger.warn("Error updating NS state for ns={}: {}".format(nsr_id, e))
quilesj7e13aeb2019-10-08 13:34:55 +0200350
garciadeblas5697b8b2021-03-24 09:17:02 +0100351 async def _on_update_k8s_db(
352 self, cluster_uuid, kdu_instance, filter=None, vca_id=None
353 ):
ksaikiranr656b6dd2021-02-19 10:25:18 +0530354 """
355 Updating vca status in NSR record
356 :param cluster_uuid: UUID of a k8s cluster
357 :param kdu_instance: The unique name of the KDU instance
358 :param filter: To get nsr_id
359 :return: none
360 """
361
362 # self.logger.debug("_on_update_k8s_db(cluster_uuid={}, kdu_instance={}, filter={}"
363 # .format(cluster_uuid, kdu_instance, filter))
364
365 try:
garciadeblas5697b8b2021-03-24 09:17:02 +0100366 nsr_id = filter.get("_id")
ksaikiranr656b6dd2021-02-19 10:25:18 +0530367
368 # get vca status for NS
David Garciac1fe90a2021-03-31 19:12:02 +0200369 vca_status = await self.k8sclusterjuju.status_kdu(
370 cluster_uuid,
371 kdu_instance,
372 complete_status=True,
373 yaml_format=False,
374 vca_id=vca_id,
375 )
ksaikiranr656b6dd2021-02-19 10:25:18 +0530376 # vcaStatus
377 db_dict = dict()
garciadeblas5697b8b2021-03-24 09:17:02 +0100378 db_dict["vcaStatus"] = {nsr_id: vca_status}
ksaikiranr656b6dd2021-02-19 10:25:18 +0530379
David Garciac1fe90a2021-03-31 19:12:02 +0200380 await self.k8sclusterjuju.update_vca_status(
garciadeblas5697b8b2021-03-24 09:17:02 +0100381 db_dict["vcaStatus"],
David Garciac1fe90a2021-03-31 19:12:02 +0200382 kdu_instance,
383 vca_id=vca_id,
384 )
ksaikiranr656b6dd2021-02-19 10:25:18 +0530385
386 # write to database
387 self.update_db_2("nsrs", nsr_id, db_dict)
388
389 except (asyncio.CancelledError, asyncio.TimeoutError):
390 raise
391 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100392 self.logger.warn("Error updating NS state for ns={}: {}".format(nsr_id, e))
ksaikiranr656b6dd2021-02-19 10:25:18 +0530393
tierno72ef84f2020-10-06 08:22:07 +0000394 @staticmethod
395 def _parse_cloud_init(cloud_init_text, additional_params, vnfd_id, vdu_id):
396 try:
397 env = Environment(undefined=StrictUndefined)
398 template = env.from_string(cloud_init_text)
399 return template.render(additional_params or {})
400 except UndefinedError as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100401 raise LcmException(
402 "Variable {} at vnfd[id={}]:vdu[id={}]:cloud-init/cloud-init-"
403 "file, must be provided in the instantiation parameters inside the "
404 "'additionalParamsForVnf/Vdu' block".format(e, vnfd_id, vdu_id)
405 )
tierno72ef84f2020-10-06 08:22:07 +0000406 except (TemplateError, TemplateNotFound) as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100407 raise LcmException(
408 "Error parsing Jinja2 to cloud-init content at vnfd[id={}]:vdu[id={}]: {}".format(
409 vnfd_id, vdu_id, e
410 )
411 )
tierno72ef84f2020-10-06 08:22:07 +0000412
bravof922c4172020-11-24 21:21:43 -0300413 def _get_vdu_cloud_init_content(self, vdu, vnfd):
414 cloud_init_content = cloud_init_file = None
tierno72ef84f2020-10-06 08:22:07 +0000415 try:
tierno72ef84f2020-10-06 08:22:07 +0000416 if vdu.get("cloud-init-file"):
417 base_folder = vnfd["_admin"]["storage"]
bravof14af4e72021-11-08 17:18:50 -0300418 if base_folder["pkg-dir"]:
419 cloud_init_file = "{}/{}/cloud_init/{}".format(
420 base_folder["folder"],
421 base_folder["pkg-dir"],
422 vdu["cloud-init-file"],
423 )
424 else:
425 cloud_init_file = "{}/Scripts/cloud_init/{}".format(
426 base_folder["folder"],
427 vdu["cloud-init-file"],
428 )
tierno72ef84f2020-10-06 08:22:07 +0000429 with self.fs.file_open(cloud_init_file, "r") as ci_file:
430 cloud_init_content = ci_file.read()
431 elif vdu.get("cloud-init"):
432 cloud_init_content = vdu["cloud-init"]
433
434 return cloud_init_content
435 except FsException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100436 raise LcmException(
437 "Error reading vnfd[id={}]:vdu[id={}]:cloud-init-file={}: {}".format(
438 vnfd["id"], vdu["id"], cloud_init_file, e
439 )
440 )
tierno72ef84f2020-10-06 08:22:07 +0000441
tierno72ef84f2020-10-06 08:22:07 +0000442 def _get_vdu_additional_params(self, db_vnfr, vdu_id):
garciadeblas5697b8b2021-03-24 09:17:02 +0100443 vdur = next(
444 vdur for vdur in db_vnfr.get("vdur") if vdu_id == vdur["vdu-id-ref"]
445 )
tierno72ef84f2020-10-06 08:22:07 +0000446 additional_params = vdur.get("additionalParams")
bravof922c4172020-11-24 21:21:43 -0300447 return parse_yaml_strings(additional_params)
tierno72ef84f2020-10-06 08:22:07 +0000448
gcalvino35be9152018-12-20 09:33:12 +0100449 def vnfd2RO(self, vnfd, new_id=None, additionalParams=None, nsrId=None):
tierno59d22d22018-09-25 18:10:19 +0200450 """
451 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
452 :param vnfd: input vnfd
453 :param new_id: overrides vnf id if provided
tierno8a518872018-12-21 13:42:14 +0000454 :param additionalParams: Instantiation params for VNFs provided
gcalvino35be9152018-12-20 09:33:12 +0100455 :param nsrId: Id of the NSR
tierno59d22d22018-09-25 18:10:19 +0200456 :return: copy of vnfd
457 """
tierno72ef84f2020-10-06 08:22:07 +0000458 vnfd_RO = deepcopy(vnfd)
459 # remove unused by RO configuration, monitoring, scaling and internal keys
460 vnfd_RO.pop("_id", None)
461 vnfd_RO.pop("_admin", None)
tierno72ef84f2020-10-06 08:22:07 +0000462 vnfd_RO.pop("monitoring-param", None)
463 vnfd_RO.pop("scaling-group-descriptor", None)
464 vnfd_RO.pop("kdu", None)
465 vnfd_RO.pop("k8s-cluster", None)
466 if new_id:
467 vnfd_RO["id"] = new_id
tierno8a518872018-12-21 13:42:14 +0000468
tierno72ef84f2020-10-06 08:22:07 +0000469 # parse cloud-init or cloud-init-file with the provided variables using Jinja2
470 for vdu in get_iterable(vnfd_RO, "vdu"):
471 vdu.pop("cloud-init-file", None)
472 vdu.pop("cloud-init", None)
473 return vnfd_RO
tierno59d22d22018-09-25 18:10:19 +0200474
tierno2357f4e2020-10-19 16:38:59 +0000475 @staticmethod
476 def ip_profile_2_RO(ip_profile):
477 RO_ip_profile = deepcopy(ip_profile)
478 if "dns-server" in RO_ip_profile:
479 if isinstance(RO_ip_profile["dns-server"], list):
480 RO_ip_profile["dns-address"] = []
481 for ds in RO_ip_profile.pop("dns-server"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100482 RO_ip_profile["dns-address"].append(ds["address"])
tierno2357f4e2020-10-19 16:38:59 +0000483 else:
484 RO_ip_profile["dns-address"] = RO_ip_profile.pop("dns-server")
485 if RO_ip_profile.get("ip-version") == "ipv4":
486 RO_ip_profile["ip-version"] = "IPv4"
487 if RO_ip_profile.get("ip-version") == "ipv6":
488 RO_ip_profile["ip-version"] = "IPv6"
489 if "dhcp-params" in RO_ip_profile:
490 RO_ip_profile["dhcp"] = RO_ip_profile.pop("dhcp-params")
491 return RO_ip_profile
492
bravof922c4172020-11-24 21:21:43 -0300493 def _get_ro_vim_id_for_vim_account(self, vim_account):
494 db_vim = self.db.get_one("vim_accounts", {"_id": vim_account})
495 if db_vim["_admin"]["operationalState"] != "ENABLED":
garciadeblas5697b8b2021-03-24 09:17:02 +0100496 raise LcmException(
497 "VIM={} is not available. operationalState={}".format(
498 vim_account, db_vim["_admin"]["operationalState"]
499 )
500 )
bravof922c4172020-11-24 21:21:43 -0300501 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
502 return RO_vim_id
tierno59d22d22018-09-25 18:10:19 +0200503
bravof922c4172020-11-24 21:21:43 -0300504 def get_ro_wim_id_for_wim_account(self, wim_account):
505 if isinstance(wim_account, str):
506 db_wim = self.db.get_one("wim_accounts", {"_id": wim_account})
507 if db_wim["_admin"]["operationalState"] != "ENABLED":
garciadeblas5697b8b2021-03-24 09:17:02 +0100508 raise LcmException(
509 "WIM={} is not available. operationalState={}".format(
510 wim_account, db_wim["_admin"]["operationalState"]
511 )
512 )
bravof922c4172020-11-24 21:21:43 -0300513 RO_wim_id = db_wim["_admin"]["deployed"]["RO-account"]
514 return RO_wim_id
515 else:
516 return wim_account
tierno59d22d22018-09-25 18:10:19 +0200517
tierno2357f4e2020-10-19 16:38:59 +0000518 def scale_vnfr(self, db_vnfr, vdu_create=None, vdu_delete=None, mark_delete=False):
tierno27246d82018-09-27 15:59:09 +0200519
tierno2357f4e2020-10-19 16:38:59 +0000520 db_vdu_push_list = []
521 db_update = {"_admin.modified": time()}
522 if vdu_create:
523 for vdu_id, vdu_count in vdu_create.items():
garciadeblas5697b8b2021-03-24 09:17:02 +0100524 vdur = next(
525 (
526 vdur
527 for vdur in reversed(db_vnfr["vdur"])
528 if vdur["vdu-id-ref"] == vdu_id
529 ),
530 None,
531 )
tierno2357f4e2020-10-19 16:38:59 +0000532 if not vdur:
garciadeblas5697b8b2021-03-24 09:17:02 +0100533 raise LcmException(
534 "Error scaling OUT VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
535 vdu_id
536 )
537 )
tierno2357f4e2020-10-19 16:38:59 +0000538
539 for count in range(vdu_count):
540 vdur_copy = deepcopy(vdur)
541 vdur_copy["status"] = "BUILD"
542 vdur_copy["status-detailed"] = None
543 vdur_copy["ip-address"]: None
tierno683eb392020-09-25 12:33:15 +0000544 vdur_copy["_id"] = str(uuid4())
tierno2357f4e2020-10-19 16:38:59 +0000545 vdur_copy["count-index"] += count + 1
garciadeblas5697b8b2021-03-24 09:17:02 +0100546 vdur_copy["id"] = "{}-{}".format(
547 vdur_copy["vdu-id-ref"], vdur_copy["count-index"]
548 )
tierno2357f4e2020-10-19 16:38:59 +0000549 vdur_copy.pop("vim_info", None)
550 for iface in vdur_copy["interfaces"]:
551 if iface.get("fixed-ip"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100552 iface["ip-address"] = self.increment_ip_mac(
553 iface["ip-address"], count + 1
554 )
tierno2357f4e2020-10-19 16:38:59 +0000555 else:
556 iface.pop("ip-address", None)
557 if iface.get("fixed-mac"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100558 iface["mac-address"] = self.increment_ip_mac(
559 iface["mac-address"], count + 1
560 )
tierno2357f4e2020-10-19 16:38:59 +0000561 else:
562 iface.pop("mac-address", None)
garciadeblas5697b8b2021-03-24 09:17:02 +0100563 iface.pop(
564 "mgmt_vnf", None
565 ) # only first vdu can be managment of vnf
tierno2357f4e2020-10-19 16:38:59 +0000566 db_vdu_push_list.append(vdur_copy)
567 # self.logger.debug("scale out, adding vdu={}".format(vdur_copy))
tierno27246d82018-09-27 15:59:09 +0200568 if vdu_delete:
tierno2357f4e2020-10-19 16:38:59 +0000569 for vdu_id, vdu_count in vdu_delete.items():
570 if mark_delete:
garciadeblas5697b8b2021-03-24 09:17:02 +0100571 indexes_to_delete = [
572 iv[0]
573 for iv in enumerate(db_vnfr["vdur"])
574 if iv[1]["vdu-id-ref"] == vdu_id
575 ]
576 db_update.update(
577 {
578 "vdur.{}.status".format(i): "DELETING"
579 for i in indexes_to_delete[-vdu_count:]
580 }
581 )
tierno2357f4e2020-10-19 16:38:59 +0000582 else:
583 # it must be deleted one by one because common.db does not allow otherwise
garciadeblas5697b8b2021-03-24 09:17:02 +0100584 vdus_to_delete = [
585 v
586 for v in reversed(db_vnfr["vdur"])
587 if v["vdu-id-ref"] == vdu_id
588 ]
tierno2357f4e2020-10-19 16:38:59 +0000589 for vdu in vdus_to_delete[:vdu_count]:
garciadeblas5697b8b2021-03-24 09:17:02 +0100590 self.db.set_one(
591 "vnfrs",
592 {"_id": db_vnfr["_id"]},
593 None,
594 pull={"vdur": {"_id": vdu["_id"]}},
595 )
tierno2357f4e2020-10-19 16:38:59 +0000596 db_push = {"vdur": db_vdu_push_list} if db_vdu_push_list else None
597 self.db.set_one("vnfrs", {"_id": db_vnfr["_id"]}, db_update, push_list=db_push)
598 # modify passed dictionary db_vnfr
599 db_vnfr_ = self.db.get_one("vnfrs", {"_id": db_vnfr["_id"]})
600 db_vnfr["vdur"] = db_vnfr_["vdur"]
tierno27246d82018-09-27 15:59:09 +0200601
tiernof578e552018-11-08 19:07:20 +0100602 def ns_update_nsr(self, ns_update_nsr, db_nsr, nsr_desc_RO):
603 """
604 Updates database nsr with the RO info for the created vld
605 :param ns_update_nsr: dictionary to be filled with the updated info
606 :param db_nsr: content of db_nsr. This is also modified
607 :param nsr_desc_RO: nsr descriptor from RO
608 :return: Nothing, LcmException is raised on errors
609 """
610
611 for vld_index, vld in enumerate(get_iterable(db_nsr, "vld")):
612 for net_RO in get_iterable(nsr_desc_RO, "nets"):
613 if vld["id"] != net_RO.get("ns_net_osm_id"):
614 continue
615 vld["vim-id"] = net_RO.get("vim_net_id")
616 vld["name"] = net_RO.get("vim_name")
617 vld["status"] = net_RO.get("status")
618 vld["status-detailed"] = net_RO.get("error_msg")
619 ns_update_nsr["vld.{}".format(vld_index)] = vld
620 break
621 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100622 raise LcmException(
623 "ns_update_nsr: Not found vld={} at RO info".format(vld["id"])
624 )
tiernof578e552018-11-08 19:07:20 +0100625
tiernoe876f672020-02-13 14:34:48 +0000626 def set_vnfr_at_error(self, db_vnfrs, error_text):
627 try:
628 for db_vnfr in db_vnfrs.values():
629 vnfr_update = {"status": "ERROR"}
630 for vdu_index, vdur in enumerate(get_iterable(db_vnfr, "vdur")):
631 if "status" not in vdur:
632 vdur["status"] = "ERROR"
633 vnfr_update["vdur.{}.status".format(vdu_index)] = "ERROR"
634 if error_text:
635 vdur["status-detailed"] = str(error_text)
garciadeblas5697b8b2021-03-24 09:17:02 +0100636 vnfr_update[
637 "vdur.{}.status-detailed".format(vdu_index)
638 ] = "ERROR"
tiernoe876f672020-02-13 14:34:48 +0000639 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
640 except DbException as e:
641 self.logger.error("Cannot update vnf. {}".format(e))
642
tierno59d22d22018-09-25 18:10:19 +0200643 def ns_update_vnfr(self, db_vnfrs, nsr_desc_RO):
644 """
645 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
tierno27246d82018-09-27 15:59:09 +0200646 :param db_vnfrs: dictionary with member-vnf-index: vnfr-content
647 :param nsr_desc_RO: nsr descriptor from RO
648 :return: Nothing, LcmException is raised on errors
tierno59d22d22018-09-25 18:10:19 +0200649 """
650 for vnf_index, db_vnfr in db_vnfrs.items():
651 for vnf_RO in nsr_desc_RO["vnfs"]:
tierno27246d82018-09-27 15:59:09 +0200652 if vnf_RO["member_vnf_index"] != vnf_index:
653 continue
654 vnfr_update = {}
tiernof578e552018-11-08 19:07:20 +0100655 if vnf_RO.get("ip_address"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100656 db_vnfr["ip-address"] = vnfr_update["ip-address"] = vnf_RO[
657 "ip_address"
658 ].split(";")[0]
tiernof578e552018-11-08 19:07:20 +0100659 elif not db_vnfr.get("ip-address"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100660 if db_vnfr.get("vdur"): # if not VDUs, there is not ip_address
661 raise LcmExceptionNoMgmtIP(
662 "ns member_vnf_index '{}' has no IP address".format(
663 vnf_index
664 )
665 )
tierno59d22d22018-09-25 18:10:19 +0200666
tierno27246d82018-09-27 15:59:09 +0200667 for vdu_index, vdur in enumerate(get_iterable(db_vnfr, "vdur")):
668 vdur_RO_count_index = 0
669 if vdur.get("pdu-type"):
670 continue
671 for vdur_RO in get_iterable(vnf_RO, "vms"):
672 if vdur["vdu-id-ref"] != vdur_RO["vdu_osm_id"]:
673 continue
674 if vdur["count-index"] != vdur_RO_count_index:
675 vdur_RO_count_index += 1
676 continue
677 vdur["vim-id"] = vdur_RO.get("vim_vm_id")
tierno1674de82019-04-09 13:03:14 +0000678 if vdur_RO.get("ip_address"):
679 vdur["ip-address"] = vdur_RO["ip_address"].split(";")[0]
tierno274ed572019-04-04 13:33:27 +0000680 else:
681 vdur["ip-address"] = None
tierno27246d82018-09-27 15:59:09 +0200682 vdur["vdu-id-ref"] = vdur_RO.get("vdu_osm_id")
683 vdur["name"] = vdur_RO.get("vim_name")
684 vdur["status"] = vdur_RO.get("status")
685 vdur["status-detailed"] = vdur_RO.get("error_msg")
686 for ifacer in get_iterable(vdur, "interfaces"):
687 for interface_RO in get_iterable(vdur_RO, "interfaces"):
688 if ifacer["name"] == interface_RO.get("internal_name"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100689 ifacer["ip-address"] = interface_RO.get(
690 "ip_address"
691 )
692 ifacer["mac-address"] = interface_RO.get(
693 "mac_address"
694 )
tierno27246d82018-09-27 15:59:09 +0200695 break
696 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100697 raise LcmException(
698 "ns_update_vnfr: Not found member_vnf_index={} vdur={} interface={} "
699 "from VIM info".format(
700 vnf_index, vdur["vdu-id-ref"], ifacer["name"]
701 )
702 )
tierno27246d82018-09-27 15:59:09 +0200703 vnfr_update["vdur.{}".format(vdu_index)] = vdur
704 break
705 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100706 raise LcmException(
707 "ns_update_vnfr: Not found member_vnf_index={} vdur={} count_index={} from "
708 "VIM info".format(
709 vnf_index, vdur["vdu-id-ref"], vdur["count-index"]
710 )
711 )
tiernof578e552018-11-08 19:07:20 +0100712
713 for vld_index, vld in enumerate(get_iterable(db_vnfr, "vld")):
714 for net_RO in get_iterable(nsr_desc_RO, "nets"):
715 if vld["id"] != net_RO.get("vnf_net_osm_id"):
716 continue
717 vld["vim-id"] = net_RO.get("vim_net_id")
718 vld["name"] = net_RO.get("vim_name")
719 vld["status"] = net_RO.get("status")
720 vld["status-detailed"] = net_RO.get("error_msg")
721 vnfr_update["vld.{}".format(vld_index)] = vld
722 break
723 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100724 raise LcmException(
725 "ns_update_vnfr: Not found member_vnf_index={} vld={} from VIM info".format(
726 vnf_index, vld["id"]
727 )
728 )
tiernof578e552018-11-08 19:07:20 +0100729
tierno27246d82018-09-27 15:59:09 +0200730 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
731 break
tierno59d22d22018-09-25 18:10:19 +0200732
733 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100734 raise LcmException(
735 "ns_update_vnfr: Not found member_vnf_index={} from VIM info".format(
736 vnf_index
737 )
738 )
tierno59d22d22018-09-25 18:10:19 +0200739
tierno5ee02052019-12-05 19:55:02 +0000740 def _get_ns_config_info(self, nsr_id):
tiernoc3f2a822019-11-05 13:45:04 +0000741 """
742 Generates a mapping between vnf,vdu elements and the N2VC id
tierno5ee02052019-12-05 19:55:02 +0000743 :param nsr_id: id of nsr to get last database _admin.deployed.VCA that contains this list
tiernoc3f2a822019-11-05 13:45:04 +0000744 :return: a dictionary with {osm-config-mapping: {}} where its element contains:
745 "<member-vnf-index>": <N2VC-id> for a vnf configuration, or
746 "<member-vnf-index>.<vdu.id>.<vdu replica(0, 1,..)>": <N2VC-id> for a vdu configuration
747 """
tierno5ee02052019-12-05 19:55:02 +0000748 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
749 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
tiernoc3f2a822019-11-05 13:45:04 +0000750 mapping = {}
751 ns_config_info = {"osm-config-mapping": mapping}
752 for vca in vca_deployed_list:
753 if not vca["member-vnf-index"]:
754 continue
755 if not vca["vdu_id"]:
756 mapping[vca["member-vnf-index"]] = vca["application"]
757 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100758 mapping[
759 "{}.{}.{}".format(
760 vca["member-vnf-index"], vca["vdu_id"], vca["vdu_count_index"]
761 )
762 ] = vca["application"]
tiernoc3f2a822019-11-05 13:45:04 +0000763 return ns_config_info
764
garciadeblas5697b8b2021-03-24 09:17:02 +0100765 async def _instantiate_ng_ro(
766 self,
767 logging_text,
768 nsr_id,
769 nsd,
770 db_nsr,
771 db_nslcmop,
772 db_vnfrs,
773 db_vnfds,
774 n2vc_key_list,
775 stage,
776 start_deploy,
777 timeout_ns_deploy,
778 ):
tierno2357f4e2020-10-19 16:38:59 +0000779
780 db_vims = {}
781
782 def get_vim_account(vim_account_id):
783 nonlocal db_vims
784 if vim_account_id in db_vims:
785 return db_vims[vim_account_id]
786 db_vim = self.db.get_one("vim_accounts", {"_id": vim_account_id})
787 db_vims[vim_account_id] = db_vim
788 return db_vim
789
790 # modify target_vld info with instantiation parameters
garciadeblas5697b8b2021-03-24 09:17:02 +0100791 def parse_vld_instantiation_params(
792 target_vim, target_vld, vld_params, target_sdn
793 ):
tierno2357f4e2020-10-19 16:38:59 +0000794 if vld_params.get("ip-profile"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100795 target_vld["vim_info"][target_vim]["ip_profile"] = vld_params[
796 "ip-profile"
797 ]
tierno2357f4e2020-10-19 16:38:59 +0000798 if vld_params.get("provider-network"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100799 target_vld["vim_info"][target_vim]["provider_network"] = vld_params[
800 "provider-network"
801 ]
tierno2357f4e2020-10-19 16:38:59 +0000802 if "sdn-ports" in vld_params["provider-network"] and target_sdn:
garciadeblas5697b8b2021-03-24 09:17:02 +0100803 target_vld["vim_info"][target_sdn]["sdn-ports"] = vld_params[
804 "provider-network"
805 ]["sdn-ports"]
tierno2357f4e2020-10-19 16:38:59 +0000806 if vld_params.get("wimAccountId"):
807 target_wim = "wim:{}".format(vld_params["wimAccountId"])
808 target_vld["vim_info"][target_wim] = {}
809 for param in ("vim-network-name", "vim-network-id"):
810 if vld_params.get(param):
811 if isinstance(vld_params[param], dict):
garciaale04694c62021-03-02 10:49:28 -0300812 for vim, vim_net in vld_params[param].items():
bravof922c4172020-11-24 21:21:43 -0300813 other_target_vim = "vim:" + vim
garciadeblas5697b8b2021-03-24 09:17:02 +0100814 populate_dict(
815 target_vld["vim_info"],
816 (other_target_vim, param.replace("-", "_")),
817 vim_net,
818 )
tierno2357f4e2020-10-19 16:38:59 +0000819 else: # isinstance str
garciadeblas5697b8b2021-03-24 09:17:02 +0100820 target_vld["vim_info"][target_vim][
821 param.replace("-", "_")
822 ] = vld_params[param]
bravof922c4172020-11-24 21:21:43 -0300823 if vld_params.get("common_id"):
824 target_vld["common_id"] = vld_params.get("common_id")
tierno2357f4e2020-10-19 16:38:59 +0000825
tierno69f0d382020-05-07 13:08:09 +0000826 nslcmop_id = db_nslcmop["_id"]
827 target = {
828 "name": db_nsr["name"],
829 "ns": {"vld": []},
830 "vnf": [],
831 "image": deepcopy(db_nsr["image"]),
832 "flavor": deepcopy(db_nsr["flavor"]),
833 "action_id": nslcmop_id,
tierno2357f4e2020-10-19 16:38:59 +0000834 "cloud_init_content": {},
tierno69f0d382020-05-07 13:08:09 +0000835 }
836 for image in target["image"]:
tierno2357f4e2020-10-19 16:38:59 +0000837 image["vim_info"] = {}
tierno69f0d382020-05-07 13:08:09 +0000838 for flavor in target["flavor"]:
tierno2357f4e2020-10-19 16:38:59 +0000839 flavor["vim_info"] = {}
tierno69f0d382020-05-07 13:08:09 +0000840
tierno2357f4e2020-10-19 16:38:59 +0000841 if db_nslcmop.get("lcmOperationType") != "instantiate":
842 # get parameters of instantiation:
garciadeblas5697b8b2021-03-24 09:17:02 +0100843 db_nslcmop_instantiate = self.db.get_list(
844 "nslcmops",
845 {
846 "nsInstanceId": db_nslcmop["nsInstanceId"],
847 "lcmOperationType": "instantiate",
848 },
849 )[-1]
tierno2357f4e2020-10-19 16:38:59 +0000850 ns_params = db_nslcmop_instantiate.get("operationParams")
851 else:
852 ns_params = db_nslcmop.get("operationParams")
bravof922c4172020-11-24 21:21:43 -0300853 ssh_keys_instantiation = ns_params.get("ssh_keys") or []
854 ssh_keys_all = ssh_keys_instantiation + (n2vc_key_list or [])
tierno69f0d382020-05-07 13:08:09 +0000855
856 cp2target = {}
tierno2357f4e2020-10-19 16:38:59 +0000857 for vld_index, vld in enumerate(db_nsr.get("vld")):
858 target_vim = "vim:{}".format(ns_params["vimAccountId"])
859 target_vld = {
860 "id": vld["id"],
861 "name": vld["name"],
862 "mgmt-network": vld.get("mgmt-network", False),
863 "type": vld.get("type"),
864 "vim_info": {
bravof922c4172020-11-24 21:21:43 -0300865 target_vim: {
866 "vim_network_name": vld.get("vim-network-name"),
garciadeblas5697b8b2021-03-24 09:17:02 +0100867 "vim_account_id": ns_params["vimAccountId"],
bravof922c4172020-11-24 21:21:43 -0300868 }
garciadeblas5697b8b2021-03-24 09:17:02 +0100869 },
tierno2357f4e2020-10-19 16:38:59 +0000870 }
871 # check if this network needs SDN assist
tierno2357f4e2020-10-19 16:38:59 +0000872 if vld.get("pci-interfaces"):
garciadeblasa5ae90b2021-02-12 11:26:46 +0000873 db_vim = get_vim_account(ns_params["vimAccountId"])
tierno2357f4e2020-10-19 16:38:59 +0000874 sdnc_id = db_vim["config"].get("sdn-controller")
875 if sdnc_id:
garciadeblasa5ae90b2021-02-12 11:26:46 +0000876 sdn_vld = "nsrs:{}:vld.{}".format(nsr_id, vld["id"])
877 target_sdn = "sdn:{}".format(sdnc_id)
878 target_vld["vim_info"][target_sdn] = {
garciadeblas5697b8b2021-03-24 09:17:02 +0100879 "sdn": True,
880 "target_vim": target_vim,
881 "vlds": [sdn_vld],
882 "type": vld.get("type"),
883 }
tierno2357f4e2020-10-19 16:38:59 +0000884
bravof922c4172020-11-24 21:21:43 -0300885 nsd_vnf_profiles = get_vnf_profiles(nsd)
886 for nsd_vnf_profile in nsd_vnf_profiles:
887 for cp in nsd_vnf_profile["virtual-link-connectivity"]:
888 if cp["virtual-link-profile-id"] == vld["id"]:
garciadeblas5697b8b2021-03-24 09:17:02 +0100889 cp2target[
890 "member_vnf:{}.{}".format(
891 cp["constituent-cpd-id"][0][
892 "constituent-base-element-id"
893 ],
894 cp["constituent-cpd-id"][0]["constituent-cpd-id"],
895 )
896 ] = "nsrs:{}:vld.{}".format(nsr_id, vld_index)
tierno2357f4e2020-10-19 16:38:59 +0000897
898 # check at nsd descriptor, if there is an ip-profile
899 vld_params = {}
lloretgalleg19008482021-04-19 11:40:18 +0000900 nsd_vlp = find_in_list(
901 get_virtual_link_profiles(nsd),
garciadeblas5697b8b2021-03-24 09:17:02 +0100902 lambda a_link_profile: a_link_profile["virtual-link-desc-id"]
903 == vld["id"],
904 )
905 if (
906 nsd_vlp
907 and nsd_vlp.get("virtual-link-protocol-data")
908 and nsd_vlp["virtual-link-protocol-data"].get("l3-protocol-data")
909 ):
910 ip_profile_source_data = nsd_vlp["virtual-link-protocol-data"][
911 "l3-protocol-data"
912 ]
lloretgalleg19008482021-04-19 11:40:18 +0000913 ip_profile_dest_data = {}
914 if "ip-version" in ip_profile_source_data:
garciadeblas5697b8b2021-03-24 09:17:02 +0100915 ip_profile_dest_data["ip-version"] = ip_profile_source_data[
916 "ip-version"
917 ]
lloretgalleg19008482021-04-19 11:40:18 +0000918 if "cidr" in ip_profile_source_data:
garciadeblas5697b8b2021-03-24 09:17:02 +0100919 ip_profile_dest_data["subnet-address"] = ip_profile_source_data[
920 "cidr"
921 ]
lloretgalleg19008482021-04-19 11:40:18 +0000922 if "gateway-ip" in ip_profile_source_data:
garciadeblas5697b8b2021-03-24 09:17:02 +0100923 ip_profile_dest_data["gateway-address"] = ip_profile_source_data[
924 "gateway-ip"
925 ]
lloretgalleg19008482021-04-19 11:40:18 +0000926 if "dhcp-enabled" in ip_profile_source_data:
927 ip_profile_dest_data["dhcp-params"] = {
928 "enabled": ip_profile_source_data["dhcp-enabled"]
929 }
930 vld_params["ip-profile"] = ip_profile_dest_data
bravof922c4172020-11-24 21:21:43 -0300931
tierno2357f4e2020-10-19 16:38:59 +0000932 # update vld_params with instantiation params
garciadeblas5697b8b2021-03-24 09:17:02 +0100933 vld_instantiation_params = find_in_list(
934 get_iterable(ns_params, "vld"),
935 lambda a_vld: a_vld["name"] in (vld["name"], vld["id"]),
936 )
tierno2357f4e2020-10-19 16:38:59 +0000937 if vld_instantiation_params:
938 vld_params.update(vld_instantiation_params)
bravof922c4172020-11-24 21:21:43 -0300939 parse_vld_instantiation_params(target_vim, target_vld, vld_params, None)
tierno69f0d382020-05-07 13:08:09 +0000940 target["ns"]["vld"].append(target_vld)
bravof922c4172020-11-24 21:21:43 -0300941
tierno69f0d382020-05-07 13:08:09 +0000942 for vnfr in db_vnfrs.values():
garciadeblas5697b8b2021-03-24 09:17:02 +0100943 vnfd = find_in_list(
944 db_vnfds, lambda db_vnf: db_vnf["id"] == vnfr["vnfd-ref"]
945 )
946 vnf_params = find_in_list(
947 get_iterable(ns_params, "vnf"),
948 lambda a_vnf: a_vnf["member-vnf-index"] == vnfr["member-vnf-index-ref"],
949 )
tierno69f0d382020-05-07 13:08:09 +0000950 target_vnf = deepcopy(vnfr)
tierno2357f4e2020-10-19 16:38:59 +0000951 target_vim = "vim:{}".format(vnfr["vim-account-id"])
tierno69f0d382020-05-07 13:08:09 +0000952 for vld in target_vnf.get("vld", ()):
tierno2357f4e2020-10-19 16:38:59 +0000953 # check if connected to a ns.vld, to fill target'
garciadeblas5697b8b2021-03-24 09:17:02 +0100954 vnf_cp = find_in_list(
955 vnfd.get("int-virtual-link-desc", ()),
956 lambda cpd: cpd.get("id") == vld["id"],
957 )
tierno69f0d382020-05-07 13:08:09 +0000958 if vnf_cp:
garciadeblas5697b8b2021-03-24 09:17:02 +0100959 ns_cp = "member_vnf:{}.{}".format(
960 vnfr["member-vnf-index-ref"], vnf_cp["id"]
961 )
tierno69f0d382020-05-07 13:08:09 +0000962 if cp2target.get(ns_cp):
963 vld["target"] = cp2target[ns_cp]
bravof922c4172020-11-24 21:21:43 -0300964
garciadeblas5697b8b2021-03-24 09:17:02 +0100965 vld["vim_info"] = {
966 target_vim: {"vim_network_name": vld.get("vim-network-name")}
967 }
tierno2357f4e2020-10-19 16:38:59 +0000968 # check if this network needs SDN assist
969 target_sdn = None
970 if vld.get("pci-interfaces"):
971 db_vim = get_vim_account(vnfr["vim-account-id"])
972 sdnc_id = db_vim["config"].get("sdn-controller")
973 if sdnc_id:
974 sdn_vld = "vnfrs:{}:vld.{}".format(target_vnf["_id"], vld["id"])
975 target_sdn = "sdn:{}".format(sdnc_id)
976 vld["vim_info"][target_sdn] = {
garciadeblas5697b8b2021-03-24 09:17:02 +0100977 "sdn": True,
978 "target_vim": target_vim,
979 "vlds": [sdn_vld],
980 "type": vld.get("type"),
981 }
tierno69f0d382020-05-07 13:08:09 +0000982
tierno2357f4e2020-10-19 16:38:59 +0000983 # check at vnfd descriptor, if there is an ip-profile
984 vld_params = {}
bravof922c4172020-11-24 21:21:43 -0300985 vnfd_vlp = find_in_list(
986 get_virtual_link_profiles(vnfd),
garciadeblas5697b8b2021-03-24 09:17:02 +0100987 lambda a_link_profile: a_link_profile["id"] == vld["id"],
bravof922c4172020-11-24 21:21:43 -0300988 )
garciadeblas5697b8b2021-03-24 09:17:02 +0100989 if (
990 vnfd_vlp
991 and vnfd_vlp.get("virtual-link-protocol-data")
992 and vnfd_vlp["virtual-link-protocol-data"].get("l3-protocol-data")
993 ):
994 ip_profile_source_data = vnfd_vlp["virtual-link-protocol-data"][
995 "l3-protocol-data"
996 ]
bravof922c4172020-11-24 21:21:43 -0300997 ip_profile_dest_data = {}
998 if "ip-version" in ip_profile_source_data:
garciadeblas5697b8b2021-03-24 09:17:02 +0100999 ip_profile_dest_data["ip-version"] = ip_profile_source_data[
1000 "ip-version"
1001 ]
bravof922c4172020-11-24 21:21:43 -03001002 if "cidr" in ip_profile_source_data:
garciadeblas5697b8b2021-03-24 09:17:02 +01001003 ip_profile_dest_data["subnet-address"] = ip_profile_source_data[
1004 "cidr"
1005 ]
bravof922c4172020-11-24 21:21:43 -03001006 if "gateway-ip" in ip_profile_source_data:
garciadeblas5697b8b2021-03-24 09:17:02 +01001007 ip_profile_dest_data[
1008 "gateway-address"
1009 ] = ip_profile_source_data["gateway-ip"]
bravof922c4172020-11-24 21:21:43 -03001010 if "dhcp-enabled" in ip_profile_source_data:
1011 ip_profile_dest_data["dhcp-params"] = {
1012 "enabled": ip_profile_source_data["dhcp-enabled"]
1013 }
1014
1015 vld_params["ip-profile"] = ip_profile_dest_data
tierno2357f4e2020-10-19 16:38:59 +00001016 # update vld_params with instantiation params
1017 if vnf_params:
garciadeblas5697b8b2021-03-24 09:17:02 +01001018 vld_instantiation_params = find_in_list(
1019 get_iterable(vnf_params, "internal-vld"),
1020 lambda i_vld: i_vld["name"] == vld["id"],
1021 )
tierno2357f4e2020-10-19 16:38:59 +00001022 if vld_instantiation_params:
1023 vld_params.update(vld_instantiation_params)
1024 parse_vld_instantiation_params(target_vim, vld, vld_params, target_sdn)
1025
1026 vdur_list = []
tierno69f0d382020-05-07 13:08:09 +00001027 for vdur in target_vnf.get("vdur", ()):
tierno2357f4e2020-10-19 16:38:59 +00001028 if vdur.get("status") == "DELETING" or vdur.get("pdu-type"):
1029 continue # This vdu must not be created
bravof922c4172020-11-24 21:21:43 -03001030 vdur["vim_info"] = {"vim_account_id": vnfr["vim-account-id"]}
tierno69f0d382020-05-07 13:08:09 +00001031
bravof922c4172020-11-24 21:21:43 -03001032 self.logger.debug("NS > ssh_keys > {}".format(ssh_keys_all))
1033
1034 if ssh_keys_all:
bravofe5a31bc2021-02-17 19:09:12 -03001035 vdu_configuration = get_configuration(vnfd, vdur["vdu-id-ref"])
1036 vnf_configuration = get_configuration(vnfd, vnfd["id"])
garciadeblas5697b8b2021-03-24 09:17:02 +01001037 if (
1038 vdu_configuration
1039 and vdu_configuration.get("config-access")
1040 and vdu_configuration.get("config-access").get("ssh-access")
1041 ):
bravof922c4172020-11-24 21:21:43 -03001042 vdur["ssh-keys"] = ssh_keys_all
garciadeblas5697b8b2021-03-24 09:17:02 +01001043 vdur["ssh-access-required"] = vdu_configuration[
1044 "config-access"
1045 ]["ssh-access"]["required"]
1046 elif (
1047 vnf_configuration
1048 and vnf_configuration.get("config-access")
1049 and vnf_configuration.get("config-access").get("ssh-access")
1050 and any(iface.get("mgmt-vnf") for iface in vdur["interfaces"])
1051 ):
bravof922c4172020-11-24 21:21:43 -03001052 vdur["ssh-keys"] = ssh_keys_all
garciadeblas5697b8b2021-03-24 09:17:02 +01001053 vdur["ssh-access-required"] = vnf_configuration[
1054 "config-access"
1055 ]["ssh-access"]["required"]
1056 elif ssh_keys_instantiation and find_in_list(
1057 vdur["interfaces"], lambda iface: iface.get("mgmt-vnf")
1058 ):
bravof922c4172020-11-24 21:21:43 -03001059 vdur["ssh-keys"] = ssh_keys_instantiation
tierno69f0d382020-05-07 13:08:09 +00001060
bravof922c4172020-11-24 21:21:43 -03001061 self.logger.debug("NS > vdur > {}".format(vdur))
1062
1063 vdud = get_vdu(vnfd, vdur["vdu-id-ref"])
tierno69f0d382020-05-07 13:08:09 +00001064 # cloud-init
1065 if vdud.get("cloud-init-file"):
garciadeblas5697b8b2021-03-24 09:17:02 +01001066 vdur["cloud-init"] = "{}:file:{}".format(
1067 vnfd["_id"], vdud.get("cloud-init-file")
1068 )
tierno2357f4e2020-10-19 16:38:59 +00001069 # read file and put content at target.cloul_init_content. Avoid ng_ro to use shared package system
1070 if vdur["cloud-init"] not in target["cloud_init_content"]:
1071 base_folder = vnfd["_admin"]["storage"]
bravof14af4e72021-11-08 17:18:50 -03001072 if base_folder["pkg-dir"]:
1073 cloud_init_file = "{}/{}/cloud_init/{}".format(
1074 base_folder["folder"],
1075 base_folder["pkg-dir"],
1076 vdud.get("cloud-init-file"),
1077 )
1078 else:
1079 cloud_init_file = "{}/Scripts/cloud_init/{}".format(
1080 base_folder["folder"],
1081 vdud.get("cloud-init-file"),
1082 )
tierno2357f4e2020-10-19 16:38:59 +00001083 with self.fs.file_open(cloud_init_file, "r") as ci_file:
garciadeblas5697b8b2021-03-24 09:17:02 +01001084 target["cloud_init_content"][
1085 vdur["cloud-init"]
1086 ] = ci_file.read()
tierno69f0d382020-05-07 13:08:09 +00001087 elif vdud.get("cloud-init"):
garciadeblas5697b8b2021-03-24 09:17:02 +01001088 vdur["cloud-init"] = "{}:vdu:{}".format(
1089 vnfd["_id"], get_vdu_index(vnfd, vdur["vdu-id-ref"])
1090 )
tierno2357f4e2020-10-19 16:38:59 +00001091 # put content at target.cloul_init_content. Avoid ng_ro read vnfd descriptor
garciadeblas5697b8b2021-03-24 09:17:02 +01001092 target["cloud_init_content"][vdur["cloud-init"]] = vdud[
1093 "cloud-init"
1094 ]
tierno2357f4e2020-10-19 16:38:59 +00001095 vdur["additionalParams"] = vdur.get("additionalParams") or {}
garciadeblas5697b8b2021-03-24 09:17:02 +01001096 deploy_params_vdu = self._format_additional_params(
1097 vdur.get("additionalParams") or {}
1098 )
1099 deploy_params_vdu["OSM"] = get_osm_params(
1100 vnfr, vdur["vdu-id-ref"], vdur["count-index"]
1101 )
tierno2357f4e2020-10-19 16:38:59 +00001102 vdur["additionalParams"] = deploy_params_vdu
tierno69f0d382020-05-07 13:08:09 +00001103
1104 # flavor
1105 ns_flavor = target["flavor"][int(vdur["ns-flavor-id"])]
tierno2357f4e2020-10-19 16:38:59 +00001106 if target_vim not in ns_flavor["vim_info"]:
1107 ns_flavor["vim_info"][target_vim] = {}
lloretgalleg7dc94672021-02-08 11:49:50 +00001108
1109 # deal with images
1110 # in case alternative images are provided we must check if they should be applied
1111 # for the vim_type, modify the vim_type taking into account
1112 ns_image_id = int(vdur["ns-image-id"])
1113 if vdur.get("alt-image-ids"):
1114 db_vim = get_vim_account(vnfr["vim-account-id"])
1115 vim_type = db_vim["vim_type"]
1116 for alt_image_id in vdur.get("alt-image-ids"):
1117 ns_alt_image = target["image"][int(alt_image_id)]
1118 if vim_type == ns_alt_image.get("vim-type"):
1119 # must use alternative image
garciadeblas5697b8b2021-03-24 09:17:02 +01001120 self.logger.debug(
1121 "use alternative image id: {}".format(alt_image_id)
1122 )
lloretgalleg7dc94672021-02-08 11:49:50 +00001123 ns_image_id = alt_image_id
1124 vdur["ns-image-id"] = ns_image_id
1125 break
1126 ns_image = target["image"][int(ns_image_id)]
tierno2357f4e2020-10-19 16:38:59 +00001127 if target_vim not in ns_image["vim_info"]:
1128 ns_image["vim_info"][target_vim] = {}
tierno69f0d382020-05-07 13:08:09 +00001129
tierno2357f4e2020-10-19 16:38:59 +00001130 vdur["vim_info"] = {target_vim: {}}
1131 # instantiation parameters
1132 # if vnf_params:
1133 # vdu_instantiation_params = next((v for v in get_iterable(vnf_params, "vdu") if v["id"] ==
1134 # vdud["id"]), None)
1135 vdur_list.append(vdur)
1136 target_vnf["vdur"] = vdur_list
tierno69f0d382020-05-07 13:08:09 +00001137 target["vnf"].append(target_vnf)
1138
1139 desc = await self.RO.deploy(nsr_id, target)
bravof922c4172020-11-24 21:21:43 -03001140 self.logger.debug("RO return > {}".format(desc))
tierno69f0d382020-05-07 13:08:09 +00001141 action_id = desc["action_id"]
garciadeblas5697b8b2021-03-24 09:17:02 +01001142 await self._wait_ng_ro(
1143 nsr_id, action_id, nslcmop_id, start_deploy, timeout_ns_deploy, stage
1144 )
tierno69f0d382020-05-07 13:08:09 +00001145
1146 # Updating NSR
1147 db_nsr_update = {
1148 "_admin.deployed.RO.operational-status": "running",
garciadeblas5697b8b2021-03-24 09:17:02 +01001149 "detailed-status": " ".join(stage),
tierno69f0d382020-05-07 13:08:09 +00001150 }
1151 # db_nsr["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
1152 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1153 self._write_op_status(nslcmop_id, stage)
garciadeblas5697b8b2021-03-24 09:17:02 +01001154 self.logger.debug(
1155 logging_text + "ns deployed at RO. RO_id={}".format(action_id)
1156 )
tierno69f0d382020-05-07 13:08:09 +00001157 return
1158
garciadeblas5697b8b2021-03-24 09:17:02 +01001159 async def _wait_ng_ro(
1160 self,
1161 nsr_id,
1162 action_id,
1163 nslcmop_id=None,
1164 start_time=None,
1165 timeout=600,
1166 stage=None,
1167 ):
tierno69f0d382020-05-07 13:08:09 +00001168 detailed_status_old = None
1169 db_nsr_update = {}
tierno2357f4e2020-10-19 16:38:59 +00001170 start_time = start_time or time()
tierno69f0d382020-05-07 13:08:09 +00001171 while time() <= start_time + timeout:
1172 desc_status = await self.RO.status(nsr_id, action_id)
bravof922c4172020-11-24 21:21:43 -03001173 self.logger.debug("Wait NG RO > {}".format(desc_status))
tierno69f0d382020-05-07 13:08:09 +00001174 if desc_status["status"] == "FAILED":
1175 raise NgRoException(desc_status["details"])
1176 elif desc_status["status"] == "BUILD":
tierno2357f4e2020-10-19 16:38:59 +00001177 if stage:
1178 stage[2] = "VIM: ({})".format(desc_status["details"])
tierno69f0d382020-05-07 13:08:09 +00001179 elif desc_status["status"] == "DONE":
tierno2357f4e2020-10-19 16:38:59 +00001180 if stage:
1181 stage[2] = "Deployed at VIM"
tierno69f0d382020-05-07 13:08:09 +00001182 break
1183 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001184 assert False, "ROclient.check_ns_status returns unknown {}".format(
1185 desc_status["status"]
1186 )
tierno2357f4e2020-10-19 16:38:59 +00001187 if stage and nslcmop_id and stage[2] != detailed_status_old:
tierno69f0d382020-05-07 13:08:09 +00001188 detailed_status_old = stage[2]
1189 db_nsr_update["detailed-status"] = " ".join(stage)
1190 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1191 self._write_op_status(nslcmop_id, stage)
bravof922c4172020-11-24 21:21:43 -03001192 await asyncio.sleep(15, loop=self.loop)
tierno69f0d382020-05-07 13:08:09 +00001193 else: # timeout_ns_deploy
1194 raise NgRoException("Timeout waiting ns to deploy")
1195
garciadeblas5697b8b2021-03-24 09:17:02 +01001196 async def _terminate_ng_ro(
1197 self, logging_text, nsr_deployed, nsr_id, nslcmop_id, stage
1198 ):
tierno69f0d382020-05-07 13:08:09 +00001199 db_nsr_update = {}
1200 failed_detail = []
1201 action_id = None
1202 start_deploy = time()
1203 try:
1204 target = {
1205 "ns": {"vld": []},
1206 "vnf": [],
1207 "image": [],
1208 "flavor": [],
garciadeblas5697b8b2021-03-24 09:17:02 +01001209 "action_id": nslcmop_id,
tierno69f0d382020-05-07 13:08:09 +00001210 }
1211 desc = await self.RO.deploy(nsr_id, target)
1212 action_id = desc["action_id"]
1213 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = action_id
1214 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETING"
garciadeblas5697b8b2021-03-24 09:17:02 +01001215 self.logger.debug(
1216 logging_text
1217 + "ns terminate action at RO. action_id={}".format(action_id)
1218 )
tierno69f0d382020-05-07 13:08:09 +00001219
1220 # wait until done
1221 delete_timeout = 20 * 60 # 20 minutes
garciadeblas5697b8b2021-03-24 09:17:02 +01001222 await self._wait_ng_ro(
1223 nsr_id, action_id, nslcmop_id, start_deploy, delete_timeout, stage
1224 )
tierno69f0d382020-05-07 13:08:09 +00001225
1226 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
1227 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
1228 # delete all nsr
1229 await self.RO.delete(nsr_id)
1230 except Exception as e:
1231 if isinstance(e, NgRoException) and e.http_code == 404: # not found
1232 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
1233 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
1234 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
garciadeblas5697b8b2021-03-24 09:17:02 +01001235 self.logger.debug(
1236 logging_text + "RO_action_id={} already deleted".format(action_id)
1237 )
tierno69f0d382020-05-07 13:08:09 +00001238 elif isinstance(e, NgRoException) and e.http_code == 409: # conflict
1239 failed_detail.append("delete conflict: {}".format(e))
garciadeblas5697b8b2021-03-24 09:17:02 +01001240 self.logger.debug(
1241 logging_text
1242 + "RO_action_id={} delete conflict: {}".format(action_id, e)
1243 )
tierno69f0d382020-05-07 13:08:09 +00001244 else:
1245 failed_detail.append("delete error: {}".format(e))
garciadeblas5697b8b2021-03-24 09:17:02 +01001246 self.logger.error(
1247 logging_text
1248 + "RO_action_id={} delete error: {}".format(action_id, e)
1249 )
tierno69f0d382020-05-07 13:08:09 +00001250
1251 if failed_detail:
1252 stage[2] = "Error deleting from VIM"
1253 else:
1254 stage[2] = "Deleted from VIM"
1255 db_nsr_update["detailed-status"] = " ".join(stage)
1256 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1257 self._write_op_status(nslcmop_id, stage)
1258
1259 if failed_detail:
1260 raise LcmException("; ".join(failed_detail))
1261 return
1262
garciadeblas5697b8b2021-03-24 09:17:02 +01001263 async def instantiate_RO(
1264 self,
1265 logging_text,
1266 nsr_id,
1267 nsd,
1268 db_nsr,
1269 db_nslcmop,
1270 db_vnfrs,
1271 db_vnfds,
1272 n2vc_key_list,
1273 stage,
1274 ):
tiernoe95ed362020-04-23 08:24:57 +00001275 """
1276 Instantiate at RO
1277 :param logging_text: preffix text to use at logging
1278 :param nsr_id: nsr identity
1279 :param nsd: database content of ns descriptor
1280 :param db_nsr: database content of ns record
1281 :param db_nslcmop: database content of ns operation, in this case, 'instantiate'
1282 :param db_vnfrs:
bravof922c4172020-11-24 21:21:43 -03001283 :param db_vnfds: database content of vnfds, indexed by id (not _id). {id: {vnfd_object}, ...}
tiernoe95ed362020-04-23 08:24:57 +00001284 :param n2vc_key_list: ssh-public-key list to be inserted to management vdus via cloud-init
1285 :param stage: list with 3 items: [general stage, tasks, vim_specific]. This task will write over vim_specific
1286 :return: None or exception
1287 """
tiernoe876f672020-02-13 14:34:48 +00001288 try:
tiernoe876f672020-02-13 14:34:48 +00001289 start_deploy = time()
1290 ns_params = db_nslcmop.get("operationParams")
1291 if ns_params and ns_params.get("timeout_ns_deploy"):
1292 timeout_ns_deploy = ns_params["timeout_ns_deploy"]
1293 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001294 timeout_ns_deploy = self.timeout.get(
1295 "ns_deploy", self.timeout_ns_deploy
1296 )
quilesj7e13aeb2019-10-08 13:34:55 +02001297
tiernoe876f672020-02-13 14:34:48 +00001298 # Check for and optionally request placement optimization. Database will be updated if placement activated
1299 stage[2] = "Waiting for Placement."
tierno8790a3d2020-04-23 22:49:52 +00001300 if await self._do_placement(logging_text, db_nslcmop, db_vnfrs):
1301 # in case of placement change ns_params[vimAcountId) if not present at any vnfrs
1302 for vnfr in db_vnfrs.values():
1303 if ns_params["vimAccountId"] == vnfr["vim-account-id"]:
1304 break
1305 else:
1306 ns_params["vimAccountId"] == vnfr["vim-account-id"]
quilesj7e13aeb2019-10-08 13:34:55 +02001307
garciadeblas5697b8b2021-03-24 09:17:02 +01001308 return await self._instantiate_ng_ro(
1309 logging_text,
1310 nsr_id,
1311 nsd,
1312 db_nsr,
1313 db_nslcmop,
1314 db_vnfrs,
1315 db_vnfds,
1316 n2vc_key_list,
1317 stage,
1318 start_deploy,
1319 timeout_ns_deploy,
1320 )
tierno2357f4e2020-10-19 16:38:59 +00001321 except Exception as e:
tierno067e04a2020-03-31 12:53:13 +00001322 stage[2] = "ERROR deploying at VIM"
tiernoe876f672020-02-13 14:34:48 +00001323 self.set_vnfr_at_error(db_vnfrs, str(e))
garciadeblas5697b8b2021-03-24 09:17:02 +01001324 self.logger.error(
1325 "Error deploying at VIM {}".format(e),
1326 exc_info=not isinstance(
1327 e,
1328 (
1329 ROclient.ROClientException,
1330 LcmException,
1331 DbException,
1332 NgRoException,
1333 ),
1334 ),
1335 )
tiernoe876f672020-02-13 14:34:48 +00001336 raise
quilesj7e13aeb2019-10-08 13:34:55 +02001337
tierno7ecbc342020-09-21 14:05:39 +00001338 async def wait_kdu_up(self, logging_text, nsr_id, vnfr_id, kdu_name):
1339 """
1340 Wait for kdu to be up, get ip address
1341 :param logging_text: prefix use for logging
1342 :param nsr_id:
1343 :param vnfr_id:
1344 :param kdu_name:
1345 :return: IP address
1346 """
1347
1348 # self.logger.debug(logging_text + "Starting wait_kdu_up")
1349 nb_tries = 0
1350
1351 while nb_tries < 360:
1352 db_vnfr = self.db.get_one("vnfrs", {"_id": vnfr_id})
garciadeblas5697b8b2021-03-24 09:17:02 +01001353 kdur = next(
1354 (
1355 x
1356 for x in get_iterable(db_vnfr, "kdur")
1357 if x.get("kdu-name") == kdu_name
1358 ),
1359 None,
1360 )
tierno7ecbc342020-09-21 14:05:39 +00001361 if not kdur:
garciadeblas5697b8b2021-03-24 09:17:02 +01001362 raise LcmException(
1363 "Not found vnfr_id={}, kdu_name={}".format(vnfr_id, kdu_name)
1364 )
tierno7ecbc342020-09-21 14:05:39 +00001365 if kdur.get("status"):
1366 if kdur["status"] in ("READY", "ENABLED"):
1367 return kdur.get("ip-address")
1368 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001369 raise LcmException(
1370 "target KDU={} is in error state".format(kdu_name)
1371 )
tierno7ecbc342020-09-21 14:05:39 +00001372
1373 await asyncio.sleep(10, loop=self.loop)
1374 nb_tries += 1
1375 raise LcmException("Timeout waiting KDU={} instantiated".format(kdu_name))
1376
garciadeblas5697b8b2021-03-24 09:17:02 +01001377 async def wait_vm_up_insert_key_ro(
1378 self, logging_text, nsr_id, vnfr_id, vdu_id, vdu_index, pub_key=None, user=None
1379 ):
tiernoa5088192019-11-26 16:12:53 +00001380 """
1381 Wait for ip addres at RO, and optionally, insert public key in virtual machine
1382 :param logging_text: prefix use for logging
1383 :param nsr_id:
1384 :param vnfr_id:
1385 :param vdu_id:
1386 :param vdu_index:
1387 :param pub_key: public ssh key to inject, None to skip
1388 :param user: user to apply the public ssh key
1389 :return: IP address
1390 """
quilesj7e13aeb2019-10-08 13:34:55 +02001391
tierno2357f4e2020-10-19 16:38:59 +00001392 self.logger.debug(logging_text + "Starting wait_vm_up_insert_key_ro")
tiernod8323042019-08-09 11:32:23 +00001393 ro_nsr_id = None
1394 ip_address = None
1395 nb_tries = 0
1396 target_vdu_id = None
quilesj3149f262019-12-03 10:58:10 +00001397 ro_retries = 0
quilesj7e13aeb2019-10-08 13:34:55 +02001398
tiernod8323042019-08-09 11:32:23 +00001399 while True:
quilesj7e13aeb2019-10-08 13:34:55 +02001400
quilesj3149f262019-12-03 10:58:10 +00001401 ro_retries += 1
1402 if ro_retries >= 360: # 1 hour
garciadeblas5697b8b2021-03-24 09:17:02 +01001403 raise LcmException(
1404 "Not found _admin.deployed.RO.nsr_id for nsr_id: {}".format(nsr_id)
1405 )
quilesj3149f262019-12-03 10:58:10 +00001406
tiernod8323042019-08-09 11:32:23 +00001407 await asyncio.sleep(10, loop=self.loop)
quilesj7e13aeb2019-10-08 13:34:55 +02001408
1409 # get ip address
tiernod8323042019-08-09 11:32:23 +00001410 if not target_vdu_id:
1411 db_vnfr = self.db.get_one("vnfrs", {"_id": vnfr_id})
quilesj3149f262019-12-03 10:58:10 +00001412
1413 if not vdu_id: # for the VNF case
tiernoe876f672020-02-13 14:34:48 +00001414 if db_vnfr.get("status") == "ERROR":
garciadeblas5697b8b2021-03-24 09:17:02 +01001415 raise LcmException(
1416 "Cannot inject ssh-key because target VNF is in error state"
1417 )
tiernod8323042019-08-09 11:32:23 +00001418 ip_address = db_vnfr.get("ip-address")
1419 if not ip_address:
1420 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01001421 vdur = next(
1422 (
1423 x
1424 for x in get_iterable(db_vnfr, "vdur")
1425 if x.get("ip-address") == ip_address
1426 ),
1427 None,
1428 )
quilesj3149f262019-12-03 10:58:10 +00001429 else: # VDU case
garciadeblas5697b8b2021-03-24 09:17:02 +01001430 vdur = next(
1431 (
1432 x
1433 for x in get_iterable(db_vnfr, "vdur")
1434 if x.get("vdu-id-ref") == vdu_id
1435 and x.get("count-index") == vdu_index
1436 ),
1437 None,
1438 )
quilesj3149f262019-12-03 10:58:10 +00001439
garciadeblas5697b8b2021-03-24 09:17:02 +01001440 if (
1441 not vdur and len(db_vnfr.get("vdur", ())) == 1
1442 ): # If only one, this should be the target vdu
tierno0e8c3f02020-03-12 17:18:21 +00001443 vdur = db_vnfr["vdur"][0]
quilesj3149f262019-12-03 10:58:10 +00001444 if not vdur:
garciadeblas5697b8b2021-03-24 09:17:02 +01001445 raise LcmException(
1446 "Not found vnfr_id={}, vdu_id={}, vdu_index={}".format(
1447 vnfr_id, vdu_id, vdu_index
1448 )
1449 )
tierno2357f4e2020-10-19 16:38:59 +00001450 # New generation RO stores information at "vim_info"
1451 ng_ro_status = None
David Garciaa8bbe672020-11-19 13:06:54 +01001452 target_vim = None
tierno2357f4e2020-10-19 16:38:59 +00001453 if vdur.get("vim_info"):
garciadeblas5697b8b2021-03-24 09:17:02 +01001454 target_vim = next(
1455 t for t in vdur["vim_info"]
1456 ) # there should be only one key
tierno2357f4e2020-10-19 16:38:59 +00001457 ng_ro_status = vdur["vim_info"][target_vim].get("vim_status")
garciadeblas5697b8b2021-03-24 09:17:02 +01001458 if (
1459 vdur.get("pdu-type")
1460 or vdur.get("status") == "ACTIVE"
1461 or ng_ro_status == "ACTIVE"
1462 ):
quilesj3149f262019-12-03 10:58:10 +00001463 ip_address = vdur.get("ip-address")
1464 if not ip_address:
1465 continue
1466 target_vdu_id = vdur["vdu-id-ref"]
bravof922c4172020-11-24 21:21:43 -03001467 elif vdur.get("status") == "ERROR" or ng_ro_status == "ERROR":
garciadeblas5697b8b2021-03-24 09:17:02 +01001468 raise LcmException(
1469 "Cannot inject ssh-key because target VM is in error state"
1470 )
quilesj3149f262019-12-03 10:58:10 +00001471
tiernod8323042019-08-09 11:32:23 +00001472 if not target_vdu_id:
1473 continue
tiernod8323042019-08-09 11:32:23 +00001474
quilesj7e13aeb2019-10-08 13:34:55 +02001475 # inject public key into machine
1476 if pub_key and user:
tierno2357f4e2020-10-19 16:38:59 +00001477 self.logger.debug(logging_text + "Inserting RO key")
bravof922c4172020-11-24 21:21:43 -03001478 self.logger.debug("SSH > PubKey > {}".format(pub_key))
tierno0e8c3f02020-03-12 17:18:21 +00001479 if vdur.get("pdu-type"):
1480 self.logger.error(logging_text + "Cannot inject ssh-ky to a PDU")
1481 return ip_address
quilesj7e13aeb2019-10-08 13:34:55 +02001482 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01001483 ro_vm_id = "{}-{}".format(
1484 db_vnfr["member-vnf-index-ref"], target_vdu_id
1485 ) # TODO add vdu_index
tierno69f0d382020-05-07 13:08:09 +00001486 if self.ng_ro:
garciadeblas5697b8b2021-03-24 09:17:02 +01001487 target = {
1488 "action": {
1489 "action": "inject_ssh_key",
1490 "key": pub_key,
1491 "user": user,
1492 },
1493 "vnf": [{"_id": vnfr_id, "vdur": [{"id": vdur["id"]}]}],
1494 }
tierno2357f4e2020-10-19 16:38:59 +00001495 desc = await self.RO.deploy(nsr_id, target)
1496 action_id = desc["action_id"]
1497 await self._wait_ng_ro(nsr_id, action_id, timeout=600)
1498 break
tierno69f0d382020-05-07 13:08:09 +00001499 else:
tierno2357f4e2020-10-19 16:38:59 +00001500 # wait until NS is deployed at RO
1501 if not ro_nsr_id:
1502 db_nsrs = self.db.get_one("nsrs", {"_id": nsr_id})
garciadeblas5697b8b2021-03-24 09:17:02 +01001503 ro_nsr_id = deep_get(
1504 db_nsrs, ("_admin", "deployed", "RO", "nsr_id")
1505 )
tierno2357f4e2020-10-19 16:38:59 +00001506 if not ro_nsr_id:
1507 continue
tierno69f0d382020-05-07 13:08:09 +00001508 result_dict = await self.RO.create_action(
1509 item="ns",
1510 item_id_name=ro_nsr_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01001511 descriptor={
1512 "add_public_key": pub_key,
1513 "vms": [ro_vm_id],
1514 "user": user,
1515 },
tierno69f0d382020-05-07 13:08:09 +00001516 )
1517 # result_dict contains the format {VM-id: {vim_result: 200, description: text}}
1518 if not result_dict or not isinstance(result_dict, dict):
garciadeblas5697b8b2021-03-24 09:17:02 +01001519 raise LcmException(
1520 "Unknown response from RO when injecting key"
1521 )
tierno69f0d382020-05-07 13:08:09 +00001522 for result in result_dict.values():
1523 if result.get("vim_result") == 200:
1524 break
1525 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001526 raise ROclient.ROClientException(
1527 "error injecting key: {}".format(
1528 result.get("description")
1529 )
1530 )
tierno69f0d382020-05-07 13:08:09 +00001531 break
1532 except NgRoException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001533 raise LcmException(
1534 "Reaching max tries injecting key. Error: {}".format(e)
1535 )
quilesj7e13aeb2019-10-08 13:34:55 +02001536 except ROclient.ROClientException as e:
tiernoa5088192019-11-26 16:12:53 +00001537 if not nb_tries:
garciadeblas5697b8b2021-03-24 09:17:02 +01001538 self.logger.debug(
1539 logging_text
1540 + "error injecting key: {}. Retrying until {} seconds".format(
1541 e, 20 * 10
1542 )
1543 )
quilesj7e13aeb2019-10-08 13:34:55 +02001544 nb_tries += 1
tiernoa5088192019-11-26 16:12:53 +00001545 if nb_tries >= 20:
garciadeblas5697b8b2021-03-24 09:17:02 +01001546 raise LcmException(
1547 "Reaching max tries injecting key. Error: {}".format(e)
1548 )
quilesj7e13aeb2019-10-08 13:34:55 +02001549 else:
quilesj7e13aeb2019-10-08 13:34:55 +02001550 break
1551
1552 return ip_address
1553
tierno5ee02052019-12-05 19:55:02 +00001554 async def _wait_dependent_n2vc(self, nsr_id, vca_deployed_list, vca_index):
1555 """
1556 Wait until dependent VCA deployments have been finished. NS wait for VNFs and VDUs. VNFs for VDUs
1557 """
1558 my_vca = vca_deployed_list[vca_index]
1559 if my_vca.get("vdu_id") or my_vca.get("kdu_name"):
quilesj3655ae02019-12-12 16:08:35 +00001560 # vdu or kdu: no dependencies
tierno5ee02052019-12-05 19:55:02 +00001561 return
1562 timeout = 300
1563 while timeout >= 0:
quilesj3655ae02019-12-12 16:08:35 +00001564 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1565 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
1566 configuration_status_list = db_nsr["configurationStatus"]
1567 for index, vca_deployed in enumerate(configuration_status_list):
tierno5ee02052019-12-05 19:55:02 +00001568 if index == vca_index:
quilesj3655ae02019-12-12 16:08:35 +00001569 # myself
tierno5ee02052019-12-05 19:55:02 +00001570 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01001571 if not my_vca.get("member-vnf-index") or (
1572 vca_deployed.get("member-vnf-index")
1573 == my_vca.get("member-vnf-index")
1574 ):
quilesj3655ae02019-12-12 16:08:35 +00001575 internal_status = configuration_status_list[index].get("status")
garciadeblas5697b8b2021-03-24 09:17:02 +01001576 if internal_status == "READY":
quilesj3655ae02019-12-12 16:08:35 +00001577 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01001578 elif internal_status == "BROKEN":
1579 raise LcmException(
1580 "Configuration aborted because dependent charm/s has failed"
1581 )
quilesj3655ae02019-12-12 16:08:35 +00001582 else:
1583 break
tierno5ee02052019-12-05 19:55:02 +00001584 else:
quilesj3655ae02019-12-12 16:08:35 +00001585 # no dependencies, return
tierno5ee02052019-12-05 19:55:02 +00001586 return
1587 await asyncio.sleep(10)
1588 timeout -= 1
tierno5ee02052019-12-05 19:55:02 +00001589
1590 raise LcmException("Configuration aborted because dependent charm/s timeout")
1591
David Garciac1fe90a2021-03-31 19:12:02 +02001592 def get_vca_id(self, db_vnfr: dict, db_nsr: dict):
David Garcia5506c182021-10-21 17:03:48 +02001593 vca_id = None
1594 if db_vnfr:
1595 vca_id = deep_get(db_vnfr, ("vca-id",))
1596 elif db_nsr:
1597 vim_account_id = deep_get(db_nsr, ("instantiate_params", "vimAccountId"))
1598 vca_id = VimAccountDB.get_vim_account_with_id(vim_account_id).get("vca")
1599 return vca_id
David Garciac1fe90a2021-03-31 19:12:02 +02001600
garciadeblas5697b8b2021-03-24 09:17:02 +01001601 async def instantiate_N2VC(
1602 self,
1603 logging_text,
1604 vca_index,
1605 nsi_id,
1606 db_nsr,
1607 db_vnfr,
1608 vdu_id,
1609 kdu_name,
1610 vdu_index,
1611 config_descriptor,
1612 deploy_params,
1613 base_folder,
1614 nslcmop_id,
1615 stage,
1616 vca_type,
1617 vca_name,
1618 ee_config_descriptor,
1619 ):
tiernod8323042019-08-09 11:32:23 +00001620 nsr_id = db_nsr["_id"]
1621 db_update_entry = "_admin.deployed.VCA.{}.".format(vca_index)
tiernoda6fb102019-11-23 00:36:52 +00001622 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
tiernod8323042019-08-09 11:32:23 +00001623 vca_deployed = db_nsr["_admin"]["deployed"]["VCA"][vca_index]
tiernob996d942020-07-03 14:52:28 +00001624 osm_config = {"osm": {"ns_id": db_nsr["_id"]}}
quilesj7e13aeb2019-10-08 13:34:55 +02001625 db_dict = {
garciadeblas5697b8b2021-03-24 09:17:02 +01001626 "collection": "nsrs",
1627 "filter": {"_id": nsr_id},
1628 "path": db_update_entry,
quilesj7e13aeb2019-10-08 13:34:55 +02001629 }
tiernod8323042019-08-09 11:32:23 +00001630 step = ""
1631 try:
quilesj3655ae02019-12-12 16:08:35 +00001632
garciadeblas5697b8b2021-03-24 09:17:02 +01001633 element_type = "NS"
quilesj3655ae02019-12-12 16:08:35 +00001634 element_under_configuration = nsr_id
1635
tiernod8323042019-08-09 11:32:23 +00001636 vnfr_id = None
1637 if db_vnfr:
1638 vnfr_id = db_vnfr["_id"]
tiernob996d942020-07-03 14:52:28 +00001639 osm_config["osm"]["vnf_id"] = vnfr_id
tiernod8323042019-08-09 11:32:23 +00001640
garciadeblas5697b8b2021-03-24 09:17:02 +01001641 namespace = "{nsi}.{ns}".format(nsi=nsi_id if nsi_id else "", ns=nsr_id)
quilesj3655ae02019-12-12 16:08:35 +00001642
aktas98488ed2021-07-29 17:42:49 +03001643 if vca_type == "native_charm":
1644 index_number = 0
1645 else:
1646 index_number = vdu_index or 0
1647
tiernod8323042019-08-09 11:32:23 +00001648 if vnfr_id:
garciadeblas5697b8b2021-03-24 09:17:02 +01001649 element_type = "VNF"
quilesj3655ae02019-12-12 16:08:35 +00001650 element_under_configuration = vnfr_id
aktas98488ed2021-07-29 17:42:49 +03001651 namespace += ".{}-{}".format(vnfr_id, index_number)
tiernod8323042019-08-09 11:32:23 +00001652 if vdu_id:
aktas98488ed2021-07-29 17:42:49 +03001653 namespace += ".{}-{}".format(vdu_id, index_number)
garciadeblas5697b8b2021-03-24 09:17:02 +01001654 element_type = "VDU"
aktas98488ed2021-07-29 17:42:49 +03001655 element_under_configuration = "{}-{}".format(vdu_id, index_number)
tiernob996d942020-07-03 14:52:28 +00001656 osm_config["osm"]["vdu_id"] = vdu_id
tierno51183952020-04-03 15:48:18 +00001657 elif kdu_name:
aktas98488ed2021-07-29 17:42:49 +03001658 namespace += ".{}".format(kdu_name)
garciadeblas5697b8b2021-03-24 09:17:02 +01001659 element_type = "KDU"
tierno51183952020-04-03 15:48:18 +00001660 element_under_configuration = kdu_name
tiernob996d942020-07-03 14:52:28 +00001661 osm_config["osm"]["kdu_name"] = kdu_name
tiernod8323042019-08-09 11:32:23 +00001662
1663 # Get artifact path
bravof14af4e72021-11-08 17:18:50 -03001664 if base_folder["pkg-dir"]:
1665 artifact_path = "{}/{}/{}/{}".format(
1666 base_folder["folder"],
1667 base_folder["pkg-dir"],
1668 "charms"
1669 if vca_type in ("native_charm", "lxc_proxy_charm", "k8s_proxy_charm")
1670 else "helm-charts",
1671 vca_name,
1672 )
1673 else:
1674 artifact_path = "{}/Scripts/{}/{}/".format(
1675 base_folder["folder"],
1676 "charms"
1677 if vca_type in ("native_charm", "lxc_proxy_charm", "k8s_proxy_charm")
1678 else "helm-charts",
1679 vca_name,
1680 )
bravof922c4172020-11-24 21:21:43 -03001681
1682 self.logger.debug("Artifact path > {}".format(artifact_path))
1683
tiernoa278b842020-07-08 15:33:55 +00001684 # get initial_config_primitive_list that applies to this element
garciadeblas5697b8b2021-03-24 09:17:02 +01001685 initial_config_primitive_list = config_descriptor.get(
1686 "initial-config-primitive"
1687 )
tiernoa278b842020-07-08 15:33:55 +00001688
garciadeblas5697b8b2021-03-24 09:17:02 +01001689 self.logger.debug(
1690 "Initial config primitive list > {}".format(
1691 initial_config_primitive_list
1692 )
1693 )
bravof922c4172020-11-24 21:21:43 -03001694
tiernoa278b842020-07-08 15:33:55 +00001695 # add config if not present for NS charm
1696 ee_descriptor_id = ee_config_descriptor.get("id")
bravof922c4172020-11-24 21:21:43 -03001697 self.logger.debug("EE Descriptor > {}".format(ee_descriptor_id))
garciadeblas5697b8b2021-03-24 09:17:02 +01001698 initial_config_primitive_list = get_ee_sorted_initial_config_primitive_list(
1699 initial_config_primitive_list, vca_deployed, ee_descriptor_id
1700 )
tiernod8323042019-08-09 11:32:23 +00001701
garciadeblas5697b8b2021-03-24 09:17:02 +01001702 self.logger.debug(
1703 "Initial config primitive list #2 > {}".format(
1704 initial_config_primitive_list
1705 )
1706 )
tierno588547c2020-07-01 15:30:20 +00001707 # n2vc_redesign STEP 3.1
tierno588547c2020-07-01 15:30:20 +00001708 # find old ee_id if exists
1709 ee_id = vca_deployed.get("ee_id")
tiernod8323042019-08-09 11:32:23 +00001710
David Garciac1fe90a2021-03-31 19:12:02 +02001711 vca_id = self.get_vca_id(db_vnfr, db_nsr)
tierno588547c2020-07-01 15:30:20 +00001712 # create or register execution environment in VCA
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001713 if vca_type in ("lxc_proxy_charm", "k8s_proxy_charm", "helm", "helm-v3"):
quilesj7e13aeb2019-10-08 13:34:55 +02001714
tierno588547c2020-07-01 15:30:20 +00001715 self._write_configuration_status(
1716 nsr_id=nsr_id,
1717 vca_index=vca_index,
garciadeblas5697b8b2021-03-24 09:17:02 +01001718 status="CREATING",
tierno588547c2020-07-01 15:30:20 +00001719 element_under_configuration=element_under_configuration,
garciadeblas5697b8b2021-03-24 09:17:02 +01001720 element_type=element_type,
tierno588547c2020-07-01 15:30:20 +00001721 )
tiernod8323042019-08-09 11:32:23 +00001722
tierno588547c2020-07-01 15:30:20 +00001723 step = "create execution environment"
garciadeblas5697b8b2021-03-24 09:17:02 +01001724 self.logger.debug(logging_text + step)
David Garciaaae391f2020-11-09 11:12:54 +01001725
1726 ee_id = None
1727 credentials = None
1728 if vca_type == "k8s_proxy_charm":
1729 ee_id = await self.vca_map[vca_type].install_k8s_proxy_charm(
garciadeblas5697b8b2021-03-24 09:17:02 +01001730 charm_name=artifact_path[artifact_path.rfind("/") + 1 :],
David Garciaaae391f2020-11-09 11:12:54 +01001731 namespace=namespace,
1732 artifact_path=artifact_path,
1733 db_dict=db_dict,
David Garciac1fe90a2021-03-31 19:12:02 +02001734 vca_id=vca_id,
David Garciaaae391f2020-11-09 11:12:54 +01001735 )
garciadeblas5697b8b2021-03-24 09:17:02 +01001736 elif vca_type == "helm" or vca_type == "helm-v3":
1737 ee_id, credentials = await self.vca_map[
1738 vca_type
1739 ].create_execution_environment(
bravof922c4172020-11-24 21:21:43 -03001740 namespace=namespace,
1741 reuse_ee_id=ee_id,
1742 db_dict=db_dict,
lloretgalleg18cb3cb2020-12-10 14:21:10 +00001743 config=osm_config,
1744 artifact_path=artifact_path,
garciadeblas5697b8b2021-03-24 09:17:02 +01001745 vca_type=vca_type,
bravof922c4172020-11-24 21:21:43 -03001746 )
garciadeblas5697b8b2021-03-24 09:17:02 +01001747 else:
1748 ee_id, credentials = await self.vca_map[
1749 vca_type
1750 ].create_execution_environment(
David Garciaaae391f2020-11-09 11:12:54 +01001751 namespace=namespace,
1752 reuse_ee_id=ee_id,
1753 db_dict=db_dict,
David Garciac1fe90a2021-03-31 19:12:02 +02001754 vca_id=vca_id,
David Garciaaae391f2020-11-09 11:12:54 +01001755 )
quilesj3655ae02019-12-12 16:08:35 +00001756
tierno588547c2020-07-01 15:30:20 +00001757 elif vca_type == "native_charm":
1758 step = "Waiting to VM being up and getting IP address"
1759 self.logger.debug(logging_text + step)
garciadeblas5697b8b2021-03-24 09:17:02 +01001760 rw_mgmt_ip = await self.wait_vm_up_insert_key_ro(
1761 logging_text,
1762 nsr_id,
1763 vnfr_id,
1764 vdu_id,
1765 vdu_index,
1766 user=None,
1767 pub_key=None,
1768 )
tierno588547c2020-07-01 15:30:20 +00001769 credentials = {"hostname": rw_mgmt_ip}
1770 # get username
garciadeblas5697b8b2021-03-24 09:17:02 +01001771 username = deep_get(
1772 config_descriptor, ("config-access", "ssh-access", "default-user")
1773 )
tierno588547c2020-07-01 15:30:20 +00001774 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1775 # merged. Meanwhile let's get username from initial-config-primitive
tiernoa278b842020-07-08 15:33:55 +00001776 if not username and initial_config_primitive_list:
1777 for config_primitive in initial_config_primitive_list:
tierno588547c2020-07-01 15:30:20 +00001778 for param in config_primitive.get("parameter", ()):
1779 if param["name"] == "ssh-username":
1780 username = param["value"]
1781 break
1782 if not username:
garciadeblas5697b8b2021-03-24 09:17:02 +01001783 raise LcmException(
1784 "Cannot determine the username neither with 'initial-config-primitive' nor with "
1785 "'config-access.ssh-access.default-user'"
1786 )
tierno588547c2020-07-01 15:30:20 +00001787 credentials["username"] = username
1788 # n2vc_redesign STEP 3.2
quilesj3655ae02019-12-12 16:08:35 +00001789
tierno588547c2020-07-01 15:30:20 +00001790 self._write_configuration_status(
1791 nsr_id=nsr_id,
1792 vca_index=vca_index,
garciadeblas5697b8b2021-03-24 09:17:02 +01001793 status="REGISTERING",
tierno588547c2020-07-01 15:30:20 +00001794 element_under_configuration=element_under_configuration,
garciadeblas5697b8b2021-03-24 09:17:02 +01001795 element_type=element_type,
tierno588547c2020-07-01 15:30:20 +00001796 )
quilesj3655ae02019-12-12 16:08:35 +00001797
tierno588547c2020-07-01 15:30:20 +00001798 step = "register execution environment {}".format(credentials)
1799 self.logger.debug(logging_text + step)
1800 ee_id = await self.vca_map[vca_type].register_execution_environment(
David Garciaaae391f2020-11-09 11:12:54 +01001801 credentials=credentials,
1802 namespace=namespace,
1803 db_dict=db_dict,
David Garciac1fe90a2021-03-31 19:12:02 +02001804 vca_id=vca_id,
David Garciaaae391f2020-11-09 11:12:54 +01001805 )
tierno3bedc9b2019-11-27 15:46:57 +00001806
tierno588547c2020-07-01 15:30:20 +00001807 # for compatibility with MON/POL modules, the need model and application name at database
1808 # TODO ask MON/POL if needed to not assuming anymore the format "model_name.application_name"
garciadeblas5697b8b2021-03-24 09:17:02 +01001809 ee_id_parts = ee_id.split(".")
tierno588547c2020-07-01 15:30:20 +00001810 db_nsr_update = {db_update_entry + "ee_id": ee_id}
1811 if len(ee_id_parts) >= 2:
1812 model_name = ee_id_parts[0]
1813 application_name = ee_id_parts[1]
1814 db_nsr_update[db_update_entry + "model"] = model_name
1815 db_nsr_update[db_update_entry + "application"] = application_name
tiernod8323042019-08-09 11:32:23 +00001816
1817 # n2vc_redesign STEP 3.3
tiernod8323042019-08-09 11:32:23 +00001818 step = "Install configuration Software"
quilesj3655ae02019-12-12 16:08:35 +00001819
tiernoc231a872020-01-21 08:49:05 +00001820 self._write_configuration_status(
quilesj3655ae02019-12-12 16:08:35 +00001821 nsr_id=nsr_id,
1822 vca_index=vca_index,
garciadeblas5697b8b2021-03-24 09:17:02 +01001823 status="INSTALLING SW",
quilesj3655ae02019-12-12 16:08:35 +00001824 element_under_configuration=element_under_configuration,
tierno51183952020-04-03 15:48:18 +00001825 element_type=element_type,
garciadeblas5697b8b2021-03-24 09:17:02 +01001826 other_update=db_nsr_update,
quilesj3655ae02019-12-12 16:08:35 +00001827 )
1828
tierno3bedc9b2019-11-27 15:46:57 +00001829 # TODO check if already done
quilesj7e13aeb2019-10-08 13:34:55 +02001830 self.logger.debug(logging_text + step)
David Garcia18a63322020-04-01 16:14:59 +02001831 config = None
tierno588547c2020-07-01 15:30:20 +00001832 if vca_type == "native_charm":
garciadeblas5697b8b2021-03-24 09:17:02 +01001833 config_primitive = next(
1834 (p for p in initial_config_primitive_list if p["name"] == "config"),
1835 None,
1836 )
tiernoa278b842020-07-08 15:33:55 +00001837 if config_primitive:
1838 config = self._map_primitive_params(
garciadeblas5697b8b2021-03-24 09:17:02 +01001839 config_primitive, {}, deploy_params
tiernoa278b842020-07-08 15:33:55 +00001840 )
tierno588547c2020-07-01 15:30:20 +00001841 num_units = 1
1842 if vca_type == "lxc_proxy_charm":
1843 if element_type == "NS":
1844 num_units = db_nsr.get("config-units") or 1
1845 elif element_type == "VNF":
1846 num_units = db_vnfr.get("config-units") or 1
1847 elif element_type == "VDU":
1848 for v in db_vnfr["vdur"]:
1849 if vdu_id == v["vdu-id-ref"]:
1850 num_units = v.get("config-units") or 1
1851 break
David Garciaaae391f2020-11-09 11:12:54 +01001852 if vca_type != "k8s_proxy_charm":
1853 await self.vca_map[vca_type].install_configuration_sw(
1854 ee_id=ee_id,
1855 artifact_path=artifact_path,
1856 db_dict=db_dict,
1857 config=config,
1858 num_units=num_units,
David Garciac1fe90a2021-03-31 19:12:02 +02001859 vca_id=vca_id,
aktas98488ed2021-07-29 17:42:49 +03001860 vca_type=vca_type,
David Garciaaae391f2020-11-09 11:12:54 +01001861 )
quilesj7e13aeb2019-10-08 13:34:55 +02001862
quilesj63f90042020-01-17 09:53:55 +00001863 # write in db flag of configuration_sw already installed
garciadeblas5697b8b2021-03-24 09:17:02 +01001864 self.update_db_2(
1865 "nsrs", nsr_id, {db_update_entry + "config_sw_installed": True}
1866 )
quilesj63f90042020-01-17 09:53:55 +00001867
1868 # add relations for this VCA (wait for other peers related with this VCA)
garciadeblas5697b8b2021-03-24 09:17:02 +01001869 await self._add_vca_relations(
1870 logging_text=logging_text,
1871 nsr_id=nsr_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01001872 vca_type=vca_type,
David Garciab4ebcd02021-10-28 02:00:43 +02001873 vca_index=vca_index,
garciadeblas5697b8b2021-03-24 09:17:02 +01001874 )
quilesj63f90042020-01-17 09:53:55 +00001875
quilesj7e13aeb2019-10-08 13:34:55 +02001876 # if SSH access is required, then get execution environment SSH public
David Garciaa27e20a2020-07-10 13:12:44 +02001877 # if native charm we have waited already to VM be UP
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001878 if vca_type in ("k8s_proxy_charm", "lxc_proxy_charm", "helm", "helm-v3"):
tierno3bedc9b2019-11-27 15:46:57 +00001879 pub_key = None
1880 user = None
tierno588547c2020-07-01 15:30:20 +00001881 # self.logger.debug("get ssh key block")
garciadeblas5697b8b2021-03-24 09:17:02 +01001882 if deep_get(
1883 config_descriptor, ("config-access", "ssh-access", "required")
1884 ):
tierno588547c2020-07-01 15:30:20 +00001885 # self.logger.debug("ssh key needed")
tierno3bedc9b2019-11-27 15:46:57 +00001886 # Needed to inject a ssh key
garciadeblas5697b8b2021-03-24 09:17:02 +01001887 user = deep_get(
1888 config_descriptor,
1889 ("config-access", "ssh-access", "default-user"),
1890 )
tierno3bedc9b2019-11-27 15:46:57 +00001891 step = "Install configuration Software, getting public ssh key"
David Garciac1fe90a2021-03-31 19:12:02 +02001892 pub_key = await self.vca_map[vca_type].get_ee_ssh_public__key(
garciadeblas5697b8b2021-03-24 09:17:02 +01001893 ee_id=ee_id, db_dict=db_dict, vca_id=vca_id
David Garciac1fe90a2021-03-31 19:12:02 +02001894 )
quilesj7e13aeb2019-10-08 13:34:55 +02001895
garciadeblas5697b8b2021-03-24 09:17:02 +01001896 step = "Insert public key into VM user={} ssh_key={}".format(
1897 user, pub_key
1898 )
tierno3bedc9b2019-11-27 15:46:57 +00001899 else:
tierno588547c2020-07-01 15:30:20 +00001900 # self.logger.debug("no need to get ssh key")
tierno3bedc9b2019-11-27 15:46:57 +00001901 step = "Waiting to VM being up and getting IP address"
1902 self.logger.debug(logging_text + step)
quilesj7e13aeb2019-10-08 13:34:55 +02001903
tierno3bedc9b2019-11-27 15:46:57 +00001904 # n2vc_redesign STEP 5.1
1905 # wait for RO (ip-address) Insert pub_key into VM
tierno5ee02052019-12-05 19:55:02 +00001906 if vnfr_id:
tierno7ecbc342020-09-21 14:05:39 +00001907 if kdu_name:
garciadeblas5697b8b2021-03-24 09:17:02 +01001908 rw_mgmt_ip = await self.wait_kdu_up(
1909 logging_text, nsr_id, vnfr_id, kdu_name
1910 )
tierno7ecbc342020-09-21 14:05:39 +00001911 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001912 rw_mgmt_ip = await self.wait_vm_up_insert_key_ro(
1913 logging_text,
1914 nsr_id,
1915 vnfr_id,
1916 vdu_id,
1917 vdu_index,
1918 user=user,
1919 pub_key=pub_key,
1920 )
tierno5ee02052019-12-05 19:55:02 +00001921 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001922 rw_mgmt_ip = None # This is for a NS configuration
tierno3bedc9b2019-11-27 15:46:57 +00001923
garciadeblas5697b8b2021-03-24 09:17:02 +01001924 self.logger.debug(logging_text + " VM_ip_address={}".format(rw_mgmt_ip))
quilesj7e13aeb2019-10-08 13:34:55 +02001925
tiernoa5088192019-11-26 16:12:53 +00001926 # store rw_mgmt_ip in deploy params for later replacement
quilesj7e13aeb2019-10-08 13:34:55 +02001927 deploy_params["rw_mgmt_ip"] = rw_mgmt_ip
tiernod8323042019-08-09 11:32:23 +00001928
1929 # n2vc_redesign STEP 6 Execute initial config primitive
garciadeblas5697b8b2021-03-24 09:17:02 +01001930 step = "execute initial config primitive"
quilesj3655ae02019-12-12 16:08:35 +00001931
1932 # wait for dependent primitives execution (NS -> VNF -> VDU)
tierno5ee02052019-12-05 19:55:02 +00001933 if initial_config_primitive_list:
1934 await self._wait_dependent_n2vc(nsr_id, vca_deployed_list, vca_index)
quilesj3655ae02019-12-12 16:08:35 +00001935
1936 # stage, in function of element type: vdu, kdu, vnf or ns
1937 my_vca = vca_deployed_list[vca_index]
1938 if my_vca.get("vdu_id") or my_vca.get("kdu_name"):
1939 # VDU or KDU
garciadeblas5697b8b2021-03-24 09:17:02 +01001940 stage[0] = "Stage 3/5: running Day-1 primitives for VDU."
quilesj3655ae02019-12-12 16:08:35 +00001941 elif my_vca.get("member-vnf-index"):
1942 # VNF
garciadeblas5697b8b2021-03-24 09:17:02 +01001943 stage[0] = "Stage 4/5: running Day-1 primitives for VNF."
quilesj3655ae02019-12-12 16:08:35 +00001944 else:
1945 # NS
garciadeblas5697b8b2021-03-24 09:17:02 +01001946 stage[0] = "Stage 5/5: running Day-1 primitives for NS."
quilesj3655ae02019-12-12 16:08:35 +00001947
tiernoc231a872020-01-21 08:49:05 +00001948 self._write_configuration_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01001949 nsr_id=nsr_id, vca_index=vca_index, status="EXECUTING PRIMITIVE"
quilesj3655ae02019-12-12 16:08:35 +00001950 )
1951
garciadeblas5697b8b2021-03-24 09:17:02 +01001952 self._write_op_status(op_id=nslcmop_id, stage=stage)
quilesj3655ae02019-12-12 16:08:35 +00001953
tiernoe876f672020-02-13 14:34:48 +00001954 check_if_terminated_needed = True
tiernod8323042019-08-09 11:32:23 +00001955 for initial_config_primitive in initial_config_primitive_list:
tiernoda6fb102019-11-23 00:36:52 +00001956 # adding information on the vca_deployed if it is a NS execution environment
1957 if not vca_deployed["member-vnf-index"]:
garciadeblas5697b8b2021-03-24 09:17:02 +01001958 deploy_params["ns_config_info"] = json.dumps(
1959 self._get_ns_config_info(nsr_id)
1960 )
tiernod8323042019-08-09 11:32:23 +00001961 # TODO check if already done
garciadeblas5697b8b2021-03-24 09:17:02 +01001962 primitive_params_ = self._map_primitive_params(
1963 initial_config_primitive, {}, deploy_params
1964 )
tierno3bedc9b2019-11-27 15:46:57 +00001965
garciadeblas5697b8b2021-03-24 09:17:02 +01001966 step = "execute primitive '{}' params '{}'".format(
1967 initial_config_primitive["name"], primitive_params_
1968 )
tiernod8323042019-08-09 11:32:23 +00001969 self.logger.debug(logging_text + step)
tierno588547c2020-07-01 15:30:20 +00001970 await self.vca_map[vca_type].exec_primitive(
quilesj7e13aeb2019-10-08 13:34:55 +02001971 ee_id=ee_id,
1972 primitive_name=initial_config_primitive["name"],
1973 params_dict=primitive_params_,
David Garciac1fe90a2021-03-31 19:12:02 +02001974 db_dict=db_dict,
1975 vca_id=vca_id,
aktas98488ed2021-07-29 17:42:49 +03001976 vca_type=vca_type,
quilesj7e13aeb2019-10-08 13:34:55 +02001977 )
tiernoe876f672020-02-13 14:34:48 +00001978 # Once some primitive has been exec, check and write at db if it needs to exec terminated primitives
1979 if check_if_terminated_needed:
garciadeblas5697b8b2021-03-24 09:17:02 +01001980 if config_descriptor.get("terminate-config-primitive"):
1981 self.update_db_2(
1982 "nsrs", nsr_id, {db_update_entry + "needed_terminate": True}
1983 )
tiernoe876f672020-02-13 14:34:48 +00001984 check_if_terminated_needed = False
quilesj3655ae02019-12-12 16:08:35 +00001985
tiernod8323042019-08-09 11:32:23 +00001986 # TODO register in database that primitive is done
quilesj7e13aeb2019-10-08 13:34:55 +02001987
tiernob996d942020-07-03 14:52:28 +00001988 # STEP 7 Configure metrics
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001989 if vca_type == "helm" or vca_type == "helm-v3":
tiernob996d942020-07-03 14:52:28 +00001990 prometheus_jobs = await self.add_prometheus_metrics(
1991 ee_id=ee_id,
1992 artifact_path=artifact_path,
1993 ee_config_descriptor=ee_config_descriptor,
1994 vnfr_id=vnfr_id,
1995 nsr_id=nsr_id,
1996 target_ip=rw_mgmt_ip,
1997 )
1998 if prometheus_jobs:
garciadeblas5697b8b2021-03-24 09:17:02 +01001999 self.update_db_2(
2000 "nsrs",
2001 nsr_id,
2002 {db_update_entry + "prometheus_jobs": prometheus_jobs},
2003 )
tiernob996d942020-07-03 14:52:28 +00002004
quilesj7e13aeb2019-10-08 13:34:55 +02002005 step = "instantiated at VCA"
2006 self.logger.debug(logging_text + step)
2007
tiernoc231a872020-01-21 08:49:05 +00002008 self._write_configuration_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01002009 nsr_id=nsr_id, vca_index=vca_index, status="READY"
quilesj3655ae02019-12-12 16:08:35 +00002010 )
2011
tiernod8323042019-08-09 11:32:23 +00002012 except Exception as e: # TODO not use Exception but N2VC exception
quilesj3655ae02019-12-12 16:08:35 +00002013 # self.update_db_2("nsrs", nsr_id, {db_update_entry + "instantiation": "FAILED"})
garciadeblas5697b8b2021-03-24 09:17:02 +01002014 if not isinstance(
2015 e, (DbException, N2VCException, LcmException, asyncio.CancelledError)
2016 ):
2017 self.logger.error(
2018 "Exception while {} : {}".format(step, e), exc_info=True
2019 )
tiernoc231a872020-01-21 08:49:05 +00002020 self._write_configuration_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01002021 nsr_id=nsr_id, vca_index=vca_index, status="BROKEN"
quilesj3655ae02019-12-12 16:08:35 +00002022 )
tiernoe876f672020-02-13 14:34:48 +00002023 raise LcmException("{} {}".format(step, e)) from e
tiernod8323042019-08-09 11:32:23 +00002024
garciadeblas5697b8b2021-03-24 09:17:02 +01002025 def _write_ns_status(
2026 self,
2027 nsr_id: str,
2028 ns_state: str,
2029 current_operation: str,
2030 current_operation_id: str,
2031 error_description: str = None,
2032 error_detail: str = None,
2033 other_update: dict = None,
2034 ):
tiernoe876f672020-02-13 14:34:48 +00002035 """
2036 Update db_nsr fields.
2037 :param nsr_id:
2038 :param ns_state:
2039 :param current_operation:
2040 :param current_operation_id:
2041 :param error_description:
tiernoa2143262020-03-27 16:20:40 +00002042 :param error_detail:
tiernoe876f672020-02-13 14:34:48 +00002043 :param other_update: Other required changes at database if provided, will be cleared
2044 :return:
2045 """
quilesj4cda56b2019-12-05 10:02:20 +00002046 try:
tiernoe876f672020-02-13 14:34:48 +00002047 db_dict = other_update or {}
garciadeblas5697b8b2021-03-24 09:17:02 +01002048 db_dict[
2049 "_admin.nslcmop"
2050 ] = current_operation_id # for backward compatibility
tiernoe876f672020-02-13 14:34:48 +00002051 db_dict["_admin.current-operation"] = current_operation_id
garciadeblas5697b8b2021-03-24 09:17:02 +01002052 db_dict["_admin.operation-type"] = (
2053 current_operation if current_operation != "IDLE" else None
2054 )
quilesj4cda56b2019-12-05 10:02:20 +00002055 db_dict["currentOperation"] = current_operation
2056 db_dict["currentOperationID"] = current_operation_id
2057 db_dict["errorDescription"] = error_description
tiernoa2143262020-03-27 16:20:40 +00002058 db_dict["errorDetail"] = error_detail
tiernoe876f672020-02-13 14:34:48 +00002059
2060 if ns_state:
2061 db_dict["nsState"] = ns_state
quilesj4cda56b2019-12-05 10:02:20 +00002062 self.update_db_2("nsrs", nsr_id, db_dict)
tiernoe876f672020-02-13 14:34:48 +00002063 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002064 self.logger.warn("Error writing NS status, ns={}: {}".format(nsr_id, e))
quilesj3655ae02019-12-12 16:08:35 +00002065
garciadeblas5697b8b2021-03-24 09:17:02 +01002066 def _write_op_status(
2067 self,
2068 op_id: str,
2069 stage: list = None,
2070 error_message: str = None,
2071 queuePosition: int = 0,
2072 operation_state: str = None,
2073 other_update: dict = None,
2074 ):
quilesj3655ae02019-12-12 16:08:35 +00002075 try:
tiernoe876f672020-02-13 14:34:48 +00002076 db_dict = other_update or {}
garciadeblas5697b8b2021-03-24 09:17:02 +01002077 db_dict["queuePosition"] = queuePosition
tiernoe876f672020-02-13 14:34:48 +00002078 if isinstance(stage, list):
garciadeblas5697b8b2021-03-24 09:17:02 +01002079 db_dict["stage"] = stage[0]
2080 db_dict["detailed-status"] = " ".join(stage)
tiernoe876f672020-02-13 14:34:48 +00002081 elif stage is not None:
garciadeblas5697b8b2021-03-24 09:17:02 +01002082 db_dict["stage"] = str(stage)
tiernoe876f672020-02-13 14:34:48 +00002083
2084 if error_message is not None:
garciadeblas5697b8b2021-03-24 09:17:02 +01002085 db_dict["errorMessage"] = error_message
tiernoe876f672020-02-13 14:34:48 +00002086 if operation_state is not None:
garciadeblas5697b8b2021-03-24 09:17:02 +01002087 db_dict["operationState"] = operation_state
tiernoe876f672020-02-13 14:34:48 +00002088 db_dict["statusEnteredTime"] = time()
quilesj3655ae02019-12-12 16:08:35 +00002089 self.update_db_2("nslcmops", op_id, db_dict)
tiernoe876f672020-02-13 14:34:48 +00002090 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002091 self.logger.warn(
2092 "Error writing OPERATION status for op_id: {} -> {}".format(op_id, e)
2093 )
quilesj3655ae02019-12-12 16:08:35 +00002094
tierno51183952020-04-03 15:48:18 +00002095 def _write_all_config_status(self, db_nsr: dict, status: str):
quilesj3655ae02019-12-12 16:08:35 +00002096 try:
tierno51183952020-04-03 15:48:18 +00002097 nsr_id = db_nsr["_id"]
quilesj3655ae02019-12-12 16:08:35 +00002098 # configurationStatus
garciadeblas5697b8b2021-03-24 09:17:02 +01002099 config_status = db_nsr.get("configurationStatus")
quilesj3655ae02019-12-12 16:08:35 +00002100 if config_status:
garciadeblas5697b8b2021-03-24 09:17:02 +01002101 db_nsr_update = {
2102 "configurationStatus.{}.status".format(index): status
2103 for index, v in enumerate(config_status)
2104 if v
2105 }
quilesj3655ae02019-12-12 16:08:35 +00002106 # update status
tierno51183952020-04-03 15:48:18 +00002107 self.update_db_2("nsrs", nsr_id, db_nsr_update)
quilesj3655ae02019-12-12 16:08:35 +00002108
tiernoe876f672020-02-13 14:34:48 +00002109 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002110 self.logger.warn(
2111 "Error writing all configuration status, ns={}: {}".format(nsr_id, e)
2112 )
quilesj3655ae02019-12-12 16:08:35 +00002113
garciadeblas5697b8b2021-03-24 09:17:02 +01002114 def _write_configuration_status(
2115 self,
2116 nsr_id: str,
2117 vca_index: int,
2118 status: str = None,
2119 element_under_configuration: str = None,
2120 element_type: str = None,
2121 other_update: dict = None,
2122 ):
quilesj3655ae02019-12-12 16:08:35 +00002123
2124 # self.logger.debug('_write_configuration_status(): vca_index={}, status={}'
2125 # .format(vca_index, status))
2126
2127 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01002128 db_path = "configurationStatus.{}.".format(vca_index)
tierno51183952020-04-03 15:48:18 +00002129 db_dict = other_update or {}
quilesj63f90042020-01-17 09:53:55 +00002130 if status:
garciadeblas5697b8b2021-03-24 09:17:02 +01002131 db_dict[db_path + "status"] = status
quilesj3655ae02019-12-12 16:08:35 +00002132 if element_under_configuration:
garciadeblas5697b8b2021-03-24 09:17:02 +01002133 db_dict[
2134 db_path + "elementUnderConfiguration"
2135 ] = element_under_configuration
quilesj3655ae02019-12-12 16:08:35 +00002136 if element_type:
garciadeblas5697b8b2021-03-24 09:17:02 +01002137 db_dict[db_path + "elementType"] = element_type
quilesj3655ae02019-12-12 16:08:35 +00002138 self.update_db_2("nsrs", nsr_id, db_dict)
tiernoe876f672020-02-13 14:34:48 +00002139 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002140 self.logger.warn(
2141 "Error writing configuration status={}, ns={}, vca_index={}: {}".format(
2142 status, nsr_id, vca_index, e
2143 )
2144 )
quilesj4cda56b2019-12-05 10:02:20 +00002145
tierno38089af2020-04-16 07:56:58 +00002146 async def _do_placement(self, logging_text, db_nslcmop, db_vnfrs):
2147 """
2148 Check and computes the placement, (vim account where to deploy). If it is decided by an external tool, it
2149 sends the request via kafka and wait until the result is wrote at database (nslcmops _admin.plca).
2150 Database is used because the result can be obtained from a different LCM worker in case of HA.
2151 :param logging_text: contains the prefix for logging, with the ns and nslcmop identifiers
2152 :param db_nslcmop: database content of nslcmop
2153 :param db_vnfrs: database content of vnfrs, indexed by member-vnf-index.
tierno8790a3d2020-04-23 22:49:52 +00002154 :return: True if some modification is done. Modifies database vnfrs and parameter db_vnfr with the
2155 computed 'vim-account-id'
tierno38089af2020-04-16 07:56:58 +00002156 """
tierno8790a3d2020-04-23 22:49:52 +00002157 modified = False
garciadeblas5697b8b2021-03-24 09:17:02 +01002158 nslcmop_id = db_nslcmop["_id"]
2159 placement_engine = deep_get(db_nslcmop, ("operationParams", "placement-engine"))
magnussonle9198bb2020-01-21 13:00:51 +01002160 if placement_engine == "PLA":
garciadeblas5697b8b2021-03-24 09:17:02 +01002161 self.logger.debug(
2162 logging_text + "Invoke and wait for placement optimization"
2163 )
2164 await self.msg.aiowrite(
2165 "pla", "get_placement", {"nslcmopId": nslcmop_id}, loop=self.loop
2166 )
magnussonle9198bb2020-01-21 13:00:51 +01002167 db_poll_interval = 5
tierno38089af2020-04-16 07:56:58 +00002168 wait = db_poll_interval * 10
magnussonle9198bb2020-01-21 13:00:51 +01002169 pla_result = None
2170 while not pla_result and wait >= 0:
2171 await asyncio.sleep(db_poll_interval)
2172 wait -= db_poll_interval
tierno38089af2020-04-16 07:56:58 +00002173 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
garciadeblas5697b8b2021-03-24 09:17:02 +01002174 pla_result = deep_get(db_nslcmop, ("_admin", "pla"))
magnussonle9198bb2020-01-21 13:00:51 +01002175
2176 if not pla_result:
garciadeblas5697b8b2021-03-24 09:17:02 +01002177 raise LcmException(
2178 "Placement timeout for nslcmopId={}".format(nslcmop_id)
2179 )
magnussonle9198bb2020-01-21 13:00:51 +01002180
garciadeblas5697b8b2021-03-24 09:17:02 +01002181 for pla_vnf in pla_result["vnf"]:
2182 vnfr = db_vnfrs.get(pla_vnf["member-vnf-index"])
2183 if not pla_vnf.get("vimAccountId") or not vnfr:
magnussonle9198bb2020-01-21 13:00:51 +01002184 continue
tierno8790a3d2020-04-23 22:49:52 +00002185 modified = True
garciadeblas5697b8b2021-03-24 09:17:02 +01002186 self.db.set_one(
2187 "vnfrs",
2188 {"_id": vnfr["_id"]},
2189 {"vim-account-id": pla_vnf["vimAccountId"]},
2190 )
tierno38089af2020-04-16 07:56:58 +00002191 # Modifies db_vnfrs
garciadeblas5697b8b2021-03-24 09:17:02 +01002192 vnfr["vim-account-id"] = pla_vnf["vimAccountId"]
tierno8790a3d2020-04-23 22:49:52 +00002193 return modified
magnussonle9198bb2020-01-21 13:00:51 +01002194
2195 def update_nsrs_with_pla_result(self, params):
2196 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01002197 nslcmop_id = deep_get(params, ("placement", "nslcmopId"))
2198 self.update_db_2(
2199 "nslcmops", nslcmop_id, {"_admin.pla": params.get("placement")}
2200 )
magnussonle9198bb2020-01-21 13:00:51 +01002201 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002202 self.logger.warn("Update failed for nslcmop_id={}:{}".format(nslcmop_id, e))
magnussonle9198bb2020-01-21 13:00:51 +01002203
tierno59d22d22018-09-25 18:10:19 +02002204 async def instantiate(self, nsr_id, nslcmop_id):
quilesj7e13aeb2019-10-08 13:34:55 +02002205 """
2206
2207 :param nsr_id: ns instance to deploy
2208 :param nslcmop_id: operation to run
2209 :return:
2210 """
kuused124bfe2019-06-18 12:09:24 +02002211
2212 # Try to lock HA task here
garciadeblas5697b8b2021-03-24 09:17:02 +01002213 task_is_locked_by_me = self.lcm_tasks.lock_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02002214 if not task_is_locked_by_me:
garciadeblas5697b8b2021-03-24 09:17:02 +01002215 self.logger.debug(
2216 "instantiate() task is not locked by me, ns={}".format(nsr_id)
2217 )
kuused124bfe2019-06-18 12:09:24 +02002218 return
2219
tierno59d22d22018-09-25 18:10:19 +02002220 logging_text = "Task ns={} instantiate={} ".format(nsr_id, nslcmop_id)
2221 self.logger.debug(logging_text + "Enter")
quilesj7e13aeb2019-10-08 13:34:55 +02002222
tierno59d22d22018-09-25 18:10:19 +02002223 # get all needed from database
quilesj7e13aeb2019-10-08 13:34:55 +02002224
2225 # database nsrs record
tierno59d22d22018-09-25 18:10:19 +02002226 db_nsr = None
quilesj7e13aeb2019-10-08 13:34:55 +02002227
2228 # database nslcmops record
tierno59d22d22018-09-25 18:10:19 +02002229 db_nslcmop = None
quilesj7e13aeb2019-10-08 13:34:55 +02002230
2231 # update operation on nsrs
tiernoe876f672020-02-13 14:34:48 +00002232 db_nsr_update = {}
quilesj7e13aeb2019-10-08 13:34:55 +02002233 # update operation on nslcmops
tierno59d22d22018-09-25 18:10:19 +02002234 db_nslcmop_update = {}
quilesj7e13aeb2019-10-08 13:34:55 +02002235
tierno59d22d22018-09-25 18:10:19 +02002236 nslcmop_operation_state = None
garciadeblas5697b8b2021-03-24 09:17:02 +01002237 db_vnfrs = {} # vnf's info indexed by member-index
quilesj7e13aeb2019-10-08 13:34:55 +02002238 # n2vc_info = {}
tiernoe876f672020-02-13 14:34:48 +00002239 tasks_dict_info = {} # from task to info text
tierno59d22d22018-09-25 18:10:19 +02002240 exc = None
tiernoe876f672020-02-13 14:34:48 +00002241 error_list = []
garciadeblas5697b8b2021-03-24 09:17:02 +01002242 stage = [
2243 "Stage 1/5: preparation of the environment.",
2244 "Waiting for previous operations to terminate.",
2245 "",
2246 ]
tiernoe876f672020-02-13 14:34:48 +00002247 # ^ stage, step, VIM progress
tierno59d22d22018-09-25 18:10:19 +02002248 try:
kuused124bfe2019-06-18 12:09:24 +02002249 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +01002250 await self.lcm_tasks.waitfor_related_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02002251
quilesj7e13aeb2019-10-08 13:34:55 +02002252 # STEP 0: Reading database (nslcmops, nsrs, nsds, vnfrs, vnfds)
tiernob5203912020-08-11 11:20:13 +00002253 stage[1] = "Reading from database."
quilesj4cda56b2019-12-05 10:02:20 +00002254 # nsState="BUILDING", currentOperation="INSTANTIATING", currentOperationID=nslcmop_id
tiernoe876f672020-02-13 14:34:48 +00002255 db_nsr_update["detailed-status"] = "creating"
2256 db_nsr_update["operational-status"] = "init"
quilesj4cda56b2019-12-05 10:02:20 +00002257 self._write_ns_status(
2258 nsr_id=nsr_id,
2259 ns_state="BUILDING",
2260 current_operation="INSTANTIATING",
tiernoe876f672020-02-13 14:34:48 +00002261 current_operation_id=nslcmop_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01002262 other_update=db_nsr_update,
tiernoe876f672020-02-13 14:34:48 +00002263 )
garciadeblas5697b8b2021-03-24 09:17:02 +01002264 self._write_op_status(op_id=nslcmop_id, stage=stage, queuePosition=0)
quilesj4cda56b2019-12-05 10:02:20 +00002265
quilesj7e13aeb2019-10-08 13:34:55 +02002266 # read from db: operation
tiernob5203912020-08-11 11:20:13 +00002267 stage[1] = "Getting nslcmop={} from db.".format(nslcmop_id)
tierno59d22d22018-09-25 18:10:19 +02002268 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
tierno744303e2020-01-13 16:46:31 +00002269 ns_params = db_nslcmop.get("operationParams")
2270 if ns_params and ns_params.get("timeout_ns_deploy"):
2271 timeout_ns_deploy = ns_params["timeout_ns_deploy"]
2272 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01002273 timeout_ns_deploy = self.timeout.get(
2274 "ns_deploy", self.timeout_ns_deploy
2275 )
quilesj7e13aeb2019-10-08 13:34:55 +02002276
2277 # read from db: ns
tiernob5203912020-08-11 11:20:13 +00002278 stage[1] = "Getting nsr={} from db.".format(nsr_id)
tierno59d22d22018-09-25 18:10:19 +02002279 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
tiernob5203912020-08-11 11:20:13 +00002280 stage[1] = "Getting nsd={} from db.".format(db_nsr["nsd-id"])
tiernod732fb82020-05-21 13:18:23 +00002281 nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
bravof021e70d2021-03-11 12:03:30 -03002282 self.fs.sync(db_nsr["nsd-id"])
tiernod732fb82020-05-21 13:18:23 +00002283 db_nsr["nsd"] = nsd
tiernod8323042019-08-09 11:32:23 +00002284 # nsr_name = db_nsr["name"] # TODO short-name??
tierno47e86b52018-10-10 14:05:55 +02002285
quilesj7e13aeb2019-10-08 13:34:55 +02002286 # read from db: vnf's of this ns
tiernob5203912020-08-11 11:20:13 +00002287 stage[1] = "Getting vnfrs from db."
tiernoe876f672020-02-13 14:34:48 +00002288 self.logger.debug(logging_text + stage[1])
tierno27246d82018-09-27 15:59:09 +02002289 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
tierno27246d82018-09-27 15:59:09 +02002290
quilesj7e13aeb2019-10-08 13:34:55 +02002291 # read from db: vnfd's for every vnf
garciadeblas5697b8b2021-03-24 09:17:02 +01002292 db_vnfds = [] # every vnfd data
quilesj7e13aeb2019-10-08 13:34:55 +02002293
2294 # for each vnf in ns, read vnfd
tierno27246d82018-09-27 15:59:09 +02002295 for vnfr in db_vnfrs_list:
bravof922c4172020-11-24 21:21:43 -03002296 db_vnfrs[vnfr["member-vnf-index-ref"]] = vnfr
2297 vnfd_id = vnfr["vnfd-id"]
2298 vnfd_ref = vnfr["vnfd-ref"]
bravof021e70d2021-03-11 12:03:30 -03002299 self.fs.sync(vnfd_id)
lloretgalleg6d488782020-07-22 10:13:46 +00002300
quilesj7e13aeb2019-10-08 13:34:55 +02002301 # if we haven't this vnfd, read it from db
tierno27246d82018-09-27 15:59:09 +02002302 if vnfd_id not in db_vnfds:
quilesj63f90042020-01-17 09:53:55 +00002303 # read from db
garciadeblas5697b8b2021-03-24 09:17:02 +01002304 stage[1] = "Getting vnfd={} id='{}' from db.".format(
2305 vnfd_id, vnfd_ref
2306 )
tiernoe876f672020-02-13 14:34:48 +00002307 self.logger.debug(logging_text + stage[1])
tierno27246d82018-09-27 15:59:09 +02002308 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
tierno27246d82018-09-27 15:59:09 +02002309
quilesj7e13aeb2019-10-08 13:34:55 +02002310 # store vnfd
David Garciad41dbd62020-12-10 12:52:52 +01002311 db_vnfds.append(vnfd)
quilesj7e13aeb2019-10-08 13:34:55 +02002312
2313 # Get or generates the _admin.deployed.VCA list
tiernoe4f7e6c2018-11-27 14:55:30 +00002314 vca_deployed_list = None
2315 if db_nsr["_admin"].get("deployed"):
2316 vca_deployed_list = db_nsr["_admin"]["deployed"].get("VCA")
2317 if vca_deployed_list is None:
2318 vca_deployed_list = []
quilesj3655ae02019-12-12 16:08:35 +00002319 configuration_status_list = []
tiernoe4f7e6c2018-11-27 14:55:30 +00002320 db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
quilesj3655ae02019-12-12 16:08:35 +00002321 db_nsr_update["configurationStatus"] = configuration_status_list
quilesj7e13aeb2019-10-08 13:34:55 +02002322 # add _admin.deployed.VCA to db_nsr dictionary, value=vca_deployed_list
tierno98ad6ea2019-05-30 17:16:28 +00002323 populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
tiernoe4f7e6c2018-11-27 14:55:30 +00002324 elif isinstance(vca_deployed_list, dict):
2325 # maintain backward compatibility. Change a dict to list at database
2326 vca_deployed_list = list(vca_deployed_list.values())
2327 db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
tierno98ad6ea2019-05-30 17:16:28 +00002328 populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
tiernoe4f7e6c2018-11-27 14:55:30 +00002329
garciadeblas5697b8b2021-03-24 09:17:02 +01002330 if not isinstance(
2331 deep_get(db_nsr, ("_admin", "deployed", "RO", "vnfd")), list
2332 ):
tiernoa009e552019-01-30 16:45:44 +00002333 populate_dict(db_nsr, ("_admin", "deployed", "RO", "vnfd"), [])
2334 db_nsr_update["_admin.deployed.RO.vnfd"] = []
tierno59d22d22018-09-25 18:10:19 +02002335
tiernobaa51102018-12-14 13:16:18 +00002336 # set state to INSTANTIATED. When instantiated NBI will not delete directly
2337 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
2338 self.update_db_2("nsrs", nsr_id, db_nsr_update)
garciadeblas5697b8b2021-03-24 09:17:02 +01002339 self.db.set_list(
2340 "vnfrs", {"nsr-id-ref": nsr_id}, {"_admin.nsState": "INSTANTIATED"}
2341 )
quilesj3655ae02019-12-12 16:08:35 +00002342
2343 # n2vc_redesign STEP 2 Deploy Network Scenario
garciadeblas5697b8b2021-03-24 09:17:02 +01002344 stage[0] = "Stage 2/5: deployment of KDUs, VMs and execution environments."
2345 self._write_op_status(op_id=nslcmop_id, stage=stage)
quilesj3655ae02019-12-12 16:08:35 +00002346
tiernob5203912020-08-11 11:20:13 +00002347 stage[1] = "Deploying KDUs."
tiernoe876f672020-02-13 14:34:48 +00002348 # self.logger.debug(logging_text + "Before deploy_kdus")
calvinosanch9f9c6f22019-11-04 13:37:39 +01002349 # Call to deploy_kdus in case exists the "vdu:kdu" param
tiernoe876f672020-02-13 14:34:48 +00002350 await self.deploy_kdus(
2351 logging_text=logging_text,
2352 nsr_id=nsr_id,
2353 nslcmop_id=nslcmop_id,
2354 db_vnfrs=db_vnfrs,
2355 db_vnfds=db_vnfds,
2356 task_instantiation_info=tasks_dict_info,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002357 )
tiernoe876f672020-02-13 14:34:48 +00002358
2359 stage[1] = "Getting VCA public key."
tiernod8323042019-08-09 11:32:23 +00002360 # n2vc_redesign STEP 1 Get VCA public ssh-key
2361 # feature 1429. Add n2vc public key to needed VMs
tierno3bedc9b2019-11-27 15:46:57 +00002362 n2vc_key = self.n2vc.get_public_key()
tiernoa5088192019-11-26 16:12:53 +00002363 n2vc_key_list = [n2vc_key]
2364 if self.vca_config.get("public_key"):
2365 n2vc_key_list.append(self.vca_config["public_key"])
tierno98ad6ea2019-05-30 17:16:28 +00002366
tiernoe876f672020-02-13 14:34:48 +00002367 stage[1] = "Deploying NS at VIM."
tiernod8323042019-08-09 11:32:23 +00002368 task_ro = asyncio.ensure_future(
quilesj7e13aeb2019-10-08 13:34:55 +02002369 self.instantiate_RO(
2370 logging_text=logging_text,
2371 nsr_id=nsr_id,
2372 nsd=nsd,
2373 db_nsr=db_nsr,
2374 db_nslcmop=db_nslcmop,
2375 db_vnfrs=db_vnfrs,
bravof922c4172020-11-24 21:21:43 -03002376 db_vnfds=db_vnfds,
tiernoe876f672020-02-13 14:34:48 +00002377 n2vc_key_list=n2vc_key_list,
garciadeblas5697b8b2021-03-24 09:17:02 +01002378 stage=stage,
tierno98ad6ea2019-05-30 17:16:28 +00002379 )
tiernod8323042019-08-09 11:32:23 +00002380 )
2381 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "instantiate_RO", task_ro)
tiernoa2143262020-03-27 16:20:40 +00002382 tasks_dict_info[task_ro] = "Deploying at VIM"
tierno98ad6ea2019-05-30 17:16:28 +00002383
tiernod8323042019-08-09 11:32:23 +00002384 # n2vc_redesign STEP 3 to 6 Deploy N2VC
tiernoe876f672020-02-13 14:34:48 +00002385 stage[1] = "Deploying Execution Environments."
2386 self.logger.debug(logging_text + stage[1])
tierno98ad6ea2019-05-30 17:16:28 +00002387
tiernod8323042019-08-09 11:32:23 +00002388 nsi_id = None # TODO put nsi_id when this nsr belongs to a NSI
bravof922c4172020-11-24 21:21:43 -03002389 for vnf_profile in get_vnf_profiles(nsd):
2390 vnfd_id = vnf_profile["vnfd-id"]
2391 vnfd = find_in_list(db_vnfds, lambda a_vnf: a_vnf["id"] == vnfd_id)
2392 member_vnf_index = str(vnf_profile["id"])
tiernod8323042019-08-09 11:32:23 +00002393 db_vnfr = db_vnfrs[member_vnf_index]
2394 base_folder = vnfd["_admin"]["storage"]
2395 vdu_id = None
2396 vdu_index = 0
tierno98ad6ea2019-05-30 17:16:28 +00002397 vdu_name = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01002398 kdu_name = None
tierno59d22d22018-09-25 18:10:19 +02002399
tierno8a518872018-12-21 13:42:14 +00002400 # Get additional parameters
bravof922c4172020-11-24 21:21:43 -03002401 deploy_params = {"OSM": get_osm_params(db_vnfr)}
tiernod8323042019-08-09 11:32:23 +00002402 if db_vnfr.get("additionalParamsForVnf"):
garciadeblas5697b8b2021-03-24 09:17:02 +01002403 deploy_params.update(
2404 parse_yaml_strings(db_vnfr["additionalParamsForVnf"].copy())
2405 )
tierno8a518872018-12-21 13:42:14 +00002406
bravofe5a31bc2021-02-17 19:09:12 -03002407 descriptor_config = get_configuration(vnfd, vnfd["id"])
tierno588547c2020-07-01 15:30:20 +00002408 if descriptor_config:
quilesj7e13aeb2019-10-08 13:34:55 +02002409 self._deploy_n2vc(
garciadeblas5697b8b2021-03-24 09:17:02 +01002410 logging_text=logging_text
2411 + "member_vnf_index={} ".format(member_vnf_index),
quilesj7e13aeb2019-10-08 13:34:55 +02002412 db_nsr=db_nsr,
2413 db_vnfr=db_vnfr,
2414 nslcmop_id=nslcmop_id,
2415 nsr_id=nsr_id,
2416 nsi_id=nsi_id,
2417 vnfd_id=vnfd_id,
2418 vdu_id=vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002419 kdu_name=kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02002420 member_vnf_index=member_vnf_index,
2421 vdu_index=vdu_index,
2422 vdu_name=vdu_name,
2423 deploy_params=deploy_params,
2424 descriptor_config=descriptor_config,
2425 base_folder=base_folder,
tiernoe876f672020-02-13 14:34:48 +00002426 task_instantiation_info=tasks_dict_info,
garciadeblas5697b8b2021-03-24 09:17:02 +01002427 stage=stage,
quilesj7e13aeb2019-10-08 13:34:55 +02002428 )
tierno59d22d22018-09-25 18:10:19 +02002429
2430 # Deploy charms for each VDU that supports one.
bravof922c4172020-11-24 21:21:43 -03002431 for vdud in get_vdu_list(vnfd):
tiernod8323042019-08-09 11:32:23 +00002432 vdu_id = vdud["id"]
bravofe5a31bc2021-02-17 19:09:12 -03002433 descriptor_config = get_configuration(vnfd, vdu_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01002434 vdur = find_in_list(
2435 db_vnfr["vdur"], lambda vdu: vdu["vdu-id-ref"] == vdu_id
2436 )
bravof922c4172020-11-24 21:21:43 -03002437
tierno626e0152019-11-29 14:16:16 +00002438 if vdur.get("additionalParams"):
bravof922c4172020-11-24 21:21:43 -03002439 deploy_params_vdu = parse_yaml_strings(vdur["additionalParams"])
tierno626e0152019-11-29 14:16:16 +00002440 else:
2441 deploy_params_vdu = deploy_params
garciadeblas5697b8b2021-03-24 09:17:02 +01002442 deploy_params_vdu["OSM"] = get_osm_params(
2443 db_vnfr, vdu_id, vdu_count_index=0
2444 )
endika76ba9232021-06-21 18:55:07 +02002445 vdud_count = get_number_of_instances(vnfd, vdu_id)
bravof922c4172020-11-24 21:21:43 -03002446
2447 self.logger.debug("VDUD > {}".format(vdud))
garciadeblas5697b8b2021-03-24 09:17:02 +01002448 self.logger.debug(
2449 "Descriptor config > {}".format(descriptor_config)
2450 )
tierno588547c2020-07-01 15:30:20 +00002451 if descriptor_config:
tiernod8323042019-08-09 11:32:23 +00002452 vdu_name = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01002453 kdu_name = None
bravof922c4172020-11-24 21:21:43 -03002454 for vdu_index in range(vdud_count):
tiernod8323042019-08-09 11:32:23 +00002455 # TODO vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
quilesj7e13aeb2019-10-08 13:34:55 +02002456 self._deploy_n2vc(
garciadeblas5697b8b2021-03-24 09:17:02 +01002457 logging_text=logging_text
2458 + "member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
2459 member_vnf_index, vdu_id, vdu_index
2460 ),
quilesj7e13aeb2019-10-08 13:34:55 +02002461 db_nsr=db_nsr,
2462 db_vnfr=db_vnfr,
2463 nslcmop_id=nslcmop_id,
2464 nsr_id=nsr_id,
2465 nsi_id=nsi_id,
2466 vnfd_id=vnfd_id,
2467 vdu_id=vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002468 kdu_name=kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02002469 member_vnf_index=member_vnf_index,
2470 vdu_index=vdu_index,
2471 vdu_name=vdu_name,
tierno626e0152019-11-29 14:16:16 +00002472 deploy_params=deploy_params_vdu,
quilesj7e13aeb2019-10-08 13:34:55 +02002473 descriptor_config=descriptor_config,
2474 base_folder=base_folder,
tierno8e2fae72020-04-01 15:21:15 +00002475 task_instantiation_info=tasks_dict_info,
garciadeblas5697b8b2021-03-24 09:17:02 +01002476 stage=stage,
quilesj7e13aeb2019-10-08 13:34:55 +02002477 )
bravof922c4172020-11-24 21:21:43 -03002478 for kdud in get_kdu_list(vnfd):
calvinosanch9f9c6f22019-11-04 13:37:39 +01002479 kdu_name = kdud["name"]
bravofe5a31bc2021-02-17 19:09:12 -03002480 descriptor_config = get_configuration(vnfd, kdu_name)
tierno588547c2020-07-01 15:30:20 +00002481 if descriptor_config:
calvinosanch9f9c6f22019-11-04 13:37:39 +01002482 vdu_id = None
2483 vdu_index = 0
2484 vdu_name = None
garciadeblas5697b8b2021-03-24 09:17:02 +01002485 kdur = next(
2486 x for x in db_vnfr["kdur"] if x["kdu-name"] == kdu_name
2487 )
bravof922c4172020-11-24 21:21:43 -03002488 deploy_params_kdu = {"OSM": get_osm_params(db_vnfr)}
tierno72ef84f2020-10-06 08:22:07 +00002489 if kdur.get("additionalParams"):
garciadeblas5697b8b2021-03-24 09:17:02 +01002490 deploy_params_kdu = parse_yaml_strings(
2491 kdur["additionalParams"]
2492 )
tierno59d22d22018-09-25 18:10:19 +02002493
calvinosanch9f9c6f22019-11-04 13:37:39 +01002494 self._deploy_n2vc(
2495 logging_text=logging_text,
2496 db_nsr=db_nsr,
2497 db_vnfr=db_vnfr,
2498 nslcmop_id=nslcmop_id,
2499 nsr_id=nsr_id,
2500 nsi_id=nsi_id,
2501 vnfd_id=vnfd_id,
2502 vdu_id=vdu_id,
2503 kdu_name=kdu_name,
2504 member_vnf_index=member_vnf_index,
2505 vdu_index=vdu_index,
2506 vdu_name=vdu_name,
tierno72ef84f2020-10-06 08:22:07 +00002507 deploy_params=deploy_params_kdu,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002508 descriptor_config=descriptor_config,
2509 base_folder=base_folder,
tierno8e2fae72020-04-01 15:21:15 +00002510 task_instantiation_info=tasks_dict_info,
garciadeblas5697b8b2021-03-24 09:17:02 +01002511 stage=stage,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002512 )
tierno59d22d22018-09-25 18:10:19 +02002513
tierno1b633412019-02-25 16:48:23 +00002514 # Check if this NS has a charm configuration
tiernod8323042019-08-09 11:32:23 +00002515 descriptor_config = nsd.get("ns-configuration")
2516 if descriptor_config and descriptor_config.get("juju"):
2517 vnfd_id = None
2518 db_vnfr = None
2519 member_vnf_index = None
2520 vdu_id = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01002521 kdu_name = None
tiernod8323042019-08-09 11:32:23 +00002522 vdu_index = 0
2523 vdu_name = None
tierno1b633412019-02-25 16:48:23 +00002524
tiernod8323042019-08-09 11:32:23 +00002525 # Get additional parameters
David Garcia40603572020-12-10 20:10:53 +01002526 deploy_params = {"OSM": {"vim_account_id": ns_params["vimAccountId"]}}
tiernod8323042019-08-09 11:32:23 +00002527 if db_nsr.get("additionalParamsForNs"):
garciadeblas5697b8b2021-03-24 09:17:02 +01002528 deploy_params.update(
2529 parse_yaml_strings(db_nsr["additionalParamsForNs"].copy())
2530 )
tiernod8323042019-08-09 11:32:23 +00002531 base_folder = nsd["_admin"]["storage"]
quilesj7e13aeb2019-10-08 13:34:55 +02002532 self._deploy_n2vc(
2533 logging_text=logging_text,
2534 db_nsr=db_nsr,
2535 db_vnfr=db_vnfr,
2536 nslcmop_id=nslcmop_id,
2537 nsr_id=nsr_id,
2538 nsi_id=nsi_id,
2539 vnfd_id=vnfd_id,
2540 vdu_id=vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002541 kdu_name=kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02002542 member_vnf_index=member_vnf_index,
2543 vdu_index=vdu_index,
2544 vdu_name=vdu_name,
2545 deploy_params=deploy_params,
2546 descriptor_config=descriptor_config,
2547 base_folder=base_folder,
tierno8e2fae72020-04-01 15:21:15 +00002548 task_instantiation_info=tasks_dict_info,
garciadeblas5697b8b2021-03-24 09:17:02 +01002549 stage=stage,
quilesj7e13aeb2019-10-08 13:34:55 +02002550 )
tierno1b633412019-02-25 16:48:23 +00002551
tiernoe876f672020-02-13 14:34:48 +00002552 # rest of staff will be done at finally
tierno1b633412019-02-25 16:48:23 +00002553
garciadeblas5697b8b2021-03-24 09:17:02 +01002554 except (
2555 ROclient.ROClientException,
2556 DbException,
2557 LcmException,
2558 N2VCException,
2559 ) as e:
2560 self.logger.error(
2561 logging_text + "Exit Exception while '{}': {}".format(stage[1], e)
2562 )
tierno59d22d22018-09-25 18:10:19 +02002563 exc = e
2564 except asyncio.CancelledError:
garciadeblas5697b8b2021-03-24 09:17:02 +01002565 self.logger.error(
2566 logging_text + "Cancelled Exception while '{}'".format(stage[1])
2567 )
tierno59d22d22018-09-25 18:10:19 +02002568 exc = "Operation was cancelled"
2569 except Exception as e:
2570 exc = traceback.format_exc()
garciadeblas5697b8b2021-03-24 09:17:02 +01002571 self.logger.critical(
2572 logging_text + "Exit Exception while '{}': {}".format(stage[1], e),
2573 exc_info=True,
2574 )
tierno59d22d22018-09-25 18:10:19 +02002575 finally:
2576 if exc:
tiernoe876f672020-02-13 14:34:48 +00002577 error_list.append(str(exc))
tiernobaa51102018-12-14 13:16:18 +00002578 try:
tiernoe876f672020-02-13 14:34:48 +00002579 # wait for pending tasks
2580 if tasks_dict_info:
2581 stage[1] = "Waiting for instantiate pending tasks."
2582 self.logger.debug(logging_text + stage[1])
garciadeblas5697b8b2021-03-24 09:17:02 +01002583 error_list += await self._wait_for_tasks(
2584 logging_text,
2585 tasks_dict_info,
2586 timeout_ns_deploy,
2587 stage,
2588 nslcmop_id,
2589 nsr_id=nsr_id,
2590 )
tiernoe876f672020-02-13 14:34:48 +00002591 stage[1] = stage[2] = ""
2592 except asyncio.CancelledError:
2593 error_list.append("Cancelled")
2594 # TODO cancel all tasks
2595 except Exception as exc:
2596 error_list.append(str(exc))
quilesj4cda56b2019-12-05 10:02:20 +00002597
tiernoe876f672020-02-13 14:34:48 +00002598 # update operation-status
2599 db_nsr_update["operational-status"] = "running"
2600 # let's begin with VCA 'configured' status (later we can change it)
2601 db_nsr_update["config-status"] = "configured"
2602 for task, task_name in tasks_dict_info.items():
2603 if not task.done() or task.cancelled() or task.exception():
2604 if task_name.startswith(self.task_name_deploy_vca):
2605 # A N2VC task is pending
2606 db_nsr_update["config-status"] = "failed"
quilesj4cda56b2019-12-05 10:02:20 +00002607 else:
tiernoe876f672020-02-13 14:34:48 +00002608 # RO or KDU task is pending
2609 db_nsr_update["operational-status"] = "failed"
quilesj3655ae02019-12-12 16:08:35 +00002610
tiernoe876f672020-02-13 14:34:48 +00002611 # update status at database
2612 if error_list:
tiernoa2143262020-03-27 16:20:40 +00002613 error_detail = ". ".join(error_list)
tiernoe876f672020-02-13 14:34:48 +00002614 self.logger.error(logging_text + error_detail)
garciadeblas5697b8b2021-03-24 09:17:02 +01002615 error_description_nslcmop = "{} Detail: {}".format(
2616 stage[0], error_detail
2617 )
2618 error_description_nsr = "Operation: INSTANTIATING.{}, {}".format(
2619 nslcmop_id, stage[0]
2620 )
quilesj3655ae02019-12-12 16:08:35 +00002621
garciadeblas5697b8b2021-03-24 09:17:02 +01002622 db_nsr_update["detailed-status"] = (
2623 error_description_nsr + " Detail: " + error_detail
2624 )
tiernoe876f672020-02-13 14:34:48 +00002625 db_nslcmop_update["detailed-status"] = error_detail
2626 nslcmop_operation_state = "FAILED"
2627 ns_state = "BROKEN"
2628 else:
tiernoa2143262020-03-27 16:20:40 +00002629 error_detail = None
tiernoe876f672020-02-13 14:34:48 +00002630 error_description_nsr = error_description_nslcmop = None
2631 ns_state = "READY"
2632 db_nsr_update["detailed-status"] = "Done"
2633 db_nslcmop_update["detailed-status"] = "Done"
2634 nslcmop_operation_state = "COMPLETED"
quilesj4cda56b2019-12-05 10:02:20 +00002635
tiernoe876f672020-02-13 14:34:48 +00002636 if db_nsr:
2637 self._write_ns_status(
2638 nsr_id=nsr_id,
2639 ns_state=ns_state,
2640 current_operation="IDLE",
2641 current_operation_id=None,
2642 error_description=error_description_nsr,
tiernoa2143262020-03-27 16:20:40 +00002643 error_detail=error_detail,
garciadeblas5697b8b2021-03-24 09:17:02 +01002644 other_update=db_nsr_update,
tiernoe876f672020-02-13 14:34:48 +00002645 )
tiernoa17d4f42020-04-28 09:59:23 +00002646 self._write_op_status(
2647 op_id=nslcmop_id,
2648 stage="",
2649 error_message=error_description_nslcmop,
2650 operation_state=nslcmop_operation_state,
2651 other_update=db_nslcmop_update,
2652 )
quilesj3655ae02019-12-12 16:08:35 +00002653
tierno59d22d22018-09-25 18:10:19 +02002654 if nslcmop_operation_state:
2655 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01002656 await self.msg.aiowrite(
2657 "ns",
2658 "instantiated",
2659 {
2660 "nsr_id": nsr_id,
2661 "nslcmop_id": nslcmop_id,
2662 "operationState": nslcmop_operation_state,
2663 },
2664 loop=self.loop,
2665 )
tierno59d22d22018-09-25 18:10:19 +02002666 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002667 self.logger.error(
2668 logging_text + "kafka_write notification Exception {}".format(e)
2669 )
tierno59d22d22018-09-25 18:10:19 +02002670
2671 self.logger.debug(logging_text + "Exit")
2672 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_instantiate")
2673
David Garciab4ebcd02021-10-28 02:00:43 +02002674 def _get_vnfd(self, vnfd_id: str, cached_vnfds: Dict[str, Any]):
2675 if vnfd_id not in cached_vnfds:
2676 cached_vnfds[vnfd_id] = self.db.get_one("vnfds", {"id": vnfd_id})
2677 return cached_vnfds[vnfd_id]
2678
2679 def _get_vnfr(self, nsr_id: str, vnf_profile_id: str, cached_vnfrs: Dict[str, Any]):
2680 if vnf_profile_id not in cached_vnfrs:
2681 cached_vnfrs[vnf_profile_id] = self.db.get_one(
2682 "vnfrs",
2683 {
2684 "member-vnf-index-ref": vnf_profile_id,
2685 "nsr-id-ref": nsr_id,
2686 },
2687 )
2688 return cached_vnfrs[vnf_profile_id]
2689
2690 def _is_deployed_vca_in_relation(
2691 self, vca: DeployedVCA, relation: Relation
2692 ) -> bool:
2693 found = False
2694 for endpoint in (relation.provider, relation.requirer):
2695 if endpoint["kdu-resource-profile-id"]:
2696 continue
2697 found = (
2698 vca.vnf_profile_id == endpoint.vnf_profile_id
2699 and vca.vdu_profile_id == endpoint.vdu_profile_id
2700 and vca.execution_environment_ref == endpoint.execution_environment_ref
2701 )
2702 if found:
2703 break
2704 return found
2705
2706 def _update_ee_relation_data_with_implicit_data(
2707 self, nsr_id, nsd, ee_relation_data, cached_vnfds, vnf_profile_id: str = None
2708 ):
2709 ee_relation_data = safe_get_ee_relation(
2710 nsr_id, ee_relation_data, vnf_profile_id=vnf_profile_id
2711 )
2712 ee_relation_level = EELevel.get_level(ee_relation_data)
2713 if (ee_relation_level in (EELevel.VNF, EELevel.VDU)) and not ee_relation_data[
2714 "execution-environment-ref"
2715 ]:
2716 vnf_profile = get_vnf_profile(nsd, ee_relation_data["vnf-profile-id"])
2717 vnfd_id = vnf_profile["vnfd-id"]
2718 db_vnfd = self._get_vnfd(vnfd_id, cached_vnfds)
2719 entity_id = (
2720 vnfd_id
2721 if ee_relation_level == EELevel.VNF
2722 else ee_relation_data["vdu-profile-id"]
2723 )
2724 ee = get_juju_ee_ref(db_vnfd, entity_id)
2725 if not ee:
2726 raise Exception(
2727 f"not execution environments found for ee_relation {ee_relation_data}"
2728 )
2729 ee_relation_data["execution-environment-ref"] = ee["id"]
2730 return ee_relation_data
2731
2732 def _get_ns_relations(
2733 self,
2734 nsr_id: str,
2735 nsd: Dict[str, Any],
2736 vca: DeployedVCA,
2737 cached_vnfds: Dict[str, Any],
David Garcia1f40aa92021-11-11 16:35:26 +01002738 ) -> List[Relation]:
David Garciab4ebcd02021-10-28 02:00:43 +02002739 relations = []
2740 db_ns_relations = get_ns_configuration_relation_list(nsd)
2741 for r in db_ns_relations:
David Garcia1f40aa92021-11-11 16:35:26 +01002742 provider_dict = None
2743 requirer_dict = None
2744 if all(key in r for key in ("provider", "requirer")):
2745 provider_dict = r["provider"]
2746 requirer_dict = r["requirer"]
2747 elif "entities" in r:
2748 provider_id = r["entities"][0]["id"]
2749 provider_dict = {
2750 "nsr-id": nsr_id,
2751 "endpoint": r["entities"][0]["endpoint"],
2752 }
2753 if provider_id != nsd["id"]:
2754 provider_dict["vnf-profile-id"] = provider_id
2755 requirer_id = r["entities"][1]["id"]
2756 requirer_dict = {
2757 "nsr-id": nsr_id,
2758 "endpoint": r["entities"][1]["endpoint"],
2759 }
2760 if requirer_id != nsd["id"]:
2761 requirer_dict["vnf-profile-id"] = requirer_id
2762 else:
2763 raise Exception("provider/requirer or entities must be included in the relation.")
David Garciab4ebcd02021-10-28 02:00:43 +02002764 relation_provider = self._update_ee_relation_data_with_implicit_data(
David Garcia1f40aa92021-11-11 16:35:26 +01002765 nsr_id, nsd, provider_dict, cached_vnfds
David Garciab4ebcd02021-10-28 02:00:43 +02002766 )
2767 relation_requirer = self._update_ee_relation_data_with_implicit_data(
David Garcia1f40aa92021-11-11 16:35:26 +01002768 nsr_id, nsd, requirer_dict, cached_vnfds
David Garciab4ebcd02021-10-28 02:00:43 +02002769 )
2770 provider = EERelation(relation_provider)
2771 requirer = EERelation(relation_requirer)
2772 relation = Relation(r["name"], provider, requirer)
2773 vca_in_relation = self._is_deployed_vca_in_relation(vca, relation)
2774 if vca_in_relation:
2775 relations.append(relation)
2776 return relations
2777
2778 def _get_vnf_relations(
2779 self,
2780 nsr_id: str,
2781 nsd: Dict[str, Any],
2782 vca: DeployedVCA,
2783 cached_vnfds: Dict[str, Any],
David Garcia1f40aa92021-11-11 16:35:26 +01002784 ) -> List[Relation]:
David Garciab4ebcd02021-10-28 02:00:43 +02002785 relations = []
2786 vnf_profile = get_vnf_profile(nsd, vca.vnf_profile_id)
2787 vnf_profile_id = vnf_profile["id"]
2788 vnfd_id = vnf_profile["vnfd-id"]
2789 db_vnfd = self._get_vnfd(vnfd_id, cached_vnfds)
2790 db_vnf_relations = get_relation_list(db_vnfd, vnfd_id)
2791 for r in db_vnf_relations:
David Garcia1f40aa92021-11-11 16:35:26 +01002792 provider_dict = None
2793 requirer_dict = None
2794 if all(key in r for key in ("provider", "requirer")):
2795 provider_dict = r["provider"]
2796 requirer_dict = r["requirer"]
2797 elif "entities" in r:
2798 provider_id = r["entities"][0]["id"]
2799 provider_dict = {
2800 "nsr-id": nsr_id,
2801 "vnf-profile-id": vnf_profile_id,
2802 "endpoint": r["entities"][0]["endpoint"],
2803 }
2804 if provider_id != vnfd_id:
2805 provider_dict["vdu-profile-id"] = provider_id
2806 requirer_id = r["entities"][1]["id"]
2807 requirer_dict = {
2808 "nsr-id": nsr_id,
2809 "vnf-profile-id": vnf_profile_id,
2810 "endpoint": r["entities"][1]["endpoint"],
2811 }
2812 if requirer_id != vnfd_id:
2813 requirer_dict["vdu-profile-id"] = requirer_id
2814 else:
2815 raise Exception("provider/requirer or entities must be included in the relation.")
David Garciab4ebcd02021-10-28 02:00:43 +02002816 relation_provider = self._update_ee_relation_data_with_implicit_data(
David Garcia1f40aa92021-11-11 16:35:26 +01002817 nsr_id, nsd, provider_dict, cached_vnfds, vnf_profile_id=vnf_profile_id
David Garciab4ebcd02021-10-28 02:00:43 +02002818 )
2819 relation_requirer = self._update_ee_relation_data_with_implicit_data(
David Garcia1f40aa92021-11-11 16:35:26 +01002820 nsr_id, nsd, requirer_dict, cached_vnfds, vnf_profile_id=vnf_profile_id
David Garciab4ebcd02021-10-28 02:00:43 +02002821 )
2822 provider = EERelation(relation_provider)
2823 requirer = EERelation(relation_requirer)
2824 relation = Relation(r["name"], provider, requirer)
2825 vca_in_relation = self._is_deployed_vca_in_relation(vca, relation)
2826 if vca_in_relation:
2827 relations.append(relation)
2828 return relations
2829
2830 def _get_kdu_resource_data(
2831 self,
2832 ee_relation: EERelation,
2833 db_nsr: Dict[str, Any],
2834 cached_vnfds: Dict[str, Any],
2835 ) -> DeployedK8sResource:
2836 nsd = get_nsd(db_nsr)
2837 vnf_profiles = get_vnf_profiles(nsd)
2838 vnfd_id = find_in_list(
2839 vnf_profiles,
2840 lambda vnf_profile: vnf_profile["id"] == ee_relation.vnf_profile_id,
2841 )["vnfd-id"]
2842 db_vnfd = self._get_vnfd(vnfd_id, cached_vnfds)
2843 kdu_resource_profile = get_kdu_resource_profile(
2844 db_vnfd, ee_relation.kdu_resource_profile_id
2845 )
2846 kdu_name = kdu_resource_profile["kdu-name"]
2847 deployed_kdu, _ = get_deployed_kdu(
2848 db_nsr.get("_admin", ()).get("deployed", ()),
2849 kdu_name,
2850 ee_relation.vnf_profile_id,
2851 )
2852 deployed_kdu.update({"resource-name": kdu_resource_profile["resource-name"]})
2853 return deployed_kdu
2854
2855 def _get_deployed_component(
2856 self,
2857 ee_relation: EERelation,
2858 db_nsr: Dict[str, Any],
2859 cached_vnfds: Dict[str, Any],
2860 ) -> DeployedComponent:
2861 nsr_id = db_nsr["_id"]
2862 deployed_component = None
2863 ee_level = EELevel.get_level(ee_relation)
2864 if ee_level == EELevel.NS:
2865 vca = get_deployed_vca(db_nsr, {"vdu_id": None, "member-vnf-index": None})
2866 if vca:
2867 deployed_component = DeployedVCA(nsr_id, vca)
2868 elif ee_level == EELevel.VNF:
2869 vca = get_deployed_vca(
2870 db_nsr,
2871 {
2872 "vdu_id": None,
2873 "member-vnf-index": ee_relation.vnf_profile_id,
2874 "ee_descriptor_id": ee_relation.execution_environment_ref,
2875 },
2876 )
2877 if vca:
2878 deployed_component = DeployedVCA(nsr_id, vca)
2879 elif ee_level == EELevel.VDU:
2880 vca = get_deployed_vca(
2881 db_nsr,
2882 {
2883 "vdu_id": ee_relation.vdu_profile_id,
2884 "member-vnf-index": ee_relation.vnf_profile_id,
2885 "ee_descriptor_id": ee_relation.execution_environment_ref,
2886 },
2887 )
2888 if vca:
2889 deployed_component = DeployedVCA(nsr_id, vca)
2890 elif ee_level == EELevel.KDU:
2891 kdu_resource_data = self._get_kdu_resource_data(
2892 ee_relation, db_nsr, cached_vnfds
2893 )
2894 if kdu_resource_data:
2895 deployed_component = DeployedK8sResource(kdu_resource_data)
2896 return deployed_component
2897
2898 async def _add_relation(
2899 self,
2900 relation: Relation,
2901 vca_type: str,
2902 db_nsr: Dict[str, Any],
2903 cached_vnfds: Dict[str, Any],
2904 cached_vnfrs: Dict[str, Any],
2905 ) -> bool:
2906 deployed_provider = self._get_deployed_component(
2907 relation.provider, db_nsr, cached_vnfds
2908 )
2909 deployed_requirer = self._get_deployed_component(
2910 relation.requirer, db_nsr, cached_vnfds
2911 )
2912 if (
2913 deployed_provider
2914 and deployed_requirer
2915 and deployed_provider.config_sw_installed
2916 and deployed_requirer.config_sw_installed
2917 ):
2918 provider_db_vnfr = (
2919 self._get_vnfr(
2920 relation.provider.nsr_id,
2921 relation.provider.vnf_profile_id,
2922 cached_vnfrs,
2923 )
2924 if relation.provider.vnf_profile_id
2925 else None
2926 )
2927 requirer_db_vnfr = (
2928 self._get_vnfr(
2929 relation.requirer.nsr_id,
2930 relation.requirer.vnf_profile_id,
2931 cached_vnfrs,
2932 )
2933 if relation.requirer.vnf_profile_id
2934 else None
2935 )
2936 provider_vca_id = self.get_vca_id(provider_db_vnfr, db_nsr)
2937 requirer_vca_id = self.get_vca_id(requirer_db_vnfr, db_nsr)
2938 provider_relation_endpoint = RelationEndpoint(
2939 deployed_provider.ee_id,
2940 provider_vca_id,
2941 relation.provider.endpoint,
2942 )
2943 requirer_relation_endpoint = RelationEndpoint(
2944 deployed_requirer.ee_id,
2945 requirer_vca_id,
2946 relation.requirer.endpoint,
2947 )
2948 await self.vca_map[vca_type].add_relation(
2949 provider=provider_relation_endpoint,
2950 requirer=requirer_relation_endpoint,
2951 )
2952 # remove entry from relations list
2953 return True
2954 return False
2955
David Garciac1fe90a2021-03-31 19:12:02 +02002956 async def _add_vca_relations(
2957 self,
2958 logging_text,
2959 nsr_id,
David Garciab4ebcd02021-10-28 02:00:43 +02002960 vca_type: str,
David Garciac1fe90a2021-03-31 19:12:02 +02002961 vca_index: int,
2962 timeout: int = 3600,
David Garciac1fe90a2021-03-31 19:12:02 +02002963 ) -> bool:
quilesj63f90042020-01-17 09:53:55 +00002964
2965 # steps:
2966 # 1. find all relations for this VCA
2967 # 2. wait for other peers related
2968 # 3. add relations
2969
2970 try:
quilesj63f90042020-01-17 09:53:55 +00002971 # STEP 1: find all relations for this VCA
2972
2973 # read nsr record
2974 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
David Garciab4ebcd02021-10-28 02:00:43 +02002975 nsd = get_nsd(db_nsr)
quilesj63f90042020-01-17 09:53:55 +00002976
2977 # this VCA data
David Garciab4ebcd02021-10-28 02:00:43 +02002978 deployed_vca_dict = get_deployed_vca_list(db_nsr)[vca_index]
2979 my_vca = DeployedVCA(nsr_id, deployed_vca_dict)
quilesj63f90042020-01-17 09:53:55 +00002980
David Garciab4ebcd02021-10-28 02:00:43 +02002981 cached_vnfds = {}
2982 cached_vnfrs = {}
2983 relations = []
2984 relations.extend(self._get_ns_relations(nsr_id, nsd, my_vca, cached_vnfds))
2985 relations.extend(self._get_vnf_relations(nsr_id, nsd, my_vca, cached_vnfds))
quilesj63f90042020-01-17 09:53:55 +00002986
2987 # if no relations, terminate
David Garciab4ebcd02021-10-28 02:00:43 +02002988 if not relations:
garciadeblas5697b8b2021-03-24 09:17:02 +01002989 self.logger.debug(logging_text + " No relations")
quilesj63f90042020-01-17 09:53:55 +00002990 return True
2991
David Garciab4ebcd02021-10-28 02:00:43 +02002992 self.logger.debug(logging_text + " adding relations {}".format(relations))
quilesj63f90042020-01-17 09:53:55 +00002993
2994 # add all relations
2995 start = time()
2996 while True:
2997 # check timeout
2998 now = time()
2999 if now - start >= timeout:
garciadeblas5697b8b2021-03-24 09:17:02 +01003000 self.logger.error(logging_text + " : timeout adding relations")
quilesj63f90042020-01-17 09:53:55 +00003001 return False
3002
David Garciab4ebcd02021-10-28 02:00:43 +02003003 # reload nsr from database (we need to update record: _admin.deployed.VCA)
quilesj63f90042020-01-17 09:53:55 +00003004 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
3005
David Garciab4ebcd02021-10-28 02:00:43 +02003006 # for each relation, find the VCA's related
3007 for relation in relations.copy():
3008 added = await self._add_relation(
3009 relation,
3010 vca_type,
3011 db_nsr,
3012 cached_vnfds,
3013 cached_vnfrs,
3014 )
3015 if added:
3016 relations.remove(relation)
quilesj63f90042020-01-17 09:53:55 +00003017
David Garciab4ebcd02021-10-28 02:00:43 +02003018 if not relations:
garciadeblas5697b8b2021-03-24 09:17:02 +01003019 self.logger.debug("Relations added")
quilesj63f90042020-01-17 09:53:55 +00003020 break
David Garciab4ebcd02021-10-28 02:00:43 +02003021 await asyncio.sleep(5.0)
quilesj63f90042020-01-17 09:53:55 +00003022
3023 return True
3024
3025 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01003026 self.logger.warn(logging_text + " ERROR adding relations: {}".format(e))
quilesj63f90042020-01-17 09:53:55 +00003027 return False
3028
garciadeblas5697b8b2021-03-24 09:17:02 +01003029 async def _install_kdu(
3030 self,
3031 nsr_id: str,
3032 nsr_db_path: str,
3033 vnfr_data: dict,
3034 kdu_index: int,
3035 kdud: dict,
3036 vnfd: dict,
3037 k8s_instance_info: dict,
3038 k8params: dict = None,
3039 timeout: int = 600,
3040 vca_id: str = None,
3041 ):
lloretgalleg7c121132020-07-08 07:53:22 +00003042
tiernob9018152020-04-16 14:18:24 +00003043 try:
lloretgalleg7c121132020-07-08 07:53:22 +00003044 k8sclustertype = k8s_instance_info["k8scluster-type"]
3045 # Instantiate kdu
garciadeblas5697b8b2021-03-24 09:17:02 +01003046 db_dict_install = {
3047 "collection": "nsrs",
3048 "filter": {"_id": nsr_id},
3049 "path": nsr_db_path,
3050 }
lloretgalleg7c121132020-07-08 07:53:22 +00003051
romeromonser4554a702021-05-28 12:00:08 +02003052 if k8s_instance_info.get("kdu-deployment-name"):
3053 kdu_instance = k8s_instance_info.get("kdu-deployment-name")
3054 else:
3055 kdu_instance = self.k8scluster_map[
3056 k8sclustertype
3057 ].generate_kdu_instance_name(
3058 db_dict=db_dict_install,
3059 kdu_model=k8s_instance_info["kdu-model"],
3060 kdu_name=k8s_instance_info["kdu-name"],
3061 )
garciadeblas5697b8b2021-03-24 09:17:02 +01003062 self.update_db_2(
3063 "nsrs", nsr_id, {nsr_db_path + ".kdu-instance": kdu_instance}
3064 )
David Garciad64e2742021-02-25 20:19:18 +01003065 await self.k8scluster_map[k8sclustertype].install(
lloretgalleg7c121132020-07-08 07:53:22 +00003066 cluster_uuid=k8s_instance_info["k8scluster-uuid"],
3067 kdu_model=k8s_instance_info["kdu-model"],
3068 atomic=True,
3069 params=k8params,
3070 db_dict=db_dict_install,
3071 timeout=timeout,
3072 kdu_name=k8s_instance_info["kdu-name"],
David Garciad64e2742021-02-25 20:19:18 +01003073 namespace=k8s_instance_info["namespace"],
3074 kdu_instance=kdu_instance,
David Garciac1fe90a2021-03-31 19:12:02 +02003075 vca_id=vca_id,
David Garciad64e2742021-02-25 20:19:18 +01003076 )
garciadeblas5697b8b2021-03-24 09:17:02 +01003077 self.update_db_2(
3078 "nsrs", nsr_id, {nsr_db_path + ".kdu-instance": kdu_instance}
3079 )
lloretgalleg7c121132020-07-08 07:53:22 +00003080
3081 # Obtain services to obtain management service ip
3082 services = await self.k8scluster_map[k8sclustertype].get_services(
3083 cluster_uuid=k8s_instance_info["k8scluster-uuid"],
3084 kdu_instance=kdu_instance,
garciadeblas5697b8b2021-03-24 09:17:02 +01003085 namespace=k8s_instance_info["namespace"],
3086 )
lloretgalleg7c121132020-07-08 07:53:22 +00003087
3088 # Obtain management service info (if exists)
tierno7ecbc342020-09-21 14:05:39 +00003089 vnfr_update_dict = {}
bravof6ec62b72021-02-25 17:20:35 -03003090 kdu_config = get_configuration(vnfd, kdud["name"])
3091 if kdu_config:
3092 target_ee_list = kdu_config.get("execution-environment-list", [])
3093 else:
3094 target_ee_list = []
3095
lloretgalleg7c121132020-07-08 07:53:22 +00003096 if services:
tierno7ecbc342020-09-21 14:05:39 +00003097 vnfr_update_dict["kdur.{}.services".format(kdu_index)] = services
garciadeblas5697b8b2021-03-24 09:17:02 +01003098 mgmt_services = [
3099 service
3100 for service in kdud.get("service", [])
3101 if service.get("mgmt-service")
3102 ]
lloretgalleg7c121132020-07-08 07:53:22 +00003103 for mgmt_service in mgmt_services:
3104 for service in services:
3105 if service["name"].startswith(mgmt_service["name"]):
3106 # Mgmt service found, Obtain service ip
3107 ip = service.get("external_ip", service.get("cluster_ip"))
3108 if isinstance(ip, list) and len(ip) == 1:
3109 ip = ip[0]
3110
garciadeblas5697b8b2021-03-24 09:17:02 +01003111 vnfr_update_dict[
3112 "kdur.{}.ip-address".format(kdu_index)
3113 ] = ip
lloretgalleg7c121132020-07-08 07:53:22 +00003114
3115 # Check if must update also mgmt ip at the vnf
garciadeblas5697b8b2021-03-24 09:17:02 +01003116 service_external_cp = mgmt_service.get(
3117 "external-connection-point-ref"
3118 )
lloretgalleg7c121132020-07-08 07:53:22 +00003119 if service_external_cp:
garciadeblas5697b8b2021-03-24 09:17:02 +01003120 if (
3121 deep_get(vnfd, ("mgmt-interface", "cp"))
3122 == service_external_cp
3123 ):
lloretgalleg7c121132020-07-08 07:53:22 +00003124 vnfr_update_dict["ip-address"] = ip
3125
bravof6ec62b72021-02-25 17:20:35 -03003126 if find_in_list(
3127 target_ee_list,
garciadeblas5697b8b2021-03-24 09:17:02 +01003128 lambda ee: ee.get(
3129 "external-connection-point-ref", ""
3130 )
3131 == service_external_cp,
bravof6ec62b72021-02-25 17:20:35 -03003132 ):
garciadeblas5697b8b2021-03-24 09:17:02 +01003133 vnfr_update_dict[
3134 "kdur.{}.ip-address".format(kdu_index)
3135 ] = ip
lloretgalleg7c121132020-07-08 07:53:22 +00003136 break
3137 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01003138 self.logger.warn(
3139 "Mgmt service name: {} not found".format(
3140 mgmt_service["name"]
3141 )
3142 )
lloretgalleg7c121132020-07-08 07:53:22 +00003143
tierno7ecbc342020-09-21 14:05:39 +00003144 vnfr_update_dict["kdur.{}.status".format(kdu_index)] = "READY"
3145 self.update_db_2("vnfrs", vnfr_data.get("_id"), vnfr_update_dict)
lloretgalleg7c121132020-07-08 07:53:22 +00003146
bravof9a256db2021-02-22 18:02:07 -03003147 kdu_config = get_configuration(vnfd, k8s_instance_info["kdu-name"])
garciadeblas5697b8b2021-03-24 09:17:02 +01003148 if (
3149 kdu_config
3150 and kdu_config.get("initial-config-primitive")
3151 and get_juju_ee_ref(vnfd, k8s_instance_info["kdu-name"]) is None
3152 ):
3153 initial_config_primitive_list = kdu_config.get(
3154 "initial-config-primitive"
3155 )
Dominik Fleischmannc1975dd2020-08-19 12:17:51 +02003156 initial_config_primitive_list.sort(key=lambda val: int(val["seq"]))
3157
3158 for initial_config_primitive in initial_config_primitive_list:
garciadeblas5697b8b2021-03-24 09:17:02 +01003159 primitive_params_ = self._map_primitive_params(
3160 initial_config_primitive, {}, {}
3161 )
Dominik Fleischmannc1975dd2020-08-19 12:17:51 +02003162
3163 await asyncio.wait_for(
3164 self.k8scluster_map[k8sclustertype].exec_primitive(
3165 cluster_uuid=k8s_instance_info["k8scluster-uuid"],
3166 kdu_instance=kdu_instance,
3167 primitive_name=initial_config_primitive["name"],
garciadeblas5697b8b2021-03-24 09:17:02 +01003168 params=primitive_params_,
3169 db_dict=db_dict_install,
David Garciac1fe90a2021-03-31 19:12:02 +02003170 vca_id=vca_id,
3171 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01003172 timeout=timeout,
David Garciac1fe90a2021-03-31 19:12:02 +02003173 )
Dominik Fleischmannc1975dd2020-08-19 12:17:51 +02003174
tiernob9018152020-04-16 14:18:24 +00003175 except Exception as e:
lloretgalleg7c121132020-07-08 07:53:22 +00003176 # Prepare update db with error and raise exception
tiernob9018152020-04-16 14:18:24 +00003177 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01003178 self.update_db_2(
3179 "nsrs", nsr_id, {nsr_db_path + ".detailed-status": str(e)}
3180 )
3181 self.update_db_2(
3182 "vnfrs",
3183 vnfr_data.get("_id"),
3184 {"kdur.{}.status".format(kdu_index): "ERROR"},
3185 )
tiernob9018152020-04-16 14:18:24 +00003186 except Exception:
lloretgalleg7c121132020-07-08 07:53:22 +00003187 # ignore to keep original exception
tiernob9018152020-04-16 14:18:24 +00003188 pass
lloretgalleg7c121132020-07-08 07:53:22 +00003189 # reraise original error
3190 raise
3191
3192 return kdu_instance
tiernob9018152020-04-16 14:18:24 +00003193
garciadeblas5697b8b2021-03-24 09:17:02 +01003194 async def deploy_kdus(
3195 self,
3196 logging_text,
3197 nsr_id,
3198 nslcmop_id,
3199 db_vnfrs,
3200 db_vnfds,
3201 task_instantiation_info,
3202 ):
calvinosanch9f9c6f22019-11-04 13:37:39 +01003203 # Launch kdus if present in the descriptor
tierno626e0152019-11-29 14:16:16 +00003204
garciadeblas5697b8b2021-03-24 09:17:02 +01003205 k8scluster_id_2_uuic = {
3206 "helm-chart-v3": {},
3207 "helm-chart": {},
3208 "juju-bundle": {},
3209 }
tierno626e0152019-11-29 14:16:16 +00003210
tierno16f4a4e2020-07-20 09:05:51 +00003211 async def _get_cluster_id(cluster_id, cluster_type):
tierno626e0152019-11-29 14:16:16 +00003212 nonlocal k8scluster_id_2_uuic
3213 if cluster_id in k8scluster_id_2_uuic[cluster_type]:
3214 return k8scluster_id_2_uuic[cluster_type][cluster_id]
3215
tierno16f4a4e2020-07-20 09:05:51 +00003216 # check if K8scluster is creating and wait look if previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +01003217 task_name, task_dependency = self.lcm_tasks.lookfor_related(
3218 "k8scluster", cluster_id
3219 )
tierno16f4a4e2020-07-20 09:05:51 +00003220 if task_dependency:
garciadeblas5697b8b2021-03-24 09:17:02 +01003221 text = "Waiting for related tasks '{}' on k8scluster {} to be completed".format(
3222 task_name, cluster_id
3223 )
tierno16f4a4e2020-07-20 09:05:51 +00003224 self.logger.debug(logging_text + text)
3225 await asyncio.wait(task_dependency, timeout=3600)
3226
garciadeblas5697b8b2021-03-24 09:17:02 +01003227 db_k8scluster = self.db.get_one(
3228 "k8sclusters", {"_id": cluster_id}, fail_on_empty=False
3229 )
tierno626e0152019-11-29 14:16:16 +00003230 if not db_k8scluster:
3231 raise LcmException("K8s cluster {} cannot be found".format(cluster_id))
tierno16f4a4e2020-07-20 09:05:51 +00003232
tierno626e0152019-11-29 14:16:16 +00003233 k8s_id = deep_get(db_k8scluster, ("_admin", cluster_type, "id"))
3234 if not k8s_id:
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003235 if cluster_type == "helm-chart-v3":
3236 try:
3237 # backward compatibility for existing clusters that have not been initialized for helm v3
garciadeblas5697b8b2021-03-24 09:17:02 +01003238 k8s_credentials = yaml.safe_dump(
3239 db_k8scluster.get("credentials")
3240 )
3241 k8s_id, uninstall_sw = await self.k8sclusterhelm3.init_env(
3242 k8s_credentials, reuse_cluster_uuid=cluster_id
3243 )
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003244 db_k8scluster_update = {}
3245 db_k8scluster_update["_admin.helm-chart-v3.error_msg"] = None
3246 db_k8scluster_update["_admin.helm-chart-v3.id"] = k8s_id
garciadeblas5697b8b2021-03-24 09:17:02 +01003247 db_k8scluster_update[
3248 "_admin.helm-chart-v3.created"
3249 ] = uninstall_sw
3250 db_k8scluster_update[
3251 "_admin.helm-chart-v3.operationalState"
3252 ] = "ENABLED"
3253 self.update_db_2(
3254 "k8sclusters", cluster_id, db_k8scluster_update
3255 )
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003256 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01003257 self.logger.error(
3258 logging_text
3259 + "error initializing helm-v3 cluster: {}".format(str(e))
3260 )
3261 raise LcmException(
3262 "K8s cluster '{}' has not been initialized for '{}'".format(
3263 cluster_id, cluster_type
3264 )
3265 )
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003266 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01003267 raise LcmException(
3268 "K8s cluster '{}' has not been initialized for '{}'".format(
3269 cluster_id, cluster_type
3270 )
3271 )
tierno626e0152019-11-29 14:16:16 +00003272 k8scluster_id_2_uuic[cluster_type][cluster_id] = k8s_id
3273 return k8s_id
3274
3275 logging_text += "Deploy kdus: "
tiernoe876f672020-02-13 14:34:48 +00003276 step = ""
calvinosanch9f9c6f22019-11-04 13:37:39 +01003277 try:
tierno626e0152019-11-29 14:16:16 +00003278 db_nsr_update = {"_admin.deployed.K8s": []}
calvinosanch9f9c6f22019-11-04 13:37:39 +01003279 self.update_db_2("nsrs", nsr_id, db_nsr_update)
calvinosanch9f9c6f22019-11-04 13:37:39 +01003280
tierno626e0152019-11-29 14:16:16 +00003281 index = 0
tiernoe876f672020-02-13 14:34:48 +00003282 updated_cluster_list = []
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003283 updated_v3_cluster_list = []
tiernoe876f672020-02-13 14:34:48 +00003284
tierno626e0152019-11-29 14:16:16 +00003285 for vnfr_data in db_vnfrs.values():
David Garciac1fe90a2021-03-31 19:12:02 +02003286 vca_id = self.get_vca_id(vnfr_data, {})
lloretgalleg7c121132020-07-08 07:53:22 +00003287 for kdu_index, kdur in enumerate(get_iterable(vnfr_data, "kdur")):
3288 # Step 0: Prepare and set parameters
bravof922c4172020-11-24 21:21:43 -03003289 desc_params = parse_yaml_strings(kdur.get("additionalParams"))
garciadeblas5697b8b2021-03-24 09:17:02 +01003290 vnfd_id = vnfr_data.get("vnfd-id")
3291 vnfd_with_id = find_in_list(
3292 db_vnfds, lambda vnfd: vnfd["_id"] == vnfd_id
3293 )
3294 kdud = next(
3295 kdud
3296 for kdud in vnfd_with_id["kdu"]
3297 if kdud["name"] == kdur["kdu-name"]
3298 )
tiernode1584f2020-04-07 09:07:33 +00003299 namespace = kdur.get("k8s-namespace")
romeromonser4554a702021-05-28 12:00:08 +02003300 kdu_deployment_name = kdur.get("kdu-deployment-name")
tierno626e0152019-11-29 14:16:16 +00003301 if kdur.get("helm-chart"):
lloretgalleg07e53f52020-12-15 10:54:02 +00003302 kdumodel = kdur["helm-chart"]
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003303 # Default version: helm3, if helm-version is v2 assign v2
3304 k8sclustertype = "helm-chart-v3"
3305 self.logger.debug("kdur: {}".format(kdur))
garciadeblas5697b8b2021-03-24 09:17:02 +01003306 if (
3307 kdur.get("helm-version")
3308 and kdur.get("helm-version") == "v2"
3309 ):
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003310 k8sclustertype = "helm-chart"
tierno626e0152019-11-29 14:16:16 +00003311 elif kdur.get("juju-bundle"):
lloretgalleg07e53f52020-12-15 10:54:02 +00003312 kdumodel = kdur["juju-bundle"]
tiernoe876f672020-02-13 14:34:48 +00003313 k8sclustertype = "juju-bundle"
tierno626e0152019-11-29 14:16:16 +00003314 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01003315 raise LcmException(
3316 "kdu type for kdu='{}.{}' is neither helm-chart nor "
3317 "juju-bundle. Maybe an old NBI version is running".format(
3318 vnfr_data["member-vnf-index-ref"], kdur["kdu-name"]
3319 )
3320 )
quilesjacde94f2020-01-23 10:07:08 +00003321 # check if kdumodel is a file and exists
3322 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01003323 vnfd_with_id = find_in_list(
3324 db_vnfds, lambda vnfd: vnfd["_id"] == vnfd_id
3325 )
3326 storage = deep_get(vnfd_with_id, ("_admin", "storage"))
bravof14af4e72021-11-08 17:18:50 -03003327 if storage: # may be not present if vnfd has not artifacts
tierno51183952020-04-03 15:48:18 +00003328 # path format: /vnfdid/pkkdir/helm-charts|juju-bundles/kdumodel
bravof14af4e72021-11-08 17:18:50 -03003329 if storage["pkg-dir"]:
3330 filename = "{}/{}/{}s/{}".format(
3331 storage["folder"],
3332 storage["pkg-dir"],
3333 k8sclustertype,
3334 kdumodel,
3335 )
3336 else:
3337 filename = "{}/Scripts/{}s/{}".format(
3338 storage["folder"],
3339 k8sclustertype,
3340 kdumodel,
3341 )
garciadeblas5697b8b2021-03-24 09:17:02 +01003342 if self.fs.file_exists(
3343 filename, mode="file"
3344 ) or self.fs.file_exists(filename, mode="dir"):
tierno51183952020-04-03 15:48:18 +00003345 kdumodel = self.fs.path + filename
3346 except (asyncio.TimeoutError, asyncio.CancelledError):
tiernoe876f672020-02-13 14:34:48 +00003347 raise
garciadeblas5697b8b2021-03-24 09:17:02 +01003348 except Exception: # it is not a file
quilesjacde94f2020-01-23 10:07:08 +00003349 pass
lloretgallegedc5f332020-02-20 11:50:50 +01003350
tiernoe876f672020-02-13 14:34:48 +00003351 k8s_cluster_id = kdur["k8s-cluster"]["id"]
garciadeblas5697b8b2021-03-24 09:17:02 +01003352 step = "Synchronize repos for k8s cluster '{}'".format(
3353 k8s_cluster_id
3354 )
tierno16f4a4e2020-07-20 09:05:51 +00003355 cluster_uuid = await _get_cluster_id(k8s_cluster_id, k8sclustertype)
lloretgallegedc5f332020-02-20 11:50:50 +01003356
lloretgalleg7c121132020-07-08 07:53:22 +00003357 # Synchronize repos
garciadeblas5697b8b2021-03-24 09:17:02 +01003358 if (
3359 k8sclustertype == "helm-chart"
3360 and cluster_uuid not in updated_cluster_list
3361 ) or (
3362 k8sclustertype == "helm-chart-v3"
3363 and cluster_uuid not in updated_v3_cluster_list
3364 ):
tiernoe876f672020-02-13 14:34:48 +00003365 del_repo_list, added_repo_dict = await asyncio.ensure_future(
garciadeblas5697b8b2021-03-24 09:17:02 +01003366 self.k8scluster_map[k8sclustertype].synchronize_repos(
3367 cluster_uuid=cluster_uuid
3368 )
3369 )
tiernoe876f672020-02-13 14:34:48 +00003370 if del_repo_list or added_repo_dict:
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003371 if k8sclustertype == "helm-chart":
garciadeblas5697b8b2021-03-24 09:17:02 +01003372 unset = {
3373 "_admin.helm_charts_added." + item: None
3374 for item in del_repo_list
3375 }
3376 updated = {
3377 "_admin.helm_charts_added." + item: name
3378 for item, name in added_repo_dict.items()
3379 }
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003380 updated_cluster_list.append(cluster_uuid)
3381 elif k8sclustertype == "helm-chart-v3":
garciadeblas5697b8b2021-03-24 09:17:02 +01003382 unset = {
3383 "_admin.helm_charts_v3_added." + item: None
3384 for item in del_repo_list
3385 }
3386 updated = {
3387 "_admin.helm_charts_v3_added." + item: name
3388 for item, name in added_repo_dict.items()
3389 }
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003390 updated_v3_cluster_list.append(cluster_uuid)
garciadeblas5697b8b2021-03-24 09:17:02 +01003391 self.logger.debug(
3392 logging_text + "repos synchronized on k8s cluster "
3393 "'{}' to_delete: {}, to_add: {}".format(
3394 k8s_cluster_id, del_repo_list, added_repo_dict
3395 )
3396 )
3397 self.db.set_one(
3398 "k8sclusters",
3399 {"_id": k8s_cluster_id},
3400 updated,
3401 unset=unset,
3402 )
lloretgallegedc5f332020-02-20 11:50:50 +01003403
lloretgalleg7c121132020-07-08 07:53:22 +00003404 # Instantiate kdu
garciadeblas5697b8b2021-03-24 09:17:02 +01003405 step = "Instantiating KDU {}.{} in k8s cluster {}".format(
3406 vnfr_data["member-vnf-index-ref"],
3407 kdur["kdu-name"],
3408 k8s_cluster_id,
3409 )
3410 k8s_instance_info = {
3411 "kdu-instance": None,
3412 "k8scluster-uuid": cluster_uuid,
3413 "k8scluster-type": k8sclustertype,
3414 "member-vnf-index": vnfr_data["member-vnf-index-ref"],
3415 "kdu-name": kdur["kdu-name"],
3416 "kdu-model": kdumodel,
3417 "namespace": namespace,
romeromonser4554a702021-05-28 12:00:08 +02003418 "kdu-deployment-name": kdu_deployment_name,
garciadeblas5697b8b2021-03-24 09:17:02 +01003419 }
tiernob9018152020-04-16 14:18:24 +00003420 db_path = "_admin.deployed.K8s.{}".format(index)
lloretgalleg7c121132020-07-08 07:53:22 +00003421 db_nsr_update[db_path] = k8s_instance_info
tierno626e0152019-11-29 14:16:16 +00003422 self.update_db_2("nsrs", nsr_id, db_nsr_update)
garciadeblas5697b8b2021-03-24 09:17:02 +01003423 vnfd_with_id = find_in_list(
3424 db_vnfds, lambda vnf: vnf["_id"] == vnfd_id
3425 )
tiernoa2143262020-03-27 16:20:40 +00003426 task = asyncio.ensure_future(
garciadeblas5697b8b2021-03-24 09:17:02 +01003427 self._install_kdu(
3428 nsr_id,
3429 db_path,
3430 vnfr_data,
3431 kdu_index,
3432 kdud,
3433 vnfd_with_id,
3434 k8s_instance_info,
3435 k8params=desc_params,
3436 timeout=600,
3437 vca_id=vca_id,
3438 )
3439 )
3440 self.lcm_tasks.register(
3441 "ns",
3442 nsr_id,
3443 nslcmop_id,
3444 "instantiate_KDU-{}".format(index),
3445 task,
3446 )
3447 task_instantiation_info[task] = "Deploying KDU {}".format(
3448 kdur["kdu-name"]
3449 )
tiernoe876f672020-02-13 14:34:48 +00003450
tierno626e0152019-11-29 14:16:16 +00003451 index += 1
quilesjdd799ac2020-01-23 16:31:11 +00003452
tiernoe876f672020-02-13 14:34:48 +00003453 except (LcmException, asyncio.CancelledError):
3454 raise
calvinosanch9f9c6f22019-11-04 13:37:39 +01003455 except Exception as e:
tiernoe876f672020-02-13 14:34:48 +00003456 msg = "Exception {} while {}: {}".format(type(e).__name__, step, e)
3457 if isinstance(e, (N2VCException, DbException)):
3458 self.logger.error(logging_text + msg)
3459 else:
3460 self.logger.critical(logging_text + msg, exc_info=True)
quilesjdd799ac2020-01-23 16:31:11 +00003461 raise LcmException(msg)
calvinosanch9f9c6f22019-11-04 13:37:39 +01003462 finally:
calvinosanch9f9c6f22019-11-04 13:37:39 +01003463 if db_nsr_update:
3464 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernoda6fb102019-11-23 00:36:52 +00003465
garciadeblas5697b8b2021-03-24 09:17:02 +01003466 def _deploy_n2vc(
3467 self,
3468 logging_text,
3469 db_nsr,
3470 db_vnfr,
3471 nslcmop_id,
3472 nsr_id,
3473 nsi_id,
3474 vnfd_id,
3475 vdu_id,
3476 kdu_name,
3477 member_vnf_index,
3478 vdu_index,
3479 vdu_name,
3480 deploy_params,
3481 descriptor_config,
3482 base_folder,
3483 task_instantiation_info,
3484 stage,
3485 ):
quilesj7e13aeb2019-10-08 13:34:55 +02003486 # launch instantiate_N2VC in a asyncio task and register task object
3487 # Look where information of this charm is at database <nsrs>._admin.deployed.VCA
3488 # if not found, create one entry and update database
quilesj7e13aeb2019-10-08 13:34:55 +02003489 # fill db_nsr._admin.deployed.VCA.<index>
tierno588547c2020-07-01 15:30:20 +00003490
garciadeblas5697b8b2021-03-24 09:17:02 +01003491 self.logger.debug(
3492 logging_text + "_deploy_n2vc vnfd_id={}, vdu_id={}".format(vnfd_id, vdu_id)
3493 )
bravof9a256db2021-02-22 18:02:07 -03003494 if "execution-environment-list" in descriptor_config:
3495 ee_list = descriptor_config.get("execution-environment-list", [])
David Garcia9ad54a42021-05-28 12:08:18 +02003496 elif "juju" in descriptor_config:
3497 ee_list = [descriptor_config] # ns charms
tierno588547c2020-07-01 15:30:20 +00003498 else: # other types as script are not supported
3499 ee_list = []
3500
3501 for ee_item in ee_list:
garciadeblas5697b8b2021-03-24 09:17:02 +01003502 self.logger.debug(
3503 logging_text
3504 + "_deploy_n2vc ee_item juju={}, helm={}".format(
3505 ee_item.get("juju"), ee_item.get("helm-chart")
3506 )
3507 )
tiernoa278b842020-07-08 15:33:55 +00003508 ee_descriptor_id = ee_item.get("id")
tierno588547c2020-07-01 15:30:20 +00003509 if ee_item.get("juju"):
garciadeblas5697b8b2021-03-24 09:17:02 +01003510 vca_name = ee_item["juju"].get("charm")
3511 vca_type = (
3512 "lxc_proxy_charm"
3513 if ee_item["juju"].get("charm") is not None
3514 else "native_charm"
3515 )
3516 if ee_item["juju"].get("cloud") == "k8s":
tierno588547c2020-07-01 15:30:20 +00003517 vca_type = "k8s_proxy_charm"
garciadeblas5697b8b2021-03-24 09:17:02 +01003518 elif ee_item["juju"].get("proxy") is False:
tierno588547c2020-07-01 15:30:20 +00003519 vca_type = "native_charm"
3520 elif ee_item.get("helm-chart"):
garciadeblas5697b8b2021-03-24 09:17:02 +01003521 vca_name = ee_item["helm-chart"]
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003522 if ee_item.get("helm-version") and ee_item.get("helm-version") == "v2":
3523 vca_type = "helm"
3524 else:
3525 vca_type = "helm-v3"
tierno588547c2020-07-01 15:30:20 +00003526 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01003527 self.logger.debug(
3528 logging_text + "skipping non juju neither charm configuration"
3529 )
quilesj7e13aeb2019-10-08 13:34:55 +02003530 continue
quilesj3655ae02019-12-12 16:08:35 +00003531
tierno588547c2020-07-01 15:30:20 +00003532 vca_index = -1
garciadeblas5697b8b2021-03-24 09:17:02 +01003533 for vca_index, vca_deployed in enumerate(
3534 db_nsr["_admin"]["deployed"]["VCA"]
3535 ):
tierno588547c2020-07-01 15:30:20 +00003536 if not vca_deployed:
3537 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01003538 if (
3539 vca_deployed.get("member-vnf-index") == member_vnf_index
3540 and vca_deployed.get("vdu_id") == vdu_id
3541 and vca_deployed.get("kdu_name") == kdu_name
3542 and vca_deployed.get("vdu_count_index", 0) == vdu_index
3543 and vca_deployed.get("ee_descriptor_id") == ee_descriptor_id
3544 ):
tierno588547c2020-07-01 15:30:20 +00003545 break
3546 else:
3547 # not found, create one.
garciadeblas5697b8b2021-03-24 09:17:02 +01003548 target = (
3549 "ns" if not member_vnf_index else "vnf/{}".format(member_vnf_index)
3550 )
tiernoa278b842020-07-08 15:33:55 +00003551 if vdu_id:
3552 target += "/vdu/{}/{}".format(vdu_id, vdu_index or 0)
3553 elif kdu_name:
3554 target += "/kdu/{}".format(kdu_name)
tierno588547c2020-07-01 15:30:20 +00003555 vca_deployed = {
tiernoa278b842020-07-08 15:33:55 +00003556 "target_element": target,
3557 # ^ target_element will replace member-vnf-index, kdu_name, vdu_id ... in a single string
tierno588547c2020-07-01 15:30:20 +00003558 "member-vnf-index": member_vnf_index,
3559 "vdu_id": vdu_id,
3560 "kdu_name": kdu_name,
3561 "vdu_count_index": vdu_index,
3562 "operational-status": "init", # TODO revise
3563 "detailed-status": "", # TODO revise
garciadeblas5697b8b2021-03-24 09:17:02 +01003564 "step": "initial-deploy", # TODO revise
tierno588547c2020-07-01 15:30:20 +00003565 "vnfd_id": vnfd_id,
3566 "vdu_name": vdu_name,
tiernoa278b842020-07-08 15:33:55 +00003567 "type": vca_type,
garciadeblas5697b8b2021-03-24 09:17:02 +01003568 "ee_descriptor_id": ee_descriptor_id,
tierno588547c2020-07-01 15:30:20 +00003569 }
3570 vca_index += 1
quilesj3655ae02019-12-12 16:08:35 +00003571
tierno588547c2020-07-01 15:30:20 +00003572 # create VCA and configurationStatus in db
3573 db_dict = {
3574 "_admin.deployed.VCA.{}".format(vca_index): vca_deployed,
garciadeblas5697b8b2021-03-24 09:17:02 +01003575 "configurationStatus.{}".format(vca_index): dict(),
tierno588547c2020-07-01 15:30:20 +00003576 }
3577 self.update_db_2("nsrs", nsr_id, db_dict)
quilesj7e13aeb2019-10-08 13:34:55 +02003578
tierno588547c2020-07-01 15:30:20 +00003579 db_nsr["_admin"]["deployed"]["VCA"].append(vca_deployed)
3580
bravof922c4172020-11-24 21:21:43 -03003581 self.logger.debug("N2VC > NSR_ID > {}".format(nsr_id))
3582 self.logger.debug("N2VC > DB_NSR > {}".format(db_nsr))
3583 self.logger.debug("N2VC > VCA_DEPLOYED > {}".format(vca_deployed))
3584
tierno588547c2020-07-01 15:30:20 +00003585 # Launch task
3586 task_n2vc = asyncio.ensure_future(
3587 self.instantiate_N2VC(
3588 logging_text=logging_text,
3589 vca_index=vca_index,
3590 nsi_id=nsi_id,
3591 db_nsr=db_nsr,
3592 db_vnfr=db_vnfr,
3593 vdu_id=vdu_id,
3594 kdu_name=kdu_name,
3595 vdu_index=vdu_index,
3596 deploy_params=deploy_params,
3597 config_descriptor=descriptor_config,
3598 base_folder=base_folder,
3599 nslcmop_id=nslcmop_id,
3600 stage=stage,
3601 vca_type=vca_type,
tiernob996d942020-07-03 14:52:28 +00003602 vca_name=vca_name,
garciadeblas5697b8b2021-03-24 09:17:02 +01003603 ee_config_descriptor=ee_item,
tierno588547c2020-07-01 15:30:20 +00003604 )
quilesj7e13aeb2019-10-08 13:34:55 +02003605 )
garciadeblas5697b8b2021-03-24 09:17:02 +01003606 self.lcm_tasks.register(
3607 "ns",
3608 nsr_id,
3609 nslcmop_id,
3610 "instantiate_N2VC-{}".format(vca_index),
3611 task_n2vc,
3612 )
3613 task_instantiation_info[
3614 task_n2vc
3615 ] = self.task_name_deploy_vca + " {}.{}".format(
3616 member_vnf_index or "", vdu_id or ""
3617 )
tiernobaa51102018-12-14 13:16:18 +00003618
tiernoc9556972019-07-05 15:25:25 +00003619 @staticmethod
kuuse0ca67472019-05-13 15:59:27 +02003620 def _create_nslcmop(nsr_id, operation, params):
3621 """
3622 Creates a ns-lcm-opp content to be stored at database.
3623 :param nsr_id: internal id of the instance
3624 :param operation: instantiate, terminate, scale, action, ...
3625 :param params: user parameters for the operation
3626 :return: dictionary following SOL005 format
3627 """
3628 # Raise exception if invalid arguments
3629 if not (nsr_id and operation and params):
3630 raise LcmException(
garciadeblas5697b8b2021-03-24 09:17:02 +01003631 "Parameters 'nsr_id', 'operation' and 'params' needed to create primitive not provided"
3632 )
kuuse0ca67472019-05-13 15:59:27 +02003633 now = time()
3634 _id = str(uuid4())
3635 nslcmop = {
3636 "id": _id,
3637 "_id": _id,
3638 # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
3639 "operationState": "PROCESSING",
3640 "statusEnteredTime": now,
3641 "nsInstanceId": nsr_id,
3642 "lcmOperationType": operation,
3643 "startTime": now,
3644 "isAutomaticInvocation": False,
3645 "operationParams": params,
3646 "isCancelPending": False,
3647 "links": {
3648 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
3649 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01003650 },
kuuse0ca67472019-05-13 15:59:27 +02003651 }
3652 return nslcmop
3653
calvinosanch9f9c6f22019-11-04 13:37:39 +01003654 def _format_additional_params(self, params):
tierno626e0152019-11-29 14:16:16 +00003655 params = params or {}
calvinosanch9f9c6f22019-11-04 13:37:39 +01003656 for key, value in params.items():
3657 if str(value).startswith("!!yaml "):
3658 params[key] = yaml.safe_load(value[7:])
calvinosanch9f9c6f22019-11-04 13:37:39 +01003659 return params
3660
kuuse8b998e42019-07-30 15:22:16 +02003661 def _get_terminate_primitive_params(self, seq, vnf_index):
garciadeblas5697b8b2021-03-24 09:17:02 +01003662 primitive = seq.get("name")
kuuse8b998e42019-07-30 15:22:16 +02003663 primitive_params = {}
3664 params = {
3665 "member_vnf_index": vnf_index,
3666 "primitive": primitive,
3667 "primitive_params": primitive_params,
3668 }
3669 desc_params = {}
3670 return self._map_primitive_params(seq, params, desc_params)
3671
kuuseac3a8882019-10-03 10:48:06 +02003672 # sub-operations
3673
tierno51183952020-04-03 15:48:18 +00003674 def _retry_or_skip_suboperation(self, db_nslcmop, op_index):
garciadeblas5697b8b2021-03-24 09:17:02 +01003675 op = deep_get(db_nslcmop, ("_admin", "operations"), [])[op_index]
3676 if op.get("operationState") == "COMPLETED":
kuuseac3a8882019-10-03 10:48:06 +02003677 # b. Skip sub-operation
3678 # _ns_execute_primitive() or RO.create_action() will NOT be executed
3679 return self.SUBOPERATION_STATUS_SKIP
3680 else:
tierno7c4e24c2020-05-13 08:41:35 +00003681 # c. retry executing sub-operation
kuuseac3a8882019-10-03 10:48:06 +02003682 # The sub-operation exists, and operationState != 'COMPLETED'
tierno7c4e24c2020-05-13 08:41:35 +00003683 # Update operationState = 'PROCESSING' to indicate a retry.
garciadeblas5697b8b2021-03-24 09:17:02 +01003684 operationState = "PROCESSING"
3685 detailed_status = "In progress"
kuuseac3a8882019-10-03 10:48:06 +02003686 self._update_suboperation_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01003687 db_nslcmop, op_index, operationState, detailed_status
3688 )
kuuseac3a8882019-10-03 10:48:06 +02003689 # Return the sub-operation index
3690 # _ns_execute_primitive() or RO.create_action() will be called from scale()
3691 # with arguments extracted from the sub-operation
3692 return op_index
3693
3694 # Find a sub-operation where all keys in a matching dictionary must match
3695 # Returns the index of the matching sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if no match
3696 def _find_suboperation(self, db_nslcmop, match):
tierno7c4e24c2020-05-13 08:41:35 +00003697 if db_nslcmop and match:
garciadeblas5697b8b2021-03-24 09:17:02 +01003698 op_list = db_nslcmop.get("_admin", {}).get("operations", [])
kuuseac3a8882019-10-03 10:48:06 +02003699 for i, op in enumerate(op_list):
3700 if all(op.get(k) == match[k] for k in match):
3701 return i
3702 return self.SUBOPERATION_STATUS_NOT_FOUND
3703
3704 # Update status for a sub-operation given its index
garciadeblas5697b8b2021-03-24 09:17:02 +01003705 def _update_suboperation_status(
3706 self, db_nslcmop, op_index, operationState, detailed_status
3707 ):
kuuseac3a8882019-10-03 10:48:06 +02003708 # Update DB for HA tasks
garciadeblas5697b8b2021-03-24 09:17:02 +01003709 q_filter = {"_id": db_nslcmop["_id"]}
3710 update_dict = {
3711 "_admin.operations.{}.operationState".format(op_index): operationState,
3712 "_admin.operations.{}.detailed-status".format(op_index): detailed_status,
3713 }
3714 self.db.set_one(
3715 "nslcmops", q_filter=q_filter, update_dict=update_dict, fail_on_empty=False
3716 )
kuuseac3a8882019-10-03 10:48:06 +02003717
3718 # Add sub-operation, return the index of the added sub-operation
3719 # Optionally, set operationState, detailed-status, and operationType
3720 # Status and type are currently set for 'scale' sub-operations:
3721 # 'operationState' : 'PROCESSING' | 'COMPLETED' | 'FAILED'
3722 # 'detailed-status' : status message
3723 # 'operationType': may be any type, in the case of scaling: 'PRE-SCALE' | 'POST-SCALE'
3724 # Status and operation type are currently only used for 'scale', but NOT for 'terminate' sub-operations.
garciadeblas5697b8b2021-03-24 09:17:02 +01003725 def _add_suboperation(
3726 self,
3727 db_nslcmop,
3728 vnf_index,
3729 vdu_id,
3730 vdu_count_index,
3731 vdu_name,
3732 primitive,
3733 mapped_primitive_params,
3734 operationState=None,
3735 detailed_status=None,
3736 operationType=None,
3737 RO_nsr_id=None,
3738 RO_scaling_info=None,
3739 ):
tiernoe876f672020-02-13 14:34:48 +00003740 if not db_nslcmop:
kuuseac3a8882019-10-03 10:48:06 +02003741 return self.SUBOPERATION_STATUS_NOT_FOUND
3742 # Get the "_admin.operations" list, if it exists
garciadeblas5697b8b2021-03-24 09:17:02 +01003743 db_nslcmop_admin = db_nslcmop.get("_admin", {})
3744 op_list = db_nslcmop_admin.get("operations")
kuuseac3a8882019-10-03 10:48:06 +02003745 # Create or append to the "_admin.operations" list
garciadeblas5697b8b2021-03-24 09:17:02 +01003746 new_op = {
3747 "member_vnf_index": vnf_index,
3748 "vdu_id": vdu_id,
3749 "vdu_count_index": vdu_count_index,
3750 "primitive": primitive,
3751 "primitive_params": mapped_primitive_params,
3752 }
kuuseac3a8882019-10-03 10:48:06 +02003753 if operationState:
garciadeblas5697b8b2021-03-24 09:17:02 +01003754 new_op["operationState"] = operationState
kuuseac3a8882019-10-03 10:48:06 +02003755 if detailed_status:
garciadeblas5697b8b2021-03-24 09:17:02 +01003756 new_op["detailed-status"] = detailed_status
kuuseac3a8882019-10-03 10:48:06 +02003757 if operationType:
garciadeblas5697b8b2021-03-24 09:17:02 +01003758 new_op["lcmOperationType"] = operationType
kuuseac3a8882019-10-03 10:48:06 +02003759 if RO_nsr_id:
garciadeblas5697b8b2021-03-24 09:17:02 +01003760 new_op["RO_nsr_id"] = RO_nsr_id
kuuseac3a8882019-10-03 10:48:06 +02003761 if RO_scaling_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01003762 new_op["RO_scaling_info"] = RO_scaling_info
kuuseac3a8882019-10-03 10:48:06 +02003763 if not op_list:
3764 # No existing operations, create key 'operations' with current operation as first list element
garciadeblas5697b8b2021-03-24 09:17:02 +01003765 db_nslcmop_admin.update({"operations": [new_op]})
3766 op_list = db_nslcmop_admin.get("operations")
kuuseac3a8882019-10-03 10:48:06 +02003767 else:
3768 # Existing operations, append operation to list
3769 op_list.append(new_op)
kuuse8b998e42019-07-30 15:22:16 +02003770
garciadeblas5697b8b2021-03-24 09:17:02 +01003771 db_nslcmop_update = {"_admin.operations": op_list}
3772 self.update_db_2("nslcmops", db_nslcmop["_id"], db_nslcmop_update)
kuuseac3a8882019-10-03 10:48:06 +02003773 op_index = len(op_list) - 1
3774 return op_index
3775
3776 # Helper methods for scale() sub-operations
3777
3778 # pre-scale/post-scale:
3779 # Check for 3 different cases:
3780 # a. New: First time execution, return SUBOPERATION_STATUS_NEW
3781 # b. Skip: Existing sub-operation exists, operationState == 'COMPLETED', return SUBOPERATION_STATUS_SKIP
tierno7c4e24c2020-05-13 08:41:35 +00003782 # c. retry: Existing sub-operation exists, operationState != 'COMPLETED', return op_index to re-execute
garciadeblas5697b8b2021-03-24 09:17:02 +01003783 def _check_or_add_scale_suboperation(
3784 self,
3785 db_nslcmop,
3786 vnf_index,
3787 vnf_config_primitive,
3788 primitive_params,
3789 operationType,
3790 RO_nsr_id=None,
3791 RO_scaling_info=None,
3792 ):
kuuseac3a8882019-10-03 10:48:06 +02003793 # Find this sub-operation
tierno7c4e24c2020-05-13 08:41:35 +00003794 if RO_nsr_id and RO_scaling_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01003795 operationType = "SCALE-RO"
kuuseac3a8882019-10-03 10:48:06 +02003796 match = {
garciadeblas5697b8b2021-03-24 09:17:02 +01003797 "member_vnf_index": vnf_index,
3798 "RO_nsr_id": RO_nsr_id,
3799 "RO_scaling_info": RO_scaling_info,
kuuseac3a8882019-10-03 10:48:06 +02003800 }
3801 else:
3802 match = {
garciadeblas5697b8b2021-03-24 09:17:02 +01003803 "member_vnf_index": vnf_index,
3804 "primitive": vnf_config_primitive,
3805 "primitive_params": primitive_params,
3806 "lcmOperationType": operationType,
kuuseac3a8882019-10-03 10:48:06 +02003807 }
3808 op_index = self._find_suboperation(db_nslcmop, match)
tierno51183952020-04-03 15:48:18 +00003809 if op_index == self.SUBOPERATION_STATUS_NOT_FOUND:
kuuseac3a8882019-10-03 10:48:06 +02003810 # a. New sub-operation
3811 # The sub-operation does not exist, add it.
3812 # _ns_execute_primitive() will be called from scale() as usual, with non-modified arguments
3813 # The following parameters are set to None for all kind of scaling:
3814 vdu_id = None
3815 vdu_count_index = None
3816 vdu_name = None
tierno51183952020-04-03 15:48:18 +00003817 if RO_nsr_id and RO_scaling_info:
kuuseac3a8882019-10-03 10:48:06 +02003818 vnf_config_primitive = None
3819 primitive_params = None
3820 else:
3821 RO_nsr_id = None
3822 RO_scaling_info = None
3823 # Initial status for sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01003824 operationState = "PROCESSING"
3825 detailed_status = "In progress"
kuuseac3a8882019-10-03 10:48:06 +02003826 # Add sub-operation for pre/post-scaling (zero or more operations)
garciadeblas5697b8b2021-03-24 09:17:02 +01003827 self._add_suboperation(
3828 db_nslcmop,
3829 vnf_index,
3830 vdu_id,
3831 vdu_count_index,
3832 vdu_name,
3833 vnf_config_primitive,
3834 primitive_params,
3835 operationState,
3836 detailed_status,
3837 operationType,
3838 RO_nsr_id,
3839 RO_scaling_info,
3840 )
kuuseac3a8882019-10-03 10:48:06 +02003841 return self.SUBOPERATION_STATUS_NEW
3842 else:
3843 # Return either SUBOPERATION_STATUS_SKIP (operationState == 'COMPLETED'),
3844 # or op_index (operationState != 'COMPLETED')
tierno51183952020-04-03 15:48:18 +00003845 return self._retry_or_skip_suboperation(db_nslcmop, op_index)
kuuseac3a8882019-10-03 10:48:06 +02003846
preethika.pdf7d8e02019-12-10 13:10:48 +00003847 # Function to return execution_environment id
3848
3849 def _get_ee_id(self, vnf_index, vdu_id, vca_deployed_list):
tiernoe876f672020-02-13 14:34:48 +00003850 # TODO vdu_index_count
preethika.pdf7d8e02019-12-10 13:10:48 +00003851 for vca in vca_deployed_list:
3852 if vca["member-vnf-index"] == vnf_index and vca["vdu_id"] == vdu_id:
3853 return vca["ee_id"]
3854
David Garciac1fe90a2021-03-31 19:12:02 +02003855 async def destroy_N2VC(
3856 self,
3857 logging_text,
3858 db_nslcmop,
3859 vca_deployed,
3860 config_descriptor,
3861 vca_index,
3862 destroy_ee=True,
3863 exec_primitives=True,
3864 scaling_in=False,
3865 vca_id: str = None,
3866 ):
tiernoe876f672020-02-13 14:34:48 +00003867 """
3868 Execute the terminate primitives and destroy the execution environment (if destroy_ee=False
3869 :param logging_text:
3870 :param db_nslcmop:
3871 :param vca_deployed: Dictionary of deployment info at db_nsr._admin.depoloyed.VCA.<INDEX>
3872 :param config_descriptor: Configuration descriptor of the NSD, VNFD, VNFD.vdu or VNFD.kdu
3873 :param vca_index: index in the database _admin.deployed.VCA
3874 :param destroy_ee: False to do not destroy, because it will be destroyed all of then at once
tierno588547c2020-07-01 15:30:20 +00003875 :param exec_primitives: False to do not execute terminate primitives, because the config is not completed or has
3876 not executed properly
aktas13251562021-02-12 22:19:10 +03003877 :param scaling_in: True destroys the application, False destroys the model
tiernoe876f672020-02-13 14:34:48 +00003878 :return: None or exception
3879 """
tiernoe876f672020-02-13 14:34:48 +00003880
tierno588547c2020-07-01 15:30:20 +00003881 self.logger.debug(
garciadeblas5697b8b2021-03-24 09:17:02 +01003882 logging_text
3883 + " vca_index: {}, vca_deployed: {}, config_descriptor: {}, destroy_ee: {}".format(
tierno588547c2020-07-01 15:30:20 +00003884 vca_index, vca_deployed, config_descriptor, destroy_ee
3885 )
3886 )
3887
3888 vca_type = vca_deployed.get("type", "lxc_proxy_charm")
3889
3890 # execute terminate_primitives
3891 if exec_primitives:
bravof922c4172020-11-24 21:21:43 -03003892 terminate_primitives = get_ee_sorted_terminate_config_primitive_list(
garciadeblas5697b8b2021-03-24 09:17:02 +01003893 config_descriptor.get("terminate-config-primitive"),
3894 vca_deployed.get("ee_descriptor_id"),
3895 )
tierno588547c2020-07-01 15:30:20 +00003896 vdu_id = vca_deployed.get("vdu_id")
3897 vdu_count_index = vca_deployed.get("vdu_count_index")
3898 vdu_name = vca_deployed.get("vdu_name")
3899 vnf_index = vca_deployed.get("member-vnf-index")
3900 if terminate_primitives and vca_deployed.get("needed_terminate"):
tierno588547c2020-07-01 15:30:20 +00003901 for seq in terminate_primitives:
3902 # For each sequence in list, get primitive and call _ns_execute_primitive()
3903 step = "Calling terminate action for vnf_member_index={} primitive={}".format(
garciadeblas5697b8b2021-03-24 09:17:02 +01003904 vnf_index, seq.get("name")
3905 )
tierno588547c2020-07-01 15:30:20 +00003906 self.logger.debug(logging_text + step)
3907 # Create the primitive for each sequence, i.e. "primitive": "touch"
garciadeblas5697b8b2021-03-24 09:17:02 +01003908 primitive = seq.get("name")
3909 mapped_primitive_params = self._get_terminate_primitive_params(
3910 seq, vnf_index
3911 )
tierno588547c2020-07-01 15:30:20 +00003912
3913 # Add sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01003914 self._add_suboperation(
3915 db_nslcmop,
3916 vnf_index,
3917 vdu_id,
3918 vdu_count_index,
3919 vdu_name,
3920 primitive,
3921 mapped_primitive_params,
3922 )
tierno588547c2020-07-01 15:30:20 +00003923 # Sub-operations: Call _ns_execute_primitive() instead of action()
3924 try:
David Garciac1fe90a2021-03-31 19:12:02 +02003925 result, result_detail = await self._ns_execute_primitive(
garciadeblas5697b8b2021-03-24 09:17:02 +01003926 vca_deployed["ee_id"],
3927 primitive,
David Garciac1fe90a2021-03-31 19:12:02 +02003928 mapped_primitive_params,
3929 vca_type=vca_type,
3930 vca_id=vca_id,
3931 )
tierno588547c2020-07-01 15:30:20 +00003932 except LcmException:
3933 # this happens when VCA is not deployed. In this case it is not needed to terminate
3934 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01003935 result_ok = ["COMPLETED", "PARTIALLY_COMPLETED"]
tierno588547c2020-07-01 15:30:20 +00003936 if result not in result_ok:
garciadeblas5697b8b2021-03-24 09:17:02 +01003937 raise LcmException(
3938 "terminate_primitive {} for vnf_member_index={} fails with "
3939 "error {}".format(seq.get("name"), vnf_index, result_detail)
3940 )
tierno588547c2020-07-01 15:30:20 +00003941 # set that this VCA do not need terminated
garciadeblas5697b8b2021-03-24 09:17:02 +01003942 db_update_entry = "_admin.deployed.VCA.{}.needed_terminate".format(
3943 vca_index
3944 )
3945 self.update_db_2(
3946 "nsrs", db_nslcmop["nsInstanceId"], {db_update_entry: False}
3947 )
tiernoe876f672020-02-13 14:34:48 +00003948
tiernob996d942020-07-03 14:52:28 +00003949 if vca_deployed.get("prometheus_jobs") and self.prometheus:
3950 await self.prometheus.update(remove_jobs=vca_deployed["prometheus_jobs"])
3951
tiernoe876f672020-02-13 14:34:48 +00003952 if destroy_ee:
David Garciac1fe90a2021-03-31 19:12:02 +02003953 await self.vca_map[vca_type].delete_execution_environment(
3954 vca_deployed["ee_id"],
3955 scaling_in=scaling_in,
aktas98488ed2021-07-29 17:42:49 +03003956 vca_type=vca_type,
David Garciac1fe90a2021-03-31 19:12:02 +02003957 vca_id=vca_id,
3958 )
kuuse0ca67472019-05-13 15:59:27 +02003959
David Garciac1fe90a2021-03-31 19:12:02 +02003960 async def _delete_all_N2VC(self, db_nsr: dict, vca_id: str = None):
garciadeblas5697b8b2021-03-24 09:17:02 +01003961 self._write_all_config_status(db_nsr=db_nsr, status="TERMINATING")
tierno51183952020-04-03 15:48:18 +00003962 namespace = "." + db_nsr["_id"]
tiernof59ad6c2020-04-08 12:50:52 +00003963 try:
David Garciac1fe90a2021-03-31 19:12:02 +02003964 await self.n2vc.delete_namespace(
3965 namespace=namespace,
3966 total_timeout=self.timeout_charm_delete,
3967 vca_id=vca_id,
3968 )
tiernof59ad6c2020-04-08 12:50:52 +00003969 except N2VCNotFound: # already deleted. Skip
3970 pass
garciadeblas5697b8b2021-03-24 09:17:02 +01003971 self._write_all_config_status(db_nsr=db_nsr, status="DELETED")
quilesj3655ae02019-12-12 16:08:35 +00003972
garciadeblas5697b8b2021-03-24 09:17:02 +01003973 async def _terminate_RO(
3974 self, logging_text, nsr_deployed, nsr_id, nslcmop_id, stage
3975 ):
tiernoe876f672020-02-13 14:34:48 +00003976 """
3977 Terminates a deployment from RO
3978 :param logging_text:
3979 :param nsr_deployed: db_nsr._admin.deployed
3980 :param nsr_id:
3981 :param nslcmop_id:
3982 :param stage: list of string with the content to write on db_nslcmop.detailed-status.
3983 this method will update only the index 2, but it will write on database the concatenated content of the list
3984 :return:
3985 """
3986 db_nsr_update = {}
3987 failed_detail = []
3988 ro_nsr_id = ro_delete_action = None
3989 if nsr_deployed and nsr_deployed.get("RO"):
3990 ro_nsr_id = nsr_deployed["RO"].get("nsr_id")
3991 ro_delete_action = nsr_deployed["RO"].get("nsr_delete_action_id")
3992 try:
3993 if ro_nsr_id:
3994 stage[2] = "Deleting ns from VIM."
3995 db_nsr_update["detailed-status"] = " ".join(stage)
3996 self._write_op_status(nslcmop_id, stage)
3997 self.logger.debug(logging_text + stage[2])
3998 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3999 self._write_op_status(nslcmop_id, stage)
4000 desc = await self.RO.delete("ns", ro_nsr_id)
4001 ro_delete_action = desc["action_id"]
garciadeblas5697b8b2021-03-24 09:17:02 +01004002 db_nsr_update[
4003 "_admin.deployed.RO.nsr_delete_action_id"
4004 ] = ro_delete_action
tiernoe876f672020-02-13 14:34:48 +00004005 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
4006 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
4007 if ro_delete_action:
4008 # wait until NS is deleted from VIM
4009 stage[2] = "Waiting ns deleted from VIM."
4010 detailed_status_old = None
garciadeblas5697b8b2021-03-24 09:17:02 +01004011 self.logger.debug(
4012 logging_text
4013 + stage[2]
4014 + " RO_id={} ro_delete_action={}".format(
4015 ro_nsr_id, ro_delete_action
4016 )
4017 )
tiernoe876f672020-02-13 14:34:48 +00004018 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4019 self._write_op_status(nslcmop_id, stage)
kuused124bfe2019-06-18 12:09:24 +02004020
tiernoe876f672020-02-13 14:34:48 +00004021 delete_timeout = 20 * 60 # 20 minutes
4022 while delete_timeout > 0:
4023 desc = await self.RO.show(
4024 "ns",
4025 item_id_name=ro_nsr_id,
4026 extra_item="action",
garciadeblas5697b8b2021-03-24 09:17:02 +01004027 extra_item_id=ro_delete_action,
4028 )
tiernoe876f672020-02-13 14:34:48 +00004029
4030 # deploymentStatus
4031 self._on_update_ro_db(nsrs_id=nsr_id, ro_descriptor=desc)
4032
4033 ns_status, ns_status_info = self.RO.check_action_status(desc)
4034 if ns_status == "ERROR":
4035 raise ROclient.ROClientException(ns_status_info)
4036 elif ns_status == "BUILD":
4037 stage[2] = "Deleting from VIM {}".format(ns_status_info)
4038 elif ns_status == "ACTIVE":
4039 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
4040 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
4041 break
4042 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004043 assert (
4044 False
4045 ), "ROclient.check_action_status returns unknown {}".format(
4046 ns_status
4047 )
tiernoe876f672020-02-13 14:34:48 +00004048 if stage[2] != detailed_status_old:
4049 detailed_status_old = stage[2]
4050 db_nsr_update["detailed-status"] = " ".join(stage)
4051 self._write_op_status(nslcmop_id, stage)
4052 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4053 await asyncio.sleep(5, loop=self.loop)
4054 delete_timeout -= 5
4055 else: # delete_timeout <= 0:
garciadeblas5697b8b2021-03-24 09:17:02 +01004056 raise ROclient.ROClientException(
4057 "Timeout waiting ns deleted from VIM"
4058 )
tiernoe876f672020-02-13 14:34:48 +00004059
4060 except Exception as e:
4061 self.update_db_2("nsrs", nsr_id, db_nsr_update)
garciadeblas5697b8b2021-03-24 09:17:02 +01004062 if (
4063 isinstance(e, ROclient.ROClientException) and e.http_code == 404
4064 ): # not found
tiernoe876f672020-02-13 14:34:48 +00004065 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
4066 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
4067 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
garciadeblas5697b8b2021-03-24 09:17:02 +01004068 self.logger.debug(
4069 logging_text + "RO_ns_id={} already deleted".format(ro_nsr_id)
4070 )
4071 elif (
4072 isinstance(e, ROclient.ROClientException) and e.http_code == 409
4073 ): # conflict
tiernoa2143262020-03-27 16:20:40 +00004074 failed_detail.append("delete conflict: {}".format(e))
garciadeblas5697b8b2021-03-24 09:17:02 +01004075 self.logger.debug(
4076 logging_text
4077 + "RO_ns_id={} delete conflict: {}".format(ro_nsr_id, e)
4078 )
tiernoe876f672020-02-13 14:34:48 +00004079 else:
tiernoa2143262020-03-27 16:20:40 +00004080 failed_detail.append("delete error: {}".format(e))
garciadeblas5697b8b2021-03-24 09:17:02 +01004081 self.logger.error(
4082 logging_text + "RO_ns_id={} delete error: {}".format(ro_nsr_id, e)
4083 )
tiernoe876f672020-02-13 14:34:48 +00004084
4085 # Delete nsd
4086 if not failed_detail and deep_get(nsr_deployed, ("RO", "nsd_id")):
4087 ro_nsd_id = nsr_deployed["RO"]["nsd_id"]
4088 try:
4089 stage[2] = "Deleting nsd from RO."
4090 db_nsr_update["detailed-status"] = " ".join(stage)
4091 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4092 self._write_op_status(nslcmop_id, stage)
4093 await self.RO.delete("nsd", ro_nsd_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01004094 self.logger.debug(
4095 logging_text + "ro_nsd_id={} deleted".format(ro_nsd_id)
4096 )
tiernoe876f672020-02-13 14:34:48 +00004097 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
4098 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01004099 if (
4100 isinstance(e, ROclient.ROClientException) and e.http_code == 404
4101 ): # not found
tiernoe876f672020-02-13 14:34:48 +00004102 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
garciadeblas5697b8b2021-03-24 09:17:02 +01004103 self.logger.debug(
4104 logging_text + "ro_nsd_id={} already deleted".format(ro_nsd_id)
4105 )
4106 elif (
4107 isinstance(e, ROclient.ROClientException) and e.http_code == 409
4108 ): # conflict
4109 failed_detail.append(
4110 "ro_nsd_id={} delete conflict: {}".format(ro_nsd_id, e)
4111 )
tiernoe876f672020-02-13 14:34:48 +00004112 self.logger.debug(logging_text + failed_detail[-1])
4113 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004114 failed_detail.append(
4115 "ro_nsd_id={} delete error: {}".format(ro_nsd_id, e)
4116 )
tiernoe876f672020-02-13 14:34:48 +00004117 self.logger.error(logging_text + failed_detail[-1])
4118
4119 if not failed_detail and deep_get(nsr_deployed, ("RO", "vnfd")):
4120 for index, vnf_deployed in enumerate(nsr_deployed["RO"]["vnfd"]):
4121 if not vnf_deployed or not vnf_deployed["id"]:
4122 continue
4123 try:
4124 ro_vnfd_id = vnf_deployed["id"]
garciadeblas5697b8b2021-03-24 09:17:02 +01004125 stage[
4126 2
4127 ] = "Deleting member_vnf_index={} ro_vnfd_id={} from RO.".format(
4128 vnf_deployed["member-vnf-index"], ro_vnfd_id
4129 )
tiernoe876f672020-02-13 14:34:48 +00004130 db_nsr_update["detailed-status"] = " ".join(stage)
4131 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4132 self._write_op_status(nslcmop_id, stage)
4133 await self.RO.delete("vnfd", ro_vnfd_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01004134 self.logger.debug(
4135 logging_text + "ro_vnfd_id={} deleted".format(ro_vnfd_id)
4136 )
tiernoe876f672020-02-13 14:34:48 +00004137 db_nsr_update["_admin.deployed.RO.vnfd.{}.id".format(index)] = None
4138 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01004139 if (
4140 isinstance(e, ROclient.ROClientException) and e.http_code == 404
4141 ): # not found
4142 db_nsr_update[
4143 "_admin.deployed.RO.vnfd.{}.id".format(index)
4144 ] = None
4145 self.logger.debug(
4146 logging_text
4147 + "ro_vnfd_id={} already deleted ".format(ro_vnfd_id)
4148 )
4149 elif (
4150 isinstance(e, ROclient.ROClientException) and e.http_code == 409
4151 ): # conflict
4152 failed_detail.append(
4153 "ro_vnfd_id={} delete conflict: {}".format(ro_vnfd_id, e)
4154 )
tiernoe876f672020-02-13 14:34:48 +00004155 self.logger.debug(logging_text + failed_detail[-1])
4156 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004157 failed_detail.append(
4158 "ro_vnfd_id={} delete error: {}".format(ro_vnfd_id, e)
4159 )
tiernoe876f672020-02-13 14:34:48 +00004160 self.logger.error(logging_text + failed_detail[-1])
4161
tiernoa2143262020-03-27 16:20:40 +00004162 if failed_detail:
4163 stage[2] = "Error deleting from VIM"
4164 else:
4165 stage[2] = "Deleted from VIM"
tiernoe876f672020-02-13 14:34:48 +00004166 db_nsr_update["detailed-status"] = " ".join(stage)
4167 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4168 self._write_op_status(nslcmop_id, stage)
4169
4170 if failed_detail:
tiernoa2143262020-03-27 16:20:40 +00004171 raise LcmException("; ".join(failed_detail))
tiernoe876f672020-02-13 14:34:48 +00004172
4173 async def terminate(self, nsr_id, nslcmop_id):
kuused124bfe2019-06-18 12:09:24 +02004174 # Try to lock HA task here
garciadeblas5697b8b2021-03-24 09:17:02 +01004175 task_is_locked_by_me = self.lcm_tasks.lock_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02004176 if not task_is_locked_by_me:
4177 return
4178
tierno59d22d22018-09-25 18:10:19 +02004179 logging_text = "Task ns={} terminate={} ".format(nsr_id, nslcmop_id)
4180 self.logger.debug(logging_text + "Enter")
tiernoe876f672020-02-13 14:34:48 +00004181 timeout_ns_terminate = self.timeout_ns_terminate
tierno59d22d22018-09-25 18:10:19 +02004182 db_nsr = None
4183 db_nslcmop = None
tiernoa17d4f42020-04-28 09:59:23 +00004184 operation_params = None
tierno59d22d22018-09-25 18:10:19 +02004185 exc = None
garciadeblas5697b8b2021-03-24 09:17:02 +01004186 error_list = [] # annotates all failed error messages
tierno59d22d22018-09-25 18:10:19 +02004187 db_nslcmop_update = {}
tiernoc2564fe2019-01-28 16:18:56 +00004188 autoremove = False # autoremove after terminated
tiernoe876f672020-02-13 14:34:48 +00004189 tasks_dict_info = {}
4190 db_nsr_update = {}
garciadeblas5697b8b2021-03-24 09:17:02 +01004191 stage = [
4192 "Stage 1/3: Preparing task.",
4193 "Waiting for previous operations to terminate.",
4194 "",
4195 ]
tiernoe876f672020-02-13 14:34:48 +00004196 # ^ contains [stage, step, VIM-status]
tierno59d22d22018-09-25 18:10:19 +02004197 try:
kuused124bfe2019-06-18 12:09:24 +02004198 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +01004199 await self.lcm_tasks.waitfor_related_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02004200
tiernoe876f672020-02-13 14:34:48 +00004201 stage[1] = "Getting nslcmop={} from db.".format(nslcmop_id)
4202 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
4203 operation_params = db_nslcmop.get("operationParams") or {}
4204 if operation_params.get("timeout_ns_terminate"):
4205 timeout_ns_terminate = operation_params["timeout_ns_terminate"]
4206 stage[1] = "Getting nsr={} from db.".format(nsr_id)
4207 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
4208
4209 db_nsr_update["operational-status"] = "terminating"
4210 db_nsr_update["config-status"] = "terminating"
quilesj4cda56b2019-12-05 10:02:20 +00004211 self._write_ns_status(
4212 nsr_id=nsr_id,
4213 ns_state="TERMINATING",
4214 current_operation="TERMINATING",
tiernoe876f672020-02-13 14:34:48 +00004215 current_operation_id=nslcmop_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01004216 other_update=db_nsr_update,
quilesj4cda56b2019-12-05 10:02:20 +00004217 )
garciadeblas5697b8b2021-03-24 09:17:02 +01004218 self._write_op_status(op_id=nslcmop_id, queuePosition=0, stage=stage)
tiernoe876f672020-02-13 14:34:48 +00004219 nsr_deployed = deepcopy(db_nsr["_admin"].get("deployed")) or {}
tierno59d22d22018-09-25 18:10:19 +02004220 if db_nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
4221 return
tierno59d22d22018-09-25 18:10:19 +02004222
tiernoe876f672020-02-13 14:34:48 +00004223 stage[1] = "Getting vnf descriptors from db."
4224 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
garciadeblas5697b8b2021-03-24 09:17:02 +01004225 db_vnfrs_dict = {
4226 db_vnfr["member-vnf-index-ref"]: db_vnfr for db_vnfr in db_vnfrs_list
4227 }
tiernoe876f672020-02-13 14:34:48 +00004228 db_vnfds_from_id = {}
4229 db_vnfds_from_member_index = {}
4230 # Loop over VNFRs
4231 for vnfr in db_vnfrs_list:
4232 vnfd_id = vnfr["vnfd-id"]
4233 if vnfd_id not in db_vnfds_from_id:
4234 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
4235 db_vnfds_from_id[vnfd_id] = vnfd
garciadeblas5697b8b2021-03-24 09:17:02 +01004236 db_vnfds_from_member_index[
4237 vnfr["member-vnf-index-ref"]
4238 ] = db_vnfds_from_id[vnfd_id]
calvinosanch9f9c6f22019-11-04 13:37:39 +01004239
tiernoe876f672020-02-13 14:34:48 +00004240 # Destroy individual execution environments when there are terminating primitives.
4241 # Rest of EE will be deleted at once
tierno588547c2020-07-01 15:30:20 +00004242 # TODO - check before calling _destroy_N2VC
4243 # if not operation_params.get("skip_terminate_primitives"):#
4244 # or not vca.get("needed_terminate"):
4245 stage[0] = "Stage 2/3 execute terminating primitives."
4246 self.logger.debug(logging_text + stage[0])
4247 stage[1] = "Looking execution environment that needs terminate."
4248 self.logger.debug(logging_text + stage[1])
bravof922c4172020-11-24 21:21:43 -03004249
tierno588547c2020-07-01 15:30:20 +00004250 for vca_index, vca in enumerate(get_iterable(nsr_deployed, "VCA")):
tierno588547c2020-07-01 15:30:20 +00004251 config_descriptor = None
David Garcia9ad54a42021-05-28 12:08:18 +02004252 vca_member_vnf_index = vca.get("member-vnf-index")
4253 vca_id = self.get_vca_id(
4254 db_vnfrs_dict.get(vca_member_vnf_index)
4255 if vca_member_vnf_index
4256 else None,
4257 db_nsr,
4258 )
tierno588547c2020-07-01 15:30:20 +00004259 if not vca or not vca.get("ee_id"):
4260 continue
4261 if not vca.get("member-vnf-index"):
4262 # ns
4263 config_descriptor = db_nsr.get("ns-configuration")
4264 elif vca.get("vdu_id"):
4265 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
bravofe5a31bc2021-02-17 19:09:12 -03004266 config_descriptor = get_configuration(db_vnfd, vca.get("vdu_id"))
tierno588547c2020-07-01 15:30:20 +00004267 elif vca.get("kdu_name"):
4268 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
bravofe5a31bc2021-02-17 19:09:12 -03004269 config_descriptor = get_configuration(db_vnfd, vca.get("kdu_name"))
tierno588547c2020-07-01 15:30:20 +00004270 else:
bravofe5a31bc2021-02-17 19:09:12 -03004271 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
aktas13251562021-02-12 22:19:10 +03004272 config_descriptor = get_configuration(db_vnfd, db_vnfd["id"])
tierno588547c2020-07-01 15:30:20 +00004273 vca_type = vca.get("type")
garciadeblas5697b8b2021-03-24 09:17:02 +01004274 exec_terminate_primitives = not operation_params.get(
4275 "skip_terminate_primitives"
4276 ) and vca.get("needed_terminate")
tiernoaebd7da2020-08-07 06:36:38 +00004277 # For helm we must destroy_ee. Also for native_charm, as juju_model cannot be deleted if there are
4278 # pending native charms
garciadeblas5697b8b2021-03-24 09:17:02 +01004279 destroy_ee = (
4280 True if vca_type in ("helm", "helm-v3", "native_charm") else False
4281 )
tierno86e33612020-09-16 14:13:06 +00004282 # self.logger.debug(logging_text + "vca_index: {}, ee_id: {}, vca_type: {} destroy_ee: {}".format(
4283 # vca_index, vca.get("ee_id"), vca_type, destroy_ee))
tiernob996d942020-07-03 14:52:28 +00004284 task = asyncio.ensure_future(
David Garciac1fe90a2021-03-31 19:12:02 +02004285 self.destroy_N2VC(
4286 logging_text,
4287 db_nslcmop,
4288 vca,
4289 config_descriptor,
4290 vca_index,
4291 destroy_ee,
4292 exec_terminate_primitives,
4293 vca_id=vca_id,
4294 )
4295 )
tierno588547c2020-07-01 15:30:20 +00004296 tasks_dict_info[task] = "Terminating VCA {}".format(vca.get("ee_id"))
tierno59d22d22018-09-25 18:10:19 +02004297
tierno588547c2020-07-01 15:30:20 +00004298 # wait for pending tasks of terminate primitives
4299 if tasks_dict_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01004300 self.logger.debug(
4301 logging_text
4302 + "Waiting for tasks {}".format(list(tasks_dict_info.keys()))
4303 )
4304 error_list = await self._wait_for_tasks(
4305 logging_text,
4306 tasks_dict_info,
4307 min(self.timeout_charm_delete, timeout_ns_terminate),
4308 stage,
4309 nslcmop_id,
4310 )
tierno86e33612020-09-16 14:13:06 +00004311 tasks_dict_info.clear()
tierno588547c2020-07-01 15:30:20 +00004312 if error_list:
garciadeblas5697b8b2021-03-24 09:17:02 +01004313 return # raise LcmException("; ".join(error_list))
tierno82974b22018-11-27 21:55:36 +00004314
tiernoe876f672020-02-13 14:34:48 +00004315 # remove All execution environments at once
4316 stage[0] = "Stage 3/3 delete all."
quilesj3655ae02019-12-12 16:08:35 +00004317
tierno49676be2020-04-07 16:34:35 +00004318 if nsr_deployed.get("VCA"):
4319 stage[1] = "Deleting all execution environments."
4320 self.logger.debug(logging_text + stage[1])
David Garciac1fe90a2021-03-31 19:12:02 +02004321 vca_id = self.get_vca_id({}, db_nsr)
4322 task_delete_ee = asyncio.ensure_future(
4323 asyncio.wait_for(
4324 self._delete_all_N2VC(db_nsr=db_nsr, vca_id=vca_id),
garciadeblas5697b8b2021-03-24 09:17:02 +01004325 timeout=self.timeout_charm_delete,
David Garciac1fe90a2021-03-31 19:12:02 +02004326 )
4327 )
tierno49676be2020-04-07 16:34:35 +00004328 # task_delete_ee = asyncio.ensure_future(self.n2vc.delete_namespace(namespace="." + nsr_id))
4329 tasks_dict_info[task_delete_ee] = "Terminating all VCA"
tierno59d22d22018-09-25 18:10:19 +02004330
tiernoe876f672020-02-13 14:34:48 +00004331 # Delete from k8scluster
4332 stage[1] = "Deleting KDUs."
4333 self.logger.debug(logging_text + stage[1])
4334 # print(nsr_deployed)
4335 for kdu in get_iterable(nsr_deployed, "K8s"):
4336 if not kdu or not kdu.get("kdu-instance"):
4337 continue
4338 kdu_instance = kdu.get("kdu-instance")
tiernoa2143262020-03-27 16:20:40 +00004339 if kdu.get("k8scluster-type") in self.k8scluster_map:
David Garciac1fe90a2021-03-31 19:12:02 +02004340 # TODO: Uninstall kdu instances taking into account they could be deployed in different VIMs
4341 vca_id = self.get_vca_id({}, db_nsr)
tiernoe876f672020-02-13 14:34:48 +00004342 task_delete_kdu_instance = asyncio.ensure_future(
tiernoa2143262020-03-27 16:20:40 +00004343 self.k8scluster_map[kdu["k8scluster-type"]].uninstall(
4344 cluster_uuid=kdu.get("k8scluster-uuid"),
David Garciac1fe90a2021-03-31 19:12:02 +02004345 kdu_instance=kdu_instance,
4346 vca_id=vca_id,
4347 )
4348 )
tiernoe876f672020-02-13 14:34:48 +00004349 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004350 self.logger.error(
4351 logging_text
4352 + "Unknown k8s deployment type {}".format(
4353 kdu.get("k8scluster-type")
4354 )
4355 )
tiernoe876f672020-02-13 14:34:48 +00004356 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01004357 tasks_dict_info[
4358 task_delete_kdu_instance
4359 ] = "Terminating KDU '{}'".format(kdu.get("kdu-name"))
tierno59d22d22018-09-25 18:10:19 +02004360
4361 # remove from RO
tiernoe876f672020-02-13 14:34:48 +00004362 stage[1] = "Deleting ns from VIM."
tierno69f0d382020-05-07 13:08:09 +00004363 if self.ng_ro:
4364 task_delete_ro = asyncio.ensure_future(
garciadeblas5697b8b2021-03-24 09:17:02 +01004365 self._terminate_ng_ro(
4366 logging_text, nsr_deployed, nsr_id, nslcmop_id, stage
4367 )
4368 )
tierno69f0d382020-05-07 13:08:09 +00004369 else:
4370 task_delete_ro = asyncio.ensure_future(
garciadeblas5697b8b2021-03-24 09:17:02 +01004371 self._terminate_RO(
4372 logging_text, nsr_deployed, nsr_id, nslcmop_id, stage
4373 )
4374 )
tiernoe876f672020-02-13 14:34:48 +00004375 tasks_dict_info[task_delete_ro] = "Removing deployment from VIM"
tierno59d22d22018-09-25 18:10:19 +02004376
tiernoe876f672020-02-13 14:34:48 +00004377 # rest of staff will be done at finally
4378
garciadeblas5697b8b2021-03-24 09:17:02 +01004379 except (
4380 ROclient.ROClientException,
4381 DbException,
4382 LcmException,
4383 N2VCException,
4384 ) as e:
tiernoe876f672020-02-13 14:34:48 +00004385 self.logger.error(logging_text + "Exit Exception {}".format(e))
4386 exc = e
4387 except asyncio.CancelledError:
garciadeblas5697b8b2021-03-24 09:17:02 +01004388 self.logger.error(
4389 logging_text + "Cancelled Exception while '{}'".format(stage[1])
4390 )
tiernoe876f672020-02-13 14:34:48 +00004391 exc = "Operation was cancelled"
4392 except Exception as e:
4393 exc = traceback.format_exc()
garciadeblas5697b8b2021-03-24 09:17:02 +01004394 self.logger.critical(
4395 logging_text + "Exit Exception while '{}': {}".format(stage[1], e),
4396 exc_info=True,
4397 )
tiernoe876f672020-02-13 14:34:48 +00004398 finally:
4399 if exc:
4400 error_list.append(str(exc))
tierno59d22d22018-09-25 18:10:19 +02004401 try:
tiernoe876f672020-02-13 14:34:48 +00004402 # wait for pending tasks
4403 if tasks_dict_info:
4404 stage[1] = "Waiting for terminate pending tasks."
4405 self.logger.debug(logging_text + stage[1])
garciadeblas5697b8b2021-03-24 09:17:02 +01004406 error_list += await self._wait_for_tasks(
4407 logging_text,
4408 tasks_dict_info,
4409 timeout_ns_terminate,
4410 stage,
4411 nslcmop_id,
4412 )
tiernoe876f672020-02-13 14:34:48 +00004413 stage[1] = stage[2] = ""
4414 except asyncio.CancelledError:
4415 error_list.append("Cancelled")
4416 # TODO cancell all tasks
4417 except Exception as exc:
4418 error_list.append(str(exc))
4419 # update status at database
4420 if error_list:
4421 error_detail = "; ".join(error_list)
4422 # self.logger.error(logging_text + error_detail)
garciadeblas5697b8b2021-03-24 09:17:02 +01004423 error_description_nslcmop = "{} Detail: {}".format(
4424 stage[0], error_detail
4425 )
4426 error_description_nsr = "Operation: TERMINATING.{}, {}.".format(
4427 nslcmop_id, stage[0]
4428 )
tierno59d22d22018-09-25 18:10:19 +02004429
tierno59d22d22018-09-25 18:10:19 +02004430 db_nsr_update["operational-status"] = "failed"
garciadeblas5697b8b2021-03-24 09:17:02 +01004431 db_nsr_update["detailed-status"] = (
4432 error_description_nsr + " Detail: " + error_detail
4433 )
tiernoe876f672020-02-13 14:34:48 +00004434 db_nslcmop_update["detailed-status"] = error_detail
4435 nslcmop_operation_state = "FAILED"
4436 ns_state = "BROKEN"
tierno59d22d22018-09-25 18:10:19 +02004437 else:
tiernoa2143262020-03-27 16:20:40 +00004438 error_detail = None
tiernoe876f672020-02-13 14:34:48 +00004439 error_description_nsr = error_description_nslcmop = None
4440 ns_state = "NOT_INSTANTIATED"
tierno59d22d22018-09-25 18:10:19 +02004441 db_nsr_update["operational-status"] = "terminated"
4442 db_nsr_update["detailed-status"] = "Done"
4443 db_nsr_update["_admin.nsState"] = "NOT_INSTANTIATED"
4444 db_nslcmop_update["detailed-status"] = "Done"
tiernoe876f672020-02-13 14:34:48 +00004445 nslcmop_operation_state = "COMPLETED"
tierno59d22d22018-09-25 18:10:19 +02004446
tiernoe876f672020-02-13 14:34:48 +00004447 if db_nsr:
4448 self._write_ns_status(
4449 nsr_id=nsr_id,
4450 ns_state=ns_state,
4451 current_operation="IDLE",
4452 current_operation_id=None,
4453 error_description=error_description_nsr,
tiernoa2143262020-03-27 16:20:40 +00004454 error_detail=error_detail,
garciadeblas5697b8b2021-03-24 09:17:02 +01004455 other_update=db_nsr_update,
tiernoe876f672020-02-13 14:34:48 +00004456 )
tiernoa17d4f42020-04-28 09:59:23 +00004457 self._write_op_status(
4458 op_id=nslcmop_id,
4459 stage="",
4460 error_message=error_description_nslcmop,
4461 operation_state=nslcmop_operation_state,
4462 other_update=db_nslcmop_update,
4463 )
lloretgalleg6d488782020-07-22 10:13:46 +00004464 if ns_state == "NOT_INSTANTIATED":
4465 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01004466 self.db.set_list(
4467 "vnfrs",
4468 {"nsr-id-ref": nsr_id},
4469 {"_admin.nsState": "NOT_INSTANTIATED"},
4470 )
lloretgalleg6d488782020-07-22 10:13:46 +00004471 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01004472 self.logger.warn(
4473 logging_text
4474 + "Error writing VNFR status for nsr-id-ref: {} -> {}".format(
4475 nsr_id, e
4476 )
4477 )
tiernoa17d4f42020-04-28 09:59:23 +00004478 if operation_params:
tiernoe876f672020-02-13 14:34:48 +00004479 autoremove = operation_params.get("autoremove", False)
tierno59d22d22018-09-25 18:10:19 +02004480 if nslcmop_operation_state:
4481 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01004482 await self.msg.aiowrite(
4483 "ns",
4484 "terminated",
4485 {
4486 "nsr_id": nsr_id,
4487 "nslcmop_id": nslcmop_id,
4488 "operationState": nslcmop_operation_state,
4489 "autoremove": autoremove,
4490 },
4491 loop=self.loop,
4492 )
tierno59d22d22018-09-25 18:10:19 +02004493 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01004494 self.logger.error(
4495 logging_text + "kafka_write notification Exception {}".format(e)
4496 )
quilesj7e13aeb2019-10-08 13:34:55 +02004497
tierno59d22d22018-09-25 18:10:19 +02004498 self.logger.debug(logging_text + "Exit")
4499 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_terminate")
4500
garciadeblas5697b8b2021-03-24 09:17:02 +01004501 async def _wait_for_tasks(
4502 self, logging_text, created_tasks_info, timeout, stage, nslcmop_id, nsr_id=None
4503 ):
tiernoe876f672020-02-13 14:34:48 +00004504 time_start = time()
tiernoa2143262020-03-27 16:20:40 +00004505 error_detail_list = []
tiernoe876f672020-02-13 14:34:48 +00004506 error_list = []
4507 pending_tasks = list(created_tasks_info.keys())
4508 num_tasks = len(pending_tasks)
4509 num_done = 0
4510 stage[1] = "{}/{}.".format(num_done, num_tasks)
4511 self._write_op_status(nslcmop_id, stage)
tiernoe876f672020-02-13 14:34:48 +00004512 while pending_tasks:
tiernoa2143262020-03-27 16:20:40 +00004513 new_error = None
tiernoe876f672020-02-13 14:34:48 +00004514 _timeout = timeout + time_start - time()
garciadeblas5697b8b2021-03-24 09:17:02 +01004515 done, pending_tasks = await asyncio.wait(
4516 pending_tasks, timeout=_timeout, return_when=asyncio.FIRST_COMPLETED
4517 )
tiernoe876f672020-02-13 14:34:48 +00004518 num_done += len(done)
garciadeblas5697b8b2021-03-24 09:17:02 +01004519 if not done: # Timeout
tiernoe876f672020-02-13 14:34:48 +00004520 for task in pending_tasks:
tiernoa2143262020-03-27 16:20:40 +00004521 new_error = created_tasks_info[task] + ": Timeout"
4522 error_detail_list.append(new_error)
4523 error_list.append(new_error)
tiernoe876f672020-02-13 14:34:48 +00004524 break
4525 for task in done:
4526 if task.cancelled():
tierno067e04a2020-03-31 12:53:13 +00004527 exc = "Cancelled"
tiernoe876f672020-02-13 14:34:48 +00004528 else:
4529 exc = task.exception()
tierno067e04a2020-03-31 12:53:13 +00004530 if exc:
4531 if isinstance(exc, asyncio.TimeoutError):
4532 exc = "Timeout"
4533 new_error = created_tasks_info[task] + ": {}".format(exc)
4534 error_list.append(created_tasks_info[task])
4535 error_detail_list.append(new_error)
garciadeblas5697b8b2021-03-24 09:17:02 +01004536 if isinstance(
4537 exc,
4538 (
4539 str,
4540 DbException,
4541 N2VCException,
4542 ROclient.ROClientException,
4543 LcmException,
4544 K8sException,
4545 NgRoException,
4546 ),
4547 ):
tierno067e04a2020-03-31 12:53:13 +00004548 self.logger.error(logging_text + new_error)
tiernoe876f672020-02-13 14:34:48 +00004549 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004550 exc_traceback = "".join(
4551 traceback.format_exception(None, exc, exc.__traceback__)
4552 )
4553 self.logger.error(
4554 logging_text
4555 + created_tasks_info[task]
4556 + " "
4557 + exc_traceback
4558 )
tierno067e04a2020-03-31 12:53:13 +00004559 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004560 self.logger.debug(
4561 logging_text + created_tasks_info[task] + ": Done"
4562 )
tiernoe876f672020-02-13 14:34:48 +00004563 stage[1] = "{}/{}.".format(num_done, num_tasks)
4564 if new_error:
tiernoa2143262020-03-27 16:20:40 +00004565 stage[1] += " Errors: " + ". ".join(error_detail_list) + "."
tiernoe876f672020-02-13 14:34:48 +00004566 if nsr_id: # update also nsr
garciadeblas5697b8b2021-03-24 09:17:02 +01004567 self.update_db_2(
4568 "nsrs",
4569 nsr_id,
4570 {
4571 "errorDescription": "Error at: " + ", ".join(error_list),
4572 "errorDetail": ". ".join(error_detail_list),
4573 },
4574 )
tiernoe876f672020-02-13 14:34:48 +00004575 self._write_op_status(nslcmop_id, stage)
tiernoa2143262020-03-27 16:20:40 +00004576 return error_detail_list
tiernoe876f672020-02-13 14:34:48 +00004577
tiernoda1ff8c2020-10-22 14:12:46 +00004578 @staticmethod
4579 def _map_primitive_params(primitive_desc, params, instantiation_params):
tiernoda964822019-01-14 15:53:47 +00004580 """
4581 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
4582 The default-value is used. If it is between < > it look for a value at instantiation_params
4583 :param primitive_desc: portion of VNFD/NSD that describes primitive
4584 :param params: Params provided by user
4585 :param instantiation_params: Instantiation params provided by user
4586 :return: a dictionary with the calculated params
4587 """
4588 calculated_params = {}
4589 for parameter in primitive_desc.get("parameter", ()):
4590 param_name = parameter["name"]
4591 if param_name in params:
4592 calculated_params[param_name] = params[param_name]
tierno98ad6ea2019-05-30 17:16:28 +00004593 elif "default-value" in parameter or "value" in parameter:
4594 if "value" in parameter:
4595 calculated_params[param_name] = parameter["value"]
4596 else:
4597 calculated_params[param_name] = parameter["default-value"]
garciadeblas5697b8b2021-03-24 09:17:02 +01004598 if (
4599 isinstance(calculated_params[param_name], str)
4600 and calculated_params[param_name].startswith("<")
4601 and calculated_params[param_name].endswith(">")
4602 ):
tierno98ad6ea2019-05-30 17:16:28 +00004603 if calculated_params[param_name][1:-1] in instantiation_params:
garciadeblas5697b8b2021-03-24 09:17:02 +01004604 calculated_params[param_name] = instantiation_params[
4605 calculated_params[param_name][1:-1]
4606 ]
tiernoda964822019-01-14 15:53:47 +00004607 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004608 raise LcmException(
4609 "Parameter {} needed to execute primitive {} not provided".format(
4610 calculated_params[param_name], primitive_desc["name"]
4611 )
4612 )
tiernoda964822019-01-14 15:53:47 +00004613 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004614 raise LcmException(
4615 "Parameter {} needed to execute primitive {} not provided".format(
4616 param_name, primitive_desc["name"]
4617 )
4618 )
tierno59d22d22018-09-25 18:10:19 +02004619
tiernoda964822019-01-14 15:53:47 +00004620 if isinstance(calculated_params[param_name], (dict, list, tuple)):
garciadeblas5697b8b2021-03-24 09:17:02 +01004621 calculated_params[param_name] = yaml.safe_dump(
4622 calculated_params[param_name], default_flow_style=True, width=256
4623 )
4624 elif isinstance(calculated_params[param_name], str) and calculated_params[
4625 param_name
4626 ].startswith("!!yaml "):
tiernoda964822019-01-14 15:53:47 +00004627 calculated_params[param_name] = calculated_params[param_name][7:]
tiernofa40e692020-10-14 14:59:36 +00004628 if parameter.get("data-type") == "INTEGER":
4629 try:
4630 calculated_params[param_name] = int(calculated_params[param_name])
4631 except ValueError: # error converting string to int
4632 raise LcmException(
garciadeblas5697b8b2021-03-24 09:17:02 +01004633 "Parameter {} of primitive {} must be integer".format(
4634 param_name, primitive_desc["name"]
4635 )
4636 )
tiernofa40e692020-10-14 14:59:36 +00004637 elif parameter.get("data-type") == "BOOLEAN":
garciadeblas5697b8b2021-03-24 09:17:02 +01004638 calculated_params[param_name] = not (
4639 (str(calculated_params[param_name])).lower() == "false"
4640 )
tiernoc3f2a822019-11-05 13:45:04 +00004641
4642 # add always ns_config_info if primitive name is config
4643 if primitive_desc["name"] == "config":
4644 if "ns_config_info" in instantiation_params:
garciadeblas5697b8b2021-03-24 09:17:02 +01004645 calculated_params["ns_config_info"] = instantiation_params[
4646 "ns_config_info"
4647 ]
tiernoda964822019-01-14 15:53:47 +00004648 return calculated_params
4649
garciadeblas5697b8b2021-03-24 09:17:02 +01004650 def _look_for_deployed_vca(
4651 self,
4652 deployed_vca,
4653 member_vnf_index,
4654 vdu_id,
4655 vdu_count_index,
4656 kdu_name=None,
4657 ee_descriptor_id=None,
4658 ):
tiernoe876f672020-02-13 14:34:48 +00004659 # find vca_deployed record for this action. Raise LcmException if not found or there is not any id.
4660 for vca in deployed_vca:
4661 if not vca:
4662 continue
4663 if member_vnf_index != vca["member-vnf-index"] or vdu_id != vca["vdu_id"]:
4664 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01004665 if (
4666 vdu_count_index is not None
4667 and vdu_count_index != vca["vdu_count_index"]
4668 ):
tiernoe876f672020-02-13 14:34:48 +00004669 continue
4670 if kdu_name and kdu_name != vca["kdu_name"]:
4671 continue
tiernoa278b842020-07-08 15:33:55 +00004672 if ee_descriptor_id and ee_descriptor_id != vca["ee_descriptor_id"]:
4673 continue
tiernoe876f672020-02-13 14:34:48 +00004674 break
4675 else:
4676 # vca_deployed not found
garciadeblas5697b8b2021-03-24 09:17:02 +01004677 raise LcmException(
4678 "charm for member_vnf_index={} vdu_id={}.{} kdu_name={} execution-environment-list.id={}"
4679 " is not deployed".format(
4680 member_vnf_index,
4681 vdu_id,
4682 vdu_count_index,
4683 kdu_name,
4684 ee_descriptor_id,
4685 )
4686 )
tiernoe876f672020-02-13 14:34:48 +00004687 # get ee_id
4688 ee_id = vca.get("ee_id")
garciadeblas5697b8b2021-03-24 09:17:02 +01004689 vca_type = vca.get(
4690 "type", "lxc_proxy_charm"
4691 ) # default value for backward compatibility - proxy charm
tiernoe876f672020-02-13 14:34:48 +00004692 if not ee_id:
garciadeblas5697b8b2021-03-24 09:17:02 +01004693 raise LcmException(
4694 "charm for member_vnf_index={} vdu_id={} kdu_name={} vdu_count_index={} has not "
4695 "execution environment".format(
4696 member_vnf_index, vdu_id, kdu_name, vdu_count_index
4697 )
4698 )
tierno588547c2020-07-01 15:30:20 +00004699 return ee_id, vca_type
tiernoe876f672020-02-13 14:34:48 +00004700
David Garciac1fe90a2021-03-31 19:12:02 +02004701 async def _ns_execute_primitive(
4702 self,
4703 ee_id,
4704 primitive,
4705 primitive_params,
4706 retries=0,
4707 retries_interval=30,
4708 timeout=None,
4709 vca_type=None,
4710 db_dict=None,
4711 vca_id: str = None,
4712 ) -> (str, str):
tiernoda964822019-01-14 15:53:47 +00004713 try:
tierno98ad6ea2019-05-30 17:16:28 +00004714 if primitive == "config":
4715 primitive_params = {"params": primitive_params}
tierno2fc7ce52019-06-11 22:50:01 +00004716
tierno588547c2020-07-01 15:30:20 +00004717 vca_type = vca_type or "lxc_proxy_charm"
4718
quilesj7e13aeb2019-10-08 13:34:55 +02004719 while retries >= 0:
4720 try:
tierno067e04a2020-03-31 12:53:13 +00004721 output = await asyncio.wait_for(
tierno588547c2020-07-01 15:30:20 +00004722 self.vca_map[vca_type].exec_primitive(
tierno067e04a2020-03-31 12:53:13 +00004723 ee_id=ee_id,
4724 primitive_name=primitive,
4725 params_dict=primitive_params,
4726 progress_timeout=self.timeout_progress_primitive,
tierno588547c2020-07-01 15:30:20 +00004727 total_timeout=self.timeout_primitive,
David Garciac1fe90a2021-03-31 19:12:02 +02004728 db_dict=db_dict,
4729 vca_id=vca_id,
aktas98488ed2021-07-29 17:42:49 +03004730 vca_type=vca_type,
David Garciac1fe90a2021-03-31 19:12:02 +02004731 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01004732 timeout=timeout or self.timeout_primitive,
4733 )
quilesj7e13aeb2019-10-08 13:34:55 +02004734 # execution was OK
4735 break
tierno067e04a2020-03-31 12:53:13 +00004736 except asyncio.CancelledError:
4737 raise
4738 except Exception as e: # asyncio.TimeoutError
4739 if isinstance(e, asyncio.TimeoutError):
4740 e = "Timeout"
quilesj7e13aeb2019-10-08 13:34:55 +02004741 retries -= 1
4742 if retries >= 0:
garciadeblas5697b8b2021-03-24 09:17:02 +01004743 self.logger.debug(
4744 "Error executing action {} on {} -> {}".format(
4745 primitive, ee_id, e
4746 )
4747 )
quilesj7e13aeb2019-10-08 13:34:55 +02004748 # wait and retry
4749 await asyncio.sleep(retries_interval, loop=self.loop)
tierno73d8bd02019-11-18 17:33:27 +00004750 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004751 return "FAILED", str(e)
quilesj7e13aeb2019-10-08 13:34:55 +02004752
garciadeblas5697b8b2021-03-24 09:17:02 +01004753 return "COMPLETED", output
quilesj7e13aeb2019-10-08 13:34:55 +02004754
tierno067e04a2020-03-31 12:53:13 +00004755 except (LcmException, asyncio.CancelledError):
tiernoe876f672020-02-13 14:34:48 +00004756 raise
quilesj7e13aeb2019-10-08 13:34:55 +02004757 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01004758 return "FAIL", "Error executing action {}: {}".format(primitive, e)
tierno59d22d22018-09-25 18:10:19 +02004759
ksaikiranr3fde2c72021-03-15 10:39:06 +05304760 async def vca_status_refresh(self, nsr_id, nslcmop_id):
4761 """
4762 Updating the vca_status with latest juju information in nsrs record
4763 :param: nsr_id: Id of the nsr
4764 :param: nslcmop_id: Id of the nslcmop
4765 :return: None
4766 """
4767
4768 self.logger.debug("Task ns={} action={} Enter".format(nsr_id, nslcmop_id))
4769 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
David Garciac1fe90a2021-03-31 19:12:02 +02004770 vca_id = self.get_vca_id({}, db_nsr)
garciadeblas5697b8b2021-03-24 09:17:02 +01004771 if db_nsr["_admin"]["deployed"]["K8s"]:
4772 for k8s_index, k8s in enumerate(db_nsr["_admin"]["deployed"]["K8s"]):
ksaikiranr656b6dd2021-02-19 10:25:18 +05304773 cluster_uuid, kdu_instance = k8s["k8scluster-uuid"], k8s["kdu-instance"]
garciadeblas5697b8b2021-03-24 09:17:02 +01004774 await self._on_update_k8s_db(
4775 cluster_uuid, kdu_instance, filter={"_id": nsr_id}, vca_id=vca_id
4776 )
ksaikiranr656b6dd2021-02-19 10:25:18 +05304777 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004778 for vca_index, _ in enumerate(db_nsr["_admin"]["deployed"]["VCA"]):
ksaikiranr656b6dd2021-02-19 10:25:18 +05304779 table, filter = "nsrs", {"_id": nsr_id}
4780 path = "_admin.deployed.VCA.{}.".format(vca_index)
4781 await self._on_update_n2vc_db(table, filter, path, {})
ksaikiranr3fde2c72021-03-15 10:39:06 +05304782
4783 self.logger.debug("Task ns={} action={} Exit".format(nsr_id, nslcmop_id))
4784 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_vca_status_refresh")
4785
tierno59d22d22018-09-25 18:10:19 +02004786 async def action(self, nsr_id, nslcmop_id):
kuused124bfe2019-06-18 12:09:24 +02004787 # Try to lock HA task here
garciadeblas5697b8b2021-03-24 09:17:02 +01004788 task_is_locked_by_me = self.lcm_tasks.lock_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02004789 if not task_is_locked_by_me:
4790 return
4791
tierno59d22d22018-09-25 18:10:19 +02004792 logging_text = "Task ns={} action={} ".format(nsr_id, nslcmop_id)
4793 self.logger.debug(logging_text + "Enter")
4794 # get all needed from database
4795 db_nsr = None
4796 db_nslcmop = None
tiernoe876f672020-02-13 14:34:48 +00004797 db_nsr_update = {}
tierno59d22d22018-09-25 18:10:19 +02004798 db_nslcmop_update = {}
4799 nslcmop_operation_state = None
tierno067e04a2020-03-31 12:53:13 +00004800 error_description_nslcmop = None
tierno59d22d22018-09-25 18:10:19 +02004801 exc = None
4802 try:
kuused124bfe2019-06-18 12:09:24 +02004803 # wait for any previous tasks in process
tierno3cf81a32019-11-11 17:07:00 +00004804 step = "Waiting for previous operations to terminate"
garciadeblas5697b8b2021-03-24 09:17:02 +01004805 await self.lcm_tasks.waitfor_related_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02004806
quilesj4cda56b2019-12-05 10:02:20 +00004807 self._write_ns_status(
4808 nsr_id=nsr_id,
4809 ns_state=None,
4810 current_operation="RUNNING ACTION",
garciadeblas5697b8b2021-03-24 09:17:02 +01004811 current_operation_id=nslcmop_id,
quilesj4cda56b2019-12-05 10:02:20 +00004812 )
4813
tierno59d22d22018-09-25 18:10:19 +02004814 step = "Getting information from database"
4815 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
4816 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
tiernoda964822019-01-14 15:53:47 +00004817
tiernoe4f7e6c2018-11-27 14:55:30 +00004818 nsr_deployed = db_nsr["_admin"].get("deployed")
tierno1b633412019-02-25 16:48:23 +00004819 vnf_index = db_nslcmop["operationParams"].get("member_vnf_index")
tierno59d22d22018-09-25 18:10:19 +02004820 vdu_id = db_nslcmop["operationParams"].get("vdu_id")
calvinosanch9f9c6f22019-11-04 13:37:39 +01004821 kdu_name = db_nslcmop["operationParams"].get("kdu_name")
tiernoe4f7e6c2018-11-27 14:55:30 +00004822 vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
tierno067e04a2020-03-31 12:53:13 +00004823 primitive = db_nslcmop["operationParams"]["primitive"]
4824 primitive_params = db_nslcmop["operationParams"]["primitive_params"]
garciadeblas5697b8b2021-03-24 09:17:02 +01004825 timeout_ns_action = db_nslcmop["operationParams"].get(
4826 "timeout_ns_action", self.timeout_primitive
4827 )
tierno59d22d22018-09-25 18:10:19 +02004828
tierno1b633412019-02-25 16:48:23 +00004829 if vnf_index:
4830 step = "Getting vnfr from database"
garciadeblas5697b8b2021-03-24 09:17:02 +01004831 db_vnfr = self.db.get_one(
4832 "vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id}
4833 )
tierno1b633412019-02-25 16:48:23 +00004834 step = "Getting vnfd from database"
4835 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
4836 else:
tierno067e04a2020-03-31 12:53:13 +00004837 step = "Getting nsd from database"
4838 db_nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
tiernoda964822019-01-14 15:53:47 +00004839
David Garciac1fe90a2021-03-31 19:12:02 +02004840 vca_id = self.get_vca_id(db_vnfr, db_nsr)
tierno82974b22018-11-27 21:55:36 +00004841 # for backward compatibility
4842 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
4843 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
4844 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
4845 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4846
tiernoda964822019-01-14 15:53:47 +00004847 # look for primitive
tiernoa278b842020-07-08 15:33:55 +00004848 config_primitive_desc = descriptor_configuration = None
tiernoda964822019-01-14 15:53:47 +00004849 if vdu_id:
bravofe5a31bc2021-02-17 19:09:12 -03004850 descriptor_configuration = get_configuration(db_vnfd, vdu_id)
calvinosanch9f9c6f22019-11-04 13:37:39 +01004851 elif kdu_name:
bravofe5a31bc2021-02-17 19:09:12 -03004852 descriptor_configuration = get_configuration(db_vnfd, kdu_name)
tierno1b633412019-02-25 16:48:23 +00004853 elif vnf_index:
bravofe5a31bc2021-02-17 19:09:12 -03004854 descriptor_configuration = get_configuration(db_vnfd, db_vnfd["id"])
tierno1b633412019-02-25 16:48:23 +00004855 else:
tiernoa278b842020-07-08 15:33:55 +00004856 descriptor_configuration = db_nsd.get("ns-configuration")
4857
garciadeblas5697b8b2021-03-24 09:17:02 +01004858 if descriptor_configuration and descriptor_configuration.get(
4859 "config-primitive"
4860 ):
tiernoa278b842020-07-08 15:33:55 +00004861 for config_primitive in descriptor_configuration["config-primitive"]:
tierno1b633412019-02-25 16:48:23 +00004862 if config_primitive["name"] == primitive:
4863 config_primitive_desc = config_primitive
4864 break
tiernoda964822019-01-14 15:53:47 +00004865
garciadeblas6bed6b32020-07-20 11:05:42 +00004866 if not config_primitive_desc:
4867 if not (kdu_name and primitive in ("upgrade", "rollback", "status")):
garciadeblas5697b8b2021-03-24 09:17:02 +01004868 raise LcmException(
4869 "Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".format(
4870 primitive
4871 )
4872 )
garciadeblas6bed6b32020-07-20 11:05:42 +00004873 primitive_name = primitive
4874 ee_descriptor_id = None
4875 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004876 primitive_name = config_primitive_desc.get(
4877 "execution-environment-primitive", primitive
4878 )
4879 ee_descriptor_id = config_primitive_desc.get(
4880 "execution-environment-ref"
4881 )
tierno1b633412019-02-25 16:48:23 +00004882
tierno1b633412019-02-25 16:48:23 +00004883 if vnf_index:
tierno626e0152019-11-29 14:16:16 +00004884 if vdu_id:
garciadeblas5697b8b2021-03-24 09:17:02 +01004885 vdur = next(
4886 (x for x in db_vnfr["vdur"] if x["vdu-id-ref"] == vdu_id), None
4887 )
bravof922c4172020-11-24 21:21:43 -03004888 desc_params = parse_yaml_strings(vdur.get("additionalParams"))
tierno067e04a2020-03-31 12:53:13 +00004889 elif kdu_name:
garciadeblas5697b8b2021-03-24 09:17:02 +01004890 kdur = next(
4891 (x for x in db_vnfr["kdur"] if x["kdu-name"] == kdu_name), None
4892 )
bravof922c4172020-11-24 21:21:43 -03004893 desc_params = parse_yaml_strings(kdur.get("additionalParams"))
tierno067e04a2020-03-31 12:53:13 +00004894 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004895 desc_params = parse_yaml_strings(
4896 db_vnfr.get("additionalParamsForVnf")
4897 )
tierno1b633412019-02-25 16:48:23 +00004898 else:
bravof922c4172020-11-24 21:21:43 -03004899 desc_params = parse_yaml_strings(db_nsr.get("additionalParamsForNs"))
bravofe5a31bc2021-02-17 19:09:12 -03004900 if kdu_name and get_configuration(db_vnfd, kdu_name):
4901 kdu_configuration = get_configuration(db_vnfd, kdu_name)
David Garciad41dbd62020-12-10 12:52:52 +01004902 actions = set()
David Garciaa1003662021-02-16 21:07:58 +01004903 for primitive in kdu_configuration.get("initial-config-primitive", []):
David Garciad41dbd62020-12-10 12:52:52 +01004904 actions.add(primitive["name"])
David Garciaa1003662021-02-16 21:07:58 +01004905 for primitive in kdu_configuration.get("config-primitive", []):
David Garciad41dbd62020-12-10 12:52:52 +01004906 actions.add(primitive["name"])
4907 kdu_action = True if primitive_name in actions else False
Dominik Fleischmann771c32b2020-04-07 12:39:36 +02004908
tiernoda964822019-01-14 15:53:47 +00004909 # TODO check if ns is in a proper status
garciadeblas5697b8b2021-03-24 09:17:02 +01004910 if kdu_name and (
4911 primitive_name in ("upgrade", "rollback", "status") or kdu_action
4912 ):
tierno067e04a2020-03-31 12:53:13 +00004913 # kdur and desc_params already set from before
4914 if primitive_params:
4915 desc_params.update(primitive_params)
4916 # TODO Check if we will need something at vnf level
4917 for index, kdu in enumerate(get_iterable(nsr_deployed, "K8s")):
garciadeblas5697b8b2021-03-24 09:17:02 +01004918 if (
4919 kdu_name == kdu["kdu-name"]
4920 and kdu["member-vnf-index"] == vnf_index
4921 ):
tierno067e04a2020-03-31 12:53:13 +00004922 break
4923 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004924 raise LcmException(
4925 "KDU '{}' for vnf '{}' not deployed".format(kdu_name, vnf_index)
4926 )
quilesj7e13aeb2019-10-08 13:34:55 +02004927
tierno067e04a2020-03-31 12:53:13 +00004928 if kdu.get("k8scluster-type") not in self.k8scluster_map:
garciadeblas5697b8b2021-03-24 09:17:02 +01004929 msg = "unknown k8scluster-type '{}'".format(
4930 kdu.get("k8scluster-type")
4931 )
tierno067e04a2020-03-31 12:53:13 +00004932 raise LcmException(msg)
4933
garciadeblas5697b8b2021-03-24 09:17:02 +01004934 db_dict = {
4935 "collection": "nsrs",
4936 "filter": {"_id": nsr_id},
4937 "path": "_admin.deployed.K8s.{}".format(index),
4938 }
4939 self.logger.debug(
4940 logging_text
4941 + "Exec k8s {} on {}.{}".format(primitive_name, vnf_index, kdu_name)
4942 )
tiernoa278b842020-07-08 15:33:55 +00004943 step = "Executing kdu {}".format(primitive_name)
4944 if primitive_name == "upgrade":
tierno067e04a2020-03-31 12:53:13 +00004945 if desc_params.get("kdu_model"):
4946 kdu_model = desc_params.get("kdu_model")
4947 del desc_params["kdu_model"]
4948 else:
4949 kdu_model = kdu.get("kdu-model")
4950 parts = kdu_model.split(sep=":")
4951 if len(parts) == 2:
4952 kdu_model = parts[0]
4953
4954 detailed_status = await asyncio.wait_for(
4955 self.k8scluster_map[kdu["k8scluster-type"]].upgrade(
4956 cluster_uuid=kdu.get("k8scluster-uuid"),
4957 kdu_instance=kdu.get("kdu-instance"),
garciadeblas5697b8b2021-03-24 09:17:02 +01004958 atomic=True,
4959 kdu_model=kdu_model,
4960 params=desc_params,
4961 db_dict=db_dict,
4962 timeout=timeout_ns_action,
4963 ),
4964 timeout=timeout_ns_action + 10,
4965 )
4966 self.logger.debug(
4967 logging_text + " Upgrade of kdu {} done".format(detailed_status)
4968 )
tiernoa278b842020-07-08 15:33:55 +00004969 elif primitive_name == "rollback":
tierno067e04a2020-03-31 12:53:13 +00004970 detailed_status = await asyncio.wait_for(
4971 self.k8scluster_map[kdu["k8scluster-type"]].rollback(
4972 cluster_uuid=kdu.get("k8scluster-uuid"),
4973 kdu_instance=kdu.get("kdu-instance"),
garciadeblas5697b8b2021-03-24 09:17:02 +01004974 db_dict=db_dict,
4975 ),
4976 timeout=timeout_ns_action,
4977 )
tiernoa278b842020-07-08 15:33:55 +00004978 elif primitive_name == "status":
tierno067e04a2020-03-31 12:53:13 +00004979 detailed_status = await asyncio.wait_for(
4980 self.k8scluster_map[kdu["k8scluster-type"]].status_kdu(
4981 cluster_uuid=kdu.get("k8scluster-uuid"),
David Garciac1fe90a2021-03-31 19:12:02 +02004982 kdu_instance=kdu.get("kdu-instance"),
4983 vca_id=vca_id,
4984 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01004985 timeout=timeout_ns_action,
David Garciac1fe90a2021-03-31 19:12:02 +02004986 )
Dominik Fleischmann771c32b2020-04-07 12:39:36 +02004987 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004988 kdu_instance = kdu.get("kdu-instance") or "{}-{}".format(
4989 kdu["kdu-name"], nsr_id
4990 )
4991 params = self._map_primitive_params(
4992 config_primitive_desc, primitive_params, desc_params
4993 )
Dominik Fleischmann771c32b2020-04-07 12:39:36 +02004994
4995 detailed_status = await asyncio.wait_for(
4996 self.k8scluster_map[kdu["k8scluster-type"]].exec_primitive(
4997 cluster_uuid=kdu.get("k8scluster-uuid"),
4998 kdu_instance=kdu_instance,
tiernoa278b842020-07-08 15:33:55 +00004999 primitive_name=primitive_name,
garciadeblas5697b8b2021-03-24 09:17:02 +01005000 params=params,
5001 db_dict=db_dict,
David Garciac1fe90a2021-03-31 19:12:02 +02005002 timeout=timeout_ns_action,
5003 vca_id=vca_id,
5004 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01005005 timeout=timeout_ns_action,
David Garciac1fe90a2021-03-31 19:12:02 +02005006 )
tierno067e04a2020-03-31 12:53:13 +00005007
5008 if detailed_status:
garciadeblas5697b8b2021-03-24 09:17:02 +01005009 nslcmop_operation_state = "COMPLETED"
tierno067e04a2020-03-31 12:53:13 +00005010 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01005011 detailed_status = ""
5012 nslcmop_operation_state = "FAILED"
tierno067e04a2020-03-31 12:53:13 +00005013 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01005014 ee_id, vca_type = self._look_for_deployed_vca(
5015 nsr_deployed["VCA"],
5016 member_vnf_index=vnf_index,
5017 vdu_id=vdu_id,
5018 vdu_count_index=vdu_count_index,
5019 ee_descriptor_id=ee_descriptor_id,
5020 )
5021 for vca_index, vca_deployed in enumerate(
5022 db_nsr["_admin"]["deployed"]["VCA"]
5023 ):
ksaikiranrb1c9f372021-03-15 11:07:29 +05305024 if vca_deployed.get("member-vnf-index") == vnf_index:
garciadeblas5697b8b2021-03-24 09:17:02 +01005025 db_dict = {
5026 "collection": "nsrs",
5027 "filter": {"_id": nsr_id},
5028 "path": "_admin.deployed.VCA.{}.".format(vca_index),
5029 }
ksaikiranrb1c9f372021-03-15 11:07:29 +05305030 break
garciadeblas5697b8b2021-03-24 09:17:02 +01005031 (
5032 nslcmop_operation_state,
5033 detailed_status,
5034 ) = await self._ns_execute_primitive(
tierno588547c2020-07-01 15:30:20 +00005035 ee_id,
tiernoa278b842020-07-08 15:33:55 +00005036 primitive=primitive_name,
garciadeblas5697b8b2021-03-24 09:17:02 +01005037 primitive_params=self._map_primitive_params(
5038 config_primitive_desc, primitive_params, desc_params
5039 ),
tierno588547c2020-07-01 15:30:20 +00005040 timeout=timeout_ns_action,
5041 vca_type=vca_type,
David Garciac1fe90a2021-03-31 19:12:02 +02005042 db_dict=db_dict,
5043 vca_id=vca_id,
5044 )
tierno067e04a2020-03-31 12:53:13 +00005045
5046 db_nslcmop_update["detailed-status"] = detailed_status
garciadeblas5697b8b2021-03-24 09:17:02 +01005047 error_description_nslcmop = (
5048 detailed_status if nslcmop_operation_state == "FAILED" else ""
5049 )
5050 self.logger.debug(
5051 logging_text
5052 + " task Done with result {} {}".format(
5053 nslcmop_operation_state, detailed_status
5054 )
5055 )
tierno59d22d22018-09-25 18:10:19 +02005056 return # database update is called inside finally
5057
tiernof59ad6c2020-04-08 12:50:52 +00005058 except (DbException, LcmException, N2VCException, K8sException) as e:
tierno59d22d22018-09-25 18:10:19 +02005059 self.logger.error(logging_text + "Exit Exception {}".format(e))
5060 exc = e
5061 except asyncio.CancelledError:
garciadeblas5697b8b2021-03-24 09:17:02 +01005062 self.logger.error(
5063 logging_text + "Cancelled Exception while '{}'".format(step)
5064 )
tierno59d22d22018-09-25 18:10:19 +02005065 exc = "Operation was cancelled"
tierno067e04a2020-03-31 12:53:13 +00005066 except asyncio.TimeoutError:
5067 self.logger.error(logging_text + "Timeout while '{}'".format(step))
5068 exc = "Timeout"
tierno59d22d22018-09-25 18:10:19 +02005069 except Exception as e:
5070 exc = traceback.format_exc()
garciadeblas5697b8b2021-03-24 09:17:02 +01005071 self.logger.critical(
5072 logging_text + "Exit Exception {} {}".format(type(e).__name__, e),
5073 exc_info=True,
5074 )
tierno59d22d22018-09-25 18:10:19 +02005075 finally:
tierno067e04a2020-03-31 12:53:13 +00005076 if exc:
garciadeblas5697b8b2021-03-24 09:17:02 +01005077 db_nslcmop_update[
5078 "detailed-status"
5079 ] = (
5080 detailed_status
5081 ) = error_description_nslcmop = "FAILED {}: {}".format(step, exc)
tierno067e04a2020-03-31 12:53:13 +00005082 nslcmop_operation_state = "FAILED"
5083 if db_nsr:
5084 self._write_ns_status(
5085 nsr_id=nsr_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01005086 ns_state=db_nsr[
5087 "nsState"
5088 ], # TODO check if degraded. For the moment use previous status
tierno067e04a2020-03-31 12:53:13 +00005089 current_operation="IDLE",
5090 current_operation_id=None,
5091 # error_description=error_description_nsr,
5092 # error_detail=error_detail,
garciadeblas5697b8b2021-03-24 09:17:02 +01005093 other_update=db_nsr_update,
tierno067e04a2020-03-31 12:53:13 +00005094 )
5095
garciadeblas5697b8b2021-03-24 09:17:02 +01005096 self._write_op_status(
5097 op_id=nslcmop_id,
5098 stage="",
5099 error_message=error_description_nslcmop,
5100 operation_state=nslcmop_operation_state,
5101 other_update=db_nslcmop_update,
5102 )
tierno067e04a2020-03-31 12:53:13 +00005103
tierno59d22d22018-09-25 18:10:19 +02005104 if nslcmop_operation_state:
5105 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01005106 await self.msg.aiowrite(
5107 "ns",
5108 "actioned",
5109 {
5110 "nsr_id": nsr_id,
5111 "nslcmop_id": nslcmop_id,
5112 "operationState": nslcmop_operation_state,
5113 },
5114 loop=self.loop,
5115 )
tierno59d22d22018-09-25 18:10:19 +02005116 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01005117 self.logger.error(
5118 logging_text + "kafka_write notification Exception {}".format(e)
5119 )
tierno59d22d22018-09-25 18:10:19 +02005120 self.logger.debug(logging_text + "Exit")
5121 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_action")
tierno067e04a2020-03-31 12:53:13 +00005122 return nslcmop_operation_state, detailed_status
tierno59d22d22018-09-25 18:10:19 +02005123
5124 async def scale(self, nsr_id, nslcmop_id):
kuused124bfe2019-06-18 12:09:24 +02005125 # Try to lock HA task here
garciadeblas5697b8b2021-03-24 09:17:02 +01005126 task_is_locked_by_me = self.lcm_tasks.lock_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02005127 if not task_is_locked_by_me:
5128 return
5129
tierno59d22d22018-09-25 18:10:19 +02005130 logging_text = "Task ns={} scale={} ".format(nsr_id, nslcmop_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01005131 stage = ["", "", ""]
aktas13251562021-02-12 22:19:10 +03005132 tasks_dict_info = {}
tierno2357f4e2020-10-19 16:38:59 +00005133 # ^ stage, step, VIM progress
tierno59d22d22018-09-25 18:10:19 +02005134 self.logger.debug(logging_text + "Enter")
5135 # get all needed from database
5136 db_nsr = None
tierno59d22d22018-09-25 18:10:19 +02005137 db_nslcmop_update = {}
tiernoe876f672020-02-13 14:34:48 +00005138 db_nsr_update = {}
tierno59d22d22018-09-25 18:10:19 +02005139 exc = None
tierno9ab95942018-10-10 16:44:22 +02005140 # in case of error, indicates what part of scale was failed to put nsr at error status
5141 scale_process = None
tiernod6de1992018-10-11 13:05:52 +02005142 old_operational_status = ""
5143 old_config_status = ""
aktas13251562021-02-12 22:19:10 +03005144 nsi_id = None
tierno59d22d22018-09-25 18:10:19 +02005145 try:
kuused124bfe2019-06-18 12:09:24 +02005146 # wait for any previous tasks in process
tierno3cf81a32019-11-11 17:07:00 +00005147 step = "Waiting for previous operations to terminate"
garciadeblas5697b8b2021-03-24 09:17:02 +01005148 await self.lcm_tasks.waitfor_related_HA("ns", "nslcmops", nslcmop_id)
5149 self._write_ns_status(
5150 nsr_id=nsr_id,
5151 ns_state=None,
5152 current_operation="SCALING",
5153 current_operation_id=nslcmop_id,
5154 )
quilesj4cda56b2019-12-05 10:02:20 +00005155
ikalyvas02d9e7b2019-05-27 18:16:01 +03005156 step = "Getting nslcmop from database"
garciadeblas5697b8b2021-03-24 09:17:02 +01005157 self.logger.debug(
5158 step + " after having waited for previous tasks to be completed"
5159 )
ikalyvas02d9e7b2019-05-27 18:16:01 +03005160 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
bravof922c4172020-11-24 21:21:43 -03005161
ikalyvas02d9e7b2019-05-27 18:16:01 +03005162 step = "Getting nsr from database"
5163 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
ikalyvas02d9e7b2019-05-27 18:16:01 +03005164 old_operational_status = db_nsr["operational-status"]
5165 old_config_status = db_nsr["config-status"]
bravof922c4172020-11-24 21:21:43 -03005166
tierno59d22d22018-09-25 18:10:19 +02005167 step = "Parsing scaling parameters"
5168 db_nsr_update["operational-status"] = "scaling"
5169 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernoe4f7e6c2018-11-27 14:55:30 +00005170 nsr_deployed = db_nsr["_admin"].get("deployed")
calvinosanch9f9c6f22019-11-04 13:37:39 +01005171
garciadeblas5697b8b2021-03-24 09:17:02 +01005172 vnf_index = db_nslcmop["operationParams"]["scaleVnfData"][
5173 "scaleByStepData"
5174 ]["member-vnf-index"]
5175 scaling_group = db_nslcmop["operationParams"]["scaleVnfData"][
5176 "scaleByStepData"
5177 ]["scaling-group-descriptor"]
tierno59d22d22018-09-25 18:10:19 +02005178 scaling_type = db_nslcmop["operationParams"]["scaleVnfData"]["scaleVnfType"]
tierno82974b22018-11-27 21:55:36 +00005179 # for backward compatibility
5180 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
5181 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
5182 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
5183 self.update_db_2("nsrs", nsr_id, db_nsr_update)
5184
tierno59d22d22018-09-25 18:10:19 +02005185 step = "Getting vnfr from database"
garciadeblas5697b8b2021-03-24 09:17:02 +01005186 db_vnfr = self.db.get_one(
5187 "vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id}
5188 )
bravof922c4172020-11-24 21:21:43 -03005189
David Garciac1fe90a2021-03-31 19:12:02 +02005190 vca_id = self.get_vca_id(db_vnfr, db_nsr)
5191
tierno59d22d22018-09-25 18:10:19 +02005192 step = "Getting vnfd from database"
5193 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
ikalyvas02d9e7b2019-05-27 18:16:01 +03005194
aktas13251562021-02-12 22:19:10 +03005195 base_folder = db_vnfd["_admin"]["storage"]
5196
tierno59d22d22018-09-25 18:10:19 +02005197 step = "Getting scaling-group-descriptor"
bravof832f8992020-12-07 12:57:31 -03005198 scaling_descriptor = find_in_list(
garciadeblas5697b8b2021-03-24 09:17:02 +01005199 get_scaling_aspect(db_vnfd),
5200 lambda scale_desc: scale_desc["name"] == scaling_group,
bravof832f8992020-12-07 12:57:31 -03005201 )
5202 if not scaling_descriptor:
garciadeblas5697b8b2021-03-24 09:17:02 +01005203 raise LcmException(
5204 "input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
5205 "at vnfd:scaling-group-descriptor".format(scaling_group)
5206 )
ikalyvas02d9e7b2019-05-27 18:16:01 +03005207
tierno15b1cf12019-08-29 13:21:40 +00005208 step = "Sending scale order to VIM"
bravof922c4172020-11-24 21:21:43 -03005209 # TODO check if ns is in a proper status
tierno59d22d22018-09-25 18:10:19 +02005210 nb_scale_op = 0
5211 if not db_nsr["_admin"].get("scaling-group"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005212 self.update_db_2(
5213 "nsrs",
5214 nsr_id,
5215 {
5216 "_admin.scaling-group": [
5217 {"name": scaling_group, "nb-scale-op": 0}
5218 ]
5219 },
5220 )
tierno59d22d22018-09-25 18:10:19 +02005221 admin_scale_index = 0
5222 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01005223 for admin_scale_index, admin_scale_info in enumerate(
5224 db_nsr["_admin"]["scaling-group"]
5225 ):
tierno59d22d22018-09-25 18:10:19 +02005226 if admin_scale_info["name"] == scaling_group:
5227 nb_scale_op = admin_scale_info.get("nb-scale-op", 0)
5228 break
tierno9ab95942018-10-10 16:44:22 +02005229 else: # not found, set index one plus last element and add new entry with the name
5230 admin_scale_index += 1
garciadeblas5697b8b2021-03-24 09:17:02 +01005231 db_nsr_update[
5232 "_admin.scaling-group.{}.name".format(admin_scale_index)
5233 ] = scaling_group
aktas5f75f102021-03-15 11:26:10 +03005234
5235 vca_scaling_info = []
5236 scaling_info = {"scaling_group_name": scaling_group, "vdu": [], "kdu": []}
tierno59d22d22018-09-25 18:10:19 +02005237 if scaling_type == "SCALE_OUT":
bravof832f8992020-12-07 12:57:31 -03005238 if "aspect-delta-details" not in scaling_descriptor:
5239 raise LcmException(
5240 "Aspect delta details not fount in scaling descriptor {}".format(
5241 scaling_descriptor["name"]
5242 )
5243 )
tierno59d22d22018-09-25 18:10:19 +02005244 # count if max-instance-count is reached
bravof832f8992020-12-07 12:57:31 -03005245 deltas = scaling_descriptor.get("aspect-delta-details")["deltas"]
kuuse8b998e42019-07-30 15:22:16 +02005246
aktas5f75f102021-03-15 11:26:10 +03005247 scaling_info["scaling_direction"] = "OUT"
5248 scaling_info["vdu-create"] = {}
5249 scaling_info["kdu-create"] = {}
bravof832f8992020-12-07 12:57:31 -03005250 for delta in deltas:
aktas5f75f102021-03-15 11:26:10 +03005251 for vdu_delta in delta.get("vdu-delta", {}):
bravof832f8992020-12-07 12:57:31 -03005252 vdud = get_vdu(db_vnfd, vdu_delta["id"])
aktas5f75f102021-03-15 11:26:10 +03005253 # vdu_index also provides the number of instance of the targeted vdu
5254 vdu_count = vdu_index = get_vdur_index(db_vnfr, vdu_delta)
garciadeblas5697b8b2021-03-24 09:17:02 +01005255 cloud_init_text = self._get_vdu_cloud_init_content(
5256 vdud, db_vnfd
5257 )
tierno72ef84f2020-10-06 08:22:07 +00005258 if cloud_init_text:
garciadeblas5697b8b2021-03-24 09:17:02 +01005259 additional_params = (
5260 self._get_vdu_additional_params(db_vnfr, vdud["id"])
5261 or {}
5262 )
bravof832f8992020-12-07 12:57:31 -03005263 cloud_init_list = []
5264
5265 vdu_profile = get_vdu_profile(db_vnfd, vdu_delta["id"])
5266 max_instance_count = 10
5267 if vdu_profile and "max-number-of-instances" in vdu_profile:
garciadeblas5697b8b2021-03-24 09:17:02 +01005268 max_instance_count = vdu_profile.get(
5269 "max-number-of-instances", 10
5270 )
5271
5272 default_instance_num = get_number_of_instances(
5273 db_vnfd, vdud["id"]
5274 )
aktas5f75f102021-03-15 11:26:10 +03005275 instances_number = vdu_delta.get("number-of-instances", 1)
5276 nb_scale_op += instances_number
bravof832f8992020-12-07 12:57:31 -03005277
aktas5f75f102021-03-15 11:26:10 +03005278 new_instance_count = nb_scale_op + default_instance_num
5279 # Control if new count is over max and vdu count is less than max.
5280 # Then assign new instance count
5281 if new_instance_count > max_instance_count > vdu_count:
5282 instances_number = new_instance_count - max_instance_count
5283 else:
5284 instances_number = instances_number
bravof832f8992020-12-07 12:57:31 -03005285
aktas5f75f102021-03-15 11:26:10 +03005286 if new_instance_count > max_instance_count:
bravof832f8992020-12-07 12:57:31 -03005287 raise LcmException(
5288 "reached the limit of {} (max-instance-count) "
5289 "scaling-out operations for the "
garciadeblas5697b8b2021-03-24 09:17:02 +01005290 "scaling-group-descriptor '{}'".format(
5291 nb_scale_op, scaling_group
5292 )
bravof922c4172020-11-24 21:21:43 -03005293 )
bravof832f8992020-12-07 12:57:31 -03005294 for x in range(vdu_delta.get("number-of-instances", 1)):
5295 if cloud_init_text:
5296 # TODO Information of its own ip is not available because db_vnfr is not updated.
5297 additional_params["OSM"] = get_osm_params(
garciadeblas5697b8b2021-03-24 09:17:02 +01005298 db_vnfr, vdu_delta["id"], vdu_index + x
bravof922c4172020-11-24 21:21:43 -03005299 )
bravof832f8992020-12-07 12:57:31 -03005300 cloud_init_list.append(
5301 self._parse_cloud_init(
5302 cloud_init_text,
5303 additional_params,
5304 db_vnfd["id"],
garciadeblas5697b8b2021-03-24 09:17:02 +01005305 vdud["id"],
bravof832f8992020-12-07 12:57:31 -03005306 )
5307 )
aktas5f75f102021-03-15 11:26:10 +03005308 vca_scaling_info.append(
aktas13251562021-02-12 22:19:10 +03005309 {
5310 "osm_vdu_id": vdu_delta["id"],
5311 "member-vnf-index": vnf_index,
5312 "type": "create",
garciadeblas5697b8b2021-03-24 09:17:02 +01005313 "vdu_index": vdu_index + x,
aktas13251562021-02-12 22:19:10 +03005314 }
5315 )
aktas5f75f102021-03-15 11:26:10 +03005316 scaling_info["vdu-create"][vdu_delta["id"]] = instances_number
5317 for kdu_delta in delta.get("kdu-resource-delta", {}):
David Garciab4ebcd02021-10-28 02:00:43 +02005318 kdu_profile = get_kdu_resource_profile(db_vnfd, kdu_delta["id"])
aktas5f75f102021-03-15 11:26:10 +03005319 kdu_name = kdu_profile["kdu-name"]
5320 resource_name = kdu_profile["resource-name"]
5321
5322 # Might have different kdus in the same delta
5323 # Should have list for each kdu
5324 if not scaling_info["kdu-create"].get(kdu_name, None):
5325 scaling_info["kdu-create"][kdu_name] = []
5326
5327 kdur = get_kdur(db_vnfr, kdu_name)
5328 if kdur.get("helm-chart"):
5329 k8s_cluster_type = "helm-chart-v3"
5330 self.logger.debug("kdur: {}".format(kdur))
5331 if (
5332 kdur.get("helm-version")
5333 and kdur.get("helm-version") == "v2"
5334 ):
5335 k8s_cluster_type = "helm-chart"
5336 raise NotImplementedError
5337 elif kdur.get("juju-bundle"):
5338 k8s_cluster_type = "juju-bundle"
5339 else:
5340 raise LcmException(
5341 "kdu type for kdu='{}.{}' is neither helm-chart nor "
5342 "juju-bundle. Maybe an old NBI version is running".format(
5343 db_vnfr["member-vnf-index-ref"], kdu_name
5344 )
5345 )
5346
5347 max_instance_count = 10
5348 if kdu_profile and "max-number-of-instances" in kdu_profile:
5349 max_instance_count = kdu_profile.get(
5350 "max-number-of-instances", 10
5351 )
5352
5353 nb_scale_op += kdu_delta.get("number-of-instances", 1)
5354 deployed_kdu, _ = get_deployed_kdu(
5355 nsr_deployed, kdu_name, vnf_index
bravof832f8992020-12-07 12:57:31 -03005356 )
aktas5f75f102021-03-15 11:26:10 +03005357 if deployed_kdu is None:
5358 raise LcmException(
5359 "KDU '{}' for vnf '{}' not deployed".format(
5360 kdu_name, vnf_index
5361 )
5362 )
5363 kdu_instance = deployed_kdu.get("kdu-instance")
5364 instance_num = await self.k8scluster_map[
5365 k8s_cluster_type
5366 ].get_scale_count(resource_name, kdu_instance, vca_id=vca_id)
5367 kdu_replica_count = instance_num + kdu_delta.get(
garciadeblas5697b8b2021-03-24 09:17:02 +01005368 "number-of-instances", 1
5369 )
ikalyvas02d9e7b2019-05-27 18:16:01 +03005370
aktas5f75f102021-03-15 11:26:10 +03005371 # Control if new count is over max and instance_num is less than max.
5372 # Then assign max instance number to kdu replica count
5373 if kdu_replica_count > max_instance_count > instance_num:
5374 kdu_replica_count = max_instance_count
5375 if kdu_replica_count > max_instance_count:
5376 raise LcmException(
5377 "reached the limit of {} (max-instance-count) "
5378 "scaling-out operations for the "
5379 "scaling-group-descriptor '{}'".format(
5380 instance_num, scaling_group
5381 )
5382 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005383
aktas5f75f102021-03-15 11:26:10 +03005384 for x in range(kdu_delta.get("number-of-instances", 1)):
5385 vca_scaling_info.append(
5386 {
5387 "osm_kdu_id": kdu_name,
5388 "member-vnf-index": vnf_index,
5389 "type": "create",
5390 "kdu_index": instance_num + x - 1,
5391 }
5392 )
5393 scaling_info["kdu-create"][kdu_name].append(
5394 {
5395 "member-vnf-index": vnf_index,
5396 "type": "create",
5397 "k8s-cluster-type": k8s_cluster_type,
5398 "resource-name": resource_name,
5399 "scale": kdu_replica_count,
5400 }
5401 )
5402 elif scaling_type == "SCALE_IN":
bravof832f8992020-12-07 12:57:31 -03005403 deltas = scaling_descriptor.get("aspect-delta-details")["deltas"]
aktas5f75f102021-03-15 11:26:10 +03005404
5405 scaling_info["scaling_direction"] = "IN"
5406 scaling_info["vdu-delete"] = {}
5407 scaling_info["kdu-delete"] = {}
5408
bravof832f8992020-12-07 12:57:31 -03005409 for delta in deltas:
aktas5f75f102021-03-15 11:26:10 +03005410 for vdu_delta in delta.get("vdu-delta", {}):
5411 vdu_count = vdu_index = get_vdur_index(db_vnfr, vdu_delta)
bravof832f8992020-12-07 12:57:31 -03005412 min_instance_count = 0
5413 vdu_profile = get_vdu_profile(db_vnfd, vdu_delta["id"])
5414 if vdu_profile and "min-number-of-instances" in vdu_profile:
5415 min_instance_count = vdu_profile["min-number-of-instances"]
5416
garciadeblas5697b8b2021-03-24 09:17:02 +01005417 default_instance_num = get_number_of_instances(
5418 db_vnfd, vdu_delta["id"]
5419 )
aktas5f75f102021-03-15 11:26:10 +03005420 instance_num = vdu_delta.get("number-of-instances", 1)
5421 nb_scale_op -= instance_num
bravof832f8992020-12-07 12:57:31 -03005422
aktas5f75f102021-03-15 11:26:10 +03005423 new_instance_count = nb_scale_op + default_instance_num
5424
5425 if new_instance_count < min_instance_count < vdu_count:
5426 instances_number = min_instance_count - new_instance_count
5427 else:
5428 instances_number = instance_num
5429
5430 if new_instance_count < min_instance_count:
bravof832f8992020-12-07 12:57:31 -03005431 raise LcmException(
5432 "reached the limit of {} (min-instance-count) scaling-in operations for the "
garciadeblas5697b8b2021-03-24 09:17:02 +01005433 "scaling-group-descriptor '{}'".format(
5434 nb_scale_op, scaling_group
5435 )
bravof832f8992020-12-07 12:57:31 -03005436 )
aktas13251562021-02-12 22:19:10 +03005437 for x in range(vdu_delta.get("number-of-instances", 1)):
aktas5f75f102021-03-15 11:26:10 +03005438 vca_scaling_info.append(
aktas13251562021-02-12 22:19:10 +03005439 {
5440 "osm_vdu_id": vdu_delta["id"],
5441 "member-vnf-index": vnf_index,
5442 "type": "delete",
garciadeblas5697b8b2021-03-24 09:17:02 +01005443 "vdu_index": vdu_index - 1 - x,
aktas13251562021-02-12 22:19:10 +03005444 }
5445 )
aktas5f75f102021-03-15 11:26:10 +03005446 scaling_info["vdu-delete"][vdu_delta["id"]] = instances_number
5447 for kdu_delta in delta.get("kdu-resource-delta", {}):
David Garciab4ebcd02021-10-28 02:00:43 +02005448 kdu_profile = get_kdu_resource_profile(db_vnfd, kdu_delta["id"])
aktas5f75f102021-03-15 11:26:10 +03005449 kdu_name = kdu_profile["kdu-name"]
5450 resource_name = kdu_profile["resource-name"]
5451
5452 if not scaling_info["kdu-delete"].get(kdu_name, None):
5453 scaling_info["kdu-delete"][kdu_name] = []
5454
5455 kdur = get_kdur(db_vnfr, kdu_name)
5456 if kdur.get("helm-chart"):
5457 k8s_cluster_type = "helm-chart-v3"
5458 self.logger.debug("kdur: {}".format(kdur))
5459 if (
5460 kdur.get("helm-version")
5461 and kdur.get("helm-version") == "v2"
5462 ):
5463 k8s_cluster_type = "helm-chart"
5464 raise NotImplementedError
5465 elif kdur.get("juju-bundle"):
5466 k8s_cluster_type = "juju-bundle"
5467 else:
5468 raise LcmException(
5469 "kdu type for kdu='{}.{}' is neither helm-chart nor "
5470 "juju-bundle. Maybe an old NBI version is running".format(
5471 db_vnfr["member-vnf-index-ref"], kdur["kdu-name"]
5472 )
5473 )
5474
5475 min_instance_count = 0
5476 if kdu_profile and "min-number-of-instances" in kdu_profile:
5477 min_instance_count = kdu_profile["min-number-of-instances"]
5478
5479 nb_scale_op -= kdu_delta.get("number-of-instances", 1)
5480 deployed_kdu, _ = get_deployed_kdu(
5481 nsr_deployed, kdu_name, vnf_index
5482 )
5483 if deployed_kdu is None:
5484 raise LcmException(
5485 "KDU '{}' for vnf '{}' not deployed".format(
5486 kdu_name, vnf_index
5487 )
5488 )
5489 kdu_instance = deployed_kdu.get("kdu-instance")
5490 instance_num = await self.k8scluster_map[
5491 k8s_cluster_type
5492 ].get_scale_count(resource_name, kdu_instance, vca_id=vca_id)
5493 kdu_replica_count = instance_num - kdu_delta.get(
garciadeblas5697b8b2021-03-24 09:17:02 +01005494 "number-of-instances", 1
5495 )
tierno59d22d22018-09-25 18:10:19 +02005496
aktas5f75f102021-03-15 11:26:10 +03005497 if kdu_replica_count < min_instance_count < instance_num:
5498 kdu_replica_count = min_instance_count
5499 if kdu_replica_count < min_instance_count:
5500 raise LcmException(
5501 "reached the limit of {} (min-instance-count) scaling-in operations for the "
5502 "scaling-group-descriptor '{}'".format(
5503 instance_num, scaling_group
5504 )
5505 )
5506
5507 for x in range(kdu_delta.get("number-of-instances", 1)):
5508 vca_scaling_info.append(
5509 {
5510 "osm_kdu_id": kdu_name,
5511 "member-vnf-index": vnf_index,
5512 "type": "delete",
5513 "kdu_index": instance_num - x - 1,
5514 }
5515 )
5516 scaling_info["kdu-delete"][kdu_name].append(
5517 {
5518 "member-vnf-index": vnf_index,
5519 "type": "delete",
5520 "k8s-cluster-type": k8s_cluster_type,
5521 "resource-name": resource_name,
5522 "scale": kdu_replica_count,
5523 }
5524 )
5525
tierno59d22d22018-09-25 18:10:19 +02005526 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
aktas5f75f102021-03-15 11:26:10 +03005527 vdu_delete = copy(scaling_info.get("vdu-delete"))
5528 if scaling_info["scaling_direction"] == "IN":
tierno59d22d22018-09-25 18:10:19 +02005529 for vdur in reversed(db_vnfr["vdur"]):
tierno27246d82018-09-27 15:59:09 +02005530 if vdu_delete.get(vdur["vdu-id-ref"]):
5531 vdu_delete[vdur["vdu-id-ref"]] -= 1
aktas5f75f102021-03-15 11:26:10 +03005532 scaling_info["vdu"].append(
garciadeblas5697b8b2021-03-24 09:17:02 +01005533 {
5534 "name": vdur.get("name") or vdur.get("vdu-name"),
5535 "vdu_id": vdur["vdu-id-ref"],
5536 "interface": [],
5537 }
5538 )
tierno59d22d22018-09-25 18:10:19 +02005539 for interface in vdur["interfaces"]:
aktas5f75f102021-03-15 11:26:10 +03005540 scaling_info["vdu"][-1]["interface"].append(
garciadeblas5697b8b2021-03-24 09:17:02 +01005541 {
5542 "name": interface["name"],
5543 "ip_address": interface["ip-address"],
5544 "mac_address": interface.get("mac-address"),
5545 }
5546 )
tierno2357f4e2020-10-19 16:38:59 +00005547 # vdu_delete = vdu_scaling_info.pop("vdu-delete")
tierno59d22d22018-09-25 18:10:19 +02005548
kuuseac3a8882019-10-03 10:48:06 +02005549 # PRE-SCALE BEGIN
tierno59d22d22018-09-25 18:10:19 +02005550 step = "Executing pre-scale vnf-config-primitive"
5551 if scaling_descriptor.get("scaling-config-action"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005552 for scaling_config_action in scaling_descriptor[
5553 "scaling-config-action"
5554 ]:
5555 if (
5556 scaling_config_action.get("trigger") == "pre-scale-in"
5557 and scaling_type == "SCALE_IN"
5558 ) or (
5559 scaling_config_action.get("trigger") == "pre-scale-out"
5560 and scaling_type == "SCALE_OUT"
5561 ):
5562 vnf_config_primitive = scaling_config_action[
5563 "vnf-config-primitive-name-ref"
5564 ]
5565 step = db_nslcmop_update[
5566 "detailed-status"
5567 ] = "executing pre-scale scaling-config-action '{}'".format(
5568 vnf_config_primitive
5569 )
tiernoda964822019-01-14 15:53:47 +00005570
tierno59d22d22018-09-25 18:10:19 +02005571 # look for primitive
garciadeblas5697b8b2021-03-24 09:17:02 +01005572 for config_primitive in (
5573 get_configuration(db_vnfd, db_vnfd["id"]) or {}
5574 ).get("config-primitive", ()):
tierno59d22d22018-09-25 18:10:19 +02005575 if config_primitive["name"] == vnf_config_primitive:
tierno59d22d22018-09-25 18:10:19 +02005576 break
5577 else:
5578 raise LcmException(
5579 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
tiernoda964822019-01-14 15:53:47 +00005580 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
garciadeblas5697b8b2021-03-24 09:17:02 +01005581 "primitive".format(scaling_group, vnf_config_primitive)
5582 )
tiernoda964822019-01-14 15:53:47 +00005583
aktas5f75f102021-03-15 11:26:10 +03005584 vnfr_params = {"VDU_SCALE_INFO": scaling_info}
tiernoda964822019-01-14 15:53:47 +00005585 if db_vnfr.get("additionalParamsForVnf"):
5586 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
quilesj7e13aeb2019-10-08 13:34:55 +02005587
tierno9ab95942018-10-10 16:44:22 +02005588 scale_process = "VCA"
tiernod6de1992018-10-11 13:05:52 +02005589 db_nsr_update["config-status"] = "configuring pre-scaling"
garciadeblas5697b8b2021-03-24 09:17:02 +01005590 primitive_params = self._map_primitive_params(
5591 config_primitive, {}, vnfr_params
5592 )
kuuseac3a8882019-10-03 10:48:06 +02005593
tierno7c4e24c2020-05-13 08:41:35 +00005594 # Pre-scale retry check: Check if this sub-operation has been executed before
kuuseac3a8882019-10-03 10:48:06 +02005595 op_index = self._check_or_add_scale_suboperation(
garciadeblas5697b8b2021-03-24 09:17:02 +01005596 db_nslcmop,
garciadeblas5697b8b2021-03-24 09:17:02 +01005597 vnf_index,
5598 vnf_config_primitive,
5599 primitive_params,
5600 "PRE-SCALE",
5601 )
tierno7c4e24c2020-05-13 08:41:35 +00005602 if op_index == self.SUBOPERATION_STATUS_SKIP:
kuuseac3a8882019-10-03 10:48:06 +02005603 # Skip sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01005604 result = "COMPLETED"
5605 result_detail = "Done"
5606 self.logger.debug(
5607 logging_text
5608 + "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
5609 vnf_config_primitive, result, result_detail
5610 )
5611 )
kuuseac3a8882019-10-03 10:48:06 +02005612 else:
tierno7c4e24c2020-05-13 08:41:35 +00005613 if op_index == self.SUBOPERATION_STATUS_NEW:
kuuseac3a8882019-10-03 10:48:06 +02005614 # New sub-operation: Get index of this sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01005615 op_index = (
5616 len(db_nslcmop.get("_admin", {}).get("operations"))
5617 - 1
5618 )
5619 self.logger.debug(
5620 logging_text
5621 + "vnf_config_primitive={} New sub-operation".format(
5622 vnf_config_primitive
5623 )
5624 )
kuuseac3a8882019-10-03 10:48:06 +02005625 else:
tierno7c4e24c2020-05-13 08:41:35 +00005626 # retry: Get registered params for this existing sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01005627 op = db_nslcmop.get("_admin", {}).get("operations", [])[
5628 op_index
5629 ]
5630 vnf_index = op.get("member_vnf_index")
5631 vnf_config_primitive = op.get("primitive")
5632 primitive_params = op.get("primitive_params")
5633 self.logger.debug(
5634 logging_text
5635 + "vnf_config_primitive={} Sub-operation retry".format(
5636 vnf_config_primitive
5637 )
5638 )
tierno588547c2020-07-01 15:30:20 +00005639 # Execute the primitive, either with new (first-time) or registered (reintent) args
garciadeblas5697b8b2021-03-24 09:17:02 +01005640 ee_descriptor_id = config_primitive.get(
5641 "execution-environment-ref"
5642 )
5643 primitive_name = config_primitive.get(
5644 "execution-environment-primitive", vnf_config_primitive
5645 )
5646 ee_id, vca_type = self._look_for_deployed_vca(
5647 nsr_deployed["VCA"],
5648 member_vnf_index=vnf_index,
5649 vdu_id=None,
5650 vdu_count_index=None,
5651 ee_descriptor_id=ee_descriptor_id,
5652 )
kuuseac3a8882019-10-03 10:48:06 +02005653 result, result_detail = await self._ns_execute_primitive(
garciadeblas5697b8b2021-03-24 09:17:02 +01005654 ee_id,
5655 primitive_name,
David Garciac1fe90a2021-03-31 19:12:02 +02005656 primitive_params,
5657 vca_type=vca_type,
5658 vca_id=vca_id,
5659 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005660 self.logger.debug(
5661 logging_text
5662 + "vnf_config_primitive={} Done with result {} {}".format(
5663 vnf_config_primitive, result, result_detail
5664 )
5665 )
kuuseac3a8882019-10-03 10:48:06 +02005666 # Update operationState = COMPLETED | FAILED
5667 self._update_suboperation_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01005668 db_nslcmop, op_index, result, result_detail
5669 )
kuuseac3a8882019-10-03 10:48:06 +02005670
tierno59d22d22018-09-25 18:10:19 +02005671 if result == "FAILED":
5672 raise LcmException(result_detail)
tiernod6de1992018-10-11 13:05:52 +02005673 db_nsr_update["config-status"] = old_config_status
5674 scale_process = None
kuuseac3a8882019-10-03 10:48:06 +02005675 # PRE-SCALE END
tierno59d22d22018-09-25 18:10:19 +02005676
garciadeblas5697b8b2021-03-24 09:17:02 +01005677 db_nsr_update[
5678 "_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index)
5679 ] = nb_scale_op
5680 db_nsr_update[
5681 "_admin.scaling-group.{}.time".format(admin_scale_index)
5682 ] = time()
tierno2357f4e2020-10-19 16:38:59 +00005683
aktas13251562021-02-12 22:19:10 +03005684 # SCALE-IN VCA - BEGIN
aktas5f75f102021-03-15 11:26:10 +03005685 if vca_scaling_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01005686 step = db_nslcmop_update[
5687 "detailed-status"
5688 ] = "Deleting the execution environments"
aktas13251562021-02-12 22:19:10 +03005689 scale_process = "VCA"
aktas5f75f102021-03-15 11:26:10 +03005690 for vca_info in vca_scaling_info:
5691 if vca_info["type"] == "delete":
5692 member_vnf_index = str(vca_info["member-vnf-index"])
garciadeblas5697b8b2021-03-24 09:17:02 +01005693 self.logger.debug(
aktas5f75f102021-03-15 11:26:10 +03005694 logging_text + "vdu info: {}".format(vca_info)
garciadeblas5697b8b2021-03-24 09:17:02 +01005695 )
aktas5f75f102021-03-15 11:26:10 +03005696 if vca_info.get("osm_vdu_id"):
5697 vdu_id = vca_info["osm_vdu_id"]
5698 vdu_index = int(vca_info["vdu_index"])
5699 stage[
5700 1
5701 ] = "Scaling member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
5702 member_vnf_index, vdu_id, vdu_index
5703 )
5704 else:
5705 vdu_index = 0
5706 kdu_id = vca_info["osm_kdu_id"]
5707 stage[
5708 1
5709 ] = "Scaling member_vnf_index={}, kdu_id={}, vdu_index={} ".format(
5710 member_vnf_index, kdu_id, vdu_index
5711 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005712 stage[2] = step = "Scaling in VCA"
5713 self._write_op_status(op_id=nslcmop_id, stage=stage)
aktas13251562021-02-12 22:19:10 +03005714 vca_update = db_nsr["_admin"]["deployed"]["VCA"]
5715 config_update = db_nsr["configurationStatus"]
5716 for vca_index, vca in enumerate(vca_update):
garciadeblas5697b8b2021-03-24 09:17:02 +01005717 if (
5718 (vca or vca.get("ee_id"))
5719 and vca["member-vnf-index"] == member_vnf_index
5720 and vca["vdu_count_index"] == vdu_index
5721 ):
aktas13251562021-02-12 22:19:10 +03005722 if vca.get("vdu_id"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005723 config_descriptor = get_configuration(
5724 db_vnfd, vca.get("vdu_id")
5725 )
aktas13251562021-02-12 22:19:10 +03005726 elif vca.get("kdu_name"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005727 config_descriptor = get_configuration(
5728 db_vnfd, vca.get("kdu_name")
5729 )
aktas13251562021-02-12 22:19:10 +03005730 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01005731 config_descriptor = get_configuration(
5732 db_vnfd, db_vnfd["id"]
5733 )
5734 operation_params = (
5735 db_nslcmop.get("operationParams") or {}
5736 )
5737 exec_terminate_primitives = not operation_params.get(
5738 "skip_terminate_primitives"
5739 ) and vca.get("needed_terminate")
David Garciac1fe90a2021-03-31 19:12:02 +02005740 task = asyncio.ensure_future(
5741 asyncio.wait_for(
5742 self.destroy_N2VC(
5743 logging_text,
5744 db_nslcmop,
5745 vca,
5746 config_descriptor,
5747 vca_index,
5748 destroy_ee=True,
5749 exec_primitives=exec_terminate_primitives,
5750 scaling_in=True,
5751 vca_id=vca_id,
5752 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01005753 timeout=self.timeout_charm_delete,
David Garciac1fe90a2021-03-31 19:12:02 +02005754 )
5755 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005756 tasks_dict_info[task] = "Terminating VCA {}".format(
5757 vca.get("ee_id")
5758 )
aktas13251562021-02-12 22:19:10 +03005759 del vca_update[vca_index]
5760 del config_update[vca_index]
5761 # wait for pending tasks of terminate primitives
5762 if tasks_dict_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01005763 self.logger.debug(
5764 logging_text
5765 + "Waiting for tasks {}".format(
5766 list(tasks_dict_info.keys())
5767 )
5768 )
5769 error_list = await self._wait_for_tasks(
5770 logging_text,
5771 tasks_dict_info,
5772 min(
5773 self.timeout_charm_delete, self.timeout_ns_terminate
5774 ),
5775 stage,
5776 nslcmop_id,
5777 )
aktas13251562021-02-12 22:19:10 +03005778 tasks_dict_info.clear()
5779 if error_list:
5780 raise LcmException("; ".join(error_list))
5781
5782 db_vca_and_config_update = {
5783 "_admin.deployed.VCA": vca_update,
garciadeblas5697b8b2021-03-24 09:17:02 +01005784 "configurationStatus": config_update,
aktas13251562021-02-12 22:19:10 +03005785 }
garciadeblas5697b8b2021-03-24 09:17:02 +01005786 self.update_db_2(
5787 "nsrs", db_nsr["_id"], db_vca_and_config_update
5788 )
aktas13251562021-02-12 22:19:10 +03005789 scale_process = None
5790 # SCALE-IN VCA - END
5791
kuuseac3a8882019-10-03 10:48:06 +02005792 # SCALE RO - BEGIN
aktas5f75f102021-03-15 11:26:10 +03005793 if scaling_info.get("vdu-create") or scaling_info.get("vdu-delete"):
tierno9ab95942018-10-10 16:44:22 +02005794 scale_process = "RO"
tierno2357f4e2020-10-19 16:38:59 +00005795 if self.ro_config.get("ng"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005796 await self._scale_ng_ro(
aktas5f75f102021-03-15 11:26:10 +03005797 logging_text, db_nsr, db_nslcmop, db_vnfr, scaling_info, stage
garciadeblas5697b8b2021-03-24 09:17:02 +01005798 )
aktas5f75f102021-03-15 11:26:10 +03005799 scaling_info.pop("vdu-create", None)
5800 scaling_info.pop("vdu-delete", None)
tierno59d22d22018-09-25 18:10:19 +02005801
tierno9ab95942018-10-10 16:44:22 +02005802 scale_process = None
aktas13251562021-02-12 22:19:10 +03005803 # SCALE RO - END
5804
aktas5f75f102021-03-15 11:26:10 +03005805 # SCALE KDU - BEGIN
5806 if scaling_info.get("kdu-create") or scaling_info.get("kdu-delete"):
5807 scale_process = "KDU"
5808 await self._scale_kdu(
5809 logging_text, nsr_id, nsr_deployed, db_vnfd, vca_id, scaling_info
5810 )
5811 scaling_info.pop("kdu-create", None)
5812 scaling_info.pop("kdu-delete", None)
5813
5814 scale_process = None
5815 # SCALE KDU - END
5816
5817 if db_nsr_update:
5818 self.update_db_2("nsrs", nsr_id, db_nsr_update)
5819
aktas13251562021-02-12 22:19:10 +03005820 # SCALE-UP VCA - BEGIN
aktas5f75f102021-03-15 11:26:10 +03005821 if vca_scaling_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01005822 step = db_nslcmop_update[
5823 "detailed-status"
5824 ] = "Creating new execution environments"
aktas13251562021-02-12 22:19:10 +03005825 scale_process = "VCA"
aktas5f75f102021-03-15 11:26:10 +03005826 for vca_info in vca_scaling_info:
5827 if vca_info["type"] == "create":
5828 member_vnf_index = str(vca_info["member-vnf-index"])
garciadeblas5697b8b2021-03-24 09:17:02 +01005829 self.logger.debug(
aktas5f75f102021-03-15 11:26:10 +03005830 logging_text + "vdu info: {}".format(vca_info)
garciadeblas5697b8b2021-03-24 09:17:02 +01005831 )
aktas13251562021-02-12 22:19:10 +03005832 vnfd_id = db_vnfr["vnfd-ref"]
aktas5f75f102021-03-15 11:26:10 +03005833 if vca_info.get("osm_vdu_id"):
5834 vdu_index = int(vca_info["vdu_index"])
5835 deploy_params = {"OSM": get_osm_params(db_vnfr)}
5836 if db_vnfr.get("additionalParamsForVnf"):
5837 deploy_params.update(
5838 parse_yaml_strings(
5839 db_vnfr["additionalParamsForVnf"].copy()
5840 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005841 )
aktas5f75f102021-03-15 11:26:10 +03005842 descriptor_config = get_configuration(
5843 db_vnfd, db_vnfd["id"]
garciadeblas5697b8b2021-03-24 09:17:02 +01005844 )
aktas5f75f102021-03-15 11:26:10 +03005845 if descriptor_config:
5846 vdu_id = None
5847 vdu_name = None
5848 kdu_name = None
5849 self._deploy_n2vc(
5850 logging_text=logging_text
5851 + "member_vnf_index={} ".format(member_vnf_index),
5852 db_nsr=db_nsr,
5853 db_vnfr=db_vnfr,
5854 nslcmop_id=nslcmop_id,
5855 nsr_id=nsr_id,
5856 nsi_id=nsi_id,
5857 vnfd_id=vnfd_id,
5858 vdu_id=vdu_id,
5859 kdu_name=kdu_name,
5860 member_vnf_index=member_vnf_index,
5861 vdu_index=vdu_index,
5862 vdu_name=vdu_name,
5863 deploy_params=deploy_params,
5864 descriptor_config=descriptor_config,
5865 base_folder=base_folder,
5866 task_instantiation_info=tasks_dict_info,
5867 stage=stage,
5868 )
5869 vdu_id = vca_info["osm_vdu_id"]
5870 vdur = find_in_list(
5871 db_vnfr["vdur"], lambda vdu: vdu["vdu-id-ref"] == vdu_id
aktas13251562021-02-12 22:19:10 +03005872 )
aktas5f75f102021-03-15 11:26:10 +03005873 descriptor_config = get_configuration(db_vnfd, vdu_id)
5874 if vdur.get("additionalParams"):
5875 deploy_params_vdu = parse_yaml_strings(
5876 vdur["additionalParams"]
5877 )
5878 else:
5879 deploy_params_vdu = deploy_params
5880 deploy_params_vdu["OSM"] = get_osm_params(
5881 db_vnfr, vdu_id, vdu_count_index=vdu_index
garciadeblas5697b8b2021-03-24 09:17:02 +01005882 )
aktas5f75f102021-03-15 11:26:10 +03005883 if descriptor_config:
5884 vdu_name = None
5885 kdu_name = None
5886 stage[
5887 1
5888 ] = "Scaling member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
garciadeblas5697b8b2021-03-24 09:17:02 +01005889 member_vnf_index, vdu_id, vdu_index
aktas5f75f102021-03-15 11:26:10 +03005890 )
5891 stage[2] = step = "Scaling out VCA"
5892 self._write_op_status(op_id=nslcmop_id, stage=stage)
5893 self._deploy_n2vc(
5894 logging_text=logging_text
5895 + "member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
5896 member_vnf_index, vdu_id, vdu_index
5897 ),
5898 db_nsr=db_nsr,
5899 db_vnfr=db_vnfr,
5900 nslcmop_id=nslcmop_id,
5901 nsr_id=nsr_id,
5902 nsi_id=nsi_id,
5903 vnfd_id=vnfd_id,
5904 vdu_id=vdu_id,
5905 kdu_name=kdu_name,
5906 member_vnf_index=member_vnf_index,
5907 vdu_index=vdu_index,
5908 vdu_name=vdu_name,
5909 deploy_params=deploy_params_vdu,
5910 descriptor_config=descriptor_config,
5911 base_folder=base_folder,
5912 task_instantiation_info=tasks_dict_info,
5913 stage=stage,
5914 )
5915 else:
5916 kdu_name = vca_info["osm_kdu_id"]
5917 descriptor_config = get_configuration(db_vnfd, kdu_name)
5918 if descriptor_config:
5919 vdu_id = None
5920 kdu_index = int(vca_info["kdu_index"])
5921 vdu_name = None
5922 kdur = next(
5923 x
5924 for x in db_vnfr["kdur"]
5925 if x["kdu-name"] == kdu_name
5926 )
5927 deploy_params_kdu = {"OSM": get_osm_params(db_vnfr)}
5928 if kdur.get("additionalParams"):
5929 deploy_params_kdu = parse_yaml_strings(
5930 kdur["additionalParams"]
5931 )
5932
5933 self._deploy_n2vc(
5934 logging_text=logging_text,
5935 db_nsr=db_nsr,
5936 db_vnfr=db_vnfr,
5937 nslcmop_id=nslcmop_id,
5938 nsr_id=nsr_id,
5939 nsi_id=nsi_id,
5940 vnfd_id=vnfd_id,
5941 vdu_id=vdu_id,
5942 kdu_name=kdu_name,
5943 member_vnf_index=member_vnf_index,
5944 vdu_index=kdu_index,
5945 vdu_name=vdu_name,
5946 deploy_params=deploy_params_kdu,
5947 descriptor_config=descriptor_config,
5948 base_folder=base_folder,
5949 task_instantiation_info=tasks_dict_info,
5950 stage=stage,
5951 )
aktas13251562021-02-12 22:19:10 +03005952 # SCALE-UP VCA - END
5953 scale_process = None
tierno59d22d22018-09-25 18:10:19 +02005954
kuuseac3a8882019-10-03 10:48:06 +02005955 # POST-SCALE BEGIN
tierno59d22d22018-09-25 18:10:19 +02005956 # execute primitive service POST-SCALING
5957 step = "Executing post-scale vnf-config-primitive"
5958 if scaling_descriptor.get("scaling-config-action"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005959 for scaling_config_action in scaling_descriptor[
5960 "scaling-config-action"
5961 ]:
5962 if (
5963 scaling_config_action.get("trigger") == "post-scale-in"
5964 and scaling_type == "SCALE_IN"
5965 ) or (
5966 scaling_config_action.get("trigger") == "post-scale-out"
5967 and scaling_type == "SCALE_OUT"
5968 ):
5969 vnf_config_primitive = scaling_config_action[
5970 "vnf-config-primitive-name-ref"
5971 ]
5972 step = db_nslcmop_update[
5973 "detailed-status"
5974 ] = "executing post-scale scaling-config-action '{}'".format(
5975 vnf_config_primitive
5976 )
tiernoda964822019-01-14 15:53:47 +00005977
aktas5f75f102021-03-15 11:26:10 +03005978 vnfr_params = {"VDU_SCALE_INFO": scaling_info}
tiernoda964822019-01-14 15:53:47 +00005979 if db_vnfr.get("additionalParamsForVnf"):
5980 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
5981
tierno59d22d22018-09-25 18:10:19 +02005982 # look for primitive
bravof9a256db2021-02-22 18:02:07 -03005983 for config_primitive in (
5984 get_configuration(db_vnfd, db_vnfd["id"]) or {}
5985 ).get("config-primitive", ()):
tierno59d22d22018-09-25 18:10:19 +02005986 if config_primitive["name"] == vnf_config_primitive:
tierno59d22d22018-09-25 18:10:19 +02005987 break
5988 else:
tiernoa278b842020-07-08 15:33:55 +00005989 raise LcmException(
5990 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-"
5991 "action[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:"
garciadeblas5697b8b2021-03-24 09:17:02 +01005992 "config-primitive".format(
5993 scaling_group, vnf_config_primitive
5994 )
5995 )
tierno9ab95942018-10-10 16:44:22 +02005996 scale_process = "VCA"
tiernod6de1992018-10-11 13:05:52 +02005997 db_nsr_update["config-status"] = "configuring post-scaling"
garciadeblas5697b8b2021-03-24 09:17:02 +01005998 primitive_params = self._map_primitive_params(
5999 config_primitive, {}, vnfr_params
6000 )
tiernod6de1992018-10-11 13:05:52 +02006001
tierno7c4e24c2020-05-13 08:41:35 +00006002 # Post-scale retry check: Check if this sub-operation has been executed before
kuuseac3a8882019-10-03 10:48:06 +02006003 op_index = self._check_or_add_scale_suboperation(
garciadeblas5697b8b2021-03-24 09:17:02 +01006004 db_nslcmop,
garciadeblas5697b8b2021-03-24 09:17:02 +01006005 vnf_index,
6006 vnf_config_primitive,
6007 primitive_params,
6008 "POST-SCALE",
6009 )
quilesj4cda56b2019-12-05 10:02:20 +00006010 if op_index == self.SUBOPERATION_STATUS_SKIP:
kuuseac3a8882019-10-03 10:48:06 +02006011 # Skip sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01006012 result = "COMPLETED"
6013 result_detail = "Done"
6014 self.logger.debug(
6015 logging_text
6016 + "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
6017 vnf_config_primitive, result, result_detail
6018 )
6019 )
kuuseac3a8882019-10-03 10:48:06 +02006020 else:
quilesj4cda56b2019-12-05 10:02:20 +00006021 if op_index == self.SUBOPERATION_STATUS_NEW:
kuuseac3a8882019-10-03 10:48:06 +02006022 # New sub-operation: Get index of this sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01006023 op_index = (
6024 len(db_nslcmop.get("_admin", {}).get("operations"))
6025 - 1
6026 )
6027 self.logger.debug(
6028 logging_text
6029 + "vnf_config_primitive={} New sub-operation".format(
6030 vnf_config_primitive
6031 )
6032 )
kuuseac3a8882019-10-03 10:48:06 +02006033 else:
tierno7c4e24c2020-05-13 08:41:35 +00006034 # retry: Get registered params for this existing sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01006035 op = db_nslcmop.get("_admin", {}).get("operations", [])[
6036 op_index
6037 ]
6038 vnf_index = op.get("member_vnf_index")
6039 vnf_config_primitive = op.get("primitive")
6040 primitive_params = op.get("primitive_params")
6041 self.logger.debug(
6042 logging_text
6043 + "vnf_config_primitive={} Sub-operation retry".format(
6044 vnf_config_primitive
6045 )
6046 )
tierno588547c2020-07-01 15:30:20 +00006047 # Execute the primitive, either with new (first-time) or registered (reintent) args
garciadeblas5697b8b2021-03-24 09:17:02 +01006048 ee_descriptor_id = config_primitive.get(
6049 "execution-environment-ref"
6050 )
6051 primitive_name = config_primitive.get(
6052 "execution-environment-primitive", vnf_config_primitive
6053 )
6054 ee_id, vca_type = self._look_for_deployed_vca(
6055 nsr_deployed["VCA"],
6056 member_vnf_index=vnf_index,
6057 vdu_id=None,
6058 vdu_count_index=None,
6059 ee_descriptor_id=ee_descriptor_id,
6060 )
kuuseac3a8882019-10-03 10:48:06 +02006061 result, result_detail = await self._ns_execute_primitive(
David Garciac1fe90a2021-03-31 19:12:02 +02006062 ee_id,
6063 primitive_name,
6064 primitive_params,
6065 vca_type=vca_type,
6066 vca_id=vca_id,
6067 )
garciadeblas5697b8b2021-03-24 09:17:02 +01006068 self.logger.debug(
6069 logging_text
6070 + "vnf_config_primitive={} Done with result {} {}".format(
6071 vnf_config_primitive, result, result_detail
6072 )
6073 )
kuuseac3a8882019-10-03 10:48:06 +02006074 # Update operationState = COMPLETED | FAILED
6075 self._update_suboperation_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01006076 db_nslcmop, op_index, result, result_detail
6077 )
kuuseac3a8882019-10-03 10:48:06 +02006078
tierno59d22d22018-09-25 18:10:19 +02006079 if result == "FAILED":
6080 raise LcmException(result_detail)
tiernod6de1992018-10-11 13:05:52 +02006081 db_nsr_update["config-status"] = old_config_status
6082 scale_process = None
kuuseac3a8882019-10-03 10:48:06 +02006083 # POST-SCALE END
tierno59d22d22018-09-25 18:10:19 +02006084
garciadeblas5697b8b2021-03-24 09:17:02 +01006085 db_nsr_update[
6086 "detailed-status"
6087 ] = "" # "scaled {} {}".format(scaling_group, scaling_type)
6088 db_nsr_update["operational-status"] = (
6089 "running"
6090 if old_operational_status == "failed"
ikalyvas02d9e7b2019-05-27 18:16:01 +03006091 else old_operational_status
garciadeblas5697b8b2021-03-24 09:17:02 +01006092 )
tiernod6de1992018-10-11 13:05:52 +02006093 db_nsr_update["config-status"] = old_config_status
tierno59d22d22018-09-25 18:10:19 +02006094 return
garciadeblas5697b8b2021-03-24 09:17:02 +01006095 except (
6096 ROclient.ROClientException,
6097 DbException,
6098 LcmException,
6099 NgRoException,
6100 ) as e:
tierno59d22d22018-09-25 18:10:19 +02006101 self.logger.error(logging_text + "Exit Exception {}".format(e))
6102 exc = e
6103 except asyncio.CancelledError:
garciadeblas5697b8b2021-03-24 09:17:02 +01006104 self.logger.error(
6105 logging_text + "Cancelled Exception while '{}'".format(step)
6106 )
tierno59d22d22018-09-25 18:10:19 +02006107 exc = "Operation was cancelled"
6108 except Exception as e:
6109 exc = traceback.format_exc()
garciadeblas5697b8b2021-03-24 09:17:02 +01006110 self.logger.critical(
6111 logging_text + "Exit Exception {} {}".format(type(e).__name__, e),
6112 exc_info=True,
6113 )
tierno59d22d22018-09-25 18:10:19 +02006114 finally:
garciadeblas5697b8b2021-03-24 09:17:02 +01006115 self._write_ns_status(
6116 nsr_id=nsr_id,
6117 ns_state=None,
6118 current_operation="IDLE",
6119 current_operation_id=None,
6120 )
aktas13251562021-02-12 22:19:10 +03006121 if tasks_dict_info:
6122 stage[1] = "Waiting for instantiate pending tasks."
6123 self.logger.debug(logging_text + stage[1])
garciadeblas5697b8b2021-03-24 09:17:02 +01006124 exc = await self._wait_for_tasks(
6125 logging_text,
6126 tasks_dict_info,
6127 self.timeout_ns_deploy,
6128 stage,
6129 nslcmop_id,
6130 nsr_id=nsr_id,
6131 )
tierno59d22d22018-09-25 18:10:19 +02006132 if exc:
garciadeblas5697b8b2021-03-24 09:17:02 +01006133 db_nslcmop_update[
6134 "detailed-status"
6135 ] = error_description_nslcmop = "FAILED {}: {}".format(step, exc)
tiernoa17d4f42020-04-28 09:59:23 +00006136 nslcmop_operation_state = "FAILED"
tierno59d22d22018-09-25 18:10:19 +02006137 if db_nsr:
tiernod6de1992018-10-11 13:05:52 +02006138 db_nsr_update["operational-status"] = old_operational_status
6139 db_nsr_update["config-status"] = old_config_status
6140 db_nsr_update["detailed-status"] = ""
6141 if scale_process:
6142 if "VCA" in scale_process:
6143 db_nsr_update["config-status"] = "failed"
6144 if "RO" in scale_process:
6145 db_nsr_update["operational-status"] = "failed"
garciadeblas5697b8b2021-03-24 09:17:02 +01006146 db_nsr_update[
6147 "detailed-status"
6148 ] = "FAILED scaling nslcmop={} {}: {}".format(
6149 nslcmop_id, step, exc
6150 )
tiernoa17d4f42020-04-28 09:59:23 +00006151 else:
6152 error_description_nslcmop = None
6153 nslcmop_operation_state = "COMPLETED"
6154 db_nslcmop_update["detailed-status"] = "Done"
quilesj4cda56b2019-12-05 10:02:20 +00006155
garciadeblas5697b8b2021-03-24 09:17:02 +01006156 self._write_op_status(
6157 op_id=nslcmop_id,
6158 stage="",
6159 error_message=error_description_nslcmop,
6160 operation_state=nslcmop_operation_state,
6161 other_update=db_nslcmop_update,
6162 )
tiernoa17d4f42020-04-28 09:59:23 +00006163 if db_nsr:
garciadeblas5697b8b2021-03-24 09:17:02 +01006164 self._write_ns_status(
6165 nsr_id=nsr_id,
6166 ns_state=None,
6167 current_operation="IDLE",
6168 current_operation_id=None,
6169 other_update=db_nsr_update,
6170 )
tiernoa17d4f42020-04-28 09:59:23 +00006171
tierno59d22d22018-09-25 18:10:19 +02006172 if nslcmop_operation_state:
6173 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01006174 msg = {
6175 "nsr_id": nsr_id,
6176 "nslcmop_id": nslcmop_id,
6177 "operationState": nslcmop_operation_state,
6178 }
bravof922c4172020-11-24 21:21:43 -03006179 await self.msg.aiowrite("ns", "scaled", msg, loop=self.loop)
tierno59d22d22018-09-25 18:10:19 +02006180 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01006181 self.logger.error(
6182 logging_text + "kafka_write notification Exception {}".format(e)
6183 )
tierno59d22d22018-09-25 18:10:19 +02006184 self.logger.debug(logging_text + "Exit")
6185 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_scale")
tiernob996d942020-07-03 14:52:28 +00006186
aktas5f75f102021-03-15 11:26:10 +03006187 async def _scale_kdu(
6188 self, logging_text, nsr_id, nsr_deployed, db_vnfd, vca_id, scaling_info
6189 ):
6190 _scaling_info = scaling_info.get("kdu-create") or scaling_info.get("kdu-delete")
6191 for kdu_name in _scaling_info:
6192 for kdu_scaling_info in _scaling_info[kdu_name]:
6193 deployed_kdu, index = get_deployed_kdu(
6194 nsr_deployed, kdu_name, kdu_scaling_info["member-vnf-index"]
6195 )
6196 cluster_uuid = deployed_kdu["k8scluster-uuid"]
6197 kdu_instance = deployed_kdu["kdu-instance"]
6198 scale = int(kdu_scaling_info["scale"])
6199 k8s_cluster_type = kdu_scaling_info["k8s-cluster-type"]
6200
6201 db_dict = {
6202 "collection": "nsrs",
6203 "filter": {"_id": nsr_id},
6204 "path": "_admin.deployed.K8s.{}".format(index),
6205 }
6206
6207 step = "scaling application {}".format(
6208 kdu_scaling_info["resource-name"]
6209 )
6210 self.logger.debug(logging_text + step)
6211
6212 if kdu_scaling_info["type"] == "delete":
6213 kdu_config = get_configuration(db_vnfd, kdu_name)
6214 if (
6215 kdu_config
6216 and kdu_config.get("terminate-config-primitive")
6217 and get_juju_ee_ref(db_vnfd, kdu_name) is None
6218 ):
6219 terminate_config_primitive_list = kdu_config.get(
6220 "terminate-config-primitive"
6221 )
6222 terminate_config_primitive_list.sort(
6223 key=lambda val: int(val["seq"])
6224 )
6225
6226 for (
6227 terminate_config_primitive
6228 ) in terminate_config_primitive_list:
6229 primitive_params_ = self._map_primitive_params(
6230 terminate_config_primitive, {}, {}
6231 )
6232 step = "execute terminate config primitive"
6233 self.logger.debug(logging_text + step)
6234 await asyncio.wait_for(
6235 self.k8scluster_map[k8s_cluster_type].exec_primitive(
6236 cluster_uuid=cluster_uuid,
6237 kdu_instance=kdu_instance,
6238 primitive_name=terminate_config_primitive["name"],
6239 params=primitive_params_,
6240 db_dict=db_dict,
6241 vca_id=vca_id,
6242 ),
6243 timeout=600,
6244 )
6245
6246 await asyncio.wait_for(
6247 self.k8scluster_map[k8s_cluster_type].scale(
6248 kdu_instance,
6249 scale,
6250 kdu_scaling_info["resource-name"],
6251 vca_id=vca_id,
6252 ),
6253 timeout=self.timeout_vca_on_error,
6254 )
6255
6256 if kdu_scaling_info["type"] == "create":
6257 kdu_config = get_configuration(db_vnfd, kdu_name)
6258 if (
6259 kdu_config
6260 and kdu_config.get("initial-config-primitive")
6261 and get_juju_ee_ref(db_vnfd, kdu_name) is None
6262 ):
6263 initial_config_primitive_list = kdu_config.get(
6264 "initial-config-primitive"
6265 )
6266 initial_config_primitive_list.sort(
6267 key=lambda val: int(val["seq"])
6268 )
6269
6270 for initial_config_primitive in initial_config_primitive_list:
6271 primitive_params_ = self._map_primitive_params(
6272 initial_config_primitive, {}, {}
6273 )
6274 step = "execute initial config primitive"
6275 self.logger.debug(logging_text + step)
6276 await asyncio.wait_for(
6277 self.k8scluster_map[k8s_cluster_type].exec_primitive(
6278 cluster_uuid=cluster_uuid,
6279 kdu_instance=kdu_instance,
6280 primitive_name=initial_config_primitive["name"],
6281 params=primitive_params_,
6282 db_dict=db_dict,
6283 vca_id=vca_id,
6284 ),
6285 timeout=600,
6286 )
6287
garciadeblas5697b8b2021-03-24 09:17:02 +01006288 async def _scale_ng_ro(
6289 self, logging_text, db_nsr, db_nslcmop, db_vnfr, vdu_scaling_info, stage
6290 ):
tierno2357f4e2020-10-19 16:38:59 +00006291 nsr_id = db_nslcmop["nsInstanceId"]
6292 db_nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
6293 db_vnfrs = {}
6294
6295 # read from db: vnfd's for every vnf
bravof832f8992020-12-07 12:57:31 -03006296 db_vnfds = []
tierno2357f4e2020-10-19 16:38:59 +00006297
6298 # for each vnf in ns, read vnfd
6299 for vnfr in self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id}):
6300 db_vnfrs[vnfr["member-vnf-index-ref"]] = vnfr
6301 vnfd_id = vnfr["vnfd-id"] # vnfd uuid for this vnf
tierno2357f4e2020-10-19 16:38:59 +00006302 # if we haven't this vnfd, read it from db
bravof832f8992020-12-07 12:57:31 -03006303 if not find_in_list(db_vnfds, lambda a_vnfd: a_vnfd["id"] == vnfd_id):
tierno2357f4e2020-10-19 16:38:59 +00006304 # read from db
6305 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
bravof832f8992020-12-07 12:57:31 -03006306 db_vnfds.append(vnfd)
tierno2357f4e2020-10-19 16:38:59 +00006307 n2vc_key = self.n2vc.get_public_key()
6308 n2vc_key_list = [n2vc_key]
garciadeblas5697b8b2021-03-24 09:17:02 +01006309 self.scale_vnfr(
6310 db_vnfr,
6311 vdu_scaling_info.get("vdu-create"),
6312 vdu_scaling_info.get("vdu-delete"),
6313 mark_delete=True,
6314 )
tierno2357f4e2020-10-19 16:38:59 +00006315 # db_vnfr has been updated, update db_vnfrs to use it
6316 db_vnfrs[db_vnfr["member-vnf-index-ref"]] = db_vnfr
garciadeblas5697b8b2021-03-24 09:17:02 +01006317 await self._instantiate_ng_ro(
6318 logging_text,
6319 nsr_id,
6320 db_nsd,
6321 db_nsr,
6322 db_nslcmop,
6323 db_vnfrs,
6324 db_vnfds,
6325 n2vc_key_list,
6326 stage=stage,
6327 start_deploy=time(),
6328 timeout_ns_deploy=self.timeout_ns_deploy,
6329 )
tierno2357f4e2020-10-19 16:38:59 +00006330 if vdu_scaling_info.get("vdu-delete"):
garciadeblas5697b8b2021-03-24 09:17:02 +01006331 self.scale_vnfr(
6332 db_vnfr, None, vdu_scaling_info["vdu-delete"], mark_delete=False
6333 )
tierno2357f4e2020-10-19 16:38:59 +00006334
garciadeblas5697b8b2021-03-24 09:17:02 +01006335 async def add_prometheus_metrics(
6336 self, ee_id, artifact_path, ee_config_descriptor, vnfr_id, nsr_id, target_ip
6337 ):
tiernob996d942020-07-03 14:52:28 +00006338 if not self.prometheus:
6339 return
6340 # look if exist a file called 'prometheus*.j2' and
6341 artifact_content = self.fs.dir_ls(artifact_path)
garciadeblas5697b8b2021-03-24 09:17:02 +01006342 job_file = next(
6343 (
6344 f
6345 for f in artifact_content
6346 if f.startswith("prometheus") and f.endswith(".j2")
6347 ),
6348 None,
6349 )
tiernob996d942020-07-03 14:52:28 +00006350 if not job_file:
6351 return
6352 with self.fs.file_open((artifact_path, job_file), "r") as f:
6353 job_data = f.read()
6354
6355 # TODO get_service
garciadeblas5697b8b2021-03-24 09:17:02 +01006356 _, _, service = ee_id.partition(".") # remove prefix "namespace."
tiernob996d942020-07-03 14:52:28 +00006357 host_name = "{}-{}".format(service, ee_config_descriptor["metric-service"])
6358 host_port = "80"
6359 vnfr_id = vnfr_id.replace("-", "")
6360 variables = {
6361 "JOB_NAME": vnfr_id,
6362 "TARGET_IP": target_ip,
6363 "EXPORTER_POD_IP": host_name,
6364 "EXPORTER_POD_PORT": host_port,
6365 }
6366 job_list = self.prometheus.parse_job(job_data, variables)
6367 # ensure job_name is using the vnfr_id. Adding the metadata nsr_id
6368 for job in job_list:
garciadeblas5697b8b2021-03-24 09:17:02 +01006369 if (
6370 not isinstance(job.get("job_name"), str)
6371 or vnfr_id not in job["job_name"]
6372 ):
tiernob996d942020-07-03 14:52:28 +00006373 job["job_name"] = vnfr_id + "_" + str(randint(1, 10000))
6374 job["nsr_id"] = nsr_id
6375 job_dict = {jl["job_name"]: jl for jl in job_list}
6376 if await self.prometheus.update(job_dict):
6377 return list(job_dict.keys())
David Garciaaae391f2020-11-09 11:12:54 +01006378
6379 def get_vca_cloud_and_credentials(self, vim_account_id: str) -> (str, str):
6380 """
6381 Get VCA Cloud and VCA Cloud Credentials for the VIM account
6382
6383 :param: vim_account_id: VIM Account ID
6384
6385 :return: (cloud_name, cloud_credential)
6386 """
bravof922c4172020-11-24 21:21:43 -03006387 config = VimAccountDB.get_vim_account_with_id(vim_account_id).get("config", {})
David Garciaaae391f2020-11-09 11:12:54 +01006388 return config.get("vca_cloud"), config.get("vca_cloud_credential")
6389
6390 def get_vca_k8s_cloud_and_credentials(self, vim_account_id: str) -> (str, str):
6391 """
6392 Get VCA K8s Cloud and VCA K8s Cloud Credentials for the VIM account
6393
6394 :param: vim_account_id: VIM Account ID
6395
6396 :return: (cloud_name, cloud_credential)
6397 """
bravof922c4172020-11-24 21:21:43 -03006398 config = VimAccountDB.get_vim_account_with_id(vim_account_id).get("config", {})
David Garciaaae391f2020-11-09 11:12:54 +01006399 return config.get("vca_k8s_cloud"), config.get("vca_k8s_cloud_credential")