blob: b13d4662f0ada383d9bb09f1be3321c71a33cf7a [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 Garciab4ebcd02021-10-28 02:00:43 +020020from typing import Any, Dict
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"]
bravof486707f2021-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"]
bravof486707f2021-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
bravof486707f2021-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],
2738 ):
2739 relations = []
2740 db_ns_relations = get_ns_configuration_relation_list(nsd)
2741 for r in db_ns_relations:
2742 relation_provider = self._update_ee_relation_data_with_implicit_data(
2743 nsr_id, nsd, r["provider"], cached_vnfds
2744 )
2745 relation_requirer = self._update_ee_relation_data_with_implicit_data(
2746 nsr_id, nsd, r["requirer"], cached_vnfds
2747 )
2748 provider = EERelation(relation_provider)
2749 requirer = EERelation(relation_requirer)
2750 relation = Relation(r["name"], provider, requirer)
2751 vca_in_relation = self._is_deployed_vca_in_relation(vca, relation)
2752 if vca_in_relation:
2753 relations.append(relation)
2754 return relations
2755
2756 def _get_vnf_relations(
2757 self,
2758 nsr_id: str,
2759 nsd: Dict[str, Any],
2760 vca: DeployedVCA,
2761 cached_vnfds: Dict[str, Any],
2762 ):
2763 relations = []
2764 vnf_profile = get_vnf_profile(nsd, vca.vnf_profile_id)
2765 vnf_profile_id = vnf_profile["id"]
2766 vnfd_id = vnf_profile["vnfd-id"]
2767 db_vnfd = self._get_vnfd(vnfd_id, cached_vnfds)
2768 db_vnf_relations = get_relation_list(db_vnfd, vnfd_id)
2769 for r in db_vnf_relations:
2770 relation_provider = self._update_ee_relation_data_with_implicit_data(
2771 nsr_id, nsd, r["provider"], cached_vnfds, vnf_profile_id=vnf_profile_id
2772 )
2773 relation_requirer = self._update_ee_relation_data_with_implicit_data(
2774 nsr_id, nsd, r["requirer"], cached_vnfds, vnf_profile_id=vnf_profile_id
2775 )
2776 provider = EERelation(relation_provider)
2777 requirer = EERelation(relation_requirer)
2778 relation = Relation(r["name"], provider, requirer)
2779 vca_in_relation = self._is_deployed_vca_in_relation(vca, relation)
2780 if vca_in_relation:
2781 relations.append(relation)
2782 return relations
2783
2784 def _get_kdu_resource_data(
2785 self,
2786 ee_relation: EERelation,
2787 db_nsr: Dict[str, Any],
2788 cached_vnfds: Dict[str, Any],
2789 ) -> DeployedK8sResource:
2790 nsd = get_nsd(db_nsr)
2791 vnf_profiles = get_vnf_profiles(nsd)
2792 vnfd_id = find_in_list(
2793 vnf_profiles,
2794 lambda vnf_profile: vnf_profile["id"] == ee_relation.vnf_profile_id,
2795 )["vnfd-id"]
2796 db_vnfd = self._get_vnfd(vnfd_id, cached_vnfds)
2797 kdu_resource_profile = get_kdu_resource_profile(
2798 db_vnfd, ee_relation.kdu_resource_profile_id
2799 )
2800 kdu_name = kdu_resource_profile["kdu-name"]
2801 deployed_kdu, _ = get_deployed_kdu(
2802 db_nsr.get("_admin", ()).get("deployed", ()),
2803 kdu_name,
2804 ee_relation.vnf_profile_id,
2805 )
2806 deployed_kdu.update({"resource-name": kdu_resource_profile["resource-name"]})
2807 return deployed_kdu
2808
2809 def _get_deployed_component(
2810 self,
2811 ee_relation: EERelation,
2812 db_nsr: Dict[str, Any],
2813 cached_vnfds: Dict[str, Any],
2814 ) -> DeployedComponent:
2815 nsr_id = db_nsr["_id"]
2816 deployed_component = None
2817 ee_level = EELevel.get_level(ee_relation)
2818 if ee_level == EELevel.NS:
2819 vca = get_deployed_vca(db_nsr, {"vdu_id": None, "member-vnf-index": None})
2820 if vca:
2821 deployed_component = DeployedVCA(nsr_id, vca)
2822 elif ee_level == EELevel.VNF:
2823 vca = get_deployed_vca(
2824 db_nsr,
2825 {
2826 "vdu_id": None,
2827 "member-vnf-index": ee_relation.vnf_profile_id,
2828 "ee_descriptor_id": ee_relation.execution_environment_ref,
2829 },
2830 )
2831 if vca:
2832 deployed_component = DeployedVCA(nsr_id, vca)
2833 elif ee_level == EELevel.VDU:
2834 vca = get_deployed_vca(
2835 db_nsr,
2836 {
2837 "vdu_id": ee_relation.vdu_profile_id,
2838 "member-vnf-index": ee_relation.vnf_profile_id,
2839 "ee_descriptor_id": ee_relation.execution_environment_ref,
2840 },
2841 )
2842 if vca:
2843 deployed_component = DeployedVCA(nsr_id, vca)
2844 elif ee_level == EELevel.KDU:
2845 kdu_resource_data = self._get_kdu_resource_data(
2846 ee_relation, db_nsr, cached_vnfds
2847 )
2848 if kdu_resource_data:
2849 deployed_component = DeployedK8sResource(kdu_resource_data)
2850 return deployed_component
2851
2852 async def _add_relation(
2853 self,
2854 relation: Relation,
2855 vca_type: str,
2856 db_nsr: Dict[str, Any],
2857 cached_vnfds: Dict[str, Any],
2858 cached_vnfrs: Dict[str, Any],
2859 ) -> bool:
2860 deployed_provider = self._get_deployed_component(
2861 relation.provider, db_nsr, cached_vnfds
2862 )
2863 deployed_requirer = self._get_deployed_component(
2864 relation.requirer, db_nsr, cached_vnfds
2865 )
2866 if (
2867 deployed_provider
2868 and deployed_requirer
2869 and deployed_provider.config_sw_installed
2870 and deployed_requirer.config_sw_installed
2871 ):
2872 provider_db_vnfr = (
2873 self._get_vnfr(
2874 relation.provider.nsr_id,
2875 relation.provider.vnf_profile_id,
2876 cached_vnfrs,
2877 )
2878 if relation.provider.vnf_profile_id
2879 else None
2880 )
2881 requirer_db_vnfr = (
2882 self._get_vnfr(
2883 relation.requirer.nsr_id,
2884 relation.requirer.vnf_profile_id,
2885 cached_vnfrs,
2886 )
2887 if relation.requirer.vnf_profile_id
2888 else None
2889 )
2890 provider_vca_id = self.get_vca_id(provider_db_vnfr, db_nsr)
2891 requirer_vca_id = self.get_vca_id(requirer_db_vnfr, db_nsr)
2892 provider_relation_endpoint = RelationEndpoint(
2893 deployed_provider.ee_id,
2894 provider_vca_id,
2895 relation.provider.endpoint,
2896 )
2897 requirer_relation_endpoint = RelationEndpoint(
2898 deployed_requirer.ee_id,
2899 requirer_vca_id,
2900 relation.requirer.endpoint,
2901 )
2902 await self.vca_map[vca_type].add_relation(
2903 provider=provider_relation_endpoint,
2904 requirer=requirer_relation_endpoint,
2905 )
2906 # remove entry from relations list
2907 return True
2908 return False
2909
David Garciac1fe90a2021-03-31 19:12:02 +02002910 async def _add_vca_relations(
2911 self,
2912 logging_text,
2913 nsr_id,
David Garciab4ebcd02021-10-28 02:00:43 +02002914 vca_type: str,
David Garciac1fe90a2021-03-31 19:12:02 +02002915 vca_index: int,
2916 timeout: int = 3600,
David Garciac1fe90a2021-03-31 19:12:02 +02002917 ) -> bool:
quilesj63f90042020-01-17 09:53:55 +00002918
2919 # steps:
2920 # 1. find all relations for this VCA
2921 # 2. wait for other peers related
2922 # 3. add relations
2923
2924 try:
quilesj63f90042020-01-17 09:53:55 +00002925 # STEP 1: find all relations for this VCA
2926
2927 # read nsr record
2928 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
David Garciab4ebcd02021-10-28 02:00:43 +02002929 nsd = get_nsd(db_nsr)
quilesj63f90042020-01-17 09:53:55 +00002930
2931 # this VCA data
David Garciab4ebcd02021-10-28 02:00:43 +02002932 deployed_vca_dict = get_deployed_vca_list(db_nsr)[vca_index]
2933 my_vca = DeployedVCA(nsr_id, deployed_vca_dict)
quilesj63f90042020-01-17 09:53:55 +00002934
David Garciab4ebcd02021-10-28 02:00:43 +02002935 cached_vnfds = {}
2936 cached_vnfrs = {}
2937 relations = []
2938 relations.extend(self._get_ns_relations(nsr_id, nsd, my_vca, cached_vnfds))
2939 relations.extend(self._get_vnf_relations(nsr_id, nsd, my_vca, cached_vnfds))
quilesj63f90042020-01-17 09:53:55 +00002940
2941 # if no relations, terminate
David Garciab4ebcd02021-10-28 02:00:43 +02002942 if not relations:
garciadeblas5697b8b2021-03-24 09:17:02 +01002943 self.logger.debug(logging_text + " No relations")
quilesj63f90042020-01-17 09:53:55 +00002944 return True
2945
David Garciab4ebcd02021-10-28 02:00:43 +02002946 self.logger.debug(logging_text + " adding relations {}".format(relations))
quilesj63f90042020-01-17 09:53:55 +00002947
2948 # add all relations
2949 start = time()
2950 while True:
2951 # check timeout
2952 now = time()
2953 if now - start >= timeout:
garciadeblas5697b8b2021-03-24 09:17:02 +01002954 self.logger.error(logging_text + " : timeout adding relations")
quilesj63f90042020-01-17 09:53:55 +00002955 return False
2956
David Garciab4ebcd02021-10-28 02:00:43 +02002957 # reload nsr from database (we need to update record: _admin.deployed.VCA)
quilesj63f90042020-01-17 09:53:55 +00002958 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2959
David Garciab4ebcd02021-10-28 02:00:43 +02002960 # for each relation, find the VCA's related
2961 for relation in relations.copy():
2962 added = await self._add_relation(
2963 relation,
2964 vca_type,
2965 db_nsr,
2966 cached_vnfds,
2967 cached_vnfrs,
2968 )
2969 if added:
2970 relations.remove(relation)
quilesj63f90042020-01-17 09:53:55 +00002971
David Garciab4ebcd02021-10-28 02:00:43 +02002972 if not relations:
garciadeblas5697b8b2021-03-24 09:17:02 +01002973 self.logger.debug("Relations added")
quilesj63f90042020-01-17 09:53:55 +00002974 break
David Garciab4ebcd02021-10-28 02:00:43 +02002975 await asyncio.sleep(5.0)
quilesj63f90042020-01-17 09:53:55 +00002976
2977 return True
2978
2979 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002980 self.logger.warn(logging_text + " ERROR adding relations: {}".format(e))
quilesj63f90042020-01-17 09:53:55 +00002981 return False
2982
garciadeblas5697b8b2021-03-24 09:17:02 +01002983 async def _install_kdu(
2984 self,
2985 nsr_id: str,
2986 nsr_db_path: str,
2987 vnfr_data: dict,
2988 kdu_index: int,
2989 kdud: dict,
2990 vnfd: dict,
2991 k8s_instance_info: dict,
2992 k8params: dict = None,
2993 timeout: int = 600,
2994 vca_id: str = None,
2995 ):
lloretgalleg7c121132020-07-08 07:53:22 +00002996
tiernob9018152020-04-16 14:18:24 +00002997 try:
lloretgalleg7c121132020-07-08 07:53:22 +00002998 k8sclustertype = k8s_instance_info["k8scluster-type"]
2999 # Instantiate kdu
garciadeblas5697b8b2021-03-24 09:17:02 +01003000 db_dict_install = {
3001 "collection": "nsrs",
3002 "filter": {"_id": nsr_id},
3003 "path": nsr_db_path,
3004 }
lloretgalleg7c121132020-07-08 07:53:22 +00003005
romeromonser4554a702021-05-28 12:00:08 +02003006 if k8s_instance_info.get("kdu-deployment-name"):
3007 kdu_instance = k8s_instance_info.get("kdu-deployment-name")
3008 else:
3009 kdu_instance = self.k8scluster_map[
3010 k8sclustertype
3011 ].generate_kdu_instance_name(
3012 db_dict=db_dict_install,
3013 kdu_model=k8s_instance_info["kdu-model"],
3014 kdu_name=k8s_instance_info["kdu-name"],
3015 )
garciadeblas5697b8b2021-03-24 09:17:02 +01003016 self.update_db_2(
3017 "nsrs", nsr_id, {nsr_db_path + ".kdu-instance": kdu_instance}
3018 )
David Garciad64e2742021-02-25 20:19:18 +01003019 await self.k8scluster_map[k8sclustertype].install(
lloretgalleg7c121132020-07-08 07:53:22 +00003020 cluster_uuid=k8s_instance_info["k8scluster-uuid"],
3021 kdu_model=k8s_instance_info["kdu-model"],
3022 atomic=True,
3023 params=k8params,
3024 db_dict=db_dict_install,
3025 timeout=timeout,
3026 kdu_name=k8s_instance_info["kdu-name"],
David Garciad64e2742021-02-25 20:19:18 +01003027 namespace=k8s_instance_info["namespace"],
3028 kdu_instance=kdu_instance,
David Garciac1fe90a2021-03-31 19:12:02 +02003029 vca_id=vca_id,
David Garciad64e2742021-02-25 20:19:18 +01003030 )
garciadeblas5697b8b2021-03-24 09:17:02 +01003031 self.update_db_2(
3032 "nsrs", nsr_id, {nsr_db_path + ".kdu-instance": kdu_instance}
3033 )
lloretgalleg7c121132020-07-08 07:53:22 +00003034
3035 # Obtain services to obtain management service ip
3036 services = await self.k8scluster_map[k8sclustertype].get_services(
3037 cluster_uuid=k8s_instance_info["k8scluster-uuid"],
3038 kdu_instance=kdu_instance,
garciadeblas5697b8b2021-03-24 09:17:02 +01003039 namespace=k8s_instance_info["namespace"],
3040 )
lloretgalleg7c121132020-07-08 07:53:22 +00003041
3042 # Obtain management service info (if exists)
tierno7ecbc342020-09-21 14:05:39 +00003043 vnfr_update_dict = {}
bravof6ec62b72021-02-25 17:20:35 -03003044 kdu_config = get_configuration(vnfd, kdud["name"])
3045 if kdu_config:
3046 target_ee_list = kdu_config.get("execution-environment-list", [])
3047 else:
3048 target_ee_list = []
3049
lloretgalleg7c121132020-07-08 07:53:22 +00003050 if services:
tierno7ecbc342020-09-21 14:05:39 +00003051 vnfr_update_dict["kdur.{}.services".format(kdu_index)] = services
garciadeblas5697b8b2021-03-24 09:17:02 +01003052 mgmt_services = [
3053 service
3054 for service in kdud.get("service", [])
3055 if service.get("mgmt-service")
3056 ]
lloretgalleg7c121132020-07-08 07:53:22 +00003057 for mgmt_service in mgmt_services:
3058 for service in services:
3059 if service["name"].startswith(mgmt_service["name"]):
3060 # Mgmt service found, Obtain service ip
3061 ip = service.get("external_ip", service.get("cluster_ip"))
3062 if isinstance(ip, list) and len(ip) == 1:
3063 ip = ip[0]
3064
garciadeblas5697b8b2021-03-24 09:17:02 +01003065 vnfr_update_dict[
3066 "kdur.{}.ip-address".format(kdu_index)
3067 ] = ip
lloretgalleg7c121132020-07-08 07:53:22 +00003068
3069 # Check if must update also mgmt ip at the vnf
garciadeblas5697b8b2021-03-24 09:17:02 +01003070 service_external_cp = mgmt_service.get(
3071 "external-connection-point-ref"
3072 )
lloretgalleg7c121132020-07-08 07:53:22 +00003073 if service_external_cp:
garciadeblas5697b8b2021-03-24 09:17:02 +01003074 if (
3075 deep_get(vnfd, ("mgmt-interface", "cp"))
3076 == service_external_cp
3077 ):
lloretgalleg7c121132020-07-08 07:53:22 +00003078 vnfr_update_dict["ip-address"] = ip
3079
bravof6ec62b72021-02-25 17:20:35 -03003080 if find_in_list(
3081 target_ee_list,
garciadeblas5697b8b2021-03-24 09:17:02 +01003082 lambda ee: ee.get(
3083 "external-connection-point-ref", ""
3084 )
3085 == service_external_cp,
bravof6ec62b72021-02-25 17:20:35 -03003086 ):
garciadeblas5697b8b2021-03-24 09:17:02 +01003087 vnfr_update_dict[
3088 "kdur.{}.ip-address".format(kdu_index)
3089 ] = ip
lloretgalleg7c121132020-07-08 07:53:22 +00003090 break
3091 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01003092 self.logger.warn(
3093 "Mgmt service name: {} not found".format(
3094 mgmt_service["name"]
3095 )
3096 )
lloretgalleg7c121132020-07-08 07:53:22 +00003097
tierno7ecbc342020-09-21 14:05:39 +00003098 vnfr_update_dict["kdur.{}.status".format(kdu_index)] = "READY"
3099 self.update_db_2("vnfrs", vnfr_data.get("_id"), vnfr_update_dict)
lloretgalleg7c121132020-07-08 07:53:22 +00003100
bravof9a256db2021-02-22 18:02:07 -03003101 kdu_config = get_configuration(vnfd, k8s_instance_info["kdu-name"])
garciadeblas5697b8b2021-03-24 09:17:02 +01003102 if (
3103 kdu_config
3104 and kdu_config.get("initial-config-primitive")
3105 and get_juju_ee_ref(vnfd, k8s_instance_info["kdu-name"]) is None
3106 ):
3107 initial_config_primitive_list = kdu_config.get(
3108 "initial-config-primitive"
3109 )
Dominik Fleischmannc1975dd2020-08-19 12:17:51 +02003110 initial_config_primitive_list.sort(key=lambda val: int(val["seq"]))
3111
3112 for initial_config_primitive in initial_config_primitive_list:
garciadeblas5697b8b2021-03-24 09:17:02 +01003113 primitive_params_ = self._map_primitive_params(
3114 initial_config_primitive, {}, {}
3115 )
Dominik Fleischmannc1975dd2020-08-19 12:17:51 +02003116
3117 await asyncio.wait_for(
3118 self.k8scluster_map[k8sclustertype].exec_primitive(
3119 cluster_uuid=k8s_instance_info["k8scluster-uuid"],
3120 kdu_instance=kdu_instance,
3121 primitive_name=initial_config_primitive["name"],
garciadeblas5697b8b2021-03-24 09:17:02 +01003122 params=primitive_params_,
3123 db_dict=db_dict_install,
David Garciac1fe90a2021-03-31 19:12:02 +02003124 vca_id=vca_id,
3125 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01003126 timeout=timeout,
David Garciac1fe90a2021-03-31 19:12:02 +02003127 )
Dominik Fleischmannc1975dd2020-08-19 12:17:51 +02003128
tiernob9018152020-04-16 14:18:24 +00003129 except Exception as e:
lloretgalleg7c121132020-07-08 07:53:22 +00003130 # Prepare update db with error and raise exception
tiernob9018152020-04-16 14:18:24 +00003131 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01003132 self.update_db_2(
3133 "nsrs", nsr_id, {nsr_db_path + ".detailed-status": str(e)}
3134 )
3135 self.update_db_2(
3136 "vnfrs",
3137 vnfr_data.get("_id"),
3138 {"kdur.{}.status".format(kdu_index): "ERROR"},
3139 )
tiernob9018152020-04-16 14:18:24 +00003140 except Exception:
lloretgalleg7c121132020-07-08 07:53:22 +00003141 # ignore to keep original exception
tiernob9018152020-04-16 14:18:24 +00003142 pass
lloretgalleg7c121132020-07-08 07:53:22 +00003143 # reraise original error
3144 raise
3145
3146 return kdu_instance
tiernob9018152020-04-16 14:18:24 +00003147
garciadeblas5697b8b2021-03-24 09:17:02 +01003148 async def deploy_kdus(
3149 self,
3150 logging_text,
3151 nsr_id,
3152 nslcmop_id,
3153 db_vnfrs,
3154 db_vnfds,
3155 task_instantiation_info,
3156 ):
calvinosanch9f9c6f22019-11-04 13:37:39 +01003157 # Launch kdus if present in the descriptor
tierno626e0152019-11-29 14:16:16 +00003158
garciadeblas5697b8b2021-03-24 09:17:02 +01003159 k8scluster_id_2_uuic = {
3160 "helm-chart-v3": {},
3161 "helm-chart": {},
3162 "juju-bundle": {},
3163 }
tierno626e0152019-11-29 14:16:16 +00003164
tierno16f4a4e2020-07-20 09:05:51 +00003165 async def _get_cluster_id(cluster_id, cluster_type):
tierno626e0152019-11-29 14:16:16 +00003166 nonlocal k8scluster_id_2_uuic
3167 if cluster_id in k8scluster_id_2_uuic[cluster_type]:
3168 return k8scluster_id_2_uuic[cluster_type][cluster_id]
3169
tierno16f4a4e2020-07-20 09:05:51 +00003170 # check if K8scluster is creating and wait look if previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +01003171 task_name, task_dependency = self.lcm_tasks.lookfor_related(
3172 "k8scluster", cluster_id
3173 )
tierno16f4a4e2020-07-20 09:05:51 +00003174 if task_dependency:
garciadeblas5697b8b2021-03-24 09:17:02 +01003175 text = "Waiting for related tasks '{}' on k8scluster {} to be completed".format(
3176 task_name, cluster_id
3177 )
tierno16f4a4e2020-07-20 09:05:51 +00003178 self.logger.debug(logging_text + text)
3179 await asyncio.wait(task_dependency, timeout=3600)
3180
garciadeblas5697b8b2021-03-24 09:17:02 +01003181 db_k8scluster = self.db.get_one(
3182 "k8sclusters", {"_id": cluster_id}, fail_on_empty=False
3183 )
tierno626e0152019-11-29 14:16:16 +00003184 if not db_k8scluster:
3185 raise LcmException("K8s cluster {} cannot be found".format(cluster_id))
tierno16f4a4e2020-07-20 09:05:51 +00003186
tierno626e0152019-11-29 14:16:16 +00003187 k8s_id = deep_get(db_k8scluster, ("_admin", cluster_type, "id"))
3188 if not k8s_id:
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003189 if cluster_type == "helm-chart-v3":
3190 try:
3191 # backward compatibility for existing clusters that have not been initialized for helm v3
garciadeblas5697b8b2021-03-24 09:17:02 +01003192 k8s_credentials = yaml.safe_dump(
3193 db_k8scluster.get("credentials")
3194 )
3195 k8s_id, uninstall_sw = await self.k8sclusterhelm3.init_env(
3196 k8s_credentials, reuse_cluster_uuid=cluster_id
3197 )
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003198 db_k8scluster_update = {}
3199 db_k8scluster_update["_admin.helm-chart-v3.error_msg"] = None
3200 db_k8scluster_update["_admin.helm-chart-v3.id"] = k8s_id
garciadeblas5697b8b2021-03-24 09:17:02 +01003201 db_k8scluster_update[
3202 "_admin.helm-chart-v3.created"
3203 ] = uninstall_sw
3204 db_k8scluster_update[
3205 "_admin.helm-chart-v3.operationalState"
3206 ] = "ENABLED"
3207 self.update_db_2(
3208 "k8sclusters", cluster_id, db_k8scluster_update
3209 )
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003210 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01003211 self.logger.error(
3212 logging_text
3213 + "error initializing helm-v3 cluster: {}".format(str(e))
3214 )
3215 raise LcmException(
3216 "K8s cluster '{}' has not been initialized for '{}'".format(
3217 cluster_id, cluster_type
3218 )
3219 )
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003220 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01003221 raise LcmException(
3222 "K8s cluster '{}' has not been initialized for '{}'".format(
3223 cluster_id, cluster_type
3224 )
3225 )
tierno626e0152019-11-29 14:16:16 +00003226 k8scluster_id_2_uuic[cluster_type][cluster_id] = k8s_id
3227 return k8s_id
3228
3229 logging_text += "Deploy kdus: "
tiernoe876f672020-02-13 14:34:48 +00003230 step = ""
calvinosanch9f9c6f22019-11-04 13:37:39 +01003231 try:
tierno626e0152019-11-29 14:16:16 +00003232 db_nsr_update = {"_admin.deployed.K8s": []}
calvinosanch9f9c6f22019-11-04 13:37:39 +01003233 self.update_db_2("nsrs", nsr_id, db_nsr_update)
calvinosanch9f9c6f22019-11-04 13:37:39 +01003234
tierno626e0152019-11-29 14:16:16 +00003235 index = 0
tiernoe876f672020-02-13 14:34:48 +00003236 updated_cluster_list = []
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003237 updated_v3_cluster_list = []
tiernoe876f672020-02-13 14:34:48 +00003238
tierno626e0152019-11-29 14:16:16 +00003239 for vnfr_data in db_vnfrs.values():
David Garciac1fe90a2021-03-31 19:12:02 +02003240 vca_id = self.get_vca_id(vnfr_data, {})
lloretgalleg7c121132020-07-08 07:53:22 +00003241 for kdu_index, kdur in enumerate(get_iterable(vnfr_data, "kdur")):
3242 # Step 0: Prepare and set parameters
bravof922c4172020-11-24 21:21:43 -03003243 desc_params = parse_yaml_strings(kdur.get("additionalParams"))
garciadeblas5697b8b2021-03-24 09:17:02 +01003244 vnfd_id = vnfr_data.get("vnfd-id")
3245 vnfd_with_id = find_in_list(
3246 db_vnfds, lambda vnfd: vnfd["_id"] == vnfd_id
3247 )
3248 kdud = next(
3249 kdud
3250 for kdud in vnfd_with_id["kdu"]
3251 if kdud["name"] == kdur["kdu-name"]
3252 )
tiernode1584f2020-04-07 09:07:33 +00003253 namespace = kdur.get("k8s-namespace")
romeromonser4554a702021-05-28 12:00:08 +02003254 kdu_deployment_name = kdur.get("kdu-deployment-name")
tierno626e0152019-11-29 14:16:16 +00003255 if kdur.get("helm-chart"):
lloretgalleg07e53f52020-12-15 10:54:02 +00003256 kdumodel = kdur["helm-chart"]
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003257 # Default version: helm3, if helm-version is v2 assign v2
3258 k8sclustertype = "helm-chart-v3"
3259 self.logger.debug("kdur: {}".format(kdur))
garciadeblas5697b8b2021-03-24 09:17:02 +01003260 if (
3261 kdur.get("helm-version")
3262 and kdur.get("helm-version") == "v2"
3263 ):
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003264 k8sclustertype = "helm-chart"
tierno626e0152019-11-29 14:16:16 +00003265 elif kdur.get("juju-bundle"):
lloretgalleg07e53f52020-12-15 10:54:02 +00003266 kdumodel = kdur["juju-bundle"]
tiernoe876f672020-02-13 14:34:48 +00003267 k8sclustertype = "juju-bundle"
tierno626e0152019-11-29 14:16:16 +00003268 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01003269 raise LcmException(
3270 "kdu type for kdu='{}.{}' is neither helm-chart nor "
3271 "juju-bundle. Maybe an old NBI version is running".format(
3272 vnfr_data["member-vnf-index-ref"], kdur["kdu-name"]
3273 )
3274 )
quilesjacde94f2020-01-23 10:07:08 +00003275 # check if kdumodel is a file and exists
3276 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01003277 vnfd_with_id = find_in_list(
3278 db_vnfds, lambda vnfd: vnfd["_id"] == vnfd_id
3279 )
3280 storage = deep_get(vnfd_with_id, ("_admin", "storage"))
bravof486707f2021-11-08 17:18:50 -03003281 if storage: # may be not present if vnfd has not artifacts
tierno51183952020-04-03 15:48:18 +00003282 # path format: /vnfdid/pkkdir/helm-charts|juju-bundles/kdumodel
bravof486707f2021-11-08 17:18:50 -03003283 if storage["pkg-dir"]:
3284 filename = "{}/{}/{}s/{}".format(
3285 storage["folder"],
3286 storage["pkg-dir"],
3287 k8sclustertype,
3288 kdumodel,
3289 )
3290 else:
3291 filename = "{}/Scripts/{}s/{}".format(
3292 storage["folder"],
3293 k8sclustertype,
3294 kdumodel,
3295 )
garciadeblas5697b8b2021-03-24 09:17:02 +01003296 if self.fs.file_exists(
3297 filename, mode="file"
3298 ) or self.fs.file_exists(filename, mode="dir"):
tierno51183952020-04-03 15:48:18 +00003299 kdumodel = self.fs.path + filename
3300 except (asyncio.TimeoutError, asyncio.CancelledError):
tiernoe876f672020-02-13 14:34:48 +00003301 raise
garciadeblas5697b8b2021-03-24 09:17:02 +01003302 except Exception: # it is not a file
quilesjacde94f2020-01-23 10:07:08 +00003303 pass
lloretgallegedc5f332020-02-20 11:50:50 +01003304
tiernoe876f672020-02-13 14:34:48 +00003305 k8s_cluster_id = kdur["k8s-cluster"]["id"]
garciadeblas5697b8b2021-03-24 09:17:02 +01003306 step = "Synchronize repos for k8s cluster '{}'".format(
3307 k8s_cluster_id
3308 )
tierno16f4a4e2020-07-20 09:05:51 +00003309 cluster_uuid = await _get_cluster_id(k8s_cluster_id, k8sclustertype)
lloretgallegedc5f332020-02-20 11:50:50 +01003310
lloretgalleg7c121132020-07-08 07:53:22 +00003311 # Synchronize repos
garciadeblas5697b8b2021-03-24 09:17:02 +01003312 if (
3313 k8sclustertype == "helm-chart"
3314 and cluster_uuid not in updated_cluster_list
3315 ) or (
3316 k8sclustertype == "helm-chart-v3"
3317 and cluster_uuid not in updated_v3_cluster_list
3318 ):
tiernoe876f672020-02-13 14:34:48 +00003319 del_repo_list, added_repo_dict = await asyncio.ensure_future(
garciadeblas5697b8b2021-03-24 09:17:02 +01003320 self.k8scluster_map[k8sclustertype].synchronize_repos(
3321 cluster_uuid=cluster_uuid
3322 )
3323 )
tiernoe876f672020-02-13 14:34:48 +00003324 if del_repo_list or added_repo_dict:
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003325 if k8sclustertype == "helm-chart":
garciadeblas5697b8b2021-03-24 09:17:02 +01003326 unset = {
3327 "_admin.helm_charts_added." + item: None
3328 for item in del_repo_list
3329 }
3330 updated = {
3331 "_admin.helm_charts_added." + item: name
3332 for item, name in added_repo_dict.items()
3333 }
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003334 updated_cluster_list.append(cluster_uuid)
3335 elif k8sclustertype == "helm-chart-v3":
garciadeblas5697b8b2021-03-24 09:17:02 +01003336 unset = {
3337 "_admin.helm_charts_v3_added." + item: None
3338 for item in del_repo_list
3339 }
3340 updated = {
3341 "_admin.helm_charts_v3_added." + item: name
3342 for item, name in added_repo_dict.items()
3343 }
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003344 updated_v3_cluster_list.append(cluster_uuid)
garciadeblas5697b8b2021-03-24 09:17:02 +01003345 self.logger.debug(
3346 logging_text + "repos synchronized on k8s cluster "
3347 "'{}' to_delete: {}, to_add: {}".format(
3348 k8s_cluster_id, del_repo_list, added_repo_dict
3349 )
3350 )
3351 self.db.set_one(
3352 "k8sclusters",
3353 {"_id": k8s_cluster_id},
3354 updated,
3355 unset=unset,
3356 )
lloretgallegedc5f332020-02-20 11:50:50 +01003357
lloretgalleg7c121132020-07-08 07:53:22 +00003358 # Instantiate kdu
garciadeblas5697b8b2021-03-24 09:17:02 +01003359 step = "Instantiating KDU {}.{} in k8s cluster {}".format(
3360 vnfr_data["member-vnf-index-ref"],
3361 kdur["kdu-name"],
3362 k8s_cluster_id,
3363 )
3364 k8s_instance_info = {
3365 "kdu-instance": None,
3366 "k8scluster-uuid": cluster_uuid,
3367 "k8scluster-type": k8sclustertype,
3368 "member-vnf-index": vnfr_data["member-vnf-index-ref"],
3369 "kdu-name": kdur["kdu-name"],
3370 "kdu-model": kdumodel,
3371 "namespace": namespace,
romeromonser4554a702021-05-28 12:00:08 +02003372 "kdu-deployment-name": kdu_deployment_name,
garciadeblas5697b8b2021-03-24 09:17:02 +01003373 }
tiernob9018152020-04-16 14:18:24 +00003374 db_path = "_admin.deployed.K8s.{}".format(index)
lloretgalleg7c121132020-07-08 07:53:22 +00003375 db_nsr_update[db_path] = k8s_instance_info
tierno626e0152019-11-29 14:16:16 +00003376 self.update_db_2("nsrs", nsr_id, db_nsr_update)
garciadeblas5697b8b2021-03-24 09:17:02 +01003377 vnfd_with_id = find_in_list(
3378 db_vnfds, lambda vnf: vnf["_id"] == vnfd_id
3379 )
tiernoa2143262020-03-27 16:20:40 +00003380 task = asyncio.ensure_future(
garciadeblas5697b8b2021-03-24 09:17:02 +01003381 self._install_kdu(
3382 nsr_id,
3383 db_path,
3384 vnfr_data,
3385 kdu_index,
3386 kdud,
3387 vnfd_with_id,
3388 k8s_instance_info,
3389 k8params=desc_params,
3390 timeout=600,
3391 vca_id=vca_id,
3392 )
3393 )
3394 self.lcm_tasks.register(
3395 "ns",
3396 nsr_id,
3397 nslcmop_id,
3398 "instantiate_KDU-{}".format(index),
3399 task,
3400 )
3401 task_instantiation_info[task] = "Deploying KDU {}".format(
3402 kdur["kdu-name"]
3403 )
tiernoe876f672020-02-13 14:34:48 +00003404
tierno626e0152019-11-29 14:16:16 +00003405 index += 1
quilesjdd799ac2020-01-23 16:31:11 +00003406
tiernoe876f672020-02-13 14:34:48 +00003407 except (LcmException, asyncio.CancelledError):
3408 raise
calvinosanch9f9c6f22019-11-04 13:37:39 +01003409 except Exception as e:
tiernoe876f672020-02-13 14:34:48 +00003410 msg = "Exception {} while {}: {}".format(type(e).__name__, step, e)
3411 if isinstance(e, (N2VCException, DbException)):
3412 self.logger.error(logging_text + msg)
3413 else:
3414 self.logger.critical(logging_text + msg, exc_info=True)
quilesjdd799ac2020-01-23 16:31:11 +00003415 raise LcmException(msg)
calvinosanch9f9c6f22019-11-04 13:37:39 +01003416 finally:
calvinosanch9f9c6f22019-11-04 13:37:39 +01003417 if db_nsr_update:
3418 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernoda6fb102019-11-23 00:36:52 +00003419
garciadeblas5697b8b2021-03-24 09:17:02 +01003420 def _deploy_n2vc(
3421 self,
3422 logging_text,
3423 db_nsr,
3424 db_vnfr,
3425 nslcmop_id,
3426 nsr_id,
3427 nsi_id,
3428 vnfd_id,
3429 vdu_id,
3430 kdu_name,
3431 member_vnf_index,
3432 vdu_index,
3433 vdu_name,
3434 deploy_params,
3435 descriptor_config,
3436 base_folder,
3437 task_instantiation_info,
3438 stage,
3439 ):
quilesj7e13aeb2019-10-08 13:34:55 +02003440 # launch instantiate_N2VC in a asyncio task and register task object
3441 # Look where information of this charm is at database <nsrs>._admin.deployed.VCA
3442 # if not found, create one entry and update database
quilesj7e13aeb2019-10-08 13:34:55 +02003443 # fill db_nsr._admin.deployed.VCA.<index>
tierno588547c2020-07-01 15:30:20 +00003444
garciadeblas5697b8b2021-03-24 09:17:02 +01003445 self.logger.debug(
3446 logging_text + "_deploy_n2vc vnfd_id={}, vdu_id={}".format(vnfd_id, vdu_id)
3447 )
bravof9a256db2021-02-22 18:02:07 -03003448 if "execution-environment-list" in descriptor_config:
3449 ee_list = descriptor_config.get("execution-environment-list", [])
David Garcia9ad54a42021-05-28 12:08:18 +02003450 elif "juju" in descriptor_config:
3451 ee_list = [descriptor_config] # ns charms
tierno588547c2020-07-01 15:30:20 +00003452 else: # other types as script are not supported
3453 ee_list = []
3454
3455 for ee_item in ee_list:
garciadeblas5697b8b2021-03-24 09:17:02 +01003456 self.logger.debug(
3457 logging_text
3458 + "_deploy_n2vc ee_item juju={}, helm={}".format(
3459 ee_item.get("juju"), ee_item.get("helm-chart")
3460 )
3461 )
tiernoa278b842020-07-08 15:33:55 +00003462 ee_descriptor_id = ee_item.get("id")
tierno588547c2020-07-01 15:30:20 +00003463 if ee_item.get("juju"):
garciadeblas5697b8b2021-03-24 09:17:02 +01003464 vca_name = ee_item["juju"].get("charm")
3465 vca_type = (
3466 "lxc_proxy_charm"
3467 if ee_item["juju"].get("charm") is not None
3468 else "native_charm"
3469 )
3470 if ee_item["juju"].get("cloud") == "k8s":
tierno588547c2020-07-01 15:30:20 +00003471 vca_type = "k8s_proxy_charm"
garciadeblas5697b8b2021-03-24 09:17:02 +01003472 elif ee_item["juju"].get("proxy") is False:
tierno588547c2020-07-01 15:30:20 +00003473 vca_type = "native_charm"
3474 elif ee_item.get("helm-chart"):
garciadeblas5697b8b2021-03-24 09:17:02 +01003475 vca_name = ee_item["helm-chart"]
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003476 if ee_item.get("helm-version") and ee_item.get("helm-version") == "v2":
3477 vca_type = "helm"
3478 else:
3479 vca_type = "helm-v3"
tierno588547c2020-07-01 15:30:20 +00003480 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01003481 self.logger.debug(
3482 logging_text + "skipping non juju neither charm configuration"
3483 )
quilesj7e13aeb2019-10-08 13:34:55 +02003484 continue
quilesj3655ae02019-12-12 16:08:35 +00003485
tierno588547c2020-07-01 15:30:20 +00003486 vca_index = -1
garciadeblas5697b8b2021-03-24 09:17:02 +01003487 for vca_index, vca_deployed in enumerate(
3488 db_nsr["_admin"]["deployed"]["VCA"]
3489 ):
tierno588547c2020-07-01 15:30:20 +00003490 if not vca_deployed:
3491 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01003492 if (
3493 vca_deployed.get("member-vnf-index") == member_vnf_index
3494 and vca_deployed.get("vdu_id") == vdu_id
3495 and vca_deployed.get("kdu_name") == kdu_name
3496 and vca_deployed.get("vdu_count_index", 0) == vdu_index
3497 and vca_deployed.get("ee_descriptor_id") == ee_descriptor_id
3498 ):
tierno588547c2020-07-01 15:30:20 +00003499 break
3500 else:
3501 # not found, create one.
garciadeblas5697b8b2021-03-24 09:17:02 +01003502 target = (
3503 "ns" if not member_vnf_index else "vnf/{}".format(member_vnf_index)
3504 )
tiernoa278b842020-07-08 15:33:55 +00003505 if vdu_id:
3506 target += "/vdu/{}/{}".format(vdu_id, vdu_index or 0)
3507 elif kdu_name:
3508 target += "/kdu/{}".format(kdu_name)
tierno588547c2020-07-01 15:30:20 +00003509 vca_deployed = {
tiernoa278b842020-07-08 15:33:55 +00003510 "target_element": target,
3511 # ^ target_element will replace member-vnf-index, kdu_name, vdu_id ... in a single string
tierno588547c2020-07-01 15:30:20 +00003512 "member-vnf-index": member_vnf_index,
3513 "vdu_id": vdu_id,
3514 "kdu_name": kdu_name,
3515 "vdu_count_index": vdu_index,
3516 "operational-status": "init", # TODO revise
3517 "detailed-status": "", # TODO revise
garciadeblas5697b8b2021-03-24 09:17:02 +01003518 "step": "initial-deploy", # TODO revise
tierno588547c2020-07-01 15:30:20 +00003519 "vnfd_id": vnfd_id,
3520 "vdu_name": vdu_name,
tiernoa278b842020-07-08 15:33:55 +00003521 "type": vca_type,
garciadeblas5697b8b2021-03-24 09:17:02 +01003522 "ee_descriptor_id": ee_descriptor_id,
tierno588547c2020-07-01 15:30:20 +00003523 }
3524 vca_index += 1
quilesj3655ae02019-12-12 16:08:35 +00003525
tierno588547c2020-07-01 15:30:20 +00003526 # create VCA and configurationStatus in db
3527 db_dict = {
3528 "_admin.deployed.VCA.{}".format(vca_index): vca_deployed,
garciadeblas5697b8b2021-03-24 09:17:02 +01003529 "configurationStatus.{}".format(vca_index): dict(),
tierno588547c2020-07-01 15:30:20 +00003530 }
3531 self.update_db_2("nsrs", nsr_id, db_dict)
quilesj7e13aeb2019-10-08 13:34:55 +02003532
tierno588547c2020-07-01 15:30:20 +00003533 db_nsr["_admin"]["deployed"]["VCA"].append(vca_deployed)
3534
bravof922c4172020-11-24 21:21:43 -03003535 self.logger.debug("N2VC > NSR_ID > {}".format(nsr_id))
3536 self.logger.debug("N2VC > DB_NSR > {}".format(db_nsr))
3537 self.logger.debug("N2VC > VCA_DEPLOYED > {}".format(vca_deployed))
3538
tierno588547c2020-07-01 15:30:20 +00003539 # Launch task
3540 task_n2vc = asyncio.ensure_future(
3541 self.instantiate_N2VC(
3542 logging_text=logging_text,
3543 vca_index=vca_index,
3544 nsi_id=nsi_id,
3545 db_nsr=db_nsr,
3546 db_vnfr=db_vnfr,
3547 vdu_id=vdu_id,
3548 kdu_name=kdu_name,
3549 vdu_index=vdu_index,
3550 deploy_params=deploy_params,
3551 config_descriptor=descriptor_config,
3552 base_folder=base_folder,
3553 nslcmop_id=nslcmop_id,
3554 stage=stage,
3555 vca_type=vca_type,
tiernob996d942020-07-03 14:52:28 +00003556 vca_name=vca_name,
garciadeblas5697b8b2021-03-24 09:17:02 +01003557 ee_config_descriptor=ee_item,
tierno588547c2020-07-01 15:30:20 +00003558 )
quilesj7e13aeb2019-10-08 13:34:55 +02003559 )
garciadeblas5697b8b2021-03-24 09:17:02 +01003560 self.lcm_tasks.register(
3561 "ns",
3562 nsr_id,
3563 nslcmop_id,
3564 "instantiate_N2VC-{}".format(vca_index),
3565 task_n2vc,
3566 )
3567 task_instantiation_info[
3568 task_n2vc
3569 ] = self.task_name_deploy_vca + " {}.{}".format(
3570 member_vnf_index or "", vdu_id or ""
3571 )
tiernobaa51102018-12-14 13:16:18 +00003572
tiernoc9556972019-07-05 15:25:25 +00003573 @staticmethod
kuuse0ca67472019-05-13 15:59:27 +02003574 def _create_nslcmop(nsr_id, operation, params):
3575 """
3576 Creates a ns-lcm-opp content to be stored at database.
3577 :param nsr_id: internal id of the instance
3578 :param operation: instantiate, terminate, scale, action, ...
3579 :param params: user parameters for the operation
3580 :return: dictionary following SOL005 format
3581 """
3582 # Raise exception if invalid arguments
3583 if not (nsr_id and operation and params):
3584 raise LcmException(
garciadeblas5697b8b2021-03-24 09:17:02 +01003585 "Parameters 'nsr_id', 'operation' and 'params' needed to create primitive not provided"
3586 )
kuuse0ca67472019-05-13 15:59:27 +02003587 now = time()
3588 _id = str(uuid4())
3589 nslcmop = {
3590 "id": _id,
3591 "_id": _id,
3592 # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
3593 "operationState": "PROCESSING",
3594 "statusEnteredTime": now,
3595 "nsInstanceId": nsr_id,
3596 "lcmOperationType": operation,
3597 "startTime": now,
3598 "isAutomaticInvocation": False,
3599 "operationParams": params,
3600 "isCancelPending": False,
3601 "links": {
3602 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
3603 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01003604 },
kuuse0ca67472019-05-13 15:59:27 +02003605 }
3606 return nslcmop
3607
calvinosanch9f9c6f22019-11-04 13:37:39 +01003608 def _format_additional_params(self, params):
tierno626e0152019-11-29 14:16:16 +00003609 params = params or {}
calvinosanch9f9c6f22019-11-04 13:37:39 +01003610 for key, value in params.items():
3611 if str(value).startswith("!!yaml "):
3612 params[key] = yaml.safe_load(value[7:])
calvinosanch9f9c6f22019-11-04 13:37:39 +01003613 return params
3614
kuuse8b998e42019-07-30 15:22:16 +02003615 def _get_terminate_primitive_params(self, seq, vnf_index):
garciadeblas5697b8b2021-03-24 09:17:02 +01003616 primitive = seq.get("name")
kuuse8b998e42019-07-30 15:22:16 +02003617 primitive_params = {}
3618 params = {
3619 "member_vnf_index": vnf_index,
3620 "primitive": primitive,
3621 "primitive_params": primitive_params,
3622 }
3623 desc_params = {}
3624 return self._map_primitive_params(seq, params, desc_params)
3625
kuuseac3a8882019-10-03 10:48:06 +02003626 # sub-operations
3627
tierno51183952020-04-03 15:48:18 +00003628 def _retry_or_skip_suboperation(self, db_nslcmop, op_index):
garciadeblas5697b8b2021-03-24 09:17:02 +01003629 op = deep_get(db_nslcmop, ("_admin", "operations"), [])[op_index]
3630 if op.get("operationState") == "COMPLETED":
kuuseac3a8882019-10-03 10:48:06 +02003631 # b. Skip sub-operation
3632 # _ns_execute_primitive() or RO.create_action() will NOT be executed
3633 return self.SUBOPERATION_STATUS_SKIP
3634 else:
tierno7c4e24c2020-05-13 08:41:35 +00003635 # c. retry executing sub-operation
kuuseac3a8882019-10-03 10:48:06 +02003636 # The sub-operation exists, and operationState != 'COMPLETED'
tierno7c4e24c2020-05-13 08:41:35 +00003637 # Update operationState = 'PROCESSING' to indicate a retry.
garciadeblas5697b8b2021-03-24 09:17:02 +01003638 operationState = "PROCESSING"
3639 detailed_status = "In progress"
kuuseac3a8882019-10-03 10:48:06 +02003640 self._update_suboperation_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01003641 db_nslcmop, op_index, operationState, detailed_status
3642 )
kuuseac3a8882019-10-03 10:48:06 +02003643 # Return the sub-operation index
3644 # _ns_execute_primitive() or RO.create_action() will be called from scale()
3645 # with arguments extracted from the sub-operation
3646 return op_index
3647
3648 # Find a sub-operation where all keys in a matching dictionary must match
3649 # Returns the index of the matching sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if no match
3650 def _find_suboperation(self, db_nslcmop, match):
tierno7c4e24c2020-05-13 08:41:35 +00003651 if db_nslcmop and match:
garciadeblas5697b8b2021-03-24 09:17:02 +01003652 op_list = db_nslcmop.get("_admin", {}).get("operations", [])
kuuseac3a8882019-10-03 10:48:06 +02003653 for i, op in enumerate(op_list):
3654 if all(op.get(k) == match[k] for k in match):
3655 return i
3656 return self.SUBOPERATION_STATUS_NOT_FOUND
3657
3658 # Update status for a sub-operation given its index
garciadeblas5697b8b2021-03-24 09:17:02 +01003659 def _update_suboperation_status(
3660 self, db_nslcmop, op_index, operationState, detailed_status
3661 ):
kuuseac3a8882019-10-03 10:48:06 +02003662 # Update DB for HA tasks
garciadeblas5697b8b2021-03-24 09:17:02 +01003663 q_filter = {"_id": db_nslcmop["_id"]}
3664 update_dict = {
3665 "_admin.operations.{}.operationState".format(op_index): operationState,
3666 "_admin.operations.{}.detailed-status".format(op_index): detailed_status,
3667 }
3668 self.db.set_one(
3669 "nslcmops", q_filter=q_filter, update_dict=update_dict, fail_on_empty=False
3670 )
kuuseac3a8882019-10-03 10:48:06 +02003671
3672 # Add sub-operation, return the index of the added sub-operation
3673 # Optionally, set operationState, detailed-status, and operationType
3674 # Status and type are currently set for 'scale' sub-operations:
3675 # 'operationState' : 'PROCESSING' | 'COMPLETED' | 'FAILED'
3676 # 'detailed-status' : status message
3677 # 'operationType': may be any type, in the case of scaling: 'PRE-SCALE' | 'POST-SCALE'
3678 # Status and operation type are currently only used for 'scale', but NOT for 'terminate' sub-operations.
garciadeblas5697b8b2021-03-24 09:17:02 +01003679 def _add_suboperation(
3680 self,
3681 db_nslcmop,
3682 vnf_index,
3683 vdu_id,
3684 vdu_count_index,
3685 vdu_name,
3686 primitive,
3687 mapped_primitive_params,
3688 operationState=None,
3689 detailed_status=None,
3690 operationType=None,
3691 RO_nsr_id=None,
3692 RO_scaling_info=None,
3693 ):
tiernoe876f672020-02-13 14:34:48 +00003694 if not db_nslcmop:
kuuseac3a8882019-10-03 10:48:06 +02003695 return self.SUBOPERATION_STATUS_NOT_FOUND
3696 # Get the "_admin.operations" list, if it exists
garciadeblas5697b8b2021-03-24 09:17:02 +01003697 db_nslcmop_admin = db_nslcmop.get("_admin", {})
3698 op_list = db_nslcmop_admin.get("operations")
kuuseac3a8882019-10-03 10:48:06 +02003699 # Create or append to the "_admin.operations" list
garciadeblas5697b8b2021-03-24 09:17:02 +01003700 new_op = {
3701 "member_vnf_index": vnf_index,
3702 "vdu_id": vdu_id,
3703 "vdu_count_index": vdu_count_index,
3704 "primitive": primitive,
3705 "primitive_params": mapped_primitive_params,
3706 }
kuuseac3a8882019-10-03 10:48:06 +02003707 if operationState:
garciadeblas5697b8b2021-03-24 09:17:02 +01003708 new_op["operationState"] = operationState
kuuseac3a8882019-10-03 10:48:06 +02003709 if detailed_status:
garciadeblas5697b8b2021-03-24 09:17:02 +01003710 new_op["detailed-status"] = detailed_status
kuuseac3a8882019-10-03 10:48:06 +02003711 if operationType:
garciadeblas5697b8b2021-03-24 09:17:02 +01003712 new_op["lcmOperationType"] = operationType
kuuseac3a8882019-10-03 10:48:06 +02003713 if RO_nsr_id:
garciadeblas5697b8b2021-03-24 09:17:02 +01003714 new_op["RO_nsr_id"] = RO_nsr_id
kuuseac3a8882019-10-03 10:48:06 +02003715 if RO_scaling_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01003716 new_op["RO_scaling_info"] = RO_scaling_info
kuuseac3a8882019-10-03 10:48:06 +02003717 if not op_list:
3718 # No existing operations, create key 'operations' with current operation as first list element
garciadeblas5697b8b2021-03-24 09:17:02 +01003719 db_nslcmop_admin.update({"operations": [new_op]})
3720 op_list = db_nslcmop_admin.get("operations")
kuuseac3a8882019-10-03 10:48:06 +02003721 else:
3722 # Existing operations, append operation to list
3723 op_list.append(new_op)
kuuse8b998e42019-07-30 15:22:16 +02003724
garciadeblas5697b8b2021-03-24 09:17:02 +01003725 db_nslcmop_update = {"_admin.operations": op_list}
3726 self.update_db_2("nslcmops", db_nslcmop["_id"], db_nslcmop_update)
kuuseac3a8882019-10-03 10:48:06 +02003727 op_index = len(op_list) - 1
3728 return op_index
3729
3730 # Helper methods for scale() sub-operations
3731
3732 # pre-scale/post-scale:
3733 # Check for 3 different cases:
3734 # a. New: First time execution, return SUBOPERATION_STATUS_NEW
3735 # b. Skip: Existing sub-operation exists, operationState == 'COMPLETED', return SUBOPERATION_STATUS_SKIP
tierno7c4e24c2020-05-13 08:41:35 +00003736 # c. retry: Existing sub-operation exists, operationState != 'COMPLETED', return op_index to re-execute
garciadeblas5697b8b2021-03-24 09:17:02 +01003737 def _check_or_add_scale_suboperation(
3738 self,
3739 db_nslcmop,
3740 vnf_index,
3741 vnf_config_primitive,
3742 primitive_params,
3743 operationType,
3744 RO_nsr_id=None,
3745 RO_scaling_info=None,
3746 ):
kuuseac3a8882019-10-03 10:48:06 +02003747 # Find this sub-operation
tierno7c4e24c2020-05-13 08:41:35 +00003748 if RO_nsr_id and RO_scaling_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01003749 operationType = "SCALE-RO"
kuuseac3a8882019-10-03 10:48:06 +02003750 match = {
garciadeblas5697b8b2021-03-24 09:17:02 +01003751 "member_vnf_index": vnf_index,
3752 "RO_nsr_id": RO_nsr_id,
3753 "RO_scaling_info": RO_scaling_info,
kuuseac3a8882019-10-03 10:48:06 +02003754 }
3755 else:
3756 match = {
garciadeblas5697b8b2021-03-24 09:17:02 +01003757 "member_vnf_index": vnf_index,
3758 "primitive": vnf_config_primitive,
3759 "primitive_params": primitive_params,
3760 "lcmOperationType": operationType,
kuuseac3a8882019-10-03 10:48:06 +02003761 }
3762 op_index = self._find_suboperation(db_nslcmop, match)
tierno51183952020-04-03 15:48:18 +00003763 if op_index == self.SUBOPERATION_STATUS_NOT_FOUND:
kuuseac3a8882019-10-03 10:48:06 +02003764 # a. New sub-operation
3765 # The sub-operation does not exist, add it.
3766 # _ns_execute_primitive() will be called from scale() as usual, with non-modified arguments
3767 # The following parameters are set to None for all kind of scaling:
3768 vdu_id = None
3769 vdu_count_index = None
3770 vdu_name = None
tierno51183952020-04-03 15:48:18 +00003771 if RO_nsr_id and RO_scaling_info:
kuuseac3a8882019-10-03 10:48:06 +02003772 vnf_config_primitive = None
3773 primitive_params = None
3774 else:
3775 RO_nsr_id = None
3776 RO_scaling_info = None
3777 # Initial status for sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01003778 operationState = "PROCESSING"
3779 detailed_status = "In progress"
kuuseac3a8882019-10-03 10:48:06 +02003780 # Add sub-operation for pre/post-scaling (zero or more operations)
garciadeblas5697b8b2021-03-24 09:17:02 +01003781 self._add_suboperation(
3782 db_nslcmop,
3783 vnf_index,
3784 vdu_id,
3785 vdu_count_index,
3786 vdu_name,
3787 vnf_config_primitive,
3788 primitive_params,
3789 operationState,
3790 detailed_status,
3791 operationType,
3792 RO_nsr_id,
3793 RO_scaling_info,
3794 )
kuuseac3a8882019-10-03 10:48:06 +02003795 return self.SUBOPERATION_STATUS_NEW
3796 else:
3797 # Return either SUBOPERATION_STATUS_SKIP (operationState == 'COMPLETED'),
3798 # or op_index (operationState != 'COMPLETED')
tierno51183952020-04-03 15:48:18 +00003799 return self._retry_or_skip_suboperation(db_nslcmop, op_index)
kuuseac3a8882019-10-03 10:48:06 +02003800
preethika.pdf7d8e02019-12-10 13:10:48 +00003801 # Function to return execution_environment id
3802
3803 def _get_ee_id(self, vnf_index, vdu_id, vca_deployed_list):
tiernoe876f672020-02-13 14:34:48 +00003804 # TODO vdu_index_count
preethika.pdf7d8e02019-12-10 13:10:48 +00003805 for vca in vca_deployed_list:
3806 if vca["member-vnf-index"] == vnf_index and vca["vdu_id"] == vdu_id:
3807 return vca["ee_id"]
3808
David Garciac1fe90a2021-03-31 19:12:02 +02003809 async def destroy_N2VC(
3810 self,
3811 logging_text,
3812 db_nslcmop,
3813 vca_deployed,
3814 config_descriptor,
3815 vca_index,
3816 destroy_ee=True,
3817 exec_primitives=True,
3818 scaling_in=False,
3819 vca_id: str = None,
3820 ):
tiernoe876f672020-02-13 14:34:48 +00003821 """
3822 Execute the terminate primitives and destroy the execution environment (if destroy_ee=False
3823 :param logging_text:
3824 :param db_nslcmop:
3825 :param vca_deployed: Dictionary of deployment info at db_nsr._admin.depoloyed.VCA.<INDEX>
3826 :param config_descriptor: Configuration descriptor of the NSD, VNFD, VNFD.vdu or VNFD.kdu
3827 :param vca_index: index in the database _admin.deployed.VCA
3828 :param destroy_ee: False to do not destroy, because it will be destroyed all of then at once
tierno588547c2020-07-01 15:30:20 +00003829 :param exec_primitives: False to do not execute terminate primitives, because the config is not completed or has
3830 not executed properly
aktas13251562021-02-12 22:19:10 +03003831 :param scaling_in: True destroys the application, False destroys the model
tiernoe876f672020-02-13 14:34:48 +00003832 :return: None or exception
3833 """
tiernoe876f672020-02-13 14:34:48 +00003834
tierno588547c2020-07-01 15:30:20 +00003835 self.logger.debug(
garciadeblas5697b8b2021-03-24 09:17:02 +01003836 logging_text
3837 + " vca_index: {}, vca_deployed: {}, config_descriptor: {}, destroy_ee: {}".format(
tierno588547c2020-07-01 15:30:20 +00003838 vca_index, vca_deployed, config_descriptor, destroy_ee
3839 )
3840 )
3841
3842 vca_type = vca_deployed.get("type", "lxc_proxy_charm")
3843
3844 # execute terminate_primitives
3845 if exec_primitives:
bravof922c4172020-11-24 21:21:43 -03003846 terminate_primitives = get_ee_sorted_terminate_config_primitive_list(
garciadeblas5697b8b2021-03-24 09:17:02 +01003847 config_descriptor.get("terminate-config-primitive"),
3848 vca_deployed.get("ee_descriptor_id"),
3849 )
tierno588547c2020-07-01 15:30:20 +00003850 vdu_id = vca_deployed.get("vdu_id")
3851 vdu_count_index = vca_deployed.get("vdu_count_index")
3852 vdu_name = vca_deployed.get("vdu_name")
3853 vnf_index = vca_deployed.get("member-vnf-index")
3854 if terminate_primitives and vca_deployed.get("needed_terminate"):
tierno588547c2020-07-01 15:30:20 +00003855 for seq in terminate_primitives:
3856 # For each sequence in list, get primitive and call _ns_execute_primitive()
3857 step = "Calling terminate action for vnf_member_index={} primitive={}".format(
garciadeblas5697b8b2021-03-24 09:17:02 +01003858 vnf_index, seq.get("name")
3859 )
tierno588547c2020-07-01 15:30:20 +00003860 self.logger.debug(logging_text + step)
3861 # Create the primitive for each sequence, i.e. "primitive": "touch"
garciadeblas5697b8b2021-03-24 09:17:02 +01003862 primitive = seq.get("name")
3863 mapped_primitive_params = self._get_terminate_primitive_params(
3864 seq, vnf_index
3865 )
tierno588547c2020-07-01 15:30:20 +00003866
3867 # Add sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01003868 self._add_suboperation(
3869 db_nslcmop,
3870 vnf_index,
3871 vdu_id,
3872 vdu_count_index,
3873 vdu_name,
3874 primitive,
3875 mapped_primitive_params,
3876 )
tierno588547c2020-07-01 15:30:20 +00003877 # Sub-operations: Call _ns_execute_primitive() instead of action()
3878 try:
David Garciac1fe90a2021-03-31 19:12:02 +02003879 result, result_detail = await self._ns_execute_primitive(
garciadeblas5697b8b2021-03-24 09:17:02 +01003880 vca_deployed["ee_id"],
3881 primitive,
David Garciac1fe90a2021-03-31 19:12:02 +02003882 mapped_primitive_params,
3883 vca_type=vca_type,
3884 vca_id=vca_id,
3885 )
tierno588547c2020-07-01 15:30:20 +00003886 except LcmException:
3887 # this happens when VCA is not deployed. In this case it is not needed to terminate
3888 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01003889 result_ok = ["COMPLETED", "PARTIALLY_COMPLETED"]
tierno588547c2020-07-01 15:30:20 +00003890 if result not in result_ok:
garciadeblas5697b8b2021-03-24 09:17:02 +01003891 raise LcmException(
3892 "terminate_primitive {} for vnf_member_index={} fails with "
3893 "error {}".format(seq.get("name"), vnf_index, result_detail)
3894 )
tierno588547c2020-07-01 15:30:20 +00003895 # set that this VCA do not need terminated
garciadeblas5697b8b2021-03-24 09:17:02 +01003896 db_update_entry = "_admin.deployed.VCA.{}.needed_terminate".format(
3897 vca_index
3898 )
3899 self.update_db_2(
3900 "nsrs", db_nslcmop["nsInstanceId"], {db_update_entry: False}
3901 )
tiernoe876f672020-02-13 14:34:48 +00003902
tiernob996d942020-07-03 14:52:28 +00003903 if vca_deployed.get("prometheus_jobs") and self.prometheus:
3904 await self.prometheus.update(remove_jobs=vca_deployed["prometheus_jobs"])
3905
tiernoe876f672020-02-13 14:34:48 +00003906 if destroy_ee:
David Garciac1fe90a2021-03-31 19:12:02 +02003907 await self.vca_map[vca_type].delete_execution_environment(
3908 vca_deployed["ee_id"],
3909 scaling_in=scaling_in,
aktas98488ed2021-07-29 17:42:49 +03003910 vca_type=vca_type,
David Garciac1fe90a2021-03-31 19:12:02 +02003911 vca_id=vca_id,
3912 )
kuuse0ca67472019-05-13 15:59:27 +02003913
David Garciac1fe90a2021-03-31 19:12:02 +02003914 async def _delete_all_N2VC(self, db_nsr: dict, vca_id: str = None):
garciadeblas5697b8b2021-03-24 09:17:02 +01003915 self._write_all_config_status(db_nsr=db_nsr, status="TERMINATING")
tierno51183952020-04-03 15:48:18 +00003916 namespace = "." + db_nsr["_id"]
tiernof59ad6c2020-04-08 12:50:52 +00003917 try:
David Garciac1fe90a2021-03-31 19:12:02 +02003918 await self.n2vc.delete_namespace(
3919 namespace=namespace,
3920 total_timeout=self.timeout_charm_delete,
3921 vca_id=vca_id,
3922 )
tiernof59ad6c2020-04-08 12:50:52 +00003923 except N2VCNotFound: # already deleted. Skip
3924 pass
garciadeblas5697b8b2021-03-24 09:17:02 +01003925 self._write_all_config_status(db_nsr=db_nsr, status="DELETED")
quilesj3655ae02019-12-12 16:08:35 +00003926
garciadeblas5697b8b2021-03-24 09:17:02 +01003927 async def _terminate_RO(
3928 self, logging_text, nsr_deployed, nsr_id, nslcmop_id, stage
3929 ):
tiernoe876f672020-02-13 14:34:48 +00003930 """
3931 Terminates a deployment from RO
3932 :param logging_text:
3933 :param nsr_deployed: db_nsr._admin.deployed
3934 :param nsr_id:
3935 :param nslcmop_id:
3936 :param stage: list of string with the content to write on db_nslcmop.detailed-status.
3937 this method will update only the index 2, but it will write on database the concatenated content of the list
3938 :return:
3939 """
3940 db_nsr_update = {}
3941 failed_detail = []
3942 ro_nsr_id = ro_delete_action = None
3943 if nsr_deployed and nsr_deployed.get("RO"):
3944 ro_nsr_id = nsr_deployed["RO"].get("nsr_id")
3945 ro_delete_action = nsr_deployed["RO"].get("nsr_delete_action_id")
3946 try:
3947 if ro_nsr_id:
3948 stage[2] = "Deleting ns from VIM."
3949 db_nsr_update["detailed-status"] = " ".join(stage)
3950 self._write_op_status(nslcmop_id, stage)
3951 self.logger.debug(logging_text + stage[2])
3952 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3953 self._write_op_status(nslcmop_id, stage)
3954 desc = await self.RO.delete("ns", ro_nsr_id)
3955 ro_delete_action = desc["action_id"]
garciadeblas5697b8b2021-03-24 09:17:02 +01003956 db_nsr_update[
3957 "_admin.deployed.RO.nsr_delete_action_id"
3958 ] = ro_delete_action
tiernoe876f672020-02-13 14:34:48 +00003959 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
3960 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
3961 if ro_delete_action:
3962 # wait until NS is deleted from VIM
3963 stage[2] = "Waiting ns deleted from VIM."
3964 detailed_status_old = None
garciadeblas5697b8b2021-03-24 09:17:02 +01003965 self.logger.debug(
3966 logging_text
3967 + stage[2]
3968 + " RO_id={} ro_delete_action={}".format(
3969 ro_nsr_id, ro_delete_action
3970 )
3971 )
tiernoe876f672020-02-13 14:34:48 +00003972 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3973 self._write_op_status(nslcmop_id, stage)
kuused124bfe2019-06-18 12:09:24 +02003974
tiernoe876f672020-02-13 14:34:48 +00003975 delete_timeout = 20 * 60 # 20 minutes
3976 while delete_timeout > 0:
3977 desc = await self.RO.show(
3978 "ns",
3979 item_id_name=ro_nsr_id,
3980 extra_item="action",
garciadeblas5697b8b2021-03-24 09:17:02 +01003981 extra_item_id=ro_delete_action,
3982 )
tiernoe876f672020-02-13 14:34:48 +00003983
3984 # deploymentStatus
3985 self._on_update_ro_db(nsrs_id=nsr_id, ro_descriptor=desc)
3986
3987 ns_status, ns_status_info = self.RO.check_action_status(desc)
3988 if ns_status == "ERROR":
3989 raise ROclient.ROClientException(ns_status_info)
3990 elif ns_status == "BUILD":
3991 stage[2] = "Deleting from VIM {}".format(ns_status_info)
3992 elif ns_status == "ACTIVE":
3993 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
3994 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
3995 break
3996 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01003997 assert (
3998 False
3999 ), "ROclient.check_action_status returns unknown {}".format(
4000 ns_status
4001 )
tiernoe876f672020-02-13 14:34:48 +00004002 if stage[2] != detailed_status_old:
4003 detailed_status_old = stage[2]
4004 db_nsr_update["detailed-status"] = " ".join(stage)
4005 self._write_op_status(nslcmop_id, stage)
4006 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4007 await asyncio.sleep(5, loop=self.loop)
4008 delete_timeout -= 5
4009 else: # delete_timeout <= 0:
garciadeblas5697b8b2021-03-24 09:17:02 +01004010 raise ROclient.ROClientException(
4011 "Timeout waiting ns deleted from VIM"
4012 )
tiernoe876f672020-02-13 14:34:48 +00004013
4014 except Exception as e:
4015 self.update_db_2("nsrs", nsr_id, db_nsr_update)
garciadeblas5697b8b2021-03-24 09:17:02 +01004016 if (
4017 isinstance(e, ROclient.ROClientException) and e.http_code == 404
4018 ): # not found
tiernoe876f672020-02-13 14:34:48 +00004019 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
4020 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
4021 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
garciadeblas5697b8b2021-03-24 09:17:02 +01004022 self.logger.debug(
4023 logging_text + "RO_ns_id={} already deleted".format(ro_nsr_id)
4024 )
4025 elif (
4026 isinstance(e, ROclient.ROClientException) and e.http_code == 409
4027 ): # conflict
tiernoa2143262020-03-27 16:20:40 +00004028 failed_detail.append("delete conflict: {}".format(e))
garciadeblas5697b8b2021-03-24 09:17:02 +01004029 self.logger.debug(
4030 logging_text
4031 + "RO_ns_id={} delete conflict: {}".format(ro_nsr_id, e)
4032 )
tiernoe876f672020-02-13 14:34:48 +00004033 else:
tiernoa2143262020-03-27 16:20:40 +00004034 failed_detail.append("delete error: {}".format(e))
garciadeblas5697b8b2021-03-24 09:17:02 +01004035 self.logger.error(
4036 logging_text + "RO_ns_id={} delete error: {}".format(ro_nsr_id, e)
4037 )
tiernoe876f672020-02-13 14:34:48 +00004038
4039 # Delete nsd
4040 if not failed_detail and deep_get(nsr_deployed, ("RO", "nsd_id")):
4041 ro_nsd_id = nsr_deployed["RO"]["nsd_id"]
4042 try:
4043 stage[2] = "Deleting nsd from RO."
4044 db_nsr_update["detailed-status"] = " ".join(stage)
4045 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4046 self._write_op_status(nslcmop_id, stage)
4047 await self.RO.delete("nsd", ro_nsd_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01004048 self.logger.debug(
4049 logging_text + "ro_nsd_id={} deleted".format(ro_nsd_id)
4050 )
tiernoe876f672020-02-13 14:34:48 +00004051 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
4052 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01004053 if (
4054 isinstance(e, ROclient.ROClientException) and e.http_code == 404
4055 ): # not found
tiernoe876f672020-02-13 14:34:48 +00004056 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
garciadeblas5697b8b2021-03-24 09:17:02 +01004057 self.logger.debug(
4058 logging_text + "ro_nsd_id={} already deleted".format(ro_nsd_id)
4059 )
4060 elif (
4061 isinstance(e, ROclient.ROClientException) and e.http_code == 409
4062 ): # conflict
4063 failed_detail.append(
4064 "ro_nsd_id={} delete conflict: {}".format(ro_nsd_id, e)
4065 )
tiernoe876f672020-02-13 14:34:48 +00004066 self.logger.debug(logging_text + failed_detail[-1])
4067 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004068 failed_detail.append(
4069 "ro_nsd_id={} delete error: {}".format(ro_nsd_id, e)
4070 )
tiernoe876f672020-02-13 14:34:48 +00004071 self.logger.error(logging_text + failed_detail[-1])
4072
4073 if not failed_detail and deep_get(nsr_deployed, ("RO", "vnfd")):
4074 for index, vnf_deployed in enumerate(nsr_deployed["RO"]["vnfd"]):
4075 if not vnf_deployed or not vnf_deployed["id"]:
4076 continue
4077 try:
4078 ro_vnfd_id = vnf_deployed["id"]
garciadeblas5697b8b2021-03-24 09:17:02 +01004079 stage[
4080 2
4081 ] = "Deleting member_vnf_index={} ro_vnfd_id={} from RO.".format(
4082 vnf_deployed["member-vnf-index"], ro_vnfd_id
4083 )
tiernoe876f672020-02-13 14:34:48 +00004084 db_nsr_update["detailed-status"] = " ".join(stage)
4085 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4086 self._write_op_status(nslcmop_id, stage)
4087 await self.RO.delete("vnfd", ro_vnfd_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01004088 self.logger.debug(
4089 logging_text + "ro_vnfd_id={} deleted".format(ro_vnfd_id)
4090 )
tiernoe876f672020-02-13 14:34:48 +00004091 db_nsr_update["_admin.deployed.RO.vnfd.{}.id".format(index)] = None
4092 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01004093 if (
4094 isinstance(e, ROclient.ROClientException) and e.http_code == 404
4095 ): # not found
4096 db_nsr_update[
4097 "_admin.deployed.RO.vnfd.{}.id".format(index)
4098 ] = None
4099 self.logger.debug(
4100 logging_text
4101 + "ro_vnfd_id={} already deleted ".format(ro_vnfd_id)
4102 )
4103 elif (
4104 isinstance(e, ROclient.ROClientException) and e.http_code == 409
4105 ): # conflict
4106 failed_detail.append(
4107 "ro_vnfd_id={} delete conflict: {}".format(ro_vnfd_id, e)
4108 )
tiernoe876f672020-02-13 14:34:48 +00004109 self.logger.debug(logging_text + failed_detail[-1])
4110 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004111 failed_detail.append(
4112 "ro_vnfd_id={} delete error: {}".format(ro_vnfd_id, e)
4113 )
tiernoe876f672020-02-13 14:34:48 +00004114 self.logger.error(logging_text + failed_detail[-1])
4115
tiernoa2143262020-03-27 16:20:40 +00004116 if failed_detail:
4117 stage[2] = "Error deleting from VIM"
4118 else:
4119 stage[2] = "Deleted from VIM"
tiernoe876f672020-02-13 14:34:48 +00004120 db_nsr_update["detailed-status"] = " ".join(stage)
4121 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4122 self._write_op_status(nslcmop_id, stage)
4123
4124 if failed_detail:
tiernoa2143262020-03-27 16:20:40 +00004125 raise LcmException("; ".join(failed_detail))
tiernoe876f672020-02-13 14:34:48 +00004126
4127 async def terminate(self, nsr_id, nslcmop_id):
kuused124bfe2019-06-18 12:09:24 +02004128 # Try to lock HA task here
garciadeblas5697b8b2021-03-24 09:17:02 +01004129 task_is_locked_by_me = self.lcm_tasks.lock_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02004130 if not task_is_locked_by_me:
4131 return
4132
tierno59d22d22018-09-25 18:10:19 +02004133 logging_text = "Task ns={} terminate={} ".format(nsr_id, nslcmop_id)
4134 self.logger.debug(logging_text + "Enter")
tiernoe876f672020-02-13 14:34:48 +00004135 timeout_ns_terminate = self.timeout_ns_terminate
tierno59d22d22018-09-25 18:10:19 +02004136 db_nsr = None
4137 db_nslcmop = None
tiernoa17d4f42020-04-28 09:59:23 +00004138 operation_params = None
tierno59d22d22018-09-25 18:10:19 +02004139 exc = None
garciadeblas5697b8b2021-03-24 09:17:02 +01004140 error_list = [] # annotates all failed error messages
tierno59d22d22018-09-25 18:10:19 +02004141 db_nslcmop_update = {}
tiernoc2564fe2019-01-28 16:18:56 +00004142 autoremove = False # autoremove after terminated
tiernoe876f672020-02-13 14:34:48 +00004143 tasks_dict_info = {}
4144 db_nsr_update = {}
garciadeblas5697b8b2021-03-24 09:17:02 +01004145 stage = [
4146 "Stage 1/3: Preparing task.",
4147 "Waiting for previous operations to terminate.",
4148 "",
4149 ]
tiernoe876f672020-02-13 14:34:48 +00004150 # ^ contains [stage, step, VIM-status]
tierno59d22d22018-09-25 18:10:19 +02004151 try:
kuused124bfe2019-06-18 12:09:24 +02004152 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +01004153 await self.lcm_tasks.waitfor_related_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02004154
tiernoe876f672020-02-13 14:34:48 +00004155 stage[1] = "Getting nslcmop={} from db.".format(nslcmop_id)
4156 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
4157 operation_params = db_nslcmop.get("operationParams") or {}
4158 if operation_params.get("timeout_ns_terminate"):
4159 timeout_ns_terminate = operation_params["timeout_ns_terminate"]
4160 stage[1] = "Getting nsr={} from db.".format(nsr_id)
4161 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
4162
4163 db_nsr_update["operational-status"] = "terminating"
4164 db_nsr_update["config-status"] = "terminating"
quilesj4cda56b2019-12-05 10:02:20 +00004165 self._write_ns_status(
4166 nsr_id=nsr_id,
4167 ns_state="TERMINATING",
4168 current_operation="TERMINATING",
tiernoe876f672020-02-13 14:34:48 +00004169 current_operation_id=nslcmop_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01004170 other_update=db_nsr_update,
quilesj4cda56b2019-12-05 10:02:20 +00004171 )
garciadeblas5697b8b2021-03-24 09:17:02 +01004172 self._write_op_status(op_id=nslcmop_id, queuePosition=0, stage=stage)
tiernoe876f672020-02-13 14:34:48 +00004173 nsr_deployed = deepcopy(db_nsr["_admin"].get("deployed")) or {}
tierno59d22d22018-09-25 18:10:19 +02004174 if db_nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
4175 return
tierno59d22d22018-09-25 18:10:19 +02004176
tiernoe876f672020-02-13 14:34:48 +00004177 stage[1] = "Getting vnf descriptors from db."
4178 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
garciadeblas5697b8b2021-03-24 09:17:02 +01004179 db_vnfrs_dict = {
4180 db_vnfr["member-vnf-index-ref"]: db_vnfr for db_vnfr in db_vnfrs_list
4181 }
tiernoe876f672020-02-13 14:34:48 +00004182 db_vnfds_from_id = {}
4183 db_vnfds_from_member_index = {}
4184 # Loop over VNFRs
4185 for vnfr in db_vnfrs_list:
4186 vnfd_id = vnfr["vnfd-id"]
4187 if vnfd_id not in db_vnfds_from_id:
4188 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
4189 db_vnfds_from_id[vnfd_id] = vnfd
garciadeblas5697b8b2021-03-24 09:17:02 +01004190 db_vnfds_from_member_index[
4191 vnfr["member-vnf-index-ref"]
4192 ] = db_vnfds_from_id[vnfd_id]
calvinosanch9f9c6f22019-11-04 13:37:39 +01004193
tiernoe876f672020-02-13 14:34:48 +00004194 # Destroy individual execution environments when there are terminating primitives.
4195 # Rest of EE will be deleted at once
tierno588547c2020-07-01 15:30:20 +00004196 # TODO - check before calling _destroy_N2VC
4197 # if not operation_params.get("skip_terminate_primitives"):#
4198 # or not vca.get("needed_terminate"):
4199 stage[0] = "Stage 2/3 execute terminating primitives."
4200 self.logger.debug(logging_text + stage[0])
4201 stage[1] = "Looking execution environment that needs terminate."
4202 self.logger.debug(logging_text + stage[1])
bravof922c4172020-11-24 21:21:43 -03004203
tierno588547c2020-07-01 15:30:20 +00004204 for vca_index, vca in enumerate(get_iterable(nsr_deployed, "VCA")):
tierno588547c2020-07-01 15:30:20 +00004205 config_descriptor = None
David Garcia9ad54a42021-05-28 12:08:18 +02004206 vca_member_vnf_index = vca.get("member-vnf-index")
4207 vca_id = self.get_vca_id(
4208 db_vnfrs_dict.get(vca_member_vnf_index)
4209 if vca_member_vnf_index
4210 else None,
4211 db_nsr,
4212 )
tierno588547c2020-07-01 15:30:20 +00004213 if not vca or not vca.get("ee_id"):
4214 continue
4215 if not vca.get("member-vnf-index"):
4216 # ns
4217 config_descriptor = db_nsr.get("ns-configuration")
4218 elif vca.get("vdu_id"):
4219 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
bravofe5a31bc2021-02-17 19:09:12 -03004220 config_descriptor = get_configuration(db_vnfd, vca.get("vdu_id"))
tierno588547c2020-07-01 15:30:20 +00004221 elif vca.get("kdu_name"):
4222 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
bravofe5a31bc2021-02-17 19:09:12 -03004223 config_descriptor = get_configuration(db_vnfd, vca.get("kdu_name"))
tierno588547c2020-07-01 15:30:20 +00004224 else:
bravofe5a31bc2021-02-17 19:09:12 -03004225 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
aktas13251562021-02-12 22:19:10 +03004226 config_descriptor = get_configuration(db_vnfd, db_vnfd["id"])
tierno588547c2020-07-01 15:30:20 +00004227 vca_type = vca.get("type")
garciadeblas5697b8b2021-03-24 09:17:02 +01004228 exec_terminate_primitives = not operation_params.get(
4229 "skip_terminate_primitives"
4230 ) and vca.get("needed_terminate")
tiernoaebd7da2020-08-07 06:36:38 +00004231 # For helm we must destroy_ee. Also for native_charm, as juju_model cannot be deleted if there are
4232 # pending native charms
garciadeblas5697b8b2021-03-24 09:17:02 +01004233 destroy_ee = (
4234 True if vca_type in ("helm", "helm-v3", "native_charm") else False
4235 )
tierno86e33612020-09-16 14:13:06 +00004236 # self.logger.debug(logging_text + "vca_index: {}, ee_id: {}, vca_type: {} destroy_ee: {}".format(
4237 # vca_index, vca.get("ee_id"), vca_type, destroy_ee))
tiernob996d942020-07-03 14:52:28 +00004238 task = asyncio.ensure_future(
David Garciac1fe90a2021-03-31 19:12:02 +02004239 self.destroy_N2VC(
4240 logging_text,
4241 db_nslcmop,
4242 vca,
4243 config_descriptor,
4244 vca_index,
4245 destroy_ee,
4246 exec_terminate_primitives,
4247 vca_id=vca_id,
4248 )
4249 )
tierno588547c2020-07-01 15:30:20 +00004250 tasks_dict_info[task] = "Terminating VCA {}".format(vca.get("ee_id"))
tierno59d22d22018-09-25 18:10:19 +02004251
tierno588547c2020-07-01 15:30:20 +00004252 # wait for pending tasks of terminate primitives
4253 if tasks_dict_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01004254 self.logger.debug(
4255 logging_text
4256 + "Waiting for tasks {}".format(list(tasks_dict_info.keys()))
4257 )
4258 error_list = await self._wait_for_tasks(
4259 logging_text,
4260 tasks_dict_info,
4261 min(self.timeout_charm_delete, timeout_ns_terminate),
4262 stage,
4263 nslcmop_id,
4264 )
tierno86e33612020-09-16 14:13:06 +00004265 tasks_dict_info.clear()
tierno588547c2020-07-01 15:30:20 +00004266 if error_list:
garciadeblas5697b8b2021-03-24 09:17:02 +01004267 return # raise LcmException("; ".join(error_list))
tierno82974b22018-11-27 21:55:36 +00004268
tiernoe876f672020-02-13 14:34:48 +00004269 # remove All execution environments at once
4270 stage[0] = "Stage 3/3 delete all."
quilesj3655ae02019-12-12 16:08:35 +00004271
tierno49676be2020-04-07 16:34:35 +00004272 if nsr_deployed.get("VCA"):
4273 stage[1] = "Deleting all execution environments."
4274 self.logger.debug(logging_text + stage[1])
David Garciac1fe90a2021-03-31 19:12:02 +02004275 vca_id = self.get_vca_id({}, db_nsr)
4276 task_delete_ee = asyncio.ensure_future(
4277 asyncio.wait_for(
4278 self._delete_all_N2VC(db_nsr=db_nsr, vca_id=vca_id),
garciadeblas5697b8b2021-03-24 09:17:02 +01004279 timeout=self.timeout_charm_delete,
David Garciac1fe90a2021-03-31 19:12:02 +02004280 )
4281 )
tierno49676be2020-04-07 16:34:35 +00004282 # task_delete_ee = asyncio.ensure_future(self.n2vc.delete_namespace(namespace="." + nsr_id))
4283 tasks_dict_info[task_delete_ee] = "Terminating all VCA"
tierno59d22d22018-09-25 18:10:19 +02004284
tiernoe876f672020-02-13 14:34:48 +00004285 # Delete from k8scluster
4286 stage[1] = "Deleting KDUs."
4287 self.logger.debug(logging_text + stage[1])
4288 # print(nsr_deployed)
4289 for kdu in get_iterable(nsr_deployed, "K8s"):
4290 if not kdu or not kdu.get("kdu-instance"):
4291 continue
4292 kdu_instance = kdu.get("kdu-instance")
tiernoa2143262020-03-27 16:20:40 +00004293 if kdu.get("k8scluster-type") in self.k8scluster_map:
David Garciac1fe90a2021-03-31 19:12:02 +02004294 # TODO: Uninstall kdu instances taking into account they could be deployed in different VIMs
4295 vca_id = self.get_vca_id({}, db_nsr)
tiernoe876f672020-02-13 14:34:48 +00004296 task_delete_kdu_instance = asyncio.ensure_future(
tiernoa2143262020-03-27 16:20:40 +00004297 self.k8scluster_map[kdu["k8scluster-type"]].uninstall(
4298 cluster_uuid=kdu.get("k8scluster-uuid"),
David Garciac1fe90a2021-03-31 19:12:02 +02004299 kdu_instance=kdu_instance,
4300 vca_id=vca_id,
4301 )
4302 )
tiernoe876f672020-02-13 14:34:48 +00004303 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004304 self.logger.error(
4305 logging_text
4306 + "Unknown k8s deployment type {}".format(
4307 kdu.get("k8scluster-type")
4308 )
4309 )
tiernoe876f672020-02-13 14:34:48 +00004310 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01004311 tasks_dict_info[
4312 task_delete_kdu_instance
4313 ] = "Terminating KDU '{}'".format(kdu.get("kdu-name"))
tierno59d22d22018-09-25 18:10:19 +02004314
4315 # remove from RO
tiernoe876f672020-02-13 14:34:48 +00004316 stage[1] = "Deleting ns from VIM."
tierno69f0d382020-05-07 13:08:09 +00004317 if self.ng_ro:
4318 task_delete_ro = asyncio.ensure_future(
garciadeblas5697b8b2021-03-24 09:17:02 +01004319 self._terminate_ng_ro(
4320 logging_text, nsr_deployed, nsr_id, nslcmop_id, stage
4321 )
4322 )
tierno69f0d382020-05-07 13:08:09 +00004323 else:
4324 task_delete_ro = asyncio.ensure_future(
garciadeblas5697b8b2021-03-24 09:17:02 +01004325 self._terminate_RO(
4326 logging_text, nsr_deployed, nsr_id, nslcmop_id, stage
4327 )
4328 )
tiernoe876f672020-02-13 14:34:48 +00004329 tasks_dict_info[task_delete_ro] = "Removing deployment from VIM"
tierno59d22d22018-09-25 18:10:19 +02004330
tiernoe876f672020-02-13 14:34:48 +00004331 # rest of staff will be done at finally
4332
garciadeblas5697b8b2021-03-24 09:17:02 +01004333 except (
4334 ROclient.ROClientException,
4335 DbException,
4336 LcmException,
4337 N2VCException,
4338 ) as e:
tiernoe876f672020-02-13 14:34:48 +00004339 self.logger.error(logging_text + "Exit Exception {}".format(e))
4340 exc = e
4341 except asyncio.CancelledError:
garciadeblas5697b8b2021-03-24 09:17:02 +01004342 self.logger.error(
4343 logging_text + "Cancelled Exception while '{}'".format(stage[1])
4344 )
tiernoe876f672020-02-13 14:34:48 +00004345 exc = "Operation was cancelled"
4346 except Exception as e:
4347 exc = traceback.format_exc()
garciadeblas5697b8b2021-03-24 09:17:02 +01004348 self.logger.critical(
4349 logging_text + "Exit Exception while '{}': {}".format(stage[1], e),
4350 exc_info=True,
4351 )
tiernoe876f672020-02-13 14:34:48 +00004352 finally:
4353 if exc:
4354 error_list.append(str(exc))
tierno59d22d22018-09-25 18:10:19 +02004355 try:
tiernoe876f672020-02-13 14:34:48 +00004356 # wait for pending tasks
4357 if tasks_dict_info:
4358 stage[1] = "Waiting for terminate pending tasks."
4359 self.logger.debug(logging_text + stage[1])
garciadeblas5697b8b2021-03-24 09:17:02 +01004360 error_list += await self._wait_for_tasks(
4361 logging_text,
4362 tasks_dict_info,
4363 timeout_ns_terminate,
4364 stage,
4365 nslcmop_id,
4366 )
tiernoe876f672020-02-13 14:34:48 +00004367 stage[1] = stage[2] = ""
4368 except asyncio.CancelledError:
4369 error_list.append("Cancelled")
4370 # TODO cancell all tasks
4371 except Exception as exc:
4372 error_list.append(str(exc))
4373 # update status at database
4374 if error_list:
4375 error_detail = "; ".join(error_list)
4376 # self.logger.error(logging_text + error_detail)
garciadeblas5697b8b2021-03-24 09:17:02 +01004377 error_description_nslcmop = "{} Detail: {}".format(
4378 stage[0], error_detail
4379 )
4380 error_description_nsr = "Operation: TERMINATING.{}, {}.".format(
4381 nslcmop_id, stage[0]
4382 )
tierno59d22d22018-09-25 18:10:19 +02004383
tierno59d22d22018-09-25 18:10:19 +02004384 db_nsr_update["operational-status"] = "failed"
garciadeblas5697b8b2021-03-24 09:17:02 +01004385 db_nsr_update["detailed-status"] = (
4386 error_description_nsr + " Detail: " + error_detail
4387 )
tiernoe876f672020-02-13 14:34:48 +00004388 db_nslcmop_update["detailed-status"] = error_detail
4389 nslcmop_operation_state = "FAILED"
4390 ns_state = "BROKEN"
tierno59d22d22018-09-25 18:10:19 +02004391 else:
tiernoa2143262020-03-27 16:20:40 +00004392 error_detail = None
tiernoe876f672020-02-13 14:34:48 +00004393 error_description_nsr = error_description_nslcmop = None
4394 ns_state = "NOT_INSTANTIATED"
tierno59d22d22018-09-25 18:10:19 +02004395 db_nsr_update["operational-status"] = "terminated"
4396 db_nsr_update["detailed-status"] = "Done"
4397 db_nsr_update["_admin.nsState"] = "NOT_INSTANTIATED"
4398 db_nslcmop_update["detailed-status"] = "Done"
tiernoe876f672020-02-13 14:34:48 +00004399 nslcmop_operation_state = "COMPLETED"
tierno59d22d22018-09-25 18:10:19 +02004400
tiernoe876f672020-02-13 14:34:48 +00004401 if db_nsr:
4402 self._write_ns_status(
4403 nsr_id=nsr_id,
4404 ns_state=ns_state,
4405 current_operation="IDLE",
4406 current_operation_id=None,
4407 error_description=error_description_nsr,
tiernoa2143262020-03-27 16:20:40 +00004408 error_detail=error_detail,
garciadeblas5697b8b2021-03-24 09:17:02 +01004409 other_update=db_nsr_update,
tiernoe876f672020-02-13 14:34:48 +00004410 )
tiernoa17d4f42020-04-28 09:59:23 +00004411 self._write_op_status(
4412 op_id=nslcmop_id,
4413 stage="",
4414 error_message=error_description_nslcmop,
4415 operation_state=nslcmop_operation_state,
4416 other_update=db_nslcmop_update,
4417 )
lloretgalleg6d488782020-07-22 10:13:46 +00004418 if ns_state == "NOT_INSTANTIATED":
4419 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01004420 self.db.set_list(
4421 "vnfrs",
4422 {"nsr-id-ref": nsr_id},
4423 {"_admin.nsState": "NOT_INSTANTIATED"},
4424 )
lloretgalleg6d488782020-07-22 10:13:46 +00004425 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01004426 self.logger.warn(
4427 logging_text
4428 + "Error writing VNFR status for nsr-id-ref: {} -> {}".format(
4429 nsr_id, e
4430 )
4431 )
tiernoa17d4f42020-04-28 09:59:23 +00004432 if operation_params:
tiernoe876f672020-02-13 14:34:48 +00004433 autoremove = operation_params.get("autoremove", False)
tierno59d22d22018-09-25 18:10:19 +02004434 if nslcmop_operation_state:
4435 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01004436 await self.msg.aiowrite(
4437 "ns",
4438 "terminated",
4439 {
4440 "nsr_id": nsr_id,
4441 "nslcmop_id": nslcmop_id,
4442 "operationState": nslcmop_operation_state,
4443 "autoremove": autoremove,
4444 },
4445 loop=self.loop,
4446 )
tierno59d22d22018-09-25 18:10:19 +02004447 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01004448 self.logger.error(
4449 logging_text + "kafka_write notification Exception {}".format(e)
4450 )
quilesj7e13aeb2019-10-08 13:34:55 +02004451
tierno59d22d22018-09-25 18:10:19 +02004452 self.logger.debug(logging_text + "Exit")
4453 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_terminate")
4454
garciadeblas5697b8b2021-03-24 09:17:02 +01004455 async def _wait_for_tasks(
4456 self, logging_text, created_tasks_info, timeout, stage, nslcmop_id, nsr_id=None
4457 ):
tiernoe876f672020-02-13 14:34:48 +00004458 time_start = time()
tiernoa2143262020-03-27 16:20:40 +00004459 error_detail_list = []
tiernoe876f672020-02-13 14:34:48 +00004460 error_list = []
4461 pending_tasks = list(created_tasks_info.keys())
4462 num_tasks = len(pending_tasks)
4463 num_done = 0
4464 stage[1] = "{}/{}.".format(num_done, num_tasks)
4465 self._write_op_status(nslcmop_id, stage)
tiernoe876f672020-02-13 14:34:48 +00004466 while pending_tasks:
tiernoa2143262020-03-27 16:20:40 +00004467 new_error = None
tiernoe876f672020-02-13 14:34:48 +00004468 _timeout = timeout + time_start - time()
garciadeblas5697b8b2021-03-24 09:17:02 +01004469 done, pending_tasks = await asyncio.wait(
4470 pending_tasks, timeout=_timeout, return_when=asyncio.FIRST_COMPLETED
4471 )
tiernoe876f672020-02-13 14:34:48 +00004472 num_done += len(done)
garciadeblas5697b8b2021-03-24 09:17:02 +01004473 if not done: # Timeout
tiernoe876f672020-02-13 14:34:48 +00004474 for task in pending_tasks:
tiernoa2143262020-03-27 16:20:40 +00004475 new_error = created_tasks_info[task] + ": Timeout"
4476 error_detail_list.append(new_error)
4477 error_list.append(new_error)
tiernoe876f672020-02-13 14:34:48 +00004478 break
4479 for task in done:
4480 if task.cancelled():
tierno067e04a2020-03-31 12:53:13 +00004481 exc = "Cancelled"
tiernoe876f672020-02-13 14:34:48 +00004482 else:
4483 exc = task.exception()
tierno067e04a2020-03-31 12:53:13 +00004484 if exc:
4485 if isinstance(exc, asyncio.TimeoutError):
4486 exc = "Timeout"
4487 new_error = created_tasks_info[task] + ": {}".format(exc)
4488 error_list.append(created_tasks_info[task])
4489 error_detail_list.append(new_error)
garciadeblas5697b8b2021-03-24 09:17:02 +01004490 if isinstance(
4491 exc,
4492 (
4493 str,
4494 DbException,
4495 N2VCException,
4496 ROclient.ROClientException,
4497 LcmException,
4498 K8sException,
4499 NgRoException,
4500 ),
4501 ):
tierno067e04a2020-03-31 12:53:13 +00004502 self.logger.error(logging_text + new_error)
tiernoe876f672020-02-13 14:34:48 +00004503 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004504 exc_traceback = "".join(
4505 traceback.format_exception(None, exc, exc.__traceback__)
4506 )
4507 self.logger.error(
4508 logging_text
4509 + created_tasks_info[task]
4510 + " "
4511 + exc_traceback
4512 )
tierno067e04a2020-03-31 12:53:13 +00004513 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004514 self.logger.debug(
4515 logging_text + created_tasks_info[task] + ": Done"
4516 )
tiernoe876f672020-02-13 14:34:48 +00004517 stage[1] = "{}/{}.".format(num_done, num_tasks)
4518 if new_error:
tiernoa2143262020-03-27 16:20:40 +00004519 stage[1] += " Errors: " + ". ".join(error_detail_list) + "."
tiernoe876f672020-02-13 14:34:48 +00004520 if nsr_id: # update also nsr
garciadeblas5697b8b2021-03-24 09:17:02 +01004521 self.update_db_2(
4522 "nsrs",
4523 nsr_id,
4524 {
4525 "errorDescription": "Error at: " + ", ".join(error_list),
4526 "errorDetail": ". ".join(error_detail_list),
4527 },
4528 )
tiernoe876f672020-02-13 14:34:48 +00004529 self._write_op_status(nslcmop_id, stage)
tiernoa2143262020-03-27 16:20:40 +00004530 return error_detail_list
tiernoe876f672020-02-13 14:34:48 +00004531
tiernoda1ff8c2020-10-22 14:12:46 +00004532 @staticmethod
4533 def _map_primitive_params(primitive_desc, params, instantiation_params):
tiernoda964822019-01-14 15:53:47 +00004534 """
4535 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
4536 The default-value is used. If it is between < > it look for a value at instantiation_params
4537 :param primitive_desc: portion of VNFD/NSD that describes primitive
4538 :param params: Params provided by user
4539 :param instantiation_params: Instantiation params provided by user
4540 :return: a dictionary with the calculated params
4541 """
4542 calculated_params = {}
4543 for parameter in primitive_desc.get("parameter", ()):
4544 param_name = parameter["name"]
4545 if param_name in params:
4546 calculated_params[param_name] = params[param_name]
tierno98ad6ea2019-05-30 17:16:28 +00004547 elif "default-value" in parameter or "value" in parameter:
4548 if "value" in parameter:
4549 calculated_params[param_name] = parameter["value"]
4550 else:
4551 calculated_params[param_name] = parameter["default-value"]
garciadeblas5697b8b2021-03-24 09:17:02 +01004552 if (
4553 isinstance(calculated_params[param_name], str)
4554 and calculated_params[param_name].startswith("<")
4555 and calculated_params[param_name].endswith(">")
4556 ):
tierno98ad6ea2019-05-30 17:16:28 +00004557 if calculated_params[param_name][1:-1] in instantiation_params:
garciadeblas5697b8b2021-03-24 09:17:02 +01004558 calculated_params[param_name] = instantiation_params[
4559 calculated_params[param_name][1:-1]
4560 ]
tiernoda964822019-01-14 15:53:47 +00004561 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004562 raise LcmException(
4563 "Parameter {} needed to execute primitive {} not provided".format(
4564 calculated_params[param_name], primitive_desc["name"]
4565 )
4566 )
tiernoda964822019-01-14 15:53:47 +00004567 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004568 raise LcmException(
4569 "Parameter {} needed to execute primitive {} not provided".format(
4570 param_name, primitive_desc["name"]
4571 )
4572 )
tierno59d22d22018-09-25 18:10:19 +02004573
tiernoda964822019-01-14 15:53:47 +00004574 if isinstance(calculated_params[param_name], (dict, list, tuple)):
garciadeblas5697b8b2021-03-24 09:17:02 +01004575 calculated_params[param_name] = yaml.safe_dump(
4576 calculated_params[param_name], default_flow_style=True, width=256
4577 )
4578 elif isinstance(calculated_params[param_name], str) and calculated_params[
4579 param_name
4580 ].startswith("!!yaml "):
tiernoda964822019-01-14 15:53:47 +00004581 calculated_params[param_name] = calculated_params[param_name][7:]
tiernofa40e692020-10-14 14:59:36 +00004582 if parameter.get("data-type") == "INTEGER":
4583 try:
4584 calculated_params[param_name] = int(calculated_params[param_name])
4585 except ValueError: # error converting string to int
4586 raise LcmException(
garciadeblas5697b8b2021-03-24 09:17:02 +01004587 "Parameter {} of primitive {} must be integer".format(
4588 param_name, primitive_desc["name"]
4589 )
4590 )
tiernofa40e692020-10-14 14:59:36 +00004591 elif parameter.get("data-type") == "BOOLEAN":
garciadeblas5697b8b2021-03-24 09:17:02 +01004592 calculated_params[param_name] = not (
4593 (str(calculated_params[param_name])).lower() == "false"
4594 )
tiernoc3f2a822019-11-05 13:45:04 +00004595
4596 # add always ns_config_info if primitive name is config
4597 if primitive_desc["name"] == "config":
4598 if "ns_config_info" in instantiation_params:
garciadeblas5697b8b2021-03-24 09:17:02 +01004599 calculated_params["ns_config_info"] = instantiation_params[
4600 "ns_config_info"
4601 ]
tiernoda964822019-01-14 15:53:47 +00004602 return calculated_params
4603
garciadeblas5697b8b2021-03-24 09:17:02 +01004604 def _look_for_deployed_vca(
4605 self,
4606 deployed_vca,
4607 member_vnf_index,
4608 vdu_id,
4609 vdu_count_index,
4610 kdu_name=None,
4611 ee_descriptor_id=None,
4612 ):
tiernoe876f672020-02-13 14:34:48 +00004613 # find vca_deployed record for this action. Raise LcmException if not found or there is not any id.
4614 for vca in deployed_vca:
4615 if not vca:
4616 continue
4617 if member_vnf_index != vca["member-vnf-index"] or vdu_id != vca["vdu_id"]:
4618 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01004619 if (
4620 vdu_count_index is not None
4621 and vdu_count_index != vca["vdu_count_index"]
4622 ):
tiernoe876f672020-02-13 14:34:48 +00004623 continue
4624 if kdu_name and kdu_name != vca["kdu_name"]:
4625 continue
tiernoa278b842020-07-08 15:33:55 +00004626 if ee_descriptor_id and ee_descriptor_id != vca["ee_descriptor_id"]:
4627 continue
tiernoe876f672020-02-13 14:34:48 +00004628 break
4629 else:
4630 # vca_deployed not found
garciadeblas5697b8b2021-03-24 09:17:02 +01004631 raise LcmException(
4632 "charm for member_vnf_index={} vdu_id={}.{} kdu_name={} execution-environment-list.id={}"
4633 " is not deployed".format(
4634 member_vnf_index,
4635 vdu_id,
4636 vdu_count_index,
4637 kdu_name,
4638 ee_descriptor_id,
4639 )
4640 )
tiernoe876f672020-02-13 14:34:48 +00004641 # get ee_id
4642 ee_id = vca.get("ee_id")
garciadeblas5697b8b2021-03-24 09:17:02 +01004643 vca_type = vca.get(
4644 "type", "lxc_proxy_charm"
4645 ) # default value for backward compatibility - proxy charm
tiernoe876f672020-02-13 14:34:48 +00004646 if not ee_id:
garciadeblas5697b8b2021-03-24 09:17:02 +01004647 raise LcmException(
4648 "charm for member_vnf_index={} vdu_id={} kdu_name={} vdu_count_index={} has not "
4649 "execution environment".format(
4650 member_vnf_index, vdu_id, kdu_name, vdu_count_index
4651 )
4652 )
tierno588547c2020-07-01 15:30:20 +00004653 return ee_id, vca_type
tiernoe876f672020-02-13 14:34:48 +00004654
David Garciac1fe90a2021-03-31 19:12:02 +02004655 async def _ns_execute_primitive(
4656 self,
4657 ee_id,
4658 primitive,
4659 primitive_params,
4660 retries=0,
4661 retries_interval=30,
4662 timeout=None,
4663 vca_type=None,
4664 db_dict=None,
4665 vca_id: str = None,
4666 ) -> (str, str):
tiernoda964822019-01-14 15:53:47 +00004667 try:
tierno98ad6ea2019-05-30 17:16:28 +00004668 if primitive == "config":
4669 primitive_params = {"params": primitive_params}
tierno2fc7ce52019-06-11 22:50:01 +00004670
tierno588547c2020-07-01 15:30:20 +00004671 vca_type = vca_type or "lxc_proxy_charm"
4672
quilesj7e13aeb2019-10-08 13:34:55 +02004673 while retries >= 0:
4674 try:
tierno067e04a2020-03-31 12:53:13 +00004675 output = await asyncio.wait_for(
tierno588547c2020-07-01 15:30:20 +00004676 self.vca_map[vca_type].exec_primitive(
tierno067e04a2020-03-31 12:53:13 +00004677 ee_id=ee_id,
4678 primitive_name=primitive,
4679 params_dict=primitive_params,
4680 progress_timeout=self.timeout_progress_primitive,
tierno588547c2020-07-01 15:30:20 +00004681 total_timeout=self.timeout_primitive,
David Garciac1fe90a2021-03-31 19:12:02 +02004682 db_dict=db_dict,
4683 vca_id=vca_id,
aktas98488ed2021-07-29 17:42:49 +03004684 vca_type=vca_type,
David Garciac1fe90a2021-03-31 19:12:02 +02004685 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01004686 timeout=timeout or self.timeout_primitive,
4687 )
quilesj7e13aeb2019-10-08 13:34:55 +02004688 # execution was OK
4689 break
tierno067e04a2020-03-31 12:53:13 +00004690 except asyncio.CancelledError:
4691 raise
4692 except Exception as e: # asyncio.TimeoutError
4693 if isinstance(e, asyncio.TimeoutError):
4694 e = "Timeout"
quilesj7e13aeb2019-10-08 13:34:55 +02004695 retries -= 1
4696 if retries >= 0:
garciadeblas5697b8b2021-03-24 09:17:02 +01004697 self.logger.debug(
4698 "Error executing action {} on {} -> {}".format(
4699 primitive, ee_id, e
4700 )
4701 )
quilesj7e13aeb2019-10-08 13:34:55 +02004702 # wait and retry
4703 await asyncio.sleep(retries_interval, loop=self.loop)
tierno73d8bd02019-11-18 17:33:27 +00004704 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004705 return "FAILED", str(e)
quilesj7e13aeb2019-10-08 13:34:55 +02004706
garciadeblas5697b8b2021-03-24 09:17:02 +01004707 return "COMPLETED", output
quilesj7e13aeb2019-10-08 13:34:55 +02004708
tierno067e04a2020-03-31 12:53:13 +00004709 except (LcmException, asyncio.CancelledError):
tiernoe876f672020-02-13 14:34:48 +00004710 raise
quilesj7e13aeb2019-10-08 13:34:55 +02004711 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01004712 return "FAIL", "Error executing action {}: {}".format(primitive, e)
tierno59d22d22018-09-25 18:10:19 +02004713
ksaikiranr3fde2c72021-03-15 10:39:06 +05304714 async def vca_status_refresh(self, nsr_id, nslcmop_id):
4715 """
4716 Updating the vca_status with latest juju information in nsrs record
4717 :param: nsr_id: Id of the nsr
4718 :param: nslcmop_id: Id of the nslcmop
4719 :return: None
4720 """
4721
4722 self.logger.debug("Task ns={} action={} Enter".format(nsr_id, nslcmop_id))
4723 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
David Garciac1fe90a2021-03-31 19:12:02 +02004724 vca_id = self.get_vca_id({}, db_nsr)
garciadeblas5697b8b2021-03-24 09:17:02 +01004725 if db_nsr["_admin"]["deployed"]["K8s"]:
4726 for k8s_index, k8s in enumerate(db_nsr["_admin"]["deployed"]["K8s"]):
ksaikiranr656b6dd2021-02-19 10:25:18 +05304727 cluster_uuid, kdu_instance = k8s["k8scluster-uuid"], k8s["kdu-instance"]
garciadeblas5697b8b2021-03-24 09:17:02 +01004728 await self._on_update_k8s_db(
4729 cluster_uuid, kdu_instance, filter={"_id": nsr_id}, vca_id=vca_id
4730 )
ksaikiranr656b6dd2021-02-19 10:25:18 +05304731 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004732 for vca_index, _ in enumerate(db_nsr["_admin"]["deployed"]["VCA"]):
ksaikiranr656b6dd2021-02-19 10:25:18 +05304733 table, filter = "nsrs", {"_id": nsr_id}
4734 path = "_admin.deployed.VCA.{}.".format(vca_index)
4735 await self._on_update_n2vc_db(table, filter, path, {})
ksaikiranr3fde2c72021-03-15 10:39:06 +05304736
4737 self.logger.debug("Task ns={} action={} Exit".format(nsr_id, nslcmop_id))
4738 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_vca_status_refresh")
4739
tierno59d22d22018-09-25 18:10:19 +02004740 async def action(self, nsr_id, nslcmop_id):
kuused124bfe2019-06-18 12:09:24 +02004741 # Try to lock HA task here
garciadeblas5697b8b2021-03-24 09:17:02 +01004742 task_is_locked_by_me = self.lcm_tasks.lock_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02004743 if not task_is_locked_by_me:
4744 return
4745
tierno59d22d22018-09-25 18:10:19 +02004746 logging_text = "Task ns={} action={} ".format(nsr_id, nslcmop_id)
4747 self.logger.debug(logging_text + "Enter")
4748 # get all needed from database
4749 db_nsr = None
4750 db_nslcmop = None
tiernoe876f672020-02-13 14:34:48 +00004751 db_nsr_update = {}
tierno59d22d22018-09-25 18:10:19 +02004752 db_nslcmop_update = {}
4753 nslcmop_operation_state = None
tierno067e04a2020-03-31 12:53:13 +00004754 error_description_nslcmop = None
tierno59d22d22018-09-25 18:10:19 +02004755 exc = None
4756 try:
kuused124bfe2019-06-18 12:09:24 +02004757 # wait for any previous tasks in process
tierno3cf81a32019-11-11 17:07:00 +00004758 step = "Waiting for previous operations to terminate"
garciadeblas5697b8b2021-03-24 09:17:02 +01004759 await self.lcm_tasks.waitfor_related_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02004760
quilesj4cda56b2019-12-05 10:02:20 +00004761 self._write_ns_status(
4762 nsr_id=nsr_id,
4763 ns_state=None,
4764 current_operation="RUNNING ACTION",
garciadeblas5697b8b2021-03-24 09:17:02 +01004765 current_operation_id=nslcmop_id,
quilesj4cda56b2019-12-05 10:02:20 +00004766 )
4767
tierno59d22d22018-09-25 18:10:19 +02004768 step = "Getting information from database"
4769 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
4770 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
tiernoda964822019-01-14 15:53:47 +00004771
tiernoe4f7e6c2018-11-27 14:55:30 +00004772 nsr_deployed = db_nsr["_admin"].get("deployed")
tierno1b633412019-02-25 16:48:23 +00004773 vnf_index = db_nslcmop["operationParams"].get("member_vnf_index")
tierno59d22d22018-09-25 18:10:19 +02004774 vdu_id = db_nslcmop["operationParams"].get("vdu_id")
calvinosanch9f9c6f22019-11-04 13:37:39 +01004775 kdu_name = db_nslcmop["operationParams"].get("kdu_name")
tiernoe4f7e6c2018-11-27 14:55:30 +00004776 vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
tierno067e04a2020-03-31 12:53:13 +00004777 primitive = db_nslcmop["operationParams"]["primitive"]
4778 primitive_params = db_nslcmop["operationParams"]["primitive_params"]
garciadeblas5697b8b2021-03-24 09:17:02 +01004779 timeout_ns_action = db_nslcmop["operationParams"].get(
4780 "timeout_ns_action", self.timeout_primitive
4781 )
tierno59d22d22018-09-25 18:10:19 +02004782
tierno1b633412019-02-25 16:48:23 +00004783 if vnf_index:
4784 step = "Getting vnfr from database"
garciadeblas5697b8b2021-03-24 09:17:02 +01004785 db_vnfr = self.db.get_one(
4786 "vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id}
4787 )
tierno1b633412019-02-25 16:48:23 +00004788 step = "Getting vnfd from database"
4789 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
4790 else:
tierno067e04a2020-03-31 12:53:13 +00004791 step = "Getting nsd from database"
4792 db_nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
tiernoda964822019-01-14 15:53:47 +00004793
David Garciac1fe90a2021-03-31 19:12:02 +02004794 vca_id = self.get_vca_id(db_vnfr, db_nsr)
tierno82974b22018-11-27 21:55:36 +00004795 # for backward compatibility
4796 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
4797 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
4798 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
4799 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4800
tiernoda964822019-01-14 15:53:47 +00004801 # look for primitive
tiernoa278b842020-07-08 15:33:55 +00004802 config_primitive_desc = descriptor_configuration = None
tiernoda964822019-01-14 15:53:47 +00004803 if vdu_id:
bravofe5a31bc2021-02-17 19:09:12 -03004804 descriptor_configuration = get_configuration(db_vnfd, vdu_id)
calvinosanch9f9c6f22019-11-04 13:37:39 +01004805 elif kdu_name:
bravofe5a31bc2021-02-17 19:09:12 -03004806 descriptor_configuration = get_configuration(db_vnfd, kdu_name)
tierno1b633412019-02-25 16:48:23 +00004807 elif vnf_index:
bravofe5a31bc2021-02-17 19:09:12 -03004808 descriptor_configuration = get_configuration(db_vnfd, db_vnfd["id"])
tierno1b633412019-02-25 16:48:23 +00004809 else:
tiernoa278b842020-07-08 15:33:55 +00004810 descriptor_configuration = db_nsd.get("ns-configuration")
4811
garciadeblas5697b8b2021-03-24 09:17:02 +01004812 if descriptor_configuration and descriptor_configuration.get(
4813 "config-primitive"
4814 ):
tiernoa278b842020-07-08 15:33:55 +00004815 for config_primitive in descriptor_configuration["config-primitive"]:
tierno1b633412019-02-25 16:48:23 +00004816 if config_primitive["name"] == primitive:
4817 config_primitive_desc = config_primitive
4818 break
tiernoda964822019-01-14 15:53:47 +00004819
garciadeblas6bed6b32020-07-20 11:05:42 +00004820 if not config_primitive_desc:
4821 if not (kdu_name and primitive in ("upgrade", "rollback", "status")):
garciadeblas5697b8b2021-03-24 09:17:02 +01004822 raise LcmException(
4823 "Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".format(
4824 primitive
4825 )
4826 )
garciadeblas6bed6b32020-07-20 11:05:42 +00004827 primitive_name = primitive
4828 ee_descriptor_id = None
4829 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004830 primitive_name = config_primitive_desc.get(
4831 "execution-environment-primitive", primitive
4832 )
4833 ee_descriptor_id = config_primitive_desc.get(
4834 "execution-environment-ref"
4835 )
tierno1b633412019-02-25 16:48:23 +00004836
tierno1b633412019-02-25 16:48:23 +00004837 if vnf_index:
tierno626e0152019-11-29 14:16:16 +00004838 if vdu_id:
garciadeblas5697b8b2021-03-24 09:17:02 +01004839 vdur = next(
4840 (x for x in db_vnfr["vdur"] if x["vdu-id-ref"] == vdu_id), None
4841 )
bravof922c4172020-11-24 21:21:43 -03004842 desc_params = parse_yaml_strings(vdur.get("additionalParams"))
tierno067e04a2020-03-31 12:53:13 +00004843 elif kdu_name:
garciadeblas5697b8b2021-03-24 09:17:02 +01004844 kdur = next(
4845 (x for x in db_vnfr["kdur"] if x["kdu-name"] == kdu_name), None
4846 )
bravof922c4172020-11-24 21:21:43 -03004847 desc_params = parse_yaml_strings(kdur.get("additionalParams"))
tierno067e04a2020-03-31 12:53:13 +00004848 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004849 desc_params = parse_yaml_strings(
4850 db_vnfr.get("additionalParamsForVnf")
4851 )
tierno1b633412019-02-25 16:48:23 +00004852 else:
bravof922c4172020-11-24 21:21:43 -03004853 desc_params = parse_yaml_strings(db_nsr.get("additionalParamsForNs"))
bravofe5a31bc2021-02-17 19:09:12 -03004854 if kdu_name and get_configuration(db_vnfd, kdu_name):
4855 kdu_configuration = get_configuration(db_vnfd, kdu_name)
David Garciad41dbd62020-12-10 12:52:52 +01004856 actions = set()
David Garciaa1003662021-02-16 21:07:58 +01004857 for primitive in kdu_configuration.get("initial-config-primitive", []):
David Garciad41dbd62020-12-10 12:52:52 +01004858 actions.add(primitive["name"])
David Garciaa1003662021-02-16 21:07:58 +01004859 for primitive in kdu_configuration.get("config-primitive", []):
David Garciad41dbd62020-12-10 12:52:52 +01004860 actions.add(primitive["name"])
4861 kdu_action = True if primitive_name in actions else False
Dominik Fleischmann771c32b2020-04-07 12:39:36 +02004862
tiernoda964822019-01-14 15:53:47 +00004863 # TODO check if ns is in a proper status
garciadeblas5697b8b2021-03-24 09:17:02 +01004864 if kdu_name and (
4865 primitive_name in ("upgrade", "rollback", "status") or kdu_action
4866 ):
tierno067e04a2020-03-31 12:53:13 +00004867 # kdur and desc_params already set from before
4868 if primitive_params:
4869 desc_params.update(primitive_params)
4870 # TODO Check if we will need something at vnf level
4871 for index, kdu in enumerate(get_iterable(nsr_deployed, "K8s")):
garciadeblas5697b8b2021-03-24 09:17:02 +01004872 if (
4873 kdu_name == kdu["kdu-name"]
4874 and kdu["member-vnf-index"] == vnf_index
4875 ):
tierno067e04a2020-03-31 12:53:13 +00004876 break
4877 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004878 raise LcmException(
4879 "KDU '{}' for vnf '{}' not deployed".format(kdu_name, vnf_index)
4880 )
quilesj7e13aeb2019-10-08 13:34:55 +02004881
tierno067e04a2020-03-31 12:53:13 +00004882 if kdu.get("k8scluster-type") not in self.k8scluster_map:
garciadeblas5697b8b2021-03-24 09:17:02 +01004883 msg = "unknown k8scluster-type '{}'".format(
4884 kdu.get("k8scluster-type")
4885 )
tierno067e04a2020-03-31 12:53:13 +00004886 raise LcmException(msg)
4887
garciadeblas5697b8b2021-03-24 09:17:02 +01004888 db_dict = {
4889 "collection": "nsrs",
4890 "filter": {"_id": nsr_id},
4891 "path": "_admin.deployed.K8s.{}".format(index),
4892 }
4893 self.logger.debug(
4894 logging_text
4895 + "Exec k8s {} on {}.{}".format(primitive_name, vnf_index, kdu_name)
4896 )
tiernoa278b842020-07-08 15:33:55 +00004897 step = "Executing kdu {}".format(primitive_name)
4898 if primitive_name == "upgrade":
tierno067e04a2020-03-31 12:53:13 +00004899 if desc_params.get("kdu_model"):
4900 kdu_model = desc_params.get("kdu_model")
4901 del desc_params["kdu_model"]
4902 else:
4903 kdu_model = kdu.get("kdu-model")
4904 parts = kdu_model.split(sep=":")
4905 if len(parts) == 2:
4906 kdu_model = parts[0]
4907
4908 detailed_status = await asyncio.wait_for(
4909 self.k8scluster_map[kdu["k8scluster-type"]].upgrade(
4910 cluster_uuid=kdu.get("k8scluster-uuid"),
4911 kdu_instance=kdu.get("kdu-instance"),
garciadeblas5697b8b2021-03-24 09:17:02 +01004912 atomic=True,
4913 kdu_model=kdu_model,
4914 params=desc_params,
4915 db_dict=db_dict,
4916 timeout=timeout_ns_action,
4917 ),
4918 timeout=timeout_ns_action + 10,
4919 )
4920 self.logger.debug(
4921 logging_text + " Upgrade of kdu {} done".format(detailed_status)
4922 )
tiernoa278b842020-07-08 15:33:55 +00004923 elif primitive_name == "rollback":
tierno067e04a2020-03-31 12:53:13 +00004924 detailed_status = await asyncio.wait_for(
4925 self.k8scluster_map[kdu["k8scluster-type"]].rollback(
4926 cluster_uuid=kdu.get("k8scluster-uuid"),
4927 kdu_instance=kdu.get("kdu-instance"),
garciadeblas5697b8b2021-03-24 09:17:02 +01004928 db_dict=db_dict,
4929 ),
4930 timeout=timeout_ns_action,
4931 )
tiernoa278b842020-07-08 15:33:55 +00004932 elif primitive_name == "status":
tierno067e04a2020-03-31 12:53:13 +00004933 detailed_status = await asyncio.wait_for(
4934 self.k8scluster_map[kdu["k8scluster-type"]].status_kdu(
4935 cluster_uuid=kdu.get("k8scluster-uuid"),
David Garciac1fe90a2021-03-31 19:12:02 +02004936 kdu_instance=kdu.get("kdu-instance"),
4937 vca_id=vca_id,
4938 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01004939 timeout=timeout_ns_action,
David Garciac1fe90a2021-03-31 19:12:02 +02004940 )
Dominik Fleischmann771c32b2020-04-07 12:39:36 +02004941 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004942 kdu_instance = kdu.get("kdu-instance") or "{}-{}".format(
4943 kdu["kdu-name"], nsr_id
4944 )
4945 params = self._map_primitive_params(
4946 config_primitive_desc, primitive_params, desc_params
4947 )
Dominik Fleischmann771c32b2020-04-07 12:39:36 +02004948
4949 detailed_status = await asyncio.wait_for(
4950 self.k8scluster_map[kdu["k8scluster-type"]].exec_primitive(
4951 cluster_uuid=kdu.get("k8scluster-uuid"),
4952 kdu_instance=kdu_instance,
tiernoa278b842020-07-08 15:33:55 +00004953 primitive_name=primitive_name,
garciadeblas5697b8b2021-03-24 09:17:02 +01004954 params=params,
4955 db_dict=db_dict,
David Garciac1fe90a2021-03-31 19:12:02 +02004956 timeout=timeout_ns_action,
4957 vca_id=vca_id,
4958 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01004959 timeout=timeout_ns_action,
David Garciac1fe90a2021-03-31 19:12:02 +02004960 )
tierno067e04a2020-03-31 12:53:13 +00004961
4962 if detailed_status:
garciadeblas5697b8b2021-03-24 09:17:02 +01004963 nslcmop_operation_state = "COMPLETED"
tierno067e04a2020-03-31 12:53:13 +00004964 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004965 detailed_status = ""
4966 nslcmop_operation_state = "FAILED"
tierno067e04a2020-03-31 12:53:13 +00004967 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004968 ee_id, vca_type = self._look_for_deployed_vca(
4969 nsr_deployed["VCA"],
4970 member_vnf_index=vnf_index,
4971 vdu_id=vdu_id,
4972 vdu_count_index=vdu_count_index,
4973 ee_descriptor_id=ee_descriptor_id,
4974 )
4975 for vca_index, vca_deployed in enumerate(
4976 db_nsr["_admin"]["deployed"]["VCA"]
4977 ):
ksaikiranrb1c9f372021-03-15 11:07:29 +05304978 if vca_deployed.get("member-vnf-index") == vnf_index:
garciadeblas5697b8b2021-03-24 09:17:02 +01004979 db_dict = {
4980 "collection": "nsrs",
4981 "filter": {"_id": nsr_id},
4982 "path": "_admin.deployed.VCA.{}.".format(vca_index),
4983 }
ksaikiranrb1c9f372021-03-15 11:07:29 +05304984 break
garciadeblas5697b8b2021-03-24 09:17:02 +01004985 (
4986 nslcmop_operation_state,
4987 detailed_status,
4988 ) = await self._ns_execute_primitive(
tierno588547c2020-07-01 15:30:20 +00004989 ee_id,
tiernoa278b842020-07-08 15:33:55 +00004990 primitive=primitive_name,
garciadeblas5697b8b2021-03-24 09:17:02 +01004991 primitive_params=self._map_primitive_params(
4992 config_primitive_desc, primitive_params, desc_params
4993 ),
tierno588547c2020-07-01 15:30:20 +00004994 timeout=timeout_ns_action,
4995 vca_type=vca_type,
David Garciac1fe90a2021-03-31 19:12:02 +02004996 db_dict=db_dict,
4997 vca_id=vca_id,
4998 )
tierno067e04a2020-03-31 12:53:13 +00004999
5000 db_nslcmop_update["detailed-status"] = detailed_status
garciadeblas5697b8b2021-03-24 09:17:02 +01005001 error_description_nslcmop = (
5002 detailed_status if nslcmop_operation_state == "FAILED" else ""
5003 )
5004 self.logger.debug(
5005 logging_text
5006 + " task Done with result {} {}".format(
5007 nslcmop_operation_state, detailed_status
5008 )
5009 )
tierno59d22d22018-09-25 18:10:19 +02005010 return # database update is called inside finally
5011
tiernof59ad6c2020-04-08 12:50:52 +00005012 except (DbException, LcmException, N2VCException, K8sException) as e:
tierno59d22d22018-09-25 18:10:19 +02005013 self.logger.error(logging_text + "Exit Exception {}".format(e))
5014 exc = e
5015 except asyncio.CancelledError:
garciadeblas5697b8b2021-03-24 09:17:02 +01005016 self.logger.error(
5017 logging_text + "Cancelled Exception while '{}'".format(step)
5018 )
tierno59d22d22018-09-25 18:10:19 +02005019 exc = "Operation was cancelled"
tierno067e04a2020-03-31 12:53:13 +00005020 except asyncio.TimeoutError:
5021 self.logger.error(logging_text + "Timeout while '{}'".format(step))
5022 exc = "Timeout"
tierno59d22d22018-09-25 18:10:19 +02005023 except Exception as e:
5024 exc = traceback.format_exc()
garciadeblas5697b8b2021-03-24 09:17:02 +01005025 self.logger.critical(
5026 logging_text + "Exit Exception {} {}".format(type(e).__name__, e),
5027 exc_info=True,
5028 )
tierno59d22d22018-09-25 18:10:19 +02005029 finally:
tierno067e04a2020-03-31 12:53:13 +00005030 if exc:
garciadeblas5697b8b2021-03-24 09:17:02 +01005031 db_nslcmop_update[
5032 "detailed-status"
5033 ] = (
5034 detailed_status
5035 ) = error_description_nslcmop = "FAILED {}: {}".format(step, exc)
tierno067e04a2020-03-31 12:53:13 +00005036 nslcmop_operation_state = "FAILED"
5037 if db_nsr:
5038 self._write_ns_status(
5039 nsr_id=nsr_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01005040 ns_state=db_nsr[
5041 "nsState"
5042 ], # TODO check if degraded. For the moment use previous status
tierno067e04a2020-03-31 12:53:13 +00005043 current_operation="IDLE",
5044 current_operation_id=None,
5045 # error_description=error_description_nsr,
5046 # error_detail=error_detail,
garciadeblas5697b8b2021-03-24 09:17:02 +01005047 other_update=db_nsr_update,
tierno067e04a2020-03-31 12:53:13 +00005048 )
5049
garciadeblas5697b8b2021-03-24 09:17:02 +01005050 self._write_op_status(
5051 op_id=nslcmop_id,
5052 stage="",
5053 error_message=error_description_nslcmop,
5054 operation_state=nslcmop_operation_state,
5055 other_update=db_nslcmop_update,
5056 )
tierno067e04a2020-03-31 12:53:13 +00005057
tierno59d22d22018-09-25 18:10:19 +02005058 if nslcmop_operation_state:
5059 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01005060 await self.msg.aiowrite(
5061 "ns",
5062 "actioned",
5063 {
5064 "nsr_id": nsr_id,
5065 "nslcmop_id": nslcmop_id,
5066 "operationState": nslcmop_operation_state,
5067 },
5068 loop=self.loop,
5069 )
tierno59d22d22018-09-25 18:10:19 +02005070 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01005071 self.logger.error(
5072 logging_text + "kafka_write notification Exception {}".format(e)
5073 )
tierno59d22d22018-09-25 18:10:19 +02005074 self.logger.debug(logging_text + "Exit")
5075 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_action")
tierno067e04a2020-03-31 12:53:13 +00005076 return nslcmop_operation_state, detailed_status
tierno59d22d22018-09-25 18:10:19 +02005077
5078 async def scale(self, nsr_id, nslcmop_id):
kuused124bfe2019-06-18 12:09:24 +02005079 # Try to lock HA task here
garciadeblas5697b8b2021-03-24 09:17:02 +01005080 task_is_locked_by_me = self.lcm_tasks.lock_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02005081 if not task_is_locked_by_me:
5082 return
5083
tierno59d22d22018-09-25 18:10:19 +02005084 logging_text = "Task ns={} scale={} ".format(nsr_id, nslcmop_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01005085 stage = ["", "", ""]
aktas13251562021-02-12 22:19:10 +03005086 tasks_dict_info = {}
tierno2357f4e2020-10-19 16:38:59 +00005087 # ^ stage, step, VIM progress
tierno59d22d22018-09-25 18:10:19 +02005088 self.logger.debug(logging_text + "Enter")
5089 # get all needed from database
5090 db_nsr = None
tierno59d22d22018-09-25 18:10:19 +02005091 db_nslcmop_update = {}
tiernoe876f672020-02-13 14:34:48 +00005092 db_nsr_update = {}
tierno59d22d22018-09-25 18:10:19 +02005093 exc = None
tierno9ab95942018-10-10 16:44:22 +02005094 # in case of error, indicates what part of scale was failed to put nsr at error status
5095 scale_process = None
tiernod6de1992018-10-11 13:05:52 +02005096 old_operational_status = ""
5097 old_config_status = ""
aktas13251562021-02-12 22:19:10 +03005098 nsi_id = None
tierno59d22d22018-09-25 18:10:19 +02005099 try:
kuused124bfe2019-06-18 12:09:24 +02005100 # wait for any previous tasks in process
tierno3cf81a32019-11-11 17:07:00 +00005101 step = "Waiting for previous operations to terminate"
garciadeblas5697b8b2021-03-24 09:17:02 +01005102 await self.lcm_tasks.waitfor_related_HA("ns", "nslcmops", nslcmop_id)
5103 self._write_ns_status(
5104 nsr_id=nsr_id,
5105 ns_state=None,
5106 current_operation="SCALING",
5107 current_operation_id=nslcmop_id,
5108 )
quilesj4cda56b2019-12-05 10:02:20 +00005109
ikalyvas02d9e7b2019-05-27 18:16:01 +03005110 step = "Getting nslcmop from database"
garciadeblas5697b8b2021-03-24 09:17:02 +01005111 self.logger.debug(
5112 step + " after having waited for previous tasks to be completed"
5113 )
ikalyvas02d9e7b2019-05-27 18:16:01 +03005114 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
bravof922c4172020-11-24 21:21:43 -03005115
ikalyvas02d9e7b2019-05-27 18:16:01 +03005116 step = "Getting nsr from database"
5117 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
ikalyvas02d9e7b2019-05-27 18:16:01 +03005118 old_operational_status = db_nsr["operational-status"]
5119 old_config_status = db_nsr["config-status"]
bravof922c4172020-11-24 21:21:43 -03005120
tierno59d22d22018-09-25 18:10:19 +02005121 step = "Parsing scaling parameters"
5122 db_nsr_update["operational-status"] = "scaling"
5123 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernoe4f7e6c2018-11-27 14:55:30 +00005124 nsr_deployed = db_nsr["_admin"].get("deployed")
calvinosanch9f9c6f22019-11-04 13:37:39 +01005125
garciadeblas5697b8b2021-03-24 09:17:02 +01005126 vnf_index = db_nslcmop["operationParams"]["scaleVnfData"][
5127 "scaleByStepData"
5128 ]["member-vnf-index"]
5129 scaling_group = db_nslcmop["operationParams"]["scaleVnfData"][
5130 "scaleByStepData"
5131 ]["scaling-group-descriptor"]
tierno59d22d22018-09-25 18:10:19 +02005132 scaling_type = db_nslcmop["operationParams"]["scaleVnfData"]["scaleVnfType"]
tierno82974b22018-11-27 21:55:36 +00005133 # for backward compatibility
5134 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
5135 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
5136 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
5137 self.update_db_2("nsrs", nsr_id, db_nsr_update)
5138
tierno59d22d22018-09-25 18:10:19 +02005139 step = "Getting vnfr from database"
garciadeblas5697b8b2021-03-24 09:17:02 +01005140 db_vnfr = self.db.get_one(
5141 "vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id}
5142 )
bravof922c4172020-11-24 21:21:43 -03005143
David Garciac1fe90a2021-03-31 19:12:02 +02005144 vca_id = self.get_vca_id(db_vnfr, db_nsr)
5145
tierno59d22d22018-09-25 18:10:19 +02005146 step = "Getting vnfd from database"
5147 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
ikalyvas02d9e7b2019-05-27 18:16:01 +03005148
aktas13251562021-02-12 22:19:10 +03005149 base_folder = db_vnfd["_admin"]["storage"]
5150
tierno59d22d22018-09-25 18:10:19 +02005151 step = "Getting scaling-group-descriptor"
bravof832f8992020-12-07 12:57:31 -03005152 scaling_descriptor = find_in_list(
garciadeblas5697b8b2021-03-24 09:17:02 +01005153 get_scaling_aspect(db_vnfd),
5154 lambda scale_desc: scale_desc["name"] == scaling_group,
bravof832f8992020-12-07 12:57:31 -03005155 )
5156 if not scaling_descriptor:
garciadeblas5697b8b2021-03-24 09:17:02 +01005157 raise LcmException(
5158 "input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
5159 "at vnfd:scaling-group-descriptor".format(scaling_group)
5160 )
ikalyvas02d9e7b2019-05-27 18:16:01 +03005161
tierno15b1cf12019-08-29 13:21:40 +00005162 step = "Sending scale order to VIM"
bravof922c4172020-11-24 21:21:43 -03005163 # TODO check if ns is in a proper status
tierno59d22d22018-09-25 18:10:19 +02005164 nb_scale_op = 0
5165 if not db_nsr["_admin"].get("scaling-group"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005166 self.update_db_2(
5167 "nsrs",
5168 nsr_id,
5169 {
5170 "_admin.scaling-group": [
5171 {"name": scaling_group, "nb-scale-op": 0}
5172 ]
5173 },
5174 )
tierno59d22d22018-09-25 18:10:19 +02005175 admin_scale_index = 0
5176 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01005177 for admin_scale_index, admin_scale_info in enumerate(
5178 db_nsr["_admin"]["scaling-group"]
5179 ):
tierno59d22d22018-09-25 18:10:19 +02005180 if admin_scale_info["name"] == scaling_group:
5181 nb_scale_op = admin_scale_info.get("nb-scale-op", 0)
5182 break
tierno9ab95942018-10-10 16:44:22 +02005183 else: # not found, set index one plus last element and add new entry with the name
5184 admin_scale_index += 1
garciadeblas5697b8b2021-03-24 09:17:02 +01005185 db_nsr_update[
5186 "_admin.scaling-group.{}.name".format(admin_scale_index)
5187 ] = scaling_group
aktas5f75f102021-03-15 11:26:10 +03005188
5189 vca_scaling_info = []
5190 scaling_info = {"scaling_group_name": scaling_group, "vdu": [], "kdu": []}
tierno59d22d22018-09-25 18:10:19 +02005191 if scaling_type == "SCALE_OUT":
bravof832f8992020-12-07 12:57:31 -03005192 if "aspect-delta-details" not in scaling_descriptor:
5193 raise LcmException(
5194 "Aspect delta details not fount in scaling descriptor {}".format(
5195 scaling_descriptor["name"]
5196 )
5197 )
tierno59d22d22018-09-25 18:10:19 +02005198 # count if max-instance-count is reached
bravof832f8992020-12-07 12:57:31 -03005199 deltas = scaling_descriptor.get("aspect-delta-details")["deltas"]
kuuse8b998e42019-07-30 15:22:16 +02005200
aktas5f75f102021-03-15 11:26:10 +03005201 scaling_info["scaling_direction"] = "OUT"
5202 scaling_info["vdu-create"] = {}
5203 scaling_info["kdu-create"] = {}
bravof832f8992020-12-07 12:57:31 -03005204 for delta in deltas:
aktas5f75f102021-03-15 11:26:10 +03005205 for vdu_delta in delta.get("vdu-delta", {}):
bravof832f8992020-12-07 12:57:31 -03005206 vdud = get_vdu(db_vnfd, vdu_delta["id"])
aktas5f75f102021-03-15 11:26:10 +03005207 # vdu_index also provides the number of instance of the targeted vdu
5208 vdu_count = vdu_index = get_vdur_index(db_vnfr, vdu_delta)
garciadeblas5697b8b2021-03-24 09:17:02 +01005209 cloud_init_text = self._get_vdu_cloud_init_content(
5210 vdud, db_vnfd
5211 )
tierno72ef84f2020-10-06 08:22:07 +00005212 if cloud_init_text:
garciadeblas5697b8b2021-03-24 09:17:02 +01005213 additional_params = (
5214 self._get_vdu_additional_params(db_vnfr, vdud["id"])
5215 or {}
5216 )
bravof832f8992020-12-07 12:57:31 -03005217 cloud_init_list = []
5218
5219 vdu_profile = get_vdu_profile(db_vnfd, vdu_delta["id"])
5220 max_instance_count = 10
5221 if vdu_profile and "max-number-of-instances" in vdu_profile:
garciadeblas5697b8b2021-03-24 09:17:02 +01005222 max_instance_count = vdu_profile.get(
5223 "max-number-of-instances", 10
5224 )
5225
5226 default_instance_num = get_number_of_instances(
5227 db_vnfd, vdud["id"]
5228 )
aktas5f75f102021-03-15 11:26:10 +03005229 instances_number = vdu_delta.get("number-of-instances", 1)
5230 nb_scale_op += instances_number
bravof832f8992020-12-07 12:57:31 -03005231
aktas5f75f102021-03-15 11:26:10 +03005232 new_instance_count = nb_scale_op + default_instance_num
5233 # Control if new count is over max and vdu count is less than max.
5234 # Then assign new instance count
5235 if new_instance_count > max_instance_count > vdu_count:
5236 instances_number = new_instance_count - max_instance_count
5237 else:
5238 instances_number = instances_number
bravof832f8992020-12-07 12:57:31 -03005239
aktas5f75f102021-03-15 11:26:10 +03005240 if new_instance_count > max_instance_count:
bravof832f8992020-12-07 12:57:31 -03005241 raise LcmException(
5242 "reached the limit of {} (max-instance-count) "
5243 "scaling-out operations for the "
garciadeblas5697b8b2021-03-24 09:17:02 +01005244 "scaling-group-descriptor '{}'".format(
5245 nb_scale_op, scaling_group
5246 )
bravof922c4172020-11-24 21:21:43 -03005247 )
bravof832f8992020-12-07 12:57:31 -03005248 for x in range(vdu_delta.get("number-of-instances", 1)):
5249 if cloud_init_text:
5250 # TODO Information of its own ip is not available because db_vnfr is not updated.
5251 additional_params["OSM"] = get_osm_params(
garciadeblas5697b8b2021-03-24 09:17:02 +01005252 db_vnfr, vdu_delta["id"], vdu_index + x
bravof922c4172020-11-24 21:21:43 -03005253 )
bravof832f8992020-12-07 12:57:31 -03005254 cloud_init_list.append(
5255 self._parse_cloud_init(
5256 cloud_init_text,
5257 additional_params,
5258 db_vnfd["id"],
garciadeblas5697b8b2021-03-24 09:17:02 +01005259 vdud["id"],
bravof832f8992020-12-07 12:57:31 -03005260 )
5261 )
aktas5f75f102021-03-15 11:26:10 +03005262 vca_scaling_info.append(
aktas13251562021-02-12 22:19:10 +03005263 {
5264 "osm_vdu_id": vdu_delta["id"],
5265 "member-vnf-index": vnf_index,
5266 "type": "create",
garciadeblas5697b8b2021-03-24 09:17:02 +01005267 "vdu_index": vdu_index + x,
aktas13251562021-02-12 22:19:10 +03005268 }
5269 )
aktas5f75f102021-03-15 11:26:10 +03005270 scaling_info["vdu-create"][vdu_delta["id"]] = instances_number
5271 for kdu_delta in delta.get("kdu-resource-delta", {}):
David Garciab4ebcd02021-10-28 02:00:43 +02005272 kdu_profile = get_kdu_resource_profile(db_vnfd, kdu_delta["id"])
aktas5f75f102021-03-15 11:26:10 +03005273 kdu_name = kdu_profile["kdu-name"]
5274 resource_name = kdu_profile["resource-name"]
5275
5276 # Might have different kdus in the same delta
5277 # Should have list for each kdu
5278 if not scaling_info["kdu-create"].get(kdu_name, None):
5279 scaling_info["kdu-create"][kdu_name] = []
5280
5281 kdur = get_kdur(db_vnfr, kdu_name)
5282 if kdur.get("helm-chart"):
5283 k8s_cluster_type = "helm-chart-v3"
5284 self.logger.debug("kdur: {}".format(kdur))
5285 if (
5286 kdur.get("helm-version")
5287 and kdur.get("helm-version") == "v2"
5288 ):
5289 k8s_cluster_type = "helm-chart"
5290 raise NotImplementedError
5291 elif kdur.get("juju-bundle"):
5292 k8s_cluster_type = "juju-bundle"
5293 else:
5294 raise LcmException(
5295 "kdu type for kdu='{}.{}' is neither helm-chart nor "
5296 "juju-bundle. Maybe an old NBI version is running".format(
5297 db_vnfr["member-vnf-index-ref"], kdu_name
5298 )
5299 )
5300
5301 max_instance_count = 10
5302 if kdu_profile and "max-number-of-instances" in kdu_profile:
5303 max_instance_count = kdu_profile.get(
5304 "max-number-of-instances", 10
5305 )
5306
5307 nb_scale_op += kdu_delta.get("number-of-instances", 1)
5308 deployed_kdu, _ = get_deployed_kdu(
5309 nsr_deployed, kdu_name, vnf_index
bravof832f8992020-12-07 12:57:31 -03005310 )
aktas5f75f102021-03-15 11:26:10 +03005311 if deployed_kdu is None:
5312 raise LcmException(
5313 "KDU '{}' for vnf '{}' not deployed".format(
5314 kdu_name, vnf_index
5315 )
5316 )
5317 kdu_instance = deployed_kdu.get("kdu-instance")
5318 instance_num = await self.k8scluster_map[
5319 k8s_cluster_type
5320 ].get_scale_count(resource_name, kdu_instance, vca_id=vca_id)
5321 kdu_replica_count = instance_num + kdu_delta.get(
garciadeblas5697b8b2021-03-24 09:17:02 +01005322 "number-of-instances", 1
5323 )
ikalyvas02d9e7b2019-05-27 18:16:01 +03005324
aktas5f75f102021-03-15 11:26:10 +03005325 # Control if new count is over max and instance_num is less than max.
5326 # Then assign max instance number to kdu replica count
5327 if kdu_replica_count > max_instance_count > instance_num:
5328 kdu_replica_count = max_instance_count
5329 if kdu_replica_count > max_instance_count:
5330 raise LcmException(
5331 "reached the limit of {} (max-instance-count) "
5332 "scaling-out operations for the "
5333 "scaling-group-descriptor '{}'".format(
5334 instance_num, scaling_group
5335 )
5336 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005337
aktas5f75f102021-03-15 11:26:10 +03005338 for x in range(kdu_delta.get("number-of-instances", 1)):
5339 vca_scaling_info.append(
5340 {
5341 "osm_kdu_id": kdu_name,
5342 "member-vnf-index": vnf_index,
5343 "type": "create",
5344 "kdu_index": instance_num + x - 1,
5345 }
5346 )
5347 scaling_info["kdu-create"][kdu_name].append(
5348 {
5349 "member-vnf-index": vnf_index,
5350 "type": "create",
5351 "k8s-cluster-type": k8s_cluster_type,
5352 "resource-name": resource_name,
5353 "scale": kdu_replica_count,
5354 }
5355 )
5356 elif scaling_type == "SCALE_IN":
bravof832f8992020-12-07 12:57:31 -03005357 deltas = scaling_descriptor.get("aspect-delta-details")["deltas"]
aktas5f75f102021-03-15 11:26:10 +03005358
5359 scaling_info["scaling_direction"] = "IN"
5360 scaling_info["vdu-delete"] = {}
5361 scaling_info["kdu-delete"] = {}
5362
bravof832f8992020-12-07 12:57:31 -03005363 for delta in deltas:
aktas5f75f102021-03-15 11:26:10 +03005364 for vdu_delta in delta.get("vdu-delta", {}):
5365 vdu_count = vdu_index = get_vdur_index(db_vnfr, vdu_delta)
bravof832f8992020-12-07 12:57:31 -03005366 min_instance_count = 0
5367 vdu_profile = get_vdu_profile(db_vnfd, vdu_delta["id"])
5368 if vdu_profile and "min-number-of-instances" in vdu_profile:
5369 min_instance_count = vdu_profile["min-number-of-instances"]
5370
garciadeblas5697b8b2021-03-24 09:17:02 +01005371 default_instance_num = get_number_of_instances(
5372 db_vnfd, vdu_delta["id"]
5373 )
aktas5f75f102021-03-15 11:26:10 +03005374 instance_num = vdu_delta.get("number-of-instances", 1)
5375 nb_scale_op -= instance_num
bravof832f8992020-12-07 12:57:31 -03005376
aktas5f75f102021-03-15 11:26:10 +03005377 new_instance_count = nb_scale_op + default_instance_num
5378
5379 if new_instance_count < min_instance_count < vdu_count:
5380 instances_number = min_instance_count - new_instance_count
5381 else:
5382 instances_number = instance_num
5383
5384 if new_instance_count < min_instance_count:
bravof832f8992020-12-07 12:57:31 -03005385 raise LcmException(
5386 "reached the limit of {} (min-instance-count) scaling-in operations for the "
garciadeblas5697b8b2021-03-24 09:17:02 +01005387 "scaling-group-descriptor '{}'".format(
5388 nb_scale_op, scaling_group
5389 )
bravof832f8992020-12-07 12:57:31 -03005390 )
aktas13251562021-02-12 22:19:10 +03005391 for x in range(vdu_delta.get("number-of-instances", 1)):
aktas5f75f102021-03-15 11:26:10 +03005392 vca_scaling_info.append(
aktas13251562021-02-12 22:19:10 +03005393 {
5394 "osm_vdu_id": vdu_delta["id"],
5395 "member-vnf-index": vnf_index,
5396 "type": "delete",
garciadeblas5697b8b2021-03-24 09:17:02 +01005397 "vdu_index": vdu_index - 1 - x,
aktas13251562021-02-12 22:19:10 +03005398 }
5399 )
aktas5f75f102021-03-15 11:26:10 +03005400 scaling_info["vdu-delete"][vdu_delta["id"]] = instances_number
5401 for kdu_delta in delta.get("kdu-resource-delta", {}):
David Garciab4ebcd02021-10-28 02:00:43 +02005402 kdu_profile = get_kdu_resource_profile(db_vnfd, kdu_delta["id"])
aktas5f75f102021-03-15 11:26:10 +03005403 kdu_name = kdu_profile["kdu-name"]
5404 resource_name = kdu_profile["resource-name"]
5405
5406 if not scaling_info["kdu-delete"].get(kdu_name, None):
5407 scaling_info["kdu-delete"][kdu_name] = []
5408
5409 kdur = get_kdur(db_vnfr, kdu_name)
5410 if kdur.get("helm-chart"):
5411 k8s_cluster_type = "helm-chart-v3"
5412 self.logger.debug("kdur: {}".format(kdur))
5413 if (
5414 kdur.get("helm-version")
5415 and kdur.get("helm-version") == "v2"
5416 ):
5417 k8s_cluster_type = "helm-chart"
5418 raise NotImplementedError
5419 elif kdur.get("juju-bundle"):
5420 k8s_cluster_type = "juju-bundle"
5421 else:
5422 raise LcmException(
5423 "kdu type for kdu='{}.{}' is neither helm-chart nor "
5424 "juju-bundle. Maybe an old NBI version is running".format(
5425 db_vnfr["member-vnf-index-ref"], kdur["kdu-name"]
5426 )
5427 )
5428
5429 min_instance_count = 0
5430 if kdu_profile and "min-number-of-instances" in kdu_profile:
5431 min_instance_count = kdu_profile["min-number-of-instances"]
5432
5433 nb_scale_op -= kdu_delta.get("number-of-instances", 1)
5434 deployed_kdu, _ = get_deployed_kdu(
5435 nsr_deployed, kdu_name, vnf_index
5436 )
5437 if deployed_kdu is None:
5438 raise LcmException(
5439 "KDU '{}' for vnf '{}' not deployed".format(
5440 kdu_name, vnf_index
5441 )
5442 )
5443 kdu_instance = deployed_kdu.get("kdu-instance")
5444 instance_num = await self.k8scluster_map[
5445 k8s_cluster_type
5446 ].get_scale_count(resource_name, kdu_instance, vca_id=vca_id)
5447 kdu_replica_count = instance_num - kdu_delta.get(
garciadeblas5697b8b2021-03-24 09:17:02 +01005448 "number-of-instances", 1
5449 )
tierno59d22d22018-09-25 18:10:19 +02005450
aktas5f75f102021-03-15 11:26:10 +03005451 if kdu_replica_count < min_instance_count < instance_num:
5452 kdu_replica_count = min_instance_count
5453 if kdu_replica_count < min_instance_count:
5454 raise LcmException(
5455 "reached the limit of {} (min-instance-count) scaling-in operations for the "
5456 "scaling-group-descriptor '{}'".format(
5457 instance_num, scaling_group
5458 )
5459 )
5460
5461 for x in range(kdu_delta.get("number-of-instances", 1)):
5462 vca_scaling_info.append(
5463 {
5464 "osm_kdu_id": kdu_name,
5465 "member-vnf-index": vnf_index,
5466 "type": "delete",
5467 "kdu_index": instance_num - x - 1,
5468 }
5469 )
5470 scaling_info["kdu-delete"][kdu_name].append(
5471 {
5472 "member-vnf-index": vnf_index,
5473 "type": "delete",
5474 "k8s-cluster-type": k8s_cluster_type,
5475 "resource-name": resource_name,
5476 "scale": kdu_replica_count,
5477 }
5478 )
5479
tierno59d22d22018-09-25 18:10:19 +02005480 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
aktas5f75f102021-03-15 11:26:10 +03005481 vdu_delete = copy(scaling_info.get("vdu-delete"))
5482 if scaling_info["scaling_direction"] == "IN":
tierno59d22d22018-09-25 18:10:19 +02005483 for vdur in reversed(db_vnfr["vdur"]):
tierno27246d82018-09-27 15:59:09 +02005484 if vdu_delete.get(vdur["vdu-id-ref"]):
5485 vdu_delete[vdur["vdu-id-ref"]] -= 1
aktas5f75f102021-03-15 11:26:10 +03005486 scaling_info["vdu"].append(
garciadeblas5697b8b2021-03-24 09:17:02 +01005487 {
5488 "name": vdur.get("name") or vdur.get("vdu-name"),
5489 "vdu_id": vdur["vdu-id-ref"],
5490 "interface": [],
5491 }
5492 )
tierno59d22d22018-09-25 18:10:19 +02005493 for interface in vdur["interfaces"]:
aktas5f75f102021-03-15 11:26:10 +03005494 scaling_info["vdu"][-1]["interface"].append(
garciadeblas5697b8b2021-03-24 09:17:02 +01005495 {
5496 "name": interface["name"],
5497 "ip_address": interface["ip-address"],
5498 "mac_address": interface.get("mac-address"),
5499 }
5500 )
tierno2357f4e2020-10-19 16:38:59 +00005501 # vdu_delete = vdu_scaling_info.pop("vdu-delete")
tierno59d22d22018-09-25 18:10:19 +02005502
kuuseac3a8882019-10-03 10:48:06 +02005503 # PRE-SCALE BEGIN
tierno59d22d22018-09-25 18:10:19 +02005504 step = "Executing pre-scale vnf-config-primitive"
5505 if scaling_descriptor.get("scaling-config-action"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005506 for scaling_config_action in scaling_descriptor[
5507 "scaling-config-action"
5508 ]:
5509 if (
5510 scaling_config_action.get("trigger") == "pre-scale-in"
5511 and scaling_type == "SCALE_IN"
5512 ) or (
5513 scaling_config_action.get("trigger") == "pre-scale-out"
5514 and scaling_type == "SCALE_OUT"
5515 ):
5516 vnf_config_primitive = scaling_config_action[
5517 "vnf-config-primitive-name-ref"
5518 ]
5519 step = db_nslcmop_update[
5520 "detailed-status"
5521 ] = "executing pre-scale scaling-config-action '{}'".format(
5522 vnf_config_primitive
5523 )
tiernoda964822019-01-14 15:53:47 +00005524
tierno59d22d22018-09-25 18:10:19 +02005525 # look for primitive
garciadeblas5697b8b2021-03-24 09:17:02 +01005526 for config_primitive in (
5527 get_configuration(db_vnfd, db_vnfd["id"]) or {}
5528 ).get("config-primitive", ()):
tierno59d22d22018-09-25 18:10:19 +02005529 if config_primitive["name"] == vnf_config_primitive:
tierno59d22d22018-09-25 18:10:19 +02005530 break
5531 else:
5532 raise LcmException(
5533 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
tiernoda964822019-01-14 15:53:47 +00005534 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
garciadeblas5697b8b2021-03-24 09:17:02 +01005535 "primitive".format(scaling_group, vnf_config_primitive)
5536 )
tiernoda964822019-01-14 15:53:47 +00005537
aktas5f75f102021-03-15 11:26:10 +03005538 vnfr_params = {"VDU_SCALE_INFO": scaling_info}
tiernoda964822019-01-14 15:53:47 +00005539 if db_vnfr.get("additionalParamsForVnf"):
5540 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
quilesj7e13aeb2019-10-08 13:34:55 +02005541
tierno9ab95942018-10-10 16:44:22 +02005542 scale_process = "VCA"
tiernod6de1992018-10-11 13:05:52 +02005543 db_nsr_update["config-status"] = "configuring pre-scaling"
garciadeblas5697b8b2021-03-24 09:17:02 +01005544 primitive_params = self._map_primitive_params(
5545 config_primitive, {}, vnfr_params
5546 )
kuuseac3a8882019-10-03 10:48:06 +02005547
tierno7c4e24c2020-05-13 08:41:35 +00005548 # Pre-scale retry check: Check if this sub-operation has been executed before
kuuseac3a8882019-10-03 10:48:06 +02005549 op_index = self._check_or_add_scale_suboperation(
garciadeblas5697b8b2021-03-24 09:17:02 +01005550 db_nslcmop,
garciadeblas5697b8b2021-03-24 09:17:02 +01005551 vnf_index,
5552 vnf_config_primitive,
5553 primitive_params,
5554 "PRE-SCALE",
5555 )
tierno7c4e24c2020-05-13 08:41:35 +00005556 if op_index == self.SUBOPERATION_STATUS_SKIP:
kuuseac3a8882019-10-03 10:48:06 +02005557 # Skip sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01005558 result = "COMPLETED"
5559 result_detail = "Done"
5560 self.logger.debug(
5561 logging_text
5562 + "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
5563 vnf_config_primitive, result, result_detail
5564 )
5565 )
kuuseac3a8882019-10-03 10:48:06 +02005566 else:
tierno7c4e24c2020-05-13 08:41:35 +00005567 if op_index == self.SUBOPERATION_STATUS_NEW:
kuuseac3a8882019-10-03 10:48:06 +02005568 # New sub-operation: Get index of this sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01005569 op_index = (
5570 len(db_nslcmop.get("_admin", {}).get("operations"))
5571 - 1
5572 )
5573 self.logger.debug(
5574 logging_text
5575 + "vnf_config_primitive={} New sub-operation".format(
5576 vnf_config_primitive
5577 )
5578 )
kuuseac3a8882019-10-03 10:48:06 +02005579 else:
tierno7c4e24c2020-05-13 08:41:35 +00005580 # retry: Get registered params for this existing sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01005581 op = db_nslcmop.get("_admin", {}).get("operations", [])[
5582 op_index
5583 ]
5584 vnf_index = op.get("member_vnf_index")
5585 vnf_config_primitive = op.get("primitive")
5586 primitive_params = op.get("primitive_params")
5587 self.logger.debug(
5588 logging_text
5589 + "vnf_config_primitive={} Sub-operation retry".format(
5590 vnf_config_primitive
5591 )
5592 )
tierno588547c2020-07-01 15:30:20 +00005593 # Execute the primitive, either with new (first-time) or registered (reintent) args
garciadeblas5697b8b2021-03-24 09:17:02 +01005594 ee_descriptor_id = config_primitive.get(
5595 "execution-environment-ref"
5596 )
5597 primitive_name = config_primitive.get(
5598 "execution-environment-primitive", vnf_config_primitive
5599 )
5600 ee_id, vca_type = self._look_for_deployed_vca(
5601 nsr_deployed["VCA"],
5602 member_vnf_index=vnf_index,
5603 vdu_id=None,
5604 vdu_count_index=None,
5605 ee_descriptor_id=ee_descriptor_id,
5606 )
kuuseac3a8882019-10-03 10:48:06 +02005607 result, result_detail = await self._ns_execute_primitive(
garciadeblas5697b8b2021-03-24 09:17:02 +01005608 ee_id,
5609 primitive_name,
David Garciac1fe90a2021-03-31 19:12:02 +02005610 primitive_params,
5611 vca_type=vca_type,
5612 vca_id=vca_id,
5613 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005614 self.logger.debug(
5615 logging_text
5616 + "vnf_config_primitive={} Done with result {} {}".format(
5617 vnf_config_primitive, result, result_detail
5618 )
5619 )
kuuseac3a8882019-10-03 10:48:06 +02005620 # Update operationState = COMPLETED | FAILED
5621 self._update_suboperation_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01005622 db_nslcmop, op_index, result, result_detail
5623 )
kuuseac3a8882019-10-03 10:48:06 +02005624
tierno59d22d22018-09-25 18:10:19 +02005625 if result == "FAILED":
5626 raise LcmException(result_detail)
tiernod6de1992018-10-11 13:05:52 +02005627 db_nsr_update["config-status"] = old_config_status
5628 scale_process = None
kuuseac3a8882019-10-03 10:48:06 +02005629 # PRE-SCALE END
tierno59d22d22018-09-25 18:10:19 +02005630
garciadeblas5697b8b2021-03-24 09:17:02 +01005631 db_nsr_update[
5632 "_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index)
5633 ] = nb_scale_op
5634 db_nsr_update[
5635 "_admin.scaling-group.{}.time".format(admin_scale_index)
5636 ] = time()
tierno2357f4e2020-10-19 16:38:59 +00005637
aktas13251562021-02-12 22:19:10 +03005638 # SCALE-IN VCA - BEGIN
aktas5f75f102021-03-15 11:26:10 +03005639 if vca_scaling_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01005640 step = db_nslcmop_update[
5641 "detailed-status"
5642 ] = "Deleting the execution environments"
aktas13251562021-02-12 22:19:10 +03005643 scale_process = "VCA"
aktas5f75f102021-03-15 11:26:10 +03005644 for vca_info in vca_scaling_info:
5645 if vca_info["type"] == "delete":
5646 member_vnf_index = str(vca_info["member-vnf-index"])
garciadeblas5697b8b2021-03-24 09:17:02 +01005647 self.logger.debug(
aktas5f75f102021-03-15 11:26:10 +03005648 logging_text + "vdu info: {}".format(vca_info)
garciadeblas5697b8b2021-03-24 09:17:02 +01005649 )
aktas5f75f102021-03-15 11:26:10 +03005650 if vca_info.get("osm_vdu_id"):
5651 vdu_id = vca_info["osm_vdu_id"]
5652 vdu_index = int(vca_info["vdu_index"])
5653 stage[
5654 1
5655 ] = "Scaling member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
5656 member_vnf_index, vdu_id, vdu_index
5657 )
5658 else:
5659 vdu_index = 0
5660 kdu_id = vca_info["osm_kdu_id"]
5661 stage[
5662 1
5663 ] = "Scaling member_vnf_index={}, kdu_id={}, vdu_index={} ".format(
5664 member_vnf_index, kdu_id, vdu_index
5665 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005666 stage[2] = step = "Scaling in VCA"
5667 self._write_op_status(op_id=nslcmop_id, stage=stage)
aktas13251562021-02-12 22:19:10 +03005668 vca_update = db_nsr["_admin"]["deployed"]["VCA"]
5669 config_update = db_nsr["configurationStatus"]
5670 for vca_index, vca in enumerate(vca_update):
garciadeblas5697b8b2021-03-24 09:17:02 +01005671 if (
5672 (vca or vca.get("ee_id"))
5673 and vca["member-vnf-index"] == member_vnf_index
5674 and vca["vdu_count_index"] == vdu_index
5675 ):
aktas13251562021-02-12 22:19:10 +03005676 if vca.get("vdu_id"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005677 config_descriptor = get_configuration(
5678 db_vnfd, vca.get("vdu_id")
5679 )
aktas13251562021-02-12 22:19:10 +03005680 elif vca.get("kdu_name"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005681 config_descriptor = get_configuration(
5682 db_vnfd, vca.get("kdu_name")
5683 )
aktas13251562021-02-12 22:19:10 +03005684 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01005685 config_descriptor = get_configuration(
5686 db_vnfd, db_vnfd["id"]
5687 )
5688 operation_params = (
5689 db_nslcmop.get("operationParams") or {}
5690 )
5691 exec_terminate_primitives = not operation_params.get(
5692 "skip_terminate_primitives"
5693 ) and vca.get("needed_terminate")
David Garciac1fe90a2021-03-31 19:12:02 +02005694 task = asyncio.ensure_future(
5695 asyncio.wait_for(
5696 self.destroy_N2VC(
5697 logging_text,
5698 db_nslcmop,
5699 vca,
5700 config_descriptor,
5701 vca_index,
5702 destroy_ee=True,
5703 exec_primitives=exec_terminate_primitives,
5704 scaling_in=True,
5705 vca_id=vca_id,
5706 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01005707 timeout=self.timeout_charm_delete,
David Garciac1fe90a2021-03-31 19:12:02 +02005708 )
5709 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005710 tasks_dict_info[task] = "Terminating VCA {}".format(
5711 vca.get("ee_id")
5712 )
aktas13251562021-02-12 22:19:10 +03005713 del vca_update[vca_index]
5714 del config_update[vca_index]
5715 # wait for pending tasks of terminate primitives
5716 if tasks_dict_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01005717 self.logger.debug(
5718 logging_text
5719 + "Waiting for tasks {}".format(
5720 list(tasks_dict_info.keys())
5721 )
5722 )
5723 error_list = await self._wait_for_tasks(
5724 logging_text,
5725 tasks_dict_info,
5726 min(
5727 self.timeout_charm_delete, self.timeout_ns_terminate
5728 ),
5729 stage,
5730 nslcmop_id,
5731 )
aktas13251562021-02-12 22:19:10 +03005732 tasks_dict_info.clear()
5733 if error_list:
5734 raise LcmException("; ".join(error_list))
5735
5736 db_vca_and_config_update = {
5737 "_admin.deployed.VCA": vca_update,
garciadeblas5697b8b2021-03-24 09:17:02 +01005738 "configurationStatus": config_update,
aktas13251562021-02-12 22:19:10 +03005739 }
garciadeblas5697b8b2021-03-24 09:17:02 +01005740 self.update_db_2(
5741 "nsrs", db_nsr["_id"], db_vca_and_config_update
5742 )
aktas13251562021-02-12 22:19:10 +03005743 scale_process = None
5744 # SCALE-IN VCA - END
5745
kuuseac3a8882019-10-03 10:48:06 +02005746 # SCALE RO - BEGIN
aktas5f75f102021-03-15 11:26:10 +03005747 if scaling_info.get("vdu-create") or scaling_info.get("vdu-delete"):
tierno9ab95942018-10-10 16:44:22 +02005748 scale_process = "RO"
tierno2357f4e2020-10-19 16:38:59 +00005749 if self.ro_config.get("ng"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005750 await self._scale_ng_ro(
aktas5f75f102021-03-15 11:26:10 +03005751 logging_text, db_nsr, db_nslcmop, db_vnfr, scaling_info, stage
garciadeblas5697b8b2021-03-24 09:17:02 +01005752 )
aktas5f75f102021-03-15 11:26:10 +03005753 scaling_info.pop("vdu-create", None)
5754 scaling_info.pop("vdu-delete", None)
tierno59d22d22018-09-25 18:10:19 +02005755
tierno9ab95942018-10-10 16:44:22 +02005756 scale_process = None
aktas13251562021-02-12 22:19:10 +03005757 # SCALE RO - END
5758
aktas5f75f102021-03-15 11:26:10 +03005759 # SCALE KDU - BEGIN
5760 if scaling_info.get("kdu-create") or scaling_info.get("kdu-delete"):
5761 scale_process = "KDU"
5762 await self._scale_kdu(
5763 logging_text, nsr_id, nsr_deployed, db_vnfd, vca_id, scaling_info
5764 )
5765 scaling_info.pop("kdu-create", None)
5766 scaling_info.pop("kdu-delete", None)
5767
5768 scale_process = None
5769 # SCALE KDU - END
5770
5771 if db_nsr_update:
5772 self.update_db_2("nsrs", nsr_id, db_nsr_update)
5773
aktas13251562021-02-12 22:19:10 +03005774 # SCALE-UP VCA - BEGIN
aktas5f75f102021-03-15 11:26:10 +03005775 if vca_scaling_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01005776 step = db_nslcmop_update[
5777 "detailed-status"
5778 ] = "Creating new execution environments"
aktas13251562021-02-12 22:19:10 +03005779 scale_process = "VCA"
aktas5f75f102021-03-15 11:26:10 +03005780 for vca_info in vca_scaling_info:
5781 if vca_info["type"] == "create":
5782 member_vnf_index = str(vca_info["member-vnf-index"])
garciadeblas5697b8b2021-03-24 09:17:02 +01005783 self.logger.debug(
aktas5f75f102021-03-15 11:26:10 +03005784 logging_text + "vdu info: {}".format(vca_info)
garciadeblas5697b8b2021-03-24 09:17:02 +01005785 )
aktas13251562021-02-12 22:19:10 +03005786 vnfd_id = db_vnfr["vnfd-ref"]
aktas5f75f102021-03-15 11:26:10 +03005787 if vca_info.get("osm_vdu_id"):
5788 vdu_index = int(vca_info["vdu_index"])
5789 deploy_params = {"OSM": get_osm_params(db_vnfr)}
5790 if db_vnfr.get("additionalParamsForVnf"):
5791 deploy_params.update(
5792 parse_yaml_strings(
5793 db_vnfr["additionalParamsForVnf"].copy()
5794 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005795 )
aktas5f75f102021-03-15 11:26:10 +03005796 descriptor_config = get_configuration(
5797 db_vnfd, db_vnfd["id"]
garciadeblas5697b8b2021-03-24 09:17:02 +01005798 )
aktas5f75f102021-03-15 11:26:10 +03005799 if descriptor_config:
5800 vdu_id = None
5801 vdu_name = None
5802 kdu_name = None
5803 self._deploy_n2vc(
5804 logging_text=logging_text
5805 + "member_vnf_index={} ".format(member_vnf_index),
5806 db_nsr=db_nsr,
5807 db_vnfr=db_vnfr,
5808 nslcmop_id=nslcmop_id,
5809 nsr_id=nsr_id,
5810 nsi_id=nsi_id,
5811 vnfd_id=vnfd_id,
5812 vdu_id=vdu_id,
5813 kdu_name=kdu_name,
5814 member_vnf_index=member_vnf_index,
5815 vdu_index=vdu_index,
5816 vdu_name=vdu_name,
5817 deploy_params=deploy_params,
5818 descriptor_config=descriptor_config,
5819 base_folder=base_folder,
5820 task_instantiation_info=tasks_dict_info,
5821 stage=stage,
5822 )
5823 vdu_id = vca_info["osm_vdu_id"]
5824 vdur = find_in_list(
5825 db_vnfr["vdur"], lambda vdu: vdu["vdu-id-ref"] == vdu_id
aktas13251562021-02-12 22:19:10 +03005826 )
aktas5f75f102021-03-15 11:26:10 +03005827 descriptor_config = get_configuration(db_vnfd, vdu_id)
5828 if vdur.get("additionalParams"):
5829 deploy_params_vdu = parse_yaml_strings(
5830 vdur["additionalParams"]
5831 )
5832 else:
5833 deploy_params_vdu = deploy_params
5834 deploy_params_vdu["OSM"] = get_osm_params(
5835 db_vnfr, vdu_id, vdu_count_index=vdu_index
garciadeblas5697b8b2021-03-24 09:17:02 +01005836 )
aktas5f75f102021-03-15 11:26:10 +03005837 if descriptor_config:
5838 vdu_name = None
5839 kdu_name = None
5840 stage[
5841 1
5842 ] = "Scaling member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
garciadeblas5697b8b2021-03-24 09:17:02 +01005843 member_vnf_index, vdu_id, vdu_index
aktas5f75f102021-03-15 11:26:10 +03005844 )
5845 stage[2] = step = "Scaling out VCA"
5846 self._write_op_status(op_id=nslcmop_id, stage=stage)
5847 self._deploy_n2vc(
5848 logging_text=logging_text
5849 + "member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
5850 member_vnf_index, vdu_id, vdu_index
5851 ),
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_vdu,
5864 descriptor_config=descriptor_config,
5865 base_folder=base_folder,
5866 task_instantiation_info=tasks_dict_info,
5867 stage=stage,
5868 )
5869 else:
5870 kdu_name = vca_info["osm_kdu_id"]
5871 descriptor_config = get_configuration(db_vnfd, kdu_name)
5872 if descriptor_config:
5873 vdu_id = None
5874 kdu_index = int(vca_info["kdu_index"])
5875 vdu_name = None
5876 kdur = next(
5877 x
5878 for x in db_vnfr["kdur"]
5879 if x["kdu-name"] == kdu_name
5880 )
5881 deploy_params_kdu = {"OSM": get_osm_params(db_vnfr)}
5882 if kdur.get("additionalParams"):
5883 deploy_params_kdu = parse_yaml_strings(
5884 kdur["additionalParams"]
5885 )
5886
5887 self._deploy_n2vc(
5888 logging_text=logging_text,
5889 db_nsr=db_nsr,
5890 db_vnfr=db_vnfr,
5891 nslcmop_id=nslcmop_id,
5892 nsr_id=nsr_id,
5893 nsi_id=nsi_id,
5894 vnfd_id=vnfd_id,
5895 vdu_id=vdu_id,
5896 kdu_name=kdu_name,
5897 member_vnf_index=member_vnf_index,
5898 vdu_index=kdu_index,
5899 vdu_name=vdu_name,
5900 deploy_params=deploy_params_kdu,
5901 descriptor_config=descriptor_config,
5902 base_folder=base_folder,
5903 task_instantiation_info=tasks_dict_info,
5904 stage=stage,
5905 )
aktas13251562021-02-12 22:19:10 +03005906 # SCALE-UP VCA - END
5907 scale_process = None
tierno59d22d22018-09-25 18:10:19 +02005908
kuuseac3a8882019-10-03 10:48:06 +02005909 # POST-SCALE BEGIN
tierno59d22d22018-09-25 18:10:19 +02005910 # execute primitive service POST-SCALING
5911 step = "Executing post-scale vnf-config-primitive"
5912 if scaling_descriptor.get("scaling-config-action"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005913 for scaling_config_action in scaling_descriptor[
5914 "scaling-config-action"
5915 ]:
5916 if (
5917 scaling_config_action.get("trigger") == "post-scale-in"
5918 and scaling_type == "SCALE_IN"
5919 ) or (
5920 scaling_config_action.get("trigger") == "post-scale-out"
5921 and scaling_type == "SCALE_OUT"
5922 ):
5923 vnf_config_primitive = scaling_config_action[
5924 "vnf-config-primitive-name-ref"
5925 ]
5926 step = db_nslcmop_update[
5927 "detailed-status"
5928 ] = "executing post-scale scaling-config-action '{}'".format(
5929 vnf_config_primitive
5930 )
tiernoda964822019-01-14 15:53:47 +00005931
aktas5f75f102021-03-15 11:26:10 +03005932 vnfr_params = {"VDU_SCALE_INFO": scaling_info}
tiernoda964822019-01-14 15:53:47 +00005933 if db_vnfr.get("additionalParamsForVnf"):
5934 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
5935
tierno59d22d22018-09-25 18:10:19 +02005936 # look for primitive
bravof9a256db2021-02-22 18:02:07 -03005937 for config_primitive in (
5938 get_configuration(db_vnfd, db_vnfd["id"]) or {}
5939 ).get("config-primitive", ()):
tierno59d22d22018-09-25 18:10:19 +02005940 if config_primitive["name"] == vnf_config_primitive:
tierno59d22d22018-09-25 18:10:19 +02005941 break
5942 else:
tiernoa278b842020-07-08 15:33:55 +00005943 raise LcmException(
5944 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-"
5945 "action[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:"
garciadeblas5697b8b2021-03-24 09:17:02 +01005946 "config-primitive".format(
5947 scaling_group, vnf_config_primitive
5948 )
5949 )
tierno9ab95942018-10-10 16:44:22 +02005950 scale_process = "VCA"
tiernod6de1992018-10-11 13:05:52 +02005951 db_nsr_update["config-status"] = "configuring post-scaling"
garciadeblas5697b8b2021-03-24 09:17:02 +01005952 primitive_params = self._map_primitive_params(
5953 config_primitive, {}, vnfr_params
5954 )
tiernod6de1992018-10-11 13:05:52 +02005955
tierno7c4e24c2020-05-13 08:41:35 +00005956 # Post-scale retry check: Check if this sub-operation has been executed before
kuuseac3a8882019-10-03 10:48:06 +02005957 op_index = self._check_or_add_scale_suboperation(
garciadeblas5697b8b2021-03-24 09:17:02 +01005958 db_nslcmop,
garciadeblas5697b8b2021-03-24 09:17:02 +01005959 vnf_index,
5960 vnf_config_primitive,
5961 primitive_params,
5962 "POST-SCALE",
5963 )
quilesj4cda56b2019-12-05 10:02:20 +00005964 if op_index == self.SUBOPERATION_STATUS_SKIP:
kuuseac3a8882019-10-03 10:48:06 +02005965 # Skip sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01005966 result = "COMPLETED"
5967 result_detail = "Done"
5968 self.logger.debug(
5969 logging_text
5970 + "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
5971 vnf_config_primitive, result, result_detail
5972 )
5973 )
kuuseac3a8882019-10-03 10:48:06 +02005974 else:
quilesj4cda56b2019-12-05 10:02:20 +00005975 if op_index == self.SUBOPERATION_STATUS_NEW:
kuuseac3a8882019-10-03 10:48:06 +02005976 # New sub-operation: Get index of this sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01005977 op_index = (
5978 len(db_nslcmop.get("_admin", {}).get("operations"))
5979 - 1
5980 )
5981 self.logger.debug(
5982 logging_text
5983 + "vnf_config_primitive={} New sub-operation".format(
5984 vnf_config_primitive
5985 )
5986 )
kuuseac3a8882019-10-03 10:48:06 +02005987 else:
tierno7c4e24c2020-05-13 08:41:35 +00005988 # retry: Get registered params for this existing sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01005989 op = db_nslcmop.get("_admin", {}).get("operations", [])[
5990 op_index
5991 ]
5992 vnf_index = op.get("member_vnf_index")
5993 vnf_config_primitive = op.get("primitive")
5994 primitive_params = op.get("primitive_params")
5995 self.logger.debug(
5996 logging_text
5997 + "vnf_config_primitive={} Sub-operation retry".format(
5998 vnf_config_primitive
5999 )
6000 )
tierno588547c2020-07-01 15:30:20 +00006001 # Execute the primitive, either with new (first-time) or registered (reintent) args
garciadeblas5697b8b2021-03-24 09:17:02 +01006002 ee_descriptor_id = config_primitive.get(
6003 "execution-environment-ref"
6004 )
6005 primitive_name = config_primitive.get(
6006 "execution-environment-primitive", vnf_config_primitive
6007 )
6008 ee_id, vca_type = self._look_for_deployed_vca(
6009 nsr_deployed["VCA"],
6010 member_vnf_index=vnf_index,
6011 vdu_id=None,
6012 vdu_count_index=None,
6013 ee_descriptor_id=ee_descriptor_id,
6014 )
kuuseac3a8882019-10-03 10:48:06 +02006015 result, result_detail = await self._ns_execute_primitive(
David Garciac1fe90a2021-03-31 19:12:02 +02006016 ee_id,
6017 primitive_name,
6018 primitive_params,
6019 vca_type=vca_type,
6020 vca_id=vca_id,
6021 )
garciadeblas5697b8b2021-03-24 09:17:02 +01006022 self.logger.debug(
6023 logging_text
6024 + "vnf_config_primitive={} Done with result {} {}".format(
6025 vnf_config_primitive, result, result_detail
6026 )
6027 )
kuuseac3a8882019-10-03 10:48:06 +02006028 # Update operationState = COMPLETED | FAILED
6029 self._update_suboperation_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01006030 db_nslcmop, op_index, result, result_detail
6031 )
kuuseac3a8882019-10-03 10:48:06 +02006032
tierno59d22d22018-09-25 18:10:19 +02006033 if result == "FAILED":
6034 raise LcmException(result_detail)
tiernod6de1992018-10-11 13:05:52 +02006035 db_nsr_update["config-status"] = old_config_status
6036 scale_process = None
kuuseac3a8882019-10-03 10:48:06 +02006037 # POST-SCALE END
tierno59d22d22018-09-25 18:10:19 +02006038
garciadeblas5697b8b2021-03-24 09:17:02 +01006039 db_nsr_update[
6040 "detailed-status"
6041 ] = "" # "scaled {} {}".format(scaling_group, scaling_type)
6042 db_nsr_update["operational-status"] = (
6043 "running"
6044 if old_operational_status == "failed"
ikalyvas02d9e7b2019-05-27 18:16:01 +03006045 else old_operational_status
garciadeblas5697b8b2021-03-24 09:17:02 +01006046 )
tiernod6de1992018-10-11 13:05:52 +02006047 db_nsr_update["config-status"] = old_config_status
tierno59d22d22018-09-25 18:10:19 +02006048 return
garciadeblas5697b8b2021-03-24 09:17:02 +01006049 except (
6050 ROclient.ROClientException,
6051 DbException,
6052 LcmException,
6053 NgRoException,
6054 ) as e:
tierno59d22d22018-09-25 18:10:19 +02006055 self.logger.error(logging_text + "Exit Exception {}".format(e))
6056 exc = e
6057 except asyncio.CancelledError:
garciadeblas5697b8b2021-03-24 09:17:02 +01006058 self.logger.error(
6059 logging_text + "Cancelled Exception while '{}'".format(step)
6060 )
tierno59d22d22018-09-25 18:10:19 +02006061 exc = "Operation was cancelled"
6062 except Exception as e:
6063 exc = traceback.format_exc()
garciadeblas5697b8b2021-03-24 09:17:02 +01006064 self.logger.critical(
6065 logging_text + "Exit Exception {} {}".format(type(e).__name__, e),
6066 exc_info=True,
6067 )
tierno59d22d22018-09-25 18:10:19 +02006068 finally:
garciadeblas5697b8b2021-03-24 09:17:02 +01006069 self._write_ns_status(
6070 nsr_id=nsr_id,
6071 ns_state=None,
6072 current_operation="IDLE",
6073 current_operation_id=None,
6074 )
aktas13251562021-02-12 22:19:10 +03006075 if tasks_dict_info:
6076 stage[1] = "Waiting for instantiate pending tasks."
6077 self.logger.debug(logging_text + stage[1])
garciadeblas5697b8b2021-03-24 09:17:02 +01006078 exc = await self._wait_for_tasks(
6079 logging_text,
6080 tasks_dict_info,
6081 self.timeout_ns_deploy,
6082 stage,
6083 nslcmop_id,
6084 nsr_id=nsr_id,
6085 )
tierno59d22d22018-09-25 18:10:19 +02006086 if exc:
garciadeblas5697b8b2021-03-24 09:17:02 +01006087 db_nslcmop_update[
6088 "detailed-status"
6089 ] = error_description_nslcmop = "FAILED {}: {}".format(step, exc)
tiernoa17d4f42020-04-28 09:59:23 +00006090 nslcmop_operation_state = "FAILED"
tierno59d22d22018-09-25 18:10:19 +02006091 if db_nsr:
tiernod6de1992018-10-11 13:05:52 +02006092 db_nsr_update["operational-status"] = old_operational_status
6093 db_nsr_update["config-status"] = old_config_status
6094 db_nsr_update["detailed-status"] = ""
6095 if scale_process:
6096 if "VCA" in scale_process:
6097 db_nsr_update["config-status"] = "failed"
6098 if "RO" in scale_process:
6099 db_nsr_update["operational-status"] = "failed"
garciadeblas5697b8b2021-03-24 09:17:02 +01006100 db_nsr_update[
6101 "detailed-status"
6102 ] = "FAILED scaling nslcmop={} {}: {}".format(
6103 nslcmop_id, step, exc
6104 )
tiernoa17d4f42020-04-28 09:59:23 +00006105 else:
6106 error_description_nslcmop = None
6107 nslcmop_operation_state = "COMPLETED"
6108 db_nslcmop_update["detailed-status"] = "Done"
quilesj4cda56b2019-12-05 10:02:20 +00006109
garciadeblas5697b8b2021-03-24 09:17:02 +01006110 self._write_op_status(
6111 op_id=nslcmop_id,
6112 stage="",
6113 error_message=error_description_nslcmop,
6114 operation_state=nslcmop_operation_state,
6115 other_update=db_nslcmop_update,
6116 )
tiernoa17d4f42020-04-28 09:59:23 +00006117 if db_nsr:
garciadeblas5697b8b2021-03-24 09:17:02 +01006118 self._write_ns_status(
6119 nsr_id=nsr_id,
6120 ns_state=None,
6121 current_operation="IDLE",
6122 current_operation_id=None,
6123 other_update=db_nsr_update,
6124 )
tiernoa17d4f42020-04-28 09:59:23 +00006125
tierno59d22d22018-09-25 18:10:19 +02006126 if nslcmop_operation_state:
6127 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01006128 msg = {
6129 "nsr_id": nsr_id,
6130 "nslcmop_id": nslcmop_id,
6131 "operationState": nslcmop_operation_state,
6132 }
bravof922c4172020-11-24 21:21:43 -03006133 await self.msg.aiowrite("ns", "scaled", msg, loop=self.loop)
tierno59d22d22018-09-25 18:10:19 +02006134 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01006135 self.logger.error(
6136 logging_text + "kafka_write notification Exception {}".format(e)
6137 )
tierno59d22d22018-09-25 18:10:19 +02006138 self.logger.debug(logging_text + "Exit")
6139 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_scale")
tiernob996d942020-07-03 14:52:28 +00006140
aktas5f75f102021-03-15 11:26:10 +03006141 async def _scale_kdu(
6142 self, logging_text, nsr_id, nsr_deployed, db_vnfd, vca_id, scaling_info
6143 ):
6144 _scaling_info = scaling_info.get("kdu-create") or scaling_info.get("kdu-delete")
6145 for kdu_name in _scaling_info:
6146 for kdu_scaling_info in _scaling_info[kdu_name]:
6147 deployed_kdu, index = get_deployed_kdu(
6148 nsr_deployed, kdu_name, kdu_scaling_info["member-vnf-index"]
6149 )
6150 cluster_uuid = deployed_kdu["k8scluster-uuid"]
6151 kdu_instance = deployed_kdu["kdu-instance"]
6152 scale = int(kdu_scaling_info["scale"])
6153 k8s_cluster_type = kdu_scaling_info["k8s-cluster-type"]
6154
6155 db_dict = {
6156 "collection": "nsrs",
6157 "filter": {"_id": nsr_id},
6158 "path": "_admin.deployed.K8s.{}".format(index),
6159 }
6160
6161 step = "scaling application {}".format(
6162 kdu_scaling_info["resource-name"]
6163 )
6164 self.logger.debug(logging_text + step)
6165
6166 if kdu_scaling_info["type"] == "delete":
6167 kdu_config = get_configuration(db_vnfd, kdu_name)
6168 if (
6169 kdu_config
6170 and kdu_config.get("terminate-config-primitive")
6171 and get_juju_ee_ref(db_vnfd, kdu_name) is None
6172 ):
6173 terminate_config_primitive_list = kdu_config.get(
6174 "terminate-config-primitive"
6175 )
6176 terminate_config_primitive_list.sort(
6177 key=lambda val: int(val["seq"])
6178 )
6179
6180 for (
6181 terminate_config_primitive
6182 ) in terminate_config_primitive_list:
6183 primitive_params_ = self._map_primitive_params(
6184 terminate_config_primitive, {}, {}
6185 )
6186 step = "execute terminate config primitive"
6187 self.logger.debug(logging_text + step)
6188 await asyncio.wait_for(
6189 self.k8scluster_map[k8s_cluster_type].exec_primitive(
6190 cluster_uuid=cluster_uuid,
6191 kdu_instance=kdu_instance,
6192 primitive_name=terminate_config_primitive["name"],
6193 params=primitive_params_,
6194 db_dict=db_dict,
6195 vca_id=vca_id,
6196 ),
6197 timeout=600,
6198 )
6199
6200 await asyncio.wait_for(
6201 self.k8scluster_map[k8s_cluster_type].scale(
6202 kdu_instance,
6203 scale,
6204 kdu_scaling_info["resource-name"],
6205 vca_id=vca_id,
6206 ),
6207 timeout=self.timeout_vca_on_error,
6208 )
6209
6210 if kdu_scaling_info["type"] == "create":
6211 kdu_config = get_configuration(db_vnfd, kdu_name)
6212 if (
6213 kdu_config
6214 and kdu_config.get("initial-config-primitive")
6215 and get_juju_ee_ref(db_vnfd, kdu_name) is None
6216 ):
6217 initial_config_primitive_list = kdu_config.get(
6218 "initial-config-primitive"
6219 )
6220 initial_config_primitive_list.sort(
6221 key=lambda val: int(val["seq"])
6222 )
6223
6224 for initial_config_primitive in initial_config_primitive_list:
6225 primitive_params_ = self._map_primitive_params(
6226 initial_config_primitive, {}, {}
6227 )
6228 step = "execute initial config primitive"
6229 self.logger.debug(logging_text + step)
6230 await asyncio.wait_for(
6231 self.k8scluster_map[k8s_cluster_type].exec_primitive(
6232 cluster_uuid=cluster_uuid,
6233 kdu_instance=kdu_instance,
6234 primitive_name=initial_config_primitive["name"],
6235 params=primitive_params_,
6236 db_dict=db_dict,
6237 vca_id=vca_id,
6238 ),
6239 timeout=600,
6240 )
6241
garciadeblas5697b8b2021-03-24 09:17:02 +01006242 async def _scale_ng_ro(
6243 self, logging_text, db_nsr, db_nslcmop, db_vnfr, vdu_scaling_info, stage
6244 ):
tierno2357f4e2020-10-19 16:38:59 +00006245 nsr_id = db_nslcmop["nsInstanceId"]
6246 db_nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
6247 db_vnfrs = {}
6248
6249 # read from db: vnfd's for every vnf
bravof832f8992020-12-07 12:57:31 -03006250 db_vnfds = []
tierno2357f4e2020-10-19 16:38:59 +00006251
6252 # for each vnf in ns, read vnfd
6253 for vnfr in self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id}):
6254 db_vnfrs[vnfr["member-vnf-index-ref"]] = vnfr
6255 vnfd_id = vnfr["vnfd-id"] # vnfd uuid for this vnf
tierno2357f4e2020-10-19 16:38:59 +00006256 # if we haven't this vnfd, read it from db
bravof832f8992020-12-07 12:57:31 -03006257 if not find_in_list(db_vnfds, lambda a_vnfd: a_vnfd["id"] == vnfd_id):
tierno2357f4e2020-10-19 16:38:59 +00006258 # read from db
6259 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
bravof832f8992020-12-07 12:57:31 -03006260 db_vnfds.append(vnfd)
tierno2357f4e2020-10-19 16:38:59 +00006261 n2vc_key = self.n2vc.get_public_key()
6262 n2vc_key_list = [n2vc_key]
garciadeblas5697b8b2021-03-24 09:17:02 +01006263 self.scale_vnfr(
6264 db_vnfr,
6265 vdu_scaling_info.get("vdu-create"),
6266 vdu_scaling_info.get("vdu-delete"),
6267 mark_delete=True,
6268 )
tierno2357f4e2020-10-19 16:38:59 +00006269 # db_vnfr has been updated, update db_vnfrs to use it
6270 db_vnfrs[db_vnfr["member-vnf-index-ref"]] = db_vnfr
garciadeblas5697b8b2021-03-24 09:17:02 +01006271 await self._instantiate_ng_ro(
6272 logging_text,
6273 nsr_id,
6274 db_nsd,
6275 db_nsr,
6276 db_nslcmop,
6277 db_vnfrs,
6278 db_vnfds,
6279 n2vc_key_list,
6280 stage=stage,
6281 start_deploy=time(),
6282 timeout_ns_deploy=self.timeout_ns_deploy,
6283 )
tierno2357f4e2020-10-19 16:38:59 +00006284 if vdu_scaling_info.get("vdu-delete"):
garciadeblas5697b8b2021-03-24 09:17:02 +01006285 self.scale_vnfr(
6286 db_vnfr, None, vdu_scaling_info["vdu-delete"], mark_delete=False
6287 )
tierno2357f4e2020-10-19 16:38:59 +00006288
garciadeblas5697b8b2021-03-24 09:17:02 +01006289 async def add_prometheus_metrics(
6290 self, ee_id, artifact_path, ee_config_descriptor, vnfr_id, nsr_id, target_ip
6291 ):
tiernob996d942020-07-03 14:52:28 +00006292 if not self.prometheus:
6293 return
6294 # look if exist a file called 'prometheus*.j2' and
6295 artifact_content = self.fs.dir_ls(artifact_path)
garciadeblas5697b8b2021-03-24 09:17:02 +01006296 job_file = next(
6297 (
6298 f
6299 for f in artifact_content
6300 if f.startswith("prometheus") and f.endswith(".j2")
6301 ),
6302 None,
6303 )
tiernob996d942020-07-03 14:52:28 +00006304 if not job_file:
6305 return
6306 with self.fs.file_open((artifact_path, job_file), "r") as f:
6307 job_data = f.read()
6308
6309 # TODO get_service
garciadeblas5697b8b2021-03-24 09:17:02 +01006310 _, _, service = ee_id.partition(".") # remove prefix "namespace."
tiernob996d942020-07-03 14:52:28 +00006311 host_name = "{}-{}".format(service, ee_config_descriptor["metric-service"])
6312 host_port = "80"
6313 vnfr_id = vnfr_id.replace("-", "")
6314 variables = {
6315 "JOB_NAME": vnfr_id,
6316 "TARGET_IP": target_ip,
6317 "EXPORTER_POD_IP": host_name,
6318 "EXPORTER_POD_PORT": host_port,
6319 }
6320 job_list = self.prometheus.parse_job(job_data, variables)
6321 # ensure job_name is using the vnfr_id. Adding the metadata nsr_id
6322 for job in job_list:
garciadeblas5697b8b2021-03-24 09:17:02 +01006323 if (
6324 not isinstance(job.get("job_name"), str)
6325 or vnfr_id not in job["job_name"]
6326 ):
tiernob996d942020-07-03 14:52:28 +00006327 job["job_name"] = vnfr_id + "_" + str(randint(1, 10000))
6328 job["nsr_id"] = nsr_id
6329 job_dict = {jl["job_name"]: jl for jl in job_list}
6330 if await self.prometheus.update(job_dict):
6331 return list(job_dict.keys())
David Garciaaae391f2020-11-09 11:12:54 +01006332
6333 def get_vca_cloud_and_credentials(self, vim_account_id: str) -> (str, str):
6334 """
6335 Get VCA Cloud and VCA Cloud Credentials for the VIM account
6336
6337 :param: vim_account_id: VIM Account ID
6338
6339 :return: (cloud_name, cloud_credential)
6340 """
bravof922c4172020-11-24 21:21:43 -03006341 config = VimAccountDB.get_vim_account_with_id(vim_account_id).get("config", {})
David Garciaaae391f2020-11-09 11:12:54 +01006342 return config.get("vca_cloud"), config.get("vca_cloud_credential")
6343
6344 def get_vca_k8s_cloud_and_credentials(self, vim_account_id: str) -> (str, str):
6345 """
6346 Get VCA K8s Cloud and VCA K8s Cloud Credentials for the VIM account
6347
6348 :param: vim_account_id: VIM Account ID
6349
6350 :return: (cloud_name, cloud_credential)
6351 """
bravof922c4172020-11-24 21:21:43 -03006352 config = VimAccountDB.get_vim_account_with_id(vim_account_id).get("config", {})
David Garciaaae391f2020-11-09 11:12:54 +01006353 return config.get("vca_k8s_cloud"), config.get("vca_k8s_cloud_credential")