blob: e530b8cef7eeccdb254a0998c5c609e380a19f28 [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 Garcia444bf962021-11-11 16:35:26 +010020from typing import Any, Dict, List
tierno59d22d22018-09-25 18:10:19 +020021import yaml
22import logging
23import logging.handlers
tierno59d22d22018-09-25 18:10:19 +020024import traceback
David Garciad4816682019-12-09 14:57:43 +010025import json
garciadeblas5697b8b2021-03-24 09:17:02 +010026from jinja2 import (
27 Environment,
28 TemplateError,
29 TemplateNotFound,
30 StrictUndefined,
31 UndefinedError,
32)
tierno59d22d22018-09-25 18:10:19 +020033
tierno77677d92019-08-22 13:46:35 +000034from osm_lcm import ROclient
David Garciab4ebcd02021-10-28 02:00:43 +020035from osm_lcm.data_utils.nsr import (
36 get_deployed_kdu,
37 get_deployed_vca,
38 get_deployed_vca_list,
39 get_nsd,
40)
41from osm_lcm.data_utils.vca import (
42 DeployedComponent,
43 DeployedK8sResource,
44 DeployedVCA,
45 EELevel,
46 Relation,
47 EERelation,
48 safe_get_ee_relation,
49)
tierno69f0d382020-05-07 13:08:09 +000050from osm_lcm.ng_ro import NgRoClient, NgRoException
garciadeblas5697b8b2021-03-24 09:17:02 +010051from osm_lcm.lcm_utils import (
52 LcmException,
53 LcmExceptionNoMgmtIP,
54 LcmBase,
55 deep_get,
56 get_iterable,
57 populate_dict,
58)
David Garciab4ebcd02021-10-28 02:00:43 +020059from osm_lcm.data_utils.nsd import (
60 get_ns_configuration_relation_list,
61 get_vnf_profile,
62 get_vnf_profiles,
63)
garciadeblas5697b8b2021-03-24 09:17:02 +010064from osm_lcm.data_utils.vnfd import (
David Garciab4ebcd02021-10-28 02:00:43 +020065 get_relation_list,
garciadeblas5697b8b2021-03-24 09:17:02 +010066 get_vdu_list,
67 get_vdu_profile,
68 get_ee_sorted_initial_config_primitive_list,
69 get_ee_sorted_terminate_config_primitive_list,
70 get_kdu_list,
71 get_virtual_link_profiles,
72 get_vdu,
73 get_configuration,
74 get_vdu_index,
75 get_scaling_aspect,
76 get_number_of_instances,
77 get_juju_ee_ref,
David Garciab4ebcd02021-10-28 02:00:43 +020078 get_kdu_resource_profile,
garciadeblas5697b8b2021-03-24 09:17:02 +010079)
bravof922c4172020-11-24 21:21:43 -030080from osm_lcm.data_utils.list_utils import find_in_list
aktas5f75f102021-03-15 11:26:10 +030081from osm_lcm.data_utils.vnfr import get_osm_params, get_vdur_index, get_kdur
bravof922c4172020-11-24 21:21:43 -030082from osm_lcm.data_utils.dict_utils import parse_yaml_strings
83from osm_lcm.data_utils.database.vim_account import VimAccountDB
David Garciab4ebcd02021-10-28 02:00:43 +020084from n2vc.definitions import RelationEndpoint
calvinosanch9f9c6f22019-11-04 13:37:39 +010085from n2vc.k8s_helm_conn import K8sHelmConnector
lloretgalleg18ebc3a2020-10-22 09:54:51 +000086from n2vc.k8s_helm3_conn import K8sHelm3Connector
Adam Israelbaacc302019-12-01 12:41:39 -050087from n2vc.k8s_juju_conn import K8sJujuConnector
tierno59d22d22018-09-25 18:10:19 +020088
tierno27246d82018-09-27 15:59:09 +020089from osm_common.dbbase import DbException
tierno59d22d22018-09-25 18:10:19 +020090from osm_common.fsbase import FsException
quilesj7e13aeb2019-10-08 13:34:55 +020091
bravof922c4172020-11-24 21:21:43 -030092from osm_lcm.data_utils.database.database import Database
93from osm_lcm.data_utils.filesystem.filesystem import Filesystem
94
quilesj7e13aeb2019-10-08 13:34:55 +020095from n2vc.n2vc_juju_conn import N2VCJujuConnector
tiernof59ad6c2020-04-08 12:50:52 +000096from n2vc.exceptions import N2VCException, N2VCNotFound, K8sException
tierno59d22d22018-09-25 18:10:19 +020097
tierno588547c2020-07-01 15:30:20 +000098from osm_lcm.lcm_helm_conn import LCMHelmConn
bravof73bac502021-05-11 07:38:47 -040099from osm_lcm.prometheus import parse_job
tierno588547c2020-07-01 15:30:20 +0000100
tierno27246d82018-09-27 15:59:09 +0200101from copy import copy, deepcopy
tierno59d22d22018-09-25 18:10:19 +0200102from time import time
tierno27246d82018-09-27 15:59:09 +0200103from uuid import uuid4
lloretgalleg7c121132020-07-08 07:53:22 +0000104
tiernob996d942020-07-03 14:52:28 +0000105from random import randint
tierno59d22d22018-09-25 18:10:19 +0200106
tierno69f0d382020-05-07 13:08:09 +0000107__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
tierno59d22d22018-09-25 18:10:19 +0200108
109
110class NsLcm(LcmBase):
garciadeblas5697b8b2021-03-24 09:17:02 +0100111 timeout_vca_on_error = (
112 5 * 60
113 ) # Time for charm from first time at blocked,error status to mark as failed
114 timeout_ns_deploy = 2 * 3600 # default global timeout for deployment a ns
115 timeout_ns_terminate = 1800 # default global timeout for un deployment a ns
garciadeblasf9b04952019-04-09 18:53:58 +0200116 timeout_charm_delete = 10 * 60
David Garciaf6919842020-05-21 16:41:07 +0200117 timeout_primitive = 30 * 60 # timeout for primitive execution
garciadeblas5697b8b2021-03-24 09:17:02 +0100118 timeout_progress_primitive = (
119 10 * 60
120 ) # timeout for some progress in a primitive execution
tierno59d22d22018-09-25 18:10:19 +0200121
kuuseac3a8882019-10-03 10:48:06 +0200122 SUBOPERATION_STATUS_NOT_FOUND = -1
123 SUBOPERATION_STATUS_NEW = -2
124 SUBOPERATION_STATUS_SKIP = -3
tiernoa2143262020-03-27 16:20:40 +0000125 task_name_deploy_vca = "Deploying VCA"
kuuseac3a8882019-10-03 10:48:06 +0200126
bravof73bac502021-05-11 07:38:47 -0400127 def __init__(self, msg, lcm_tasks, config, loop):
tierno59d22d22018-09-25 18:10:19 +0200128 """
129 Init, Connect to database, filesystem storage, and messaging
130 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
131 :return: None
132 """
garciadeblas5697b8b2021-03-24 09:17:02 +0100133 super().__init__(msg=msg, logger=logging.getLogger("lcm.ns"))
quilesj7e13aeb2019-10-08 13:34:55 +0200134
bravof922c4172020-11-24 21:21:43 -0300135 self.db = Database().instance.db
136 self.fs = Filesystem().instance.fs
tierno59d22d22018-09-25 18:10:19 +0200137 self.loop = loop
138 self.lcm_tasks = lcm_tasks
tierno744303e2020-01-13 16:46:31 +0000139 self.timeout = config["timeout"]
140 self.ro_config = config["ro_config"]
tierno69f0d382020-05-07 13:08:09 +0000141 self.ng_ro = config["ro_config"].get("ng")
tierno744303e2020-01-13 16:46:31 +0000142 self.vca_config = config["VCA"].copy()
tierno59d22d22018-09-25 18:10:19 +0200143
quilesj7e13aeb2019-10-08 13:34:55 +0200144 # create N2VC connector
David Garciaaae391f2020-11-09 11:12:54 +0100145 self.n2vc = N2VCJujuConnector(
tierno59d22d22018-09-25 18:10:19 +0200146 log=self.logger,
quilesj7e13aeb2019-10-08 13:34:55 +0200147 loop=self.loop,
bravof922c4172020-11-24 21:21:43 -0300148 on_update_db=self._on_update_n2vc_db,
149 fs=self.fs,
garciadeblas5697b8b2021-03-24 09:17:02 +0100150 db=self.db,
tierno59d22d22018-09-25 18:10:19 +0200151 )
quilesj7e13aeb2019-10-08 13:34:55 +0200152
tierno588547c2020-07-01 15:30:20 +0000153 self.conn_helm_ee = LCMHelmConn(
tierno588547c2020-07-01 15:30:20 +0000154 log=self.logger,
155 loop=self.loop,
tierno588547c2020-07-01 15:30:20 +0000156 vca_config=self.vca_config,
garciadeblas5697b8b2021-03-24 09:17:02 +0100157 on_update_db=self._on_update_n2vc_db,
tierno588547c2020-07-01 15:30:20 +0000158 )
159
lloretgalleg18ebc3a2020-10-22 09:54:51 +0000160 self.k8sclusterhelm2 = K8sHelmConnector(
calvinosanch9f9c6f22019-11-04 13:37:39 +0100161 kubectl_command=self.vca_config.get("kubectlpath"),
162 helm_command=self.vca_config.get("helmpath"),
calvinosanch9f9c6f22019-11-04 13:37:39 +0100163 log=self.logger,
calvinosanch9f9c6f22019-11-04 13:37:39 +0100164 on_update_db=None,
bravof922c4172020-11-24 21:21:43 -0300165 fs=self.fs,
garciadeblas5697b8b2021-03-24 09:17:02 +0100166 db=self.db,
calvinosanch9f9c6f22019-11-04 13:37:39 +0100167 )
168
lloretgalleg18ebc3a2020-10-22 09:54:51 +0000169 self.k8sclusterhelm3 = K8sHelm3Connector(
170 kubectl_command=self.vca_config.get("kubectlpath"),
171 helm_command=self.vca_config.get("helm3path"),
172 fs=self.fs,
173 log=self.logger,
174 db=self.db,
175 on_update_db=None,
176 )
177
Adam Israelbaacc302019-12-01 12:41:39 -0500178 self.k8sclusterjuju = K8sJujuConnector(
179 kubectl_command=self.vca_config.get("kubectlpath"),
180 juju_command=self.vca_config.get("jujupath"),
Adam Israelbaacc302019-12-01 12:41:39 -0500181 log=self.logger,
David Garciaba89cbb2020-10-16 13:05:34 +0200182 loop=self.loop,
ksaikiranr656b6dd2021-02-19 10:25:18 +0530183 on_update_db=self._on_update_k8s_db,
bravof922c4172020-11-24 21:21:43 -0300184 fs=self.fs,
garciadeblas5697b8b2021-03-24 09:17:02 +0100185 db=self.db,
Adam Israelbaacc302019-12-01 12:41:39 -0500186 )
187
tiernoa2143262020-03-27 16:20:40 +0000188 self.k8scluster_map = {
lloretgalleg18ebc3a2020-10-22 09:54:51 +0000189 "helm-chart": self.k8sclusterhelm2,
190 "helm-chart-v3": self.k8sclusterhelm3,
191 "chart": self.k8sclusterhelm3,
tiernoa2143262020-03-27 16:20:40 +0000192 "juju-bundle": self.k8sclusterjuju,
193 "juju": self.k8sclusterjuju,
194 }
tierno588547c2020-07-01 15:30:20 +0000195
196 self.vca_map = {
197 "lxc_proxy_charm": self.n2vc,
198 "native_charm": self.n2vc,
199 "k8s_proxy_charm": self.n2vc,
lloretgalleg18ebc3a2020-10-22 09:54:51 +0000200 "helm": self.conn_helm_ee,
garciadeblas5697b8b2021-03-24 09:17:02 +0100201 "helm-v3": self.conn_helm_ee,
tierno588547c2020-07-01 15:30:20 +0000202 }
203
quilesj7e13aeb2019-10-08 13:34:55 +0200204 # create RO client
bravof922c4172020-11-24 21:21:43 -0300205 self.RO = NgRoClient(self.loop, **self.ro_config)
tierno59d22d22018-09-25 18:10:19 +0200206
tierno2357f4e2020-10-19 16:38:59 +0000207 @staticmethod
208 def increment_ip_mac(ip_mac, vm_index=1):
209 if not isinstance(ip_mac, str):
210 return ip_mac
211 try:
212 # try with ipv4 look for last dot
213 i = ip_mac.rfind(".")
214 if i > 0:
215 i += 1
216 return "{}{}".format(ip_mac[:i], int(ip_mac[i:]) + vm_index)
217 # try with ipv6 or mac look for last colon. Operate in hex
218 i = ip_mac.rfind(":")
219 if i > 0:
220 i += 1
221 # format in hex, len can be 2 for mac or 4 for ipv6
garciadeblas5697b8b2021-03-24 09:17:02 +0100222 return ("{}{:0" + str(len(ip_mac) - i) + "x}").format(
223 ip_mac[:i], int(ip_mac[i:], 16) + vm_index
224 )
tierno2357f4e2020-10-19 16:38:59 +0000225 except Exception:
226 pass
227 return None
228
quilesj3655ae02019-12-12 16:08:35 +0000229 def _on_update_ro_db(self, nsrs_id, ro_descriptor):
quilesj7e13aeb2019-10-08 13:34:55 +0200230
quilesj3655ae02019-12-12 16:08:35 +0000231 # self.logger.debug('_on_update_ro_db(nsrs_id={}'.format(nsrs_id))
232
233 try:
234 # TODO filter RO descriptor fields...
235
236 # write to database
237 db_dict = dict()
238 # db_dict['deploymentStatus'] = yaml.dump(ro_descriptor, default_flow_style=False, indent=2)
garciadeblas5697b8b2021-03-24 09:17:02 +0100239 db_dict["deploymentStatus"] = ro_descriptor
quilesj3655ae02019-12-12 16:08:35 +0000240 self.update_db_2("nsrs", nsrs_id, db_dict)
241
242 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100243 self.logger.warn(
244 "Cannot write database RO deployment for ns={} -> {}".format(nsrs_id, e)
245 )
quilesj3655ae02019-12-12 16:08:35 +0000246
David Garciac1fe90a2021-03-31 19:12:02 +0200247 async def _on_update_n2vc_db(self, table, filter, path, updated_data, vca_id=None):
quilesj3655ae02019-12-12 16:08:35 +0000248
quilesj69a722c2020-01-09 08:30:17 +0000249 # remove last dot from path (if exists)
garciadeblas5697b8b2021-03-24 09:17:02 +0100250 if path.endswith("."):
quilesj69a722c2020-01-09 08:30:17 +0000251 path = path[:-1]
252
quilesj3655ae02019-12-12 16:08:35 +0000253 # self.logger.debug('_on_update_n2vc_db(table={}, filter={}, path={}, updated_data={}'
254 # .format(table, filter, path, updated_data))
quilesj3655ae02019-12-12 16:08:35 +0000255 try:
256
garciadeblas5697b8b2021-03-24 09:17:02 +0100257 nsr_id = filter.get("_id")
quilesj3655ae02019-12-12 16:08:35 +0000258
259 # read ns record from database
garciadeblas5697b8b2021-03-24 09:17:02 +0100260 nsr = self.db.get_one(table="nsrs", q_filter=filter)
261 current_ns_status = nsr.get("nsState")
quilesj3655ae02019-12-12 16:08:35 +0000262
263 # get vca status for NS
garciadeblas5697b8b2021-03-24 09:17:02 +0100264 status_dict = await self.n2vc.get_status(
265 namespace="." + nsr_id, yaml_format=False, vca_id=vca_id
266 )
quilesj3655ae02019-12-12 16:08:35 +0000267
268 # vcaStatus
269 db_dict = dict()
garciadeblas5697b8b2021-03-24 09:17:02 +0100270 db_dict["vcaStatus"] = status_dict
271 await self.n2vc.update_vca_status(db_dict["vcaStatus"], vca_id=vca_id)
quilesj3655ae02019-12-12 16:08:35 +0000272
273 # update configurationStatus for this VCA
274 try:
garciadeblas5697b8b2021-03-24 09:17:02 +0100275 vca_index = int(path[path.rfind(".") + 1 :])
quilesj3655ae02019-12-12 16:08:35 +0000276
garciadeblas5697b8b2021-03-24 09:17:02 +0100277 vca_list = deep_get(
278 target_dict=nsr, key_list=("_admin", "deployed", "VCA")
279 )
280 vca_status = vca_list[vca_index].get("status")
quilesj3655ae02019-12-12 16:08:35 +0000281
garciadeblas5697b8b2021-03-24 09:17:02 +0100282 configuration_status_list = nsr.get("configurationStatus")
283 config_status = configuration_status_list[vca_index].get("status")
quilesj3655ae02019-12-12 16:08:35 +0000284
garciadeblas5697b8b2021-03-24 09:17:02 +0100285 if config_status == "BROKEN" and vca_status != "failed":
286 db_dict["configurationStatus"][vca_index] = "READY"
287 elif config_status != "BROKEN" and vca_status == "failed":
288 db_dict["configurationStatus"][vca_index] = "BROKEN"
quilesj3655ae02019-12-12 16:08:35 +0000289 except Exception as e:
290 # not update configurationStatus
garciadeblas5697b8b2021-03-24 09:17:02 +0100291 self.logger.debug("Error updating vca_index (ignore): {}".format(e))
quilesj3655ae02019-12-12 16:08:35 +0000292
293 # if nsState = 'READY' check if juju is reporting some error => nsState = 'DEGRADED'
294 # if nsState = 'DEGRADED' check if all is OK
295 is_degraded = False
garciadeblas5697b8b2021-03-24 09:17:02 +0100296 if current_ns_status in ("READY", "DEGRADED"):
297 error_description = ""
quilesj3655ae02019-12-12 16:08:35 +0000298 # check machines
garciadeblas5697b8b2021-03-24 09:17:02 +0100299 if status_dict.get("machines"):
300 for machine_id in status_dict.get("machines"):
301 machine = status_dict.get("machines").get(machine_id)
quilesj3655ae02019-12-12 16:08:35 +0000302 # check machine agent-status
garciadeblas5697b8b2021-03-24 09:17:02 +0100303 if machine.get("agent-status"):
304 s = machine.get("agent-status").get("status")
305 if s != "started":
quilesj3655ae02019-12-12 16:08:35 +0000306 is_degraded = True
garciadeblas5697b8b2021-03-24 09:17:02 +0100307 error_description += (
308 "machine {} agent-status={} ; ".format(
309 machine_id, s
310 )
311 )
quilesj3655ae02019-12-12 16:08:35 +0000312 # check machine instance status
garciadeblas5697b8b2021-03-24 09:17:02 +0100313 if machine.get("instance-status"):
314 s = machine.get("instance-status").get("status")
315 if s != "running":
quilesj3655ae02019-12-12 16:08:35 +0000316 is_degraded = True
garciadeblas5697b8b2021-03-24 09:17:02 +0100317 error_description += (
318 "machine {} instance-status={} ; ".format(
319 machine_id, s
320 )
321 )
quilesj3655ae02019-12-12 16:08:35 +0000322 # check applications
garciadeblas5697b8b2021-03-24 09:17:02 +0100323 if status_dict.get("applications"):
324 for app_id in status_dict.get("applications"):
325 app = status_dict.get("applications").get(app_id)
quilesj3655ae02019-12-12 16:08:35 +0000326 # check application status
garciadeblas5697b8b2021-03-24 09:17:02 +0100327 if app.get("status"):
328 s = app.get("status").get("status")
329 if s != "active":
quilesj3655ae02019-12-12 16:08:35 +0000330 is_degraded = True
garciadeblas5697b8b2021-03-24 09:17:02 +0100331 error_description += (
332 "application {} status={} ; ".format(app_id, s)
333 )
quilesj3655ae02019-12-12 16:08:35 +0000334
335 if error_description:
garciadeblas5697b8b2021-03-24 09:17:02 +0100336 db_dict["errorDescription"] = error_description
337 if current_ns_status == "READY" and is_degraded:
338 db_dict["nsState"] = "DEGRADED"
339 if current_ns_status == "DEGRADED" and not is_degraded:
340 db_dict["nsState"] = "READY"
quilesj3655ae02019-12-12 16:08:35 +0000341
342 # write to database
343 self.update_db_2("nsrs", nsr_id, db_dict)
344
tierno51183952020-04-03 15:48:18 +0000345 except (asyncio.CancelledError, asyncio.TimeoutError):
346 raise
quilesj3655ae02019-12-12 16:08:35 +0000347 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100348 self.logger.warn("Error updating NS state for ns={}: {}".format(nsr_id, e))
quilesj7e13aeb2019-10-08 13:34:55 +0200349
garciadeblas5697b8b2021-03-24 09:17:02 +0100350 async def _on_update_k8s_db(
351 self, cluster_uuid, kdu_instance, filter=None, vca_id=None
352 ):
ksaikiranr656b6dd2021-02-19 10:25:18 +0530353 """
354 Updating vca status in NSR record
355 :param cluster_uuid: UUID of a k8s cluster
356 :param kdu_instance: The unique name of the KDU instance
357 :param filter: To get nsr_id
358 :return: none
359 """
360
361 # self.logger.debug("_on_update_k8s_db(cluster_uuid={}, kdu_instance={}, filter={}"
362 # .format(cluster_uuid, kdu_instance, filter))
363
364 try:
garciadeblas5697b8b2021-03-24 09:17:02 +0100365 nsr_id = filter.get("_id")
ksaikiranr656b6dd2021-02-19 10:25:18 +0530366
367 # get vca status for NS
David Garciac1fe90a2021-03-31 19:12:02 +0200368 vca_status = await self.k8sclusterjuju.status_kdu(
369 cluster_uuid,
370 kdu_instance,
371 complete_status=True,
372 yaml_format=False,
373 vca_id=vca_id,
374 )
ksaikiranr656b6dd2021-02-19 10:25:18 +0530375 # vcaStatus
376 db_dict = dict()
garciadeblas5697b8b2021-03-24 09:17:02 +0100377 db_dict["vcaStatus"] = {nsr_id: vca_status}
ksaikiranr656b6dd2021-02-19 10:25:18 +0530378
David Garciac1fe90a2021-03-31 19:12:02 +0200379 await self.k8sclusterjuju.update_vca_status(
garciadeblas5697b8b2021-03-24 09:17:02 +0100380 db_dict["vcaStatus"],
David Garciac1fe90a2021-03-31 19:12:02 +0200381 kdu_instance,
382 vca_id=vca_id,
383 )
ksaikiranr656b6dd2021-02-19 10:25:18 +0530384
385 # write to database
386 self.update_db_2("nsrs", nsr_id, db_dict)
387
388 except (asyncio.CancelledError, asyncio.TimeoutError):
389 raise
390 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100391 self.logger.warn("Error updating NS state for ns={}: {}".format(nsr_id, e))
ksaikiranr656b6dd2021-02-19 10:25:18 +0530392
tierno72ef84f2020-10-06 08:22:07 +0000393 @staticmethod
394 def _parse_cloud_init(cloud_init_text, additional_params, vnfd_id, vdu_id):
395 try:
396 env = Environment(undefined=StrictUndefined)
397 template = env.from_string(cloud_init_text)
398 return template.render(additional_params or {})
399 except UndefinedError as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100400 raise LcmException(
401 "Variable {} at vnfd[id={}]:vdu[id={}]:cloud-init/cloud-init-"
402 "file, must be provided in the instantiation parameters inside the "
403 "'additionalParamsForVnf/Vdu' block".format(e, vnfd_id, vdu_id)
404 )
tierno72ef84f2020-10-06 08:22:07 +0000405 except (TemplateError, TemplateNotFound) as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100406 raise LcmException(
407 "Error parsing Jinja2 to cloud-init content at vnfd[id={}]:vdu[id={}]: {}".format(
408 vnfd_id, vdu_id, e
409 )
410 )
tierno72ef84f2020-10-06 08:22:07 +0000411
bravof922c4172020-11-24 21:21:43 -0300412 def _get_vdu_cloud_init_content(self, vdu, vnfd):
413 cloud_init_content = cloud_init_file = None
tierno72ef84f2020-10-06 08:22:07 +0000414 try:
tierno72ef84f2020-10-06 08:22:07 +0000415 if vdu.get("cloud-init-file"):
416 base_folder = vnfd["_admin"]["storage"]
bravof486707f2021-11-08 17:18:50 -0300417 if base_folder["pkg-dir"]:
418 cloud_init_file = "{}/{}/cloud_init/{}".format(
419 base_folder["folder"],
420 base_folder["pkg-dir"],
421 vdu["cloud-init-file"],
422 )
423 else:
424 cloud_init_file = "{}/Scripts/cloud_init/{}".format(
425 base_folder["folder"],
426 vdu["cloud-init-file"],
427 )
tierno72ef84f2020-10-06 08:22:07 +0000428 with self.fs.file_open(cloud_init_file, "r") as ci_file:
429 cloud_init_content = ci_file.read()
430 elif vdu.get("cloud-init"):
431 cloud_init_content = vdu["cloud-init"]
432
433 return cloud_init_content
434 except FsException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100435 raise LcmException(
436 "Error reading vnfd[id={}]:vdu[id={}]:cloud-init-file={}: {}".format(
437 vnfd["id"], vdu["id"], cloud_init_file, e
438 )
439 )
tierno72ef84f2020-10-06 08:22:07 +0000440
tierno72ef84f2020-10-06 08:22:07 +0000441 def _get_vdu_additional_params(self, db_vnfr, vdu_id):
garciadeblas5697b8b2021-03-24 09:17:02 +0100442 vdur = next(
443 vdur for vdur in db_vnfr.get("vdur") if vdu_id == vdur["vdu-id-ref"]
444 )
tierno72ef84f2020-10-06 08:22:07 +0000445 additional_params = vdur.get("additionalParams")
bravof922c4172020-11-24 21:21:43 -0300446 return parse_yaml_strings(additional_params)
tierno72ef84f2020-10-06 08:22:07 +0000447
gcalvino35be9152018-12-20 09:33:12 +0100448 def vnfd2RO(self, vnfd, new_id=None, additionalParams=None, nsrId=None):
tierno59d22d22018-09-25 18:10:19 +0200449 """
450 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
451 :param vnfd: input vnfd
452 :param new_id: overrides vnf id if provided
tierno8a518872018-12-21 13:42:14 +0000453 :param additionalParams: Instantiation params for VNFs provided
gcalvino35be9152018-12-20 09:33:12 +0100454 :param nsrId: Id of the NSR
tierno59d22d22018-09-25 18:10:19 +0200455 :return: copy of vnfd
456 """
tierno72ef84f2020-10-06 08:22:07 +0000457 vnfd_RO = deepcopy(vnfd)
458 # remove unused by RO configuration, monitoring, scaling and internal keys
459 vnfd_RO.pop("_id", None)
460 vnfd_RO.pop("_admin", None)
tierno72ef84f2020-10-06 08:22:07 +0000461 vnfd_RO.pop("monitoring-param", None)
462 vnfd_RO.pop("scaling-group-descriptor", None)
463 vnfd_RO.pop("kdu", None)
464 vnfd_RO.pop("k8s-cluster", None)
465 if new_id:
466 vnfd_RO["id"] = new_id
tierno8a518872018-12-21 13:42:14 +0000467
tierno72ef84f2020-10-06 08:22:07 +0000468 # parse cloud-init or cloud-init-file with the provided variables using Jinja2
469 for vdu in get_iterable(vnfd_RO, "vdu"):
470 vdu.pop("cloud-init-file", None)
471 vdu.pop("cloud-init", None)
472 return vnfd_RO
tierno59d22d22018-09-25 18:10:19 +0200473
tierno2357f4e2020-10-19 16:38:59 +0000474 @staticmethod
475 def ip_profile_2_RO(ip_profile):
476 RO_ip_profile = deepcopy(ip_profile)
477 if "dns-server" in RO_ip_profile:
478 if isinstance(RO_ip_profile["dns-server"], list):
479 RO_ip_profile["dns-address"] = []
480 for ds in RO_ip_profile.pop("dns-server"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100481 RO_ip_profile["dns-address"].append(ds["address"])
tierno2357f4e2020-10-19 16:38:59 +0000482 else:
483 RO_ip_profile["dns-address"] = RO_ip_profile.pop("dns-server")
484 if RO_ip_profile.get("ip-version") == "ipv4":
485 RO_ip_profile["ip-version"] = "IPv4"
486 if RO_ip_profile.get("ip-version") == "ipv6":
487 RO_ip_profile["ip-version"] = "IPv6"
488 if "dhcp-params" in RO_ip_profile:
489 RO_ip_profile["dhcp"] = RO_ip_profile.pop("dhcp-params")
490 return RO_ip_profile
491
bravof922c4172020-11-24 21:21:43 -0300492 def _get_ro_vim_id_for_vim_account(self, vim_account):
493 db_vim = self.db.get_one("vim_accounts", {"_id": vim_account})
494 if db_vim["_admin"]["operationalState"] != "ENABLED":
garciadeblas5697b8b2021-03-24 09:17:02 +0100495 raise LcmException(
496 "VIM={} is not available. operationalState={}".format(
497 vim_account, db_vim["_admin"]["operationalState"]
498 )
499 )
bravof922c4172020-11-24 21:21:43 -0300500 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
501 return RO_vim_id
tierno59d22d22018-09-25 18:10:19 +0200502
bravof922c4172020-11-24 21:21:43 -0300503 def get_ro_wim_id_for_wim_account(self, wim_account):
504 if isinstance(wim_account, str):
505 db_wim = self.db.get_one("wim_accounts", {"_id": wim_account})
506 if db_wim["_admin"]["operationalState"] != "ENABLED":
garciadeblas5697b8b2021-03-24 09:17:02 +0100507 raise LcmException(
508 "WIM={} is not available. operationalState={}".format(
509 wim_account, db_wim["_admin"]["operationalState"]
510 )
511 )
bravof922c4172020-11-24 21:21:43 -0300512 RO_wim_id = db_wim["_admin"]["deployed"]["RO-account"]
513 return RO_wim_id
514 else:
515 return wim_account
tierno59d22d22018-09-25 18:10:19 +0200516
tierno2357f4e2020-10-19 16:38:59 +0000517 def scale_vnfr(self, db_vnfr, vdu_create=None, vdu_delete=None, mark_delete=False):
tierno27246d82018-09-27 15:59:09 +0200518
tierno2357f4e2020-10-19 16:38:59 +0000519 db_vdu_push_list = []
520 db_update = {"_admin.modified": time()}
521 if vdu_create:
522 for vdu_id, vdu_count in vdu_create.items():
garciadeblas5697b8b2021-03-24 09:17:02 +0100523 vdur = next(
524 (
525 vdur
526 for vdur in reversed(db_vnfr["vdur"])
527 if vdur["vdu-id-ref"] == vdu_id
528 ),
529 None,
530 )
tierno2357f4e2020-10-19 16:38:59 +0000531 if not vdur:
garciadeblas5697b8b2021-03-24 09:17:02 +0100532 raise LcmException(
533 "Error scaling OUT VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
534 vdu_id
535 )
536 )
tierno2357f4e2020-10-19 16:38:59 +0000537
538 for count in range(vdu_count):
539 vdur_copy = deepcopy(vdur)
540 vdur_copy["status"] = "BUILD"
541 vdur_copy["status-detailed"] = None
Guillermo Calvino57c68152022-01-26 17:40:31 +0100542 vdur_copy["ip-address"] = None
tierno683eb392020-09-25 12:33:15 +0000543 vdur_copy["_id"] = str(uuid4())
tierno2357f4e2020-10-19 16:38:59 +0000544 vdur_copy["count-index"] += count + 1
garciadeblas5697b8b2021-03-24 09:17:02 +0100545 vdur_copy["id"] = "{}-{}".format(
546 vdur_copy["vdu-id-ref"], vdur_copy["count-index"]
547 )
tierno2357f4e2020-10-19 16:38:59 +0000548 vdur_copy.pop("vim_info", None)
549 for iface in vdur_copy["interfaces"]:
550 if iface.get("fixed-ip"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100551 iface["ip-address"] = self.increment_ip_mac(
552 iface["ip-address"], count + 1
553 )
tierno2357f4e2020-10-19 16:38:59 +0000554 else:
555 iface.pop("ip-address", None)
556 if iface.get("fixed-mac"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100557 iface["mac-address"] = self.increment_ip_mac(
558 iface["mac-address"], count + 1
559 )
tierno2357f4e2020-10-19 16:38:59 +0000560 else:
561 iface.pop("mac-address", None)
garciadeblas5697b8b2021-03-24 09:17:02 +0100562 iface.pop(
563 "mgmt_vnf", None
564 ) # only first vdu can be managment of vnf
tierno2357f4e2020-10-19 16:38:59 +0000565 db_vdu_push_list.append(vdur_copy)
566 # self.logger.debug("scale out, adding vdu={}".format(vdur_copy))
tierno27246d82018-09-27 15:59:09 +0200567 if vdu_delete:
tierno2357f4e2020-10-19 16:38:59 +0000568 for vdu_id, vdu_count in vdu_delete.items():
569 if mark_delete:
garciadeblas5697b8b2021-03-24 09:17:02 +0100570 indexes_to_delete = [
571 iv[0]
572 for iv in enumerate(db_vnfr["vdur"])
573 if iv[1]["vdu-id-ref"] == vdu_id
574 ]
575 db_update.update(
576 {
577 "vdur.{}.status".format(i): "DELETING"
578 for i in indexes_to_delete[-vdu_count:]
579 }
580 )
tierno2357f4e2020-10-19 16:38:59 +0000581 else:
582 # it must be deleted one by one because common.db does not allow otherwise
garciadeblas5697b8b2021-03-24 09:17:02 +0100583 vdus_to_delete = [
584 v
585 for v in reversed(db_vnfr["vdur"])
586 if v["vdu-id-ref"] == vdu_id
587 ]
tierno2357f4e2020-10-19 16:38:59 +0000588 for vdu in vdus_to_delete[:vdu_count]:
garciadeblas5697b8b2021-03-24 09:17:02 +0100589 self.db.set_one(
590 "vnfrs",
591 {"_id": db_vnfr["_id"]},
592 None,
593 pull={"vdur": {"_id": vdu["_id"]}},
594 )
tierno2357f4e2020-10-19 16:38:59 +0000595 db_push = {"vdur": db_vdu_push_list} if db_vdu_push_list else None
596 self.db.set_one("vnfrs", {"_id": db_vnfr["_id"]}, db_update, push_list=db_push)
597 # modify passed dictionary db_vnfr
598 db_vnfr_ = self.db.get_one("vnfrs", {"_id": db_vnfr["_id"]})
599 db_vnfr["vdur"] = db_vnfr_["vdur"]
tierno27246d82018-09-27 15:59:09 +0200600
tiernof578e552018-11-08 19:07:20 +0100601 def ns_update_nsr(self, ns_update_nsr, db_nsr, nsr_desc_RO):
602 """
603 Updates database nsr with the RO info for the created vld
604 :param ns_update_nsr: dictionary to be filled with the updated info
605 :param db_nsr: content of db_nsr. This is also modified
606 :param nsr_desc_RO: nsr descriptor from RO
607 :return: Nothing, LcmException is raised on errors
608 """
609
610 for vld_index, vld in enumerate(get_iterable(db_nsr, "vld")):
611 for net_RO in get_iterable(nsr_desc_RO, "nets"):
612 if vld["id"] != net_RO.get("ns_net_osm_id"):
613 continue
614 vld["vim-id"] = net_RO.get("vim_net_id")
615 vld["name"] = net_RO.get("vim_name")
616 vld["status"] = net_RO.get("status")
617 vld["status-detailed"] = net_RO.get("error_msg")
618 ns_update_nsr["vld.{}".format(vld_index)] = vld
619 break
620 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100621 raise LcmException(
622 "ns_update_nsr: Not found vld={} at RO info".format(vld["id"])
623 )
tiernof578e552018-11-08 19:07:20 +0100624
tiernoe876f672020-02-13 14:34:48 +0000625 def set_vnfr_at_error(self, db_vnfrs, error_text):
626 try:
627 for db_vnfr in db_vnfrs.values():
628 vnfr_update = {"status": "ERROR"}
629 for vdu_index, vdur in enumerate(get_iterable(db_vnfr, "vdur")):
630 if "status" not in vdur:
631 vdur["status"] = "ERROR"
632 vnfr_update["vdur.{}.status".format(vdu_index)] = "ERROR"
633 if error_text:
634 vdur["status-detailed"] = str(error_text)
garciadeblas5697b8b2021-03-24 09:17:02 +0100635 vnfr_update[
636 "vdur.{}.status-detailed".format(vdu_index)
637 ] = "ERROR"
tiernoe876f672020-02-13 14:34:48 +0000638 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
639 except DbException as e:
640 self.logger.error("Cannot update vnf. {}".format(e))
641
tierno59d22d22018-09-25 18:10:19 +0200642 def ns_update_vnfr(self, db_vnfrs, nsr_desc_RO):
643 """
644 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 +0200645 :param db_vnfrs: dictionary with member-vnf-index: vnfr-content
646 :param nsr_desc_RO: nsr descriptor from RO
647 :return: Nothing, LcmException is raised on errors
tierno59d22d22018-09-25 18:10:19 +0200648 """
649 for vnf_index, db_vnfr in db_vnfrs.items():
650 for vnf_RO in nsr_desc_RO["vnfs"]:
tierno27246d82018-09-27 15:59:09 +0200651 if vnf_RO["member_vnf_index"] != vnf_index:
652 continue
653 vnfr_update = {}
tiernof578e552018-11-08 19:07:20 +0100654 if vnf_RO.get("ip_address"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100655 db_vnfr["ip-address"] = vnfr_update["ip-address"] = vnf_RO[
656 "ip_address"
657 ].split(";")[0]
tiernof578e552018-11-08 19:07:20 +0100658 elif not db_vnfr.get("ip-address"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100659 if db_vnfr.get("vdur"): # if not VDUs, there is not ip_address
660 raise LcmExceptionNoMgmtIP(
661 "ns member_vnf_index '{}' has no IP address".format(
662 vnf_index
663 )
664 )
tierno59d22d22018-09-25 18:10:19 +0200665
tierno27246d82018-09-27 15:59:09 +0200666 for vdu_index, vdur in enumerate(get_iterable(db_vnfr, "vdur")):
667 vdur_RO_count_index = 0
668 if vdur.get("pdu-type"):
669 continue
670 for vdur_RO in get_iterable(vnf_RO, "vms"):
671 if vdur["vdu-id-ref"] != vdur_RO["vdu_osm_id"]:
672 continue
673 if vdur["count-index"] != vdur_RO_count_index:
674 vdur_RO_count_index += 1
675 continue
676 vdur["vim-id"] = vdur_RO.get("vim_vm_id")
tierno1674de82019-04-09 13:03:14 +0000677 if vdur_RO.get("ip_address"):
678 vdur["ip-address"] = vdur_RO["ip_address"].split(";")[0]
tierno274ed572019-04-04 13:33:27 +0000679 else:
680 vdur["ip-address"] = None
tierno27246d82018-09-27 15:59:09 +0200681 vdur["vdu-id-ref"] = vdur_RO.get("vdu_osm_id")
682 vdur["name"] = vdur_RO.get("vim_name")
683 vdur["status"] = vdur_RO.get("status")
684 vdur["status-detailed"] = vdur_RO.get("error_msg")
685 for ifacer in get_iterable(vdur, "interfaces"):
686 for interface_RO in get_iterable(vdur_RO, "interfaces"):
687 if ifacer["name"] == interface_RO.get("internal_name"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100688 ifacer["ip-address"] = interface_RO.get(
689 "ip_address"
690 )
691 ifacer["mac-address"] = interface_RO.get(
692 "mac_address"
693 )
tierno27246d82018-09-27 15:59:09 +0200694 break
695 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100696 raise LcmException(
697 "ns_update_vnfr: Not found member_vnf_index={} vdur={} interface={} "
698 "from VIM info".format(
699 vnf_index, vdur["vdu-id-ref"], ifacer["name"]
700 )
701 )
tierno27246d82018-09-27 15:59:09 +0200702 vnfr_update["vdur.{}".format(vdu_index)] = vdur
703 break
704 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100705 raise LcmException(
706 "ns_update_vnfr: Not found member_vnf_index={} vdur={} count_index={} from "
707 "VIM info".format(
708 vnf_index, vdur["vdu-id-ref"], vdur["count-index"]
709 )
710 )
tiernof578e552018-11-08 19:07:20 +0100711
712 for vld_index, vld in enumerate(get_iterable(db_vnfr, "vld")):
713 for net_RO in get_iterable(nsr_desc_RO, "nets"):
714 if vld["id"] != net_RO.get("vnf_net_osm_id"):
715 continue
716 vld["vim-id"] = net_RO.get("vim_net_id")
717 vld["name"] = net_RO.get("vim_name")
718 vld["status"] = net_RO.get("status")
719 vld["status-detailed"] = net_RO.get("error_msg")
720 vnfr_update["vld.{}".format(vld_index)] = vld
721 break
722 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100723 raise LcmException(
724 "ns_update_vnfr: Not found member_vnf_index={} vld={} from VIM info".format(
725 vnf_index, vld["id"]
726 )
727 )
tiernof578e552018-11-08 19:07:20 +0100728
tierno27246d82018-09-27 15:59:09 +0200729 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
730 break
tierno59d22d22018-09-25 18:10:19 +0200731
732 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100733 raise LcmException(
734 "ns_update_vnfr: Not found member_vnf_index={} from VIM info".format(
735 vnf_index
736 )
737 )
tierno59d22d22018-09-25 18:10:19 +0200738
tierno5ee02052019-12-05 19:55:02 +0000739 def _get_ns_config_info(self, nsr_id):
tiernoc3f2a822019-11-05 13:45:04 +0000740 """
741 Generates a mapping between vnf,vdu elements and the N2VC id
tierno5ee02052019-12-05 19:55:02 +0000742 :param nsr_id: id of nsr to get last database _admin.deployed.VCA that contains this list
tiernoc3f2a822019-11-05 13:45:04 +0000743 :return: a dictionary with {osm-config-mapping: {}} where its element contains:
744 "<member-vnf-index>": <N2VC-id> for a vnf configuration, or
745 "<member-vnf-index>.<vdu.id>.<vdu replica(0, 1,..)>": <N2VC-id> for a vdu configuration
746 """
tierno5ee02052019-12-05 19:55:02 +0000747 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
748 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
tiernoc3f2a822019-11-05 13:45:04 +0000749 mapping = {}
750 ns_config_info = {"osm-config-mapping": mapping}
751 for vca in vca_deployed_list:
752 if not vca["member-vnf-index"]:
753 continue
754 if not vca["vdu_id"]:
755 mapping[vca["member-vnf-index"]] = vca["application"]
756 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100757 mapping[
758 "{}.{}.{}".format(
759 vca["member-vnf-index"], vca["vdu_id"], vca["vdu_count_index"]
760 )
761 ] = vca["application"]
tiernoc3f2a822019-11-05 13:45:04 +0000762 return ns_config_info
763
garciadeblas5697b8b2021-03-24 09:17:02 +0100764 async def _instantiate_ng_ro(
765 self,
766 logging_text,
767 nsr_id,
768 nsd,
769 db_nsr,
770 db_nslcmop,
771 db_vnfrs,
772 db_vnfds,
773 n2vc_key_list,
774 stage,
775 start_deploy,
776 timeout_ns_deploy,
777 ):
tierno2357f4e2020-10-19 16:38:59 +0000778
779 db_vims = {}
780
781 def get_vim_account(vim_account_id):
782 nonlocal db_vims
783 if vim_account_id in db_vims:
784 return db_vims[vim_account_id]
785 db_vim = self.db.get_one("vim_accounts", {"_id": vim_account_id})
786 db_vims[vim_account_id] = db_vim
787 return db_vim
788
789 # modify target_vld info with instantiation parameters
garciadeblas5697b8b2021-03-24 09:17:02 +0100790 def parse_vld_instantiation_params(
791 target_vim, target_vld, vld_params, target_sdn
792 ):
tierno2357f4e2020-10-19 16:38:59 +0000793 if vld_params.get("ip-profile"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100794 target_vld["vim_info"][target_vim]["ip_profile"] = vld_params[
795 "ip-profile"
796 ]
tierno2357f4e2020-10-19 16:38:59 +0000797 if vld_params.get("provider-network"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100798 target_vld["vim_info"][target_vim]["provider_network"] = vld_params[
799 "provider-network"
800 ]
tierno2357f4e2020-10-19 16:38:59 +0000801 if "sdn-ports" in vld_params["provider-network"] and target_sdn:
garciadeblas5697b8b2021-03-24 09:17:02 +0100802 target_vld["vim_info"][target_sdn]["sdn-ports"] = vld_params[
803 "provider-network"
804 ]["sdn-ports"]
tierno2357f4e2020-10-19 16:38:59 +0000805 if vld_params.get("wimAccountId"):
806 target_wim = "wim:{}".format(vld_params["wimAccountId"])
807 target_vld["vim_info"][target_wim] = {}
808 for param in ("vim-network-name", "vim-network-id"):
809 if vld_params.get(param):
810 if isinstance(vld_params[param], dict):
garciaale04694c62021-03-02 10:49:28 -0300811 for vim, vim_net in vld_params[param].items():
bravof922c4172020-11-24 21:21:43 -0300812 other_target_vim = "vim:" + vim
garciadeblas5697b8b2021-03-24 09:17:02 +0100813 populate_dict(
814 target_vld["vim_info"],
815 (other_target_vim, param.replace("-", "_")),
816 vim_net,
817 )
tierno2357f4e2020-10-19 16:38:59 +0000818 else: # isinstance str
garciadeblas5697b8b2021-03-24 09:17:02 +0100819 target_vld["vim_info"][target_vim][
820 param.replace("-", "_")
821 ] = vld_params[param]
bravof922c4172020-11-24 21:21:43 -0300822 if vld_params.get("common_id"):
823 target_vld["common_id"] = vld_params.get("common_id")
tierno2357f4e2020-10-19 16:38:59 +0000824
tierno69f0d382020-05-07 13:08:09 +0000825 nslcmop_id = db_nslcmop["_id"]
826 target = {
827 "name": db_nsr["name"],
828 "ns": {"vld": []},
829 "vnf": [],
830 "image": deepcopy(db_nsr["image"]),
831 "flavor": deepcopy(db_nsr["flavor"]),
832 "action_id": nslcmop_id,
tierno2357f4e2020-10-19 16:38:59 +0000833 "cloud_init_content": {},
tierno69f0d382020-05-07 13:08:09 +0000834 }
835 for image in target["image"]:
tierno2357f4e2020-10-19 16:38:59 +0000836 image["vim_info"] = {}
tierno69f0d382020-05-07 13:08:09 +0000837 for flavor in target["flavor"]:
tierno2357f4e2020-10-19 16:38:59 +0000838 flavor["vim_info"] = {}
tierno69f0d382020-05-07 13:08:09 +0000839
tierno2357f4e2020-10-19 16:38:59 +0000840 if db_nslcmop.get("lcmOperationType") != "instantiate":
841 # get parameters of instantiation:
garciadeblas5697b8b2021-03-24 09:17:02 +0100842 db_nslcmop_instantiate = self.db.get_list(
843 "nslcmops",
844 {
845 "nsInstanceId": db_nslcmop["nsInstanceId"],
846 "lcmOperationType": "instantiate",
847 },
848 )[-1]
tierno2357f4e2020-10-19 16:38:59 +0000849 ns_params = db_nslcmop_instantiate.get("operationParams")
850 else:
851 ns_params = db_nslcmop.get("operationParams")
bravof922c4172020-11-24 21:21:43 -0300852 ssh_keys_instantiation = ns_params.get("ssh_keys") or []
853 ssh_keys_all = ssh_keys_instantiation + (n2vc_key_list or [])
tierno69f0d382020-05-07 13:08:09 +0000854
855 cp2target = {}
tierno2357f4e2020-10-19 16:38:59 +0000856 for vld_index, vld in enumerate(db_nsr.get("vld")):
857 target_vim = "vim:{}".format(ns_params["vimAccountId"])
858 target_vld = {
859 "id": vld["id"],
860 "name": vld["name"],
861 "mgmt-network": vld.get("mgmt-network", False),
862 "type": vld.get("type"),
863 "vim_info": {
bravof922c4172020-11-24 21:21:43 -0300864 target_vim: {
865 "vim_network_name": vld.get("vim-network-name"),
garciadeblas5697b8b2021-03-24 09:17:02 +0100866 "vim_account_id": ns_params["vimAccountId"],
bravof922c4172020-11-24 21:21:43 -0300867 }
garciadeblas5697b8b2021-03-24 09:17:02 +0100868 },
tierno2357f4e2020-10-19 16:38:59 +0000869 }
870 # check if this network needs SDN assist
tierno2357f4e2020-10-19 16:38:59 +0000871 if vld.get("pci-interfaces"):
garciadeblasa5ae90b2021-02-12 11:26:46 +0000872 db_vim = get_vim_account(ns_params["vimAccountId"])
tierno2357f4e2020-10-19 16:38:59 +0000873 sdnc_id = db_vim["config"].get("sdn-controller")
874 if sdnc_id:
garciadeblasa5ae90b2021-02-12 11:26:46 +0000875 sdn_vld = "nsrs:{}:vld.{}".format(nsr_id, vld["id"])
876 target_sdn = "sdn:{}".format(sdnc_id)
877 target_vld["vim_info"][target_sdn] = {
garciadeblas5697b8b2021-03-24 09:17:02 +0100878 "sdn": True,
879 "target_vim": target_vim,
880 "vlds": [sdn_vld],
881 "type": vld.get("type"),
882 }
tierno2357f4e2020-10-19 16:38:59 +0000883
bravof922c4172020-11-24 21:21:43 -0300884 nsd_vnf_profiles = get_vnf_profiles(nsd)
885 for nsd_vnf_profile in nsd_vnf_profiles:
886 for cp in nsd_vnf_profile["virtual-link-connectivity"]:
887 if cp["virtual-link-profile-id"] == vld["id"]:
garciadeblas5697b8b2021-03-24 09:17:02 +0100888 cp2target[
889 "member_vnf:{}.{}".format(
890 cp["constituent-cpd-id"][0][
891 "constituent-base-element-id"
892 ],
893 cp["constituent-cpd-id"][0]["constituent-cpd-id"],
894 )
895 ] = "nsrs:{}:vld.{}".format(nsr_id, vld_index)
tierno2357f4e2020-10-19 16:38:59 +0000896
897 # check at nsd descriptor, if there is an ip-profile
898 vld_params = {}
lloretgalleg19008482021-04-19 11:40:18 +0000899 nsd_vlp = find_in_list(
900 get_virtual_link_profiles(nsd),
garciadeblas5697b8b2021-03-24 09:17:02 +0100901 lambda a_link_profile: a_link_profile["virtual-link-desc-id"]
902 == vld["id"],
903 )
904 if (
905 nsd_vlp
906 and nsd_vlp.get("virtual-link-protocol-data")
907 and nsd_vlp["virtual-link-protocol-data"].get("l3-protocol-data")
908 ):
909 ip_profile_source_data = nsd_vlp["virtual-link-protocol-data"][
910 "l3-protocol-data"
911 ]
lloretgalleg19008482021-04-19 11:40:18 +0000912 ip_profile_dest_data = {}
913 if "ip-version" in ip_profile_source_data:
garciadeblas5697b8b2021-03-24 09:17:02 +0100914 ip_profile_dest_data["ip-version"] = ip_profile_source_data[
915 "ip-version"
916 ]
lloretgalleg19008482021-04-19 11:40:18 +0000917 if "cidr" in ip_profile_source_data:
garciadeblas5697b8b2021-03-24 09:17:02 +0100918 ip_profile_dest_data["subnet-address"] = ip_profile_source_data[
919 "cidr"
920 ]
lloretgalleg19008482021-04-19 11:40:18 +0000921 if "gateway-ip" in ip_profile_source_data:
garciadeblas5697b8b2021-03-24 09:17:02 +0100922 ip_profile_dest_data["gateway-address"] = ip_profile_source_data[
923 "gateway-ip"
924 ]
lloretgalleg19008482021-04-19 11:40:18 +0000925 if "dhcp-enabled" in ip_profile_source_data:
926 ip_profile_dest_data["dhcp-params"] = {
927 "enabled": ip_profile_source_data["dhcp-enabled"]
928 }
929 vld_params["ip-profile"] = ip_profile_dest_data
bravof922c4172020-11-24 21:21:43 -0300930
tierno2357f4e2020-10-19 16:38:59 +0000931 # update vld_params with instantiation params
garciadeblas5697b8b2021-03-24 09:17:02 +0100932 vld_instantiation_params = find_in_list(
933 get_iterable(ns_params, "vld"),
934 lambda a_vld: a_vld["name"] in (vld["name"], vld["id"]),
935 )
tierno2357f4e2020-10-19 16:38:59 +0000936 if vld_instantiation_params:
937 vld_params.update(vld_instantiation_params)
bravof922c4172020-11-24 21:21:43 -0300938 parse_vld_instantiation_params(target_vim, target_vld, vld_params, None)
tierno69f0d382020-05-07 13:08:09 +0000939 target["ns"]["vld"].append(target_vld)
bravof922c4172020-11-24 21:21:43 -0300940
tierno69f0d382020-05-07 13:08:09 +0000941 for vnfr in db_vnfrs.values():
garciadeblas5697b8b2021-03-24 09:17:02 +0100942 vnfd = find_in_list(
943 db_vnfds, lambda db_vnf: db_vnf["id"] == vnfr["vnfd-ref"]
944 )
945 vnf_params = find_in_list(
946 get_iterable(ns_params, "vnf"),
947 lambda a_vnf: a_vnf["member-vnf-index"] == vnfr["member-vnf-index-ref"],
948 )
tierno69f0d382020-05-07 13:08:09 +0000949 target_vnf = deepcopy(vnfr)
tierno2357f4e2020-10-19 16:38:59 +0000950 target_vim = "vim:{}".format(vnfr["vim-account-id"])
tierno69f0d382020-05-07 13:08:09 +0000951 for vld in target_vnf.get("vld", ()):
tierno2357f4e2020-10-19 16:38:59 +0000952 # check if connected to a ns.vld, to fill target'
garciadeblas5697b8b2021-03-24 09:17:02 +0100953 vnf_cp = find_in_list(
954 vnfd.get("int-virtual-link-desc", ()),
955 lambda cpd: cpd.get("id") == vld["id"],
956 )
tierno69f0d382020-05-07 13:08:09 +0000957 if vnf_cp:
garciadeblas5697b8b2021-03-24 09:17:02 +0100958 ns_cp = "member_vnf:{}.{}".format(
959 vnfr["member-vnf-index-ref"], vnf_cp["id"]
960 )
tierno69f0d382020-05-07 13:08:09 +0000961 if cp2target.get(ns_cp):
962 vld["target"] = cp2target[ns_cp]
bravof922c4172020-11-24 21:21:43 -0300963
garciadeblas5697b8b2021-03-24 09:17:02 +0100964 vld["vim_info"] = {
965 target_vim: {"vim_network_name": vld.get("vim-network-name")}
966 }
tierno2357f4e2020-10-19 16:38:59 +0000967 # check if this network needs SDN assist
968 target_sdn = None
969 if vld.get("pci-interfaces"):
970 db_vim = get_vim_account(vnfr["vim-account-id"])
971 sdnc_id = db_vim["config"].get("sdn-controller")
972 if sdnc_id:
973 sdn_vld = "vnfrs:{}:vld.{}".format(target_vnf["_id"], vld["id"])
974 target_sdn = "sdn:{}".format(sdnc_id)
975 vld["vim_info"][target_sdn] = {
garciadeblas5697b8b2021-03-24 09:17:02 +0100976 "sdn": True,
977 "target_vim": target_vim,
978 "vlds": [sdn_vld],
979 "type": vld.get("type"),
980 }
tierno69f0d382020-05-07 13:08:09 +0000981
tierno2357f4e2020-10-19 16:38:59 +0000982 # check at vnfd descriptor, if there is an ip-profile
983 vld_params = {}
bravof922c4172020-11-24 21:21:43 -0300984 vnfd_vlp = find_in_list(
985 get_virtual_link_profiles(vnfd),
garciadeblas5697b8b2021-03-24 09:17:02 +0100986 lambda a_link_profile: a_link_profile["id"] == vld["id"],
bravof922c4172020-11-24 21:21:43 -0300987 )
garciadeblas5697b8b2021-03-24 09:17:02 +0100988 if (
989 vnfd_vlp
990 and vnfd_vlp.get("virtual-link-protocol-data")
991 and vnfd_vlp["virtual-link-protocol-data"].get("l3-protocol-data")
992 ):
993 ip_profile_source_data = vnfd_vlp["virtual-link-protocol-data"][
994 "l3-protocol-data"
995 ]
bravof922c4172020-11-24 21:21:43 -0300996 ip_profile_dest_data = {}
997 if "ip-version" in ip_profile_source_data:
garciadeblas5697b8b2021-03-24 09:17:02 +0100998 ip_profile_dest_data["ip-version"] = ip_profile_source_data[
999 "ip-version"
1000 ]
bravof922c4172020-11-24 21:21:43 -03001001 if "cidr" in ip_profile_source_data:
garciadeblas5697b8b2021-03-24 09:17:02 +01001002 ip_profile_dest_data["subnet-address"] = ip_profile_source_data[
1003 "cidr"
1004 ]
bravof922c4172020-11-24 21:21:43 -03001005 if "gateway-ip" in ip_profile_source_data:
garciadeblas5697b8b2021-03-24 09:17:02 +01001006 ip_profile_dest_data[
1007 "gateway-address"
1008 ] = ip_profile_source_data["gateway-ip"]
bravof922c4172020-11-24 21:21:43 -03001009 if "dhcp-enabled" in ip_profile_source_data:
1010 ip_profile_dest_data["dhcp-params"] = {
1011 "enabled": ip_profile_source_data["dhcp-enabled"]
1012 }
1013
1014 vld_params["ip-profile"] = ip_profile_dest_data
tierno2357f4e2020-10-19 16:38:59 +00001015 # update vld_params with instantiation params
1016 if vnf_params:
garciadeblas5697b8b2021-03-24 09:17:02 +01001017 vld_instantiation_params = find_in_list(
1018 get_iterable(vnf_params, "internal-vld"),
1019 lambda i_vld: i_vld["name"] == vld["id"],
1020 )
tierno2357f4e2020-10-19 16:38:59 +00001021 if vld_instantiation_params:
1022 vld_params.update(vld_instantiation_params)
1023 parse_vld_instantiation_params(target_vim, vld, vld_params, target_sdn)
1024
1025 vdur_list = []
tierno69f0d382020-05-07 13:08:09 +00001026 for vdur in target_vnf.get("vdur", ()):
tierno2357f4e2020-10-19 16:38:59 +00001027 if vdur.get("status") == "DELETING" or vdur.get("pdu-type"):
1028 continue # This vdu must not be created
bravof922c4172020-11-24 21:21:43 -03001029 vdur["vim_info"] = {"vim_account_id": vnfr["vim-account-id"]}
tierno69f0d382020-05-07 13:08:09 +00001030
bravof922c4172020-11-24 21:21:43 -03001031 self.logger.debug("NS > ssh_keys > {}".format(ssh_keys_all))
1032
1033 if ssh_keys_all:
bravofe5a31bc2021-02-17 19:09:12 -03001034 vdu_configuration = get_configuration(vnfd, vdur["vdu-id-ref"])
1035 vnf_configuration = get_configuration(vnfd, vnfd["id"])
garciadeblas5697b8b2021-03-24 09:17:02 +01001036 if (
1037 vdu_configuration
1038 and vdu_configuration.get("config-access")
1039 and vdu_configuration.get("config-access").get("ssh-access")
1040 ):
bravof922c4172020-11-24 21:21:43 -03001041 vdur["ssh-keys"] = ssh_keys_all
garciadeblas5697b8b2021-03-24 09:17:02 +01001042 vdur["ssh-access-required"] = vdu_configuration[
1043 "config-access"
1044 ]["ssh-access"]["required"]
1045 elif (
1046 vnf_configuration
1047 and vnf_configuration.get("config-access")
1048 and vnf_configuration.get("config-access").get("ssh-access")
1049 and any(iface.get("mgmt-vnf") for iface in vdur["interfaces"])
1050 ):
bravof922c4172020-11-24 21:21:43 -03001051 vdur["ssh-keys"] = ssh_keys_all
garciadeblas5697b8b2021-03-24 09:17:02 +01001052 vdur["ssh-access-required"] = vnf_configuration[
1053 "config-access"
1054 ]["ssh-access"]["required"]
1055 elif ssh_keys_instantiation and find_in_list(
1056 vdur["interfaces"], lambda iface: iface.get("mgmt-vnf")
1057 ):
bravof922c4172020-11-24 21:21:43 -03001058 vdur["ssh-keys"] = ssh_keys_instantiation
tierno69f0d382020-05-07 13:08:09 +00001059
bravof922c4172020-11-24 21:21:43 -03001060 self.logger.debug("NS > vdur > {}".format(vdur))
1061
1062 vdud = get_vdu(vnfd, vdur["vdu-id-ref"])
tierno69f0d382020-05-07 13:08:09 +00001063 # cloud-init
1064 if vdud.get("cloud-init-file"):
garciadeblas5697b8b2021-03-24 09:17:02 +01001065 vdur["cloud-init"] = "{}:file:{}".format(
1066 vnfd["_id"], vdud.get("cloud-init-file")
1067 )
tierno2357f4e2020-10-19 16:38:59 +00001068 # read file and put content at target.cloul_init_content. Avoid ng_ro to use shared package system
1069 if vdur["cloud-init"] not in target["cloud_init_content"]:
1070 base_folder = vnfd["_admin"]["storage"]
bravof486707f2021-11-08 17:18:50 -03001071 if base_folder["pkg-dir"]:
1072 cloud_init_file = "{}/{}/cloud_init/{}".format(
1073 base_folder["folder"],
1074 base_folder["pkg-dir"],
1075 vdud.get("cloud-init-file"),
1076 )
1077 else:
1078 cloud_init_file = "{}/Scripts/cloud_init/{}".format(
1079 base_folder["folder"],
1080 vdud.get("cloud-init-file"),
1081 )
tierno2357f4e2020-10-19 16:38:59 +00001082 with self.fs.file_open(cloud_init_file, "r") as ci_file:
garciadeblas5697b8b2021-03-24 09:17:02 +01001083 target["cloud_init_content"][
1084 vdur["cloud-init"]
1085 ] = ci_file.read()
tierno69f0d382020-05-07 13:08:09 +00001086 elif vdud.get("cloud-init"):
garciadeblas5697b8b2021-03-24 09:17:02 +01001087 vdur["cloud-init"] = "{}:vdu:{}".format(
1088 vnfd["_id"], get_vdu_index(vnfd, vdur["vdu-id-ref"])
1089 )
tierno2357f4e2020-10-19 16:38:59 +00001090 # put content at target.cloul_init_content. Avoid ng_ro read vnfd descriptor
garciadeblas5697b8b2021-03-24 09:17:02 +01001091 target["cloud_init_content"][vdur["cloud-init"]] = vdud[
1092 "cloud-init"
1093 ]
tierno2357f4e2020-10-19 16:38:59 +00001094 vdur["additionalParams"] = vdur.get("additionalParams") or {}
garciadeblas5697b8b2021-03-24 09:17:02 +01001095 deploy_params_vdu = self._format_additional_params(
1096 vdur.get("additionalParams") or {}
1097 )
1098 deploy_params_vdu["OSM"] = get_osm_params(
1099 vnfr, vdur["vdu-id-ref"], vdur["count-index"]
1100 )
tierno2357f4e2020-10-19 16:38:59 +00001101 vdur["additionalParams"] = deploy_params_vdu
tierno69f0d382020-05-07 13:08:09 +00001102
1103 # flavor
1104 ns_flavor = target["flavor"][int(vdur["ns-flavor-id"])]
tierno2357f4e2020-10-19 16:38:59 +00001105 if target_vim not in ns_flavor["vim_info"]:
1106 ns_flavor["vim_info"][target_vim] = {}
lloretgalleg7dc94672021-02-08 11:49:50 +00001107
1108 # deal with images
1109 # in case alternative images are provided we must check if they should be applied
1110 # for the vim_type, modify the vim_type taking into account
1111 ns_image_id = int(vdur["ns-image-id"])
1112 if vdur.get("alt-image-ids"):
1113 db_vim = get_vim_account(vnfr["vim-account-id"])
1114 vim_type = db_vim["vim_type"]
1115 for alt_image_id in vdur.get("alt-image-ids"):
1116 ns_alt_image = target["image"][int(alt_image_id)]
1117 if vim_type == ns_alt_image.get("vim-type"):
1118 # must use alternative image
garciadeblas5697b8b2021-03-24 09:17:02 +01001119 self.logger.debug(
1120 "use alternative image id: {}".format(alt_image_id)
1121 )
lloretgalleg7dc94672021-02-08 11:49:50 +00001122 ns_image_id = alt_image_id
1123 vdur["ns-image-id"] = ns_image_id
1124 break
1125 ns_image = target["image"][int(ns_image_id)]
tierno2357f4e2020-10-19 16:38:59 +00001126 if target_vim not in ns_image["vim_info"]:
1127 ns_image["vim_info"][target_vim] = {}
tierno69f0d382020-05-07 13:08:09 +00001128
tierno2357f4e2020-10-19 16:38:59 +00001129 vdur["vim_info"] = {target_vim: {}}
1130 # instantiation parameters
1131 # if vnf_params:
1132 # vdu_instantiation_params = next((v for v in get_iterable(vnf_params, "vdu") if v["id"] ==
1133 # vdud["id"]), None)
1134 vdur_list.append(vdur)
1135 target_vnf["vdur"] = vdur_list
tierno69f0d382020-05-07 13:08:09 +00001136 target["vnf"].append(target_vnf)
1137
1138 desc = await self.RO.deploy(nsr_id, target)
bravof922c4172020-11-24 21:21:43 -03001139 self.logger.debug("RO return > {}".format(desc))
tierno69f0d382020-05-07 13:08:09 +00001140 action_id = desc["action_id"]
garciadeblas5697b8b2021-03-24 09:17:02 +01001141 await self._wait_ng_ro(
1142 nsr_id, action_id, nslcmop_id, start_deploy, timeout_ns_deploy, stage
1143 )
tierno69f0d382020-05-07 13:08:09 +00001144
1145 # Updating NSR
1146 db_nsr_update = {
1147 "_admin.deployed.RO.operational-status": "running",
garciadeblas5697b8b2021-03-24 09:17:02 +01001148 "detailed-status": " ".join(stage),
tierno69f0d382020-05-07 13:08:09 +00001149 }
1150 # db_nsr["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
1151 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1152 self._write_op_status(nslcmop_id, stage)
garciadeblas5697b8b2021-03-24 09:17:02 +01001153 self.logger.debug(
1154 logging_text + "ns deployed at RO. RO_id={}".format(action_id)
1155 )
tierno69f0d382020-05-07 13:08:09 +00001156 return
1157
garciadeblas5697b8b2021-03-24 09:17:02 +01001158 async def _wait_ng_ro(
1159 self,
1160 nsr_id,
1161 action_id,
1162 nslcmop_id=None,
1163 start_time=None,
1164 timeout=600,
1165 stage=None,
1166 ):
tierno69f0d382020-05-07 13:08:09 +00001167 detailed_status_old = None
1168 db_nsr_update = {}
tierno2357f4e2020-10-19 16:38:59 +00001169 start_time = start_time or time()
tierno69f0d382020-05-07 13:08:09 +00001170 while time() <= start_time + timeout:
1171 desc_status = await self.RO.status(nsr_id, action_id)
bravof922c4172020-11-24 21:21:43 -03001172 self.logger.debug("Wait NG RO > {}".format(desc_status))
tierno69f0d382020-05-07 13:08:09 +00001173 if desc_status["status"] == "FAILED":
1174 raise NgRoException(desc_status["details"])
1175 elif desc_status["status"] == "BUILD":
tierno2357f4e2020-10-19 16:38:59 +00001176 if stage:
1177 stage[2] = "VIM: ({})".format(desc_status["details"])
tierno69f0d382020-05-07 13:08:09 +00001178 elif desc_status["status"] == "DONE":
tierno2357f4e2020-10-19 16:38:59 +00001179 if stage:
1180 stage[2] = "Deployed at VIM"
tierno69f0d382020-05-07 13:08:09 +00001181 break
1182 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001183 assert False, "ROclient.check_ns_status returns unknown {}".format(
1184 desc_status["status"]
1185 )
tierno2357f4e2020-10-19 16:38:59 +00001186 if stage and nslcmop_id and stage[2] != detailed_status_old:
tierno69f0d382020-05-07 13:08:09 +00001187 detailed_status_old = stage[2]
1188 db_nsr_update["detailed-status"] = " ".join(stage)
1189 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1190 self._write_op_status(nslcmop_id, stage)
bravof922c4172020-11-24 21:21:43 -03001191 await asyncio.sleep(15, loop=self.loop)
tierno69f0d382020-05-07 13:08:09 +00001192 else: # timeout_ns_deploy
1193 raise NgRoException("Timeout waiting ns to deploy")
1194
garciadeblas5697b8b2021-03-24 09:17:02 +01001195 async def _terminate_ng_ro(
1196 self, logging_text, nsr_deployed, nsr_id, nslcmop_id, stage
1197 ):
tierno69f0d382020-05-07 13:08:09 +00001198 db_nsr_update = {}
1199 failed_detail = []
1200 action_id = None
1201 start_deploy = time()
1202 try:
1203 target = {
1204 "ns": {"vld": []},
1205 "vnf": [],
1206 "image": [],
1207 "flavor": [],
garciadeblas5697b8b2021-03-24 09:17:02 +01001208 "action_id": nslcmop_id,
tierno69f0d382020-05-07 13:08:09 +00001209 }
1210 desc = await self.RO.deploy(nsr_id, target)
1211 action_id = desc["action_id"]
1212 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = action_id
1213 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETING"
garciadeblas5697b8b2021-03-24 09:17:02 +01001214 self.logger.debug(
1215 logging_text
1216 + "ns terminate action at RO. action_id={}".format(action_id)
1217 )
tierno69f0d382020-05-07 13:08:09 +00001218
1219 # wait until done
1220 delete_timeout = 20 * 60 # 20 minutes
garciadeblas5697b8b2021-03-24 09:17:02 +01001221 await self._wait_ng_ro(
1222 nsr_id, action_id, nslcmop_id, start_deploy, delete_timeout, stage
1223 )
tierno69f0d382020-05-07 13:08:09 +00001224
1225 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
1226 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
1227 # delete all nsr
1228 await self.RO.delete(nsr_id)
1229 except Exception as e:
1230 if isinstance(e, NgRoException) and e.http_code == 404: # not found
1231 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
1232 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
1233 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
garciadeblas5697b8b2021-03-24 09:17:02 +01001234 self.logger.debug(
1235 logging_text + "RO_action_id={} already deleted".format(action_id)
1236 )
tierno69f0d382020-05-07 13:08:09 +00001237 elif isinstance(e, NgRoException) and e.http_code == 409: # conflict
1238 failed_detail.append("delete conflict: {}".format(e))
garciadeblas5697b8b2021-03-24 09:17:02 +01001239 self.logger.debug(
1240 logging_text
1241 + "RO_action_id={} delete conflict: {}".format(action_id, e)
1242 )
tierno69f0d382020-05-07 13:08:09 +00001243 else:
1244 failed_detail.append("delete error: {}".format(e))
garciadeblas5697b8b2021-03-24 09:17:02 +01001245 self.logger.error(
1246 logging_text
1247 + "RO_action_id={} delete error: {}".format(action_id, e)
1248 )
tierno69f0d382020-05-07 13:08:09 +00001249
1250 if failed_detail:
1251 stage[2] = "Error deleting from VIM"
1252 else:
1253 stage[2] = "Deleted from VIM"
1254 db_nsr_update["detailed-status"] = " ".join(stage)
1255 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1256 self._write_op_status(nslcmop_id, stage)
1257
1258 if failed_detail:
1259 raise LcmException("; ".join(failed_detail))
1260 return
1261
garciadeblas5697b8b2021-03-24 09:17:02 +01001262 async def instantiate_RO(
1263 self,
1264 logging_text,
1265 nsr_id,
1266 nsd,
1267 db_nsr,
1268 db_nslcmop,
1269 db_vnfrs,
1270 db_vnfds,
1271 n2vc_key_list,
1272 stage,
1273 ):
tiernoe95ed362020-04-23 08:24:57 +00001274 """
1275 Instantiate at RO
1276 :param logging_text: preffix text to use at logging
1277 :param nsr_id: nsr identity
1278 :param nsd: database content of ns descriptor
1279 :param db_nsr: database content of ns record
1280 :param db_nslcmop: database content of ns operation, in this case, 'instantiate'
1281 :param db_vnfrs:
bravof922c4172020-11-24 21:21:43 -03001282 :param db_vnfds: database content of vnfds, indexed by id (not _id). {id: {vnfd_object}, ...}
tiernoe95ed362020-04-23 08:24:57 +00001283 :param n2vc_key_list: ssh-public-key list to be inserted to management vdus via cloud-init
1284 :param stage: list with 3 items: [general stage, tasks, vim_specific]. This task will write over vim_specific
1285 :return: None or exception
1286 """
tiernoe876f672020-02-13 14:34:48 +00001287 try:
tiernoe876f672020-02-13 14:34:48 +00001288 start_deploy = time()
1289 ns_params = db_nslcmop.get("operationParams")
1290 if ns_params and ns_params.get("timeout_ns_deploy"):
1291 timeout_ns_deploy = ns_params["timeout_ns_deploy"]
1292 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001293 timeout_ns_deploy = self.timeout.get(
1294 "ns_deploy", self.timeout_ns_deploy
1295 )
quilesj7e13aeb2019-10-08 13:34:55 +02001296
tiernoe876f672020-02-13 14:34:48 +00001297 # Check for and optionally request placement optimization. Database will be updated if placement activated
1298 stage[2] = "Waiting for Placement."
tierno8790a3d2020-04-23 22:49:52 +00001299 if await self._do_placement(logging_text, db_nslcmop, db_vnfrs):
1300 # in case of placement change ns_params[vimAcountId) if not present at any vnfrs
1301 for vnfr in db_vnfrs.values():
1302 if ns_params["vimAccountId"] == vnfr["vim-account-id"]:
1303 break
1304 else:
1305 ns_params["vimAccountId"] == vnfr["vim-account-id"]
quilesj7e13aeb2019-10-08 13:34:55 +02001306
garciadeblas5697b8b2021-03-24 09:17:02 +01001307 return await self._instantiate_ng_ro(
1308 logging_text,
1309 nsr_id,
1310 nsd,
1311 db_nsr,
1312 db_nslcmop,
1313 db_vnfrs,
1314 db_vnfds,
1315 n2vc_key_list,
1316 stage,
1317 start_deploy,
1318 timeout_ns_deploy,
1319 )
tierno2357f4e2020-10-19 16:38:59 +00001320 except Exception as e:
tierno067e04a2020-03-31 12:53:13 +00001321 stage[2] = "ERROR deploying at VIM"
tiernoe876f672020-02-13 14:34:48 +00001322 self.set_vnfr_at_error(db_vnfrs, str(e))
garciadeblas5697b8b2021-03-24 09:17:02 +01001323 self.logger.error(
1324 "Error deploying at VIM {}".format(e),
1325 exc_info=not isinstance(
1326 e,
1327 (
1328 ROclient.ROClientException,
1329 LcmException,
1330 DbException,
1331 NgRoException,
1332 ),
1333 ),
1334 )
tiernoe876f672020-02-13 14:34:48 +00001335 raise
quilesj7e13aeb2019-10-08 13:34:55 +02001336
tierno7ecbc342020-09-21 14:05:39 +00001337 async def wait_kdu_up(self, logging_text, nsr_id, vnfr_id, kdu_name):
1338 """
1339 Wait for kdu to be up, get ip address
1340 :param logging_text: prefix use for logging
1341 :param nsr_id:
1342 :param vnfr_id:
1343 :param kdu_name:
1344 :return: IP address
1345 """
1346
1347 # self.logger.debug(logging_text + "Starting wait_kdu_up")
1348 nb_tries = 0
1349
1350 while nb_tries < 360:
1351 db_vnfr = self.db.get_one("vnfrs", {"_id": vnfr_id})
garciadeblas5697b8b2021-03-24 09:17:02 +01001352 kdur = next(
1353 (
1354 x
1355 for x in get_iterable(db_vnfr, "kdur")
1356 if x.get("kdu-name") == kdu_name
1357 ),
1358 None,
1359 )
tierno7ecbc342020-09-21 14:05:39 +00001360 if not kdur:
garciadeblas5697b8b2021-03-24 09:17:02 +01001361 raise LcmException(
1362 "Not found vnfr_id={}, kdu_name={}".format(vnfr_id, kdu_name)
1363 )
tierno7ecbc342020-09-21 14:05:39 +00001364 if kdur.get("status"):
1365 if kdur["status"] in ("READY", "ENABLED"):
1366 return kdur.get("ip-address")
1367 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001368 raise LcmException(
1369 "target KDU={} is in error state".format(kdu_name)
1370 )
tierno7ecbc342020-09-21 14:05:39 +00001371
1372 await asyncio.sleep(10, loop=self.loop)
1373 nb_tries += 1
1374 raise LcmException("Timeout waiting KDU={} instantiated".format(kdu_name))
1375
garciadeblas5697b8b2021-03-24 09:17:02 +01001376 async def wait_vm_up_insert_key_ro(
1377 self, logging_text, nsr_id, vnfr_id, vdu_id, vdu_index, pub_key=None, user=None
1378 ):
tiernoa5088192019-11-26 16:12:53 +00001379 """
1380 Wait for ip addres at RO, and optionally, insert public key in virtual machine
1381 :param logging_text: prefix use for logging
1382 :param nsr_id:
1383 :param vnfr_id:
1384 :param vdu_id:
1385 :param vdu_index:
1386 :param pub_key: public ssh key to inject, None to skip
1387 :param user: user to apply the public ssh key
1388 :return: IP address
1389 """
quilesj7e13aeb2019-10-08 13:34:55 +02001390
tierno2357f4e2020-10-19 16:38:59 +00001391 self.logger.debug(logging_text + "Starting wait_vm_up_insert_key_ro")
tiernod8323042019-08-09 11:32:23 +00001392 ro_nsr_id = None
1393 ip_address = None
1394 nb_tries = 0
1395 target_vdu_id = None
quilesj3149f262019-12-03 10:58:10 +00001396 ro_retries = 0
quilesj7e13aeb2019-10-08 13:34:55 +02001397
tiernod8323042019-08-09 11:32:23 +00001398 while True:
quilesj7e13aeb2019-10-08 13:34:55 +02001399
quilesj3149f262019-12-03 10:58:10 +00001400 ro_retries += 1
1401 if ro_retries >= 360: # 1 hour
garciadeblas5697b8b2021-03-24 09:17:02 +01001402 raise LcmException(
1403 "Not found _admin.deployed.RO.nsr_id for nsr_id: {}".format(nsr_id)
1404 )
quilesj3149f262019-12-03 10:58:10 +00001405
tiernod8323042019-08-09 11:32:23 +00001406 await asyncio.sleep(10, loop=self.loop)
quilesj7e13aeb2019-10-08 13:34:55 +02001407
1408 # get ip address
tiernod8323042019-08-09 11:32:23 +00001409 if not target_vdu_id:
1410 db_vnfr = self.db.get_one("vnfrs", {"_id": vnfr_id})
quilesj3149f262019-12-03 10:58:10 +00001411
1412 if not vdu_id: # for the VNF case
tiernoe876f672020-02-13 14:34:48 +00001413 if db_vnfr.get("status") == "ERROR":
garciadeblas5697b8b2021-03-24 09:17:02 +01001414 raise LcmException(
1415 "Cannot inject ssh-key because target VNF is in error state"
1416 )
tiernod8323042019-08-09 11:32:23 +00001417 ip_address = db_vnfr.get("ip-address")
1418 if not ip_address:
1419 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01001420 vdur = next(
1421 (
1422 x
1423 for x in get_iterable(db_vnfr, "vdur")
1424 if x.get("ip-address") == ip_address
1425 ),
1426 None,
1427 )
quilesj3149f262019-12-03 10:58:10 +00001428 else: # VDU case
garciadeblas5697b8b2021-03-24 09:17:02 +01001429 vdur = next(
1430 (
1431 x
1432 for x in get_iterable(db_vnfr, "vdur")
1433 if x.get("vdu-id-ref") == vdu_id
1434 and x.get("count-index") == vdu_index
1435 ),
1436 None,
1437 )
quilesj3149f262019-12-03 10:58:10 +00001438
garciadeblas5697b8b2021-03-24 09:17:02 +01001439 if (
1440 not vdur and len(db_vnfr.get("vdur", ())) == 1
1441 ): # If only one, this should be the target vdu
tierno0e8c3f02020-03-12 17:18:21 +00001442 vdur = db_vnfr["vdur"][0]
quilesj3149f262019-12-03 10:58:10 +00001443 if not vdur:
garciadeblas5697b8b2021-03-24 09:17:02 +01001444 raise LcmException(
1445 "Not found vnfr_id={}, vdu_id={}, vdu_index={}".format(
1446 vnfr_id, vdu_id, vdu_index
1447 )
1448 )
tierno2357f4e2020-10-19 16:38:59 +00001449 # New generation RO stores information at "vim_info"
1450 ng_ro_status = None
David Garciaa8bbe672020-11-19 13:06:54 +01001451 target_vim = None
tierno2357f4e2020-10-19 16:38:59 +00001452 if vdur.get("vim_info"):
garciadeblas5697b8b2021-03-24 09:17:02 +01001453 target_vim = next(
1454 t for t in vdur["vim_info"]
1455 ) # there should be only one key
tierno2357f4e2020-10-19 16:38:59 +00001456 ng_ro_status = vdur["vim_info"][target_vim].get("vim_status")
garciadeblas5697b8b2021-03-24 09:17:02 +01001457 if (
1458 vdur.get("pdu-type")
1459 or vdur.get("status") == "ACTIVE"
1460 or ng_ro_status == "ACTIVE"
1461 ):
quilesj3149f262019-12-03 10:58:10 +00001462 ip_address = vdur.get("ip-address")
1463 if not ip_address:
1464 continue
1465 target_vdu_id = vdur["vdu-id-ref"]
bravof922c4172020-11-24 21:21:43 -03001466 elif vdur.get("status") == "ERROR" or ng_ro_status == "ERROR":
garciadeblas5697b8b2021-03-24 09:17:02 +01001467 raise LcmException(
1468 "Cannot inject ssh-key because target VM is in error state"
1469 )
quilesj3149f262019-12-03 10:58:10 +00001470
tiernod8323042019-08-09 11:32:23 +00001471 if not target_vdu_id:
1472 continue
tiernod8323042019-08-09 11:32:23 +00001473
quilesj7e13aeb2019-10-08 13:34:55 +02001474 # inject public key into machine
1475 if pub_key and user:
tierno2357f4e2020-10-19 16:38:59 +00001476 self.logger.debug(logging_text + "Inserting RO key")
bravof922c4172020-11-24 21:21:43 -03001477 self.logger.debug("SSH > PubKey > {}".format(pub_key))
tierno0e8c3f02020-03-12 17:18:21 +00001478 if vdur.get("pdu-type"):
1479 self.logger.error(logging_text + "Cannot inject ssh-ky to a PDU")
1480 return ip_address
quilesj7e13aeb2019-10-08 13:34:55 +02001481 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01001482 ro_vm_id = "{}-{}".format(
1483 db_vnfr["member-vnf-index-ref"], target_vdu_id
1484 ) # TODO add vdu_index
tierno69f0d382020-05-07 13:08:09 +00001485 if self.ng_ro:
garciadeblas5697b8b2021-03-24 09:17:02 +01001486 target = {
1487 "action": {
1488 "action": "inject_ssh_key",
1489 "key": pub_key,
1490 "user": user,
1491 },
1492 "vnf": [{"_id": vnfr_id, "vdur": [{"id": vdur["id"]}]}],
1493 }
tierno2357f4e2020-10-19 16:38:59 +00001494 desc = await self.RO.deploy(nsr_id, target)
1495 action_id = desc["action_id"]
1496 await self._wait_ng_ro(nsr_id, action_id, timeout=600)
1497 break
tierno69f0d382020-05-07 13:08:09 +00001498 else:
tierno2357f4e2020-10-19 16:38:59 +00001499 # wait until NS is deployed at RO
1500 if not ro_nsr_id:
1501 db_nsrs = self.db.get_one("nsrs", {"_id": nsr_id})
garciadeblas5697b8b2021-03-24 09:17:02 +01001502 ro_nsr_id = deep_get(
1503 db_nsrs, ("_admin", "deployed", "RO", "nsr_id")
1504 )
tierno2357f4e2020-10-19 16:38:59 +00001505 if not ro_nsr_id:
1506 continue
tierno69f0d382020-05-07 13:08:09 +00001507 result_dict = await self.RO.create_action(
1508 item="ns",
1509 item_id_name=ro_nsr_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01001510 descriptor={
1511 "add_public_key": pub_key,
1512 "vms": [ro_vm_id],
1513 "user": user,
1514 },
tierno69f0d382020-05-07 13:08:09 +00001515 )
1516 # result_dict contains the format {VM-id: {vim_result: 200, description: text}}
1517 if not result_dict or not isinstance(result_dict, dict):
garciadeblas5697b8b2021-03-24 09:17:02 +01001518 raise LcmException(
1519 "Unknown response from RO when injecting key"
1520 )
tierno69f0d382020-05-07 13:08:09 +00001521 for result in result_dict.values():
1522 if result.get("vim_result") == 200:
1523 break
1524 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001525 raise ROclient.ROClientException(
1526 "error injecting key: {}".format(
1527 result.get("description")
1528 )
1529 )
tierno69f0d382020-05-07 13:08:09 +00001530 break
1531 except NgRoException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001532 raise LcmException(
1533 "Reaching max tries injecting key. Error: {}".format(e)
1534 )
quilesj7e13aeb2019-10-08 13:34:55 +02001535 except ROclient.ROClientException as e:
tiernoa5088192019-11-26 16:12:53 +00001536 if not nb_tries:
garciadeblas5697b8b2021-03-24 09:17:02 +01001537 self.logger.debug(
1538 logging_text
1539 + "error injecting key: {}. Retrying until {} seconds".format(
1540 e, 20 * 10
1541 )
1542 )
quilesj7e13aeb2019-10-08 13:34:55 +02001543 nb_tries += 1
tiernoa5088192019-11-26 16:12:53 +00001544 if nb_tries >= 20:
garciadeblas5697b8b2021-03-24 09:17:02 +01001545 raise LcmException(
1546 "Reaching max tries injecting key. Error: {}".format(e)
1547 )
quilesj7e13aeb2019-10-08 13:34:55 +02001548 else:
quilesj7e13aeb2019-10-08 13:34:55 +02001549 break
1550
1551 return ip_address
1552
tierno5ee02052019-12-05 19:55:02 +00001553 async def _wait_dependent_n2vc(self, nsr_id, vca_deployed_list, vca_index):
1554 """
1555 Wait until dependent VCA deployments have been finished. NS wait for VNFs and VDUs. VNFs for VDUs
1556 """
1557 my_vca = vca_deployed_list[vca_index]
1558 if my_vca.get("vdu_id") or my_vca.get("kdu_name"):
quilesj3655ae02019-12-12 16:08:35 +00001559 # vdu or kdu: no dependencies
tierno5ee02052019-12-05 19:55:02 +00001560 return
1561 timeout = 300
1562 while timeout >= 0:
quilesj3655ae02019-12-12 16:08:35 +00001563 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1564 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
1565 configuration_status_list = db_nsr["configurationStatus"]
1566 for index, vca_deployed in enumerate(configuration_status_list):
tierno5ee02052019-12-05 19:55:02 +00001567 if index == vca_index:
quilesj3655ae02019-12-12 16:08:35 +00001568 # myself
tierno5ee02052019-12-05 19:55:02 +00001569 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01001570 if not my_vca.get("member-vnf-index") or (
1571 vca_deployed.get("member-vnf-index")
1572 == my_vca.get("member-vnf-index")
1573 ):
quilesj3655ae02019-12-12 16:08:35 +00001574 internal_status = configuration_status_list[index].get("status")
garciadeblas5697b8b2021-03-24 09:17:02 +01001575 if internal_status == "READY":
quilesj3655ae02019-12-12 16:08:35 +00001576 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01001577 elif internal_status == "BROKEN":
1578 raise LcmException(
1579 "Configuration aborted because dependent charm/s has failed"
1580 )
quilesj3655ae02019-12-12 16:08:35 +00001581 else:
1582 break
tierno5ee02052019-12-05 19:55:02 +00001583 else:
quilesj3655ae02019-12-12 16:08:35 +00001584 # no dependencies, return
tierno5ee02052019-12-05 19:55:02 +00001585 return
1586 await asyncio.sleep(10)
1587 timeout -= 1
tierno5ee02052019-12-05 19:55:02 +00001588
1589 raise LcmException("Configuration aborted because dependent charm/s timeout")
1590
David Garciac1fe90a2021-03-31 19:12:02 +02001591 def get_vca_id(self, db_vnfr: dict, db_nsr: dict):
David Garcia5506c182021-10-21 17:03:48 +02001592 vca_id = None
1593 if db_vnfr:
1594 vca_id = deep_get(db_vnfr, ("vca-id",))
1595 elif db_nsr:
1596 vim_account_id = deep_get(db_nsr, ("instantiate_params", "vimAccountId"))
1597 vca_id = VimAccountDB.get_vim_account_with_id(vim_account_id).get("vca")
1598 return vca_id
David Garciac1fe90a2021-03-31 19:12:02 +02001599
garciadeblas5697b8b2021-03-24 09:17:02 +01001600 async def instantiate_N2VC(
1601 self,
1602 logging_text,
1603 vca_index,
1604 nsi_id,
1605 db_nsr,
1606 db_vnfr,
1607 vdu_id,
1608 kdu_name,
1609 vdu_index,
1610 config_descriptor,
1611 deploy_params,
1612 base_folder,
1613 nslcmop_id,
1614 stage,
1615 vca_type,
1616 vca_name,
1617 ee_config_descriptor,
1618 ):
tiernod8323042019-08-09 11:32:23 +00001619 nsr_id = db_nsr["_id"]
1620 db_update_entry = "_admin.deployed.VCA.{}.".format(vca_index)
tiernoda6fb102019-11-23 00:36:52 +00001621 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
tiernod8323042019-08-09 11:32:23 +00001622 vca_deployed = db_nsr["_admin"]["deployed"]["VCA"][vca_index]
tiernob996d942020-07-03 14:52:28 +00001623 osm_config = {"osm": {"ns_id": db_nsr["_id"]}}
quilesj7e13aeb2019-10-08 13:34:55 +02001624 db_dict = {
garciadeblas5697b8b2021-03-24 09:17:02 +01001625 "collection": "nsrs",
1626 "filter": {"_id": nsr_id},
1627 "path": db_update_entry,
quilesj7e13aeb2019-10-08 13:34:55 +02001628 }
tiernod8323042019-08-09 11:32:23 +00001629 step = ""
1630 try:
quilesj3655ae02019-12-12 16:08:35 +00001631
garciadeblas5697b8b2021-03-24 09:17:02 +01001632 element_type = "NS"
quilesj3655ae02019-12-12 16:08:35 +00001633 element_under_configuration = nsr_id
1634
tiernod8323042019-08-09 11:32:23 +00001635 vnfr_id = None
1636 if db_vnfr:
1637 vnfr_id = db_vnfr["_id"]
tiernob996d942020-07-03 14:52:28 +00001638 osm_config["osm"]["vnf_id"] = vnfr_id
tiernod8323042019-08-09 11:32:23 +00001639
garciadeblas5697b8b2021-03-24 09:17:02 +01001640 namespace = "{nsi}.{ns}".format(nsi=nsi_id if nsi_id else "", ns=nsr_id)
quilesj3655ae02019-12-12 16:08:35 +00001641
aktas98488ed2021-07-29 17:42:49 +03001642 if vca_type == "native_charm":
1643 index_number = 0
1644 else:
1645 index_number = vdu_index or 0
1646
tiernod8323042019-08-09 11:32:23 +00001647 if vnfr_id:
garciadeblas5697b8b2021-03-24 09:17:02 +01001648 element_type = "VNF"
quilesj3655ae02019-12-12 16:08:35 +00001649 element_under_configuration = vnfr_id
aktas98488ed2021-07-29 17:42:49 +03001650 namespace += ".{}-{}".format(vnfr_id, index_number)
tiernod8323042019-08-09 11:32:23 +00001651 if vdu_id:
aktas98488ed2021-07-29 17:42:49 +03001652 namespace += ".{}-{}".format(vdu_id, index_number)
garciadeblas5697b8b2021-03-24 09:17:02 +01001653 element_type = "VDU"
aktas98488ed2021-07-29 17:42:49 +03001654 element_under_configuration = "{}-{}".format(vdu_id, index_number)
tiernob996d942020-07-03 14:52:28 +00001655 osm_config["osm"]["vdu_id"] = vdu_id
tierno51183952020-04-03 15:48:18 +00001656 elif kdu_name:
aktas98488ed2021-07-29 17:42:49 +03001657 namespace += ".{}".format(kdu_name)
garciadeblas5697b8b2021-03-24 09:17:02 +01001658 element_type = "KDU"
tierno51183952020-04-03 15:48:18 +00001659 element_under_configuration = kdu_name
tiernob996d942020-07-03 14:52:28 +00001660 osm_config["osm"]["kdu_name"] = kdu_name
tiernod8323042019-08-09 11:32:23 +00001661
1662 # Get artifact path
bravof486707f2021-11-08 17:18:50 -03001663 if base_folder["pkg-dir"]:
1664 artifact_path = "{}/{}/{}/{}".format(
1665 base_folder["folder"],
1666 base_folder["pkg-dir"],
1667 "charms"
1668 if vca_type in ("native_charm", "lxc_proxy_charm", "k8s_proxy_charm")
1669 else "helm-charts",
1670 vca_name,
1671 )
1672 else:
1673 artifact_path = "{}/Scripts/{}/{}/".format(
1674 base_folder["folder"],
1675 "charms"
1676 if vca_type in ("native_charm", "lxc_proxy_charm", "k8s_proxy_charm")
1677 else "helm-charts",
1678 vca_name,
1679 )
bravof922c4172020-11-24 21:21:43 -03001680
1681 self.logger.debug("Artifact path > {}".format(artifact_path))
1682
tiernoa278b842020-07-08 15:33:55 +00001683 # get initial_config_primitive_list that applies to this element
garciadeblas5697b8b2021-03-24 09:17:02 +01001684 initial_config_primitive_list = config_descriptor.get(
1685 "initial-config-primitive"
1686 )
tiernoa278b842020-07-08 15:33:55 +00001687
garciadeblas5697b8b2021-03-24 09:17:02 +01001688 self.logger.debug(
1689 "Initial config primitive list > {}".format(
1690 initial_config_primitive_list
1691 )
1692 )
bravof922c4172020-11-24 21:21:43 -03001693
tiernoa278b842020-07-08 15:33:55 +00001694 # add config if not present for NS charm
1695 ee_descriptor_id = ee_config_descriptor.get("id")
bravof922c4172020-11-24 21:21:43 -03001696 self.logger.debug("EE Descriptor > {}".format(ee_descriptor_id))
garciadeblas5697b8b2021-03-24 09:17:02 +01001697 initial_config_primitive_list = get_ee_sorted_initial_config_primitive_list(
1698 initial_config_primitive_list, vca_deployed, ee_descriptor_id
1699 )
tiernod8323042019-08-09 11:32:23 +00001700
garciadeblas5697b8b2021-03-24 09:17:02 +01001701 self.logger.debug(
1702 "Initial config primitive list #2 > {}".format(
1703 initial_config_primitive_list
1704 )
1705 )
tierno588547c2020-07-01 15:30:20 +00001706 # n2vc_redesign STEP 3.1
tierno588547c2020-07-01 15:30:20 +00001707 # find old ee_id if exists
1708 ee_id = vca_deployed.get("ee_id")
tiernod8323042019-08-09 11:32:23 +00001709
David Garciac1fe90a2021-03-31 19:12:02 +02001710 vca_id = self.get_vca_id(db_vnfr, db_nsr)
tierno588547c2020-07-01 15:30:20 +00001711 # create or register execution environment in VCA
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001712 if vca_type in ("lxc_proxy_charm", "k8s_proxy_charm", "helm", "helm-v3"):
quilesj7e13aeb2019-10-08 13:34:55 +02001713
tierno588547c2020-07-01 15:30:20 +00001714 self._write_configuration_status(
1715 nsr_id=nsr_id,
1716 vca_index=vca_index,
garciadeblas5697b8b2021-03-24 09:17:02 +01001717 status="CREATING",
tierno588547c2020-07-01 15:30:20 +00001718 element_under_configuration=element_under_configuration,
garciadeblas5697b8b2021-03-24 09:17:02 +01001719 element_type=element_type,
tierno588547c2020-07-01 15:30:20 +00001720 )
tiernod8323042019-08-09 11:32:23 +00001721
tierno588547c2020-07-01 15:30:20 +00001722 step = "create execution environment"
garciadeblas5697b8b2021-03-24 09:17:02 +01001723 self.logger.debug(logging_text + step)
David Garciaaae391f2020-11-09 11:12:54 +01001724
1725 ee_id = None
1726 credentials = None
1727 if vca_type == "k8s_proxy_charm":
1728 ee_id = await self.vca_map[vca_type].install_k8s_proxy_charm(
garciadeblas5697b8b2021-03-24 09:17:02 +01001729 charm_name=artifact_path[artifact_path.rfind("/") + 1 :],
David Garciaaae391f2020-11-09 11:12:54 +01001730 namespace=namespace,
1731 artifact_path=artifact_path,
1732 db_dict=db_dict,
David Garciac1fe90a2021-03-31 19:12:02 +02001733 vca_id=vca_id,
David Garciaaae391f2020-11-09 11:12:54 +01001734 )
garciadeblas5697b8b2021-03-24 09:17:02 +01001735 elif vca_type == "helm" or vca_type == "helm-v3":
1736 ee_id, credentials = await self.vca_map[
1737 vca_type
1738 ].create_execution_environment(
bravof922c4172020-11-24 21:21:43 -03001739 namespace=namespace,
1740 reuse_ee_id=ee_id,
1741 db_dict=db_dict,
lloretgalleg18cb3cb2020-12-10 14:21:10 +00001742 config=osm_config,
1743 artifact_path=artifact_path,
garciadeblas5697b8b2021-03-24 09:17:02 +01001744 vca_type=vca_type,
bravof922c4172020-11-24 21:21:43 -03001745 )
garciadeblas5697b8b2021-03-24 09:17:02 +01001746 else:
1747 ee_id, credentials = await self.vca_map[
1748 vca_type
1749 ].create_execution_environment(
David Garciaaae391f2020-11-09 11:12:54 +01001750 namespace=namespace,
1751 reuse_ee_id=ee_id,
1752 db_dict=db_dict,
David Garciac1fe90a2021-03-31 19:12:02 +02001753 vca_id=vca_id,
David Garciaaae391f2020-11-09 11:12:54 +01001754 )
quilesj3655ae02019-12-12 16:08:35 +00001755
tierno588547c2020-07-01 15:30:20 +00001756 elif vca_type == "native_charm":
1757 step = "Waiting to VM being up and getting IP address"
1758 self.logger.debug(logging_text + step)
garciadeblas5697b8b2021-03-24 09:17:02 +01001759 rw_mgmt_ip = await self.wait_vm_up_insert_key_ro(
1760 logging_text,
1761 nsr_id,
1762 vnfr_id,
1763 vdu_id,
1764 vdu_index,
1765 user=None,
1766 pub_key=None,
1767 )
tierno588547c2020-07-01 15:30:20 +00001768 credentials = {"hostname": rw_mgmt_ip}
1769 # get username
garciadeblas5697b8b2021-03-24 09:17:02 +01001770 username = deep_get(
1771 config_descriptor, ("config-access", "ssh-access", "default-user")
1772 )
tierno588547c2020-07-01 15:30:20 +00001773 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1774 # merged. Meanwhile let's get username from initial-config-primitive
tiernoa278b842020-07-08 15:33:55 +00001775 if not username and initial_config_primitive_list:
1776 for config_primitive in initial_config_primitive_list:
tierno588547c2020-07-01 15:30:20 +00001777 for param in config_primitive.get("parameter", ()):
1778 if param["name"] == "ssh-username":
1779 username = param["value"]
1780 break
1781 if not username:
garciadeblas5697b8b2021-03-24 09:17:02 +01001782 raise LcmException(
1783 "Cannot determine the username neither with 'initial-config-primitive' nor with "
1784 "'config-access.ssh-access.default-user'"
1785 )
tierno588547c2020-07-01 15:30:20 +00001786 credentials["username"] = username
1787 # n2vc_redesign STEP 3.2
quilesj3655ae02019-12-12 16:08:35 +00001788
tierno588547c2020-07-01 15:30:20 +00001789 self._write_configuration_status(
1790 nsr_id=nsr_id,
1791 vca_index=vca_index,
garciadeblas5697b8b2021-03-24 09:17:02 +01001792 status="REGISTERING",
tierno588547c2020-07-01 15:30:20 +00001793 element_under_configuration=element_under_configuration,
garciadeblas5697b8b2021-03-24 09:17:02 +01001794 element_type=element_type,
tierno588547c2020-07-01 15:30:20 +00001795 )
quilesj3655ae02019-12-12 16:08:35 +00001796
tierno588547c2020-07-01 15:30:20 +00001797 step = "register execution environment {}".format(credentials)
1798 self.logger.debug(logging_text + step)
1799 ee_id = await self.vca_map[vca_type].register_execution_environment(
David Garciaaae391f2020-11-09 11:12:54 +01001800 credentials=credentials,
1801 namespace=namespace,
1802 db_dict=db_dict,
David Garciac1fe90a2021-03-31 19:12:02 +02001803 vca_id=vca_id,
David Garciaaae391f2020-11-09 11:12:54 +01001804 )
tierno3bedc9b2019-11-27 15:46:57 +00001805
tierno588547c2020-07-01 15:30:20 +00001806 # for compatibility with MON/POL modules, the need model and application name at database
1807 # TODO ask MON/POL if needed to not assuming anymore the format "model_name.application_name"
garciadeblas5697b8b2021-03-24 09:17:02 +01001808 ee_id_parts = ee_id.split(".")
tierno588547c2020-07-01 15:30:20 +00001809 db_nsr_update = {db_update_entry + "ee_id": ee_id}
1810 if len(ee_id_parts) >= 2:
1811 model_name = ee_id_parts[0]
1812 application_name = ee_id_parts[1]
1813 db_nsr_update[db_update_entry + "model"] = model_name
1814 db_nsr_update[db_update_entry + "application"] = application_name
tiernod8323042019-08-09 11:32:23 +00001815
1816 # n2vc_redesign STEP 3.3
tiernod8323042019-08-09 11:32:23 +00001817 step = "Install configuration Software"
quilesj3655ae02019-12-12 16:08:35 +00001818
tiernoc231a872020-01-21 08:49:05 +00001819 self._write_configuration_status(
quilesj3655ae02019-12-12 16:08:35 +00001820 nsr_id=nsr_id,
1821 vca_index=vca_index,
garciadeblas5697b8b2021-03-24 09:17:02 +01001822 status="INSTALLING SW",
quilesj3655ae02019-12-12 16:08:35 +00001823 element_under_configuration=element_under_configuration,
tierno51183952020-04-03 15:48:18 +00001824 element_type=element_type,
garciadeblas5697b8b2021-03-24 09:17:02 +01001825 other_update=db_nsr_update,
quilesj3655ae02019-12-12 16:08:35 +00001826 )
1827
tierno3bedc9b2019-11-27 15:46:57 +00001828 # TODO check if already done
quilesj7e13aeb2019-10-08 13:34:55 +02001829 self.logger.debug(logging_text + step)
David Garcia18a63322020-04-01 16:14:59 +02001830 config = None
tierno588547c2020-07-01 15:30:20 +00001831 if vca_type == "native_charm":
garciadeblas5697b8b2021-03-24 09:17:02 +01001832 config_primitive = next(
1833 (p for p in initial_config_primitive_list if p["name"] == "config"),
1834 None,
1835 )
tiernoa278b842020-07-08 15:33:55 +00001836 if config_primitive:
1837 config = self._map_primitive_params(
garciadeblas5697b8b2021-03-24 09:17:02 +01001838 config_primitive, {}, deploy_params
tiernoa278b842020-07-08 15:33:55 +00001839 )
tierno588547c2020-07-01 15:30:20 +00001840 num_units = 1
1841 if vca_type == "lxc_proxy_charm":
1842 if element_type == "NS":
1843 num_units = db_nsr.get("config-units") or 1
1844 elif element_type == "VNF":
1845 num_units = db_vnfr.get("config-units") or 1
1846 elif element_type == "VDU":
1847 for v in db_vnfr["vdur"]:
1848 if vdu_id == v["vdu-id-ref"]:
1849 num_units = v.get("config-units") or 1
1850 break
David Garciaaae391f2020-11-09 11:12:54 +01001851 if vca_type != "k8s_proxy_charm":
1852 await self.vca_map[vca_type].install_configuration_sw(
1853 ee_id=ee_id,
1854 artifact_path=artifact_path,
1855 db_dict=db_dict,
1856 config=config,
1857 num_units=num_units,
David Garciac1fe90a2021-03-31 19:12:02 +02001858 vca_id=vca_id,
aktas98488ed2021-07-29 17:42:49 +03001859 vca_type=vca_type,
David Garciaaae391f2020-11-09 11:12:54 +01001860 )
quilesj7e13aeb2019-10-08 13:34:55 +02001861
quilesj63f90042020-01-17 09:53:55 +00001862 # write in db flag of configuration_sw already installed
garciadeblas5697b8b2021-03-24 09:17:02 +01001863 self.update_db_2(
1864 "nsrs", nsr_id, {db_update_entry + "config_sw_installed": True}
1865 )
quilesj63f90042020-01-17 09:53:55 +00001866
1867 # add relations for this VCA (wait for other peers related with this VCA)
garciadeblas5697b8b2021-03-24 09:17:02 +01001868 await self._add_vca_relations(
1869 logging_text=logging_text,
1870 nsr_id=nsr_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01001871 vca_type=vca_type,
David Garciab4ebcd02021-10-28 02:00:43 +02001872 vca_index=vca_index,
garciadeblas5697b8b2021-03-24 09:17:02 +01001873 )
quilesj63f90042020-01-17 09:53:55 +00001874
quilesj7e13aeb2019-10-08 13:34:55 +02001875 # if SSH access is required, then get execution environment SSH public
David Garciaa27e20a2020-07-10 13:12:44 +02001876 # if native charm we have waited already to VM be UP
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001877 if vca_type in ("k8s_proxy_charm", "lxc_proxy_charm", "helm", "helm-v3"):
tierno3bedc9b2019-11-27 15:46:57 +00001878 pub_key = None
1879 user = None
tierno588547c2020-07-01 15:30:20 +00001880 # self.logger.debug("get ssh key block")
garciadeblas5697b8b2021-03-24 09:17:02 +01001881 if deep_get(
1882 config_descriptor, ("config-access", "ssh-access", "required")
1883 ):
tierno588547c2020-07-01 15:30:20 +00001884 # self.logger.debug("ssh key needed")
tierno3bedc9b2019-11-27 15:46:57 +00001885 # Needed to inject a ssh key
garciadeblas5697b8b2021-03-24 09:17:02 +01001886 user = deep_get(
1887 config_descriptor,
1888 ("config-access", "ssh-access", "default-user"),
1889 )
tierno3bedc9b2019-11-27 15:46:57 +00001890 step = "Install configuration Software, getting public ssh key"
David Garciac1fe90a2021-03-31 19:12:02 +02001891 pub_key = await self.vca_map[vca_type].get_ee_ssh_public__key(
garciadeblas5697b8b2021-03-24 09:17:02 +01001892 ee_id=ee_id, db_dict=db_dict, vca_id=vca_id
David Garciac1fe90a2021-03-31 19:12:02 +02001893 )
quilesj7e13aeb2019-10-08 13:34:55 +02001894
garciadeblas5697b8b2021-03-24 09:17:02 +01001895 step = "Insert public key into VM user={} ssh_key={}".format(
1896 user, pub_key
1897 )
tierno3bedc9b2019-11-27 15:46:57 +00001898 else:
tierno588547c2020-07-01 15:30:20 +00001899 # self.logger.debug("no need to get ssh key")
tierno3bedc9b2019-11-27 15:46:57 +00001900 step = "Waiting to VM being up and getting IP address"
1901 self.logger.debug(logging_text + step)
quilesj7e13aeb2019-10-08 13:34:55 +02001902
tierno3bedc9b2019-11-27 15:46:57 +00001903 # n2vc_redesign STEP 5.1
1904 # wait for RO (ip-address) Insert pub_key into VM
tierno5ee02052019-12-05 19:55:02 +00001905 if vnfr_id:
tierno7ecbc342020-09-21 14:05:39 +00001906 if kdu_name:
garciadeblas5697b8b2021-03-24 09:17:02 +01001907 rw_mgmt_ip = await self.wait_kdu_up(
1908 logging_text, nsr_id, vnfr_id, kdu_name
1909 )
tierno7ecbc342020-09-21 14:05:39 +00001910 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001911 rw_mgmt_ip = await self.wait_vm_up_insert_key_ro(
1912 logging_text,
1913 nsr_id,
1914 vnfr_id,
1915 vdu_id,
1916 vdu_index,
1917 user=user,
1918 pub_key=pub_key,
1919 )
tierno5ee02052019-12-05 19:55:02 +00001920 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001921 rw_mgmt_ip = None # This is for a NS configuration
tierno3bedc9b2019-11-27 15:46:57 +00001922
garciadeblas5697b8b2021-03-24 09:17:02 +01001923 self.logger.debug(logging_text + " VM_ip_address={}".format(rw_mgmt_ip))
quilesj7e13aeb2019-10-08 13:34:55 +02001924
tiernoa5088192019-11-26 16:12:53 +00001925 # store rw_mgmt_ip in deploy params for later replacement
quilesj7e13aeb2019-10-08 13:34:55 +02001926 deploy_params["rw_mgmt_ip"] = rw_mgmt_ip
tiernod8323042019-08-09 11:32:23 +00001927
1928 # n2vc_redesign STEP 6 Execute initial config primitive
garciadeblas5697b8b2021-03-24 09:17:02 +01001929 step = "execute initial config primitive"
quilesj3655ae02019-12-12 16:08:35 +00001930
1931 # wait for dependent primitives execution (NS -> VNF -> VDU)
tierno5ee02052019-12-05 19:55:02 +00001932 if initial_config_primitive_list:
1933 await self._wait_dependent_n2vc(nsr_id, vca_deployed_list, vca_index)
quilesj3655ae02019-12-12 16:08:35 +00001934
1935 # stage, in function of element type: vdu, kdu, vnf or ns
1936 my_vca = vca_deployed_list[vca_index]
1937 if my_vca.get("vdu_id") or my_vca.get("kdu_name"):
1938 # VDU or KDU
garciadeblas5697b8b2021-03-24 09:17:02 +01001939 stage[0] = "Stage 3/5: running Day-1 primitives for VDU."
quilesj3655ae02019-12-12 16:08:35 +00001940 elif my_vca.get("member-vnf-index"):
1941 # VNF
garciadeblas5697b8b2021-03-24 09:17:02 +01001942 stage[0] = "Stage 4/5: running Day-1 primitives for VNF."
quilesj3655ae02019-12-12 16:08:35 +00001943 else:
1944 # NS
garciadeblas5697b8b2021-03-24 09:17:02 +01001945 stage[0] = "Stage 5/5: running Day-1 primitives for NS."
quilesj3655ae02019-12-12 16:08:35 +00001946
tiernoc231a872020-01-21 08:49:05 +00001947 self._write_configuration_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01001948 nsr_id=nsr_id, vca_index=vca_index, status="EXECUTING PRIMITIVE"
quilesj3655ae02019-12-12 16:08:35 +00001949 )
1950
garciadeblas5697b8b2021-03-24 09:17:02 +01001951 self._write_op_status(op_id=nslcmop_id, stage=stage)
quilesj3655ae02019-12-12 16:08:35 +00001952
tiernoe876f672020-02-13 14:34:48 +00001953 check_if_terminated_needed = True
tiernod8323042019-08-09 11:32:23 +00001954 for initial_config_primitive in initial_config_primitive_list:
tiernoda6fb102019-11-23 00:36:52 +00001955 # adding information on the vca_deployed if it is a NS execution environment
1956 if not vca_deployed["member-vnf-index"]:
garciadeblas5697b8b2021-03-24 09:17:02 +01001957 deploy_params["ns_config_info"] = json.dumps(
1958 self._get_ns_config_info(nsr_id)
1959 )
tiernod8323042019-08-09 11:32:23 +00001960 # TODO check if already done
garciadeblas5697b8b2021-03-24 09:17:02 +01001961 primitive_params_ = self._map_primitive_params(
1962 initial_config_primitive, {}, deploy_params
1963 )
tierno3bedc9b2019-11-27 15:46:57 +00001964
garciadeblas5697b8b2021-03-24 09:17:02 +01001965 step = "execute primitive '{}' params '{}'".format(
1966 initial_config_primitive["name"], primitive_params_
1967 )
tiernod8323042019-08-09 11:32:23 +00001968 self.logger.debug(logging_text + step)
tierno588547c2020-07-01 15:30:20 +00001969 await self.vca_map[vca_type].exec_primitive(
quilesj7e13aeb2019-10-08 13:34:55 +02001970 ee_id=ee_id,
1971 primitive_name=initial_config_primitive["name"],
1972 params_dict=primitive_params_,
David Garciac1fe90a2021-03-31 19:12:02 +02001973 db_dict=db_dict,
1974 vca_id=vca_id,
aktas98488ed2021-07-29 17:42:49 +03001975 vca_type=vca_type,
quilesj7e13aeb2019-10-08 13:34:55 +02001976 )
tiernoe876f672020-02-13 14:34:48 +00001977 # Once some primitive has been exec, check and write at db if it needs to exec terminated primitives
1978 if check_if_terminated_needed:
garciadeblas5697b8b2021-03-24 09:17:02 +01001979 if config_descriptor.get("terminate-config-primitive"):
1980 self.update_db_2(
1981 "nsrs", nsr_id, {db_update_entry + "needed_terminate": True}
1982 )
tiernoe876f672020-02-13 14:34:48 +00001983 check_if_terminated_needed = False
quilesj3655ae02019-12-12 16:08:35 +00001984
tiernod8323042019-08-09 11:32:23 +00001985 # TODO register in database that primitive is done
quilesj7e13aeb2019-10-08 13:34:55 +02001986
tiernob996d942020-07-03 14:52:28 +00001987 # STEP 7 Configure metrics
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001988 if vca_type == "helm" or vca_type == "helm-v3":
bravof73bac502021-05-11 07:38:47 -04001989 prometheus_jobs = await self.extract_prometheus_scrape_jobs(
tiernob996d942020-07-03 14:52:28 +00001990 ee_id=ee_id,
1991 artifact_path=artifact_path,
1992 ee_config_descriptor=ee_config_descriptor,
1993 vnfr_id=vnfr_id,
1994 nsr_id=nsr_id,
1995 target_ip=rw_mgmt_ip,
1996 )
1997 if prometheus_jobs:
garciadeblas5697b8b2021-03-24 09:17:02 +01001998 self.update_db_2(
1999 "nsrs",
2000 nsr_id,
2001 {db_update_entry + "prometheus_jobs": prometheus_jobs},
2002 )
tiernob996d942020-07-03 14:52:28 +00002003
bravof73bac502021-05-11 07:38:47 -04002004 for job in prometheus_jobs:
2005 self.db.set_one(
2006 "prometheus_jobs",
2007 {
2008 "job_name": job["job_name"]
2009 },
2010 job,
2011 upsert=True,
2012 fail_on_empty=False
2013 )
2014
quilesj7e13aeb2019-10-08 13:34:55 +02002015 step = "instantiated at VCA"
2016 self.logger.debug(logging_text + step)
2017
tiernoc231a872020-01-21 08:49:05 +00002018 self._write_configuration_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01002019 nsr_id=nsr_id, vca_index=vca_index, status="READY"
quilesj3655ae02019-12-12 16:08:35 +00002020 )
2021
tiernod8323042019-08-09 11:32:23 +00002022 except Exception as e: # TODO not use Exception but N2VC exception
quilesj3655ae02019-12-12 16:08:35 +00002023 # self.update_db_2("nsrs", nsr_id, {db_update_entry + "instantiation": "FAILED"})
garciadeblas5697b8b2021-03-24 09:17:02 +01002024 if not isinstance(
2025 e, (DbException, N2VCException, LcmException, asyncio.CancelledError)
2026 ):
2027 self.logger.error(
2028 "Exception while {} : {}".format(step, e), exc_info=True
2029 )
tiernoc231a872020-01-21 08:49:05 +00002030 self._write_configuration_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01002031 nsr_id=nsr_id, vca_index=vca_index, status="BROKEN"
quilesj3655ae02019-12-12 16:08:35 +00002032 )
tiernoe876f672020-02-13 14:34:48 +00002033 raise LcmException("{} {}".format(step, e)) from e
tiernod8323042019-08-09 11:32:23 +00002034
garciadeblas5697b8b2021-03-24 09:17:02 +01002035 def _write_ns_status(
2036 self,
2037 nsr_id: str,
2038 ns_state: str,
2039 current_operation: str,
2040 current_operation_id: str,
2041 error_description: str = None,
2042 error_detail: str = None,
2043 other_update: dict = None,
2044 ):
tiernoe876f672020-02-13 14:34:48 +00002045 """
2046 Update db_nsr fields.
2047 :param nsr_id:
2048 :param ns_state:
2049 :param current_operation:
2050 :param current_operation_id:
2051 :param error_description:
tiernoa2143262020-03-27 16:20:40 +00002052 :param error_detail:
tiernoe876f672020-02-13 14:34:48 +00002053 :param other_update: Other required changes at database if provided, will be cleared
2054 :return:
2055 """
quilesj4cda56b2019-12-05 10:02:20 +00002056 try:
tiernoe876f672020-02-13 14:34:48 +00002057 db_dict = other_update or {}
garciadeblas5697b8b2021-03-24 09:17:02 +01002058 db_dict[
2059 "_admin.nslcmop"
2060 ] = current_operation_id # for backward compatibility
tiernoe876f672020-02-13 14:34:48 +00002061 db_dict["_admin.current-operation"] = current_operation_id
garciadeblas5697b8b2021-03-24 09:17:02 +01002062 db_dict["_admin.operation-type"] = (
2063 current_operation if current_operation != "IDLE" else None
2064 )
quilesj4cda56b2019-12-05 10:02:20 +00002065 db_dict["currentOperation"] = current_operation
2066 db_dict["currentOperationID"] = current_operation_id
2067 db_dict["errorDescription"] = error_description
tiernoa2143262020-03-27 16:20:40 +00002068 db_dict["errorDetail"] = error_detail
tiernoe876f672020-02-13 14:34:48 +00002069
2070 if ns_state:
2071 db_dict["nsState"] = ns_state
quilesj4cda56b2019-12-05 10:02:20 +00002072 self.update_db_2("nsrs", nsr_id, db_dict)
tiernoe876f672020-02-13 14:34:48 +00002073 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002074 self.logger.warn("Error writing NS status, ns={}: {}".format(nsr_id, e))
quilesj3655ae02019-12-12 16:08:35 +00002075
garciadeblas5697b8b2021-03-24 09:17:02 +01002076 def _write_op_status(
2077 self,
2078 op_id: str,
2079 stage: list = None,
2080 error_message: str = None,
2081 queuePosition: int = 0,
2082 operation_state: str = None,
2083 other_update: dict = None,
2084 ):
quilesj3655ae02019-12-12 16:08:35 +00002085 try:
tiernoe876f672020-02-13 14:34:48 +00002086 db_dict = other_update or {}
garciadeblas5697b8b2021-03-24 09:17:02 +01002087 db_dict["queuePosition"] = queuePosition
tiernoe876f672020-02-13 14:34:48 +00002088 if isinstance(stage, list):
garciadeblas5697b8b2021-03-24 09:17:02 +01002089 db_dict["stage"] = stage[0]
2090 db_dict["detailed-status"] = " ".join(stage)
tiernoe876f672020-02-13 14:34:48 +00002091 elif stage is not None:
garciadeblas5697b8b2021-03-24 09:17:02 +01002092 db_dict["stage"] = str(stage)
tiernoe876f672020-02-13 14:34:48 +00002093
2094 if error_message is not None:
garciadeblas5697b8b2021-03-24 09:17:02 +01002095 db_dict["errorMessage"] = error_message
tiernoe876f672020-02-13 14:34:48 +00002096 if operation_state is not None:
garciadeblas5697b8b2021-03-24 09:17:02 +01002097 db_dict["operationState"] = operation_state
tiernoe876f672020-02-13 14:34:48 +00002098 db_dict["statusEnteredTime"] = time()
quilesj3655ae02019-12-12 16:08:35 +00002099 self.update_db_2("nslcmops", op_id, db_dict)
tiernoe876f672020-02-13 14:34:48 +00002100 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002101 self.logger.warn(
2102 "Error writing OPERATION status for op_id: {} -> {}".format(op_id, e)
2103 )
quilesj3655ae02019-12-12 16:08:35 +00002104
tierno51183952020-04-03 15:48:18 +00002105 def _write_all_config_status(self, db_nsr: dict, status: str):
quilesj3655ae02019-12-12 16:08:35 +00002106 try:
tierno51183952020-04-03 15:48:18 +00002107 nsr_id = db_nsr["_id"]
quilesj3655ae02019-12-12 16:08:35 +00002108 # configurationStatus
garciadeblas5697b8b2021-03-24 09:17:02 +01002109 config_status = db_nsr.get("configurationStatus")
quilesj3655ae02019-12-12 16:08:35 +00002110 if config_status:
garciadeblas5697b8b2021-03-24 09:17:02 +01002111 db_nsr_update = {
2112 "configurationStatus.{}.status".format(index): status
2113 for index, v in enumerate(config_status)
2114 if v
2115 }
quilesj3655ae02019-12-12 16:08:35 +00002116 # update status
tierno51183952020-04-03 15:48:18 +00002117 self.update_db_2("nsrs", nsr_id, db_nsr_update)
quilesj3655ae02019-12-12 16:08:35 +00002118
tiernoe876f672020-02-13 14:34:48 +00002119 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002120 self.logger.warn(
2121 "Error writing all configuration status, ns={}: {}".format(nsr_id, e)
2122 )
quilesj3655ae02019-12-12 16:08:35 +00002123
garciadeblas5697b8b2021-03-24 09:17:02 +01002124 def _write_configuration_status(
2125 self,
2126 nsr_id: str,
2127 vca_index: int,
2128 status: str = None,
2129 element_under_configuration: str = None,
2130 element_type: str = None,
2131 other_update: dict = None,
2132 ):
quilesj3655ae02019-12-12 16:08:35 +00002133
2134 # self.logger.debug('_write_configuration_status(): vca_index={}, status={}'
2135 # .format(vca_index, status))
2136
2137 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01002138 db_path = "configurationStatus.{}.".format(vca_index)
tierno51183952020-04-03 15:48:18 +00002139 db_dict = other_update or {}
quilesj63f90042020-01-17 09:53:55 +00002140 if status:
garciadeblas5697b8b2021-03-24 09:17:02 +01002141 db_dict[db_path + "status"] = status
quilesj3655ae02019-12-12 16:08:35 +00002142 if element_under_configuration:
garciadeblas5697b8b2021-03-24 09:17:02 +01002143 db_dict[
2144 db_path + "elementUnderConfiguration"
2145 ] = element_under_configuration
quilesj3655ae02019-12-12 16:08:35 +00002146 if element_type:
garciadeblas5697b8b2021-03-24 09:17:02 +01002147 db_dict[db_path + "elementType"] = element_type
quilesj3655ae02019-12-12 16:08:35 +00002148 self.update_db_2("nsrs", nsr_id, db_dict)
tiernoe876f672020-02-13 14:34:48 +00002149 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002150 self.logger.warn(
2151 "Error writing configuration status={}, ns={}, vca_index={}: {}".format(
2152 status, nsr_id, vca_index, e
2153 )
2154 )
quilesj4cda56b2019-12-05 10:02:20 +00002155
tierno38089af2020-04-16 07:56:58 +00002156 async def _do_placement(self, logging_text, db_nslcmop, db_vnfrs):
2157 """
2158 Check and computes the placement, (vim account where to deploy). If it is decided by an external tool, it
2159 sends the request via kafka and wait until the result is wrote at database (nslcmops _admin.plca).
2160 Database is used because the result can be obtained from a different LCM worker in case of HA.
2161 :param logging_text: contains the prefix for logging, with the ns and nslcmop identifiers
2162 :param db_nslcmop: database content of nslcmop
2163 :param db_vnfrs: database content of vnfrs, indexed by member-vnf-index.
tierno8790a3d2020-04-23 22:49:52 +00002164 :return: True if some modification is done. Modifies database vnfrs and parameter db_vnfr with the
2165 computed 'vim-account-id'
tierno38089af2020-04-16 07:56:58 +00002166 """
tierno8790a3d2020-04-23 22:49:52 +00002167 modified = False
garciadeblas5697b8b2021-03-24 09:17:02 +01002168 nslcmop_id = db_nslcmop["_id"]
2169 placement_engine = deep_get(db_nslcmop, ("operationParams", "placement-engine"))
magnussonle9198bb2020-01-21 13:00:51 +01002170 if placement_engine == "PLA":
garciadeblas5697b8b2021-03-24 09:17:02 +01002171 self.logger.debug(
2172 logging_text + "Invoke and wait for placement optimization"
2173 )
2174 await self.msg.aiowrite(
2175 "pla", "get_placement", {"nslcmopId": nslcmop_id}, loop=self.loop
2176 )
magnussonle9198bb2020-01-21 13:00:51 +01002177 db_poll_interval = 5
tierno38089af2020-04-16 07:56:58 +00002178 wait = db_poll_interval * 10
magnussonle9198bb2020-01-21 13:00:51 +01002179 pla_result = None
2180 while not pla_result and wait >= 0:
2181 await asyncio.sleep(db_poll_interval)
2182 wait -= db_poll_interval
tierno38089af2020-04-16 07:56:58 +00002183 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
garciadeblas5697b8b2021-03-24 09:17:02 +01002184 pla_result = deep_get(db_nslcmop, ("_admin", "pla"))
magnussonle9198bb2020-01-21 13:00:51 +01002185
2186 if not pla_result:
garciadeblas5697b8b2021-03-24 09:17:02 +01002187 raise LcmException(
2188 "Placement timeout for nslcmopId={}".format(nslcmop_id)
2189 )
magnussonle9198bb2020-01-21 13:00:51 +01002190
garciadeblas5697b8b2021-03-24 09:17:02 +01002191 for pla_vnf in pla_result["vnf"]:
2192 vnfr = db_vnfrs.get(pla_vnf["member-vnf-index"])
2193 if not pla_vnf.get("vimAccountId") or not vnfr:
magnussonle9198bb2020-01-21 13:00:51 +01002194 continue
tierno8790a3d2020-04-23 22:49:52 +00002195 modified = True
garciadeblas5697b8b2021-03-24 09:17:02 +01002196 self.db.set_one(
2197 "vnfrs",
2198 {"_id": vnfr["_id"]},
2199 {"vim-account-id": pla_vnf["vimAccountId"]},
2200 )
tierno38089af2020-04-16 07:56:58 +00002201 # Modifies db_vnfrs
garciadeblas5697b8b2021-03-24 09:17:02 +01002202 vnfr["vim-account-id"] = pla_vnf["vimAccountId"]
tierno8790a3d2020-04-23 22:49:52 +00002203 return modified
magnussonle9198bb2020-01-21 13:00:51 +01002204
2205 def update_nsrs_with_pla_result(self, params):
2206 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01002207 nslcmop_id = deep_get(params, ("placement", "nslcmopId"))
2208 self.update_db_2(
2209 "nslcmops", nslcmop_id, {"_admin.pla": params.get("placement")}
2210 )
magnussonle9198bb2020-01-21 13:00:51 +01002211 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002212 self.logger.warn("Update failed for nslcmop_id={}:{}".format(nslcmop_id, e))
magnussonle9198bb2020-01-21 13:00:51 +01002213
tierno59d22d22018-09-25 18:10:19 +02002214 async def instantiate(self, nsr_id, nslcmop_id):
quilesj7e13aeb2019-10-08 13:34:55 +02002215 """
2216
2217 :param nsr_id: ns instance to deploy
2218 :param nslcmop_id: operation to run
2219 :return:
2220 """
kuused124bfe2019-06-18 12:09:24 +02002221
2222 # Try to lock HA task here
garciadeblas5697b8b2021-03-24 09:17:02 +01002223 task_is_locked_by_me = self.lcm_tasks.lock_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02002224 if not task_is_locked_by_me:
garciadeblas5697b8b2021-03-24 09:17:02 +01002225 self.logger.debug(
2226 "instantiate() task is not locked by me, ns={}".format(nsr_id)
2227 )
kuused124bfe2019-06-18 12:09:24 +02002228 return
2229
tierno59d22d22018-09-25 18:10:19 +02002230 logging_text = "Task ns={} instantiate={} ".format(nsr_id, nslcmop_id)
2231 self.logger.debug(logging_text + "Enter")
quilesj7e13aeb2019-10-08 13:34:55 +02002232
tierno59d22d22018-09-25 18:10:19 +02002233 # get all needed from database
quilesj7e13aeb2019-10-08 13:34:55 +02002234
2235 # database nsrs record
tierno59d22d22018-09-25 18:10:19 +02002236 db_nsr = None
quilesj7e13aeb2019-10-08 13:34:55 +02002237
2238 # database nslcmops record
tierno59d22d22018-09-25 18:10:19 +02002239 db_nslcmop = None
quilesj7e13aeb2019-10-08 13:34:55 +02002240
2241 # update operation on nsrs
tiernoe876f672020-02-13 14:34:48 +00002242 db_nsr_update = {}
quilesj7e13aeb2019-10-08 13:34:55 +02002243 # update operation on nslcmops
tierno59d22d22018-09-25 18:10:19 +02002244 db_nslcmop_update = {}
quilesj7e13aeb2019-10-08 13:34:55 +02002245
tierno59d22d22018-09-25 18:10:19 +02002246 nslcmop_operation_state = None
garciadeblas5697b8b2021-03-24 09:17:02 +01002247 db_vnfrs = {} # vnf's info indexed by member-index
quilesj7e13aeb2019-10-08 13:34:55 +02002248 # n2vc_info = {}
tiernoe876f672020-02-13 14:34:48 +00002249 tasks_dict_info = {} # from task to info text
tierno59d22d22018-09-25 18:10:19 +02002250 exc = None
tiernoe876f672020-02-13 14:34:48 +00002251 error_list = []
garciadeblas5697b8b2021-03-24 09:17:02 +01002252 stage = [
2253 "Stage 1/5: preparation of the environment.",
2254 "Waiting for previous operations to terminate.",
2255 "",
2256 ]
tiernoe876f672020-02-13 14:34:48 +00002257 # ^ stage, step, VIM progress
tierno59d22d22018-09-25 18:10:19 +02002258 try:
kuused124bfe2019-06-18 12:09:24 +02002259 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +01002260 await self.lcm_tasks.waitfor_related_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02002261
quilesj7e13aeb2019-10-08 13:34:55 +02002262 # STEP 0: Reading database (nslcmops, nsrs, nsds, vnfrs, vnfds)
tiernob5203912020-08-11 11:20:13 +00002263 stage[1] = "Reading from database."
quilesj4cda56b2019-12-05 10:02:20 +00002264 # nsState="BUILDING", currentOperation="INSTANTIATING", currentOperationID=nslcmop_id
tiernoe876f672020-02-13 14:34:48 +00002265 db_nsr_update["detailed-status"] = "creating"
2266 db_nsr_update["operational-status"] = "init"
quilesj4cda56b2019-12-05 10:02:20 +00002267 self._write_ns_status(
2268 nsr_id=nsr_id,
2269 ns_state="BUILDING",
2270 current_operation="INSTANTIATING",
tiernoe876f672020-02-13 14:34:48 +00002271 current_operation_id=nslcmop_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01002272 other_update=db_nsr_update,
tiernoe876f672020-02-13 14:34:48 +00002273 )
garciadeblas5697b8b2021-03-24 09:17:02 +01002274 self._write_op_status(op_id=nslcmop_id, stage=stage, queuePosition=0)
quilesj4cda56b2019-12-05 10:02:20 +00002275
quilesj7e13aeb2019-10-08 13:34:55 +02002276 # read from db: operation
tiernob5203912020-08-11 11:20:13 +00002277 stage[1] = "Getting nslcmop={} from db.".format(nslcmop_id)
tierno59d22d22018-09-25 18:10:19 +02002278 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
Guillermo Calvino57c68152022-01-26 17:40:31 +01002279 if db_nslcmop["operationParams"].get("additionalParamsForVnf"):
2280 db_nslcmop["operationParams"]["additionalParamsForVnf"] = json.loads(
2281 db_nslcmop["operationParams"]["additionalParamsForVnf"]
2282 )
tierno744303e2020-01-13 16:46:31 +00002283 ns_params = db_nslcmop.get("operationParams")
2284 if ns_params and ns_params.get("timeout_ns_deploy"):
2285 timeout_ns_deploy = ns_params["timeout_ns_deploy"]
2286 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01002287 timeout_ns_deploy = self.timeout.get(
2288 "ns_deploy", self.timeout_ns_deploy
2289 )
quilesj7e13aeb2019-10-08 13:34:55 +02002290
2291 # read from db: ns
tiernob5203912020-08-11 11:20:13 +00002292 stage[1] = "Getting nsr={} from db.".format(nsr_id)
garciadeblascd509f52021-11-23 10:04:12 +01002293 self.logger.debug(logging_text + stage[1])
tierno59d22d22018-09-25 18:10:19 +02002294 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
tiernob5203912020-08-11 11:20:13 +00002295 stage[1] = "Getting nsd={} from db.".format(db_nsr["nsd-id"])
garciadeblascd509f52021-11-23 10:04:12 +01002296 self.logger.debug(logging_text + stage[1])
tiernod732fb82020-05-21 13:18:23 +00002297 nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
bravof021e70d2021-03-11 12:03:30 -03002298 self.fs.sync(db_nsr["nsd-id"])
tiernod732fb82020-05-21 13:18:23 +00002299 db_nsr["nsd"] = nsd
tiernod8323042019-08-09 11:32:23 +00002300 # nsr_name = db_nsr["name"] # TODO short-name??
tierno47e86b52018-10-10 14:05:55 +02002301
quilesj7e13aeb2019-10-08 13:34:55 +02002302 # read from db: vnf's of this ns
tiernob5203912020-08-11 11:20:13 +00002303 stage[1] = "Getting vnfrs from db."
tiernoe876f672020-02-13 14:34:48 +00002304 self.logger.debug(logging_text + stage[1])
tierno27246d82018-09-27 15:59:09 +02002305 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
tierno27246d82018-09-27 15:59:09 +02002306
quilesj7e13aeb2019-10-08 13:34:55 +02002307 # read from db: vnfd's for every vnf
garciadeblas5697b8b2021-03-24 09:17:02 +01002308 db_vnfds = [] # every vnfd data
quilesj7e13aeb2019-10-08 13:34:55 +02002309
2310 # for each vnf in ns, read vnfd
tierno27246d82018-09-27 15:59:09 +02002311 for vnfr in db_vnfrs_list:
Guillermo Calvino57c68152022-01-26 17:40:31 +01002312 if vnfr.get("kdur"):
2313 kdur_list = []
2314 for kdur in vnfr["kdur"]:
2315 if kdur.get("additionalParams"):
2316 kdur["additionalParams"] = json.loads(kdur["additionalParams"])
2317 kdur_list.append(kdur)
2318 vnfr["kdur"] = kdur_list
2319
bravof922c4172020-11-24 21:21:43 -03002320 db_vnfrs[vnfr["member-vnf-index-ref"]] = vnfr
2321 vnfd_id = vnfr["vnfd-id"]
2322 vnfd_ref = vnfr["vnfd-ref"]
bravof021e70d2021-03-11 12:03:30 -03002323 self.fs.sync(vnfd_id)
lloretgalleg6d488782020-07-22 10:13:46 +00002324
quilesj7e13aeb2019-10-08 13:34:55 +02002325 # if we haven't this vnfd, read it from db
tierno27246d82018-09-27 15:59:09 +02002326 if vnfd_id not in db_vnfds:
quilesj63f90042020-01-17 09:53:55 +00002327 # read from db
garciadeblas5697b8b2021-03-24 09:17:02 +01002328 stage[1] = "Getting vnfd={} id='{}' from db.".format(
2329 vnfd_id, vnfd_ref
2330 )
tiernoe876f672020-02-13 14:34:48 +00002331 self.logger.debug(logging_text + stage[1])
tierno27246d82018-09-27 15:59:09 +02002332 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
tierno27246d82018-09-27 15:59:09 +02002333
quilesj7e13aeb2019-10-08 13:34:55 +02002334 # store vnfd
David Garciad41dbd62020-12-10 12:52:52 +01002335 db_vnfds.append(vnfd)
quilesj7e13aeb2019-10-08 13:34:55 +02002336
2337 # Get or generates the _admin.deployed.VCA list
tiernoe4f7e6c2018-11-27 14:55:30 +00002338 vca_deployed_list = None
2339 if db_nsr["_admin"].get("deployed"):
2340 vca_deployed_list = db_nsr["_admin"]["deployed"].get("VCA")
2341 if vca_deployed_list is None:
2342 vca_deployed_list = []
quilesj3655ae02019-12-12 16:08:35 +00002343 configuration_status_list = []
tiernoe4f7e6c2018-11-27 14:55:30 +00002344 db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
quilesj3655ae02019-12-12 16:08:35 +00002345 db_nsr_update["configurationStatus"] = configuration_status_list
quilesj7e13aeb2019-10-08 13:34:55 +02002346 # add _admin.deployed.VCA to db_nsr dictionary, value=vca_deployed_list
tierno98ad6ea2019-05-30 17:16:28 +00002347 populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
tiernoe4f7e6c2018-11-27 14:55:30 +00002348 elif isinstance(vca_deployed_list, dict):
2349 # maintain backward compatibility. Change a dict to list at database
2350 vca_deployed_list = list(vca_deployed_list.values())
2351 db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
tierno98ad6ea2019-05-30 17:16:28 +00002352 populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
tiernoe4f7e6c2018-11-27 14:55:30 +00002353
garciadeblas5697b8b2021-03-24 09:17:02 +01002354 if not isinstance(
2355 deep_get(db_nsr, ("_admin", "deployed", "RO", "vnfd")), list
2356 ):
tiernoa009e552019-01-30 16:45:44 +00002357 populate_dict(db_nsr, ("_admin", "deployed", "RO", "vnfd"), [])
2358 db_nsr_update["_admin.deployed.RO.vnfd"] = []
tierno59d22d22018-09-25 18:10:19 +02002359
tiernobaa51102018-12-14 13:16:18 +00002360 # set state to INSTANTIATED. When instantiated NBI will not delete directly
2361 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
2362 self.update_db_2("nsrs", nsr_id, db_nsr_update)
garciadeblas5697b8b2021-03-24 09:17:02 +01002363 self.db.set_list(
2364 "vnfrs", {"nsr-id-ref": nsr_id}, {"_admin.nsState": "INSTANTIATED"}
2365 )
quilesj3655ae02019-12-12 16:08:35 +00002366
2367 # n2vc_redesign STEP 2 Deploy Network Scenario
garciadeblas5697b8b2021-03-24 09:17:02 +01002368 stage[0] = "Stage 2/5: deployment of KDUs, VMs and execution environments."
2369 self._write_op_status(op_id=nslcmop_id, stage=stage)
quilesj3655ae02019-12-12 16:08:35 +00002370
tiernob5203912020-08-11 11:20:13 +00002371 stage[1] = "Deploying KDUs."
tiernoe876f672020-02-13 14:34:48 +00002372 # self.logger.debug(logging_text + "Before deploy_kdus")
calvinosanch9f9c6f22019-11-04 13:37:39 +01002373 # Call to deploy_kdus in case exists the "vdu:kdu" param
tiernoe876f672020-02-13 14:34:48 +00002374 await self.deploy_kdus(
2375 logging_text=logging_text,
2376 nsr_id=nsr_id,
2377 nslcmop_id=nslcmop_id,
2378 db_vnfrs=db_vnfrs,
2379 db_vnfds=db_vnfds,
2380 task_instantiation_info=tasks_dict_info,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002381 )
tiernoe876f672020-02-13 14:34:48 +00002382
2383 stage[1] = "Getting VCA public key."
tiernod8323042019-08-09 11:32:23 +00002384 # n2vc_redesign STEP 1 Get VCA public ssh-key
2385 # feature 1429. Add n2vc public key to needed VMs
tierno3bedc9b2019-11-27 15:46:57 +00002386 n2vc_key = self.n2vc.get_public_key()
tiernoa5088192019-11-26 16:12:53 +00002387 n2vc_key_list = [n2vc_key]
2388 if self.vca_config.get("public_key"):
2389 n2vc_key_list.append(self.vca_config["public_key"])
tierno98ad6ea2019-05-30 17:16:28 +00002390
tiernoe876f672020-02-13 14:34:48 +00002391 stage[1] = "Deploying NS at VIM."
tiernod8323042019-08-09 11:32:23 +00002392 task_ro = asyncio.ensure_future(
quilesj7e13aeb2019-10-08 13:34:55 +02002393 self.instantiate_RO(
2394 logging_text=logging_text,
2395 nsr_id=nsr_id,
2396 nsd=nsd,
2397 db_nsr=db_nsr,
2398 db_nslcmop=db_nslcmop,
2399 db_vnfrs=db_vnfrs,
bravof922c4172020-11-24 21:21:43 -03002400 db_vnfds=db_vnfds,
tiernoe876f672020-02-13 14:34:48 +00002401 n2vc_key_list=n2vc_key_list,
garciadeblas5697b8b2021-03-24 09:17:02 +01002402 stage=stage,
tierno98ad6ea2019-05-30 17:16:28 +00002403 )
tiernod8323042019-08-09 11:32:23 +00002404 )
2405 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "instantiate_RO", task_ro)
tiernoa2143262020-03-27 16:20:40 +00002406 tasks_dict_info[task_ro] = "Deploying at VIM"
tierno98ad6ea2019-05-30 17:16:28 +00002407
tiernod8323042019-08-09 11:32:23 +00002408 # n2vc_redesign STEP 3 to 6 Deploy N2VC
tiernoe876f672020-02-13 14:34:48 +00002409 stage[1] = "Deploying Execution Environments."
2410 self.logger.debug(logging_text + stage[1])
tierno98ad6ea2019-05-30 17:16:28 +00002411
tiernod8323042019-08-09 11:32:23 +00002412 nsi_id = None # TODO put nsi_id when this nsr belongs to a NSI
bravof922c4172020-11-24 21:21:43 -03002413 for vnf_profile in get_vnf_profiles(nsd):
2414 vnfd_id = vnf_profile["vnfd-id"]
2415 vnfd = find_in_list(db_vnfds, lambda a_vnf: a_vnf["id"] == vnfd_id)
2416 member_vnf_index = str(vnf_profile["id"])
tiernod8323042019-08-09 11:32:23 +00002417 db_vnfr = db_vnfrs[member_vnf_index]
2418 base_folder = vnfd["_admin"]["storage"]
2419 vdu_id = None
2420 vdu_index = 0
tierno98ad6ea2019-05-30 17:16:28 +00002421 vdu_name = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01002422 kdu_name = None
tierno59d22d22018-09-25 18:10:19 +02002423
tierno8a518872018-12-21 13:42:14 +00002424 # Get additional parameters
bravof922c4172020-11-24 21:21:43 -03002425 deploy_params = {"OSM": get_osm_params(db_vnfr)}
tiernod8323042019-08-09 11:32:23 +00002426 if db_vnfr.get("additionalParamsForVnf"):
garciadeblas5697b8b2021-03-24 09:17:02 +01002427 deploy_params.update(
2428 parse_yaml_strings(db_vnfr["additionalParamsForVnf"].copy())
2429 )
tierno8a518872018-12-21 13:42:14 +00002430
bravofe5a31bc2021-02-17 19:09:12 -03002431 descriptor_config = get_configuration(vnfd, vnfd["id"])
tierno588547c2020-07-01 15:30:20 +00002432 if descriptor_config:
quilesj7e13aeb2019-10-08 13:34:55 +02002433 self._deploy_n2vc(
garciadeblas5697b8b2021-03-24 09:17:02 +01002434 logging_text=logging_text
2435 + "member_vnf_index={} ".format(member_vnf_index),
quilesj7e13aeb2019-10-08 13:34:55 +02002436 db_nsr=db_nsr,
2437 db_vnfr=db_vnfr,
2438 nslcmop_id=nslcmop_id,
2439 nsr_id=nsr_id,
2440 nsi_id=nsi_id,
2441 vnfd_id=vnfd_id,
2442 vdu_id=vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002443 kdu_name=kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02002444 member_vnf_index=member_vnf_index,
2445 vdu_index=vdu_index,
2446 vdu_name=vdu_name,
2447 deploy_params=deploy_params,
2448 descriptor_config=descriptor_config,
2449 base_folder=base_folder,
tiernoe876f672020-02-13 14:34:48 +00002450 task_instantiation_info=tasks_dict_info,
garciadeblas5697b8b2021-03-24 09:17:02 +01002451 stage=stage,
quilesj7e13aeb2019-10-08 13:34:55 +02002452 )
tierno59d22d22018-09-25 18:10:19 +02002453
2454 # Deploy charms for each VDU that supports one.
bravof922c4172020-11-24 21:21:43 -03002455 for vdud in get_vdu_list(vnfd):
tiernod8323042019-08-09 11:32:23 +00002456 vdu_id = vdud["id"]
bravofe5a31bc2021-02-17 19:09:12 -03002457 descriptor_config = get_configuration(vnfd, vdu_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01002458 vdur = find_in_list(
2459 db_vnfr["vdur"], lambda vdu: vdu["vdu-id-ref"] == vdu_id
2460 )
bravof922c4172020-11-24 21:21:43 -03002461
tierno626e0152019-11-29 14:16:16 +00002462 if vdur.get("additionalParams"):
bravof922c4172020-11-24 21:21:43 -03002463 deploy_params_vdu = parse_yaml_strings(vdur["additionalParams"])
tierno626e0152019-11-29 14:16:16 +00002464 else:
2465 deploy_params_vdu = deploy_params
garciadeblas5697b8b2021-03-24 09:17:02 +01002466 deploy_params_vdu["OSM"] = get_osm_params(
2467 db_vnfr, vdu_id, vdu_count_index=0
2468 )
endika76ba9232021-06-21 18:55:07 +02002469 vdud_count = get_number_of_instances(vnfd, vdu_id)
bravof922c4172020-11-24 21:21:43 -03002470
2471 self.logger.debug("VDUD > {}".format(vdud))
garciadeblas5697b8b2021-03-24 09:17:02 +01002472 self.logger.debug(
2473 "Descriptor config > {}".format(descriptor_config)
2474 )
tierno588547c2020-07-01 15:30:20 +00002475 if descriptor_config:
tiernod8323042019-08-09 11:32:23 +00002476 vdu_name = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01002477 kdu_name = None
bravof922c4172020-11-24 21:21:43 -03002478 for vdu_index in range(vdud_count):
tiernod8323042019-08-09 11:32:23 +00002479 # TODO vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
quilesj7e13aeb2019-10-08 13:34:55 +02002480 self._deploy_n2vc(
garciadeblas5697b8b2021-03-24 09:17:02 +01002481 logging_text=logging_text
2482 + "member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
2483 member_vnf_index, vdu_id, vdu_index
2484 ),
quilesj7e13aeb2019-10-08 13:34:55 +02002485 db_nsr=db_nsr,
2486 db_vnfr=db_vnfr,
2487 nslcmop_id=nslcmop_id,
2488 nsr_id=nsr_id,
2489 nsi_id=nsi_id,
2490 vnfd_id=vnfd_id,
2491 vdu_id=vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002492 kdu_name=kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02002493 member_vnf_index=member_vnf_index,
2494 vdu_index=vdu_index,
2495 vdu_name=vdu_name,
tierno626e0152019-11-29 14:16:16 +00002496 deploy_params=deploy_params_vdu,
quilesj7e13aeb2019-10-08 13:34:55 +02002497 descriptor_config=descriptor_config,
2498 base_folder=base_folder,
tierno8e2fae72020-04-01 15:21:15 +00002499 task_instantiation_info=tasks_dict_info,
garciadeblas5697b8b2021-03-24 09:17:02 +01002500 stage=stage,
quilesj7e13aeb2019-10-08 13:34:55 +02002501 )
bravof922c4172020-11-24 21:21:43 -03002502 for kdud in get_kdu_list(vnfd):
calvinosanch9f9c6f22019-11-04 13:37:39 +01002503 kdu_name = kdud["name"]
bravofe5a31bc2021-02-17 19:09:12 -03002504 descriptor_config = get_configuration(vnfd, kdu_name)
tierno588547c2020-07-01 15:30:20 +00002505 if descriptor_config:
calvinosanch9f9c6f22019-11-04 13:37:39 +01002506 vdu_id = None
2507 vdu_index = 0
2508 vdu_name = None
garciadeblas5697b8b2021-03-24 09:17:02 +01002509 kdur = next(
2510 x for x in db_vnfr["kdur"] if x["kdu-name"] == kdu_name
2511 )
bravof922c4172020-11-24 21:21:43 -03002512 deploy_params_kdu = {"OSM": get_osm_params(db_vnfr)}
tierno72ef84f2020-10-06 08:22:07 +00002513 if kdur.get("additionalParams"):
garciadeblas5697b8b2021-03-24 09:17:02 +01002514 deploy_params_kdu = parse_yaml_strings(
2515 kdur["additionalParams"]
2516 )
tierno59d22d22018-09-25 18:10:19 +02002517
calvinosanch9f9c6f22019-11-04 13:37:39 +01002518 self._deploy_n2vc(
2519 logging_text=logging_text,
2520 db_nsr=db_nsr,
2521 db_vnfr=db_vnfr,
2522 nslcmop_id=nslcmop_id,
2523 nsr_id=nsr_id,
2524 nsi_id=nsi_id,
2525 vnfd_id=vnfd_id,
2526 vdu_id=vdu_id,
2527 kdu_name=kdu_name,
2528 member_vnf_index=member_vnf_index,
2529 vdu_index=vdu_index,
2530 vdu_name=vdu_name,
tierno72ef84f2020-10-06 08:22:07 +00002531 deploy_params=deploy_params_kdu,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002532 descriptor_config=descriptor_config,
2533 base_folder=base_folder,
tierno8e2fae72020-04-01 15:21:15 +00002534 task_instantiation_info=tasks_dict_info,
garciadeblas5697b8b2021-03-24 09:17:02 +01002535 stage=stage,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002536 )
tierno59d22d22018-09-25 18:10:19 +02002537
tierno1b633412019-02-25 16:48:23 +00002538 # Check if this NS has a charm configuration
tiernod8323042019-08-09 11:32:23 +00002539 descriptor_config = nsd.get("ns-configuration")
2540 if descriptor_config and descriptor_config.get("juju"):
2541 vnfd_id = None
2542 db_vnfr = None
2543 member_vnf_index = None
2544 vdu_id = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01002545 kdu_name = None
tiernod8323042019-08-09 11:32:23 +00002546 vdu_index = 0
2547 vdu_name = None
tierno1b633412019-02-25 16:48:23 +00002548
tiernod8323042019-08-09 11:32:23 +00002549 # Get additional parameters
David Garcia40603572020-12-10 20:10:53 +01002550 deploy_params = {"OSM": {"vim_account_id": ns_params["vimAccountId"]}}
tiernod8323042019-08-09 11:32:23 +00002551 if db_nsr.get("additionalParamsForNs"):
garciadeblas5697b8b2021-03-24 09:17:02 +01002552 deploy_params.update(
2553 parse_yaml_strings(db_nsr["additionalParamsForNs"].copy())
2554 )
tiernod8323042019-08-09 11:32:23 +00002555 base_folder = nsd["_admin"]["storage"]
quilesj7e13aeb2019-10-08 13:34:55 +02002556 self._deploy_n2vc(
2557 logging_text=logging_text,
2558 db_nsr=db_nsr,
2559 db_vnfr=db_vnfr,
2560 nslcmop_id=nslcmop_id,
2561 nsr_id=nsr_id,
2562 nsi_id=nsi_id,
2563 vnfd_id=vnfd_id,
2564 vdu_id=vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002565 kdu_name=kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02002566 member_vnf_index=member_vnf_index,
2567 vdu_index=vdu_index,
2568 vdu_name=vdu_name,
2569 deploy_params=deploy_params,
2570 descriptor_config=descriptor_config,
2571 base_folder=base_folder,
tierno8e2fae72020-04-01 15:21:15 +00002572 task_instantiation_info=tasks_dict_info,
garciadeblas5697b8b2021-03-24 09:17:02 +01002573 stage=stage,
quilesj7e13aeb2019-10-08 13:34:55 +02002574 )
tierno1b633412019-02-25 16:48:23 +00002575
tiernoe876f672020-02-13 14:34:48 +00002576 # rest of staff will be done at finally
tierno1b633412019-02-25 16:48:23 +00002577
garciadeblas5697b8b2021-03-24 09:17:02 +01002578 except (
2579 ROclient.ROClientException,
2580 DbException,
2581 LcmException,
2582 N2VCException,
2583 ) as e:
2584 self.logger.error(
2585 logging_text + "Exit Exception while '{}': {}".format(stage[1], e)
2586 )
tierno59d22d22018-09-25 18:10:19 +02002587 exc = e
2588 except asyncio.CancelledError:
garciadeblas5697b8b2021-03-24 09:17:02 +01002589 self.logger.error(
2590 logging_text + "Cancelled Exception while '{}'".format(stage[1])
2591 )
tierno59d22d22018-09-25 18:10:19 +02002592 exc = "Operation was cancelled"
2593 except Exception as e:
2594 exc = traceback.format_exc()
garciadeblas5697b8b2021-03-24 09:17:02 +01002595 self.logger.critical(
2596 logging_text + "Exit Exception while '{}': {}".format(stage[1], e),
2597 exc_info=True,
2598 )
tierno59d22d22018-09-25 18:10:19 +02002599 finally:
2600 if exc:
tiernoe876f672020-02-13 14:34:48 +00002601 error_list.append(str(exc))
tiernobaa51102018-12-14 13:16:18 +00002602 try:
tiernoe876f672020-02-13 14:34:48 +00002603 # wait for pending tasks
2604 if tasks_dict_info:
2605 stage[1] = "Waiting for instantiate pending tasks."
2606 self.logger.debug(logging_text + stage[1])
garciadeblas5697b8b2021-03-24 09:17:02 +01002607 error_list += await self._wait_for_tasks(
2608 logging_text,
2609 tasks_dict_info,
2610 timeout_ns_deploy,
2611 stage,
2612 nslcmop_id,
2613 nsr_id=nsr_id,
2614 )
tiernoe876f672020-02-13 14:34:48 +00002615 stage[1] = stage[2] = ""
2616 except asyncio.CancelledError:
2617 error_list.append("Cancelled")
2618 # TODO cancel all tasks
2619 except Exception as exc:
2620 error_list.append(str(exc))
quilesj4cda56b2019-12-05 10:02:20 +00002621
tiernoe876f672020-02-13 14:34:48 +00002622 # update operation-status
2623 db_nsr_update["operational-status"] = "running"
2624 # let's begin with VCA 'configured' status (later we can change it)
2625 db_nsr_update["config-status"] = "configured"
2626 for task, task_name in tasks_dict_info.items():
2627 if not task.done() or task.cancelled() or task.exception():
2628 if task_name.startswith(self.task_name_deploy_vca):
2629 # A N2VC task is pending
2630 db_nsr_update["config-status"] = "failed"
quilesj4cda56b2019-12-05 10:02:20 +00002631 else:
tiernoe876f672020-02-13 14:34:48 +00002632 # RO or KDU task is pending
2633 db_nsr_update["operational-status"] = "failed"
quilesj3655ae02019-12-12 16:08:35 +00002634
tiernoe876f672020-02-13 14:34:48 +00002635 # update status at database
2636 if error_list:
tiernoa2143262020-03-27 16:20:40 +00002637 error_detail = ". ".join(error_list)
tiernoe876f672020-02-13 14:34:48 +00002638 self.logger.error(logging_text + error_detail)
garciadeblas5697b8b2021-03-24 09:17:02 +01002639 error_description_nslcmop = "{} Detail: {}".format(
2640 stage[0], error_detail
2641 )
2642 error_description_nsr = "Operation: INSTANTIATING.{}, {}".format(
2643 nslcmop_id, stage[0]
2644 )
quilesj3655ae02019-12-12 16:08:35 +00002645
garciadeblas5697b8b2021-03-24 09:17:02 +01002646 db_nsr_update["detailed-status"] = (
2647 error_description_nsr + " Detail: " + error_detail
2648 )
tiernoe876f672020-02-13 14:34:48 +00002649 db_nslcmop_update["detailed-status"] = error_detail
2650 nslcmop_operation_state = "FAILED"
2651 ns_state = "BROKEN"
2652 else:
tiernoa2143262020-03-27 16:20:40 +00002653 error_detail = None
tiernoe876f672020-02-13 14:34:48 +00002654 error_description_nsr = error_description_nslcmop = None
2655 ns_state = "READY"
2656 db_nsr_update["detailed-status"] = "Done"
2657 db_nslcmop_update["detailed-status"] = "Done"
2658 nslcmop_operation_state = "COMPLETED"
quilesj4cda56b2019-12-05 10:02:20 +00002659
tiernoe876f672020-02-13 14:34:48 +00002660 if db_nsr:
2661 self._write_ns_status(
2662 nsr_id=nsr_id,
2663 ns_state=ns_state,
2664 current_operation="IDLE",
2665 current_operation_id=None,
2666 error_description=error_description_nsr,
tiernoa2143262020-03-27 16:20:40 +00002667 error_detail=error_detail,
garciadeblas5697b8b2021-03-24 09:17:02 +01002668 other_update=db_nsr_update,
tiernoe876f672020-02-13 14:34:48 +00002669 )
tiernoa17d4f42020-04-28 09:59:23 +00002670 self._write_op_status(
2671 op_id=nslcmop_id,
2672 stage="",
2673 error_message=error_description_nslcmop,
2674 operation_state=nslcmop_operation_state,
2675 other_update=db_nslcmop_update,
2676 )
quilesj3655ae02019-12-12 16:08:35 +00002677
tierno59d22d22018-09-25 18:10:19 +02002678 if nslcmop_operation_state:
2679 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01002680 await self.msg.aiowrite(
2681 "ns",
2682 "instantiated",
2683 {
2684 "nsr_id": nsr_id,
2685 "nslcmop_id": nslcmop_id,
2686 "operationState": nslcmop_operation_state,
2687 },
2688 loop=self.loop,
2689 )
tierno59d22d22018-09-25 18:10:19 +02002690 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002691 self.logger.error(
2692 logging_text + "kafka_write notification Exception {}".format(e)
2693 )
tierno59d22d22018-09-25 18:10:19 +02002694
2695 self.logger.debug(logging_text + "Exit")
2696 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_instantiate")
2697
David Garciab4ebcd02021-10-28 02:00:43 +02002698 def _get_vnfd(self, vnfd_id: str, cached_vnfds: Dict[str, Any]):
2699 if vnfd_id not in cached_vnfds:
2700 cached_vnfds[vnfd_id] = self.db.get_one("vnfds", {"id": vnfd_id})
2701 return cached_vnfds[vnfd_id]
2702
2703 def _get_vnfr(self, nsr_id: str, vnf_profile_id: str, cached_vnfrs: Dict[str, Any]):
2704 if vnf_profile_id not in cached_vnfrs:
2705 cached_vnfrs[vnf_profile_id] = self.db.get_one(
2706 "vnfrs",
2707 {
2708 "member-vnf-index-ref": vnf_profile_id,
2709 "nsr-id-ref": nsr_id,
2710 },
2711 )
2712 return cached_vnfrs[vnf_profile_id]
2713
2714 def _is_deployed_vca_in_relation(
2715 self, vca: DeployedVCA, relation: Relation
2716 ) -> bool:
2717 found = False
2718 for endpoint in (relation.provider, relation.requirer):
2719 if endpoint["kdu-resource-profile-id"]:
2720 continue
2721 found = (
2722 vca.vnf_profile_id == endpoint.vnf_profile_id
2723 and vca.vdu_profile_id == endpoint.vdu_profile_id
2724 and vca.execution_environment_ref == endpoint.execution_environment_ref
2725 )
2726 if found:
2727 break
2728 return found
2729
2730 def _update_ee_relation_data_with_implicit_data(
2731 self, nsr_id, nsd, ee_relation_data, cached_vnfds, vnf_profile_id: str = None
2732 ):
2733 ee_relation_data = safe_get_ee_relation(
2734 nsr_id, ee_relation_data, vnf_profile_id=vnf_profile_id
2735 )
2736 ee_relation_level = EELevel.get_level(ee_relation_data)
2737 if (ee_relation_level in (EELevel.VNF, EELevel.VDU)) and not ee_relation_data[
2738 "execution-environment-ref"
2739 ]:
2740 vnf_profile = get_vnf_profile(nsd, ee_relation_data["vnf-profile-id"])
2741 vnfd_id = vnf_profile["vnfd-id"]
2742 db_vnfd = self._get_vnfd(vnfd_id, cached_vnfds)
2743 entity_id = (
2744 vnfd_id
2745 if ee_relation_level == EELevel.VNF
2746 else ee_relation_data["vdu-profile-id"]
2747 )
2748 ee = get_juju_ee_ref(db_vnfd, entity_id)
2749 if not ee:
2750 raise Exception(
2751 f"not execution environments found for ee_relation {ee_relation_data}"
2752 )
2753 ee_relation_data["execution-environment-ref"] = ee["id"]
2754 return ee_relation_data
2755
2756 def _get_ns_relations(
2757 self,
2758 nsr_id: str,
2759 nsd: Dict[str, Any],
2760 vca: DeployedVCA,
2761 cached_vnfds: Dict[str, Any],
David Garcia444bf962021-11-11 16:35:26 +01002762 ) -> List[Relation]:
David Garciab4ebcd02021-10-28 02:00:43 +02002763 relations = []
2764 db_ns_relations = get_ns_configuration_relation_list(nsd)
2765 for r in db_ns_relations:
David Garcia444bf962021-11-11 16:35:26 +01002766 provider_dict = None
2767 requirer_dict = None
2768 if all(key in r for key in ("provider", "requirer")):
2769 provider_dict = r["provider"]
2770 requirer_dict = r["requirer"]
2771 elif "entities" in r:
2772 provider_id = r["entities"][0]["id"]
2773 provider_dict = {
2774 "nsr-id": nsr_id,
2775 "endpoint": r["entities"][0]["endpoint"],
2776 }
2777 if provider_id != nsd["id"]:
2778 provider_dict["vnf-profile-id"] = provider_id
2779 requirer_id = r["entities"][1]["id"]
2780 requirer_dict = {
2781 "nsr-id": nsr_id,
2782 "endpoint": r["entities"][1]["endpoint"],
2783 }
2784 if requirer_id != nsd["id"]:
2785 requirer_dict["vnf-profile-id"] = requirer_id
2786 else:
2787 raise Exception("provider/requirer or entities must be included in the relation.")
David Garciab4ebcd02021-10-28 02:00:43 +02002788 relation_provider = self._update_ee_relation_data_with_implicit_data(
David Garcia444bf962021-11-11 16:35:26 +01002789 nsr_id, nsd, provider_dict, cached_vnfds
David Garciab4ebcd02021-10-28 02:00:43 +02002790 )
2791 relation_requirer = self._update_ee_relation_data_with_implicit_data(
David Garcia444bf962021-11-11 16:35:26 +01002792 nsr_id, nsd, requirer_dict, cached_vnfds
David Garciab4ebcd02021-10-28 02:00:43 +02002793 )
2794 provider = EERelation(relation_provider)
2795 requirer = EERelation(relation_requirer)
2796 relation = Relation(r["name"], provider, requirer)
2797 vca_in_relation = self._is_deployed_vca_in_relation(vca, relation)
2798 if vca_in_relation:
2799 relations.append(relation)
2800 return relations
2801
2802 def _get_vnf_relations(
2803 self,
2804 nsr_id: str,
2805 nsd: Dict[str, Any],
2806 vca: DeployedVCA,
2807 cached_vnfds: Dict[str, Any],
David Garcia444bf962021-11-11 16:35:26 +01002808 ) -> List[Relation]:
David Garciab4ebcd02021-10-28 02:00:43 +02002809 relations = []
2810 vnf_profile = get_vnf_profile(nsd, vca.vnf_profile_id)
2811 vnf_profile_id = vnf_profile["id"]
2812 vnfd_id = vnf_profile["vnfd-id"]
2813 db_vnfd = self._get_vnfd(vnfd_id, cached_vnfds)
2814 db_vnf_relations = get_relation_list(db_vnfd, vnfd_id)
2815 for r in db_vnf_relations:
David Garcia444bf962021-11-11 16:35:26 +01002816 provider_dict = None
2817 requirer_dict = None
2818 if all(key in r for key in ("provider", "requirer")):
2819 provider_dict = r["provider"]
2820 requirer_dict = r["requirer"]
2821 elif "entities" in r:
2822 provider_id = r["entities"][0]["id"]
2823 provider_dict = {
2824 "nsr-id": nsr_id,
2825 "vnf-profile-id": vnf_profile_id,
2826 "endpoint": r["entities"][0]["endpoint"],
2827 }
2828 if provider_id != vnfd_id:
2829 provider_dict["vdu-profile-id"] = provider_id
2830 requirer_id = r["entities"][1]["id"]
2831 requirer_dict = {
2832 "nsr-id": nsr_id,
2833 "vnf-profile-id": vnf_profile_id,
2834 "endpoint": r["entities"][1]["endpoint"],
2835 }
2836 if requirer_id != vnfd_id:
2837 requirer_dict["vdu-profile-id"] = requirer_id
2838 else:
2839 raise Exception("provider/requirer or entities must be included in the relation.")
David Garciab4ebcd02021-10-28 02:00:43 +02002840 relation_provider = self._update_ee_relation_data_with_implicit_data(
David Garcia444bf962021-11-11 16:35:26 +01002841 nsr_id, nsd, provider_dict, cached_vnfds, vnf_profile_id=vnf_profile_id
David Garciab4ebcd02021-10-28 02:00:43 +02002842 )
2843 relation_requirer = self._update_ee_relation_data_with_implicit_data(
David Garcia444bf962021-11-11 16:35:26 +01002844 nsr_id, nsd, requirer_dict, cached_vnfds, vnf_profile_id=vnf_profile_id
David Garciab4ebcd02021-10-28 02:00:43 +02002845 )
2846 provider = EERelation(relation_provider)
2847 requirer = EERelation(relation_requirer)
2848 relation = Relation(r["name"], provider, requirer)
2849 vca_in_relation = self._is_deployed_vca_in_relation(vca, relation)
2850 if vca_in_relation:
2851 relations.append(relation)
2852 return relations
2853
2854 def _get_kdu_resource_data(
2855 self,
2856 ee_relation: EERelation,
2857 db_nsr: Dict[str, Any],
2858 cached_vnfds: Dict[str, Any],
2859 ) -> DeployedK8sResource:
2860 nsd = get_nsd(db_nsr)
2861 vnf_profiles = get_vnf_profiles(nsd)
2862 vnfd_id = find_in_list(
2863 vnf_profiles,
2864 lambda vnf_profile: vnf_profile["id"] == ee_relation.vnf_profile_id,
2865 )["vnfd-id"]
2866 db_vnfd = self._get_vnfd(vnfd_id, cached_vnfds)
2867 kdu_resource_profile = get_kdu_resource_profile(
2868 db_vnfd, ee_relation.kdu_resource_profile_id
2869 )
2870 kdu_name = kdu_resource_profile["kdu-name"]
2871 deployed_kdu, _ = get_deployed_kdu(
2872 db_nsr.get("_admin", ()).get("deployed", ()),
2873 kdu_name,
2874 ee_relation.vnf_profile_id,
2875 )
2876 deployed_kdu.update({"resource-name": kdu_resource_profile["resource-name"]})
2877 return deployed_kdu
2878
2879 def _get_deployed_component(
2880 self,
2881 ee_relation: EERelation,
2882 db_nsr: Dict[str, Any],
2883 cached_vnfds: Dict[str, Any],
2884 ) -> DeployedComponent:
2885 nsr_id = db_nsr["_id"]
2886 deployed_component = None
2887 ee_level = EELevel.get_level(ee_relation)
2888 if ee_level == EELevel.NS:
2889 vca = get_deployed_vca(db_nsr, {"vdu_id": None, "member-vnf-index": None})
2890 if vca:
2891 deployed_component = DeployedVCA(nsr_id, vca)
2892 elif ee_level == EELevel.VNF:
2893 vca = get_deployed_vca(
2894 db_nsr,
2895 {
2896 "vdu_id": None,
2897 "member-vnf-index": ee_relation.vnf_profile_id,
2898 "ee_descriptor_id": ee_relation.execution_environment_ref,
2899 },
2900 )
2901 if vca:
2902 deployed_component = DeployedVCA(nsr_id, vca)
2903 elif ee_level == EELevel.VDU:
2904 vca = get_deployed_vca(
2905 db_nsr,
2906 {
2907 "vdu_id": ee_relation.vdu_profile_id,
2908 "member-vnf-index": ee_relation.vnf_profile_id,
2909 "ee_descriptor_id": ee_relation.execution_environment_ref,
2910 },
2911 )
2912 if vca:
2913 deployed_component = DeployedVCA(nsr_id, vca)
2914 elif ee_level == EELevel.KDU:
2915 kdu_resource_data = self._get_kdu_resource_data(
2916 ee_relation, db_nsr, cached_vnfds
2917 )
2918 if kdu_resource_data:
2919 deployed_component = DeployedK8sResource(kdu_resource_data)
2920 return deployed_component
2921
2922 async def _add_relation(
2923 self,
2924 relation: Relation,
2925 vca_type: str,
2926 db_nsr: Dict[str, Any],
2927 cached_vnfds: Dict[str, Any],
2928 cached_vnfrs: Dict[str, Any],
2929 ) -> bool:
2930 deployed_provider = self._get_deployed_component(
2931 relation.provider, db_nsr, cached_vnfds
2932 )
2933 deployed_requirer = self._get_deployed_component(
2934 relation.requirer, db_nsr, cached_vnfds
2935 )
2936 if (
2937 deployed_provider
2938 and deployed_requirer
2939 and deployed_provider.config_sw_installed
2940 and deployed_requirer.config_sw_installed
2941 ):
2942 provider_db_vnfr = (
2943 self._get_vnfr(
2944 relation.provider.nsr_id,
2945 relation.provider.vnf_profile_id,
2946 cached_vnfrs,
2947 )
2948 if relation.provider.vnf_profile_id
2949 else None
2950 )
2951 requirer_db_vnfr = (
2952 self._get_vnfr(
2953 relation.requirer.nsr_id,
2954 relation.requirer.vnf_profile_id,
2955 cached_vnfrs,
2956 )
2957 if relation.requirer.vnf_profile_id
2958 else None
2959 )
2960 provider_vca_id = self.get_vca_id(provider_db_vnfr, db_nsr)
2961 requirer_vca_id = self.get_vca_id(requirer_db_vnfr, db_nsr)
2962 provider_relation_endpoint = RelationEndpoint(
2963 deployed_provider.ee_id,
2964 provider_vca_id,
2965 relation.provider.endpoint,
2966 )
2967 requirer_relation_endpoint = RelationEndpoint(
2968 deployed_requirer.ee_id,
2969 requirer_vca_id,
2970 relation.requirer.endpoint,
2971 )
2972 await self.vca_map[vca_type].add_relation(
2973 provider=provider_relation_endpoint,
2974 requirer=requirer_relation_endpoint,
2975 )
2976 # remove entry from relations list
2977 return True
2978 return False
2979
David Garciac1fe90a2021-03-31 19:12:02 +02002980 async def _add_vca_relations(
2981 self,
2982 logging_text,
2983 nsr_id,
David Garciab4ebcd02021-10-28 02:00:43 +02002984 vca_type: str,
David Garciac1fe90a2021-03-31 19:12:02 +02002985 vca_index: int,
2986 timeout: int = 3600,
David Garciac1fe90a2021-03-31 19:12:02 +02002987 ) -> bool:
quilesj63f90042020-01-17 09:53:55 +00002988
2989 # steps:
2990 # 1. find all relations for this VCA
2991 # 2. wait for other peers related
2992 # 3. add relations
2993
2994 try:
quilesj63f90042020-01-17 09:53:55 +00002995 # STEP 1: find all relations for this VCA
2996
2997 # read nsr record
2998 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
David Garciab4ebcd02021-10-28 02:00:43 +02002999 nsd = get_nsd(db_nsr)
quilesj63f90042020-01-17 09:53:55 +00003000
3001 # this VCA data
David Garciab4ebcd02021-10-28 02:00:43 +02003002 deployed_vca_dict = get_deployed_vca_list(db_nsr)[vca_index]
3003 my_vca = DeployedVCA(nsr_id, deployed_vca_dict)
quilesj63f90042020-01-17 09:53:55 +00003004
David Garciab4ebcd02021-10-28 02:00:43 +02003005 cached_vnfds = {}
3006 cached_vnfrs = {}
3007 relations = []
3008 relations.extend(self._get_ns_relations(nsr_id, nsd, my_vca, cached_vnfds))
3009 relations.extend(self._get_vnf_relations(nsr_id, nsd, my_vca, cached_vnfds))
quilesj63f90042020-01-17 09:53:55 +00003010
3011 # if no relations, terminate
David Garciab4ebcd02021-10-28 02:00:43 +02003012 if not relations:
garciadeblas5697b8b2021-03-24 09:17:02 +01003013 self.logger.debug(logging_text + " No relations")
quilesj63f90042020-01-17 09:53:55 +00003014 return True
3015
David Garciab4ebcd02021-10-28 02:00:43 +02003016 self.logger.debug(logging_text + " adding relations {}".format(relations))
quilesj63f90042020-01-17 09:53:55 +00003017
3018 # add all relations
3019 start = time()
3020 while True:
3021 # check timeout
3022 now = time()
3023 if now - start >= timeout:
garciadeblas5697b8b2021-03-24 09:17:02 +01003024 self.logger.error(logging_text + " : timeout adding relations")
quilesj63f90042020-01-17 09:53:55 +00003025 return False
3026
David Garciab4ebcd02021-10-28 02:00:43 +02003027 # reload nsr from database (we need to update record: _admin.deployed.VCA)
quilesj63f90042020-01-17 09:53:55 +00003028 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
3029
David Garciab4ebcd02021-10-28 02:00:43 +02003030 # for each relation, find the VCA's related
3031 for relation in relations.copy():
3032 added = await self._add_relation(
3033 relation,
3034 vca_type,
3035 db_nsr,
3036 cached_vnfds,
3037 cached_vnfrs,
3038 )
3039 if added:
3040 relations.remove(relation)
quilesj63f90042020-01-17 09:53:55 +00003041
David Garciab4ebcd02021-10-28 02:00:43 +02003042 if not relations:
garciadeblas5697b8b2021-03-24 09:17:02 +01003043 self.logger.debug("Relations added")
quilesj63f90042020-01-17 09:53:55 +00003044 break
David Garciab4ebcd02021-10-28 02:00:43 +02003045 await asyncio.sleep(5.0)
quilesj63f90042020-01-17 09:53:55 +00003046
3047 return True
3048
3049 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01003050 self.logger.warn(logging_text + " ERROR adding relations: {}".format(e))
quilesj63f90042020-01-17 09:53:55 +00003051 return False
3052
garciadeblas5697b8b2021-03-24 09:17:02 +01003053 async def _install_kdu(
3054 self,
3055 nsr_id: str,
3056 nsr_db_path: str,
3057 vnfr_data: dict,
3058 kdu_index: int,
3059 kdud: dict,
3060 vnfd: dict,
3061 k8s_instance_info: dict,
3062 k8params: dict = None,
3063 timeout: int = 600,
3064 vca_id: str = None,
3065 ):
lloretgalleg7c121132020-07-08 07:53:22 +00003066
tiernob9018152020-04-16 14:18:24 +00003067 try:
lloretgalleg7c121132020-07-08 07:53:22 +00003068 k8sclustertype = k8s_instance_info["k8scluster-type"]
3069 # Instantiate kdu
garciadeblas5697b8b2021-03-24 09:17:02 +01003070 db_dict_install = {
3071 "collection": "nsrs",
3072 "filter": {"_id": nsr_id},
3073 "path": nsr_db_path,
3074 }
lloretgalleg7c121132020-07-08 07:53:22 +00003075
romeromonser4554a702021-05-28 12:00:08 +02003076 if k8s_instance_info.get("kdu-deployment-name"):
3077 kdu_instance = k8s_instance_info.get("kdu-deployment-name")
3078 else:
3079 kdu_instance = self.k8scluster_map[
3080 k8sclustertype
3081 ].generate_kdu_instance_name(
3082 db_dict=db_dict_install,
3083 kdu_model=k8s_instance_info["kdu-model"],
3084 kdu_name=k8s_instance_info["kdu-name"],
3085 )
garciadeblas5697b8b2021-03-24 09:17:02 +01003086 self.update_db_2(
3087 "nsrs", nsr_id, {nsr_db_path + ".kdu-instance": kdu_instance}
3088 )
David Garciad64e2742021-02-25 20:19:18 +01003089 await self.k8scluster_map[k8sclustertype].install(
lloretgalleg7c121132020-07-08 07:53:22 +00003090 cluster_uuid=k8s_instance_info["k8scluster-uuid"],
3091 kdu_model=k8s_instance_info["kdu-model"],
3092 atomic=True,
3093 params=k8params,
3094 db_dict=db_dict_install,
3095 timeout=timeout,
3096 kdu_name=k8s_instance_info["kdu-name"],
David Garciad64e2742021-02-25 20:19:18 +01003097 namespace=k8s_instance_info["namespace"],
3098 kdu_instance=kdu_instance,
David Garciac1fe90a2021-03-31 19:12:02 +02003099 vca_id=vca_id,
David Garciad64e2742021-02-25 20:19:18 +01003100 )
garciadeblas5697b8b2021-03-24 09:17:02 +01003101 self.update_db_2(
3102 "nsrs", nsr_id, {nsr_db_path + ".kdu-instance": kdu_instance}
3103 )
lloretgalleg7c121132020-07-08 07:53:22 +00003104
3105 # Obtain services to obtain management service ip
3106 services = await self.k8scluster_map[k8sclustertype].get_services(
3107 cluster_uuid=k8s_instance_info["k8scluster-uuid"],
3108 kdu_instance=kdu_instance,
garciadeblas5697b8b2021-03-24 09:17:02 +01003109 namespace=k8s_instance_info["namespace"],
3110 )
lloretgalleg7c121132020-07-08 07:53:22 +00003111
3112 # Obtain management service info (if exists)
tierno7ecbc342020-09-21 14:05:39 +00003113 vnfr_update_dict = {}
bravof6ec62b72021-02-25 17:20:35 -03003114 kdu_config = get_configuration(vnfd, kdud["name"])
3115 if kdu_config:
3116 target_ee_list = kdu_config.get("execution-environment-list", [])
3117 else:
3118 target_ee_list = []
3119
lloretgalleg7c121132020-07-08 07:53:22 +00003120 if services:
tierno7ecbc342020-09-21 14:05:39 +00003121 vnfr_update_dict["kdur.{}.services".format(kdu_index)] = services
garciadeblas5697b8b2021-03-24 09:17:02 +01003122 mgmt_services = [
3123 service
3124 for service in kdud.get("service", [])
3125 if service.get("mgmt-service")
3126 ]
lloretgalleg7c121132020-07-08 07:53:22 +00003127 for mgmt_service in mgmt_services:
3128 for service in services:
3129 if service["name"].startswith(mgmt_service["name"]):
3130 # Mgmt service found, Obtain service ip
3131 ip = service.get("external_ip", service.get("cluster_ip"))
3132 if isinstance(ip, list) and len(ip) == 1:
3133 ip = ip[0]
3134
garciadeblas5697b8b2021-03-24 09:17:02 +01003135 vnfr_update_dict[
3136 "kdur.{}.ip-address".format(kdu_index)
3137 ] = ip
lloretgalleg7c121132020-07-08 07:53:22 +00003138
3139 # Check if must update also mgmt ip at the vnf
garciadeblas5697b8b2021-03-24 09:17:02 +01003140 service_external_cp = mgmt_service.get(
3141 "external-connection-point-ref"
3142 )
lloretgalleg7c121132020-07-08 07:53:22 +00003143 if service_external_cp:
garciadeblas5697b8b2021-03-24 09:17:02 +01003144 if (
3145 deep_get(vnfd, ("mgmt-interface", "cp"))
3146 == service_external_cp
3147 ):
lloretgalleg7c121132020-07-08 07:53:22 +00003148 vnfr_update_dict["ip-address"] = ip
3149
bravof6ec62b72021-02-25 17:20:35 -03003150 if find_in_list(
3151 target_ee_list,
garciadeblas5697b8b2021-03-24 09:17:02 +01003152 lambda ee: ee.get(
3153 "external-connection-point-ref", ""
3154 )
3155 == service_external_cp,
bravof6ec62b72021-02-25 17:20:35 -03003156 ):
garciadeblas5697b8b2021-03-24 09:17:02 +01003157 vnfr_update_dict[
3158 "kdur.{}.ip-address".format(kdu_index)
3159 ] = ip
lloretgalleg7c121132020-07-08 07:53:22 +00003160 break
3161 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01003162 self.logger.warn(
3163 "Mgmt service name: {} not found".format(
3164 mgmt_service["name"]
3165 )
3166 )
lloretgalleg7c121132020-07-08 07:53:22 +00003167
tierno7ecbc342020-09-21 14:05:39 +00003168 vnfr_update_dict["kdur.{}.status".format(kdu_index)] = "READY"
3169 self.update_db_2("vnfrs", vnfr_data.get("_id"), vnfr_update_dict)
lloretgalleg7c121132020-07-08 07:53:22 +00003170
bravof9a256db2021-02-22 18:02:07 -03003171 kdu_config = get_configuration(vnfd, k8s_instance_info["kdu-name"])
garciadeblas5697b8b2021-03-24 09:17:02 +01003172 if (
3173 kdu_config
3174 and kdu_config.get("initial-config-primitive")
3175 and get_juju_ee_ref(vnfd, k8s_instance_info["kdu-name"]) is None
3176 ):
3177 initial_config_primitive_list = kdu_config.get(
3178 "initial-config-primitive"
3179 )
Dominik Fleischmannc1975dd2020-08-19 12:17:51 +02003180 initial_config_primitive_list.sort(key=lambda val: int(val["seq"]))
3181
3182 for initial_config_primitive in initial_config_primitive_list:
garciadeblas5697b8b2021-03-24 09:17:02 +01003183 primitive_params_ = self._map_primitive_params(
3184 initial_config_primitive, {}, {}
3185 )
Dominik Fleischmannc1975dd2020-08-19 12:17:51 +02003186
3187 await asyncio.wait_for(
3188 self.k8scluster_map[k8sclustertype].exec_primitive(
3189 cluster_uuid=k8s_instance_info["k8scluster-uuid"],
3190 kdu_instance=kdu_instance,
3191 primitive_name=initial_config_primitive["name"],
garciadeblas5697b8b2021-03-24 09:17:02 +01003192 params=primitive_params_,
3193 db_dict=db_dict_install,
David Garciac1fe90a2021-03-31 19:12:02 +02003194 vca_id=vca_id,
3195 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01003196 timeout=timeout,
David Garciac1fe90a2021-03-31 19:12:02 +02003197 )
Dominik Fleischmannc1975dd2020-08-19 12:17:51 +02003198
tiernob9018152020-04-16 14:18:24 +00003199 except Exception as e:
lloretgalleg7c121132020-07-08 07:53:22 +00003200 # Prepare update db with error and raise exception
tiernob9018152020-04-16 14:18:24 +00003201 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01003202 self.update_db_2(
3203 "nsrs", nsr_id, {nsr_db_path + ".detailed-status": str(e)}
3204 )
3205 self.update_db_2(
3206 "vnfrs",
3207 vnfr_data.get("_id"),
3208 {"kdur.{}.status".format(kdu_index): "ERROR"},
3209 )
tiernob9018152020-04-16 14:18:24 +00003210 except Exception:
lloretgalleg7c121132020-07-08 07:53:22 +00003211 # ignore to keep original exception
tiernob9018152020-04-16 14:18:24 +00003212 pass
lloretgalleg7c121132020-07-08 07:53:22 +00003213 # reraise original error
3214 raise
3215
3216 return kdu_instance
tiernob9018152020-04-16 14:18:24 +00003217
garciadeblas5697b8b2021-03-24 09:17:02 +01003218 async def deploy_kdus(
3219 self,
3220 logging_text,
3221 nsr_id,
3222 nslcmop_id,
3223 db_vnfrs,
3224 db_vnfds,
3225 task_instantiation_info,
3226 ):
calvinosanch9f9c6f22019-11-04 13:37:39 +01003227 # Launch kdus if present in the descriptor
tierno626e0152019-11-29 14:16:16 +00003228
garciadeblas5697b8b2021-03-24 09:17:02 +01003229 k8scluster_id_2_uuic = {
3230 "helm-chart-v3": {},
3231 "helm-chart": {},
3232 "juju-bundle": {},
3233 }
tierno626e0152019-11-29 14:16:16 +00003234
tierno16f4a4e2020-07-20 09:05:51 +00003235 async def _get_cluster_id(cluster_id, cluster_type):
tierno626e0152019-11-29 14:16:16 +00003236 nonlocal k8scluster_id_2_uuic
3237 if cluster_id in k8scluster_id_2_uuic[cluster_type]:
3238 return k8scluster_id_2_uuic[cluster_type][cluster_id]
3239
tierno16f4a4e2020-07-20 09:05:51 +00003240 # check if K8scluster is creating and wait look if previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +01003241 task_name, task_dependency = self.lcm_tasks.lookfor_related(
3242 "k8scluster", cluster_id
3243 )
tierno16f4a4e2020-07-20 09:05:51 +00003244 if task_dependency:
garciadeblas5697b8b2021-03-24 09:17:02 +01003245 text = "Waiting for related tasks '{}' on k8scluster {} to be completed".format(
3246 task_name, cluster_id
3247 )
tierno16f4a4e2020-07-20 09:05:51 +00003248 self.logger.debug(logging_text + text)
3249 await asyncio.wait(task_dependency, timeout=3600)
3250
garciadeblas5697b8b2021-03-24 09:17:02 +01003251 db_k8scluster = self.db.get_one(
3252 "k8sclusters", {"_id": cluster_id}, fail_on_empty=False
3253 )
tierno626e0152019-11-29 14:16:16 +00003254 if not db_k8scluster:
3255 raise LcmException("K8s cluster {} cannot be found".format(cluster_id))
tierno16f4a4e2020-07-20 09:05:51 +00003256
tierno626e0152019-11-29 14:16:16 +00003257 k8s_id = deep_get(db_k8scluster, ("_admin", cluster_type, "id"))
3258 if not k8s_id:
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003259 if cluster_type == "helm-chart-v3":
3260 try:
3261 # backward compatibility for existing clusters that have not been initialized for helm v3
garciadeblas5697b8b2021-03-24 09:17:02 +01003262 k8s_credentials = yaml.safe_dump(
3263 db_k8scluster.get("credentials")
3264 )
3265 k8s_id, uninstall_sw = await self.k8sclusterhelm3.init_env(
3266 k8s_credentials, reuse_cluster_uuid=cluster_id
3267 )
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003268 db_k8scluster_update = {}
3269 db_k8scluster_update["_admin.helm-chart-v3.error_msg"] = None
3270 db_k8scluster_update["_admin.helm-chart-v3.id"] = k8s_id
garciadeblas5697b8b2021-03-24 09:17:02 +01003271 db_k8scluster_update[
3272 "_admin.helm-chart-v3.created"
3273 ] = uninstall_sw
3274 db_k8scluster_update[
3275 "_admin.helm-chart-v3.operationalState"
3276 ] = "ENABLED"
3277 self.update_db_2(
3278 "k8sclusters", cluster_id, db_k8scluster_update
3279 )
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003280 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01003281 self.logger.error(
3282 logging_text
3283 + "error initializing helm-v3 cluster: {}".format(str(e))
3284 )
3285 raise LcmException(
3286 "K8s cluster '{}' has not been initialized for '{}'".format(
3287 cluster_id, cluster_type
3288 )
3289 )
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003290 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01003291 raise LcmException(
3292 "K8s cluster '{}' has not been initialized for '{}'".format(
3293 cluster_id, cluster_type
3294 )
3295 )
tierno626e0152019-11-29 14:16:16 +00003296 k8scluster_id_2_uuic[cluster_type][cluster_id] = k8s_id
3297 return k8s_id
3298
3299 logging_text += "Deploy kdus: "
tiernoe876f672020-02-13 14:34:48 +00003300 step = ""
calvinosanch9f9c6f22019-11-04 13:37:39 +01003301 try:
tierno626e0152019-11-29 14:16:16 +00003302 db_nsr_update = {"_admin.deployed.K8s": []}
calvinosanch9f9c6f22019-11-04 13:37:39 +01003303 self.update_db_2("nsrs", nsr_id, db_nsr_update)
calvinosanch9f9c6f22019-11-04 13:37:39 +01003304
tierno626e0152019-11-29 14:16:16 +00003305 index = 0
tiernoe876f672020-02-13 14:34:48 +00003306 updated_cluster_list = []
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003307 updated_v3_cluster_list = []
tiernoe876f672020-02-13 14:34:48 +00003308
tierno626e0152019-11-29 14:16:16 +00003309 for vnfr_data in db_vnfrs.values():
David Garciac1fe90a2021-03-31 19:12:02 +02003310 vca_id = self.get_vca_id(vnfr_data, {})
lloretgalleg7c121132020-07-08 07:53:22 +00003311 for kdu_index, kdur in enumerate(get_iterable(vnfr_data, "kdur")):
3312 # Step 0: Prepare and set parameters
bravof922c4172020-11-24 21:21:43 -03003313 desc_params = parse_yaml_strings(kdur.get("additionalParams"))
garciadeblas5697b8b2021-03-24 09:17:02 +01003314 vnfd_id = vnfr_data.get("vnfd-id")
3315 vnfd_with_id = find_in_list(
3316 db_vnfds, lambda vnfd: vnfd["_id"] == vnfd_id
3317 )
3318 kdud = next(
3319 kdud
3320 for kdud in vnfd_with_id["kdu"]
3321 if kdud["name"] == kdur["kdu-name"]
3322 )
tiernode1584f2020-04-07 09:07:33 +00003323 namespace = kdur.get("k8s-namespace")
romeromonser4554a702021-05-28 12:00:08 +02003324 kdu_deployment_name = kdur.get("kdu-deployment-name")
tierno626e0152019-11-29 14:16:16 +00003325 if kdur.get("helm-chart"):
lloretgalleg07e53f52020-12-15 10:54:02 +00003326 kdumodel = kdur["helm-chart"]
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003327 # Default version: helm3, if helm-version is v2 assign v2
3328 k8sclustertype = "helm-chart-v3"
3329 self.logger.debug("kdur: {}".format(kdur))
garciadeblas5697b8b2021-03-24 09:17:02 +01003330 if (
3331 kdur.get("helm-version")
3332 and kdur.get("helm-version") == "v2"
3333 ):
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003334 k8sclustertype = "helm-chart"
tierno626e0152019-11-29 14:16:16 +00003335 elif kdur.get("juju-bundle"):
lloretgalleg07e53f52020-12-15 10:54:02 +00003336 kdumodel = kdur["juju-bundle"]
tiernoe876f672020-02-13 14:34:48 +00003337 k8sclustertype = "juju-bundle"
tierno626e0152019-11-29 14:16:16 +00003338 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01003339 raise LcmException(
3340 "kdu type for kdu='{}.{}' is neither helm-chart nor "
3341 "juju-bundle. Maybe an old NBI version is running".format(
3342 vnfr_data["member-vnf-index-ref"], kdur["kdu-name"]
3343 )
3344 )
quilesjacde94f2020-01-23 10:07:08 +00003345 # check if kdumodel is a file and exists
3346 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01003347 vnfd_with_id = find_in_list(
3348 db_vnfds, lambda vnfd: vnfd["_id"] == vnfd_id
3349 )
3350 storage = deep_get(vnfd_with_id, ("_admin", "storage"))
bravof486707f2021-11-08 17:18:50 -03003351 if storage: # may be not present if vnfd has not artifacts
tierno51183952020-04-03 15:48:18 +00003352 # path format: /vnfdid/pkkdir/helm-charts|juju-bundles/kdumodel
bravof486707f2021-11-08 17:18:50 -03003353 if storage["pkg-dir"]:
3354 filename = "{}/{}/{}s/{}".format(
3355 storage["folder"],
3356 storage["pkg-dir"],
3357 k8sclustertype,
3358 kdumodel,
3359 )
3360 else:
3361 filename = "{}/Scripts/{}s/{}".format(
3362 storage["folder"],
3363 k8sclustertype,
3364 kdumodel,
3365 )
garciadeblas5697b8b2021-03-24 09:17:02 +01003366 if self.fs.file_exists(
3367 filename, mode="file"
3368 ) or self.fs.file_exists(filename, mode="dir"):
tierno51183952020-04-03 15:48:18 +00003369 kdumodel = self.fs.path + filename
3370 except (asyncio.TimeoutError, asyncio.CancelledError):
tiernoe876f672020-02-13 14:34:48 +00003371 raise
garciadeblas5697b8b2021-03-24 09:17:02 +01003372 except Exception: # it is not a file
quilesjacde94f2020-01-23 10:07:08 +00003373 pass
lloretgallegedc5f332020-02-20 11:50:50 +01003374
tiernoe876f672020-02-13 14:34:48 +00003375 k8s_cluster_id = kdur["k8s-cluster"]["id"]
garciadeblas5697b8b2021-03-24 09:17:02 +01003376 step = "Synchronize repos for k8s cluster '{}'".format(
3377 k8s_cluster_id
3378 )
tierno16f4a4e2020-07-20 09:05:51 +00003379 cluster_uuid = await _get_cluster_id(k8s_cluster_id, k8sclustertype)
lloretgallegedc5f332020-02-20 11:50:50 +01003380
lloretgalleg7c121132020-07-08 07:53:22 +00003381 # Synchronize repos
garciadeblas5697b8b2021-03-24 09:17:02 +01003382 if (
3383 k8sclustertype == "helm-chart"
3384 and cluster_uuid not in updated_cluster_list
3385 ) or (
3386 k8sclustertype == "helm-chart-v3"
3387 and cluster_uuid not in updated_v3_cluster_list
3388 ):
tiernoe876f672020-02-13 14:34:48 +00003389 del_repo_list, added_repo_dict = await asyncio.ensure_future(
garciadeblas5697b8b2021-03-24 09:17:02 +01003390 self.k8scluster_map[k8sclustertype].synchronize_repos(
3391 cluster_uuid=cluster_uuid
3392 )
3393 )
tiernoe876f672020-02-13 14:34:48 +00003394 if del_repo_list or added_repo_dict:
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003395 if k8sclustertype == "helm-chart":
garciadeblas5697b8b2021-03-24 09:17:02 +01003396 unset = {
3397 "_admin.helm_charts_added." + item: None
3398 for item in del_repo_list
3399 }
3400 updated = {
3401 "_admin.helm_charts_added." + item: name
3402 for item, name in added_repo_dict.items()
3403 }
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003404 updated_cluster_list.append(cluster_uuid)
3405 elif k8sclustertype == "helm-chart-v3":
garciadeblas5697b8b2021-03-24 09:17:02 +01003406 unset = {
3407 "_admin.helm_charts_v3_added." + item: None
3408 for item in del_repo_list
3409 }
3410 updated = {
3411 "_admin.helm_charts_v3_added." + item: name
3412 for item, name in added_repo_dict.items()
3413 }
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003414 updated_v3_cluster_list.append(cluster_uuid)
garciadeblas5697b8b2021-03-24 09:17:02 +01003415 self.logger.debug(
3416 logging_text + "repos synchronized on k8s cluster "
3417 "'{}' to_delete: {}, to_add: {}".format(
3418 k8s_cluster_id, del_repo_list, added_repo_dict
3419 )
3420 )
3421 self.db.set_one(
3422 "k8sclusters",
3423 {"_id": k8s_cluster_id},
3424 updated,
3425 unset=unset,
3426 )
lloretgallegedc5f332020-02-20 11:50:50 +01003427
lloretgalleg7c121132020-07-08 07:53:22 +00003428 # Instantiate kdu
garciadeblas5697b8b2021-03-24 09:17:02 +01003429 step = "Instantiating KDU {}.{} in k8s cluster {}".format(
3430 vnfr_data["member-vnf-index-ref"],
3431 kdur["kdu-name"],
3432 k8s_cluster_id,
3433 )
3434 k8s_instance_info = {
3435 "kdu-instance": None,
3436 "k8scluster-uuid": cluster_uuid,
3437 "k8scluster-type": k8sclustertype,
3438 "member-vnf-index": vnfr_data["member-vnf-index-ref"],
3439 "kdu-name": kdur["kdu-name"],
3440 "kdu-model": kdumodel,
3441 "namespace": namespace,
romeromonser4554a702021-05-28 12:00:08 +02003442 "kdu-deployment-name": kdu_deployment_name,
garciadeblas5697b8b2021-03-24 09:17:02 +01003443 }
tiernob9018152020-04-16 14:18:24 +00003444 db_path = "_admin.deployed.K8s.{}".format(index)
lloretgalleg7c121132020-07-08 07:53:22 +00003445 db_nsr_update[db_path] = k8s_instance_info
tierno626e0152019-11-29 14:16:16 +00003446 self.update_db_2("nsrs", nsr_id, db_nsr_update)
garciadeblas5697b8b2021-03-24 09:17:02 +01003447 vnfd_with_id = find_in_list(
3448 db_vnfds, lambda vnf: vnf["_id"] == vnfd_id
3449 )
tiernoa2143262020-03-27 16:20:40 +00003450 task = asyncio.ensure_future(
garciadeblas5697b8b2021-03-24 09:17:02 +01003451 self._install_kdu(
3452 nsr_id,
3453 db_path,
3454 vnfr_data,
3455 kdu_index,
3456 kdud,
3457 vnfd_with_id,
3458 k8s_instance_info,
3459 k8params=desc_params,
3460 timeout=600,
3461 vca_id=vca_id,
3462 )
3463 )
3464 self.lcm_tasks.register(
3465 "ns",
3466 nsr_id,
3467 nslcmop_id,
3468 "instantiate_KDU-{}".format(index),
3469 task,
3470 )
3471 task_instantiation_info[task] = "Deploying KDU {}".format(
3472 kdur["kdu-name"]
3473 )
tiernoe876f672020-02-13 14:34:48 +00003474
tierno626e0152019-11-29 14:16:16 +00003475 index += 1
quilesjdd799ac2020-01-23 16:31:11 +00003476
tiernoe876f672020-02-13 14:34:48 +00003477 except (LcmException, asyncio.CancelledError):
3478 raise
calvinosanch9f9c6f22019-11-04 13:37:39 +01003479 except Exception as e:
tiernoe876f672020-02-13 14:34:48 +00003480 msg = "Exception {} while {}: {}".format(type(e).__name__, step, e)
3481 if isinstance(e, (N2VCException, DbException)):
3482 self.logger.error(logging_text + msg)
3483 else:
3484 self.logger.critical(logging_text + msg, exc_info=True)
quilesjdd799ac2020-01-23 16:31:11 +00003485 raise LcmException(msg)
calvinosanch9f9c6f22019-11-04 13:37:39 +01003486 finally:
calvinosanch9f9c6f22019-11-04 13:37:39 +01003487 if db_nsr_update:
3488 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernoda6fb102019-11-23 00:36:52 +00003489
garciadeblas5697b8b2021-03-24 09:17:02 +01003490 def _deploy_n2vc(
3491 self,
3492 logging_text,
3493 db_nsr,
3494 db_vnfr,
3495 nslcmop_id,
3496 nsr_id,
3497 nsi_id,
3498 vnfd_id,
3499 vdu_id,
3500 kdu_name,
3501 member_vnf_index,
3502 vdu_index,
3503 vdu_name,
3504 deploy_params,
3505 descriptor_config,
3506 base_folder,
3507 task_instantiation_info,
3508 stage,
3509 ):
quilesj7e13aeb2019-10-08 13:34:55 +02003510 # launch instantiate_N2VC in a asyncio task and register task object
3511 # Look where information of this charm is at database <nsrs>._admin.deployed.VCA
3512 # if not found, create one entry and update database
quilesj7e13aeb2019-10-08 13:34:55 +02003513 # fill db_nsr._admin.deployed.VCA.<index>
tierno588547c2020-07-01 15:30:20 +00003514
garciadeblas5697b8b2021-03-24 09:17:02 +01003515 self.logger.debug(
3516 logging_text + "_deploy_n2vc vnfd_id={}, vdu_id={}".format(vnfd_id, vdu_id)
3517 )
bravof9a256db2021-02-22 18:02:07 -03003518 if "execution-environment-list" in descriptor_config:
3519 ee_list = descriptor_config.get("execution-environment-list", [])
David Garcia9ad54a42021-05-28 12:08:18 +02003520 elif "juju" in descriptor_config:
3521 ee_list = [descriptor_config] # ns charms
tierno588547c2020-07-01 15:30:20 +00003522 else: # other types as script are not supported
3523 ee_list = []
3524
3525 for ee_item in ee_list:
garciadeblas5697b8b2021-03-24 09:17:02 +01003526 self.logger.debug(
3527 logging_text
3528 + "_deploy_n2vc ee_item juju={}, helm={}".format(
3529 ee_item.get("juju"), ee_item.get("helm-chart")
3530 )
3531 )
tiernoa278b842020-07-08 15:33:55 +00003532 ee_descriptor_id = ee_item.get("id")
tierno588547c2020-07-01 15:30:20 +00003533 if ee_item.get("juju"):
garciadeblas5697b8b2021-03-24 09:17:02 +01003534 vca_name = ee_item["juju"].get("charm")
3535 vca_type = (
3536 "lxc_proxy_charm"
3537 if ee_item["juju"].get("charm") is not None
3538 else "native_charm"
3539 )
3540 if ee_item["juju"].get("cloud") == "k8s":
tierno588547c2020-07-01 15:30:20 +00003541 vca_type = "k8s_proxy_charm"
garciadeblas5697b8b2021-03-24 09:17:02 +01003542 elif ee_item["juju"].get("proxy") is False:
tierno588547c2020-07-01 15:30:20 +00003543 vca_type = "native_charm"
3544 elif ee_item.get("helm-chart"):
garciadeblas5697b8b2021-03-24 09:17:02 +01003545 vca_name = ee_item["helm-chart"]
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003546 if ee_item.get("helm-version") and ee_item.get("helm-version") == "v2":
3547 vca_type = "helm"
3548 else:
3549 vca_type = "helm-v3"
tierno588547c2020-07-01 15:30:20 +00003550 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01003551 self.logger.debug(
3552 logging_text + "skipping non juju neither charm configuration"
3553 )
quilesj7e13aeb2019-10-08 13:34:55 +02003554 continue
quilesj3655ae02019-12-12 16:08:35 +00003555
tierno588547c2020-07-01 15:30:20 +00003556 vca_index = -1
garciadeblas5697b8b2021-03-24 09:17:02 +01003557 for vca_index, vca_deployed in enumerate(
3558 db_nsr["_admin"]["deployed"]["VCA"]
3559 ):
tierno588547c2020-07-01 15:30:20 +00003560 if not vca_deployed:
3561 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01003562 if (
3563 vca_deployed.get("member-vnf-index") == member_vnf_index
3564 and vca_deployed.get("vdu_id") == vdu_id
3565 and vca_deployed.get("kdu_name") == kdu_name
3566 and vca_deployed.get("vdu_count_index", 0) == vdu_index
3567 and vca_deployed.get("ee_descriptor_id") == ee_descriptor_id
3568 ):
tierno588547c2020-07-01 15:30:20 +00003569 break
3570 else:
3571 # not found, create one.
garciadeblas5697b8b2021-03-24 09:17:02 +01003572 target = (
3573 "ns" if not member_vnf_index else "vnf/{}".format(member_vnf_index)
3574 )
tiernoa278b842020-07-08 15:33:55 +00003575 if vdu_id:
3576 target += "/vdu/{}/{}".format(vdu_id, vdu_index or 0)
3577 elif kdu_name:
3578 target += "/kdu/{}".format(kdu_name)
tierno588547c2020-07-01 15:30:20 +00003579 vca_deployed = {
tiernoa278b842020-07-08 15:33:55 +00003580 "target_element": target,
3581 # ^ target_element will replace member-vnf-index, kdu_name, vdu_id ... in a single string
tierno588547c2020-07-01 15:30:20 +00003582 "member-vnf-index": member_vnf_index,
3583 "vdu_id": vdu_id,
3584 "kdu_name": kdu_name,
3585 "vdu_count_index": vdu_index,
3586 "operational-status": "init", # TODO revise
3587 "detailed-status": "", # TODO revise
garciadeblas5697b8b2021-03-24 09:17:02 +01003588 "step": "initial-deploy", # TODO revise
tierno588547c2020-07-01 15:30:20 +00003589 "vnfd_id": vnfd_id,
3590 "vdu_name": vdu_name,
tiernoa278b842020-07-08 15:33:55 +00003591 "type": vca_type,
garciadeblas5697b8b2021-03-24 09:17:02 +01003592 "ee_descriptor_id": ee_descriptor_id,
tierno588547c2020-07-01 15:30:20 +00003593 }
3594 vca_index += 1
quilesj3655ae02019-12-12 16:08:35 +00003595
tierno588547c2020-07-01 15:30:20 +00003596 # create VCA and configurationStatus in db
3597 db_dict = {
3598 "_admin.deployed.VCA.{}".format(vca_index): vca_deployed,
garciadeblas5697b8b2021-03-24 09:17:02 +01003599 "configurationStatus.{}".format(vca_index): dict(),
tierno588547c2020-07-01 15:30:20 +00003600 }
3601 self.update_db_2("nsrs", nsr_id, db_dict)
quilesj7e13aeb2019-10-08 13:34:55 +02003602
tierno588547c2020-07-01 15:30:20 +00003603 db_nsr["_admin"]["deployed"]["VCA"].append(vca_deployed)
3604
bravof922c4172020-11-24 21:21:43 -03003605 self.logger.debug("N2VC > NSR_ID > {}".format(nsr_id))
3606 self.logger.debug("N2VC > DB_NSR > {}".format(db_nsr))
3607 self.logger.debug("N2VC > VCA_DEPLOYED > {}".format(vca_deployed))
3608
tierno588547c2020-07-01 15:30:20 +00003609 # Launch task
3610 task_n2vc = asyncio.ensure_future(
3611 self.instantiate_N2VC(
3612 logging_text=logging_text,
3613 vca_index=vca_index,
3614 nsi_id=nsi_id,
3615 db_nsr=db_nsr,
3616 db_vnfr=db_vnfr,
3617 vdu_id=vdu_id,
3618 kdu_name=kdu_name,
3619 vdu_index=vdu_index,
3620 deploy_params=deploy_params,
3621 config_descriptor=descriptor_config,
3622 base_folder=base_folder,
3623 nslcmop_id=nslcmop_id,
3624 stage=stage,
3625 vca_type=vca_type,
tiernob996d942020-07-03 14:52:28 +00003626 vca_name=vca_name,
garciadeblas5697b8b2021-03-24 09:17:02 +01003627 ee_config_descriptor=ee_item,
tierno588547c2020-07-01 15:30:20 +00003628 )
quilesj7e13aeb2019-10-08 13:34:55 +02003629 )
garciadeblas5697b8b2021-03-24 09:17:02 +01003630 self.lcm_tasks.register(
3631 "ns",
3632 nsr_id,
3633 nslcmop_id,
3634 "instantiate_N2VC-{}".format(vca_index),
3635 task_n2vc,
3636 )
3637 task_instantiation_info[
3638 task_n2vc
3639 ] = self.task_name_deploy_vca + " {}.{}".format(
3640 member_vnf_index or "", vdu_id or ""
3641 )
tiernobaa51102018-12-14 13:16:18 +00003642
tiernoc9556972019-07-05 15:25:25 +00003643 @staticmethod
kuuse0ca67472019-05-13 15:59:27 +02003644 def _create_nslcmop(nsr_id, operation, params):
3645 """
3646 Creates a ns-lcm-opp content to be stored at database.
3647 :param nsr_id: internal id of the instance
3648 :param operation: instantiate, terminate, scale, action, ...
3649 :param params: user parameters for the operation
3650 :return: dictionary following SOL005 format
3651 """
3652 # Raise exception if invalid arguments
3653 if not (nsr_id and operation and params):
3654 raise LcmException(
garciadeblas5697b8b2021-03-24 09:17:02 +01003655 "Parameters 'nsr_id', 'operation' and 'params' needed to create primitive not provided"
3656 )
kuuse0ca67472019-05-13 15:59:27 +02003657 now = time()
3658 _id = str(uuid4())
3659 nslcmop = {
3660 "id": _id,
3661 "_id": _id,
3662 # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
3663 "operationState": "PROCESSING",
3664 "statusEnteredTime": now,
3665 "nsInstanceId": nsr_id,
3666 "lcmOperationType": operation,
3667 "startTime": now,
3668 "isAutomaticInvocation": False,
3669 "operationParams": params,
3670 "isCancelPending": False,
3671 "links": {
3672 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
3673 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01003674 },
kuuse0ca67472019-05-13 15:59:27 +02003675 }
3676 return nslcmop
3677
calvinosanch9f9c6f22019-11-04 13:37:39 +01003678 def _format_additional_params(self, params):
tierno626e0152019-11-29 14:16:16 +00003679 params = params or {}
calvinosanch9f9c6f22019-11-04 13:37:39 +01003680 for key, value in params.items():
3681 if str(value).startswith("!!yaml "):
3682 params[key] = yaml.safe_load(value[7:])
calvinosanch9f9c6f22019-11-04 13:37:39 +01003683 return params
3684
kuuse8b998e42019-07-30 15:22:16 +02003685 def _get_terminate_primitive_params(self, seq, vnf_index):
garciadeblas5697b8b2021-03-24 09:17:02 +01003686 primitive = seq.get("name")
kuuse8b998e42019-07-30 15:22:16 +02003687 primitive_params = {}
3688 params = {
3689 "member_vnf_index": vnf_index,
3690 "primitive": primitive,
3691 "primitive_params": primitive_params,
3692 }
3693 desc_params = {}
3694 return self._map_primitive_params(seq, params, desc_params)
3695
kuuseac3a8882019-10-03 10:48:06 +02003696 # sub-operations
3697
tierno51183952020-04-03 15:48:18 +00003698 def _retry_or_skip_suboperation(self, db_nslcmop, op_index):
garciadeblas5697b8b2021-03-24 09:17:02 +01003699 op = deep_get(db_nslcmop, ("_admin", "operations"), [])[op_index]
3700 if op.get("operationState") == "COMPLETED":
kuuseac3a8882019-10-03 10:48:06 +02003701 # b. Skip sub-operation
3702 # _ns_execute_primitive() or RO.create_action() will NOT be executed
3703 return self.SUBOPERATION_STATUS_SKIP
3704 else:
tierno7c4e24c2020-05-13 08:41:35 +00003705 # c. retry executing sub-operation
kuuseac3a8882019-10-03 10:48:06 +02003706 # The sub-operation exists, and operationState != 'COMPLETED'
tierno7c4e24c2020-05-13 08:41:35 +00003707 # Update operationState = 'PROCESSING' to indicate a retry.
garciadeblas5697b8b2021-03-24 09:17:02 +01003708 operationState = "PROCESSING"
3709 detailed_status = "In progress"
kuuseac3a8882019-10-03 10:48:06 +02003710 self._update_suboperation_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01003711 db_nslcmop, op_index, operationState, detailed_status
3712 )
kuuseac3a8882019-10-03 10:48:06 +02003713 # Return the sub-operation index
3714 # _ns_execute_primitive() or RO.create_action() will be called from scale()
3715 # with arguments extracted from the sub-operation
3716 return op_index
3717
3718 # Find a sub-operation where all keys in a matching dictionary must match
3719 # Returns the index of the matching sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if no match
3720 def _find_suboperation(self, db_nslcmop, match):
tierno7c4e24c2020-05-13 08:41:35 +00003721 if db_nslcmop and match:
garciadeblas5697b8b2021-03-24 09:17:02 +01003722 op_list = db_nslcmop.get("_admin", {}).get("operations", [])
kuuseac3a8882019-10-03 10:48:06 +02003723 for i, op in enumerate(op_list):
3724 if all(op.get(k) == match[k] for k in match):
3725 return i
3726 return self.SUBOPERATION_STATUS_NOT_FOUND
3727
3728 # Update status for a sub-operation given its index
garciadeblas5697b8b2021-03-24 09:17:02 +01003729 def _update_suboperation_status(
3730 self, db_nslcmop, op_index, operationState, detailed_status
3731 ):
kuuseac3a8882019-10-03 10:48:06 +02003732 # Update DB for HA tasks
garciadeblas5697b8b2021-03-24 09:17:02 +01003733 q_filter = {"_id": db_nslcmop["_id"]}
3734 update_dict = {
3735 "_admin.operations.{}.operationState".format(op_index): operationState,
3736 "_admin.operations.{}.detailed-status".format(op_index): detailed_status,
3737 }
3738 self.db.set_one(
3739 "nslcmops", q_filter=q_filter, update_dict=update_dict, fail_on_empty=False
3740 )
kuuseac3a8882019-10-03 10:48:06 +02003741
3742 # Add sub-operation, return the index of the added sub-operation
3743 # Optionally, set operationState, detailed-status, and operationType
3744 # Status and type are currently set for 'scale' sub-operations:
3745 # 'operationState' : 'PROCESSING' | 'COMPLETED' | 'FAILED'
3746 # 'detailed-status' : status message
3747 # 'operationType': may be any type, in the case of scaling: 'PRE-SCALE' | 'POST-SCALE'
3748 # Status and operation type are currently only used for 'scale', but NOT for 'terminate' sub-operations.
garciadeblas5697b8b2021-03-24 09:17:02 +01003749 def _add_suboperation(
3750 self,
3751 db_nslcmop,
3752 vnf_index,
3753 vdu_id,
3754 vdu_count_index,
3755 vdu_name,
3756 primitive,
3757 mapped_primitive_params,
3758 operationState=None,
3759 detailed_status=None,
3760 operationType=None,
3761 RO_nsr_id=None,
3762 RO_scaling_info=None,
3763 ):
tiernoe876f672020-02-13 14:34:48 +00003764 if not db_nslcmop:
kuuseac3a8882019-10-03 10:48:06 +02003765 return self.SUBOPERATION_STATUS_NOT_FOUND
3766 # Get the "_admin.operations" list, if it exists
garciadeblas5697b8b2021-03-24 09:17:02 +01003767 db_nslcmop_admin = db_nslcmop.get("_admin", {})
3768 op_list = db_nslcmop_admin.get("operations")
kuuseac3a8882019-10-03 10:48:06 +02003769 # Create or append to the "_admin.operations" list
garciadeblas5697b8b2021-03-24 09:17:02 +01003770 new_op = {
3771 "member_vnf_index": vnf_index,
3772 "vdu_id": vdu_id,
3773 "vdu_count_index": vdu_count_index,
3774 "primitive": primitive,
3775 "primitive_params": mapped_primitive_params,
3776 }
kuuseac3a8882019-10-03 10:48:06 +02003777 if operationState:
garciadeblas5697b8b2021-03-24 09:17:02 +01003778 new_op["operationState"] = operationState
kuuseac3a8882019-10-03 10:48:06 +02003779 if detailed_status:
garciadeblas5697b8b2021-03-24 09:17:02 +01003780 new_op["detailed-status"] = detailed_status
kuuseac3a8882019-10-03 10:48:06 +02003781 if operationType:
garciadeblas5697b8b2021-03-24 09:17:02 +01003782 new_op["lcmOperationType"] = operationType
kuuseac3a8882019-10-03 10:48:06 +02003783 if RO_nsr_id:
garciadeblas5697b8b2021-03-24 09:17:02 +01003784 new_op["RO_nsr_id"] = RO_nsr_id
kuuseac3a8882019-10-03 10:48:06 +02003785 if RO_scaling_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01003786 new_op["RO_scaling_info"] = RO_scaling_info
kuuseac3a8882019-10-03 10:48:06 +02003787 if not op_list:
3788 # No existing operations, create key 'operations' with current operation as first list element
garciadeblas5697b8b2021-03-24 09:17:02 +01003789 db_nslcmop_admin.update({"operations": [new_op]})
3790 op_list = db_nslcmop_admin.get("operations")
kuuseac3a8882019-10-03 10:48:06 +02003791 else:
3792 # Existing operations, append operation to list
3793 op_list.append(new_op)
kuuse8b998e42019-07-30 15:22:16 +02003794
garciadeblas5697b8b2021-03-24 09:17:02 +01003795 db_nslcmop_update = {"_admin.operations": op_list}
3796 self.update_db_2("nslcmops", db_nslcmop["_id"], db_nslcmop_update)
kuuseac3a8882019-10-03 10:48:06 +02003797 op_index = len(op_list) - 1
3798 return op_index
3799
3800 # Helper methods for scale() sub-operations
3801
3802 # pre-scale/post-scale:
3803 # Check for 3 different cases:
3804 # a. New: First time execution, return SUBOPERATION_STATUS_NEW
3805 # b. Skip: Existing sub-operation exists, operationState == 'COMPLETED', return SUBOPERATION_STATUS_SKIP
tierno7c4e24c2020-05-13 08:41:35 +00003806 # c. retry: Existing sub-operation exists, operationState != 'COMPLETED', return op_index to re-execute
garciadeblas5697b8b2021-03-24 09:17:02 +01003807 def _check_or_add_scale_suboperation(
3808 self,
3809 db_nslcmop,
3810 vnf_index,
3811 vnf_config_primitive,
3812 primitive_params,
3813 operationType,
3814 RO_nsr_id=None,
3815 RO_scaling_info=None,
3816 ):
kuuseac3a8882019-10-03 10:48:06 +02003817 # Find this sub-operation
tierno7c4e24c2020-05-13 08:41:35 +00003818 if RO_nsr_id and RO_scaling_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01003819 operationType = "SCALE-RO"
kuuseac3a8882019-10-03 10:48:06 +02003820 match = {
garciadeblas5697b8b2021-03-24 09:17:02 +01003821 "member_vnf_index": vnf_index,
3822 "RO_nsr_id": RO_nsr_id,
3823 "RO_scaling_info": RO_scaling_info,
kuuseac3a8882019-10-03 10:48:06 +02003824 }
3825 else:
3826 match = {
garciadeblas5697b8b2021-03-24 09:17:02 +01003827 "member_vnf_index": vnf_index,
3828 "primitive": vnf_config_primitive,
3829 "primitive_params": primitive_params,
3830 "lcmOperationType": operationType,
kuuseac3a8882019-10-03 10:48:06 +02003831 }
3832 op_index = self._find_suboperation(db_nslcmop, match)
tierno51183952020-04-03 15:48:18 +00003833 if op_index == self.SUBOPERATION_STATUS_NOT_FOUND:
kuuseac3a8882019-10-03 10:48:06 +02003834 # a. New sub-operation
3835 # The sub-operation does not exist, add it.
3836 # _ns_execute_primitive() will be called from scale() as usual, with non-modified arguments
3837 # The following parameters are set to None for all kind of scaling:
3838 vdu_id = None
3839 vdu_count_index = None
3840 vdu_name = None
tierno51183952020-04-03 15:48:18 +00003841 if RO_nsr_id and RO_scaling_info:
kuuseac3a8882019-10-03 10:48:06 +02003842 vnf_config_primitive = None
3843 primitive_params = None
3844 else:
3845 RO_nsr_id = None
3846 RO_scaling_info = None
3847 # Initial status for sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01003848 operationState = "PROCESSING"
3849 detailed_status = "In progress"
kuuseac3a8882019-10-03 10:48:06 +02003850 # Add sub-operation for pre/post-scaling (zero or more operations)
garciadeblas5697b8b2021-03-24 09:17:02 +01003851 self._add_suboperation(
3852 db_nslcmop,
3853 vnf_index,
3854 vdu_id,
3855 vdu_count_index,
3856 vdu_name,
3857 vnf_config_primitive,
3858 primitive_params,
3859 operationState,
3860 detailed_status,
3861 operationType,
3862 RO_nsr_id,
3863 RO_scaling_info,
3864 )
kuuseac3a8882019-10-03 10:48:06 +02003865 return self.SUBOPERATION_STATUS_NEW
3866 else:
3867 # Return either SUBOPERATION_STATUS_SKIP (operationState == 'COMPLETED'),
3868 # or op_index (operationState != 'COMPLETED')
tierno51183952020-04-03 15:48:18 +00003869 return self._retry_or_skip_suboperation(db_nslcmop, op_index)
kuuseac3a8882019-10-03 10:48:06 +02003870
preethika.pdf7d8e02019-12-10 13:10:48 +00003871 # Function to return execution_environment id
3872
3873 def _get_ee_id(self, vnf_index, vdu_id, vca_deployed_list):
tiernoe876f672020-02-13 14:34:48 +00003874 # TODO vdu_index_count
preethika.pdf7d8e02019-12-10 13:10:48 +00003875 for vca in vca_deployed_list:
3876 if vca["member-vnf-index"] == vnf_index and vca["vdu_id"] == vdu_id:
3877 return vca["ee_id"]
3878
David Garciac1fe90a2021-03-31 19:12:02 +02003879 async def destroy_N2VC(
3880 self,
3881 logging_text,
3882 db_nslcmop,
3883 vca_deployed,
3884 config_descriptor,
3885 vca_index,
3886 destroy_ee=True,
3887 exec_primitives=True,
3888 scaling_in=False,
3889 vca_id: str = None,
3890 ):
tiernoe876f672020-02-13 14:34:48 +00003891 """
3892 Execute the terminate primitives and destroy the execution environment (if destroy_ee=False
3893 :param logging_text:
3894 :param db_nslcmop:
3895 :param vca_deployed: Dictionary of deployment info at db_nsr._admin.depoloyed.VCA.<INDEX>
3896 :param config_descriptor: Configuration descriptor of the NSD, VNFD, VNFD.vdu or VNFD.kdu
3897 :param vca_index: index in the database _admin.deployed.VCA
3898 :param destroy_ee: False to do not destroy, because it will be destroyed all of then at once
tierno588547c2020-07-01 15:30:20 +00003899 :param exec_primitives: False to do not execute terminate primitives, because the config is not completed or has
3900 not executed properly
aktas13251562021-02-12 22:19:10 +03003901 :param scaling_in: True destroys the application, False destroys the model
tiernoe876f672020-02-13 14:34:48 +00003902 :return: None or exception
3903 """
tiernoe876f672020-02-13 14:34:48 +00003904
tierno588547c2020-07-01 15:30:20 +00003905 self.logger.debug(
garciadeblas5697b8b2021-03-24 09:17:02 +01003906 logging_text
3907 + " vca_index: {}, vca_deployed: {}, config_descriptor: {}, destroy_ee: {}".format(
tierno588547c2020-07-01 15:30:20 +00003908 vca_index, vca_deployed, config_descriptor, destroy_ee
3909 )
3910 )
3911
3912 vca_type = vca_deployed.get("type", "lxc_proxy_charm")
3913
3914 # execute terminate_primitives
3915 if exec_primitives:
bravof922c4172020-11-24 21:21:43 -03003916 terminate_primitives = get_ee_sorted_terminate_config_primitive_list(
garciadeblas5697b8b2021-03-24 09:17:02 +01003917 config_descriptor.get("terminate-config-primitive"),
3918 vca_deployed.get("ee_descriptor_id"),
3919 )
tierno588547c2020-07-01 15:30:20 +00003920 vdu_id = vca_deployed.get("vdu_id")
3921 vdu_count_index = vca_deployed.get("vdu_count_index")
3922 vdu_name = vca_deployed.get("vdu_name")
3923 vnf_index = vca_deployed.get("member-vnf-index")
3924 if terminate_primitives and vca_deployed.get("needed_terminate"):
tierno588547c2020-07-01 15:30:20 +00003925 for seq in terminate_primitives:
3926 # For each sequence in list, get primitive and call _ns_execute_primitive()
3927 step = "Calling terminate action for vnf_member_index={} primitive={}".format(
garciadeblas5697b8b2021-03-24 09:17:02 +01003928 vnf_index, seq.get("name")
3929 )
tierno588547c2020-07-01 15:30:20 +00003930 self.logger.debug(logging_text + step)
3931 # Create the primitive for each sequence, i.e. "primitive": "touch"
garciadeblas5697b8b2021-03-24 09:17:02 +01003932 primitive = seq.get("name")
3933 mapped_primitive_params = self._get_terminate_primitive_params(
3934 seq, vnf_index
3935 )
tierno588547c2020-07-01 15:30:20 +00003936
3937 # Add sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01003938 self._add_suboperation(
3939 db_nslcmop,
3940 vnf_index,
3941 vdu_id,
3942 vdu_count_index,
3943 vdu_name,
3944 primitive,
3945 mapped_primitive_params,
3946 )
tierno588547c2020-07-01 15:30:20 +00003947 # Sub-operations: Call _ns_execute_primitive() instead of action()
3948 try:
David Garciac1fe90a2021-03-31 19:12:02 +02003949 result, result_detail = await self._ns_execute_primitive(
garciadeblas5697b8b2021-03-24 09:17:02 +01003950 vca_deployed["ee_id"],
3951 primitive,
David Garciac1fe90a2021-03-31 19:12:02 +02003952 mapped_primitive_params,
3953 vca_type=vca_type,
3954 vca_id=vca_id,
3955 )
tierno588547c2020-07-01 15:30:20 +00003956 except LcmException:
3957 # this happens when VCA is not deployed. In this case it is not needed to terminate
3958 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01003959 result_ok = ["COMPLETED", "PARTIALLY_COMPLETED"]
tierno588547c2020-07-01 15:30:20 +00003960 if result not in result_ok:
garciadeblas5697b8b2021-03-24 09:17:02 +01003961 raise LcmException(
3962 "terminate_primitive {} for vnf_member_index={} fails with "
3963 "error {}".format(seq.get("name"), vnf_index, result_detail)
3964 )
tierno588547c2020-07-01 15:30:20 +00003965 # set that this VCA do not need terminated
garciadeblas5697b8b2021-03-24 09:17:02 +01003966 db_update_entry = "_admin.deployed.VCA.{}.needed_terminate".format(
3967 vca_index
3968 )
3969 self.update_db_2(
3970 "nsrs", db_nslcmop["nsInstanceId"], {db_update_entry: False}
3971 )
tiernoe876f672020-02-13 14:34:48 +00003972
bravof73bac502021-05-11 07:38:47 -04003973 # Delete Prometheus Jobs if any
3974 # This uses NSR_ID, so it will destroy any jobs under this index
3975 self.db.del_list("prometheus_jobs", {"nsr_id": db_nslcmop["nsInstanceId"]})
tiernob996d942020-07-03 14:52:28 +00003976
tiernoe876f672020-02-13 14:34:48 +00003977 if destroy_ee:
David Garciac1fe90a2021-03-31 19:12:02 +02003978 await self.vca_map[vca_type].delete_execution_environment(
3979 vca_deployed["ee_id"],
3980 scaling_in=scaling_in,
aktas98488ed2021-07-29 17:42:49 +03003981 vca_type=vca_type,
David Garciac1fe90a2021-03-31 19:12:02 +02003982 vca_id=vca_id,
3983 )
kuuse0ca67472019-05-13 15:59:27 +02003984
David Garciac1fe90a2021-03-31 19:12:02 +02003985 async def _delete_all_N2VC(self, db_nsr: dict, vca_id: str = None):
garciadeblas5697b8b2021-03-24 09:17:02 +01003986 self._write_all_config_status(db_nsr=db_nsr, status="TERMINATING")
tierno51183952020-04-03 15:48:18 +00003987 namespace = "." + db_nsr["_id"]
tiernof59ad6c2020-04-08 12:50:52 +00003988 try:
David Garciac1fe90a2021-03-31 19:12:02 +02003989 await self.n2vc.delete_namespace(
3990 namespace=namespace,
3991 total_timeout=self.timeout_charm_delete,
3992 vca_id=vca_id,
3993 )
tiernof59ad6c2020-04-08 12:50:52 +00003994 except N2VCNotFound: # already deleted. Skip
3995 pass
garciadeblas5697b8b2021-03-24 09:17:02 +01003996 self._write_all_config_status(db_nsr=db_nsr, status="DELETED")
quilesj3655ae02019-12-12 16:08:35 +00003997
garciadeblas5697b8b2021-03-24 09:17:02 +01003998 async def _terminate_RO(
3999 self, logging_text, nsr_deployed, nsr_id, nslcmop_id, stage
4000 ):
tiernoe876f672020-02-13 14:34:48 +00004001 """
4002 Terminates a deployment from RO
4003 :param logging_text:
4004 :param nsr_deployed: db_nsr._admin.deployed
4005 :param nsr_id:
4006 :param nslcmop_id:
4007 :param stage: list of string with the content to write on db_nslcmop.detailed-status.
4008 this method will update only the index 2, but it will write on database the concatenated content of the list
4009 :return:
4010 """
4011 db_nsr_update = {}
4012 failed_detail = []
4013 ro_nsr_id = ro_delete_action = None
4014 if nsr_deployed and nsr_deployed.get("RO"):
4015 ro_nsr_id = nsr_deployed["RO"].get("nsr_id")
4016 ro_delete_action = nsr_deployed["RO"].get("nsr_delete_action_id")
4017 try:
4018 if ro_nsr_id:
4019 stage[2] = "Deleting ns from VIM."
4020 db_nsr_update["detailed-status"] = " ".join(stage)
4021 self._write_op_status(nslcmop_id, stage)
4022 self.logger.debug(logging_text + stage[2])
4023 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4024 self._write_op_status(nslcmop_id, stage)
4025 desc = await self.RO.delete("ns", ro_nsr_id)
4026 ro_delete_action = desc["action_id"]
garciadeblas5697b8b2021-03-24 09:17:02 +01004027 db_nsr_update[
4028 "_admin.deployed.RO.nsr_delete_action_id"
4029 ] = ro_delete_action
tiernoe876f672020-02-13 14:34:48 +00004030 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
4031 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
4032 if ro_delete_action:
4033 # wait until NS is deleted from VIM
4034 stage[2] = "Waiting ns deleted from VIM."
4035 detailed_status_old = None
garciadeblas5697b8b2021-03-24 09:17:02 +01004036 self.logger.debug(
4037 logging_text
4038 + stage[2]
4039 + " RO_id={} ro_delete_action={}".format(
4040 ro_nsr_id, ro_delete_action
4041 )
4042 )
tiernoe876f672020-02-13 14:34:48 +00004043 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4044 self._write_op_status(nslcmop_id, stage)
kuused124bfe2019-06-18 12:09:24 +02004045
tiernoe876f672020-02-13 14:34:48 +00004046 delete_timeout = 20 * 60 # 20 minutes
4047 while delete_timeout > 0:
4048 desc = await self.RO.show(
4049 "ns",
4050 item_id_name=ro_nsr_id,
4051 extra_item="action",
garciadeblas5697b8b2021-03-24 09:17:02 +01004052 extra_item_id=ro_delete_action,
4053 )
tiernoe876f672020-02-13 14:34:48 +00004054
4055 # deploymentStatus
4056 self._on_update_ro_db(nsrs_id=nsr_id, ro_descriptor=desc)
4057
4058 ns_status, ns_status_info = self.RO.check_action_status(desc)
4059 if ns_status == "ERROR":
4060 raise ROclient.ROClientException(ns_status_info)
4061 elif ns_status == "BUILD":
4062 stage[2] = "Deleting from VIM {}".format(ns_status_info)
4063 elif ns_status == "ACTIVE":
4064 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
4065 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
4066 break
4067 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004068 assert (
4069 False
4070 ), "ROclient.check_action_status returns unknown {}".format(
4071 ns_status
4072 )
tiernoe876f672020-02-13 14:34:48 +00004073 if stage[2] != detailed_status_old:
4074 detailed_status_old = stage[2]
4075 db_nsr_update["detailed-status"] = " ".join(stage)
4076 self._write_op_status(nslcmop_id, stage)
4077 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4078 await asyncio.sleep(5, loop=self.loop)
4079 delete_timeout -= 5
4080 else: # delete_timeout <= 0:
garciadeblas5697b8b2021-03-24 09:17:02 +01004081 raise ROclient.ROClientException(
4082 "Timeout waiting ns deleted from VIM"
4083 )
tiernoe876f672020-02-13 14:34:48 +00004084
4085 except Exception as e:
4086 self.update_db_2("nsrs", nsr_id, db_nsr_update)
garciadeblas5697b8b2021-03-24 09:17:02 +01004087 if (
4088 isinstance(e, ROclient.ROClientException) and e.http_code == 404
4089 ): # not found
tiernoe876f672020-02-13 14:34:48 +00004090 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
4091 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
4092 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
garciadeblas5697b8b2021-03-24 09:17:02 +01004093 self.logger.debug(
4094 logging_text + "RO_ns_id={} already deleted".format(ro_nsr_id)
4095 )
4096 elif (
4097 isinstance(e, ROclient.ROClientException) and e.http_code == 409
4098 ): # conflict
tiernoa2143262020-03-27 16:20:40 +00004099 failed_detail.append("delete conflict: {}".format(e))
garciadeblas5697b8b2021-03-24 09:17:02 +01004100 self.logger.debug(
4101 logging_text
4102 + "RO_ns_id={} delete conflict: {}".format(ro_nsr_id, e)
4103 )
tiernoe876f672020-02-13 14:34:48 +00004104 else:
tiernoa2143262020-03-27 16:20:40 +00004105 failed_detail.append("delete error: {}".format(e))
garciadeblas5697b8b2021-03-24 09:17:02 +01004106 self.logger.error(
4107 logging_text + "RO_ns_id={} delete error: {}".format(ro_nsr_id, e)
4108 )
tiernoe876f672020-02-13 14:34:48 +00004109
4110 # Delete nsd
4111 if not failed_detail and deep_get(nsr_deployed, ("RO", "nsd_id")):
4112 ro_nsd_id = nsr_deployed["RO"]["nsd_id"]
4113 try:
4114 stage[2] = "Deleting nsd from RO."
4115 db_nsr_update["detailed-status"] = " ".join(stage)
4116 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4117 self._write_op_status(nslcmop_id, stage)
4118 await self.RO.delete("nsd", ro_nsd_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01004119 self.logger.debug(
4120 logging_text + "ro_nsd_id={} deleted".format(ro_nsd_id)
4121 )
tiernoe876f672020-02-13 14:34:48 +00004122 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
4123 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01004124 if (
4125 isinstance(e, ROclient.ROClientException) and e.http_code == 404
4126 ): # not found
tiernoe876f672020-02-13 14:34:48 +00004127 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
garciadeblas5697b8b2021-03-24 09:17:02 +01004128 self.logger.debug(
4129 logging_text + "ro_nsd_id={} already deleted".format(ro_nsd_id)
4130 )
4131 elif (
4132 isinstance(e, ROclient.ROClientException) and e.http_code == 409
4133 ): # conflict
4134 failed_detail.append(
4135 "ro_nsd_id={} delete conflict: {}".format(ro_nsd_id, e)
4136 )
tiernoe876f672020-02-13 14:34:48 +00004137 self.logger.debug(logging_text + failed_detail[-1])
4138 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004139 failed_detail.append(
4140 "ro_nsd_id={} delete error: {}".format(ro_nsd_id, e)
4141 )
tiernoe876f672020-02-13 14:34:48 +00004142 self.logger.error(logging_text + failed_detail[-1])
4143
4144 if not failed_detail and deep_get(nsr_deployed, ("RO", "vnfd")):
4145 for index, vnf_deployed in enumerate(nsr_deployed["RO"]["vnfd"]):
4146 if not vnf_deployed or not vnf_deployed["id"]:
4147 continue
4148 try:
4149 ro_vnfd_id = vnf_deployed["id"]
garciadeblas5697b8b2021-03-24 09:17:02 +01004150 stage[
4151 2
4152 ] = "Deleting member_vnf_index={} ro_vnfd_id={} from RO.".format(
4153 vnf_deployed["member-vnf-index"], ro_vnfd_id
4154 )
tiernoe876f672020-02-13 14:34:48 +00004155 db_nsr_update["detailed-status"] = " ".join(stage)
4156 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4157 self._write_op_status(nslcmop_id, stage)
4158 await self.RO.delete("vnfd", ro_vnfd_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01004159 self.logger.debug(
4160 logging_text + "ro_vnfd_id={} deleted".format(ro_vnfd_id)
4161 )
tiernoe876f672020-02-13 14:34:48 +00004162 db_nsr_update["_admin.deployed.RO.vnfd.{}.id".format(index)] = None
4163 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01004164 if (
4165 isinstance(e, ROclient.ROClientException) and e.http_code == 404
4166 ): # not found
4167 db_nsr_update[
4168 "_admin.deployed.RO.vnfd.{}.id".format(index)
4169 ] = None
4170 self.logger.debug(
4171 logging_text
4172 + "ro_vnfd_id={} already deleted ".format(ro_vnfd_id)
4173 )
4174 elif (
4175 isinstance(e, ROclient.ROClientException) and e.http_code == 409
4176 ): # conflict
4177 failed_detail.append(
4178 "ro_vnfd_id={} delete conflict: {}".format(ro_vnfd_id, e)
4179 )
tiernoe876f672020-02-13 14:34:48 +00004180 self.logger.debug(logging_text + failed_detail[-1])
4181 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004182 failed_detail.append(
4183 "ro_vnfd_id={} delete error: {}".format(ro_vnfd_id, e)
4184 )
tiernoe876f672020-02-13 14:34:48 +00004185 self.logger.error(logging_text + failed_detail[-1])
4186
tiernoa2143262020-03-27 16:20:40 +00004187 if failed_detail:
4188 stage[2] = "Error deleting from VIM"
4189 else:
4190 stage[2] = "Deleted from VIM"
tiernoe876f672020-02-13 14:34:48 +00004191 db_nsr_update["detailed-status"] = " ".join(stage)
4192 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4193 self._write_op_status(nslcmop_id, stage)
4194
4195 if failed_detail:
tiernoa2143262020-03-27 16:20:40 +00004196 raise LcmException("; ".join(failed_detail))
tiernoe876f672020-02-13 14:34:48 +00004197
4198 async def terminate(self, nsr_id, nslcmop_id):
kuused124bfe2019-06-18 12:09:24 +02004199 # Try to lock HA task here
garciadeblas5697b8b2021-03-24 09:17:02 +01004200 task_is_locked_by_me = self.lcm_tasks.lock_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02004201 if not task_is_locked_by_me:
4202 return
4203
tierno59d22d22018-09-25 18:10:19 +02004204 logging_text = "Task ns={} terminate={} ".format(nsr_id, nslcmop_id)
4205 self.logger.debug(logging_text + "Enter")
tiernoe876f672020-02-13 14:34:48 +00004206 timeout_ns_terminate = self.timeout_ns_terminate
tierno59d22d22018-09-25 18:10:19 +02004207 db_nsr = None
4208 db_nslcmop = None
tiernoa17d4f42020-04-28 09:59:23 +00004209 operation_params = None
tierno59d22d22018-09-25 18:10:19 +02004210 exc = None
garciadeblas5697b8b2021-03-24 09:17:02 +01004211 error_list = [] # annotates all failed error messages
tierno59d22d22018-09-25 18:10:19 +02004212 db_nslcmop_update = {}
tiernoc2564fe2019-01-28 16:18:56 +00004213 autoremove = False # autoremove after terminated
tiernoe876f672020-02-13 14:34:48 +00004214 tasks_dict_info = {}
4215 db_nsr_update = {}
garciadeblas5697b8b2021-03-24 09:17:02 +01004216 stage = [
4217 "Stage 1/3: Preparing task.",
4218 "Waiting for previous operations to terminate.",
4219 "",
4220 ]
tiernoe876f672020-02-13 14:34:48 +00004221 # ^ contains [stage, step, VIM-status]
tierno59d22d22018-09-25 18:10:19 +02004222 try:
kuused124bfe2019-06-18 12:09:24 +02004223 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +01004224 await self.lcm_tasks.waitfor_related_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02004225
tiernoe876f672020-02-13 14:34:48 +00004226 stage[1] = "Getting nslcmop={} from db.".format(nslcmop_id)
4227 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
4228 operation_params = db_nslcmop.get("operationParams") or {}
4229 if operation_params.get("timeout_ns_terminate"):
4230 timeout_ns_terminate = operation_params["timeout_ns_terminate"]
4231 stage[1] = "Getting nsr={} from db.".format(nsr_id)
4232 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
4233
4234 db_nsr_update["operational-status"] = "terminating"
4235 db_nsr_update["config-status"] = "terminating"
quilesj4cda56b2019-12-05 10:02:20 +00004236 self._write_ns_status(
4237 nsr_id=nsr_id,
4238 ns_state="TERMINATING",
4239 current_operation="TERMINATING",
tiernoe876f672020-02-13 14:34:48 +00004240 current_operation_id=nslcmop_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01004241 other_update=db_nsr_update,
quilesj4cda56b2019-12-05 10:02:20 +00004242 )
garciadeblas5697b8b2021-03-24 09:17:02 +01004243 self._write_op_status(op_id=nslcmop_id, queuePosition=0, stage=stage)
tiernoe876f672020-02-13 14:34:48 +00004244 nsr_deployed = deepcopy(db_nsr["_admin"].get("deployed")) or {}
tierno59d22d22018-09-25 18:10:19 +02004245 if db_nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
4246 return
tierno59d22d22018-09-25 18:10:19 +02004247
tiernoe876f672020-02-13 14:34:48 +00004248 stage[1] = "Getting vnf descriptors from db."
4249 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
garciadeblas5697b8b2021-03-24 09:17:02 +01004250 db_vnfrs_dict = {
4251 db_vnfr["member-vnf-index-ref"]: db_vnfr for db_vnfr in db_vnfrs_list
4252 }
tiernoe876f672020-02-13 14:34:48 +00004253 db_vnfds_from_id = {}
4254 db_vnfds_from_member_index = {}
4255 # Loop over VNFRs
4256 for vnfr in db_vnfrs_list:
4257 vnfd_id = vnfr["vnfd-id"]
4258 if vnfd_id not in db_vnfds_from_id:
4259 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
4260 db_vnfds_from_id[vnfd_id] = vnfd
garciadeblas5697b8b2021-03-24 09:17:02 +01004261 db_vnfds_from_member_index[
4262 vnfr["member-vnf-index-ref"]
4263 ] = db_vnfds_from_id[vnfd_id]
calvinosanch9f9c6f22019-11-04 13:37:39 +01004264
tiernoe876f672020-02-13 14:34:48 +00004265 # Destroy individual execution environments when there are terminating primitives.
4266 # Rest of EE will be deleted at once
tierno588547c2020-07-01 15:30:20 +00004267 # TODO - check before calling _destroy_N2VC
4268 # if not operation_params.get("skip_terminate_primitives"):#
4269 # or not vca.get("needed_terminate"):
4270 stage[0] = "Stage 2/3 execute terminating primitives."
4271 self.logger.debug(logging_text + stage[0])
4272 stage[1] = "Looking execution environment that needs terminate."
4273 self.logger.debug(logging_text + stage[1])
bravof922c4172020-11-24 21:21:43 -03004274
tierno588547c2020-07-01 15:30:20 +00004275 for vca_index, vca in enumerate(get_iterable(nsr_deployed, "VCA")):
tierno588547c2020-07-01 15:30:20 +00004276 config_descriptor = None
David Garcia9ad54a42021-05-28 12:08:18 +02004277 vca_member_vnf_index = vca.get("member-vnf-index")
4278 vca_id = self.get_vca_id(
4279 db_vnfrs_dict.get(vca_member_vnf_index)
4280 if vca_member_vnf_index
4281 else None,
4282 db_nsr,
4283 )
tierno588547c2020-07-01 15:30:20 +00004284 if not vca or not vca.get("ee_id"):
4285 continue
4286 if not vca.get("member-vnf-index"):
4287 # ns
4288 config_descriptor = db_nsr.get("ns-configuration")
4289 elif vca.get("vdu_id"):
4290 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
bravofe5a31bc2021-02-17 19:09:12 -03004291 config_descriptor = get_configuration(db_vnfd, vca.get("vdu_id"))
tierno588547c2020-07-01 15:30:20 +00004292 elif vca.get("kdu_name"):
4293 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
bravofe5a31bc2021-02-17 19:09:12 -03004294 config_descriptor = get_configuration(db_vnfd, vca.get("kdu_name"))
tierno588547c2020-07-01 15:30:20 +00004295 else:
bravofe5a31bc2021-02-17 19:09:12 -03004296 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
aktas13251562021-02-12 22:19:10 +03004297 config_descriptor = get_configuration(db_vnfd, db_vnfd["id"])
tierno588547c2020-07-01 15:30:20 +00004298 vca_type = vca.get("type")
garciadeblas5697b8b2021-03-24 09:17:02 +01004299 exec_terminate_primitives = not operation_params.get(
4300 "skip_terminate_primitives"
4301 ) and vca.get("needed_terminate")
tiernoaebd7da2020-08-07 06:36:38 +00004302 # For helm we must destroy_ee. Also for native_charm, as juju_model cannot be deleted if there are
4303 # pending native charms
garciadeblas5697b8b2021-03-24 09:17:02 +01004304 destroy_ee = (
4305 True if vca_type in ("helm", "helm-v3", "native_charm") else False
4306 )
tierno86e33612020-09-16 14:13:06 +00004307 # self.logger.debug(logging_text + "vca_index: {}, ee_id: {}, vca_type: {} destroy_ee: {}".format(
4308 # vca_index, vca.get("ee_id"), vca_type, destroy_ee))
tiernob996d942020-07-03 14:52:28 +00004309 task = asyncio.ensure_future(
David Garciac1fe90a2021-03-31 19:12:02 +02004310 self.destroy_N2VC(
4311 logging_text,
4312 db_nslcmop,
4313 vca,
4314 config_descriptor,
4315 vca_index,
4316 destroy_ee,
4317 exec_terminate_primitives,
4318 vca_id=vca_id,
4319 )
4320 )
tierno588547c2020-07-01 15:30:20 +00004321 tasks_dict_info[task] = "Terminating VCA {}".format(vca.get("ee_id"))
tierno59d22d22018-09-25 18:10:19 +02004322
tierno588547c2020-07-01 15:30:20 +00004323 # wait for pending tasks of terminate primitives
4324 if tasks_dict_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01004325 self.logger.debug(
4326 logging_text
4327 + "Waiting for tasks {}".format(list(tasks_dict_info.keys()))
4328 )
4329 error_list = await self._wait_for_tasks(
4330 logging_text,
4331 tasks_dict_info,
4332 min(self.timeout_charm_delete, timeout_ns_terminate),
4333 stage,
4334 nslcmop_id,
4335 )
tierno86e33612020-09-16 14:13:06 +00004336 tasks_dict_info.clear()
tierno588547c2020-07-01 15:30:20 +00004337 if error_list:
garciadeblas5697b8b2021-03-24 09:17:02 +01004338 return # raise LcmException("; ".join(error_list))
tierno82974b22018-11-27 21:55:36 +00004339
tiernoe876f672020-02-13 14:34:48 +00004340 # remove All execution environments at once
4341 stage[0] = "Stage 3/3 delete all."
quilesj3655ae02019-12-12 16:08:35 +00004342
tierno49676be2020-04-07 16:34:35 +00004343 if nsr_deployed.get("VCA"):
4344 stage[1] = "Deleting all execution environments."
4345 self.logger.debug(logging_text + stage[1])
David Garciac1fe90a2021-03-31 19:12:02 +02004346 vca_id = self.get_vca_id({}, db_nsr)
4347 task_delete_ee = asyncio.ensure_future(
4348 asyncio.wait_for(
4349 self._delete_all_N2VC(db_nsr=db_nsr, vca_id=vca_id),
garciadeblas5697b8b2021-03-24 09:17:02 +01004350 timeout=self.timeout_charm_delete,
David Garciac1fe90a2021-03-31 19:12:02 +02004351 )
4352 )
tierno49676be2020-04-07 16:34:35 +00004353 # task_delete_ee = asyncio.ensure_future(self.n2vc.delete_namespace(namespace="." + nsr_id))
4354 tasks_dict_info[task_delete_ee] = "Terminating all VCA"
tierno59d22d22018-09-25 18:10:19 +02004355
tiernoe876f672020-02-13 14:34:48 +00004356 # Delete from k8scluster
4357 stage[1] = "Deleting KDUs."
4358 self.logger.debug(logging_text + stage[1])
4359 # print(nsr_deployed)
4360 for kdu in get_iterable(nsr_deployed, "K8s"):
4361 if not kdu or not kdu.get("kdu-instance"):
4362 continue
4363 kdu_instance = kdu.get("kdu-instance")
tiernoa2143262020-03-27 16:20:40 +00004364 if kdu.get("k8scluster-type") in self.k8scluster_map:
David Garciac1fe90a2021-03-31 19:12:02 +02004365 # TODO: Uninstall kdu instances taking into account they could be deployed in different VIMs
4366 vca_id = self.get_vca_id({}, db_nsr)
tiernoe876f672020-02-13 14:34:48 +00004367 task_delete_kdu_instance = asyncio.ensure_future(
tiernoa2143262020-03-27 16:20:40 +00004368 self.k8scluster_map[kdu["k8scluster-type"]].uninstall(
4369 cluster_uuid=kdu.get("k8scluster-uuid"),
David Garciac1fe90a2021-03-31 19:12:02 +02004370 kdu_instance=kdu_instance,
4371 vca_id=vca_id,
4372 )
4373 )
tiernoe876f672020-02-13 14:34:48 +00004374 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004375 self.logger.error(
4376 logging_text
4377 + "Unknown k8s deployment type {}".format(
4378 kdu.get("k8scluster-type")
4379 )
4380 )
tiernoe876f672020-02-13 14:34:48 +00004381 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01004382 tasks_dict_info[
4383 task_delete_kdu_instance
4384 ] = "Terminating KDU '{}'".format(kdu.get("kdu-name"))
tierno59d22d22018-09-25 18:10:19 +02004385
4386 # remove from RO
tiernoe876f672020-02-13 14:34:48 +00004387 stage[1] = "Deleting ns from VIM."
tierno69f0d382020-05-07 13:08:09 +00004388 if self.ng_ro:
4389 task_delete_ro = asyncio.ensure_future(
garciadeblas5697b8b2021-03-24 09:17:02 +01004390 self._terminate_ng_ro(
4391 logging_text, nsr_deployed, nsr_id, nslcmop_id, stage
4392 )
4393 )
tierno69f0d382020-05-07 13:08:09 +00004394 else:
4395 task_delete_ro = asyncio.ensure_future(
garciadeblas5697b8b2021-03-24 09:17:02 +01004396 self._terminate_RO(
4397 logging_text, nsr_deployed, nsr_id, nslcmop_id, stage
4398 )
4399 )
tiernoe876f672020-02-13 14:34:48 +00004400 tasks_dict_info[task_delete_ro] = "Removing deployment from VIM"
tierno59d22d22018-09-25 18:10:19 +02004401
tiernoe876f672020-02-13 14:34:48 +00004402 # rest of staff will be done at finally
4403
garciadeblas5697b8b2021-03-24 09:17:02 +01004404 except (
4405 ROclient.ROClientException,
4406 DbException,
4407 LcmException,
4408 N2VCException,
4409 ) as e:
tiernoe876f672020-02-13 14:34:48 +00004410 self.logger.error(logging_text + "Exit Exception {}".format(e))
4411 exc = e
4412 except asyncio.CancelledError:
garciadeblas5697b8b2021-03-24 09:17:02 +01004413 self.logger.error(
4414 logging_text + "Cancelled Exception while '{}'".format(stage[1])
4415 )
tiernoe876f672020-02-13 14:34:48 +00004416 exc = "Operation was cancelled"
4417 except Exception as e:
4418 exc = traceback.format_exc()
garciadeblas5697b8b2021-03-24 09:17:02 +01004419 self.logger.critical(
4420 logging_text + "Exit Exception while '{}': {}".format(stage[1], e),
4421 exc_info=True,
4422 )
tiernoe876f672020-02-13 14:34:48 +00004423 finally:
4424 if exc:
4425 error_list.append(str(exc))
tierno59d22d22018-09-25 18:10:19 +02004426 try:
tiernoe876f672020-02-13 14:34:48 +00004427 # wait for pending tasks
4428 if tasks_dict_info:
4429 stage[1] = "Waiting for terminate pending tasks."
4430 self.logger.debug(logging_text + stage[1])
garciadeblas5697b8b2021-03-24 09:17:02 +01004431 error_list += await self._wait_for_tasks(
4432 logging_text,
4433 tasks_dict_info,
4434 timeout_ns_terminate,
4435 stage,
4436 nslcmop_id,
4437 )
tiernoe876f672020-02-13 14:34:48 +00004438 stage[1] = stage[2] = ""
4439 except asyncio.CancelledError:
4440 error_list.append("Cancelled")
4441 # TODO cancell all tasks
4442 except Exception as exc:
4443 error_list.append(str(exc))
4444 # update status at database
4445 if error_list:
4446 error_detail = "; ".join(error_list)
4447 # self.logger.error(logging_text + error_detail)
garciadeblas5697b8b2021-03-24 09:17:02 +01004448 error_description_nslcmop = "{} Detail: {}".format(
4449 stage[0], error_detail
4450 )
4451 error_description_nsr = "Operation: TERMINATING.{}, {}.".format(
4452 nslcmop_id, stage[0]
4453 )
tierno59d22d22018-09-25 18:10:19 +02004454
tierno59d22d22018-09-25 18:10:19 +02004455 db_nsr_update["operational-status"] = "failed"
garciadeblas5697b8b2021-03-24 09:17:02 +01004456 db_nsr_update["detailed-status"] = (
4457 error_description_nsr + " Detail: " + error_detail
4458 )
tiernoe876f672020-02-13 14:34:48 +00004459 db_nslcmop_update["detailed-status"] = error_detail
4460 nslcmop_operation_state = "FAILED"
4461 ns_state = "BROKEN"
tierno59d22d22018-09-25 18:10:19 +02004462 else:
tiernoa2143262020-03-27 16:20:40 +00004463 error_detail = None
tiernoe876f672020-02-13 14:34:48 +00004464 error_description_nsr = error_description_nslcmop = None
4465 ns_state = "NOT_INSTANTIATED"
tierno59d22d22018-09-25 18:10:19 +02004466 db_nsr_update["operational-status"] = "terminated"
4467 db_nsr_update["detailed-status"] = "Done"
4468 db_nsr_update["_admin.nsState"] = "NOT_INSTANTIATED"
4469 db_nslcmop_update["detailed-status"] = "Done"
tiernoe876f672020-02-13 14:34:48 +00004470 nslcmop_operation_state = "COMPLETED"
tierno59d22d22018-09-25 18:10:19 +02004471
tiernoe876f672020-02-13 14:34:48 +00004472 if db_nsr:
4473 self._write_ns_status(
4474 nsr_id=nsr_id,
4475 ns_state=ns_state,
4476 current_operation="IDLE",
4477 current_operation_id=None,
4478 error_description=error_description_nsr,
tiernoa2143262020-03-27 16:20:40 +00004479 error_detail=error_detail,
garciadeblas5697b8b2021-03-24 09:17:02 +01004480 other_update=db_nsr_update,
tiernoe876f672020-02-13 14:34:48 +00004481 )
tiernoa17d4f42020-04-28 09:59:23 +00004482 self._write_op_status(
4483 op_id=nslcmop_id,
4484 stage="",
4485 error_message=error_description_nslcmop,
4486 operation_state=nslcmop_operation_state,
4487 other_update=db_nslcmop_update,
4488 )
lloretgalleg6d488782020-07-22 10:13:46 +00004489 if ns_state == "NOT_INSTANTIATED":
4490 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01004491 self.db.set_list(
4492 "vnfrs",
4493 {"nsr-id-ref": nsr_id},
4494 {"_admin.nsState": "NOT_INSTANTIATED"},
4495 )
lloretgalleg6d488782020-07-22 10:13:46 +00004496 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01004497 self.logger.warn(
4498 logging_text
4499 + "Error writing VNFR status for nsr-id-ref: {} -> {}".format(
4500 nsr_id, e
4501 )
4502 )
tiernoa17d4f42020-04-28 09:59:23 +00004503 if operation_params:
tiernoe876f672020-02-13 14:34:48 +00004504 autoremove = operation_params.get("autoremove", False)
tierno59d22d22018-09-25 18:10:19 +02004505 if nslcmop_operation_state:
4506 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01004507 await self.msg.aiowrite(
4508 "ns",
4509 "terminated",
4510 {
4511 "nsr_id": nsr_id,
4512 "nslcmop_id": nslcmop_id,
4513 "operationState": nslcmop_operation_state,
4514 "autoremove": autoremove,
4515 },
4516 loop=self.loop,
4517 )
tierno59d22d22018-09-25 18:10:19 +02004518 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01004519 self.logger.error(
4520 logging_text + "kafka_write notification Exception {}".format(e)
4521 )
quilesj7e13aeb2019-10-08 13:34:55 +02004522
tierno59d22d22018-09-25 18:10:19 +02004523 self.logger.debug(logging_text + "Exit")
4524 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_terminate")
4525
garciadeblas5697b8b2021-03-24 09:17:02 +01004526 async def _wait_for_tasks(
4527 self, logging_text, created_tasks_info, timeout, stage, nslcmop_id, nsr_id=None
4528 ):
tiernoe876f672020-02-13 14:34:48 +00004529 time_start = time()
tiernoa2143262020-03-27 16:20:40 +00004530 error_detail_list = []
tiernoe876f672020-02-13 14:34:48 +00004531 error_list = []
4532 pending_tasks = list(created_tasks_info.keys())
4533 num_tasks = len(pending_tasks)
4534 num_done = 0
4535 stage[1] = "{}/{}.".format(num_done, num_tasks)
4536 self._write_op_status(nslcmop_id, stage)
tiernoe876f672020-02-13 14:34:48 +00004537 while pending_tasks:
tiernoa2143262020-03-27 16:20:40 +00004538 new_error = None
tiernoe876f672020-02-13 14:34:48 +00004539 _timeout = timeout + time_start - time()
garciadeblas5697b8b2021-03-24 09:17:02 +01004540 done, pending_tasks = await asyncio.wait(
4541 pending_tasks, timeout=_timeout, return_when=asyncio.FIRST_COMPLETED
4542 )
tiernoe876f672020-02-13 14:34:48 +00004543 num_done += len(done)
garciadeblas5697b8b2021-03-24 09:17:02 +01004544 if not done: # Timeout
tiernoe876f672020-02-13 14:34:48 +00004545 for task in pending_tasks:
tiernoa2143262020-03-27 16:20:40 +00004546 new_error = created_tasks_info[task] + ": Timeout"
4547 error_detail_list.append(new_error)
4548 error_list.append(new_error)
tiernoe876f672020-02-13 14:34:48 +00004549 break
4550 for task in done:
4551 if task.cancelled():
tierno067e04a2020-03-31 12:53:13 +00004552 exc = "Cancelled"
tiernoe876f672020-02-13 14:34:48 +00004553 else:
4554 exc = task.exception()
tierno067e04a2020-03-31 12:53:13 +00004555 if exc:
4556 if isinstance(exc, asyncio.TimeoutError):
4557 exc = "Timeout"
4558 new_error = created_tasks_info[task] + ": {}".format(exc)
4559 error_list.append(created_tasks_info[task])
4560 error_detail_list.append(new_error)
garciadeblas5697b8b2021-03-24 09:17:02 +01004561 if isinstance(
4562 exc,
4563 (
4564 str,
4565 DbException,
4566 N2VCException,
4567 ROclient.ROClientException,
4568 LcmException,
4569 K8sException,
4570 NgRoException,
4571 ),
4572 ):
tierno067e04a2020-03-31 12:53:13 +00004573 self.logger.error(logging_text + new_error)
tiernoe876f672020-02-13 14:34:48 +00004574 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004575 exc_traceback = "".join(
4576 traceback.format_exception(None, exc, exc.__traceback__)
4577 )
4578 self.logger.error(
4579 logging_text
4580 + created_tasks_info[task]
4581 + " "
4582 + exc_traceback
4583 )
tierno067e04a2020-03-31 12:53:13 +00004584 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004585 self.logger.debug(
4586 logging_text + created_tasks_info[task] + ": Done"
4587 )
tiernoe876f672020-02-13 14:34:48 +00004588 stage[1] = "{}/{}.".format(num_done, num_tasks)
4589 if new_error:
tiernoa2143262020-03-27 16:20:40 +00004590 stage[1] += " Errors: " + ". ".join(error_detail_list) + "."
tiernoe876f672020-02-13 14:34:48 +00004591 if nsr_id: # update also nsr
garciadeblas5697b8b2021-03-24 09:17:02 +01004592 self.update_db_2(
4593 "nsrs",
4594 nsr_id,
4595 {
4596 "errorDescription": "Error at: " + ", ".join(error_list),
4597 "errorDetail": ". ".join(error_detail_list),
4598 },
4599 )
tiernoe876f672020-02-13 14:34:48 +00004600 self._write_op_status(nslcmop_id, stage)
tiernoa2143262020-03-27 16:20:40 +00004601 return error_detail_list
tiernoe876f672020-02-13 14:34:48 +00004602
tiernoda1ff8c2020-10-22 14:12:46 +00004603 @staticmethod
4604 def _map_primitive_params(primitive_desc, params, instantiation_params):
tiernoda964822019-01-14 15:53:47 +00004605 """
4606 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
4607 The default-value is used. If it is between < > it look for a value at instantiation_params
4608 :param primitive_desc: portion of VNFD/NSD that describes primitive
4609 :param params: Params provided by user
4610 :param instantiation_params: Instantiation params provided by user
4611 :return: a dictionary with the calculated params
4612 """
4613 calculated_params = {}
4614 for parameter in primitive_desc.get("parameter", ()):
4615 param_name = parameter["name"]
4616 if param_name in params:
4617 calculated_params[param_name] = params[param_name]
tierno98ad6ea2019-05-30 17:16:28 +00004618 elif "default-value" in parameter or "value" in parameter:
4619 if "value" in parameter:
4620 calculated_params[param_name] = parameter["value"]
4621 else:
4622 calculated_params[param_name] = parameter["default-value"]
garciadeblas5697b8b2021-03-24 09:17:02 +01004623 if (
4624 isinstance(calculated_params[param_name], str)
4625 and calculated_params[param_name].startswith("<")
4626 and calculated_params[param_name].endswith(">")
4627 ):
tierno98ad6ea2019-05-30 17:16:28 +00004628 if calculated_params[param_name][1:-1] in instantiation_params:
garciadeblas5697b8b2021-03-24 09:17:02 +01004629 calculated_params[param_name] = instantiation_params[
4630 calculated_params[param_name][1:-1]
4631 ]
tiernoda964822019-01-14 15:53:47 +00004632 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004633 raise LcmException(
4634 "Parameter {} needed to execute primitive {} not provided".format(
4635 calculated_params[param_name], primitive_desc["name"]
4636 )
4637 )
tiernoda964822019-01-14 15:53:47 +00004638 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004639 raise LcmException(
4640 "Parameter {} needed to execute primitive {} not provided".format(
4641 param_name, primitive_desc["name"]
4642 )
4643 )
tierno59d22d22018-09-25 18:10:19 +02004644
tiernoda964822019-01-14 15:53:47 +00004645 if isinstance(calculated_params[param_name], (dict, list, tuple)):
garciadeblas5697b8b2021-03-24 09:17:02 +01004646 calculated_params[param_name] = yaml.safe_dump(
4647 calculated_params[param_name], default_flow_style=True, width=256
4648 )
4649 elif isinstance(calculated_params[param_name], str) and calculated_params[
4650 param_name
4651 ].startswith("!!yaml "):
tiernoda964822019-01-14 15:53:47 +00004652 calculated_params[param_name] = calculated_params[param_name][7:]
tiernofa40e692020-10-14 14:59:36 +00004653 if parameter.get("data-type") == "INTEGER":
4654 try:
4655 calculated_params[param_name] = int(calculated_params[param_name])
4656 except ValueError: # error converting string to int
4657 raise LcmException(
garciadeblas5697b8b2021-03-24 09:17:02 +01004658 "Parameter {} of primitive {} must be integer".format(
4659 param_name, primitive_desc["name"]
4660 )
4661 )
tiernofa40e692020-10-14 14:59:36 +00004662 elif parameter.get("data-type") == "BOOLEAN":
garciadeblas5697b8b2021-03-24 09:17:02 +01004663 calculated_params[param_name] = not (
4664 (str(calculated_params[param_name])).lower() == "false"
4665 )
tiernoc3f2a822019-11-05 13:45:04 +00004666
4667 # add always ns_config_info if primitive name is config
4668 if primitive_desc["name"] == "config":
4669 if "ns_config_info" in instantiation_params:
garciadeblas5697b8b2021-03-24 09:17:02 +01004670 calculated_params["ns_config_info"] = instantiation_params[
4671 "ns_config_info"
4672 ]
tiernoda964822019-01-14 15:53:47 +00004673 return calculated_params
4674
garciadeblas5697b8b2021-03-24 09:17:02 +01004675 def _look_for_deployed_vca(
4676 self,
4677 deployed_vca,
4678 member_vnf_index,
4679 vdu_id,
4680 vdu_count_index,
4681 kdu_name=None,
4682 ee_descriptor_id=None,
4683 ):
tiernoe876f672020-02-13 14:34:48 +00004684 # find vca_deployed record for this action. Raise LcmException if not found or there is not any id.
4685 for vca in deployed_vca:
4686 if not vca:
4687 continue
4688 if member_vnf_index != vca["member-vnf-index"] or vdu_id != vca["vdu_id"]:
4689 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01004690 if (
4691 vdu_count_index is not None
4692 and vdu_count_index != vca["vdu_count_index"]
4693 ):
tiernoe876f672020-02-13 14:34:48 +00004694 continue
4695 if kdu_name and kdu_name != vca["kdu_name"]:
4696 continue
tiernoa278b842020-07-08 15:33:55 +00004697 if ee_descriptor_id and ee_descriptor_id != vca["ee_descriptor_id"]:
4698 continue
tiernoe876f672020-02-13 14:34:48 +00004699 break
4700 else:
4701 # vca_deployed not found
garciadeblas5697b8b2021-03-24 09:17:02 +01004702 raise LcmException(
4703 "charm for member_vnf_index={} vdu_id={}.{} kdu_name={} execution-environment-list.id={}"
4704 " is not deployed".format(
4705 member_vnf_index,
4706 vdu_id,
4707 vdu_count_index,
4708 kdu_name,
4709 ee_descriptor_id,
4710 )
4711 )
tiernoe876f672020-02-13 14:34:48 +00004712 # get ee_id
4713 ee_id = vca.get("ee_id")
garciadeblas5697b8b2021-03-24 09:17:02 +01004714 vca_type = vca.get(
4715 "type", "lxc_proxy_charm"
4716 ) # default value for backward compatibility - proxy charm
tiernoe876f672020-02-13 14:34:48 +00004717 if not ee_id:
garciadeblas5697b8b2021-03-24 09:17:02 +01004718 raise LcmException(
4719 "charm for member_vnf_index={} vdu_id={} kdu_name={} vdu_count_index={} has not "
4720 "execution environment".format(
4721 member_vnf_index, vdu_id, kdu_name, vdu_count_index
4722 )
4723 )
tierno588547c2020-07-01 15:30:20 +00004724 return ee_id, vca_type
tiernoe876f672020-02-13 14:34:48 +00004725
David Garciac1fe90a2021-03-31 19:12:02 +02004726 async def _ns_execute_primitive(
4727 self,
4728 ee_id,
4729 primitive,
4730 primitive_params,
4731 retries=0,
4732 retries_interval=30,
4733 timeout=None,
4734 vca_type=None,
4735 db_dict=None,
4736 vca_id: str = None,
4737 ) -> (str, str):
tiernoda964822019-01-14 15:53:47 +00004738 try:
tierno98ad6ea2019-05-30 17:16:28 +00004739 if primitive == "config":
4740 primitive_params = {"params": primitive_params}
tierno2fc7ce52019-06-11 22:50:01 +00004741
tierno588547c2020-07-01 15:30:20 +00004742 vca_type = vca_type or "lxc_proxy_charm"
4743
quilesj7e13aeb2019-10-08 13:34:55 +02004744 while retries >= 0:
4745 try:
tierno067e04a2020-03-31 12:53:13 +00004746 output = await asyncio.wait_for(
tierno588547c2020-07-01 15:30:20 +00004747 self.vca_map[vca_type].exec_primitive(
tierno067e04a2020-03-31 12:53:13 +00004748 ee_id=ee_id,
4749 primitive_name=primitive,
4750 params_dict=primitive_params,
4751 progress_timeout=self.timeout_progress_primitive,
tierno588547c2020-07-01 15:30:20 +00004752 total_timeout=self.timeout_primitive,
David Garciac1fe90a2021-03-31 19:12:02 +02004753 db_dict=db_dict,
4754 vca_id=vca_id,
aktas98488ed2021-07-29 17:42:49 +03004755 vca_type=vca_type,
David Garciac1fe90a2021-03-31 19:12:02 +02004756 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01004757 timeout=timeout or self.timeout_primitive,
4758 )
quilesj7e13aeb2019-10-08 13:34:55 +02004759 # execution was OK
4760 break
tierno067e04a2020-03-31 12:53:13 +00004761 except asyncio.CancelledError:
4762 raise
4763 except Exception as e: # asyncio.TimeoutError
4764 if isinstance(e, asyncio.TimeoutError):
4765 e = "Timeout"
quilesj7e13aeb2019-10-08 13:34:55 +02004766 retries -= 1
4767 if retries >= 0:
garciadeblas5697b8b2021-03-24 09:17:02 +01004768 self.logger.debug(
4769 "Error executing action {} on {} -> {}".format(
4770 primitive, ee_id, e
4771 )
4772 )
quilesj7e13aeb2019-10-08 13:34:55 +02004773 # wait and retry
4774 await asyncio.sleep(retries_interval, loop=self.loop)
tierno73d8bd02019-11-18 17:33:27 +00004775 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004776 return "FAILED", str(e)
quilesj7e13aeb2019-10-08 13:34:55 +02004777
garciadeblas5697b8b2021-03-24 09:17:02 +01004778 return "COMPLETED", output
quilesj7e13aeb2019-10-08 13:34:55 +02004779
tierno067e04a2020-03-31 12:53:13 +00004780 except (LcmException, asyncio.CancelledError):
tiernoe876f672020-02-13 14:34:48 +00004781 raise
quilesj7e13aeb2019-10-08 13:34:55 +02004782 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01004783 return "FAIL", "Error executing action {}: {}".format(primitive, e)
tierno59d22d22018-09-25 18:10:19 +02004784
ksaikiranr3fde2c72021-03-15 10:39:06 +05304785 async def vca_status_refresh(self, nsr_id, nslcmop_id):
4786 """
4787 Updating the vca_status with latest juju information in nsrs record
4788 :param: nsr_id: Id of the nsr
4789 :param: nslcmop_id: Id of the nslcmop
4790 :return: None
4791 """
4792
4793 self.logger.debug("Task ns={} action={} Enter".format(nsr_id, nslcmop_id))
4794 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
David Garciac1fe90a2021-03-31 19:12:02 +02004795 vca_id = self.get_vca_id({}, db_nsr)
garciadeblas5697b8b2021-03-24 09:17:02 +01004796 if db_nsr["_admin"]["deployed"]["K8s"]:
4797 for k8s_index, k8s in enumerate(db_nsr["_admin"]["deployed"]["K8s"]):
ksaikiranr656b6dd2021-02-19 10:25:18 +05304798 cluster_uuid, kdu_instance = k8s["k8scluster-uuid"], k8s["kdu-instance"]
garciadeblas5697b8b2021-03-24 09:17:02 +01004799 await self._on_update_k8s_db(
4800 cluster_uuid, kdu_instance, filter={"_id": nsr_id}, vca_id=vca_id
4801 )
ksaikiranr656b6dd2021-02-19 10:25:18 +05304802 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004803 for vca_index, _ in enumerate(db_nsr["_admin"]["deployed"]["VCA"]):
ksaikiranr656b6dd2021-02-19 10:25:18 +05304804 table, filter = "nsrs", {"_id": nsr_id}
4805 path = "_admin.deployed.VCA.{}.".format(vca_index)
4806 await self._on_update_n2vc_db(table, filter, path, {})
ksaikiranr3fde2c72021-03-15 10:39:06 +05304807
4808 self.logger.debug("Task ns={} action={} Exit".format(nsr_id, nslcmop_id))
4809 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_vca_status_refresh")
4810
tierno59d22d22018-09-25 18:10:19 +02004811 async def action(self, nsr_id, nslcmop_id):
kuused124bfe2019-06-18 12:09:24 +02004812 # Try to lock HA task here
garciadeblas5697b8b2021-03-24 09:17:02 +01004813 task_is_locked_by_me = self.lcm_tasks.lock_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02004814 if not task_is_locked_by_me:
4815 return
4816
tierno59d22d22018-09-25 18:10:19 +02004817 logging_text = "Task ns={} action={} ".format(nsr_id, nslcmop_id)
4818 self.logger.debug(logging_text + "Enter")
4819 # get all needed from database
4820 db_nsr = None
4821 db_nslcmop = None
tiernoe876f672020-02-13 14:34:48 +00004822 db_nsr_update = {}
tierno59d22d22018-09-25 18:10:19 +02004823 db_nslcmop_update = {}
4824 nslcmop_operation_state = None
tierno067e04a2020-03-31 12:53:13 +00004825 error_description_nslcmop = None
tierno59d22d22018-09-25 18:10:19 +02004826 exc = None
4827 try:
kuused124bfe2019-06-18 12:09:24 +02004828 # wait for any previous tasks in process
tierno3cf81a32019-11-11 17:07:00 +00004829 step = "Waiting for previous operations to terminate"
garciadeblas5697b8b2021-03-24 09:17:02 +01004830 await self.lcm_tasks.waitfor_related_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02004831
quilesj4cda56b2019-12-05 10:02:20 +00004832 self._write_ns_status(
4833 nsr_id=nsr_id,
4834 ns_state=None,
4835 current_operation="RUNNING ACTION",
garciadeblas5697b8b2021-03-24 09:17:02 +01004836 current_operation_id=nslcmop_id,
quilesj4cda56b2019-12-05 10:02:20 +00004837 )
4838
tierno59d22d22018-09-25 18:10:19 +02004839 step = "Getting information from database"
4840 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
4841 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
Guillermo Calvino57c68152022-01-26 17:40:31 +01004842 if db_nslcmop["operationParams"].get("primitive_params"):
4843 db_nslcmop["operationParams"]["primitive_params"] = json.loads(
4844 db_nslcmop["operationParams"]["primitive_params"]
4845 )
tiernoda964822019-01-14 15:53:47 +00004846
tiernoe4f7e6c2018-11-27 14:55:30 +00004847 nsr_deployed = db_nsr["_admin"].get("deployed")
tierno1b633412019-02-25 16:48:23 +00004848 vnf_index = db_nslcmop["operationParams"].get("member_vnf_index")
tierno59d22d22018-09-25 18:10:19 +02004849 vdu_id = db_nslcmop["operationParams"].get("vdu_id")
calvinosanch9f9c6f22019-11-04 13:37:39 +01004850 kdu_name = db_nslcmop["operationParams"].get("kdu_name")
tiernoe4f7e6c2018-11-27 14:55:30 +00004851 vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
tierno067e04a2020-03-31 12:53:13 +00004852 primitive = db_nslcmop["operationParams"]["primitive"]
4853 primitive_params = db_nslcmop["operationParams"]["primitive_params"]
garciadeblas5697b8b2021-03-24 09:17:02 +01004854 timeout_ns_action = db_nslcmop["operationParams"].get(
4855 "timeout_ns_action", self.timeout_primitive
4856 )
tierno59d22d22018-09-25 18:10:19 +02004857
tierno1b633412019-02-25 16:48:23 +00004858 if vnf_index:
4859 step = "Getting vnfr from database"
garciadeblas5697b8b2021-03-24 09:17:02 +01004860 db_vnfr = self.db.get_one(
4861 "vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id}
4862 )
Guillermo Calvino48aee4c2022-02-01 18:59:50 +01004863 if db_vnfr.get("kdur"):
4864 kdur_list = []
4865 for kdur in db_vnfr["kdur"]:
4866 if kdur.get("additionalParams"):
4867 kdur["additionalParams"] = json.loads(kdur["additionalParams"])
4868 kdur_list.append(kdur)
4869 db_vnfr["kdur"] = kdur_list
tierno1b633412019-02-25 16:48:23 +00004870 step = "Getting vnfd from database"
4871 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
bravofa96dd9c2021-10-13 17:37:36 -03004872
4873 # Sync filesystem before running a primitive
4874 self.fs.sync(db_vnfr["vnfd-id"])
tierno1b633412019-02-25 16:48:23 +00004875 else:
tierno067e04a2020-03-31 12:53:13 +00004876 step = "Getting nsd from database"
4877 db_nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
tiernoda964822019-01-14 15:53:47 +00004878
David Garciac1fe90a2021-03-31 19:12:02 +02004879 vca_id = self.get_vca_id(db_vnfr, db_nsr)
tierno82974b22018-11-27 21:55:36 +00004880 # for backward compatibility
4881 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
4882 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
4883 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
4884 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4885
tiernoda964822019-01-14 15:53:47 +00004886 # look for primitive
tiernoa278b842020-07-08 15:33:55 +00004887 config_primitive_desc = descriptor_configuration = None
tiernoda964822019-01-14 15:53:47 +00004888 if vdu_id:
bravofe5a31bc2021-02-17 19:09:12 -03004889 descriptor_configuration = get_configuration(db_vnfd, vdu_id)
calvinosanch9f9c6f22019-11-04 13:37:39 +01004890 elif kdu_name:
bravofe5a31bc2021-02-17 19:09:12 -03004891 descriptor_configuration = get_configuration(db_vnfd, kdu_name)
tierno1b633412019-02-25 16:48:23 +00004892 elif vnf_index:
bravofe5a31bc2021-02-17 19:09:12 -03004893 descriptor_configuration = get_configuration(db_vnfd, db_vnfd["id"])
tierno1b633412019-02-25 16:48:23 +00004894 else:
tiernoa278b842020-07-08 15:33:55 +00004895 descriptor_configuration = db_nsd.get("ns-configuration")
4896
garciadeblas5697b8b2021-03-24 09:17:02 +01004897 if descriptor_configuration and descriptor_configuration.get(
4898 "config-primitive"
4899 ):
tiernoa278b842020-07-08 15:33:55 +00004900 for config_primitive in descriptor_configuration["config-primitive"]:
tierno1b633412019-02-25 16:48:23 +00004901 if config_primitive["name"] == primitive:
4902 config_primitive_desc = config_primitive
4903 break
tiernoda964822019-01-14 15:53:47 +00004904
garciadeblas6bed6b32020-07-20 11:05:42 +00004905 if not config_primitive_desc:
4906 if not (kdu_name and primitive in ("upgrade", "rollback", "status")):
garciadeblas5697b8b2021-03-24 09:17:02 +01004907 raise LcmException(
4908 "Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".format(
4909 primitive
4910 )
4911 )
garciadeblas6bed6b32020-07-20 11:05:42 +00004912 primitive_name = primitive
4913 ee_descriptor_id = None
4914 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004915 primitive_name = config_primitive_desc.get(
4916 "execution-environment-primitive", primitive
4917 )
4918 ee_descriptor_id = config_primitive_desc.get(
4919 "execution-environment-ref"
4920 )
tierno1b633412019-02-25 16:48:23 +00004921
tierno1b633412019-02-25 16:48:23 +00004922 if vnf_index:
tierno626e0152019-11-29 14:16:16 +00004923 if vdu_id:
garciadeblas5697b8b2021-03-24 09:17:02 +01004924 vdur = next(
4925 (x for x in db_vnfr["vdur"] if x["vdu-id-ref"] == vdu_id), None
4926 )
bravof922c4172020-11-24 21:21:43 -03004927 desc_params = parse_yaml_strings(vdur.get("additionalParams"))
tierno067e04a2020-03-31 12:53:13 +00004928 elif kdu_name:
garciadeblas5697b8b2021-03-24 09:17:02 +01004929 kdur = next(
4930 (x for x in db_vnfr["kdur"] if x["kdu-name"] == kdu_name), None
4931 )
bravof922c4172020-11-24 21:21:43 -03004932 desc_params = parse_yaml_strings(kdur.get("additionalParams"))
tierno067e04a2020-03-31 12:53:13 +00004933 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004934 desc_params = parse_yaml_strings(
4935 db_vnfr.get("additionalParamsForVnf")
4936 )
tierno1b633412019-02-25 16:48:23 +00004937 else:
bravof922c4172020-11-24 21:21:43 -03004938 desc_params = parse_yaml_strings(db_nsr.get("additionalParamsForNs"))
bravofe5a31bc2021-02-17 19:09:12 -03004939 if kdu_name and get_configuration(db_vnfd, kdu_name):
4940 kdu_configuration = get_configuration(db_vnfd, kdu_name)
David Garciad41dbd62020-12-10 12:52:52 +01004941 actions = set()
David Garciaa1003662021-02-16 21:07:58 +01004942 for primitive in kdu_configuration.get("initial-config-primitive", []):
David Garciad41dbd62020-12-10 12:52:52 +01004943 actions.add(primitive["name"])
David Garciaa1003662021-02-16 21:07:58 +01004944 for primitive in kdu_configuration.get("config-primitive", []):
David Garciad41dbd62020-12-10 12:52:52 +01004945 actions.add(primitive["name"])
4946 kdu_action = True if primitive_name in actions else False
Dominik Fleischmann771c32b2020-04-07 12:39:36 +02004947
tiernoda964822019-01-14 15:53:47 +00004948 # TODO check if ns is in a proper status
garciadeblas5697b8b2021-03-24 09:17:02 +01004949 if kdu_name and (
4950 primitive_name in ("upgrade", "rollback", "status") or kdu_action
4951 ):
tierno067e04a2020-03-31 12:53:13 +00004952 # kdur and desc_params already set from before
4953 if primitive_params:
4954 desc_params.update(primitive_params)
4955 # TODO Check if we will need something at vnf level
4956 for index, kdu in enumerate(get_iterable(nsr_deployed, "K8s")):
garciadeblas5697b8b2021-03-24 09:17:02 +01004957 if (
4958 kdu_name == kdu["kdu-name"]
4959 and kdu["member-vnf-index"] == vnf_index
4960 ):
tierno067e04a2020-03-31 12:53:13 +00004961 break
4962 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004963 raise LcmException(
4964 "KDU '{}' for vnf '{}' not deployed".format(kdu_name, vnf_index)
4965 )
quilesj7e13aeb2019-10-08 13:34:55 +02004966
tierno067e04a2020-03-31 12:53:13 +00004967 if kdu.get("k8scluster-type") not in self.k8scluster_map:
garciadeblas5697b8b2021-03-24 09:17:02 +01004968 msg = "unknown k8scluster-type '{}'".format(
4969 kdu.get("k8scluster-type")
4970 )
tierno067e04a2020-03-31 12:53:13 +00004971 raise LcmException(msg)
4972
garciadeblas5697b8b2021-03-24 09:17:02 +01004973 db_dict = {
4974 "collection": "nsrs",
4975 "filter": {"_id": nsr_id},
4976 "path": "_admin.deployed.K8s.{}".format(index),
4977 }
4978 self.logger.debug(
4979 logging_text
4980 + "Exec k8s {} on {}.{}".format(primitive_name, vnf_index, kdu_name)
4981 )
tiernoa278b842020-07-08 15:33:55 +00004982 step = "Executing kdu {}".format(primitive_name)
4983 if primitive_name == "upgrade":
tierno067e04a2020-03-31 12:53:13 +00004984 if desc_params.get("kdu_model"):
4985 kdu_model = desc_params.get("kdu_model")
4986 del desc_params["kdu_model"]
4987 else:
4988 kdu_model = kdu.get("kdu-model")
4989 parts = kdu_model.split(sep=":")
4990 if len(parts) == 2:
4991 kdu_model = parts[0]
4992
4993 detailed_status = await asyncio.wait_for(
4994 self.k8scluster_map[kdu["k8scluster-type"]].upgrade(
4995 cluster_uuid=kdu.get("k8scluster-uuid"),
4996 kdu_instance=kdu.get("kdu-instance"),
garciadeblas5697b8b2021-03-24 09:17:02 +01004997 atomic=True,
4998 kdu_model=kdu_model,
4999 params=desc_params,
5000 db_dict=db_dict,
5001 timeout=timeout_ns_action,
5002 ),
5003 timeout=timeout_ns_action + 10,
5004 )
5005 self.logger.debug(
5006 logging_text + " Upgrade of kdu {} done".format(detailed_status)
5007 )
tiernoa278b842020-07-08 15:33:55 +00005008 elif primitive_name == "rollback":
tierno067e04a2020-03-31 12:53:13 +00005009 detailed_status = await asyncio.wait_for(
5010 self.k8scluster_map[kdu["k8scluster-type"]].rollback(
5011 cluster_uuid=kdu.get("k8scluster-uuid"),
5012 kdu_instance=kdu.get("kdu-instance"),
garciadeblas5697b8b2021-03-24 09:17:02 +01005013 db_dict=db_dict,
5014 ),
5015 timeout=timeout_ns_action,
5016 )
tiernoa278b842020-07-08 15:33:55 +00005017 elif primitive_name == "status":
tierno067e04a2020-03-31 12:53:13 +00005018 detailed_status = await asyncio.wait_for(
5019 self.k8scluster_map[kdu["k8scluster-type"]].status_kdu(
5020 cluster_uuid=kdu.get("k8scluster-uuid"),
David Garciac1fe90a2021-03-31 19:12:02 +02005021 kdu_instance=kdu.get("kdu-instance"),
5022 vca_id=vca_id,
5023 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01005024 timeout=timeout_ns_action,
David Garciac1fe90a2021-03-31 19:12:02 +02005025 )
Dominik Fleischmann771c32b2020-04-07 12:39:36 +02005026 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01005027 kdu_instance = kdu.get("kdu-instance") or "{}-{}".format(
5028 kdu["kdu-name"], nsr_id
5029 )
5030 params = self._map_primitive_params(
5031 config_primitive_desc, primitive_params, desc_params
5032 )
Dominik Fleischmann771c32b2020-04-07 12:39:36 +02005033
5034 detailed_status = await asyncio.wait_for(
5035 self.k8scluster_map[kdu["k8scluster-type"]].exec_primitive(
5036 cluster_uuid=kdu.get("k8scluster-uuid"),
5037 kdu_instance=kdu_instance,
tiernoa278b842020-07-08 15:33:55 +00005038 primitive_name=primitive_name,
garciadeblas5697b8b2021-03-24 09:17:02 +01005039 params=params,
5040 db_dict=db_dict,
David Garciac1fe90a2021-03-31 19:12:02 +02005041 timeout=timeout_ns_action,
5042 vca_id=vca_id,
5043 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01005044 timeout=timeout_ns_action,
David Garciac1fe90a2021-03-31 19:12:02 +02005045 )
tierno067e04a2020-03-31 12:53:13 +00005046
5047 if detailed_status:
garciadeblas5697b8b2021-03-24 09:17:02 +01005048 nslcmop_operation_state = "COMPLETED"
tierno067e04a2020-03-31 12:53:13 +00005049 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01005050 detailed_status = ""
5051 nslcmop_operation_state = "FAILED"
tierno067e04a2020-03-31 12:53:13 +00005052 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01005053 ee_id, vca_type = self._look_for_deployed_vca(
5054 nsr_deployed["VCA"],
5055 member_vnf_index=vnf_index,
5056 vdu_id=vdu_id,
5057 vdu_count_index=vdu_count_index,
5058 ee_descriptor_id=ee_descriptor_id,
5059 )
5060 for vca_index, vca_deployed in enumerate(
5061 db_nsr["_admin"]["deployed"]["VCA"]
5062 ):
ksaikiranrb1c9f372021-03-15 11:07:29 +05305063 if vca_deployed.get("member-vnf-index") == vnf_index:
garciadeblas5697b8b2021-03-24 09:17:02 +01005064 db_dict = {
5065 "collection": "nsrs",
5066 "filter": {"_id": nsr_id},
5067 "path": "_admin.deployed.VCA.{}.".format(vca_index),
5068 }
ksaikiranrb1c9f372021-03-15 11:07:29 +05305069 break
garciadeblas5697b8b2021-03-24 09:17:02 +01005070 (
5071 nslcmop_operation_state,
5072 detailed_status,
5073 ) = await self._ns_execute_primitive(
tierno588547c2020-07-01 15:30:20 +00005074 ee_id,
tiernoa278b842020-07-08 15:33:55 +00005075 primitive=primitive_name,
garciadeblas5697b8b2021-03-24 09:17:02 +01005076 primitive_params=self._map_primitive_params(
5077 config_primitive_desc, primitive_params, desc_params
5078 ),
tierno588547c2020-07-01 15:30:20 +00005079 timeout=timeout_ns_action,
5080 vca_type=vca_type,
David Garciac1fe90a2021-03-31 19:12:02 +02005081 db_dict=db_dict,
5082 vca_id=vca_id,
5083 )
tierno067e04a2020-03-31 12:53:13 +00005084
5085 db_nslcmop_update["detailed-status"] = detailed_status
garciadeblas5697b8b2021-03-24 09:17:02 +01005086 error_description_nslcmop = (
5087 detailed_status if nslcmop_operation_state == "FAILED" else ""
5088 )
5089 self.logger.debug(
5090 logging_text
5091 + " task Done with result {} {}".format(
5092 nslcmop_operation_state, detailed_status
5093 )
5094 )
tierno59d22d22018-09-25 18:10:19 +02005095 return # database update is called inside finally
5096
tiernof59ad6c2020-04-08 12:50:52 +00005097 except (DbException, LcmException, N2VCException, K8sException) as e:
tierno59d22d22018-09-25 18:10:19 +02005098 self.logger.error(logging_text + "Exit Exception {}".format(e))
5099 exc = e
5100 except asyncio.CancelledError:
garciadeblas5697b8b2021-03-24 09:17:02 +01005101 self.logger.error(
5102 logging_text + "Cancelled Exception while '{}'".format(step)
5103 )
tierno59d22d22018-09-25 18:10:19 +02005104 exc = "Operation was cancelled"
tierno067e04a2020-03-31 12:53:13 +00005105 except asyncio.TimeoutError:
5106 self.logger.error(logging_text + "Timeout while '{}'".format(step))
5107 exc = "Timeout"
tierno59d22d22018-09-25 18:10:19 +02005108 except Exception as e:
5109 exc = traceback.format_exc()
garciadeblas5697b8b2021-03-24 09:17:02 +01005110 self.logger.critical(
5111 logging_text + "Exit Exception {} {}".format(type(e).__name__, e),
5112 exc_info=True,
5113 )
tierno59d22d22018-09-25 18:10:19 +02005114 finally:
tierno067e04a2020-03-31 12:53:13 +00005115 if exc:
garciadeblas5697b8b2021-03-24 09:17:02 +01005116 db_nslcmop_update[
5117 "detailed-status"
5118 ] = (
5119 detailed_status
5120 ) = error_description_nslcmop = "FAILED {}: {}".format(step, exc)
tierno067e04a2020-03-31 12:53:13 +00005121 nslcmop_operation_state = "FAILED"
5122 if db_nsr:
5123 self._write_ns_status(
5124 nsr_id=nsr_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01005125 ns_state=db_nsr[
5126 "nsState"
5127 ], # TODO check if degraded. For the moment use previous status
tierno067e04a2020-03-31 12:53:13 +00005128 current_operation="IDLE",
5129 current_operation_id=None,
5130 # error_description=error_description_nsr,
5131 # error_detail=error_detail,
garciadeblas5697b8b2021-03-24 09:17:02 +01005132 other_update=db_nsr_update,
tierno067e04a2020-03-31 12:53:13 +00005133 )
5134
garciadeblas5697b8b2021-03-24 09:17:02 +01005135 self._write_op_status(
5136 op_id=nslcmop_id,
5137 stage="",
5138 error_message=error_description_nslcmop,
5139 operation_state=nslcmop_operation_state,
5140 other_update=db_nslcmop_update,
5141 )
tierno067e04a2020-03-31 12:53:13 +00005142
tierno59d22d22018-09-25 18:10:19 +02005143 if nslcmop_operation_state:
5144 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01005145 await self.msg.aiowrite(
5146 "ns",
5147 "actioned",
5148 {
5149 "nsr_id": nsr_id,
5150 "nslcmop_id": nslcmop_id,
5151 "operationState": nslcmop_operation_state,
5152 },
5153 loop=self.loop,
5154 )
tierno59d22d22018-09-25 18:10:19 +02005155 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01005156 self.logger.error(
5157 logging_text + "kafka_write notification Exception {}".format(e)
5158 )
tierno59d22d22018-09-25 18:10:19 +02005159 self.logger.debug(logging_text + "Exit")
5160 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_action")
tierno067e04a2020-03-31 12:53:13 +00005161 return nslcmop_operation_state, detailed_status
tierno59d22d22018-09-25 18:10:19 +02005162
5163 async def scale(self, nsr_id, nslcmop_id):
kuused124bfe2019-06-18 12:09:24 +02005164 # Try to lock HA task here
garciadeblas5697b8b2021-03-24 09:17:02 +01005165 task_is_locked_by_me = self.lcm_tasks.lock_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02005166 if not task_is_locked_by_me:
5167 return
5168
tierno59d22d22018-09-25 18:10:19 +02005169 logging_text = "Task ns={} scale={} ".format(nsr_id, nslcmop_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01005170 stage = ["", "", ""]
aktas13251562021-02-12 22:19:10 +03005171 tasks_dict_info = {}
tierno2357f4e2020-10-19 16:38:59 +00005172 # ^ stage, step, VIM progress
tierno59d22d22018-09-25 18:10:19 +02005173 self.logger.debug(logging_text + "Enter")
5174 # get all needed from database
5175 db_nsr = None
tierno59d22d22018-09-25 18:10:19 +02005176 db_nslcmop_update = {}
tiernoe876f672020-02-13 14:34:48 +00005177 db_nsr_update = {}
tierno59d22d22018-09-25 18:10:19 +02005178 exc = None
tierno9ab95942018-10-10 16:44:22 +02005179 # in case of error, indicates what part of scale was failed to put nsr at error status
5180 scale_process = None
tiernod6de1992018-10-11 13:05:52 +02005181 old_operational_status = ""
5182 old_config_status = ""
aktas13251562021-02-12 22:19:10 +03005183 nsi_id = None
tierno59d22d22018-09-25 18:10:19 +02005184 try:
kuused124bfe2019-06-18 12:09:24 +02005185 # wait for any previous tasks in process
tierno3cf81a32019-11-11 17:07:00 +00005186 step = "Waiting for previous operations to terminate"
garciadeblas5697b8b2021-03-24 09:17:02 +01005187 await self.lcm_tasks.waitfor_related_HA("ns", "nslcmops", nslcmop_id)
5188 self._write_ns_status(
5189 nsr_id=nsr_id,
5190 ns_state=None,
5191 current_operation="SCALING",
5192 current_operation_id=nslcmop_id,
5193 )
quilesj4cda56b2019-12-05 10:02:20 +00005194
ikalyvas02d9e7b2019-05-27 18:16:01 +03005195 step = "Getting nslcmop from database"
garciadeblas5697b8b2021-03-24 09:17:02 +01005196 self.logger.debug(
5197 step + " after having waited for previous tasks to be completed"
5198 )
ikalyvas02d9e7b2019-05-27 18:16:01 +03005199 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
bravof922c4172020-11-24 21:21:43 -03005200
ikalyvas02d9e7b2019-05-27 18:16:01 +03005201 step = "Getting nsr from database"
5202 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
ikalyvas02d9e7b2019-05-27 18:16:01 +03005203 old_operational_status = db_nsr["operational-status"]
5204 old_config_status = db_nsr["config-status"]
bravof922c4172020-11-24 21:21:43 -03005205
tierno59d22d22018-09-25 18:10:19 +02005206 step = "Parsing scaling parameters"
5207 db_nsr_update["operational-status"] = "scaling"
5208 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernoe4f7e6c2018-11-27 14:55:30 +00005209 nsr_deployed = db_nsr["_admin"].get("deployed")
calvinosanch9f9c6f22019-11-04 13:37:39 +01005210
garciadeblas5697b8b2021-03-24 09:17:02 +01005211 vnf_index = db_nslcmop["operationParams"]["scaleVnfData"][
5212 "scaleByStepData"
5213 ]["member-vnf-index"]
5214 scaling_group = db_nslcmop["operationParams"]["scaleVnfData"][
5215 "scaleByStepData"
5216 ]["scaling-group-descriptor"]
tierno59d22d22018-09-25 18:10:19 +02005217 scaling_type = db_nslcmop["operationParams"]["scaleVnfData"]["scaleVnfType"]
tierno82974b22018-11-27 21:55:36 +00005218 # for backward compatibility
5219 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
5220 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
5221 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
5222 self.update_db_2("nsrs", nsr_id, db_nsr_update)
5223
tierno59d22d22018-09-25 18:10:19 +02005224 step = "Getting vnfr from database"
garciadeblas5697b8b2021-03-24 09:17:02 +01005225 db_vnfr = self.db.get_one(
5226 "vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id}
5227 )
bravof922c4172020-11-24 21:21:43 -03005228
David Garciac1fe90a2021-03-31 19:12:02 +02005229 vca_id = self.get_vca_id(db_vnfr, db_nsr)
5230
tierno59d22d22018-09-25 18:10:19 +02005231 step = "Getting vnfd from database"
5232 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
ikalyvas02d9e7b2019-05-27 18:16:01 +03005233
aktas13251562021-02-12 22:19:10 +03005234 base_folder = db_vnfd["_admin"]["storage"]
5235
tierno59d22d22018-09-25 18:10:19 +02005236 step = "Getting scaling-group-descriptor"
bravof832f8992020-12-07 12:57:31 -03005237 scaling_descriptor = find_in_list(
garciadeblas5697b8b2021-03-24 09:17:02 +01005238 get_scaling_aspect(db_vnfd),
5239 lambda scale_desc: scale_desc["name"] == scaling_group,
bravof832f8992020-12-07 12:57:31 -03005240 )
5241 if not scaling_descriptor:
garciadeblas5697b8b2021-03-24 09:17:02 +01005242 raise LcmException(
5243 "input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
5244 "at vnfd:scaling-group-descriptor".format(scaling_group)
5245 )
ikalyvas02d9e7b2019-05-27 18:16:01 +03005246
tierno15b1cf12019-08-29 13:21:40 +00005247 step = "Sending scale order to VIM"
bravof922c4172020-11-24 21:21:43 -03005248 # TODO check if ns is in a proper status
tierno59d22d22018-09-25 18:10:19 +02005249 nb_scale_op = 0
5250 if not db_nsr["_admin"].get("scaling-group"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005251 self.update_db_2(
5252 "nsrs",
5253 nsr_id,
5254 {
5255 "_admin.scaling-group": [
5256 {"name": scaling_group, "nb-scale-op": 0}
5257 ]
5258 },
5259 )
tierno59d22d22018-09-25 18:10:19 +02005260 admin_scale_index = 0
5261 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01005262 for admin_scale_index, admin_scale_info in enumerate(
5263 db_nsr["_admin"]["scaling-group"]
5264 ):
tierno59d22d22018-09-25 18:10:19 +02005265 if admin_scale_info["name"] == scaling_group:
5266 nb_scale_op = admin_scale_info.get("nb-scale-op", 0)
5267 break
tierno9ab95942018-10-10 16:44:22 +02005268 else: # not found, set index one plus last element and add new entry with the name
5269 admin_scale_index += 1
garciadeblas5697b8b2021-03-24 09:17:02 +01005270 db_nsr_update[
5271 "_admin.scaling-group.{}.name".format(admin_scale_index)
5272 ] = scaling_group
aktas5f75f102021-03-15 11:26:10 +03005273
5274 vca_scaling_info = []
5275 scaling_info = {"scaling_group_name": scaling_group, "vdu": [], "kdu": []}
tierno59d22d22018-09-25 18:10:19 +02005276 if scaling_type == "SCALE_OUT":
bravof832f8992020-12-07 12:57:31 -03005277 if "aspect-delta-details" not in scaling_descriptor:
5278 raise LcmException(
5279 "Aspect delta details not fount in scaling descriptor {}".format(
5280 scaling_descriptor["name"]
5281 )
5282 )
tierno59d22d22018-09-25 18:10:19 +02005283 # count if max-instance-count is reached
bravof832f8992020-12-07 12:57:31 -03005284 deltas = scaling_descriptor.get("aspect-delta-details")["deltas"]
kuuse8b998e42019-07-30 15:22:16 +02005285
aktas5f75f102021-03-15 11:26:10 +03005286 scaling_info["scaling_direction"] = "OUT"
5287 scaling_info["vdu-create"] = {}
5288 scaling_info["kdu-create"] = {}
bravof832f8992020-12-07 12:57:31 -03005289 for delta in deltas:
aktas5f75f102021-03-15 11:26:10 +03005290 for vdu_delta in delta.get("vdu-delta", {}):
bravof832f8992020-12-07 12:57:31 -03005291 vdud = get_vdu(db_vnfd, vdu_delta["id"])
aktas5f75f102021-03-15 11:26:10 +03005292 # vdu_index also provides the number of instance of the targeted vdu
5293 vdu_count = vdu_index = get_vdur_index(db_vnfr, vdu_delta)
garciadeblas5697b8b2021-03-24 09:17:02 +01005294 cloud_init_text = self._get_vdu_cloud_init_content(
5295 vdud, db_vnfd
5296 )
tierno72ef84f2020-10-06 08:22:07 +00005297 if cloud_init_text:
garciadeblas5697b8b2021-03-24 09:17:02 +01005298 additional_params = (
5299 self._get_vdu_additional_params(db_vnfr, vdud["id"])
5300 or {}
5301 )
bravof832f8992020-12-07 12:57:31 -03005302 cloud_init_list = []
5303
5304 vdu_profile = get_vdu_profile(db_vnfd, vdu_delta["id"])
5305 max_instance_count = 10
5306 if vdu_profile and "max-number-of-instances" in vdu_profile:
garciadeblas5697b8b2021-03-24 09:17:02 +01005307 max_instance_count = vdu_profile.get(
5308 "max-number-of-instances", 10
5309 )
5310
5311 default_instance_num = get_number_of_instances(
5312 db_vnfd, vdud["id"]
5313 )
aktas5f75f102021-03-15 11:26:10 +03005314 instances_number = vdu_delta.get("number-of-instances", 1)
5315 nb_scale_op += instances_number
bravof832f8992020-12-07 12:57:31 -03005316
aktas5f75f102021-03-15 11:26:10 +03005317 new_instance_count = nb_scale_op + default_instance_num
5318 # Control if new count is over max and vdu count is less than max.
5319 # Then assign new instance count
5320 if new_instance_count > max_instance_count > vdu_count:
5321 instances_number = new_instance_count - max_instance_count
5322 else:
5323 instances_number = instances_number
bravof832f8992020-12-07 12:57:31 -03005324
aktas5f75f102021-03-15 11:26:10 +03005325 if new_instance_count > max_instance_count:
bravof832f8992020-12-07 12:57:31 -03005326 raise LcmException(
5327 "reached the limit of {} (max-instance-count) "
5328 "scaling-out operations for the "
garciadeblas5697b8b2021-03-24 09:17:02 +01005329 "scaling-group-descriptor '{}'".format(
5330 nb_scale_op, scaling_group
5331 )
bravof922c4172020-11-24 21:21:43 -03005332 )
bravof832f8992020-12-07 12:57:31 -03005333 for x in range(vdu_delta.get("number-of-instances", 1)):
5334 if cloud_init_text:
5335 # TODO Information of its own ip is not available because db_vnfr is not updated.
5336 additional_params["OSM"] = get_osm_params(
garciadeblas5697b8b2021-03-24 09:17:02 +01005337 db_vnfr, vdu_delta["id"], vdu_index + x
bravof922c4172020-11-24 21:21:43 -03005338 )
bravof832f8992020-12-07 12:57:31 -03005339 cloud_init_list.append(
5340 self._parse_cloud_init(
5341 cloud_init_text,
5342 additional_params,
5343 db_vnfd["id"],
garciadeblas5697b8b2021-03-24 09:17:02 +01005344 vdud["id"],
bravof832f8992020-12-07 12:57:31 -03005345 )
5346 )
aktas5f75f102021-03-15 11:26:10 +03005347 vca_scaling_info.append(
aktas13251562021-02-12 22:19:10 +03005348 {
5349 "osm_vdu_id": vdu_delta["id"],
5350 "member-vnf-index": vnf_index,
5351 "type": "create",
garciadeblas5697b8b2021-03-24 09:17:02 +01005352 "vdu_index": vdu_index + x,
aktas13251562021-02-12 22:19:10 +03005353 }
5354 )
aktas5f75f102021-03-15 11:26:10 +03005355 scaling_info["vdu-create"][vdu_delta["id"]] = instances_number
5356 for kdu_delta in delta.get("kdu-resource-delta", {}):
David Garciab4ebcd02021-10-28 02:00:43 +02005357 kdu_profile = get_kdu_resource_profile(db_vnfd, kdu_delta["id"])
aktas5f75f102021-03-15 11:26:10 +03005358 kdu_name = kdu_profile["kdu-name"]
aktasc41fe832021-11-29 18:41:42 +03005359 resource_name = kdu_profile.get("resource-name", "")
aktas5f75f102021-03-15 11:26:10 +03005360
5361 # Might have different kdus in the same delta
5362 # Should have list for each kdu
5363 if not scaling_info["kdu-create"].get(kdu_name, None):
5364 scaling_info["kdu-create"][kdu_name] = []
5365
5366 kdur = get_kdur(db_vnfr, kdu_name)
5367 if kdur.get("helm-chart"):
5368 k8s_cluster_type = "helm-chart-v3"
5369 self.logger.debug("kdur: {}".format(kdur))
5370 if (
5371 kdur.get("helm-version")
5372 and kdur.get("helm-version") == "v2"
5373 ):
5374 k8s_cluster_type = "helm-chart"
aktas5f75f102021-03-15 11:26:10 +03005375 elif kdur.get("juju-bundle"):
5376 k8s_cluster_type = "juju-bundle"
5377 else:
5378 raise LcmException(
5379 "kdu type for kdu='{}.{}' is neither helm-chart nor "
5380 "juju-bundle. Maybe an old NBI version is running".format(
5381 db_vnfr["member-vnf-index-ref"], kdu_name
5382 )
5383 )
5384
5385 max_instance_count = 10
5386 if kdu_profile and "max-number-of-instances" in kdu_profile:
5387 max_instance_count = kdu_profile.get(
5388 "max-number-of-instances", 10
5389 )
5390
5391 nb_scale_op += kdu_delta.get("number-of-instances", 1)
5392 deployed_kdu, _ = get_deployed_kdu(
5393 nsr_deployed, kdu_name, vnf_index
bravof832f8992020-12-07 12:57:31 -03005394 )
aktas5f75f102021-03-15 11:26:10 +03005395 if deployed_kdu is None:
5396 raise LcmException(
5397 "KDU '{}' for vnf '{}' not deployed".format(
5398 kdu_name, vnf_index
5399 )
5400 )
5401 kdu_instance = deployed_kdu.get("kdu-instance")
5402 instance_num = await self.k8scluster_map[
5403 k8s_cluster_type
aktasc41fe832021-11-29 18:41:42 +03005404 ].get_scale_count(
5405 resource_name,
5406 kdu_instance,
5407 vca_id=vca_id,
5408 cluster_uuid=deployed_kdu.get("k8scluster-uuid"),
5409 kdu_model=deployed_kdu.get("kdu-model"),
5410 )
aktas5f75f102021-03-15 11:26:10 +03005411 kdu_replica_count = instance_num + kdu_delta.get(
garciadeblas5697b8b2021-03-24 09:17:02 +01005412 "number-of-instances", 1
5413 )
ikalyvas02d9e7b2019-05-27 18:16:01 +03005414
aktas5f75f102021-03-15 11:26:10 +03005415 # Control if new count is over max and instance_num is less than max.
5416 # Then assign max instance number to kdu replica count
5417 if kdu_replica_count > max_instance_count > instance_num:
5418 kdu_replica_count = max_instance_count
5419 if kdu_replica_count > max_instance_count:
5420 raise LcmException(
5421 "reached the limit of {} (max-instance-count) "
5422 "scaling-out operations for the "
5423 "scaling-group-descriptor '{}'".format(
5424 instance_num, scaling_group
5425 )
5426 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005427
aktas5f75f102021-03-15 11:26:10 +03005428 for x in range(kdu_delta.get("number-of-instances", 1)):
5429 vca_scaling_info.append(
5430 {
5431 "osm_kdu_id": kdu_name,
5432 "member-vnf-index": vnf_index,
5433 "type": "create",
5434 "kdu_index": instance_num + x - 1,
5435 }
5436 )
5437 scaling_info["kdu-create"][kdu_name].append(
5438 {
5439 "member-vnf-index": vnf_index,
5440 "type": "create",
5441 "k8s-cluster-type": k8s_cluster_type,
5442 "resource-name": resource_name,
5443 "scale": kdu_replica_count,
5444 }
5445 )
5446 elif scaling_type == "SCALE_IN":
bravof832f8992020-12-07 12:57:31 -03005447 deltas = scaling_descriptor.get("aspect-delta-details")["deltas"]
aktas5f75f102021-03-15 11:26:10 +03005448
5449 scaling_info["scaling_direction"] = "IN"
5450 scaling_info["vdu-delete"] = {}
5451 scaling_info["kdu-delete"] = {}
5452
bravof832f8992020-12-07 12:57:31 -03005453 for delta in deltas:
aktas5f75f102021-03-15 11:26:10 +03005454 for vdu_delta in delta.get("vdu-delta", {}):
5455 vdu_count = vdu_index = get_vdur_index(db_vnfr, vdu_delta)
bravof832f8992020-12-07 12:57:31 -03005456 min_instance_count = 0
5457 vdu_profile = get_vdu_profile(db_vnfd, vdu_delta["id"])
5458 if vdu_profile and "min-number-of-instances" in vdu_profile:
5459 min_instance_count = vdu_profile["min-number-of-instances"]
5460
garciadeblas5697b8b2021-03-24 09:17:02 +01005461 default_instance_num = get_number_of_instances(
5462 db_vnfd, vdu_delta["id"]
5463 )
aktas5f75f102021-03-15 11:26:10 +03005464 instance_num = vdu_delta.get("number-of-instances", 1)
5465 nb_scale_op -= instance_num
bravof832f8992020-12-07 12:57:31 -03005466
aktas5f75f102021-03-15 11:26:10 +03005467 new_instance_count = nb_scale_op + default_instance_num
5468
5469 if new_instance_count < min_instance_count < vdu_count:
5470 instances_number = min_instance_count - new_instance_count
5471 else:
5472 instances_number = instance_num
5473
5474 if new_instance_count < min_instance_count:
bravof832f8992020-12-07 12:57:31 -03005475 raise LcmException(
5476 "reached the limit of {} (min-instance-count) scaling-in operations for the "
garciadeblas5697b8b2021-03-24 09:17:02 +01005477 "scaling-group-descriptor '{}'".format(
5478 nb_scale_op, scaling_group
5479 )
bravof832f8992020-12-07 12:57:31 -03005480 )
aktas13251562021-02-12 22:19:10 +03005481 for x in range(vdu_delta.get("number-of-instances", 1)):
aktas5f75f102021-03-15 11:26:10 +03005482 vca_scaling_info.append(
aktas13251562021-02-12 22:19:10 +03005483 {
5484 "osm_vdu_id": vdu_delta["id"],
5485 "member-vnf-index": vnf_index,
5486 "type": "delete",
garciadeblas5697b8b2021-03-24 09:17:02 +01005487 "vdu_index": vdu_index - 1 - x,
aktas13251562021-02-12 22:19:10 +03005488 }
5489 )
aktas5f75f102021-03-15 11:26:10 +03005490 scaling_info["vdu-delete"][vdu_delta["id"]] = instances_number
5491 for kdu_delta in delta.get("kdu-resource-delta", {}):
David Garciab4ebcd02021-10-28 02:00:43 +02005492 kdu_profile = get_kdu_resource_profile(db_vnfd, kdu_delta["id"])
aktas5f75f102021-03-15 11:26:10 +03005493 kdu_name = kdu_profile["kdu-name"]
aktasc41fe832021-11-29 18:41:42 +03005494 resource_name = kdu_profile.get("resource-name", "")
aktas5f75f102021-03-15 11:26:10 +03005495
5496 if not scaling_info["kdu-delete"].get(kdu_name, None):
5497 scaling_info["kdu-delete"][kdu_name] = []
5498
5499 kdur = get_kdur(db_vnfr, kdu_name)
5500 if kdur.get("helm-chart"):
5501 k8s_cluster_type = "helm-chart-v3"
5502 self.logger.debug("kdur: {}".format(kdur))
5503 if (
5504 kdur.get("helm-version")
5505 and kdur.get("helm-version") == "v2"
5506 ):
5507 k8s_cluster_type = "helm-chart"
aktas5f75f102021-03-15 11:26:10 +03005508 elif kdur.get("juju-bundle"):
5509 k8s_cluster_type = "juju-bundle"
5510 else:
5511 raise LcmException(
5512 "kdu type for kdu='{}.{}' is neither helm-chart nor "
5513 "juju-bundle. Maybe an old NBI version is running".format(
5514 db_vnfr["member-vnf-index-ref"], kdur["kdu-name"]
5515 )
5516 )
5517
5518 min_instance_count = 0
5519 if kdu_profile and "min-number-of-instances" in kdu_profile:
5520 min_instance_count = kdu_profile["min-number-of-instances"]
5521
5522 nb_scale_op -= kdu_delta.get("number-of-instances", 1)
5523 deployed_kdu, _ = get_deployed_kdu(
5524 nsr_deployed, kdu_name, vnf_index
5525 )
5526 if deployed_kdu is None:
5527 raise LcmException(
5528 "KDU '{}' for vnf '{}' not deployed".format(
5529 kdu_name, vnf_index
5530 )
5531 )
5532 kdu_instance = deployed_kdu.get("kdu-instance")
5533 instance_num = await self.k8scluster_map[
5534 k8s_cluster_type
aktasc41fe832021-11-29 18:41:42 +03005535 ].get_scale_count(
5536 resource_name,
5537 kdu_instance,
5538 vca_id=vca_id,
5539 cluster_uuid=deployed_kdu.get("k8scluster-uuid"),
5540 kdu_model=deployed_kdu.get("kdu-model"),
5541 )
aktas5f75f102021-03-15 11:26:10 +03005542 kdu_replica_count = instance_num - kdu_delta.get(
garciadeblas5697b8b2021-03-24 09:17:02 +01005543 "number-of-instances", 1
5544 )
tierno59d22d22018-09-25 18:10:19 +02005545
aktas5f75f102021-03-15 11:26:10 +03005546 if kdu_replica_count < min_instance_count < instance_num:
5547 kdu_replica_count = min_instance_count
5548 if kdu_replica_count < min_instance_count:
5549 raise LcmException(
5550 "reached the limit of {} (min-instance-count) scaling-in operations for the "
5551 "scaling-group-descriptor '{}'".format(
5552 instance_num, scaling_group
5553 )
5554 )
5555
5556 for x in range(kdu_delta.get("number-of-instances", 1)):
5557 vca_scaling_info.append(
5558 {
5559 "osm_kdu_id": kdu_name,
5560 "member-vnf-index": vnf_index,
5561 "type": "delete",
5562 "kdu_index": instance_num - x - 1,
5563 }
5564 )
5565 scaling_info["kdu-delete"][kdu_name].append(
5566 {
5567 "member-vnf-index": vnf_index,
5568 "type": "delete",
5569 "k8s-cluster-type": k8s_cluster_type,
5570 "resource-name": resource_name,
5571 "scale": kdu_replica_count,
5572 }
5573 )
5574
tierno59d22d22018-09-25 18:10:19 +02005575 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
aktas5f75f102021-03-15 11:26:10 +03005576 vdu_delete = copy(scaling_info.get("vdu-delete"))
5577 if scaling_info["scaling_direction"] == "IN":
tierno59d22d22018-09-25 18:10:19 +02005578 for vdur in reversed(db_vnfr["vdur"]):
tierno27246d82018-09-27 15:59:09 +02005579 if vdu_delete.get(vdur["vdu-id-ref"]):
5580 vdu_delete[vdur["vdu-id-ref"]] -= 1
aktas5f75f102021-03-15 11:26:10 +03005581 scaling_info["vdu"].append(
garciadeblas5697b8b2021-03-24 09:17:02 +01005582 {
5583 "name": vdur.get("name") or vdur.get("vdu-name"),
5584 "vdu_id": vdur["vdu-id-ref"],
5585 "interface": [],
5586 }
5587 )
tierno59d22d22018-09-25 18:10:19 +02005588 for interface in vdur["interfaces"]:
aktas5f75f102021-03-15 11:26:10 +03005589 scaling_info["vdu"][-1]["interface"].append(
garciadeblas5697b8b2021-03-24 09:17:02 +01005590 {
5591 "name": interface["name"],
5592 "ip_address": interface["ip-address"],
5593 "mac_address": interface.get("mac-address"),
5594 }
5595 )
tierno2357f4e2020-10-19 16:38:59 +00005596 # vdu_delete = vdu_scaling_info.pop("vdu-delete")
tierno59d22d22018-09-25 18:10:19 +02005597
kuuseac3a8882019-10-03 10:48:06 +02005598 # PRE-SCALE BEGIN
tierno59d22d22018-09-25 18:10:19 +02005599 step = "Executing pre-scale vnf-config-primitive"
5600 if scaling_descriptor.get("scaling-config-action"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005601 for scaling_config_action in scaling_descriptor[
5602 "scaling-config-action"
5603 ]:
5604 if (
5605 scaling_config_action.get("trigger") == "pre-scale-in"
5606 and scaling_type == "SCALE_IN"
5607 ) or (
5608 scaling_config_action.get("trigger") == "pre-scale-out"
5609 and scaling_type == "SCALE_OUT"
5610 ):
5611 vnf_config_primitive = scaling_config_action[
5612 "vnf-config-primitive-name-ref"
5613 ]
5614 step = db_nslcmop_update[
5615 "detailed-status"
5616 ] = "executing pre-scale scaling-config-action '{}'".format(
5617 vnf_config_primitive
5618 )
tiernoda964822019-01-14 15:53:47 +00005619
tierno59d22d22018-09-25 18:10:19 +02005620 # look for primitive
garciadeblas5697b8b2021-03-24 09:17:02 +01005621 for config_primitive in (
5622 get_configuration(db_vnfd, db_vnfd["id"]) or {}
5623 ).get("config-primitive", ()):
tierno59d22d22018-09-25 18:10:19 +02005624 if config_primitive["name"] == vnf_config_primitive:
tierno59d22d22018-09-25 18:10:19 +02005625 break
5626 else:
5627 raise LcmException(
5628 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
tiernoda964822019-01-14 15:53:47 +00005629 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
garciadeblas5697b8b2021-03-24 09:17:02 +01005630 "primitive".format(scaling_group, vnf_config_primitive)
5631 )
tiernoda964822019-01-14 15:53:47 +00005632
aktas5f75f102021-03-15 11:26:10 +03005633 vnfr_params = {"VDU_SCALE_INFO": scaling_info}
tiernoda964822019-01-14 15:53:47 +00005634 if db_vnfr.get("additionalParamsForVnf"):
5635 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
quilesj7e13aeb2019-10-08 13:34:55 +02005636
tierno9ab95942018-10-10 16:44:22 +02005637 scale_process = "VCA"
tiernod6de1992018-10-11 13:05:52 +02005638 db_nsr_update["config-status"] = "configuring pre-scaling"
garciadeblas5697b8b2021-03-24 09:17:02 +01005639 primitive_params = self._map_primitive_params(
5640 config_primitive, {}, vnfr_params
5641 )
kuuseac3a8882019-10-03 10:48:06 +02005642
tierno7c4e24c2020-05-13 08:41:35 +00005643 # Pre-scale retry check: Check if this sub-operation has been executed before
kuuseac3a8882019-10-03 10:48:06 +02005644 op_index = self._check_or_add_scale_suboperation(
garciadeblas5697b8b2021-03-24 09:17:02 +01005645 db_nslcmop,
garciadeblas5697b8b2021-03-24 09:17:02 +01005646 vnf_index,
5647 vnf_config_primitive,
5648 primitive_params,
5649 "PRE-SCALE",
5650 )
tierno7c4e24c2020-05-13 08:41:35 +00005651 if op_index == self.SUBOPERATION_STATUS_SKIP:
kuuseac3a8882019-10-03 10:48:06 +02005652 # Skip sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01005653 result = "COMPLETED"
5654 result_detail = "Done"
5655 self.logger.debug(
5656 logging_text
5657 + "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
5658 vnf_config_primitive, result, result_detail
5659 )
5660 )
kuuseac3a8882019-10-03 10:48:06 +02005661 else:
tierno7c4e24c2020-05-13 08:41:35 +00005662 if op_index == self.SUBOPERATION_STATUS_NEW:
kuuseac3a8882019-10-03 10:48:06 +02005663 # New sub-operation: Get index of this sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01005664 op_index = (
5665 len(db_nslcmop.get("_admin", {}).get("operations"))
5666 - 1
5667 )
5668 self.logger.debug(
5669 logging_text
5670 + "vnf_config_primitive={} New sub-operation".format(
5671 vnf_config_primitive
5672 )
5673 )
kuuseac3a8882019-10-03 10:48:06 +02005674 else:
tierno7c4e24c2020-05-13 08:41:35 +00005675 # retry: Get registered params for this existing sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01005676 op = db_nslcmop.get("_admin", {}).get("operations", [])[
5677 op_index
5678 ]
5679 vnf_index = op.get("member_vnf_index")
5680 vnf_config_primitive = op.get("primitive")
5681 primitive_params = op.get("primitive_params")
5682 self.logger.debug(
5683 logging_text
5684 + "vnf_config_primitive={} Sub-operation retry".format(
5685 vnf_config_primitive
5686 )
5687 )
tierno588547c2020-07-01 15:30:20 +00005688 # Execute the primitive, either with new (first-time) or registered (reintent) args
garciadeblas5697b8b2021-03-24 09:17:02 +01005689 ee_descriptor_id = config_primitive.get(
5690 "execution-environment-ref"
5691 )
5692 primitive_name = config_primitive.get(
5693 "execution-environment-primitive", vnf_config_primitive
5694 )
5695 ee_id, vca_type = self._look_for_deployed_vca(
5696 nsr_deployed["VCA"],
5697 member_vnf_index=vnf_index,
5698 vdu_id=None,
5699 vdu_count_index=None,
5700 ee_descriptor_id=ee_descriptor_id,
5701 )
kuuseac3a8882019-10-03 10:48:06 +02005702 result, result_detail = await self._ns_execute_primitive(
garciadeblas5697b8b2021-03-24 09:17:02 +01005703 ee_id,
5704 primitive_name,
David Garciac1fe90a2021-03-31 19:12:02 +02005705 primitive_params,
5706 vca_type=vca_type,
5707 vca_id=vca_id,
5708 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005709 self.logger.debug(
5710 logging_text
5711 + "vnf_config_primitive={} Done with result {} {}".format(
5712 vnf_config_primitive, result, result_detail
5713 )
5714 )
kuuseac3a8882019-10-03 10:48:06 +02005715 # Update operationState = COMPLETED | FAILED
5716 self._update_suboperation_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01005717 db_nslcmop, op_index, result, result_detail
5718 )
kuuseac3a8882019-10-03 10:48:06 +02005719
tierno59d22d22018-09-25 18:10:19 +02005720 if result == "FAILED":
5721 raise LcmException(result_detail)
tiernod6de1992018-10-11 13:05:52 +02005722 db_nsr_update["config-status"] = old_config_status
5723 scale_process = None
kuuseac3a8882019-10-03 10:48:06 +02005724 # PRE-SCALE END
tierno59d22d22018-09-25 18:10:19 +02005725
garciadeblas5697b8b2021-03-24 09:17:02 +01005726 db_nsr_update[
5727 "_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index)
5728 ] = nb_scale_op
5729 db_nsr_update[
5730 "_admin.scaling-group.{}.time".format(admin_scale_index)
5731 ] = time()
tierno2357f4e2020-10-19 16:38:59 +00005732
aktas13251562021-02-12 22:19:10 +03005733 # SCALE-IN VCA - BEGIN
aktas5f75f102021-03-15 11:26:10 +03005734 if vca_scaling_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01005735 step = db_nslcmop_update[
5736 "detailed-status"
5737 ] = "Deleting the execution environments"
aktas13251562021-02-12 22:19:10 +03005738 scale_process = "VCA"
aktas5f75f102021-03-15 11:26:10 +03005739 for vca_info in vca_scaling_info:
5740 if vca_info["type"] == "delete":
5741 member_vnf_index = str(vca_info["member-vnf-index"])
garciadeblas5697b8b2021-03-24 09:17:02 +01005742 self.logger.debug(
aktas5f75f102021-03-15 11:26:10 +03005743 logging_text + "vdu info: {}".format(vca_info)
garciadeblas5697b8b2021-03-24 09:17:02 +01005744 )
aktas5f75f102021-03-15 11:26:10 +03005745 if vca_info.get("osm_vdu_id"):
5746 vdu_id = vca_info["osm_vdu_id"]
5747 vdu_index = int(vca_info["vdu_index"])
5748 stage[
5749 1
5750 ] = "Scaling member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
5751 member_vnf_index, vdu_id, vdu_index
5752 )
5753 else:
5754 vdu_index = 0
5755 kdu_id = vca_info["osm_kdu_id"]
5756 stage[
5757 1
5758 ] = "Scaling member_vnf_index={}, kdu_id={}, vdu_index={} ".format(
5759 member_vnf_index, kdu_id, vdu_index
5760 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005761 stage[2] = step = "Scaling in VCA"
5762 self._write_op_status(op_id=nslcmop_id, stage=stage)
aktas13251562021-02-12 22:19:10 +03005763 vca_update = db_nsr["_admin"]["deployed"]["VCA"]
5764 config_update = db_nsr["configurationStatus"]
5765 for vca_index, vca in enumerate(vca_update):
garciadeblas5697b8b2021-03-24 09:17:02 +01005766 if (
5767 (vca or vca.get("ee_id"))
5768 and vca["member-vnf-index"] == member_vnf_index
5769 and vca["vdu_count_index"] == vdu_index
5770 ):
aktas13251562021-02-12 22:19:10 +03005771 if vca.get("vdu_id"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005772 config_descriptor = get_configuration(
5773 db_vnfd, vca.get("vdu_id")
5774 )
aktas13251562021-02-12 22:19:10 +03005775 elif vca.get("kdu_name"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005776 config_descriptor = get_configuration(
5777 db_vnfd, vca.get("kdu_name")
5778 )
aktas13251562021-02-12 22:19:10 +03005779 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01005780 config_descriptor = get_configuration(
5781 db_vnfd, db_vnfd["id"]
5782 )
5783 operation_params = (
5784 db_nslcmop.get("operationParams") or {}
5785 )
5786 exec_terminate_primitives = not operation_params.get(
5787 "skip_terminate_primitives"
5788 ) and vca.get("needed_terminate")
David Garciac1fe90a2021-03-31 19:12:02 +02005789 task = asyncio.ensure_future(
5790 asyncio.wait_for(
5791 self.destroy_N2VC(
5792 logging_text,
5793 db_nslcmop,
5794 vca,
5795 config_descriptor,
5796 vca_index,
5797 destroy_ee=True,
5798 exec_primitives=exec_terminate_primitives,
5799 scaling_in=True,
5800 vca_id=vca_id,
5801 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01005802 timeout=self.timeout_charm_delete,
David Garciac1fe90a2021-03-31 19:12:02 +02005803 )
5804 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005805 tasks_dict_info[task] = "Terminating VCA {}".format(
5806 vca.get("ee_id")
5807 )
aktas13251562021-02-12 22:19:10 +03005808 del vca_update[vca_index]
5809 del config_update[vca_index]
5810 # wait for pending tasks of terminate primitives
5811 if tasks_dict_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01005812 self.logger.debug(
5813 logging_text
5814 + "Waiting for tasks {}".format(
5815 list(tasks_dict_info.keys())
5816 )
5817 )
5818 error_list = await self._wait_for_tasks(
5819 logging_text,
5820 tasks_dict_info,
5821 min(
5822 self.timeout_charm_delete, self.timeout_ns_terminate
5823 ),
5824 stage,
5825 nslcmop_id,
5826 )
aktas13251562021-02-12 22:19:10 +03005827 tasks_dict_info.clear()
5828 if error_list:
5829 raise LcmException("; ".join(error_list))
5830
5831 db_vca_and_config_update = {
5832 "_admin.deployed.VCA": vca_update,
garciadeblas5697b8b2021-03-24 09:17:02 +01005833 "configurationStatus": config_update,
aktas13251562021-02-12 22:19:10 +03005834 }
garciadeblas5697b8b2021-03-24 09:17:02 +01005835 self.update_db_2(
5836 "nsrs", db_nsr["_id"], db_vca_and_config_update
5837 )
aktas13251562021-02-12 22:19:10 +03005838 scale_process = None
5839 # SCALE-IN VCA - END
5840
kuuseac3a8882019-10-03 10:48:06 +02005841 # SCALE RO - BEGIN
aktas5f75f102021-03-15 11:26:10 +03005842 if scaling_info.get("vdu-create") or scaling_info.get("vdu-delete"):
tierno9ab95942018-10-10 16:44:22 +02005843 scale_process = "RO"
tierno2357f4e2020-10-19 16:38:59 +00005844 if self.ro_config.get("ng"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005845 await self._scale_ng_ro(
aktas5f75f102021-03-15 11:26:10 +03005846 logging_text, db_nsr, db_nslcmop, db_vnfr, scaling_info, stage
garciadeblas5697b8b2021-03-24 09:17:02 +01005847 )
aktas5f75f102021-03-15 11:26:10 +03005848 scaling_info.pop("vdu-create", None)
5849 scaling_info.pop("vdu-delete", None)
tierno59d22d22018-09-25 18:10:19 +02005850
tierno9ab95942018-10-10 16:44:22 +02005851 scale_process = None
aktas13251562021-02-12 22:19:10 +03005852 # SCALE RO - END
5853
aktas5f75f102021-03-15 11:26:10 +03005854 # SCALE KDU - BEGIN
5855 if scaling_info.get("kdu-create") or scaling_info.get("kdu-delete"):
5856 scale_process = "KDU"
5857 await self._scale_kdu(
5858 logging_text, nsr_id, nsr_deployed, db_vnfd, vca_id, scaling_info
5859 )
5860 scaling_info.pop("kdu-create", None)
5861 scaling_info.pop("kdu-delete", None)
5862
5863 scale_process = None
5864 # SCALE KDU - END
5865
5866 if db_nsr_update:
5867 self.update_db_2("nsrs", nsr_id, db_nsr_update)
5868
aktas13251562021-02-12 22:19:10 +03005869 # SCALE-UP VCA - BEGIN
aktas5f75f102021-03-15 11:26:10 +03005870 if vca_scaling_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01005871 step = db_nslcmop_update[
5872 "detailed-status"
5873 ] = "Creating new execution environments"
aktas13251562021-02-12 22:19:10 +03005874 scale_process = "VCA"
aktas5f75f102021-03-15 11:26:10 +03005875 for vca_info in vca_scaling_info:
5876 if vca_info["type"] == "create":
5877 member_vnf_index = str(vca_info["member-vnf-index"])
garciadeblas5697b8b2021-03-24 09:17:02 +01005878 self.logger.debug(
aktas5f75f102021-03-15 11:26:10 +03005879 logging_text + "vdu info: {}".format(vca_info)
garciadeblas5697b8b2021-03-24 09:17:02 +01005880 )
aktas13251562021-02-12 22:19:10 +03005881 vnfd_id = db_vnfr["vnfd-ref"]
aktas5f75f102021-03-15 11:26:10 +03005882 if vca_info.get("osm_vdu_id"):
5883 vdu_index = int(vca_info["vdu_index"])
5884 deploy_params = {"OSM": get_osm_params(db_vnfr)}
5885 if db_vnfr.get("additionalParamsForVnf"):
5886 deploy_params.update(
5887 parse_yaml_strings(
5888 db_vnfr["additionalParamsForVnf"].copy()
5889 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005890 )
aktas5f75f102021-03-15 11:26:10 +03005891 descriptor_config = get_configuration(
5892 db_vnfd, db_vnfd["id"]
garciadeblas5697b8b2021-03-24 09:17:02 +01005893 )
aktas5f75f102021-03-15 11:26:10 +03005894 if descriptor_config:
5895 vdu_id = None
5896 vdu_name = None
5897 kdu_name = None
5898 self._deploy_n2vc(
5899 logging_text=logging_text
5900 + "member_vnf_index={} ".format(member_vnf_index),
5901 db_nsr=db_nsr,
5902 db_vnfr=db_vnfr,
5903 nslcmop_id=nslcmop_id,
5904 nsr_id=nsr_id,
5905 nsi_id=nsi_id,
5906 vnfd_id=vnfd_id,
5907 vdu_id=vdu_id,
5908 kdu_name=kdu_name,
5909 member_vnf_index=member_vnf_index,
5910 vdu_index=vdu_index,
5911 vdu_name=vdu_name,
5912 deploy_params=deploy_params,
5913 descriptor_config=descriptor_config,
5914 base_folder=base_folder,
5915 task_instantiation_info=tasks_dict_info,
5916 stage=stage,
5917 )
5918 vdu_id = vca_info["osm_vdu_id"]
5919 vdur = find_in_list(
5920 db_vnfr["vdur"], lambda vdu: vdu["vdu-id-ref"] == vdu_id
aktas13251562021-02-12 22:19:10 +03005921 )
aktas5f75f102021-03-15 11:26:10 +03005922 descriptor_config = get_configuration(db_vnfd, vdu_id)
5923 if vdur.get("additionalParams"):
5924 deploy_params_vdu = parse_yaml_strings(
5925 vdur["additionalParams"]
5926 )
5927 else:
5928 deploy_params_vdu = deploy_params
5929 deploy_params_vdu["OSM"] = get_osm_params(
5930 db_vnfr, vdu_id, vdu_count_index=vdu_index
garciadeblas5697b8b2021-03-24 09:17:02 +01005931 )
aktas5f75f102021-03-15 11:26:10 +03005932 if descriptor_config:
5933 vdu_name = None
5934 kdu_name = None
5935 stage[
5936 1
5937 ] = "Scaling member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
garciadeblas5697b8b2021-03-24 09:17:02 +01005938 member_vnf_index, vdu_id, vdu_index
aktas5f75f102021-03-15 11:26:10 +03005939 )
5940 stage[2] = step = "Scaling out VCA"
5941 self._write_op_status(op_id=nslcmop_id, stage=stage)
5942 self._deploy_n2vc(
5943 logging_text=logging_text
5944 + "member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
5945 member_vnf_index, vdu_id, vdu_index
5946 ),
5947 db_nsr=db_nsr,
5948 db_vnfr=db_vnfr,
5949 nslcmop_id=nslcmop_id,
5950 nsr_id=nsr_id,
5951 nsi_id=nsi_id,
5952 vnfd_id=vnfd_id,
5953 vdu_id=vdu_id,
5954 kdu_name=kdu_name,
5955 member_vnf_index=member_vnf_index,
5956 vdu_index=vdu_index,
5957 vdu_name=vdu_name,
5958 deploy_params=deploy_params_vdu,
5959 descriptor_config=descriptor_config,
5960 base_folder=base_folder,
5961 task_instantiation_info=tasks_dict_info,
5962 stage=stage,
5963 )
5964 else:
5965 kdu_name = vca_info["osm_kdu_id"]
5966 descriptor_config = get_configuration(db_vnfd, kdu_name)
5967 if descriptor_config:
5968 vdu_id = None
5969 kdu_index = int(vca_info["kdu_index"])
5970 vdu_name = None
5971 kdur = next(
5972 x
5973 for x in db_vnfr["kdur"]
5974 if x["kdu-name"] == kdu_name
5975 )
5976 deploy_params_kdu = {"OSM": get_osm_params(db_vnfr)}
5977 if kdur.get("additionalParams"):
5978 deploy_params_kdu = parse_yaml_strings(
5979 kdur["additionalParams"]
5980 )
5981
5982 self._deploy_n2vc(
5983 logging_text=logging_text,
5984 db_nsr=db_nsr,
5985 db_vnfr=db_vnfr,
5986 nslcmop_id=nslcmop_id,
5987 nsr_id=nsr_id,
5988 nsi_id=nsi_id,
5989 vnfd_id=vnfd_id,
5990 vdu_id=vdu_id,
5991 kdu_name=kdu_name,
5992 member_vnf_index=member_vnf_index,
5993 vdu_index=kdu_index,
5994 vdu_name=vdu_name,
5995 deploy_params=deploy_params_kdu,
5996 descriptor_config=descriptor_config,
5997 base_folder=base_folder,
5998 task_instantiation_info=tasks_dict_info,
5999 stage=stage,
6000 )
aktas13251562021-02-12 22:19:10 +03006001 # SCALE-UP VCA - END
6002 scale_process = None
tierno59d22d22018-09-25 18:10:19 +02006003
kuuseac3a8882019-10-03 10:48:06 +02006004 # POST-SCALE BEGIN
tierno59d22d22018-09-25 18:10:19 +02006005 # execute primitive service POST-SCALING
6006 step = "Executing post-scale vnf-config-primitive"
6007 if scaling_descriptor.get("scaling-config-action"):
garciadeblas5697b8b2021-03-24 09:17:02 +01006008 for scaling_config_action in scaling_descriptor[
6009 "scaling-config-action"
6010 ]:
6011 if (
6012 scaling_config_action.get("trigger") == "post-scale-in"
6013 and scaling_type == "SCALE_IN"
6014 ) or (
6015 scaling_config_action.get("trigger") == "post-scale-out"
6016 and scaling_type == "SCALE_OUT"
6017 ):
6018 vnf_config_primitive = scaling_config_action[
6019 "vnf-config-primitive-name-ref"
6020 ]
6021 step = db_nslcmop_update[
6022 "detailed-status"
6023 ] = "executing post-scale scaling-config-action '{}'".format(
6024 vnf_config_primitive
6025 )
tiernoda964822019-01-14 15:53:47 +00006026
aktas5f75f102021-03-15 11:26:10 +03006027 vnfr_params = {"VDU_SCALE_INFO": scaling_info}
tiernoda964822019-01-14 15:53:47 +00006028 if db_vnfr.get("additionalParamsForVnf"):
6029 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
6030
tierno59d22d22018-09-25 18:10:19 +02006031 # look for primitive
bravof9a256db2021-02-22 18:02:07 -03006032 for config_primitive in (
6033 get_configuration(db_vnfd, db_vnfd["id"]) or {}
6034 ).get("config-primitive", ()):
tierno59d22d22018-09-25 18:10:19 +02006035 if config_primitive["name"] == vnf_config_primitive:
tierno59d22d22018-09-25 18:10:19 +02006036 break
6037 else:
tiernoa278b842020-07-08 15:33:55 +00006038 raise LcmException(
6039 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-"
6040 "action[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:"
garciadeblas5697b8b2021-03-24 09:17:02 +01006041 "config-primitive".format(
6042 scaling_group, vnf_config_primitive
6043 )
6044 )
tierno9ab95942018-10-10 16:44:22 +02006045 scale_process = "VCA"
tiernod6de1992018-10-11 13:05:52 +02006046 db_nsr_update["config-status"] = "configuring post-scaling"
garciadeblas5697b8b2021-03-24 09:17:02 +01006047 primitive_params = self._map_primitive_params(
6048 config_primitive, {}, vnfr_params
6049 )
tiernod6de1992018-10-11 13:05:52 +02006050
tierno7c4e24c2020-05-13 08:41:35 +00006051 # Post-scale retry check: Check if this sub-operation has been executed before
kuuseac3a8882019-10-03 10:48:06 +02006052 op_index = self._check_or_add_scale_suboperation(
garciadeblas5697b8b2021-03-24 09:17:02 +01006053 db_nslcmop,
garciadeblas5697b8b2021-03-24 09:17:02 +01006054 vnf_index,
6055 vnf_config_primitive,
6056 primitive_params,
6057 "POST-SCALE",
6058 )
quilesj4cda56b2019-12-05 10:02:20 +00006059 if op_index == self.SUBOPERATION_STATUS_SKIP:
kuuseac3a8882019-10-03 10:48:06 +02006060 # Skip sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01006061 result = "COMPLETED"
6062 result_detail = "Done"
6063 self.logger.debug(
6064 logging_text
6065 + "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
6066 vnf_config_primitive, result, result_detail
6067 )
6068 )
kuuseac3a8882019-10-03 10:48:06 +02006069 else:
quilesj4cda56b2019-12-05 10:02:20 +00006070 if op_index == self.SUBOPERATION_STATUS_NEW:
kuuseac3a8882019-10-03 10:48:06 +02006071 # New sub-operation: Get index of this sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01006072 op_index = (
6073 len(db_nslcmop.get("_admin", {}).get("operations"))
6074 - 1
6075 )
6076 self.logger.debug(
6077 logging_text
6078 + "vnf_config_primitive={} New sub-operation".format(
6079 vnf_config_primitive
6080 )
6081 )
kuuseac3a8882019-10-03 10:48:06 +02006082 else:
tierno7c4e24c2020-05-13 08:41:35 +00006083 # retry: Get registered params for this existing sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01006084 op = db_nslcmop.get("_admin", {}).get("operations", [])[
6085 op_index
6086 ]
6087 vnf_index = op.get("member_vnf_index")
6088 vnf_config_primitive = op.get("primitive")
6089 primitive_params = op.get("primitive_params")
6090 self.logger.debug(
6091 logging_text
6092 + "vnf_config_primitive={} Sub-operation retry".format(
6093 vnf_config_primitive
6094 )
6095 )
tierno588547c2020-07-01 15:30:20 +00006096 # Execute the primitive, either with new (first-time) or registered (reintent) args
garciadeblas5697b8b2021-03-24 09:17:02 +01006097 ee_descriptor_id = config_primitive.get(
6098 "execution-environment-ref"
6099 )
6100 primitive_name = config_primitive.get(
6101 "execution-environment-primitive", vnf_config_primitive
6102 )
6103 ee_id, vca_type = self._look_for_deployed_vca(
6104 nsr_deployed["VCA"],
6105 member_vnf_index=vnf_index,
6106 vdu_id=None,
6107 vdu_count_index=None,
6108 ee_descriptor_id=ee_descriptor_id,
6109 )
kuuseac3a8882019-10-03 10:48:06 +02006110 result, result_detail = await self._ns_execute_primitive(
David Garciac1fe90a2021-03-31 19:12:02 +02006111 ee_id,
6112 primitive_name,
6113 primitive_params,
6114 vca_type=vca_type,
6115 vca_id=vca_id,
6116 )
garciadeblas5697b8b2021-03-24 09:17:02 +01006117 self.logger.debug(
6118 logging_text
6119 + "vnf_config_primitive={} Done with result {} {}".format(
6120 vnf_config_primitive, result, result_detail
6121 )
6122 )
kuuseac3a8882019-10-03 10:48:06 +02006123 # Update operationState = COMPLETED | FAILED
6124 self._update_suboperation_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01006125 db_nslcmop, op_index, result, result_detail
6126 )
kuuseac3a8882019-10-03 10:48:06 +02006127
tierno59d22d22018-09-25 18:10:19 +02006128 if result == "FAILED":
6129 raise LcmException(result_detail)
tiernod6de1992018-10-11 13:05:52 +02006130 db_nsr_update["config-status"] = old_config_status
6131 scale_process = None
kuuseac3a8882019-10-03 10:48:06 +02006132 # POST-SCALE END
tierno59d22d22018-09-25 18:10:19 +02006133
garciadeblas5697b8b2021-03-24 09:17:02 +01006134 db_nsr_update[
6135 "detailed-status"
6136 ] = "" # "scaled {} {}".format(scaling_group, scaling_type)
6137 db_nsr_update["operational-status"] = (
6138 "running"
6139 if old_operational_status == "failed"
ikalyvas02d9e7b2019-05-27 18:16:01 +03006140 else old_operational_status
garciadeblas5697b8b2021-03-24 09:17:02 +01006141 )
tiernod6de1992018-10-11 13:05:52 +02006142 db_nsr_update["config-status"] = old_config_status
tierno59d22d22018-09-25 18:10:19 +02006143 return
garciadeblas5697b8b2021-03-24 09:17:02 +01006144 except (
6145 ROclient.ROClientException,
6146 DbException,
6147 LcmException,
6148 NgRoException,
6149 ) as e:
tierno59d22d22018-09-25 18:10:19 +02006150 self.logger.error(logging_text + "Exit Exception {}".format(e))
6151 exc = e
6152 except asyncio.CancelledError:
garciadeblas5697b8b2021-03-24 09:17:02 +01006153 self.logger.error(
6154 logging_text + "Cancelled Exception while '{}'".format(step)
6155 )
tierno59d22d22018-09-25 18:10:19 +02006156 exc = "Operation was cancelled"
6157 except Exception as e:
6158 exc = traceback.format_exc()
garciadeblas5697b8b2021-03-24 09:17:02 +01006159 self.logger.critical(
6160 logging_text + "Exit Exception {} {}".format(type(e).__name__, e),
6161 exc_info=True,
6162 )
tierno59d22d22018-09-25 18:10:19 +02006163 finally:
garciadeblas5697b8b2021-03-24 09:17:02 +01006164 self._write_ns_status(
6165 nsr_id=nsr_id,
6166 ns_state=None,
6167 current_operation="IDLE",
6168 current_operation_id=None,
6169 )
aktas13251562021-02-12 22:19:10 +03006170 if tasks_dict_info:
6171 stage[1] = "Waiting for instantiate pending tasks."
6172 self.logger.debug(logging_text + stage[1])
garciadeblas5697b8b2021-03-24 09:17:02 +01006173 exc = await self._wait_for_tasks(
6174 logging_text,
6175 tasks_dict_info,
6176 self.timeout_ns_deploy,
6177 stage,
6178 nslcmop_id,
6179 nsr_id=nsr_id,
6180 )
tierno59d22d22018-09-25 18:10:19 +02006181 if exc:
garciadeblas5697b8b2021-03-24 09:17:02 +01006182 db_nslcmop_update[
6183 "detailed-status"
6184 ] = error_description_nslcmop = "FAILED {}: {}".format(step, exc)
tiernoa17d4f42020-04-28 09:59:23 +00006185 nslcmop_operation_state = "FAILED"
tierno59d22d22018-09-25 18:10:19 +02006186 if db_nsr:
tiernod6de1992018-10-11 13:05:52 +02006187 db_nsr_update["operational-status"] = old_operational_status
6188 db_nsr_update["config-status"] = old_config_status
6189 db_nsr_update["detailed-status"] = ""
6190 if scale_process:
6191 if "VCA" in scale_process:
6192 db_nsr_update["config-status"] = "failed"
6193 if "RO" in scale_process:
6194 db_nsr_update["operational-status"] = "failed"
garciadeblas5697b8b2021-03-24 09:17:02 +01006195 db_nsr_update[
6196 "detailed-status"
6197 ] = "FAILED scaling nslcmop={} {}: {}".format(
6198 nslcmop_id, step, exc
6199 )
tiernoa17d4f42020-04-28 09:59:23 +00006200 else:
6201 error_description_nslcmop = None
6202 nslcmop_operation_state = "COMPLETED"
6203 db_nslcmop_update["detailed-status"] = "Done"
quilesj4cda56b2019-12-05 10:02:20 +00006204
garciadeblas5697b8b2021-03-24 09:17:02 +01006205 self._write_op_status(
6206 op_id=nslcmop_id,
6207 stage="",
6208 error_message=error_description_nslcmop,
6209 operation_state=nslcmop_operation_state,
6210 other_update=db_nslcmop_update,
6211 )
tiernoa17d4f42020-04-28 09:59:23 +00006212 if db_nsr:
garciadeblas5697b8b2021-03-24 09:17:02 +01006213 self._write_ns_status(
6214 nsr_id=nsr_id,
6215 ns_state=None,
6216 current_operation="IDLE",
6217 current_operation_id=None,
6218 other_update=db_nsr_update,
6219 )
tiernoa17d4f42020-04-28 09:59:23 +00006220
tierno59d22d22018-09-25 18:10:19 +02006221 if nslcmop_operation_state:
6222 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01006223 msg = {
6224 "nsr_id": nsr_id,
6225 "nslcmop_id": nslcmop_id,
6226 "operationState": nslcmop_operation_state,
6227 }
bravof922c4172020-11-24 21:21:43 -03006228 await self.msg.aiowrite("ns", "scaled", msg, loop=self.loop)
tierno59d22d22018-09-25 18:10:19 +02006229 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01006230 self.logger.error(
6231 logging_text + "kafka_write notification Exception {}".format(e)
6232 )
tierno59d22d22018-09-25 18:10:19 +02006233 self.logger.debug(logging_text + "Exit")
6234 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_scale")
tiernob996d942020-07-03 14:52:28 +00006235
aktas5f75f102021-03-15 11:26:10 +03006236 async def _scale_kdu(
6237 self, logging_text, nsr_id, nsr_deployed, db_vnfd, vca_id, scaling_info
6238 ):
6239 _scaling_info = scaling_info.get("kdu-create") or scaling_info.get("kdu-delete")
6240 for kdu_name in _scaling_info:
6241 for kdu_scaling_info in _scaling_info[kdu_name]:
6242 deployed_kdu, index = get_deployed_kdu(
6243 nsr_deployed, kdu_name, kdu_scaling_info["member-vnf-index"]
6244 )
6245 cluster_uuid = deployed_kdu["k8scluster-uuid"]
6246 kdu_instance = deployed_kdu["kdu-instance"]
aktasc41fe832021-11-29 18:41:42 +03006247 kdu_model = deployed_kdu.get("kdu-model")
aktas5f75f102021-03-15 11:26:10 +03006248 scale = int(kdu_scaling_info["scale"])
6249 k8s_cluster_type = kdu_scaling_info["k8s-cluster-type"]
6250
6251 db_dict = {
6252 "collection": "nsrs",
6253 "filter": {"_id": nsr_id},
6254 "path": "_admin.deployed.K8s.{}".format(index),
6255 }
6256
6257 step = "scaling application {}".format(
6258 kdu_scaling_info["resource-name"]
6259 )
6260 self.logger.debug(logging_text + step)
6261
6262 if kdu_scaling_info["type"] == "delete":
6263 kdu_config = get_configuration(db_vnfd, kdu_name)
6264 if (
6265 kdu_config
6266 and kdu_config.get("terminate-config-primitive")
6267 and get_juju_ee_ref(db_vnfd, kdu_name) is None
6268 ):
6269 terminate_config_primitive_list = kdu_config.get(
6270 "terminate-config-primitive"
6271 )
6272 terminate_config_primitive_list.sort(
6273 key=lambda val: int(val["seq"])
6274 )
6275
6276 for (
6277 terminate_config_primitive
6278 ) in terminate_config_primitive_list:
6279 primitive_params_ = self._map_primitive_params(
6280 terminate_config_primitive, {}, {}
6281 )
6282 step = "execute terminate config primitive"
6283 self.logger.debug(logging_text + step)
6284 await asyncio.wait_for(
6285 self.k8scluster_map[k8s_cluster_type].exec_primitive(
6286 cluster_uuid=cluster_uuid,
6287 kdu_instance=kdu_instance,
6288 primitive_name=terminate_config_primitive["name"],
6289 params=primitive_params_,
6290 db_dict=db_dict,
6291 vca_id=vca_id,
6292 ),
6293 timeout=600,
6294 )
6295
6296 await asyncio.wait_for(
6297 self.k8scluster_map[k8s_cluster_type].scale(
6298 kdu_instance,
6299 scale,
6300 kdu_scaling_info["resource-name"],
6301 vca_id=vca_id,
aktasc41fe832021-11-29 18:41:42 +03006302 cluster_uuid=cluster_uuid,
6303 kdu_model=kdu_model,
6304 atomic=True,
6305 db_dict=db_dict,
aktas5f75f102021-03-15 11:26:10 +03006306 ),
6307 timeout=self.timeout_vca_on_error,
6308 )
6309
6310 if kdu_scaling_info["type"] == "create":
6311 kdu_config = get_configuration(db_vnfd, kdu_name)
6312 if (
6313 kdu_config
6314 and kdu_config.get("initial-config-primitive")
6315 and get_juju_ee_ref(db_vnfd, kdu_name) is None
6316 ):
6317 initial_config_primitive_list = kdu_config.get(
6318 "initial-config-primitive"
6319 )
6320 initial_config_primitive_list.sort(
6321 key=lambda val: int(val["seq"])
6322 )
6323
6324 for initial_config_primitive in initial_config_primitive_list:
6325 primitive_params_ = self._map_primitive_params(
6326 initial_config_primitive, {}, {}
6327 )
6328 step = "execute initial config primitive"
6329 self.logger.debug(logging_text + step)
6330 await asyncio.wait_for(
6331 self.k8scluster_map[k8s_cluster_type].exec_primitive(
6332 cluster_uuid=cluster_uuid,
6333 kdu_instance=kdu_instance,
6334 primitive_name=initial_config_primitive["name"],
6335 params=primitive_params_,
6336 db_dict=db_dict,
6337 vca_id=vca_id,
6338 ),
6339 timeout=600,
6340 )
6341
garciadeblas5697b8b2021-03-24 09:17:02 +01006342 async def _scale_ng_ro(
6343 self, logging_text, db_nsr, db_nslcmop, db_vnfr, vdu_scaling_info, stage
6344 ):
tierno2357f4e2020-10-19 16:38:59 +00006345 nsr_id = db_nslcmop["nsInstanceId"]
6346 db_nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
6347 db_vnfrs = {}
6348
6349 # read from db: vnfd's for every vnf
bravof832f8992020-12-07 12:57:31 -03006350 db_vnfds = []
tierno2357f4e2020-10-19 16:38:59 +00006351
6352 # for each vnf in ns, read vnfd
6353 for vnfr in self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id}):
6354 db_vnfrs[vnfr["member-vnf-index-ref"]] = vnfr
6355 vnfd_id = vnfr["vnfd-id"] # vnfd uuid for this vnf
tierno2357f4e2020-10-19 16:38:59 +00006356 # if we haven't this vnfd, read it from db
bravof832f8992020-12-07 12:57:31 -03006357 if not find_in_list(db_vnfds, lambda a_vnfd: a_vnfd["id"] == vnfd_id):
tierno2357f4e2020-10-19 16:38:59 +00006358 # read from db
6359 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
bravof832f8992020-12-07 12:57:31 -03006360 db_vnfds.append(vnfd)
tierno2357f4e2020-10-19 16:38:59 +00006361 n2vc_key = self.n2vc.get_public_key()
6362 n2vc_key_list = [n2vc_key]
garciadeblas5697b8b2021-03-24 09:17:02 +01006363 self.scale_vnfr(
6364 db_vnfr,
6365 vdu_scaling_info.get("vdu-create"),
6366 vdu_scaling_info.get("vdu-delete"),
6367 mark_delete=True,
6368 )
tierno2357f4e2020-10-19 16:38:59 +00006369 # db_vnfr has been updated, update db_vnfrs to use it
6370 db_vnfrs[db_vnfr["member-vnf-index-ref"]] = db_vnfr
garciadeblas5697b8b2021-03-24 09:17:02 +01006371 await self._instantiate_ng_ro(
6372 logging_text,
6373 nsr_id,
6374 db_nsd,
6375 db_nsr,
6376 db_nslcmop,
6377 db_vnfrs,
6378 db_vnfds,
6379 n2vc_key_list,
6380 stage=stage,
6381 start_deploy=time(),
6382 timeout_ns_deploy=self.timeout_ns_deploy,
6383 )
tierno2357f4e2020-10-19 16:38:59 +00006384 if vdu_scaling_info.get("vdu-delete"):
garciadeblas5697b8b2021-03-24 09:17:02 +01006385 self.scale_vnfr(
6386 db_vnfr, None, vdu_scaling_info["vdu-delete"], mark_delete=False
6387 )
tierno2357f4e2020-10-19 16:38:59 +00006388
bravof73bac502021-05-11 07:38:47 -04006389 async def extract_prometheus_scrape_jobs(
6390 self,
6391 ee_id,
6392 artifact_path,
6393 ee_config_descriptor,
6394 vnfr_id,
6395 nsr_id,
6396 target_ip
garciadeblas5697b8b2021-03-24 09:17:02 +01006397 ):
tiernob996d942020-07-03 14:52:28 +00006398 # look if exist a file called 'prometheus*.j2' and
6399 artifact_content = self.fs.dir_ls(artifact_path)
garciadeblas5697b8b2021-03-24 09:17:02 +01006400 job_file = next(
6401 (
6402 f
6403 for f in artifact_content
6404 if f.startswith("prometheus") and f.endswith(".j2")
6405 ),
6406 None,
6407 )
tiernob996d942020-07-03 14:52:28 +00006408 if not job_file:
6409 return
6410 with self.fs.file_open((artifact_path, job_file), "r") as f:
6411 job_data = f.read()
6412
6413 # TODO get_service
garciadeblas5697b8b2021-03-24 09:17:02 +01006414 _, _, service = ee_id.partition(".") # remove prefix "namespace."
tiernob996d942020-07-03 14:52:28 +00006415 host_name = "{}-{}".format(service, ee_config_descriptor["metric-service"])
6416 host_port = "80"
6417 vnfr_id = vnfr_id.replace("-", "")
6418 variables = {
6419 "JOB_NAME": vnfr_id,
6420 "TARGET_IP": target_ip,
6421 "EXPORTER_POD_IP": host_name,
6422 "EXPORTER_POD_PORT": host_port,
6423 }
bravof73bac502021-05-11 07:38:47 -04006424 job_list = parse_job(job_data, variables)
tiernob996d942020-07-03 14:52:28 +00006425 # ensure job_name is using the vnfr_id. Adding the metadata nsr_id
6426 for job in job_list:
garciadeblas5697b8b2021-03-24 09:17:02 +01006427 if (
6428 not isinstance(job.get("job_name"), str)
6429 or vnfr_id not in job["job_name"]
6430 ):
tiernob996d942020-07-03 14:52:28 +00006431 job["job_name"] = vnfr_id + "_" + str(randint(1, 10000))
6432 job["nsr_id"] = nsr_id
bravof73bac502021-05-11 07:38:47 -04006433 job["vnfr_id"] = vnfr_id
6434 return job_list
David Garciaaae391f2020-11-09 11:12:54 +01006435
6436 def get_vca_cloud_and_credentials(self, vim_account_id: str) -> (str, str):
6437 """
6438 Get VCA Cloud and VCA Cloud Credentials for the VIM account
6439
6440 :param: vim_account_id: VIM Account ID
6441
6442 :return: (cloud_name, cloud_credential)
6443 """
bravof922c4172020-11-24 21:21:43 -03006444 config = VimAccountDB.get_vim_account_with_id(vim_account_id).get("config", {})
David Garciaaae391f2020-11-09 11:12:54 +01006445 return config.get("vca_cloud"), config.get("vca_cloud_credential")
6446
6447 def get_vca_k8s_cloud_and_credentials(self, vim_account_id: str) -> (str, str):
6448 """
6449 Get VCA K8s Cloud and VCA K8s Cloud Credentials for the VIM account
6450
6451 :param: vim_account_id: VIM Account ID
6452
6453 :return: (cloud_name, cloud_credential)
6454 """
bravof922c4172020-11-24 21:21:43 -03006455 config = VimAccountDB.get_vim_account_with_id(vim_account_id).get("config", {})
David Garciaaae391f2020-11-09 11:12:54 +01006456 return config.get("vca_k8s_cloud"), config.get("vca_k8s_cloud_credential")