blob: ab1ee3b1bf1e7940c683bc553fa8acb02236b386 [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
20import yaml
21import logging
22import logging.handlers
tierno59d22d22018-09-25 18:10:19 +020023import traceback
David Garciad4816682019-12-09 14:57:43 +010024import json
garciadeblas5697b8b2021-03-24 09:17:02 +010025from jinja2 import (
26 Environment,
27 TemplateError,
28 TemplateNotFound,
29 StrictUndefined,
30 UndefinedError,
31)
tierno59d22d22018-09-25 18:10:19 +020032
tierno77677d92019-08-22 13:46:35 +000033from osm_lcm import ROclient
aktas5f75f102021-03-15 11:26:10 +030034from osm_lcm.data_utils.nsr import get_deployed_kdu
tierno69f0d382020-05-07 13:08:09 +000035from osm_lcm.ng_ro import NgRoClient, NgRoException
garciadeblas5697b8b2021-03-24 09:17:02 +010036from osm_lcm.lcm_utils import (
37 LcmException,
38 LcmExceptionNoMgmtIP,
39 LcmBase,
40 deep_get,
41 get_iterable,
42 populate_dict,
43)
bravof922c4172020-11-24 21:21:43 -030044from osm_lcm.data_utils.nsd import get_vnf_profiles
garciadeblas5697b8b2021-03-24 09:17:02 +010045from osm_lcm.data_utils.vnfd import (
46 get_vdu_list,
47 get_vdu_profile,
48 get_ee_sorted_initial_config_primitive_list,
49 get_ee_sorted_terminate_config_primitive_list,
50 get_kdu_list,
51 get_virtual_link_profiles,
52 get_vdu,
53 get_configuration,
54 get_vdu_index,
55 get_scaling_aspect,
56 get_number_of_instances,
57 get_juju_ee_ref,
aktas5f75f102021-03-15 11:26:10 +030058 get_kdu_profile,
garciadeblas5697b8b2021-03-24 09:17:02 +010059)
bravof922c4172020-11-24 21:21:43 -030060from osm_lcm.data_utils.list_utils import find_in_list
aktas5f75f102021-03-15 11:26:10 +030061from osm_lcm.data_utils.vnfr import get_osm_params, get_vdur_index, get_kdur
bravof922c4172020-11-24 21:21:43 -030062from osm_lcm.data_utils.dict_utils import parse_yaml_strings
63from osm_lcm.data_utils.database.vim_account import VimAccountDB
calvinosanch9f9c6f22019-11-04 13:37:39 +010064from n2vc.k8s_helm_conn import K8sHelmConnector
lloretgalleg18ebc3a2020-10-22 09:54:51 +000065from n2vc.k8s_helm3_conn import K8sHelm3Connector
Adam Israelbaacc302019-12-01 12:41:39 -050066from n2vc.k8s_juju_conn import K8sJujuConnector
tierno59d22d22018-09-25 18:10:19 +020067
tierno27246d82018-09-27 15:59:09 +020068from osm_common.dbbase import DbException
tierno59d22d22018-09-25 18:10:19 +020069from osm_common.fsbase import FsException
quilesj7e13aeb2019-10-08 13:34:55 +020070
bravof922c4172020-11-24 21:21:43 -030071from osm_lcm.data_utils.database.database import Database
72from osm_lcm.data_utils.filesystem.filesystem import Filesystem
73
quilesj7e13aeb2019-10-08 13:34:55 +020074from n2vc.n2vc_juju_conn import N2VCJujuConnector
tiernof59ad6c2020-04-08 12:50:52 +000075from n2vc.exceptions import N2VCException, N2VCNotFound, K8sException
tierno59d22d22018-09-25 18:10:19 +020076
tierno588547c2020-07-01 15:30:20 +000077from osm_lcm.lcm_helm_conn import LCMHelmConn
78
tierno27246d82018-09-27 15:59:09 +020079from copy import copy, deepcopy
tierno59d22d22018-09-25 18:10:19 +020080from time import time
tierno27246d82018-09-27 15:59:09 +020081from uuid import uuid4
lloretgalleg7c121132020-07-08 07:53:22 +000082
tiernob996d942020-07-03 14:52:28 +000083from random import randint
tierno59d22d22018-09-25 18:10:19 +020084
tierno69f0d382020-05-07 13:08:09 +000085__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
tierno59d22d22018-09-25 18:10:19 +020086
87
88class NsLcm(LcmBase):
garciadeblas5697b8b2021-03-24 09:17:02 +010089 timeout_vca_on_error = (
90 5 * 60
91 ) # Time for charm from first time at blocked,error status to mark as failed
92 timeout_ns_deploy = 2 * 3600 # default global timeout for deployment a ns
93 timeout_ns_terminate = 1800 # default global timeout for un deployment a ns
garciadeblasf9b04952019-04-09 18:53:58 +020094 timeout_charm_delete = 10 * 60
David Garciaf6919842020-05-21 16:41:07 +020095 timeout_primitive = 30 * 60 # timeout for primitive execution
garciadeblas5697b8b2021-03-24 09:17:02 +010096 timeout_progress_primitive = (
97 10 * 60
98 ) # timeout for some progress in a primitive execution
tierno59d22d22018-09-25 18:10:19 +020099
kuuseac3a8882019-10-03 10:48:06 +0200100 SUBOPERATION_STATUS_NOT_FOUND = -1
101 SUBOPERATION_STATUS_NEW = -2
102 SUBOPERATION_STATUS_SKIP = -3
tiernoa2143262020-03-27 16:20:40 +0000103 task_name_deploy_vca = "Deploying VCA"
kuuseac3a8882019-10-03 10:48:06 +0200104
bravof922c4172020-11-24 21:21:43 -0300105 def __init__(self, msg, lcm_tasks, config, loop, prometheus=None):
tierno59d22d22018-09-25 18:10:19 +0200106 """
107 Init, Connect to database, filesystem storage, and messaging
108 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
109 :return: None
110 """
garciadeblas5697b8b2021-03-24 09:17:02 +0100111 super().__init__(msg=msg, logger=logging.getLogger("lcm.ns"))
quilesj7e13aeb2019-10-08 13:34:55 +0200112
bravof922c4172020-11-24 21:21:43 -0300113 self.db = Database().instance.db
114 self.fs = Filesystem().instance.fs
tierno59d22d22018-09-25 18:10:19 +0200115 self.loop = loop
116 self.lcm_tasks = lcm_tasks
tierno744303e2020-01-13 16:46:31 +0000117 self.timeout = config["timeout"]
118 self.ro_config = config["ro_config"]
tierno69f0d382020-05-07 13:08:09 +0000119 self.ng_ro = config["ro_config"].get("ng")
tierno744303e2020-01-13 16:46:31 +0000120 self.vca_config = config["VCA"].copy()
tierno59d22d22018-09-25 18:10:19 +0200121
quilesj7e13aeb2019-10-08 13:34:55 +0200122 # create N2VC connector
David Garciaaae391f2020-11-09 11:12:54 +0100123 self.n2vc = N2VCJujuConnector(
tierno59d22d22018-09-25 18:10:19 +0200124 log=self.logger,
quilesj7e13aeb2019-10-08 13:34:55 +0200125 loop=self.loop,
bravof922c4172020-11-24 21:21:43 -0300126 on_update_db=self._on_update_n2vc_db,
127 fs=self.fs,
garciadeblas5697b8b2021-03-24 09:17:02 +0100128 db=self.db,
tierno59d22d22018-09-25 18:10:19 +0200129 )
quilesj7e13aeb2019-10-08 13:34:55 +0200130
tierno588547c2020-07-01 15:30:20 +0000131 self.conn_helm_ee = LCMHelmConn(
tierno588547c2020-07-01 15:30:20 +0000132 log=self.logger,
133 loop=self.loop,
tierno588547c2020-07-01 15:30:20 +0000134 vca_config=self.vca_config,
garciadeblas5697b8b2021-03-24 09:17:02 +0100135 on_update_db=self._on_update_n2vc_db,
tierno588547c2020-07-01 15:30:20 +0000136 )
137
lloretgalleg18ebc3a2020-10-22 09:54:51 +0000138 self.k8sclusterhelm2 = K8sHelmConnector(
calvinosanch9f9c6f22019-11-04 13:37:39 +0100139 kubectl_command=self.vca_config.get("kubectlpath"),
140 helm_command=self.vca_config.get("helmpath"),
calvinosanch9f9c6f22019-11-04 13:37:39 +0100141 log=self.logger,
calvinosanch9f9c6f22019-11-04 13:37:39 +0100142 on_update_db=None,
bravof922c4172020-11-24 21:21:43 -0300143 fs=self.fs,
garciadeblas5697b8b2021-03-24 09:17:02 +0100144 db=self.db,
calvinosanch9f9c6f22019-11-04 13:37:39 +0100145 )
146
lloretgalleg18ebc3a2020-10-22 09:54:51 +0000147 self.k8sclusterhelm3 = K8sHelm3Connector(
148 kubectl_command=self.vca_config.get("kubectlpath"),
149 helm_command=self.vca_config.get("helm3path"),
150 fs=self.fs,
151 log=self.logger,
152 db=self.db,
153 on_update_db=None,
154 )
155
Adam Israelbaacc302019-12-01 12:41:39 -0500156 self.k8sclusterjuju = K8sJujuConnector(
157 kubectl_command=self.vca_config.get("kubectlpath"),
158 juju_command=self.vca_config.get("jujupath"),
Adam Israelbaacc302019-12-01 12:41:39 -0500159 log=self.logger,
David Garciaba89cbb2020-10-16 13:05:34 +0200160 loop=self.loop,
ksaikiranr656b6dd2021-02-19 10:25:18 +0530161 on_update_db=self._on_update_k8s_db,
bravof922c4172020-11-24 21:21:43 -0300162 fs=self.fs,
garciadeblas5697b8b2021-03-24 09:17:02 +0100163 db=self.db,
Adam Israelbaacc302019-12-01 12:41:39 -0500164 )
165
tiernoa2143262020-03-27 16:20:40 +0000166 self.k8scluster_map = {
lloretgalleg18ebc3a2020-10-22 09:54:51 +0000167 "helm-chart": self.k8sclusterhelm2,
168 "helm-chart-v3": self.k8sclusterhelm3,
169 "chart": self.k8sclusterhelm3,
tiernoa2143262020-03-27 16:20:40 +0000170 "juju-bundle": self.k8sclusterjuju,
171 "juju": self.k8sclusterjuju,
172 }
tierno588547c2020-07-01 15:30:20 +0000173
174 self.vca_map = {
175 "lxc_proxy_charm": self.n2vc,
176 "native_charm": self.n2vc,
177 "k8s_proxy_charm": self.n2vc,
lloretgalleg18ebc3a2020-10-22 09:54:51 +0000178 "helm": self.conn_helm_ee,
garciadeblas5697b8b2021-03-24 09:17:02 +0100179 "helm-v3": self.conn_helm_ee,
tierno588547c2020-07-01 15:30:20 +0000180 }
181
tiernob996d942020-07-03 14:52:28 +0000182 self.prometheus = prometheus
183
quilesj7e13aeb2019-10-08 13:34:55 +0200184 # create RO client
bravof922c4172020-11-24 21:21:43 -0300185 self.RO = NgRoClient(self.loop, **self.ro_config)
tierno59d22d22018-09-25 18:10:19 +0200186
tierno2357f4e2020-10-19 16:38:59 +0000187 @staticmethod
188 def increment_ip_mac(ip_mac, vm_index=1):
189 if not isinstance(ip_mac, str):
190 return ip_mac
191 try:
192 # try with ipv4 look for last dot
193 i = ip_mac.rfind(".")
194 if i > 0:
195 i += 1
196 return "{}{}".format(ip_mac[:i], int(ip_mac[i:]) + vm_index)
197 # try with ipv6 or mac look for last colon. Operate in hex
198 i = ip_mac.rfind(":")
199 if i > 0:
200 i += 1
201 # format in hex, len can be 2 for mac or 4 for ipv6
garciadeblas5697b8b2021-03-24 09:17:02 +0100202 return ("{}{:0" + str(len(ip_mac) - i) + "x}").format(
203 ip_mac[:i], int(ip_mac[i:], 16) + vm_index
204 )
tierno2357f4e2020-10-19 16:38:59 +0000205 except Exception:
206 pass
207 return None
208
quilesj3655ae02019-12-12 16:08:35 +0000209 def _on_update_ro_db(self, nsrs_id, ro_descriptor):
quilesj7e13aeb2019-10-08 13:34:55 +0200210
quilesj3655ae02019-12-12 16:08:35 +0000211 # self.logger.debug('_on_update_ro_db(nsrs_id={}'.format(nsrs_id))
212
213 try:
214 # TODO filter RO descriptor fields...
215
216 # write to database
217 db_dict = dict()
218 # db_dict['deploymentStatus'] = yaml.dump(ro_descriptor, default_flow_style=False, indent=2)
garciadeblas5697b8b2021-03-24 09:17:02 +0100219 db_dict["deploymentStatus"] = ro_descriptor
quilesj3655ae02019-12-12 16:08:35 +0000220 self.update_db_2("nsrs", nsrs_id, db_dict)
221
222 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100223 self.logger.warn(
224 "Cannot write database RO deployment for ns={} -> {}".format(nsrs_id, e)
225 )
quilesj3655ae02019-12-12 16:08:35 +0000226
David Garciac1fe90a2021-03-31 19:12:02 +0200227 async def _on_update_n2vc_db(self, table, filter, path, updated_data, vca_id=None):
quilesj3655ae02019-12-12 16:08:35 +0000228
quilesj69a722c2020-01-09 08:30:17 +0000229 # remove last dot from path (if exists)
garciadeblas5697b8b2021-03-24 09:17:02 +0100230 if path.endswith("."):
quilesj69a722c2020-01-09 08:30:17 +0000231 path = path[:-1]
232
quilesj3655ae02019-12-12 16:08:35 +0000233 # self.logger.debug('_on_update_n2vc_db(table={}, filter={}, path={}, updated_data={}'
234 # .format(table, filter, path, updated_data))
quilesj3655ae02019-12-12 16:08:35 +0000235 try:
236
garciadeblas5697b8b2021-03-24 09:17:02 +0100237 nsr_id = filter.get("_id")
quilesj3655ae02019-12-12 16:08:35 +0000238
239 # read ns record from database
garciadeblas5697b8b2021-03-24 09:17:02 +0100240 nsr = self.db.get_one(table="nsrs", q_filter=filter)
241 current_ns_status = nsr.get("nsState")
quilesj3655ae02019-12-12 16:08:35 +0000242
243 # get vca status for NS
garciadeblas5697b8b2021-03-24 09:17:02 +0100244 status_dict = await self.n2vc.get_status(
245 namespace="." + nsr_id, yaml_format=False, vca_id=vca_id
246 )
quilesj3655ae02019-12-12 16:08:35 +0000247
248 # vcaStatus
249 db_dict = dict()
garciadeblas5697b8b2021-03-24 09:17:02 +0100250 db_dict["vcaStatus"] = status_dict
251 await self.n2vc.update_vca_status(db_dict["vcaStatus"], vca_id=vca_id)
quilesj3655ae02019-12-12 16:08:35 +0000252
253 # update configurationStatus for this VCA
254 try:
garciadeblas5697b8b2021-03-24 09:17:02 +0100255 vca_index = int(path[path.rfind(".") + 1 :])
quilesj3655ae02019-12-12 16:08:35 +0000256
garciadeblas5697b8b2021-03-24 09:17:02 +0100257 vca_list = deep_get(
258 target_dict=nsr, key_list=("_admin", "deployed", "VCA")
259 )
260 vca_status = vca_list[vca_index].get("status")
quilesj3655ae02019-12-12 16:08:35 +0000261
garciadeblas5697b8b2021-03-24 09:17:02 +0100262 configuration_status_list = nsr.get("configurationStatus")
263 config_status = configuration_status_list[vca_index].get("status")
quilesj3655ae02019-12-12 16:08:35 +0000264
garciadeblas5697b8b2021-03-24 09:17:02 +0100265 if config_status == "BROKEN" and vca_status != "failed":
266 db_dict["configurationStatus"][vca_index] = "READY"
267 elif config_status != "BROKEN" and vca_status == "failed":
268 db_dict["configurationStatus"][vca_index] = "BROKEN"
quilesj3655ae02019-12-12 16:08:35 +0000269 except Exception as e:
270 # not update configurationStatus
garciadeblas5697b8b2021-03-24 09:17:02 +0100271 self.logger.debug("Error updating vca_index (ignore): {}".format(e))
quilesj3655ae02019-12-12 16:08:35 +0000272
273 # if nsState = 'READY' check if juju is reporting some error => nsState = 'DEGRADED'
274 # if nsState = 'DEGRADED' check if all is OK
275 is_degraded = False
garciadeblas5697b8b2021-03-24 09:17:02 +0100276 if current_ns_status in ("READY", "DEGRADED"):
277 error_description = ""
quilesj3655ae02019-12-12 16:08:35 +0000278 # check machines
garciadeblas5697b8b2021-03-24 09:17:02 +0100279 if status_dict.get("machines"):
280 for machine_id in status_dict.get("machines"):
281 machine = status_dict.get("machines").get(machine_id)
quilesj3655ae02019-12-12 16:08:35 +0000282 # check machine agent-status
garciadeblas5697b8b2021-03-24 09:17:02 +0100283 if machine.get("agent-status"):
284 s = machine.get("agent-status").get("status")
285 if s != "started":
quilesj3655ae02019-12-12 16:08:35 +0000286 is_degraded = True
garciadeblas5697b8b2021-03-24 09:17:02 +0100287 error_description += (
288 "machine {} agent-status={} ; ".format(
289 machine_id, s
290 )
291 )
quilesj3655ae02019-12-12 16:08:35 +0000292 # check machine instance status
garciadeblas5697b8b2021-03-24 09:17:02 +0100293 if machine.get("instance-status"):
294 s = machine.get("instance-status").get("status")
295 if s != "running":
quilesj3655ae02019-12-12 16:08:35 +0000296 is_degraded = True
garciadeblas5697b8b2021-03-24 09:17:02 +0100297 error_description += (
298 "machine {} instance-status={} ; ".format(
299 machine_id, s
300 )
301 )
quilesj3655ae02019-12-12 16:08:35 +0000302 # check applications
garciadeblas5697b8b2021-03-24 09:17:02 +0100303 if status_dict.get("applications"):
304 for app_id in status_dict.get("applications"):
305 app = status_dict.get("applications").get(app_id)
quilesj3655ae02019-12-12 16:08:35 +0000306 # check application status
garciadeblas5697b8b2021-03-24 09:17:02 +0100307 if app.get("status"):
308 s = app.get("status").get("status")
309 if s != "active":
quilesj3655ae02019-12-12 16:08:35 +0000310 is_degraded = True
garciadeblas5697b8b2021-03-24 09:17:02 +0100311 error_description += (
312 "application {} status={} ; ".format(app_id, s)
313 )
quilesj3655ae02019-12-12 16:08:35 +0000314
315 if error_description:
garciadeblas5697b8b2021-03-24 09:17:02 +0100316 db_dict["errorDescription"] = error_description
317 if current_ns_status == "READY" and is_degraded:
318 db_dict["nsState"] = "DEGRADED"
319 if current_ns_status == "DEGRADED" and not is_degraded:
320 db_dict["nsState"] = "READY"
quilesj3655ae02019-12-12 16:08:35 +0000321
322 # write to database
323 self.update_db_2("nsrs", nsr_id, db_dict)
324
tierno51183952020-04-03 15:48:18 +0000325 except (asyncio.CancelledError, asyncio.TimeoutError):
326 raise
quilesj3655ae02019-12-12 16:08:35 +0000327 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100328 self.logger.warn("Error updating NS state for ns={}: {}".format(nsr_id, e))
quilesj7e13aeb2019-10-08 13:34:55 +0200329
garciadeblas5697b8b2021-03-24 09:17:02 +0100330 async def _on_update_k8s_db(
331 self, cluster_uuid, kdu_instance, filter=None, vca_id=None
332 ):
ksaikiranr656b6dd2021-02-19 10:25:18 +0530333 """
334 Updating vca status in NSR record
335 :param cluster_uuid: UUID of a k8s cluster
336 :param kdu_instance: The unique name of the KDU instance
337 :param filter: To get nsr_id
338 :return: none
339 """
340
341 # self.logger.debug("_on_update_k8s_db(cluster_uuid={}, kdu_instance={}, filter={}"
342 # .format(cluster_uuid, kdu_instance, filter))
343
344 try:
garciadeblas5697b8b2021-03-24 09:17:02 +0100345 nsr_id = filter.get("_id")
ksaikiranr656b6dd2021-02-19 10:25:18 +0530346
347 # get vca status for NS
David Garciac1fe90a2021-03-31 19:12:02 +0200348 vca_status = await self.k8sclusterjuju.status_kdu(
349 cluster_uuid,
350 kdu_instance,
351 complete_status=True,
352 yaml_format=False,
353 vca_id=vca_id,
354 )
ksaikiranr656b6dd2021-02-19 10:25:18 +0530355 # vcaStatus
356 db_dict = dict()
garciadeblas5697b8b2021-03-24 09:17:02 +0100357 db_dict["vcaStatus"] = {nsr_id: vca_status}
ksaikiranr656b6dd2021-02-19 10:25:18 +0530358
David Garciac1fe90a2021-03-31 19:12:02 +0200359 await self.k8sclusterjuju.update_vca_status(
garciadeblas5697b8b2021-03-24 09:17:02 +0100360 db_dict["vcaStatus"],
David Garciac1fe90a2021-03-31 19:12:02 +0200361 kdu_instance,
362 vca_id=vca_id,
363 )
ksaikiranr656b6dd2021-02-19 10:25:18 +0530364
365 # write to database
366 self.update_db_2("nsrs", nsr_id, db_dict)
367
368 except (asyncio.CancelledError, asyncio.TimeoutError):
369 raise
370 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100371 self.logger.warn("Error updating NS state for ns={}: {}".format(nsr_id, e))
ksaikiranr656b6dd2021-02-19 10:25:18 +0530372
tierno72ef84f2020-10-06 08:22:07 +0000373 @staticmethod
374 def _parse_cloud_init(cloud_init_text, additional_params, vnfd_id, vdu_id):
375 try:
376 env = Environment(undefined=StrictUndefined)
377 template = env.from_string(cloud_init_text)
378 return template.render(additional_params or {})
379 except UndefinedError as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100380 raise LcmException(
381 "Variable {} at vnfd[id={}]:vdu[id={}]:cloud-init/cloud-init-"
382 "file, must be provided in the instantiation parameters inside the "
383 "'additionalParamsForVnf/Vdu' block".format(e, vnfd_id, vdu_id)
384 )
tierno72ef84f2020-10-06 08:22:07 +0000385 except (TemplateError, TemplateNotFound) as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100386 raise LcmException(
387 "Error parsing Jinja2 to cloud-init content at vnfd[id={}]:vdu[id={}]: {}".format(
388 vnfd_id, vdu_id, e
389 )
390 )
tierno72ef84f2020-10-06 08:22:07 +0000391
bravof922c4172020-11-24 21:21:43 -0300392 def _get_vdu_cloud_init_content(self, vdu, vnfd):
393 cloud_init_content = cloud_init_file = None
tierno72ef84f2020-10-06 08:22:07 +0000394 try:
tierno72ef84f2020-10-06 08:22:07 +0000395 if vdu.get("cloud-init-file"):
396 base_folder = vnfd["_admin"]["storage"]
garciadeblas5697b8b2021-03-24 09:17:02 +0100397 cloud_init_file = "{}/{}/cloud_init/{}".format(
398 base_folder["folder"],
399 base_folder["pkg-dir"],
400 vdu["cloud-init-file"],
401 )
tierno72ef84f2020-10-06 08:22:07 +0000402 with self.fs.file_open(cloud_init_file, "r") as ci_file:
403 cloud_init_content = ci_file.read()
404 elif vdu.get("cloud-init"):
405 cloud_init_content = vdu["cloud-init"]
406
407 return cloud_init_content
408 except FsException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100409 raise LcmException(
410 "Error reading vnfd[id={}]:vdu[id={}]:cloud-init-file={}: {}".format(
411 vnfd["id"], vdu["id"], cloud_init_file, e
412 )
413 )
tierno72ef84f2020-10-06 08:22:07 +0000414
tierno72ef84f2020-10-06 08:22:07 +0000415 def _get_vdu_additional_params(self, db_vnfr, vdu_id):
garciadeblas5697b8b2021-03-24 09:17:02 +0100416 vdur = next(
417 vdur for vdur in db_vnfr.get("vdur") if vdu_id == vdur["vdu-id-ref"]
418 )
tierno72ef84f2020-10-06 08:22:07 +0000419 additional_params = vdur.get("additionalParams")
bravof922c4172020-11-24 21:21:43 -0300420 return parse_yaml_strings(additional_params)
tierno72ef84f2020-10-06 08:22:07 +0000421
gcalvino35be9152018-12-20 09:33:12 +0100422 def vnfd2RO(self, vnfd, new_id=None, additionalParams=None, nsrId=None):
tierno59d22d22018-09-25 18:10:19 +0200423 """
424 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
425 :param vnfd: input vnfd
426 :param new_id: overrides vnf id if provided
tierno8a518872018-12-21 13:42:14 +0000427 :param additionalParams: Instantiation params for VNFs provided
gcalvino35be9152018-12-20 09:33:12 +0100428 :param nsrId: Id of the NSR
tierno59d22d22018-09-25 18:10:19 +0200429 :return: copy of vnfd
430 """
tierno72ef84f2020-10-06 08:22:07 +0000431 vnfd_RO = deepcopy(vnfd)
432 # remove unused by RO configuration, monitoring, scaling and internal keys
433 vnfd_RO.pop("_id", None)
434 vnfd_RO.pop("_admin", None)
tierno72ef84f2020-10-06 08:22:07 +0000435 vnfd_RO.pop("monitoring-param", None)
436 vnfd_RO.pop("scaling-group-descriptor", None)
437 vnfd_RO.pop("kdu", None)
438 vnfd_RO.pop("k8s-cluster", None)
439 if new_id:
440 vnfd_RO["id"] = new_id
tierno8a518872018-12-21 13:42:14 +0000441
tierno72ef84f2020-10-06 08:22:07 +0000442 # parse cloud-init or cloud-init-file with the provided variables using Jinja2
443 for vdu in get_iterable(vnfd_RO, "vdu"):
444 vdu.pop("cloud-init-file", None)
445 vdu.pop("cloud-init", None)
446 return vnfd_RO
tierno59d22d22018-09-25 18:10:19 +0200447
tierno2357f4e2020-10-19 16:38:59 +0000448 @staticmethod
449 def ip_profile_2_RO(ip_profile):
450 RO_ip_profile = deepcopy(ip_profile)
451 if "dns-server" in RO_ip_profile:
452 if isinstance(RO_ip_profile["dns-server"], list):
453 RO_ip_profile["dns-address"] = []
454 for ds in RO_ip_profile.pop("dns-server"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100455 RO_ip_profile["dns-address"].append(ds["address"])
tierno2357f4e2020-10-19 16:38:59 +0000456 else:
457 RO_ip_profile["dns-address"] = RO_ip_profile.pop("dns-server")
458 if RO_ip_profile.get("ip-version") == "ipv4":
459 RO_ip_profile["ip-version"] = "IPv4"
460 if RO_ip_profile.get("ip-version") == "ipv6":
461 RO_ip_profile["ip-version"] = "IPv6"
462 if "dhcp-params" in RO_ip_profile:
463 RO_ip_profile["dhcp"] = RO_ip_profile.pop("dhcp-params")
464 return RO_ip_profile
465
bravof922c4172020-11-24 21:21:43 -0300466 def _get_ro_vim_id_for_vim_account(self, vim_account):
467 db_vim = self.db.get_one("vim_accounts", {"_id": vim_account})
468 if db_vim["_admin"]["operationalState"] != "ENABLED":
garciadeblas5697b8b2021-03-24 09:17:02 +0100469 raise LcmException(
470 "VIM={} is not available. operationalState={}".format(
471 vim_account, db_vim["_admin"]["operationalState"]
472 )
473 )
bravof922c4172020-11-24 21:21:43 -0300474 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
475 return RO_vim_id
tierno59d22d22018-09-25 18:10:19 +0200476
bravof922c4172020-11-24 21:21:43 -0300477 def get_ro_wim_id_for_wim_account(self, wim_account):
478 if isinstance(wim_account, str):
479 db_wim = self.db.get_one("wim_accounts", {"_id": wim_account})
480 if db_wim["_admin"]["operationalState"] != "ENABLED":
garciadeblas5697b8b2021-03-24 09:17:02 +0100481 raise LcmException(
482 "WIM={} is not available. operationalState={}".format(
483 wim_account, db_wim["_admin"]["operationalState"]
484 )
485 )
bravof922c4172020-11-24 21:21:43 -0300486 RO_wim_id = db_wim["_admin"]["deployed"]["RO-account"]
487 return RO_wim_id
488 else:
489 return wim_account
tierno59d22d22018-09-25 18:10:19 +0200490
tierno2357f4e2020-10-19 16:38:59 +0000491 def scale_vnfr(self, db_vnfr, vdu_create=None, vdu_delete=None, mark_delete=False):
tierno27246d82018-09-27 15:59:09 +0200492
tierno2357f4e2020-10-19 16:38:59 +0000493 db_vdu_push_list = []
494 db_update = {"_admin.modified": time()}
495 if vdu_create:
496 for vdu_id, vdu_count in vdu_create.items():
garciadeblas5697b8b2021-03-24 09:17:02 +0100497 vdur = next(
498 (
499 vdur
500 for vdur in reversed(db_vnfr["vdur"])
501 if vdur["vdu-id-ref"] == vdu_id
502 ),
503 None,
504 )
tierno2357f4e2020-10-19 16:38:59 +0000505 if not vdur:
garciadeblas5697b8b2021-03-24 09:17:02 +0100506 raise LcmException(
507 "Error scaling OUT VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
508 vdu_id
509 )
510 )
tierno2357f4e2020-10-19 16:38:59 +0000511
512 for count in range(vdu_count):
513 vdur_copy = deepcopy(vdur)
514 vdur_copy["status"] = "BUILD"
515 vdur_copy["status-detailed"] = None
Guillermo Calvinofbf294c2022-01-26 17:40:31 +0100516 vdur_copy["ip-address"] = None
tierno683eb392020-09-25 12:33:15 +0000517 vdur_copy["_id"] = str(uuid4())
tierno2357f4e2020-10-19 16:38:59 +0000518 vdur_copy["count-index"] += count + 1
garciadeblas5697b8b2021-03-24 09:17:02 +0100519 vdur_copy["id"] = "{}-{}".format(
520 vdur_copy["vdu-id-ref"], vdur_copy["count-index"]
521 )
tierno2357f4e2020-10-19 16:38:59 +0000522 vdur_copy.pop("vim_info", None)
523 for iface in vdur_copy["interfaces"]:
524 if iface.get("fixed-ip"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100525 iface["ip-address"] = self.increment_ip_mac(
526 iface["ip-address"], count + 1
527 )
tierno2357f4e2020-10-19 16:38:59 +0000528 else:
529 iface.pop("ip-address", None)
530 if iface.get("fixed-mac"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100531 iface["mac-address"] = self.increment_ip_mac(
532 iface["mac-address"], count + 1
533 )
tierno2357f4e2020-10-19 16:38:59 +0000534 else:
535 iface.pop("mac-address", None)
garciadeblas5697b8b2021-03-24 09:17:02 +0100536 iface.pop(
537 "mgmt_vnf", None
538 ) # only first vdu can be managment of vnf
tierno2357f4e2020-10-19 16:38:59 +0000539 db_vdu_push_list.append(vdur_copy)
540 # self.logger.debug("scale out, adding vdu={}".format(vdur_copy))
tierno27246d82018-09-27 15:59:09 +0200541 if vdu_delete:
tierno2357f4e2020-10-19 16:38:59 +0000542 for vdu_id, vdu_count in vdu_delete.items():
543 if mark_delete:
garciadeblas5697b8b2021-03-24 09:17:02 +0100544 indexes_to_delete = [
545 iv[0]
546 for iv in enumerate(db_vnfr["vdur"])
547 if iv[1]["vdu-id-ref"] == vdu_id
548 ]
549 db_update.update(
550 {
551 "vdur.{}.status".format(i): "DELETING"
552 for i in indexes_to_delete[-vdu_count:]
553 }
554 )
tierno2357f4e2020-10-19 16:38:59 +0000555 else:
556 # it must be deleted one by one because common.db does not allow otherwise
garciadeblas5697b8b2021-03-24 09:17:02 +0100557 vdus_to_delete = [
558 v
559 for v in reversed(db_vnfr["vdur"])
560 if v["vdu-id-ref"] == vdu_id
561 ]
tierno2357f4e2020-10-19 16:38:59 +0000562 for vdu in vdus_to_delete[:vdu_count]:
garciadeblas5697b8b2021-03-24 09:17:02 +0100563 self.db.set_one(
564 "vnfrs",
565 {"_id": db_vnfr["_id"]},
566 None,
567 pull={"vdur": {"_id": vdu["_id"]}},
568 )
tierno2357f4e2020-10-19 16:38:59 +0000569 db_push = {"vdur": db_vdu_push_list} if db_vdu_push_list else None
570 self.db.set_one("vnfrs", {"_id": db_vnfr["_id"]}, db_update, push_list=db_push)
571 # modify passed dictionary db_vnfr
572 db_vnfr_ = self.db.get_one("vnfrs", {"_id": db_vnfr["_id"]})
573 db_vnfr["vdur"] = db_vnfr_["vdur"]
tierno27246d82018-09-27 15:59:09 +0200574
tiernof578e552018-11-08 19:07:20 +0100575 def ns_update_nsr(self, ns_update_nsr, db_nsr, nsr_desc_RO):
576 """
577 Updates database nsr with the RO info for the created vld
578 :param ns_update_nsr: dictionary to be filled with the updated info
579 :param db_nsr: content of db_nsr. This is also modified
580 :param nsr_desc_RO: nsr descriptor from RO
581 :return: Nothing, LcmException is raised on errors
582 """
583
584 for vld_index, vld in enumerate(get_iterable(db_nsr, "vld")):
585 for net_RO in get_iterable(nsr_desc_RO, "nets"):
586 if vld["id"] != net_RO.get("ns_net_osm_id"):
587 continue
588 vld["vim-id"] = net_RO.get("vim_net_id")
589 vld["name"] = net_RO.get("vim_name")
590 vld["status"] = net_RO.get("status")
591 vld["status-detailed"] = net_RO.get("error_msg")
592 ns_update_nsr["vld.{}".format(vld_index)] = vld
593 break
594 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100595 raise LcmException(
596 "ns_update_nsr: Not found vld={} at RO info".format(vld["id"])
597 )
tiernof578e552018-11-08 19:07:20 +0100598
tiernoe876f672020-02-13 14:34:48 +0000599 def set_vnfr_at_error(self, db_vnfrs, error_text):
600 try:
601 for db_vnfr in db_vnfrs.values():
602 vnfr_update = {"status": "ERROR"}
603 for vdu_index, vdur in enumerate(get_iterable(db_vnfr, "vdur")):
604 if "status" not in vdur:
605 vdur["status"] = "ERROR"
606 vnfr_update["vdur.{}.status".format(vdu_index)] = "ERROR"
607 if error_text:
608 vdur["status-detailed"] = str(error_text)
garciadeblas5697b8b2021-03-24 09:17:02 +0100609 vnfr_update[
610 "vdur.{}.status-detailed".format(vdu_index)
611 ] = "ERROR"
tiernoe876f672020-02-13 14:34:48 +0000612 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
613 except DbException as e:
614 self.logger.error("Cannot update vnf. {}".format(e))
615
tierno59d22d22018-09-25 18:10:19 +0200616 def ns_update_vnfr(self, db_vnfrs, nsr_desc_RO):
617 """
618 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 +0200619 :param db_vnfrs: dictionary with member-vnf-index: vnfr-content
620 :param nsr_desc_RO: nsr descriptor from RO
621 :return: Nothing, LcmException is raised on errors
tierno59d22d22018-09-25 18:10:19 +0200622 """
623 for vnf_index, db_vnfr in db_vnfrs.items():
624 for vnf_RO in nsr_desc_RO["vnfs"]:
tierno27246d82018-09-27 15:59:09 +0200625 if vnf_RO["member_vnf_index"] != vnf_index:
626 continue
627 vnfr_update = {}
tiernof578e552018-11-08 19:07:20 +0100628 if vnf_RO.get("ip_address"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100629 db_vnfr["ip-address"] = vnfr_update["ip-address"] = vnf_RO[
630 "ip_address"
631 ].split(";")[0]
tiernof578e552018-11-08 19:07:20 +0100632 elif not db_vnfr.get("ip-address"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100633 if db_vnfr.get("vdur"): # if not VDUs, there is not ip_address
634 raise LcmExceptionNoMgmtIP(
635 "ns member_vnf_index '{}' has no IP address".format(
636 vnf_index
637 )
638 )
tierno59d22d22018-09-25 18:10:19 +0200639
tierno27246d82018-09-27 15:59:09 +0200640 for vdu_index, vdur in enumerate(get_iterable(db_vnfr, "vdur")):
641 vdur_RO_count_index = 0
642 if vdur.get("pdu-type"):
643 continue
644 for vdur_RO in get_iterable(vnf_RO, "vms"):
645 if vdur["vdu-id-ref"] != vdur_RO["vdu_osm_id"]:
646 continue
647 if vdur["count-index"] != vdur_RO_count_index:
648 vdur_RO_count_index += 1
649 continue
650 vdur["vim-id"] = vdur_RO.get("vim_vm_id")
tierno1674de82019-04-09 13:03:14 +0000651 if vdur_RO.get("ip_address"):
652 vdur["ip-address"] = vdur_RO["ip_address"].split(";")[0]
tierno274ed572019-04-04 13:33:27 +0000653 else:
654 vdur["ip-address"] = None
tierno27246d82018-09-27 15:59:09 +0200655 vdur["vdu-id-ref"] = vdur_RO.get("vdu_osm_id")
656 vdur["name"] = vdur_RO.get("vim_name")
657 vdur["status"] = vdur_RO.get("status")
658 vdur["status-detailed"] = vdur_RO.get("error_msg")
659 for ifacer in get_iterable(vdur, "interfaces"):
660 for interface_RO in get_iterable(vdur_RO, "interfaces"):
661 if ifacer["name"] == interface_RO.get("internal_name"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100662 ifacer["ip-address"] = interface_RO.get(
663 "ip_address"
664 )
665 ifacer["mac-address"] = interface_RO.get(
666 "mac_address"
667 )
tierno27246d82018-09-27 15:59:09 +0200668 break
669 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100670 raise LcmException(
671 "ns_update_vnfr: Not found member_vnf_index={} vdur={} interface={} "
672 "from VIM info".format(
673 vnf_index, vdur["vdu-id-ref"], ifacer["name"]
674 )
675 )
tierno27246d82018-09-27 15:59:09 +0200676 vnfr_update["vdur.{}".format(vdu_index)] = vdur
677 break
678 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100679 raise LcmException(
680 "ns_update_vnfr: Not found member_vnf_index={} vdur={} count_index={} from "
681 "VIM info".format(
682 vnf_index, vdur["vdu-id-ref"], vdur["count-index"]
683 )
684 )
tiernof578e552018-11-08 19:07:20 +0100685
686 for vld_index, vld in enumerate(get_iterable(db_vnfr, "vld")):
687 for net_RO in get_iterable(nsr_desc_RO, "nets"):
688 if vld["id"] != net_RO.get("vnf_net_osm_id"):
689 continue
690 vld["vim-id"] = net_RO.get("vim_net_id")
691 vld["name"] = net_RO.get("vim_name")
692 vld["status"] = net_RO.get("status")
693 vld["status-detailed"] = net_RO.get("error_msg")
694 vnfr_update["vld.{}".format(vld_index)] = vld
695 break
696 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100697 raise LcmException(
698 "ns_update_vnfr: Not found member_vnf_index={} vld={} from VIM info".format(
699 vnf_index, vld["id"]
700 )
701 )
tiernof578e552018-11-08 19:07:20 +0100702
tierno27246d82018-09-27 15:59:09 +0200703 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
704 break
tierno59d22d22018-09-25 18:10:19 +0200705
706 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100707 raise LcmException(
708 "ns_update_vnfr: Not found member_vnf_index={} from VIM info".format(
709 vnf_index
710 )
711 )
tierno59d22d22018-09-25 18:10:19 +0200712
tierno5ee02052019-12-05 19:55:02 +0000713 def _get_ns_config_info(self, nsr_id):
tiernoc3f2a822019-11-05 13:45:04 +0000714 """
715 Generates a mapping between vnf,vdu elements and the N2VC id
tierno5ee02052019-12-05 19:55:02 +0000716 :param nsr_id: id of nsr to get last database _admin.deployed.VCA that contains this list
tiernoc3f2a822019-11-05 13:45:04 +0000717 :return: a dictionary with {osm-config-mapping: {}} where its element contains:
718 "<member-vnf-index>": <N2VC-id> for a vnf configuration, or
719 "<member-vnf-index>.<vdu.id>.<vdu replica(0, 1,..)>": <N2VC-id> for a vdu configuration
720 """
tierno5ee02052019-12-05 19:55:02 +0000721 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
722 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
tiernoc3f2a822019-11-05 13:45:04 +0000723 mapping = {}
724 ns_config_info = {"osm-config-mapping": mapping}
725 for vca in vca_deployed_list:
726 if not vca["member-vnf-index"]:
727 continue
728 if not vca["vdu_id"]:
729 mapping[vca["member-vnf-index"]] = vca["application"]
730 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100731 mapping[
732 "{}.{}.{}".format(
733 vca["member-vnf-index"], vca["vdu_id"], vca["vdu_count_index"]
734 )
735 ] = vca["application"]
tiernoc3f2a822019-11-05 13:45:04 +0000736 return ns_config_info
737
garciadeblas5697b8b2021-03-24 09:17:02 +0100738 async def _instantiate_ng_ro(
739 self,
740 logging_text,
741 nsr_id,
742 nsd,
743 db_nsr,
744 db_nslcmop,
745 db_vnfrs,
746 db_vnfds,
747 n2vc_key_list,
748 stage,
749 start_deploy,
750 timeout_ns_deploy,
751 ):
tierno2357f4e2020-10-19 16:38:59 +0000752
753 db_vims = {}
754
755 def get_vim_account(vim_account_id):
756 nonlocal db_vims
757 if vim_account_id in db_vims:
758 return db_vims[vim_account_id]
759 db_vim = self.db.get_one("vim_accounts", {"_id": vim_account_id})
760 db_vims[vim_account_id] = db_vim
761 return db_vim
762
763 # modify target_vld info with instantiation parameters
garciadeblas5697b8b2021-03-24 09:17:02 +0100764 def parse_vld_instantiation_params(
765 target_vim, target_vld, vld_params, target_sdn
766 ):
tierno2357f4e2020-10-19 16:38:59 +0000767 if vld_params.get("ip-profile"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100768 target_vld["vim_info"][target_vim]["ip_profile"] = vld_params[
769 "ip-profile"
770 ]
tierno2357f4e2020-10-19 16:38:59 +0000771 if vld_params.get("provider-network"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100772 target_vld["vim_info"][target_vim]["provider_network"] = vld_params[
773 "provider-network"
774 ]
tierno2357f4e2020-10-19 16:38:59 +0000775 if "sdn-ports" in vld_params["provider-network"] and target_sdn:
garciadeblas5697b8b2021-03-24 09:17:02 +0100776 target_vld["vim_info"][target_sdn]["sdn-ports"] = vld_params[
777 "provider-network"
778 ]["sdn-ports"]
tierno2357f4e2020-10-19 16:38:59 +0000779 if vld_params.get("wimAccountId"):
780 target_wim = "wim:{}".format(vld_params["wimAccountId"])
781 target_vld["vim_info"][target_wim] = {}
782 for param in ("vim-network-name", "vim-network-id"):
783 if vld_params.get(param):
784 if isinstance(vld_params[param], dict):
garciaale04694c62021-03-02 10:49:28 -0300785 for vim, vim_net in vld_params[param].items():
bravof922c4172020-11-24 21:21:43 -0300786 other_target_vim = "vim:" + vim
garciadeblas5697b8b2021-03-24 09:17:02 +0100787 populate_dict(
788 target_vld["vim_info"],
789 (other_target_vim, param.replace("-", "_")),
790 vim_net,
791 )
tierno2357f4e2020-10-19 16:38:59 +0000792 else: # isinstance str
garciadeblas5697b8b2021-03-24 09:17:02 +0100793 target_vld["vim_info"][target_vim][
794 param.replace("-", "_")
795 ] = vld_params[param]
bravof922c4172020-11-24 21:21:43 -0300796 if vld_params.get("common_id"):
797 target_vld["common_id"] = vld_params.get("common_id")
tierno2357f4e2020-10-19 16:38:59 +0000798
aticigc90db8e2022-03-11 21:14:22 +0300799 # modify target["ns"]["vld"] with instantiation parameters to override vnf vim-account
800 def update_ns_vld_target(target, ns_params):
801 for vnf_params in ns_params.get("vnf", ()):
802 if vnf_params.get("vimAccountId"):
803 target_vnf = next(
804 (
805 vnfr
806 for vnfr in db_vnfrs.values()
807 if vnf_params["member-vnf-index"]
808 == vnfr["member-vnf-index-ref"]
809 ),
810 None,
811 )
812 vdur = next((vdur for vdur in target_vnf.get("vdur", ())), None)
813 for a_index, a_vld in enumerate(target["ns"]["vld"]):
814 target_vld = find_in_list(
815 get_iterable(vdur, "interfaces"),
816 lambda iface: iface.get("ns-vld-id") == a_vld["name"],
817 )
818 if target_vld:
819 if vnf_params.get("vimAccountId") not in a_vld.get(
820 "vim_info", {}
821 ):
822 target["ns"]["vld"][a_index].get("vim_info").update(
823 {
824 "vim:{}".format(vnf_params["vimAccountId"]): {
825 "vim_network_name": ""
826 }
827 }
828 )
829
tierno69f0d382020-05-07 13:08:09 +0000830 nslcmop_id = db_nslcmop["_id"]
831 target = {
832 "name": db_nsr["name"],
833 "ns": {"vld": []},
834 "vnf": [],
835 "image": deepcopy(db_nsr["image"]),
836 "flavor": deepcopy(db_nsr["flavor"]),
837 "action_id": nslcmop_id,
tierno2357f4e2020-10-19 16:38:59 +0000838 "cloud_init_content": {},
tierno69f0d382020-05-07 13:08:09 +0000839 }
840 for image in target["image"]:
tierno2357f4e2020-10-19 16:38:59 +0000841 image["vim_info"] = {}
tierno69f0d382020-05-07 13:08:09 +0000842 for flavor in target["flavor"]:
tierno2357f4e2020-10-19 16:38:59 +0000843 flavor["vim_info"] = {}
tierno69f0d382020-05-07 13:08:09 +0000844
tierno2357f4e2020-10-19 16:38:59 +0000845 if db_nslcmop.get("lcmOperationType") != "instantiate":
846 # get parameters of instantiation:
garciadeblas5697b8b2021-03-24 09:17:02 +0100847 db_nslcmop_instantiate = self.db.get_list(
848 "nslcmops",
849 {
850 "nsInstanceId": db_nslcmop["nsInstanceId"],
851 "lcmOperationType": "instantiate",
852 },
853 )[-1]
tierno2357f4e2020-10-19 16:38:59 +0000854 ns_params = db_nslcmop_instantiate.get("operationParams")
855 else:
856 ns_params = db_nslcmop.get("operationParams")
bravof922c4172020-11-24 21:21:43 -0300857 ssh_keys_instantiation = ns_params.get("ssh_keys") or []
858 ssh_keys_all = ssh_keys_instantiation + (n2vc_key_list or [])
tierno69f0d382020-05-07 13:08:09 +0000859
860 cp2target = {}
tierno2357f4e2020-10-19 16:38:59 +0000861 for vld_index, vld in enumerate(db_nsr.get("vld")):
862 target_vim = "vim:{}".format(ns_params["vimAccountId"])
863 target_vld = {
864 "id": vld["id"],
865 "name": vld["name"],
866 "mgmt-network": vld.get("mgmt-network", False),
867 "type": vld.get("type"),
868 "vim_info": {
bravof922c4172020-11-24 21:21:43 -0300869 target_vim: {
870 "vim_network_name": vld.get("vim-network-name"),
garciadeblas5697b8b2021-03-24 09:17:02 +0100871 "vim_account_id": ns_params["vimAccountId"],
bravof922c4172020-11-24 21:21:43 -0300872 }
garciadeblas5697b8b2021-03-24 09:17:02 +0100873 },
tierno2357f4e2020-10-19 16:38:59 +0000874 }
875 # check if this network needs SDN assist
tierno2357f4e2020-10-19 16:38:59 +0000876 if vld.get("pci-interfaces"):
garciadeblasa5ae90b2021-02-12 11:26:46 +0000877 db_vim = get_vim_account(ns_params["vimAccountId"])
tierno2357f4e2020-10-19 16:38:59 +0000878 sdnc_id = db_vim["config"].get("sdn-controller")
879 if sdnc_id:
garciadeblasa5ae90b2021-02-12 11:26:46 +0000880 sdn_vld = "nsrs:{}:vld.{}".format(nsr_id, vld["id"])
881 target_sdn = "sdn:{}".format(sdnc_id)
882 target_vld["vim_info"][target_sdn] = {
garciadeblas5697b8b2021-03-24 09:17:02 +0100883 "sdn": True,
884 "target_vim": target_vim,
885 "vlds": [sdn_vld],
886 "type": vld.get("type"),
887 }
tierno2357f4e2020-10-19 16:38:59 +0000888
bravof922c4172020-11-24 21:21:43 -0300889 nsd_vnf_profiles = get_vnf_profiles(nsd)
890 for nsd_vnf_profile in nsd_vnf_profiles:
891 for cp in nsd_vnf_profile["virtual-link-connectivity"]:
892 if cp["virtual-link-profile-id"] == vld["id"]:
garciadeblas5697b8b2021-03-24 09:17:02 +0100893 cp2target[
894 "member_vnf:{}.{}".format(
895 cp["constituent-cpd-id"][0][
896 "constituent-base-element-id"
897 ],
898 cp["constituent-cpd-id"][0]["constituent-cpd-id"],
899 )
900 ] = "nsrs:{}:vld.{}".format(nsr_id, vld_index)
tierno2357f4e2020-10-19 16:38:59 +0000901
902 # check at nsd descriptor, if there is an ip-profile
903 vld_params = {}
lloretgalleg19008482021-04-19 11:40:18 +0000904 nsd_vlp = find_in_list(
905 get_virtual_link_profiles(nsd),
garciadeblas5697b8b2021-03-24 09:17:02 +0100906 lambda a_link_profile: a_link_profile["virtual-link-desc-id"]
907 == vld["id"],
908 )
909 if (
910 nsd_vlp
911 and nsd_vlp.get("virtual-link-protocol-data")
912 and nsd_vlp["virtual-link-protocol-data"].get("l3-protocol-data")
913 ):
914 ip_profile_source_data = nsd_vlp["virtual-link-protocol-data"][
915 "l3-protocol-data"
916 ]
lloretgalleg19008482021-04-19 11:40:18 +0000917 ip_profile_dest_data = {}
918 if "ip-version" in ip_profile_source_data:
garciadeblas5697b8b2021-03-24 09:17:02 +0100919 ip_profile_dest_data["ip-version"] = ip_profile_source_data[
920 "ip-version"
921 ]
lloretgalleg19008482021-04-19 11:40:18 +0000922 if "cidr" in ip_profile_source_data:
garciadeblas5697b8b2021-03-24 09:17:02 +0100923 ip_profile_dest_data["subnet-address"] = ip_profile_source_data[
924 "cidr"
925 ]
lloretgalleg19008482021-04-19 11:40:18 +0000926 if "gateway-ip" in ip_profile_source_data:
garciadeblas5697b8b2021-03-24 09:17:02 +0100927 ip_profile_dest_data["gateway-address"] = ip_profile_source_data[
928 "gateway-ip"
929 ]
lloretgalleg19008482021-04-19 11:40:18 +0000930 if "dhcp-enabled" in ip_profile_source_data:
931 ip_profile_dest_data["dhcp-params"] = {
932 "enabled": ip_profile_source_data["dhcp-enabled"]
933 }
934 vld_params["ip-profile"] = ip_profile_dest_data
bravof922c4172020-11-24 21:21:43 -0300935
tierno2357f4e2020-10-19 16:38:59 +0000936 # update vld_params with instantiation params
garciadeblas5697b8b2021-03-24 09:17:02 +0100937 vld_instantiation_params = find_in_list(
938 get_iterable(ns_params, "vld"),
939 lambda a_vld: a_vld["name"] in (vld["name"], vld["id"]),
940 )
tierno2357f4e2020-10-19 16:38:59 +0000941 if vld_instantiation_params:
942 vld_params.update(vld_instantiation_params)
bravof922c4172020-11-24 21:21:43 -0300943 parse_vld_instantiation_params(target_vim, target_vld, vld_params, None)
tierno69f0d382020-05-07 13:08:09 +0000944 target["ns"]["vld"].append(target_vld)
aticigc90db8e2022-03-11 21:14:22 +0300945 # Update the target ns_vld if vnf vim_account is overriden by instantiation params
946 update_ns_vld_target(target, ns_params)
bravof922c4172020-11-24 21:21:43 -0300947
tierno69f0d382020-05-07 13:08:09 +0000948 for vnfr in db_vnfrs.values():
garciadeblas5697b8b2021-03-24 09:17:02 +0100949 vnfd = find_in_list(
950 db_vnfds, lambda db_vnf: db_vnf["id"] == vnfr["vnfd-ref"]
951 )
952 vnf_params = find_in_list(
953 get_iterable(ns_params, "vnf"),
954 lambda a_vnf: a_vnf["member-vnf-index"] == vnfr["member-vnf-index-ref"],
955 )
tierno69f0d382020-05-07 13:08:09 +0000956 target_vnf = deepcopy(vnfr)
tierno2357f4e2020-10-19 16:38:59 +0000957 target_vim = "vim:{}".format(vnfr["vim-account-id"])
tierno69f0d382020-05-07 13:08:09 +0000958 for vld in target_vnf.get("vld", ()):
tierno2357f4e2020-10-19 16:38:59 +0000959 # check if connected to a ns.vld, to fill target'
garciadeblas5697b8b2021-03-24 09:17:02 +0100960 vnf_cp = find_in_list(
961 vnfd.get("int-virtual-link-desc", ()),
962 lambda cpd: cpd.get("id") == vld["id"],
963 )
tierno69f0d382020-05-07 13:08:09 +0000964 if vnf_cp:
garciadeblas5697b8b2021-03-24 09:17:02 +0100965 ns_cp = "member_vnf:{}.{}".format(
966 vnfr["member-vnf-index-ref"], vnf_cp["id"]
967 )
tierno69f0d382020-05-07 13:08:09 +0000968 if cp2target.get(ns_cp):
969 vld["target"] = cp2target[ns_cp]
bravof922c4172020-11-24 21:21:43 -0300970
garciadeblas5697b8b2021-03-24 09:17:02 +0100971 vld["vim_info"] = {
972 target_vim: {"vim_network_name": vld.get("vim-network-name")}
973 }
tierno2357f4e2020-10-19 16:38:59 +0000974 # check if this network needs SDN assist
975 target_sdn = None
976 if vld.get("pci-interfaces"):
977 db_vim = get_vim_account(vnfr["vim-account-id"])
978 sdnc_id = db_vim["config"].get("sdn-controller")
979 if sdnc_id:
980 sdn_vld = "vnfrs:{}:vld.{}".format(target_vnf["_id"], vld["id"])
981 target_sdn = "sdn:{}".format(sdnc_id)
982 vld["vim_info"][target_sdn] = {
garciadeblas5697b8b2021-03-24 09:17:02 +0100983 "sdn": True,
984 "target_vim": target_vim,
985 "vlds": [sdn_vld],
986 "type": vld.get("type"),
987 }
tierno69f0d382020-05-07 13:08:09 +0000988
tierno2357f4e2020-10-19 16:38:59 +0000989 # check at vnfd descriptor, if there is an ip-profile
990 vld_params = {}
bravof922c4172020-11-24 21:21:43 -0300991 vnfd_vlp = find_in_list(
992 get_virtual_link_profiles(vnfd),
garciadeblas5697b8b2021-03-24 09:17:02 +0100993 lambda a_link_profile: a_link_profile["id"] == vld["id"],
bravof922c4172020-11-24 21:21:43 -0300994 )
garciadeblas5697b8b2021-03-24 09:17:02 +0100995 if (
996 vnfd_vlp
997 and vnfd_vlp.get("virtual-link-protocol-data")
998 and vnfd_vlp["virtual-link-protocol-data"].get("l3-protocol-data")
999 ):
1000 ip_profile_source_data = vnfd_vlp["virtual-link-protocol-data"][
1001 "l3-protocol-data"
1002 ]
bravof922c4172020-11-24 21:21:43 -03001003 ip_profile_dest_data = {}
1004 if "ip-version" in ip_profile_source_data:
garciadeblas5697b8b2021-03-24 09:17:02 +01001005 ip_profile_dest_data["ip-version"] = ip_profile_source_data[
1006 "ip-version"
1007 ]
bravof922c4172020-11-24 21:21:43 -03001008 if "cidr" in ip_profile_source_data:
garciadeblas5697b8b2021-03-24 09:17:02 +01001009 ip_profile_dest_data["subnet-address"] = ip_profile_source_data[
1010 "cidr"
1011 ]
bravof922c4172020-11-24 21:21:43 -03001012 if "gateway-ip" in ip_profile_source_data:
garciadeblas5697b8b2021-03-24 09:17:02 +01001013 ip_profile_dest_data[
1014 "gateway-address"
1015 ] = ip_profile_source_data["gateway-ip"]
bravof922c4172020-11-24 21:21:43 -03001016 if "dhcp-enabled" in ip_profile_source_data:
1017 ip_profile_dest_data["dhcp-params"] = {
1018 "enabled": ip_profile_source_data["dhcp-enabled"]
1019 }
1020
1021 vld_params["ip-profile"] = ip_profile_dest_data
tierno2357f4e2020-10-19 16:38:59 +00001022 # update vld_params with instantiation params
1023 if vnf_params:
garciadeblas5697b8b2021-03-24 09:17:02 +01001024 vld_instantiation_params = find_in_list(
1025 get_iterable(vnf_params, "internal-vld"),
1026 lambda i_vld: i_vld["name"] == vld["id"],
1027 )
tierno2357f4e2020-10-19 16:38:59 +00001028 if vld_instantiation_params:
1029 vld_params.update(vld_instantiation_params)
1030 parse_vld_instantiation_params(target_vim, vld, vld_params, target_sdn)
1031
1032 vdur_list = []
tierno69f0d382020-05-07 13:08:09 +00001033 for vdur in target_vnf.get("vdur", ()):
tierno2357f4e2020-10-19 16:38:59 +00001034 if vdur.get("status") == "DELETING" or vdur.get("pdu-type"):
1035 continue # This vdu must not be created
bravof922c4172020-11-24 21:21:43 -03001036 vdur["vim_info"] = {"vim_account_id": vnfr["vim-account-id"]}
tierno69f0d382020-05-07 13:08:09 +00001037
bravof922c4172020-11-24 21:21:43 -03001038 self.logger.debug("NS > ssh_keys > {}".format(ssh_keys_all))
1039
1040 if ssh_keys_all:
bravofe5a31bc2021-02-17 19:09:12 -03001041 vdu_configuration = get_configuration(vnfd, vdur["vdu-id-ref"])
1042 vnf_configuration = get_configuration(vnfd, vnfd["id"])
garciadeblas5697b8b2021-03-24 09:17:02 +01001043 if (
1044 vdu_configuration
1045 and vdu_configuration.get("config-access")
1046 and vdu_configuration.get("config-access").get("ssh-access")
1047 ):
bravof922c4172020-11-24 21:21:43 -03001048 vdur["ssh-keys"] = ssh_keys_all
garciadeblas5697b8b2021-03-24 09:17:02 +01001049 vdur["ssh-access-required"] = vdu_configuration[
1050 "config-access"
1051 ]["ssh-access"]["required"]
1052 elif (
1053 vnf_configuration
1054 and vnf_configuration.get("config-access")
1055 and vnf_configuration.get("config-access").get("ssh-access")
1056 and any(iface.get("mgmt-vnf") for iface in vdur["interfaces"])
1057 ):
bravof922c4172020-11-24 21:21:43 -03001058 vdur["ssh-keys"] = ssh_keys_all
garciadeblas5697b8b2021-03-24 09:17:02 +01001059 vdur["ssh-access-required"] = vnf_configuration[
1060 "config-access"
1061 ]["ssh-access"]["required"]
1062 elif ssh_keys_instantiation and find_in_list(
1063 vdur["interfaces"], lambda iface: iface.get("mgmt-vnf")
1064 ):
bravof922c4172020-11-24 21:21:43 -03001065 vdur["ssh-keys"] = ssh_keys_instantiation
tierno69f0d382020-05-07 13:08:09 +00001066
bravof922c4172020-11-24 21:21:43 -03001067 self.logger.debug("NS > vdur > {}".format(vdur))
1068
1069 vdud = get_vdu(vnfd, vdur["vdu-id-ref"])
tierno69f0d382020-05-07 13:08:09 +00001070 # cloud-init
1071 if vdud.get("cloud-init-file"):
garciadeblas5697b8b2021-03-24 09:17:02 +01001072 vdur["cloud-init"] = "{}:file:{}".format(
1073 vnfd["_id"], vdud.get("cloud-init-file")
1074 )
tierno2357f4e2020-10-19 16:38:59 +00001075 # read file and put content at target.cloul_init_content. Avoid ng_ro to use shared package system
1076 if vdur["cloud-init"] not in target["cloud_init_content"]:
1077 base_folder = vnfd["_admin"]["storage"]
garciadeblas5697b8b2021-03-24 09:17:02 +01001078 cloud_init_file = "{}/{}/cloud_init/{}".format(
1079 base_folder["folder"],
1080 base_folder["pkg-dir"],
1081 vdud.get("cloud-init-file"),
1082 )
tierno2357f4e2020-10-19 16:38:59 +00001083 with self.fs.file_open(cloud_init_file, "r") as ci_file:
garciadeblas5697b8b2021-03-24 09:17:02 +01001084 target["cloud_init_content"][
1085 vdur["cloud-init"]
1086 ] = ci_file.read()
tierno69f0d382020-05-07 13:08:09 +00001087 elif vdud.get("cloud-init"):
garciadeblas5697b8b2021-03-24 09:17:02 +01001088 vdur["cloud-init"] = "{}:vdu:{}".format(
1089 vnfd["_id"], get_vdu_index(vnfd, vdur["vdu-id-ref"])
1090 )
tierno2357f4e2020-10-19 16:38:59 +00001091 # put content at target.cloul_init_content. Avoid ng_ro read vnfd descriptor
garciadeblas5697b8b2021-03-24 09:17:02 +01001092 target["cloud_init_content"][vdur["cloud-init"]] = vdud[
1093 "cloud-init"
1094 ]
tierno2357f4e2020-10-19 16:38:59 +00001095 vdur["additionalParams"] = vdur.get("additionalParams") or {}
garciadeblas5697b8b2021-03-24 09:17:02 +01001096 deploy_params_vdu = self._format_additional_params(
1097 vdur.get("additionalParams") or {}
1098 )
1099 deploy_params_vdu["OSM"] = get_osm_params(
1100 vnfr, vdur["vdu-id-ref"], vdur["count-index"]
1101 )
tierno2357f4e2020-10-19 16:38:59 +00001102 vdur["additionalParams"] = deploy_params_vdu
tierno69f0d382020-05-07 13:08:09 +00001103
1104 # flavor
1105 ns_flavor = target["flavor"][int(vdur["ns-flavor-id"])]
tierno2357f4e2020-10-19 16:38:59 +00001106 if target_vim not in ns_flavor["vim_info"]:
1107 ns_flavor["vim_info"][target_vim] = {}
lloretgalleg7dc94672021-02-08 11:49:50 +00001108
1109 # deal with images
1110 # in case alternative images are provided we must check if they should be applied
1111 # for the vim_type, modify the vim_type taking into account
1112 ns_image_id = int(vdur["ns-image-id"])
1113 if vdur.get("alt-image-ids"):
1114 db_vim = get_vim_account(vnfr["vim-account-id"])
1115 vim_type = db_vim["vim_type"]
1116 for alt_image_id in vdur.get("alt-image-ids"):
1117 ns_alt_image = target["image"][int(alt_image_id)]
1118 if vim_type == ns_alt_image.get("vim-type"):
1119 # must use alternative image
garciadeblas5697b8b2021-03-24 09:17:02 +01001120 self.logger.debug(
1121 "use alternative image id: {}".format(alt_image_id)
1122 )
lloretgalleg7dc94672021-02-08 11:49:50 +00001123 ns_image_id = alt_image_id
1124 vdur["ns-image-id"] = ns_image_id
1125 break
1126 ns_image = target["image"][int(ns_image_id)]
tierno2357f4e2020-10-19 16:38:59 +00001127 if target_vim not in ns_image["vim_info"]:
1128 ns_image["vim_info"][target_vim] = {}
tierno69f0d382020-05-07 13:08:09 +00001129
tierno2357f4e2020-10-19 16:38:59 +00001130 vdur["vim_info"] = {target_vim: {}}
1131 # instantiation parameters
1132 # if vnf_params:
1133 # vdu_instantiation_params = next((v for v in get_iterable(vnf_params, "vdu") if v["id"] ==
1134 # vdud["id"]), None)
1135 vdur_list.append(vdur)
1136 target_vnf["vdur"] = vdur_list
tierno69f0d382020-05-07 13:08:09 +00001137 target["vnf"].append(target_vnf)
1138
1139 desc = await self.RO.deploy(nsr_id, target)
bravof922c4172020-11-24 21:21:43 -03001140 self.logger.debug("RO return > {}".format(desc))
tierno69f0d382020-05-07 13:08:09 +00001141 action_id = desc["action_id"]
garciadeblas5697b8b2021-03-24 09:17:02 +01001142 await self._wait_ng_ro(
1143 nsr_id, action_id, nslcmop_id, start_deploy, timeout_ns_deploy, stage
1144 )
tierno69f0d382020-05-07 13:08:09 +00001145
1146 # Updating NSR
1147 db_nsr_update = {
1148 "_admin.deployed.RO.operational-status": "running",
garciadeblas5697b8b2021-03-24 09:17:02 +01001149 "detailed-status": " ".join(stage),
tierno69f0d382020-05-07 13:08:09 +00001150 }
1151 # db_nsr["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
1152 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1153 self._write_op_status(nslcmop_id, stage)
garciadeblas5697b8b2021-03-24 09:17:02 +01001154 self.logger.debug(
1155 logging_text + "ns deployed at RO. RO_id={}".format(action_id)
1156 )
tierno69f0d382020-05-07 13:08:09 +00001157 return
1158
garciadeblas5697b8b2021-03-24 09:17:02 +01001159 async def _wait_ng_ro(
1160 self,
1161 nsr_id,
1162 action_id,
1163 nslcmop_id=None,
1164 start_time=None,
1165 timeout=600,
1166 stage=None,
1167 ):
tierno69f0d382020-05-07 13:08:09 +00001168 detailed_status_old = None
1169 db_nsr_update = {}
tierno2357f4e2020-10-19 16:38:59 +00001170 start_time = start_time or time()
tierno69f0d382020-05-07 13:08:09 +00001171 while time() <= start_time + timeout:
1172 desc_status = await self.RO.status(nsr_id, action_id)
bravof922c4172020-11-24 21:21:43 -03001173 self.logger.debug("Wait NG RO > {}".format(desc_status))
tierno69f0d382020-05-07 13:08:09 +00001174 if desc_status["status"] == "FAILED":
1175 raise NgRoException(desc_status["details"])
1176 elif desc_status["status"] == "BUILD":
tierno2357f4e2020-10-19 16:38:59 +00001177 if stage:
1178 stage[2] = "VIM: ({})".format(desc_status["details"])
tierno69f0d382020-05-07 13:08:09 +00001179 elif desc_status["status"] == "DONE":
tierno2357f4e2020-10-19 16:38:59 +00001180 if stage:
1181 stage[2] = "Deployed at VIM"
tierno69f0d382020-05-07 13:08:09 +00001182 break
1183 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001184 assert False, "ROclient.check_ns_status returns unknown {}".format(
1185 desc_status["status"]
1186 )
tierno2357f4e2020-10-19 16:38:59 +00001187 if stage and nslcmop_id and stage[2] != detailed_status_old:
tierno69f0d382020-05-07 13:08:09 +00001188 detailed_status_old = stage[2]
1189 db_nsr_update["detailed-status"] = " ".join(stage)
1190 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1191 self._write_op_status(nslcmop_id, stage)
bravof922c4172020-11-24 21:21:43 -03001192 await asyncio.sleep(15, loop=self.loop)
tierno69f0d382020-05-07 13:08:09 +00001193 else: # timeout_ns_deploy
1194 raise NgRoException("Timeout waiting ns to deploy")
1195
garciadeblas5697b8b2021-03-24 09:17:02 +01001196 async def _terminate_ng_ro(
1197 self, logging_text, nsr_deployed, nsr_id, nslcmop_id, stage
1198 ):
tierno69f0d382020-05-07 13:08:09 +00001199 db_nsr_update = {}
1200 failed_detail = []
1201 action_id = None
1202 start_deploy = time()
1203 try:
1204 target = {
1205 "ns": {"vld": []},
1206 "vnf": [],
1207 "image": [],
1208 "flavor": [],
garciadeblas5697b8b2021-03-24 09:17:02 +01001209 "action_id": nslcmop_id,
tierno69f0d382020-05-07 13:08:09 +00001210 }
1211 desc = await self.RO.deploy(nsr_id, target)
1212 action_id = desc["action_id"]
1213 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = action_id
1214 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETING"
garciadeblas5697b8b2021-03-24 09:17:02 +01001215 self.logger.debug(
1216 logging_text
1217 + "ns terminate action at RO. action_id={}".format(action_id)
1218 )
tierno69f0d382020-05-07 13:08:09 +00001219
1220 # wait until done
1221 delete_timeout = 20 * 60 # 20 minutes
garciadeblas5697b8b2021-03-24 09:17:02 +01001222 await self._wait_ng_ro(
1223 nsr_id, action_id, nslcmop_id, start_deploy, delete_timeout, stage
1224 )
tierno69f0d382020-05-07 13:08:09 +00001225
1226 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
1227 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
1228 # delete all nsr
1229 await self.RO.delete(nsr_id)
1230 except Exception as e:
1231 if isinstance(e, NgRoException) and e.http_code == 404: # not found
1232 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
1233 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
1234 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
garciadeblas5697b8b2021-03-24 09:17:02 +01001235 self.logger.debug(
1236 logging_text + "RO_action_id={} already deleted".format(action_id)
1237 )
tierno69f0d382020-05-07 13:08:09 +00001238 elif isinstance(e, NgRoException) and e.http_code == 409: # conflict
1239 failed_detail.append("delete conflict: {}".format(e))
garciadeblas5697b8b2021-03-24 09:17:02 +01001240 self.logger.debug(
1241 logging_text
1242 + "RO_action_id={} delete conflict: {}".format(action_id, e)
1243 )
tierno69f0d382020-05-07 13:08:09 +00001244 else:
1245 failed_detail.append("delete error: {}".format(e))
garciadeblas5697b8b2021-03-24 09:17:02 +01001246 self.logger.error(
1247 logging_text
1248 + "RO_action_id={} delete error: {}".format(action_id, e)
1249 )
tierno69f0d382020-05-07 13:08:09 +00001250
1251 if failed_detail:
1252 stage[2] = "Error deleting from VIM"
1253 else:
1254 stage[2] = "Deleted from VIM"
1255 db_nsr_update["detailed-status"] = " ".join(stage)
1256 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1257 self._write_op_status(nslcmop_id, stage)
1258
1259 if failed_detail:
1260 raise LcmException("; ".join(failed_detail))
1261 return
1262
garciadeblas5697b8b2021-03-24 09:17:02 +01001263 async def instantiate_RO(
1264 self,
1265 logging_text,
1266 nsr_id,
1267 nsd,
1268 db_nsr,
1269 db_nslcmop,
1270 db_vnfrs,
1271 db_vnfds,
1272 n2vc_key_list,
1273 stage,
1274 ):
tiernoe95ed362020-04-23 08:24:57 +00001275 """
1276 Instantiate at RO
1277 :param logging_text: preffix text to use at logging
1278 :param nsr_id: nsr identity
1279 :param nsd: database content of ns descriptor
1280 :param db_nsr: database content of ns record
1281 :param db_nslcmop: database content of ns operation, in this case, 'instantiate'
1282 :param db_vnfrs:
bravof922c4172020-11-24 21:21:43 -03001283 :param db_vnfds: database content of vnfds, indexed by id (not _id). {id: {vnfd_object}, ...}
tiernoe95ed362020-04-23 08:24:57 +00001284 :param n2vc_key_list: ssh-public-key list to be inserted to management vdus via cloud-init
1285 :param stage: list with 3 items: [general stage, tasks, vim_specific]. This task will write over vim_specific
1286 :return: None or exception
1287 """
tiernoe876f672020-02-13 14:34:48 +00001288 try:
tiernoe876f672020-02-13 14:34:48 +00001289 start_deploy = time()
1290 ns_params = db_nslcmop.get("operationParams")
1291 if ns_params and ns_params.get("timeout_ns_deploy"):
1292 timeout_ns_deploy = ns_params["timeout_ns_deploy"]
1293 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001294 timeout_ns_deploy = self.timeout.get(
1295 "ns_deploy", self.timeout_ns_deploy
1296 )
quilesj7e13aeb2019-10-08 13:34:55 +02001297
tiernoe876f672020-02-13 14:34:48 +00001298 # Check for and optionally request placement optimization. Database will be updated if placement activated
1299 stage[2] = "Waiting for Placement."
tierno8790a3d2020-04-23 22:49:52 +00001300 if await self._do_placement(logging_text, db_nslcmop, db_vnfrs):
1301 # in case of placement change ns_params[vimAcountId) if not present at any vnfrs
1302 for vnfr in db_vnfrs.values():
1303 if ns_params["vimAccountId"] == vnfr["vim-account-id"]:
1304 break
1305 else:
1306 ns_params["vimAccountId"] == vnfr["vim-account-id"]
quilesj7e13aeb2019-10-08 13:34:55 +02001307
garciadeblas5697b8b2021-03-24 09:17:02 +01001308 return await self._instantiate_ng_ro(
1309 logging_text,
1310 nsr_id,
1311 nsd,
1312 db_nsr,
1313 db_nslcmop,
1314 db_vnfrs,
1315 db_vnfds,
1316 n2vc_key_list,
1317 stage,
1318 start_deploy,
1319 timeout_ns_deploy,
1320 )
tierno2357f4e2020-10-19 16:38:59 +00001321 except Exception as e:
tierno067e04a2020-03-31 12:53:13 +00001322 stage[2] = "ERROR deploying at VIM"
tiernoe876f672020-02-13 14:34:48 +00001323 self.set_vnfr_at_error(db_vnfrs, str(e))
garciadeblas5697b8b2021-03-24 09:17:02 +01001324 self.logger.error(
1325 "Error deploying at VIM {}".format(e),
1326 exc_info=not isinstance(
1327 e,
1328 (
1329 ROclient.ROClientException,
1330 LcmException,
1331 DbException,
1332 NgRoException,
1333 ),
1334 ),
1335 )
tiernoe876f672020-02-13 14:34:48 +00001336 raise
quilesj7e13aeb2019-10-08 13:34:55 +02001337
tierno7ecbc342020-09-21 14:05:39 +00001338 async def wait_kdu_up(self, logging_text, nsr_id, vnfr_id, kdu_name):
1339 """
1340 Wait for kdu to be up, get ip address
1341 :param logging_text: prefix use for logging
1342 :param nsr_id:
1343 :param vnfr_id:
1344 :param kdu_name:
1345 :return: IP address
1346 """
1347
1348 # self.logger.debug(logging_text + "Starting wait_kdu_up")
1349 nb_tries = 0
1350
1351 while nb_tries < 360:
1352 db_vnfr = self.db.get_one("vnfrs", {"_id": vnfr_id})
garciadeblas5697b8b2021-03-24 09:17:02 +01001353 kdur = next(
1354 (
1355 x
1356 for x in get_iterable(db_vnfr, "kdur")
1357 if x.get("kdu-name") == kdu_name
1358 ),
1359 None,
1360 )
tierno7ecbc342020-09-21 14:05:39 +00001361 if not kdur:
garciadeblas5697b8b2021-03-24 09:17:02 +01001362 raise LcmException(
1363 "Not found vnfr_id={}, kdu_name={}".format(vnfr_id, kdu_name)
1364 )
tierno7ecbc342020-09-21 14:05:39 +00001365 if kdur.get("status"):
1366 if kdur["status"] in ("READY", "ENABLED"):
1367 return kdur.get("ip-address")
1368 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001369 raise LcmException(
1370 "target KDU={} is in error state".format(kdu_name)
1371 )
tierno7ecbc342020-09-21 14:05:39 +00001372
1373 await asyncio.sleep(10, loop=self.loop)
1374 nb_tries += 1
1375 raise LcmException("Timeout waiting KDU={} instantiated".format(kdu_name))
1376
garciadeblas5697b8b2021-03-24 09:17:02 +01001377 async def wait_vm_up_insert_key_ro(
1378 self, logging_text, nsr_id, vnfr_id, vdu_id, vdu_index, pub_key=None, user=None
1379 ):
tiernoa5088192019-11-26 16:12:53 +00001380 """
1381 Wait for ip addres at RO, and optionally, insert public key in virtual machine
1382 :param logging_text: prefix use for logging
1383 :param nsr_id:
1384 :param vnfr_id:
1385 :param vdu_id:
1386 :param vdu_index:
1387 :param pub_key: public ssh key to inject, None to skip
1388 :param user: user to apply the public ssh key
1389 :return: IP address
1390 """
quilesj7e13aeb2019-10-08 13:34:55 +02001391
tierno2357f4e2020-10-19 16:38:59 +00001392 self.logger.debug(logging_text + "Starting wait_vm_up_insert_key_ro")
tiernod8323042019-08-09 11:32:23 +00001393 ro_nsr_id = None
1394 ip_address = None
1395 nb_tries = 0
1396 target_vdu_id = None
quilesj3149f262019-12-03 10:58:10 +00001397 ro_retries = 0
quilesj7e13aeb2019-10-08 13:34:55 +02001398
tiernod8323042019-08-09 11:32:23 +00001399 while True:
quilesj7e13aeb2019-10-08 13:34:55 +02001400
quilesj3149f262019-12-03 10:58:10 +00001401 ro_retries += 1
1402 if ro_retries >= 360: # 1 hour
garciadeblas5697b8b2021-03-24 09:17:02 +01001403 raise LcmException(
1404 "Not found _admin.deployed.RO.nsr_id for nsr_id: {}".format(nsr_id)
1405 )
quilesj3149f262019-12-03 10:58:10 +00001406
tiernod8323042019-08-09 11:32:23 +00001407 await asyncio.sleep(10, loop=self.loop)
quilesj7e13aeb2019-10-08 13:34:55 +02001408
1409 # get ip address
tiernod8323042019-08-09 11:32:23 +00001410 if not target_vdu_id:
1411 db_vnfr = self.db.get_one("vnfrs", {"_id": vnfr_id})
quilesj3149f262019-12-03 10:58:10 +00001412
1413 if not vdu_id: # for the VNF case
tiernoe876f672020-02-13 14:34:48 +00001414 if db_vnfr.get("status") == "ERROR":
garciadeblas5697b8b2021-03-24 09:17:02 +01001415 raise LcmException(
1416 "Cannot inject ssh-key because target VNF is in error state"
1417 )
tiernod8323042019-08-09 11:32:23 +00001418 ip_address = db_vnfr.get("ip-address")
1419 if not ip_address:
1420 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01001421 vdur = next(
1422 (
1423 x
1424 for x in get_iterable(db_vnfr, "vdur")
1425 if x.get("ip-address") == ip_address
1426 ),
1427 None,
1428 )
quilesj3149f262019-12-03 10:58:10 +00001429 else: # VDU case
garciadeblas5697b8b2021-03-24 09:17:02 +01001430 vdur = next(
1431 (
1432 x
1433 for x in get_iterable(db_vnfr, "vdur")
1434 if x.get("vdu-id-ref") == vdu_id
1435 and x.get("count-index") == vdu_index
1436 ),
1437 None,
1438 )
quilesj3149f262019-12-03 10:58:10 +00001439
garciadeblas5697b8b2021-03-24 09:17:02 +01001440 if (
1441 not vdur and len(db_vnfr.get("vdur", ())) == 1
1442 ): # If only one, this should be the target vdu
tierno0e8c3f02020-03-12 17:18:21 +00001443 vdur = db_vnfr["vdur"][0]
quilesj3149f262019-12-03 10:58:10 +00001444 if not vdur:
garciadeblas5697b8b2021-03-24 09:17:02 +01001445 raise LcmException(
1446 "Not found vnfr_id={}, vdu_id={}, vdu_index={}".format(
1447 vnfr_id, vdu_id, vdu_index
1448 )
1449 )
tierno2357f4e2020-10-19 16:38:59 +00001450 # New generation RO stores information at "vim_info"
1451 ng_ro_status = None
David Garciaa8bbe672020-11-19 13:06:54 +01001452 target_vim = None
tierno2357f4e2020-10-19 16:38:59 +00001453 if vdur.get("vim_info"):
garciadeblas5697b8b2021-03-24 09:17:02 +01001454 target_vim = next(
1455 t for t in vdur["vim_info"]
1456 ) # there should be only one key
tierno2357f4e2020-10-19 16:38:59 +00001457 ng_ro_status = vdur["vim_info"][target_vim].get("vim_status")
garciadeblas5697b8b2021-03-24 09:17:02 +01001458 if (
1459 vdur.get("pdu-type")
1460 or vdur.get("status") == "ACTIVE"
1461 or ng_ro_status == "ACTIVE"
1462 ):
quilesj3149f262019-12-03 10:58:10 +00001463 ip_address = vdur.get("ip-address")
1464 if not ip_address:
1465 continue
1466 target_vdu_id = vdur["vdu-id-ref"]
bravof922c4172020-11-24 21:21:43 -03001467 elif vdur.get("status") == "ERROR" or ng_ro_status == "ERROR":
garciadeblas5697b8b2021-03-24 09:17:02 +01001468 raise LcmException(
1469 "Cannot inject ssh-key because target VM is in error state"
1470 )
quilesj3149f262019-12-03 10:58:10 +00001471
tiernod8323042019-08-09 11:32:23 +00001472 if not target_vdu_id:
1473 continue
tiernod8323042019-08-09 11:32:23 +00001474
quilesj7e13aeb2019-10-08 13:34:55 +02001475 # inject public key into machine
1476 if pub_key and user:
tierno2357f4e2020-10-19 16:38:59 +00001477 self.logger.debug(logging_text + "Inserting RO key")
bravof922c4172020-11-24 21:21:43 -03001478 self.logger.debug("SSH > PubKey > {}".format(pub_key))
tierno0e8c3f02020-03-12 17:18:21 +00001479 if vdur.get("pdu-type"):
1480 self.logger.error(logging_text + "Cannot inject ssh-ky to a PDU")
1481 return ip_address
quilesj7e13aeb2019-10-08 13:34:55 +02001482 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01001483 ro_vm_id = "{}-{}".format(
1484 db_vnfr["member-vnf-index-ref"], target_vdu_id
1485 ) # TODO add vdu_index
tierno69f0d382020-05-07 13:08:09 +00001486 if self.ng_ro:
garciadeblas5697b8b2021-03-24 09:17:02 +01001487 target = {
1488 "action": {
1489 "action": "inject_ssh_key",
1490 "key": pub_key,
1491 "user": user,
1492 },
1493 "vnf": [{"_id": vnfr_id, "vdur": [{"id": vdur["id"]}]}],
1494 }
tierno2357f4e2020-10-19 16:38:59 +00001495 desc = await self.RO.deploy(nsr_id, target)
1496 action_id = desc["action_id"]
1497 await self._wait_ng_ro(nsr_id, action_id, timeout=600)
1498 break
tierno69f0d382020-05-07 13:08:09 +00001499 else:
tierno2357f4e2020-10-19 16:38:59 +00001500 # wait until NS is deployed at RO
1501 if not ro_nsr_id:
1502 db_nsrs = self.db.get_one("nsrs", {"_id": nsr_id})
garciadeblas5697b8b2021-03-24 09:17:02 +01001503 ro_nsr_id = deep_get(
1504 db_nsrs, ("_admin", "deployed", "RO", "nsr_id")
1505 )
tierno2357f4e2020-10-19 16:38:59 +00001506 if not ro_nsr_id:
1507 continue
tierno69f0d382020-05-07 13:08:09 +00001508 result_dict = await self.RO.create_action(
1509 item="ns",
1510 item_id_name=ro_nsr_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01001511 descriptor={
1512 "add_public_key": pub_key,
1513 "vms": [ro_vm_id],
1514 "user": user,
1515 },
tierno69f0d382020-05-07 13:08:09 +00001516 )
1517 # result_dict contains the format {VM-id: {vim_result: 200, description: text}}
1518 if not result_dict or not isinstance(result_dict, dict):
garciadeblas5697b8b2021-03-24 09:17:02 +01001519 raise LcmException(
1520 "Unknown response from RO when injecting key"
1521 )
tierno69f0d382020-05-07 13:08:09 +00001522 for result in result_dict.values():
1523 if result.get("vim_result") == 200:
1524 break
1525 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001526 raise ROclient.ROClientException(
1527 "error injecting key: {}".format(
1528 result.get("description")
1529 )
1530 )
tierno69f0d382020-05-07 13:08:09 +00001531 break
1532 except NgRoException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001533 raise LcmException(
1534 "Reaching max tries injecting key. Error: {}".format(e)
1535 )
quilesj7e13aeb2019-10-08 13:34:55 +02001536 except ROclient.ROClientException as e:
tiernoa5088192019-11-26 16:12:53 +00001537 if not nb_tries:
garciadeblas5697b8b2021-03-24 09:17:02 +01001538 self.logger.debug(
1539 logging_text
1540 + "error injecting key: {}. Retrying until {} seconds".format(
1541 e, 20 * 10
1542 )
1543 )
quilesj7e13aeb2019-10-08 13:34:55 +02001544 nb_tries += 1
tiernoa5088192019-11-26 16:12:53 +00001545 if nb_tries >= 20:
garciadeblas5697b8b2021-03-24 09:17:02 +01001546 raise LcmException(
1547 "Reaching max tries injecting key. Error: {}".format(e)
1548 )
quilesj7e13aeb2019-10-08 13:34:55 +02001549 else:
quilesj7e13aeb2019-10-08 13:34:55 +02001550 break
1551
1552 return ip_address
1553
tierno5ee02052019-12-05 19:55:02 +00001554 async def _wait_dependent_n2vc(self, nsr_id, vca_deployed_list, vca_index):
1555 """
1556 Wait until dependent VCA deployments have been finished. NS wait for VNFs and VDUs. VNFs for VDUs
1557 """
1558 my_vca = vca_deployed_list[vca_index]
1559 if my_vca.get("vdu_id") or my_vca.get("kdu_name"):
quilesj3655ae02019-12-12 16:08:35 +00001560 # vdu or kdu: no dependencies
tierno5ee02052019-12-05 19:55:02 +00001561 return
1562 timeout = 300
1563 while timeout >= 0:
quilesj3655ae02019-12-12 16:08:35 +00001564 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1565 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
1566 configuration_status_list = db_nsr["configurationStatus"]
1567 for index, vca_deployed in enumerate(configuration_status_list):
tierno5ee02052019-12-05 19:55:02 +00001568 if index == vca_index:
quilesj3655ae02019-12-12 16:08:35 +00001569 # myself
tierno5ee02052019-12-05 19:55:02 +00001570 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01001571 if not my_vca.get("member-vnf-index") or (
1572 vca_deployed.get("member-vnf-index")
1573 == my_vca.get("member-vnf-index")
1574 ):
quilesj3655ae02019-12-12 16:08:35 +00001575 internal_status = configuration_status_list[index].get("status")
garciadeblas5697b8b2021-03-24 09:17:02 +01001576 if internal_status == "READY":
quilesj3655ae02019-12-12 16:08:35 +00001577 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01001578 elif internal_status == "BROKEN":
1579 raise LcmException(
1580 "Configuration aborted because dependent charm/s has failed"
1581 )
quilesj3655ae02019-12-12 16:08:35 +00001582 else:
1583 break
tierno5ee02052019-12-05 19:55:02 +00001584 else:
quilesj3655ae02019-12-12 16:08:35 +00001585 # no dependencies, return
tierno5ee02052019-12-05 19:55:02 +00001586 return
1587 await asyncio.sleep(10)
1588 timeout -= 1
tierno5ee02052019-12-05 19:55:02 +00001589
1590 raise LcmException("Configuration aborted because dependent charm/s timeout")
1591
David Garciac1fe90a2021-03-31 19:12:02 +02001592 def get_vca_id(self, db_vnfr: dict, db_nsr: dict):
David Garcia0b2b1882021-10-21 17:03:48 +02001593 vca_id = None
1594 if db_vnfr:
1595 vca_id = deep_get(db_vnfr, ("vca-id",))
1596 elif db_nsr:
1597 vim_account_id = deep_get(db_nsr, ("instantiate_params", "vimAccountId"))
1598 vca_id = VimAccountDB.get_vim_account_with_id(vim_account_id).get("vca")
1599 return vca_id
David Garciac1fe90a2021-03-31 19:12:02 +02001600
garciadeblas5697b8b2021-03-24 09:17:02 +01001601 async def instantiate_N2VC(
1602 self,
1603 logging_text,
1604 vca_index,
1605 nsi_id,
1606 db_nsr,
1607 db_vnfr,
1608 vdu_id,
1609 kdu_name,
1610 vdu_index,
1611 config_descriptor,
1612 deploy_params,
1613 base_folder,
1614 nslcmop_id,
1615 stage,
1616 vca_type,
1617 vca_name,
1618 ee_config_descriptor,
1619 ):
tiernod8323042019-08-09 11:32:23 +00001620 nsr_id = db_nsr["_id"]
1621 db_update_entry = "_admin.deployed.VCA.{}.".format(vca_index)
tiernoda6fb102019-11-23 00:36:52 +00001622 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
tiernod8323042019-08-09 11:32:23 +00001623 vca_deployed = db_nsr["_admin"]["deployed"]["VCA"][vca_index]
tiernob996d942020-07-03 14:52:28 +00001624 osm_config = {"osm": {"ns_id": db_nsr["_id"]}}
quilesj7e13aeb2019-10-08 13:34:55 +02001625 db_dict = {
garciadeblas5697b8b2021-03-24 09:17:02 +01001626 "collection": "nsrs",
1627 "filter": {"_id": nsr_id},
1628 "path": db_update_entry,
quilesj7e13aeb2019-10-08 13:34:55 +02001629 }
tiernod8323042019-08-09 11:32:23 +00001630 step = ""
1631 try:
quilesj3655ae02019-12-12 16:08:35 +00001632
garciadeblas5697b8b2021-03-24 09:17:02 +01001633 element_type = "NS"
quilesj3655ae02019-12-12 16:08:35 +00001634 element_under_configuration = nsr_id
1635
tiernod8323042019-08-09 11:32:23 +00001636 vnfr_id = None
1637 if db_vnfr:
1638 vnfr_id = db_vnfr["_id"]
tiernob996d942020-07-03 14:52:28 +00001639 osm_config["osm"]["vnf_id"] = vnfr_id
tiernod8323042019-08-09 11:32:23 +00001640
garciadeblas5697b8b2021-03-24 09:17:02 +01001641 namespace = "{nsi}.{ns}".format(nsi=nsi_id if nsi_id else "", ns=nsr_id)
quilesj3655ae02019-12-12 16:08:35 +00001642
aktas730569b2021-07-29 17:42:49 +03001643 if vca_type == "native_charm":
1644 index_number = 0
1645 else:
1646 index_number = vdu_index or 0
1647
tiernod8323042019-08-09 11:32:23 +00001648 if vnfr_id:
garciadeblas5697b8b2021-03-24 09:17:02 +01001649 element_type = "VNF"
quilesj3655ae02019-12-12 16:08:35 +00001650 element_under_configuration = vnfr_id
aktas730569b2021-07-29 17:42:49 +03001651 namespace += ".{}-{}".format(vnfr_id, index_number)
tiernod8323042019-08-09 11:32:23 +00001652 if vdu_id:
aktas730569b2021-07-29 17:42:49 +03001653 namespace += ".{}-{}".format(vdu_id, index_number)
garciadeblas5697b8b2021-03-24 09:17:02 +01001654 element_type = "VDU"
aktas730569b2021-07-29 17:42:49 +03001655 element_under_configuration = "{}-{}".format(vdu_id, index_number)
tiernob996d942020-07-03 14:52:28 +00001656 osm_config["osm"]["vdu_id"] = vdu_id
tierno51183952020-04-03 15:48:18 +00001657 elif kdu_name:
aktas730569b2021-07-29 17:42:49 +03001658 namespace += ".{}".format(kdu_name)
garciadeblas5697b8b2021-03-24 09:17:02 +01001659 element_type = "KDU"
tierno51183952020-04-03 15:48:18 +00001660 element_under_configuration = kdu_name
tiernob996d942020-07-03 14:52:28 +00001661 osm_config["osm"]["kdu_name"] = kdu_name
tiernod8323042019-08-09 11:32:23 +00001662
1663 # Get artifact path
tierno588547c2020-07-01 15:30:20 +00001664 artifact_path = "{}/{}/{}/{}".format(
tiernod8323042019-08-09 11:32:23 +00001665 base_folder["folder"],
1666 base_folder["pkg-dir"],
garciadeblas5697b8b2021-03-24 09:17:02 +01001667 "charms"
1668 if vca_type in ("native_charm", "lxc_proxy_charm", "k8s_proxy_charm")
1669 else "helm-charts",
1670 vca_name,
tiernod8323042019-08-09 11:32:23 +00001671 )
bravof922c4172020-11-24 21:21:43 -03001672
1673 self.logger.debug("Artifact path > {}".format(artifact_path))
1674
tiernoa278b842020-07-08 15:33:55 +00001675 # get initial_config_primitive_list that applies to this element
garciadeblas5697b8b2021-03-24 09:17:02 +01001676 initial_config_primitive_list = config_descriptor.get(
1677 "initial-config-primitive"
1678 )
tiernoa278b842020-07-08 15:33:55 +00001679
garciadeblas5697b8b2021-03-24 09:17:02 +01001680 self.logger.debug(
1681 "Initial config primitive list > {}".format(
1682 initial_config_primitive_list
1683 )
1684 )
bravof922c4172020-11-24 21:21:43 -03001685
tiernoa278b842020-07-08 15:33:55 +00001686 # add config if not present for NS charm
1687 ee_descriptor_id = ee_config_descriptor.get("id")
bravof922c4172020-11-24 21:21:43 -03001688 self.logger.debug("EE Descriptor > {}".format(ee_descriptor_id))
garciadeblas5697b8b2021-03-24 09:17:02 +01001689 initial_config_primitive_list = get_ee_sorted_initial_config_primitive_list(
1690 initial_config_primitive_list, vca_deployed, ee_descriptor_id
1691 )
tiernod8323042019-08-09 11:32:23 +00001692
garciadeblas5697b8b2021-03-24 09:17:02 +01001693 self.logger.debug(
1694 "Initial config primitive list #2 > {}".format(
1695 initial_config_primitive_list
1696 )
1697 )
tierno588547c2020-07-01 15:30:20 +00001698 # n2vc_redesign STEP 3.1
tierno588547c2020-07-01 15:30:20 +00001699 # find old ee_id if exists
1700 ee_id = vca_deployed.get("ee_id")
tiernod8323042019-08-09 11:32:23 +00001701
David Garciac1fe90a2021-03-31 19:12:02 +02001702 vca_id = self.get_vca_id(db_vnfr, db_nsr)
tierno588547c2020-07-01 15:30:20 +00001703 # create or register execution environment in VCA
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001704 if vca_type in ("lxc_proxy_charm", "k8s_proxy_charm", "helm", "helm-v3"):
quilesj7e13aeb2019-10-08 13:34:55 +02001705
tierno588547c2020-07-01 15:30:20 +00001706 self._write_configuration_status(
1707 nsr_id=nsr_id,
1708 vca_index=vca_index,
garciadeblas5697b8b2021-03-24 09:17:02 +01001709 status="CREATING",
tierno588547c2020-07-01 15:30:20 +00001710 element_under_configuration=element_under_configuration,
garciadeblas5697b8b2021-03-24 09:17:02 +01001711 element_type=element_type,
tierno588547c2020-07-01 15:30:20 +00001712 )
tiernod8323042019-08-09 11:32:23 +00001713
tierno588547c2020-07-01 15:30:20 +00001714 step = "create execution environment"
garciadeblas5697b8b2021-03-24 09:17:02 +01001715 self.logger.debug(logging_text + step)
David Garciaaae391f2020-11-09 11:12:54 +01001716
1717 ee_id = None
1718 credentials = None
1719 if vca_type == "k8s_proxy_charm":
1720 ee_id = await self.vca_map[vca_type].install_k8s_proxy_charm(
garciadeblas5697b8b2021-03-24 09:17:02 +01001721 charm_name=artifact_path[artifact_path.rfind("/") + 1 :],
David Garciaaae391f2020-11-09 11:12:54 +01001722 namespace=namespace,
1723 artifact_path=artifact_path,
1724 db_dict=db_dict,
David Garciac1fe90a2021-03-31 19:12:02 +02001725 vca_id=vca_id,
David Garciaaae391f2020-11-09 11:12:54 +01001726 )
garciadeblas5697b8b2021-03-24 09:17:02 +01001727 elif vca_type == "helm" or vca_type == "helm-v3":
1728 ee_id, credentials = await self.vca_map[
1729 vca_type
1730 ].create_execution_environment(
bravof922c4172020-11-24 21:21:43 -03001731 namespace=namespace,
1732 reuse_ee_id=ee_id,
1733 db_dict=db_dict,
lloretgalleg18cb3cb2020-12-10 14:21:10 +00001734 config=osm_config,
1735 artifact_path=artifact_path,
garciadeblas5697b8b2021-03-24 09:17:02 +01001736 vca_type=vca_type,
bravof922c4172020-11-24 21:21:43 -03001737 )
garciadeblas5697b8b2021-03-24 09:17:02 +01001738 else:
1739 ee_id, credentials = await self.vca_map[
1740 vca_type
1741 ].create_execution_environment(
David Garciaaae391f2020-11-09 11:12:54 +01001742 namespace=namespace,
1743 reuse_ee_id=ee_id,
1744 db_dict=db_dict,
David Garciac1fe90a2021-03-31 19:12:02 +02001745 vca_id=vca_id,
David Garciaaae391f2020-11-09 11:12:54 +01001746 )
quilesj3655ae02019-12-12 16:08:35 +00001747
tierno588547c2020-07-01 15:30:20 +00001748 elif vca_type == "native_charm":
1749 step = "Waiting to VM being up and getting IP address"
1750 self.logger.debug(logging_text + step)
garciadeblas5697b8b2021-03-24 09:17:02 +01001751 rw_mgmt_ip = await self.wait_vm_up_insert_key_ro(
1752 logging_text,
1753 nsr_id,
1754 vnfr_id,
1755 vdu_id,
1756 vdu_index,
1757 user=None,
1758 pub_key=None,
1759 )
tierno588547c2020-07-01 15:30:20 +00001760 credentials = {"hostname": rw_mgmt_ip}
1761 # get username
garciadeblas5697b8b2021-03-24 09:17:02 +01001762 username = deep_get(
1763 config_descriptor, ("config-access", "ssh-access", "default-user")
1764 )
tierno588547c2020-07-01 15:30:20 +00001765 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1766 # merged. Meanwhile let's get username from initial-config-primitive
tiernoa278b842020-07-08 15:33:55 +00001767 if not username and initial_config_primitive_list:
1768 for config_primitive in initial_config_primitive_list:
tierno588547c2020-07-01 15:30:20 +00001769 for param in config_primitive.get("parameter", ()):
1770 if param["name"] == "ssh-username":
1771 username = param["value"]
1772 break
1773 if not username:
garciadeblas5697b8b2021-03-24 09:17:02 +01001774 raise LcmException(
1775 "Cannot determine the username neither with 'initial-config-primitive' nor with "
1776 "'config-access.ssh-access.default-user'"
1777 )
tierno588547c2020-07-01 15:30:20 +00001778 credentials["username"] = username
1779 # n2vc_redesign STEP 3.2
quilesj3655ae02019-12-12 16:08:35 +00001780
tierno588547c2020-07-01 15:30:20 +00001781 self._write_configuration_status(
1782 nsr_id=nsr_id,
1783 vca_index=vca_index,
garciadeblas5697b8b2021-03-24 09:17:02 +01001784 status="REGISTERING",
tierno588547c2020-07-01 15:30:20 +00001785 element_under_configuration=element_under_configuration,
garciadeblas5697b8b2021-03-24 09:17:02 +01001786 element_type=element_type,
tierno588547c2020-07-01 15:30:20 +00001787 )
quilesj3655ae02019-12-12 16:08:35 +00001788
tierno588547c2020-07-01 15:30:20 +00001789 step = "register execution environment {}".format(credentials)
1790 self.logger.debug(logging_text + step)
1791 ee_id = await self.vca_map[vca_type].register_execution_environment(
David Garciaaae391f2020-11-09 11:12:54 +01001792 credentials=credentials,
1793 namespace=namespace,
1794 db_dict=db_dict,
David Garciac1fe90a2021-03-31 19:12:02 +02001795 vca_id=vca_id,
David Garciaaae391f2020-11-09 11:12:54 +01001796 )
tierno3bedc9b2019-11-27 15:46:57 +00001797
tierno588547c2020-07-01 15:30:20 +00001798 # for compatibility with MON/POL modules, the need model and application name at database
1799 # TODO ask MON/POL if needed to not assuming anymore the format "model_name.application_name"
garciadeblas5697b8b2021-03-24 09:17:02 +01001800 ee_id_parts = ee_id.split(".")
tierno588547c2020-07-01 15:30:20 +00001801 db_nsr_update = {db_update_entry + "ee_id": ee_id}
1802 if len(ee_id_parts) >= 2:
1803 model_name = ee_id_parts[0]
1804 application_name = ee_id_parts[1]
1805 db_nsr_update[db_update_entry + "model"] = model_name
1806 db_nsr_update[db_update_entry + "application"] = application_name
tiernod8323042019-08-09 11:32:23 +00001807
1808 # n2vc_redesign STEP 3.3
tiernod8323042019-08-09 11:32:23 +00001809 step = "Install configuration Software"
quilesj3655ae02019-12-12 16:08:35 +00001810
tiernoc231a872020-01-21 08:49:05 +00001811 self._write_configuration_status(
quilesj3655ae02019-12-12 16:08:35 +00001812 nsr_id=nsr_id,
1813 vca_index=vca_index,
garciadeblas5697b8b2021-03-24 09:17:02 +01001814 status="INSTALLING SW",
quilesj3655ae02019-12-12 16:08:35 +00001815 element_under_configuration=element_under_configuration,
tierno51183952020-04-03 15:48:18 +00001816 element_type=element_type,
garciadeblas5697b8b2021-03-24 09:17:02 +01001817 other_update=db_nsr_update,
quilesj3655ae02019-12-12 16:08:35 +00001818 )
1819
tierno3bedc9b2019-11-27 15:46:57 +00001820 # TODO check if already done
quilesj7e13aeb2019-10-08 13:34:55 +02001821 self.logger.debug(logging_text + step)
David Garcia18a63322020-04-01 16:14:59 +02001822 config = None
tierno588547c2020-07-01 15:30:20 +00001823 if vca_type == "native_charm":
garciadeblas5697b8b2021-03-24 09:17:02 +01001824 config_primitive = next(
1825 (p for p in initial_config_primitive_list if p["name"] == "config"),
1826 None,
1827 )
tiernoa278b842020-07-08 15:33:55 +00001828 if config_primitive:
1829 config = self._map_primitive_params(
garciadeblas5697b8b2021-03-24 09:17:02 +01001830 config_primitive, {}, deploy_params
tiernoa278b842020-07-08 15:33:55 +00001831 )
tierno588547c2020-07-01 15:30:20 +00001832 num_units = 1
1833 if vca_type == "lxc_proxy_charm":
1834 if element_type == "NS":
1835 num_units = db_nsr.get("config-units") or 1
1836 elif element_type == "VNF":
1837 num_units = db_vnfr.get("config-units") or 1
1838 elif element_type == "VDU":
1839 for v in db_vnfr["vdur"]:
1840 if vdu_id == v["vdu-id-ref"]:
1841 num_units = v.get("config-units") or 1
1842 break
David Garciaaae391f2020-11-09 11:12:54 +01001843 if vca_type != "k8s_proxy_charm":
1844 await self.vca_map[vca_type].install_configuration_sw(
1845 ee_id=ee_id,
1846 artifact_path=artifact_path,
1847 db_dict=db_dict,
1848 config=config,
1849 num_units=num_units,
David Garciac1fe90a2021-03-31 19:12:02 +02001850 vca_id=vca_id,
aktas730569b2021-07-29 17:42:49 +03001851 vca_type=vca_type,
David Garciaaae391f2020-11-09 11:12:54 +01001852 )
quilesj7e13aeb2019-10-08 13:34:55 +02001853
quilesj63f90042020-01-17 09:53:55 +00001854 # write in db flag of configuration_sw already installed
garciadeblas5697b8b2021-03-24 09:17:02 +01001855 self.update_db_2(
1856 "nsrs", nsr_id, {db_update_entry + "config_sw_installed": True}
1857 )
quilesj63f90042020-01-17 09:53:55 +00001858
1859 # add relations for this VCA (wait for other peers related with this VCA)
garciadeblas5697b8b2021-03-24 09:17:02 +01001860 await self._add_vca_relations(
1861 logging_text=logging_text,
1862 nsr_id=nsr_id,
1863 vca_index=vca_index,
1864 vca_id=vca_id,
1865 vca_type=vca_type,
1866 )
quilesj63f90042020-01-17 09:53:55 +00001867
quilesj7e13aeb2019-10-08 13:34:55 +02001868 # if SSH access is required, then get execution environment SSH public
David Garciaa27e20a2020-07-10 13:12:44 +02001869 # if native charm we have waited already to VM be UP
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001870 if vca_type in ("k8s_proxy_charm", "lxc_proxy_charm", "helm", "helm-v3"):
tierno3bedc9b2019-11-27 15:46:57 +00001871 pub_key = None
1872 user = None
tierno588547c2020-07-01 15:30:20 +00001873 # self.logger.debug("get ssh key block")
garciadeblas5697b8b2021-03-24 09:17:02 +01001874 if deep_get(
1875 config_descriptor, ("config-access", "ssh-access", "required")
1876 ):
tierno588547c2020-07-01 15:30:20 +00001877 # self.logger.debug("ssh key needed")
tierno3bedc9b2019-11-27 15:46:57 +00001878 # Needed to inject a ssh key
garciadeblas5697b8b2021-03-24 09:17:02 +01001879 user = deep_get(
1880 config_descriptor,
1881 ("config-access", "ssh-access", "default-user"),
1882 )
tierno3bedc9b2019-11-27 15:46:57 +00001883 step = "Install configuration Software, getting public ssh key"
David Garciac1fe90a2021-03-31 19:12:02 +02001884 pub_key = await self.vca_map[vca_type].get_ee_ssh_public__key(
garciadeblas5697b8b2021-03-24 09:17:02 +01001885 ee_id=ee_id, db_dict=db_dict, vca_id=vca_id
David Garciac1fe90a2021-03-31 19:12:02 +02001886 )
quilesj7e13aeb2019-10-08 13:34:55 +02001887
garciadeblas5697b8b2021-03-24 09:17:02 +01001888 step = "Insert public key into VM user={} ssh_key={}".format(
1889 user, pub_key
1890 )
tierno3bedc9b2019-11-27 15:46:57 +00001891 else:
tierno588547c2020-07-01 15:30:20 +00001892 # self.logger.debug("no need to get ssh key")
tierno3bedc9b2019-11-27 15:46:57 +00001893 step = "Waiting to VM being up and getting IP address"
1894 self.logger.debug(logging_text + step)
quilesj7e13aeb2019-10-08 13:34:55 +02001895
tierno3bedc9b2019-11-27 15:46:57 +00001896 # n2vc_redesign STEP 5.1
1897 # wait for RO (ip-address) Insert pub_key into VM
tierno5ee02052019-12-05 19:55:02 +00001898 if vnfr_id:
tierno7ecbc342020-09-21 14:05:39 +00001899 if kdu_name:
garciadeblas5697b8b2021-03-24 09:17:02 +01001900 rw_mgmt_ip = await self.wait_kdu_up(
1901 logging_text, nsr_id, vnfr_id, kdu_name
1902 )
tierno7ecbc342020-09-21 14:05:39 +00001903 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001904 rw_mgmt_ip = await self.wait_vm_up_insert_key_ro(
1905 logging_text,
1906 nsr_id,
1907 vnfr_id,
1908 vdu_id,
1909 vdu_index,
1910 user=user,
1911 pub_key=pub_key,
1912 )
tierno5ee02052019-12-05 19:55:02 +00001913 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001914 rw_mgmt_ip = None # This is for a NS configuration
tierno3bedc9b2019-11-27 15:46:57 +00001915
garciadeblas5697b8b2021-03-24 09:17:02 +01001916 self.logger.debug(logging_text + " VM_ip_address={}".format(rw_mgmt_ip))
quilesj7e13aeb2019-10-08 13:34:55 +02001917
tiernoa5088192019-11-26 16:12:53 +00001918 # store rw_mgmt_ip in deploy params for later replacement
quilesj7e13aeb2019-10-08 13:34:55 +02001919 deploy_params["rw_mgmt_ip"] = rw_mgmt_ip
tiernod8323042019-08-09 11:32:23 +00001920
1921 # n2vc_redesign STEP 6 Execute initial config primitive
garciadeblas5697b8b2021-03-24 09:17:02 +01001922 step = "execute initial config primitive"
quilesj3655ae02019-12-12 16:08:35 +00001923
1924 # wait for dependent primitives execution (NS -> VNF -> VDU)
tierno5ee02052019-12-05 19:55:02 +00001925 if initial_config_primitive_list:
1926 await self._wait_dependent_n2vc(nsr_id, vca_deployed_list, vca_index)
quilesj3655ae02019-12-12 16:08:35 +00001927
1928 # stage, in function of element type: vdu, kdu, vnf or ns
1929 my_vca = vca_deployed_list[vca_index]
1930 if my_vca.get("vdu_id") or my_vca.get("kdu_name"):
1931 # VDU or KDU
garciadeblas5697b8b2021-03-24 09:17:02 +01001932 stage[0] = "Stage 3/5: running Day-1 primitives for VDU."
quilesj3655ae02019-12-12 16:08:35 +00001933 elif my_vca.get("member-vnf-index"):
1934 # VNF
garciadeblas5697b8b2021-03-24 09:17:02 +01001935 stage[0] = "Stage 4/5: running Day-1 primitives for VNF."
quilesj3655ae02019-12-12 16:08:35 +00001936 else:
1937 # NS
garciadeblas5697b8b2021-03-24 09:17:02 +01001938 stage[0] = "Stage 5/5: running Day-1 primitives for NS."
quilesj3655ae02019-12-12 16:08:35 +00001939
tiernoc231a872020-01-21 08:49:05 +00001940 self._write_configuration_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01001941 nsr_id=nsr_id, vca_index=vca_index, status="EXECUTING PRIMITIVE"
quilesj3655ae02019-12-12 16:08:35 +00001942 )
1943
garciadeblas5697b8b2021-03-24 09:17:02 +01001944 self._write_op_status(op_id=nslcmop_id, stage=stage)
quilesj3655ae02019-12-12 16:08:35 +00001945
tiernoe876f672020-02-13 14:34:48 +00001946 check_if_terminated_needed = True
tiernod8323042019-08-09 11:32:23 +00001947 for initial_config_primitive in initial_config_primitive_list:
tiernoda6fb102019-11-23 00:36:52 +00001948 # adding information on the vca_deployed if it is a NS execution environment
1949 if not vca_deployed["member-vnf-index"]:
garciadeblas5697b8b2021-03-24 09:17:02 +01001950 deploy_params["ns_config_info"] = json.dumps(
1951 self._get_ns_config_info(nsr_id)
1952 )
tiernod8323042019-08-09 11:32:23 +00001953 # TODO check if already done
garciadeblas5697b8b2021-03-24 09:17:02 +01001954 primitive_params_ = self._map_primitive_params(
1955 initial_config_primitive, {}, deploy_params
1956 )
tierno3bedc9b2019-11-27 15:46:57 +00001957
garciadeblas5697b8b2021-03-24 09:17:02 +01001958 step = "execute primitive '{}' params '{}'".format(
1959 initial_config_primitive["name"], primitive_params_
1960 )
tiernod8323042019-08-09 11:32:23 +00001961 self.logger.debug(logging_text + step)
tierno588547c2020-07-01 15:30:20 +00001962 await self.vca_map[vca_type].exec_primitive(
quilesj7e13aeb2019-10-08 13:34:55 +02001963 ee_id=ee_id,
1964 primitive_name=initial_config_primitive["name"],
1965 params_dict=primitive_params_,
David Garciac1fe90a2021-03-31 19:12:02 +02001966 db_dict=db_dict,
1967 vca_id=vca_id,
aktas730569b2021-07-29 17:42:49 +03001968 vca_type=vca_type,
quilesj7e13aeb2019-10-08 13:34:55 +02001969 )
tiernoe876f672020-02-13 14:34:48 +00001970 # Once some primitive has been exec, check and write at db if it needs to exec terminated primitives
1971 if check_if_terminated_needed:
garciadeblas5697b8b2021-03-24 09:17:02 +01001972 if config_descriptor.get("terminate-config-primitive"):
1973 self.update_db_2(
1974 "nsrs", nsr_id, {db_update_entry + "needed_terminate": True}
1975 )
tiernoe876f672020-02-13 14:34:48 +00001976 check_if_terminated_needed = False
quilesj3655ae02019-12-12 16:08:35 +00001977
tiernod8323042019-08-09 11:32:23 +00001978 # TODO register in database that primitive is done
quilesj7e13aeb2019-10-08 13:34:55 +02001979
tiernob996d942020-07-03 14:52:28 +00001980 # STEP 7 Configure metrics
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001981 if vca_type == "helm" or vca_type == "helm-v3":
tiernob996d942020-07-03 14:52:28 +00001982 prometheus_jobs = await self.add_prometheus_metrics(
1983 ee_id=ee_id,
1984 artifact_path=artifact_path,
1985 ee_config_descriptor=ee_config_descriptor,
1986 vnfr_id=vnfr_id,
1987 nsr_id=nsr_id,
1988 target_ip=rw_mgmt_ip,
1989 )
1990 if prometheus_jobs:
garciadeblas5697b8b2021-03-24 09:17:02 +01001991 self.update_db_2(
1992 "nsrs",
1993 nsr_id,
1994 {db_update_entry + "prometheus_jobs": prometheus_jobs},
1995 )
tiernob996d942020-07-03 14:52:28 +00001996
quilesj7e13aeb2019-10-08 13:34:55 +02001997 step = "instantiated at VCA"
1998 self.logger.debug(logging_text + step)
1999
tiernoc231a872020-01-21 08:49:05 +00002000 self._write_configuration_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01002001 nsr_id=nsr_id, vca_index=vca_index, status="READY"
quilesj3655ae02019-12-12 16:08:35 +00002002 )
2003
tiernod8323042019-08-09 11:32:23 +00002004 except Exception as e: # TODO not use Exception but N2VC exception
quilesj3655ae02019-12-12 16:08:35 +00002005 # self.update_db_2("nsrs", nsr_id, {db_update_entry + "instantiation": "FAILED"})
garciadeblas5697b8b2021-03-24 09:17:02 +01002006 if not isinstance(
2007 e, (DbException, N2VCException, LcmException, asyncio.CancelledError)
2008 ):
2009 self.logger.error(
2010 "Exception while {} : {}".format(step, e), exc_info=True
2011 )
tiernoc231a872020-01-21 08:49:05 +00002012 self._write_configuration_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01002013 nsr_id=nsr_id, vca_index=vca_index, status="BROKEN"
quilesj3655ae02019-12-12 16:08:35 +00002014 )
tiernoe876f672020-02-13 14:34:48 +00002015 raise LcmException("{} {}".format(step, e)) from e
tiernod8323042019-08-09 11:32:23 +00002016
garciadeblas5697b8b2021-03-24 09:17:02 +01002017 def _write_ns_status(
2018 self,
2019 nsr_id: str,
2020 ns_state: str,
2021 current_operation: str,
2022 current_operation_id: str,
2023 error_description: str = None,
2024 error_detail: str = None,
2025 other_update: dict = None,
2026 ):
tiernoe876f672020-02-13 14:34:48 +00002027 """
2028 Update db_nsr fields.
2029 :param nsr_id:
2030 :param ns_state:
2031 :param current_operation:
2032 :param current_operation_id:
2033 :param error_description:
tiernoa2143262020-03-27 16:20:40 +00002034 :param error_detail:
tiernoe876f672020-02-13 14:34:48 +00002035 :param other_update: Other required changes at database if provided, will be cleared
2036 :return:
2037 """
quilesj4cda56b2019-12-05 10:02:20 +00002038 try:
tiernoe876f672020-02-13 14:34:48 +00002039 db_dict = other_update or {}
garciadeblas5697b8b2021-03-24 09:17:02 +01002040 db_dict[
2041 "_admin.nslcmop"
2042 ] = current_operation_id # for backward compatibility
tiernoe876f672020-02-13 14:34:48 +00002043 db_dict["_admin.current-operation"] = current_operation_id
garciadeblas5697b8b2021-03-24 09:17:02 +01002044 db_dict["_admin.operation-type"] = (
2045 current_operation if current_operation != "IDLE" else None
2046 )
quilesj4cda56b2019-12-05 10:02:20 +00002047 db_dict["currentOperation"] = current_operation
2048 db_dict["currentOperationID"] = current_operation_id
2049 db_dict["errorDescription"] = error_description
tiernoa2143262020-03-27 16:20:40 +00002050 db_dict["errorDetail"] = error_detail
tiernoe876f672020-02-13 14:34:48 +00002051
2052 if ns_state:
2053 db_dict["nsState"] = ns_state
quilesj4cda56b2019-12-05 10:02:20 +00002054 self.update_db_2("nsrs", nsr_id, db_dict)
tiernoe876f672020-02-13 14:34:48 +00002055 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002056 self.logger.warn("Error writing NS status, ns={}: {}".format(nsr_id, e))
quilesj3655ae02019-12-12 16:08:35 +00002057
garciadeblas5697b8b2021-03-24 09:17:02 +01002058 def _write_op_status(
2059 self,
2060 op_id: str,
2061 stage: list = None,
2062 error_message: str = None,
2063 queuePosition: int = 0,
2064 operation_state: str = None,
2065 other_update: dict = None,
2066 ):
quilesj3655ae02019-12-12 16:08:35 +00002067 try:
tiernoe876f672020-02-13 14:34:48 +00002068 db_dict = other_update or {}
garciadeblas5697b8b2021-03-24 09:17:02 +01002069 db_dict["queuePosition"] = queuePosition
tiernoe876f672020-02-13 14:34:48 +00002070 if isinstance(stage, list):
garciadeblas5697b8b2021-03-24 09:17:02 +01002071 db_dict["stage"] = stage[0]
2072 db_dict["detailed-status"] = " ".join(stage)
tiernoe876f672020-02-13 14:34:48 +00002073 elif stage is not None:
garciadeblas5697b8b2021-03-24 09:17:02 +01002074 db_dict["stage"] = str(stage)
tiernoe876f672020-02-13 14:34:48 +00002075
2076 if error_message is not None:
garciadeblas5697b8b2021-03-24 09:17:02 +01002077 db_dict["errorMessage"] = error_message
tiernoe876f672020-02-13 14:34:48 +00002078 if operation_state is not None:
garciadeblas5697b8b2021-03-24 09:17:02 +01002079 db_dict["operationState"] = operation_state
tiernoe876f672020-02-13 14:34:48 +00002080 db_dict["statusEnteredTime"] = time()
quilesj3655ae02019-12-12 16:08:35 +00002081 self.update_db_2("nslcmops", op_id, db_dict)
tiernoe876f672020-02-13 14:34:48 +00002082 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002083 self.logger.warn(
2084 "Error writing OPERATION status for op_id: {} -> {}".format(op_id, e)
2085 )
quilesj3655ae02019-12-12 16:08:35 +00002086
tierno51183952020-04-03 15:48:18 +00002087 def _write_all_config_status(self, db_nsr: dict, status: str):
quilesj3655ae02019-12-12 16:08:35 +00002088 try:
tierno51183952020-04-03 15:48:18 +00002089 nsr_id = db_nsr["_id"]
quilesj3655ae02019-12-12 16:08:35 +00002090 # configurationStatus
garciadeblas5697b8b2021-03-24 09:17:02 +01002091 config_status = db_nsr.get("configurationStatus")
quilesj3655ae02019-12-12 16:08:35 +00002092 if config_status:
garciadeblas5697b8b2021-03-24 09:17:02 +01002093 db_nsr_update = {
2094 "configurationStatus.{}.status".format(index): status
2095 for index, v in enumerate(config_status)
2096 if v
2097 }
quilesj3655ae02019-12-12 16:08:35 +00002098 # update status
tierno51183952020-04-03 15:48:18 +00002099 self.update_db_2("nsrs", nsr_id, db_nsr_update)
quilesj3655ae02019-12-12 16:08:35 +00002100
tiernoe876f672020-02-13 14:34:48 +00002101 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002102 self.logger.warn(
2103 "Error writing all configuration status, ns={}: {}".format(nsr_id, e)
2104 )
quilesj3655ae02019-12-12 16:08:35 +00002105
garciadeblas5697b8b2021-03-24 09:17:02 +01002106 def _write_configuration_status(
2107 self,
2108 nsr_id: str,
2109 vca_index: int,
2110 status: str = None,
2111 element_under_configuration: str = None,
2112 element_type: str = None,
2113 other_update: dict = None,
2114 ):
quilesj3655ae02019-12-12 16:08:35 +00002115
2116 # self.logger.debug('_write_configuration_status(): vca_index={}, status={}'
2117 # .format(vca_index, status))
2118
2119 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01002120 db_path = "configurationStatus.{}.".format(vca_index)
tierno51183952020-04-03 15:48:18 +00002121 db_dict = other_update or {}
quilesj63f90042020-01-17 09:53:55 +00002122 if status:
garciadeblas5697b8b2021-03-24 09:17:02 +01002123 db_dict[db_path + "status"] = status
quilesj3655ae02019-12-12 16:08:35 +00002124 if element_under_configuration:
garciadeblas5697b8b2021-03-24 09:17:02 +01002125 db_dict[
2126 db_path + "elementUnderConfiguration"
2127 ] = element_under_configuration
quilesj3655ae02019-12-12 16:08:35 +00002128 if element_type:
garciadeblas5697b8b2021-03-24 09:17:02 +01002129 db_dict[db_path + "elementType"] = element_type
quilesj3655ae02019-12-12 16:08:35 +00002130 self.update_db_2("nsrs", nsr_id, db_dict)
tiernoe876f672020-02-13 14:34:48 +00002131 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002132 self.logger.warn(
2133 "Error writing configuration status={}, ns={}, vca_index={}: {}".format(
2134 status, nsr_id, vca_index, e
2135 )
2136 )
quilesj4cda56b2019-12-05 10:02:20 +00002137
tierno38089af2020-04-16 07:56:58 +00002138 async def _do_placement(self, logging_text, db_nslcmop, db_vnfrs):
2139 """
2140 Check and computes the placement, (vim account where to deploy). If it is decided by an external tool, it
2141 sends the request via kafka and wait until the result is wrote at database (nslcmops _admin.plca).
2142 Database is used because the result can be obtained from a different LCM worker in case of HA.
2143 :param logging_text: contains the prefix for logging, with the ns and nslcmop identifiers
2144 :param db_nslcmop: database content of nslcmop
2145 :param db_vnfrs: database content of vnfrs, indexed by member-vnf-index.
tierno8790a3d2020-04-23 22:49:52 +00002146 :return: True if some modification is done. Modifies database vnfrs and parameter db_vnfr with the
2147 computed 'vim-account-id'
tierno38089af2020-04-16 07:56:58 +00002148 """
tierno8790a3d2020-04-23 22:49:52 +00002149 modified = False
garciadeblas5697b8b2021-03-24 09:17:02 +01002150 nslcmop_id = db_nslcmop["_id"]
2151 placement_engine = deep_get(db_nslcmop, ("operationParams", "placement-engine"))
magnussonle9198bb2020-01-21 13:00:51 +01002152 if placement_engine == "PLA":
garciadeblas5697b8b2021-03-24 09:17:02 +01002153 self.logger.debug(
2154 logging_text + "Invoke and wait for placement optimization"
2155 )
2156 await self.msg.aiowrite(
2157 "pla", "get_placement", {"nslcmopId": nslcmop_id}, loop=self.loop
2158 )
magnussonle9198bb2020-01-21 13:00:51 +01002159 db_poll_interval = 5
tierno38089af2020-04-16 07:56:58 +00002160 wait = db_poll_interval * 10
magnussonle9198bb2020-01-21 13:00:51 +01002161 pla_result = None
2162 while not pla_result and wait >= 0:
2163 await asyncio.sleep(db_poll_interval)
2164 wait -= db_poll_interval
tierno38089af2020-04-16 07:56:58 +00002165 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
garciadeblas5697b8b2021-03-24 09:17:02 +01002166 pla_result = deep_get(db_nslcmop, ("_admin", "pla"))
magnussonle9198bb2020-01-21 13:00:51 +01002167
2168 if not pla_result:
garciadeblas5697b8b2021-03-24 09:17:02 +01002169 raise LcmException(
2170 "Placement timeout for nslcmopId={}".format(nslcmop_id)
2171 )
magnussonle9198bb2020-01-21 13:00:51 +01002172
garciadeblas5697b8b2021-03-24 09:17:02 +01002173 for pla_vnf in pla_result["vnf"]:
2174 vnfr = db_vnfrs.get(pla_vnf["member-vnf-index"])
2175 if not pla_vnf.get("vimAccountId") or not vnfr:
magnussonle9198bb2020-01-21 13:00:51 +01002176 continue
tierno8790a3d2020-04-23 22:49:52 +00002177 modified = True
garciadeblas5697b8b2021-03-24 09:17:02 +01002178 self.db.set_one(
2179 "vnfrs",
2180 {"_id": vnfr["_id"]},
2181 {"vim-account-id": pla_vnf["vimAccountId"]},
2182 )
tierno38089af2020-04-16 07:56:58 +00002183 # Modifies db_vnfrs
garciadeblas5697b8b2021-03-24 09:17:02 +01002184 vnfr["vim-account-id"] = pla_vnf["vimAccountId"]
tierno8790a3d2020-04-23 22:49:52 +00002185 return modified
magnussonle9198bb2020-01-21 13:00:51 +01002186
2187 def update_nsrs_with_pla_result(self, params):
2188 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01002189 nslcmop_id = deep_get(params, ("placement", "nslcmopId"))
2190 self.update_db_2(
2191 "nslcmops", nslcmop_id, {"_admin.pla": params.get("placement")}
2192 )
magnussonle9198bb2020-01-21 13:00:51 +01002193 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002194 self.logger.warn("Update failed for nslcmop_id={}:{}".format(nslcmop_id, e))
magnussonle9198bb2020-01-21 13:00:51 +01002195
tierno59d22d22018-09-25 18:10:19 +02002196 async def instantiate(self, nsr_id, nslcmop_id):
quilesj7e13aeb2019-10-08 13:34:55 +02002197 """
2198
2199 :param nsr_id: ns instance to deploy
2200 :param nslcmop_id: operation to run
2201 :return:
2202 """
kuused124bfe2019-06-18 12:09:24 +02002203
2204 # Try to lock HA task here
garciadeblas5697b8b2021-03-24 09:17:02 +01002205 task_is_locked_by_me = self.lcm_tasks.lock_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02002206 if not task_is_locked_by_me:
garciadeblas5697b8b2021-03-24 09:17:02 +01002207 self.logger.debug(
2208 "instantiate() task is not locked by me, ns={}".format(nsr_id)
2209 )
kuused124bfe2019-06-18 12:09:24 +02002210 return
2211
tierno59d22d22018-09-25 18:10:19 +02002212 logging_text = "Task ns={} instantiate={} ".format(nsr_id, nslcmop_id)
2213 self.logger.debug(logging_text + "Enter")
quilesj7e13aeb2019-10-08 13:34:55 +02002214
tierno59d22d22018-09-25 18:10:19 +02002215 # get all needed from database
quilesj7e13aeb2019-10-08 13:34:55 +02002216
2217 # database nsrs record
tierno59d22d22018-09-25 18:10:19 +02002218 db_nsr = None
quilesj7e13aeb2019-10-08 13:34:55 +02002219
2220 # database nslcmops record
tierno59d22d22018-09-25 18:10:19 +02002221 db_nslcmop = None
quilesj7e13aeb2019-10-08 13:34:55 +02002222
2223 # update operation on nsrs
tiernoe876f672020-02-13 14:34:48 +00002224 db_nsr_update = {}
quilesj7e13aeb2019-10-08 13:34:55 +02002225 # update operation on nslcmops
tierno59d22d22018-09-25 18:10:19 +02002226 db_nslcmop_update = {}
quilesj7e13aeb2019-10-08 13:34:55 +02002227
tierno59d22d22018-09-25 18:10:19 +02002228 nslcmop_operation_state = None
garciadeblas5697b8b2021-03-24 09:17:02 +01002229 db_vnfrs = {} # vnf's info indexed by member-index
quilesj7e13aeb2019-10-08 13:34:55 +02002230 # n2vc_info = {}
tiernoe876f672020-02-13 14:34:48 +00002231 tasks_dict_info = {} # from task to info text
tierno59d22d22018-09-25 18:10:19 +02002232 exc = None
tiernoe876f672020-02-13 14:34:48 +00002233 error_list = []
garciadeblas5697b8b2021-03-24 09:17:02 +01002234 stage = [
2235 "Stage 1/5: preparation of the environment.",
2236 "Waiting for previous operations to terminate.",
2237 "",
2238 ]
tiernoe876f672020-02-13 14:34:48 +00002239 # ^ stage, step, VIM progress
tierno59d22d22018-09-25 18:10:19 +02002240 try:
kuused124bfe2019-06-18 12:09:24 +02002241 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +01002242 await self.lcm_tasks.waitfor_related_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02002243
quilesj7e13aeb2019-10-08 13:34:55 +02002244 # STEP 0: Reading database (nslcmops, nsrs, nsds, vnfrs, vnfds)
tiernob5203912020-08-11 11:20:13 +00002245 stage[1] = "Reading from database."
quilesj4cda56b2019-12-05 10:02:20 +00002246 # nsState="BUILDING", currentOperation="INSTANTIATING", currentOperationID=nslcmop_id
tiernoe876f672020-02-13 14:34:48 +00002247 db_nsr_update["detailed-status"] = "creating"
2248 db_nsr_update["operational-status"] = "init"
quilesj4cda56b2019-12-05 10:02:20 +00002249 self._write_ns_status(
2250 nsr_id=nsr_id,
2251 ns_state="BUILDING",
2252 current_operation="INSTANTIATING",
tiernoe876f672020-02-13 14:34:48 +00002253 current_operation_id=nslcmop_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01002254 other_update=db_nsr_update,
tiernoe876f672020-02-13 14:34:48 +00002255 )
garciadeblas5697b8b2021-03-24 09:17:02 +01002256 self._write_op_status(op_id=nslcmop_id, stage=stage, queuePosition=0)
quilesj4cda56b2019-12-05 10:02:20 +00002257
quilesj7e13aeb2019-10-08 13:34:55 +02002258 # read from db: operation
tiernob5203912020-08-11 11:20:13 +00002259 stage[1] = "Getting nslcmop={} from db.".format(nslcmop_id)
tierno59d22d22018-09-25 18:10:19 +02002260 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
Guillermo Calvinofbf294c2022-01-26 17:40:31 +01002261 if db_nslcmop["operationParams"].get("additionalParamsForVnf"):
2262 db_nslcmop["operationParams"]["additionalParamsForVnf"] = json.loads(
2263 db_nslcmop["operationParams"]["additionalParamsForVnf"]
2264 )
tierno744303e2020-01-13 16:46:31 +00002265 ns_params = db_nslcmop.get("operationParams")
2266 if ns_params and ns_params.get("timeout_ns_deploy"):
2267 timeout_ns_deploy = ns_params["timeout_ns_deploy"]
2268 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01002269 timeout_ns_deploy = self.timeout.get(
2270 "ns_deploy", self.timeout_ns_deploy
2271 )
quilesj7e13aeb2019-10-08 13:34:55 +02002272
2273 # read from db: ns
tiernob5203912020-08-11 11:20:13 +00002274 stage[1] = "Getting nsr={} from db.".format(nsr_id)
tierno59d22d22018-09-25 18:10:19 +02002275 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
tiernob5203912020-08-11 11:20:13 +00002276 stage[1] = "Getting nsd={} from db.".format(db_nsr["nsd-id"])
tiernod732fb82020-05-21 13:18:23 +00002277 nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
bravof021e70d2021-03-11 12:03:30 -03002278 self.fs.sync(db_nsr["nsd-id"])
tiernod732fb82020-05-21 13:18:23 +00002279 db_nsr["nsd"] = nsd
tiernod8323042019-08-09 11:32:23 +00002280 # nsr_name = db_nsr["name"] # TODO short-name??
tierno47e86b52018-10-10 14:05:55 +02002281
quilesj7e13aeb2019-10-08 13:34:55 +02002282 # read from db: vnf's of this ns
tiernob5203912020-08-11 11:20:13 +00002283 stage[1] = "Getting vnfrs from db."
tiernoe876f672020-02-13 14:34:48 +00002284 self.logger.debug(logging_text + stage[1])
tierno27246d82018-09-27 15:59:09 +02002285 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
tierno27246d82018-09-27 15:59:09 +02002286
quilesj7e13aeb2019-10-08 13:34:55 +02002287 # read from db: vnfd's for every vnf
garciadeblas5697b8b2021-03-24 09:17:02 +01002288 db_vnfds = [] # every vnfd data
quilesj7e13aeb2019-10-08 13:34:55 +02002289
2290 # for each vnf in ns, read vnfd
tierno27246d82018-09-27 15:59:09 +02002291 for vnfr in db_vnfrs_list:
Guillermo Calvinofbf294c2022-01-26 17:40:31 +01002292 if vnfr.get("kdur"):
2293 kdur_list = []
2294 for kdur in vnfr["kdur"]:
2295 if kdur.get("additionalParams"):
2296 kdur["additionalParams"] = json.loads(kdur["additionalParams"])
2297 kdur_list.append(kdur)
2298 vnfr["kdur"] = kdur_list
2299
bravof922c4172020-11-24 21:21:43 -03002300 db_vnfrs[vnfr["member-vnf-index-ref"]] = vnfr
2301 vnfd_id = vnfr["vnfd-id"]
2302 vnfd_ref = vnfr["vnfd-ref"]
bravof021e70d2021-03-11 12:03:30 -03002303 self.fs.sync(vnfd_id)
lloretgalleg6d488782020-07-22 10:13:46 +00002304
quilesj7e13aeb2019-10-08 13:34:55 +02002305 # if we haven't this vnfd, read it from db
tierno27246d82018-09-27 15:59:09 +02002306 if vnfd_id not in db_vnfds:
quilesj63f90042020-01-17 09:53:55 +00002307 # read from db
garciadeblas5697b8b2021-03-24 09:17:02 +01002308 stage[1] = "Getting vnfd={} id='{}' from db.".format(
2309 vnfd_id, vnfd_ref
2310 )
tiernoe876f672020-02-13 14:34:48 +00002311 self.logger.debug(logging_text + stage[1])
tierno27246d82018-09-27 15:59:09 +02002312 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
tierno27246d82018-09-27 15:59:09 +02002313
quilesj7e13aeb2019-10-08 13:34:55 +02002314 # store vnfd
David Garciad41dbd62020-12-10 12:52:52 +01002315 db_vnfds.append(vnfd)
quilesj7e13aeb2019-10-08 13:34:55 +02002316
2317 # Get or generates the _admin.deployed.VCA list
tiernoe4f7e6c2018-11-27 14:55:30 +00002318 vca_deployed_list = None
2319 if db_nsr["_admin"].get("deployed"):
2320 vca_deployed_list = db_nsr["_admin"]["deployed"].get("VCA")
2321 if vca_deployed_list is None:
2322 vca_deployed_list = []
quilesj3655ae02019-12-12 16:08:35 +00002323 configuration_status_list = []
tiernoe4f7e6c2018-11-27 14:55:30 +00002324 db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
quilesj3655ae02019-12-12 16:08:35 +00002325 db_nsr_update["configurationStatus"] = configuration_status_list
quilesj7e13aeb2019-10-08 13:34:55 +02002326 # add _admin.deployed.VCA to db_nsr dictionary, value=vca_deployed_list
tierno98ad6ea2019-05-30 17:16:28 +00002327 populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
tiernoe4f7e6c2018-11-27 14:55:30 +00002328 elif isinstance(vca_deployed_list, dict):
2329 # maintain backward compatibility. Change a dict to list at database
2330 vca_deployed_list = list(vca_deployed_list.values())
2331 db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
tierno98ad6ea2019-05-30 17:16:28 +00002332 populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
tiernoe4f7e6c2018-11-27 14:55:30 +00002333
garciadeblas5697b8b2021-03-24 09:17:02 +01002334 if not isinstance(
2335 deep_get(db_nsr, ("_admin", "deployed", "RO", "vnfd")), list
2336 ):
tiernoa009e552019-01-30 16:45:44 +00002337 populate_dict(db_nsr, ("_admin", "deployed", "RO", "vnfd"), [])
2338 db_nsr_update["_admin.deployed.RO.vnfd"] = []
tierno59d22d22018-09-25 18:10:19 +02002339
tiernobaa51102018-12-14 13:16:18 +00002340 # set state to INSTANTIATED. When instantiated NBI will not delete directly
2341 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
2342 self.update_db_2("nsrs", nsr_id, db_nsr_update)
garciadeblas5697b8b2021-03-24 09:17:02 +01002343 self.db.set_list(
2344 "vnfrs", {"nsr-id-ref": nsr_id}, {"_admin.nsState": "INSTANTIATED"}
2345 )
quilesj3655ae02019-12-12 16:08:35 +00002346
2347 # n2vc_redesign STEP 2 Deploy Network Scenario
garciadeblas5697b8b2021-03-24 09:17:02 +01002348 stage[0] = "Stage 2/5: deployment of KDUs, VMs and execution environments."
2349 self._write_op_status(op_id=nslcmop_id, stage=stage)
quilesj3655ae02019-12-12 16:08:35 +00002350
tiernob5203912020-08-11 11:20:13 +00002351 stage[1] = "Deploying KDUs."
tiernoe876f672020-02-13 14:34:48 +00002352 # self.logger.debug(logging_text + "Before deploy_kdus")
calvinosanch9f9c6f22019-11-04 13:37:39 +01002353 # Call to deploy_kdus in case exists the "vdu:kdu" param
tiernoe876f672020-02-13 14:34:48 +00002354 await self.deploy_kdus(
2355 logging_text=logging_text,
2356 nsr_id=nsr_id,
2357 nslcmop_id=nslcmop_id,
2358 db_vnfrs=db_vnfrs,
2359 db_vnfds=db_vnfds,
2360 task_instantiation_info=tasks_dict_info,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002361 )
tiernoe876f672020-02-13 14:34:48 +00002362
2363 stage[1] = "Getting VCA public key."
tiernod8323042019-08-09 11:32:23 +00002364 # n2vc_redesign STEP 1 Get VCA public ssh-key
2365 # feature 1429. Add n2vc public key to needed VMs
tierno3bedc9b2019-11-27 15:46:57 +00002366 n2vc_key = self.n2vc.get_public_key()
tiernoa5088192019-11-26 16:12:53 +00002367 n2vc_key_list = [n2vc_key]
2368 if self.vca_config.get("public_key"):
2369 n2vc_key_list.append(self.vca_config["public_key"])
tierno98ad6ea2019-05-30 17:16:28 +00002370
tiernoe876f672020-02-13 14:34:48 +00002371 stage[1] = "Deploying NS at VIM."
tiernod8323042019-08-09 11:32:23 +00002372 task_ro = asyncio.ensure_future(
quilesj7e13aeb2019-10-08 13:34:55 +02002373 self.instantiate_RO(
2374 logging_text=logging_text,
2375 nsr_id=nsr_id,
2376 nsd=nsd,
2377 db_nsr=db_nsr,
2378 db_nslcmop=db_nslcmop,
2379 db_vnfrs=db_vnfrs,
bravof922c4172020-11-24 21:21:43 -03002380 db_vnfds=db_vnfds,
tiernoe876f672020-02-13 14:34:48 +00002381 n2vc_key_list=n2vc_key_list,
garciadeblas5697b8b2021-03-24 09:17:02 +01002382 stage=stage,
tierno98ad6ea2019-05-30 17:16:28 +00002383 )
tiernod8323042019-08-09 11:32:23 +00002384 )
2385 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "instantiate_RO", task_ro)
tiernoa2143262020-03-27 16:20:40 +00002386 tasks_dict_info[task_ro] = "Deploying at VIM"
tierno98ad6ea2019-05-30 17:16:28 +00002387
tiernod8323042019-08-09 11:32:23 +00002388 # n2vc_redesign STEP 3 to 6 Deploy N2VC
tiernoe876f672020-02-13 14:34:48 +00002389 stage[1] = "Deploying Execution Environments."
2390 self.logger.debug(logging_text + stage[1])
tierno98ad6ea2019-05-30 17:16:28 +00002391
tiernod8323042019-08-09 11:32:23 +00002392 nsi_id = None # TODO put nsi_id when this nsr belongs to a NSI
bravof922c4172020-11-24 21:21:43 -03002393 for vnf_profile in get_vnf_profiles(nsd):
2394 vnfd_id = vnf_profile["vnfd-id"]
2395 vnfd = find_in_list(db_vnfds, lambda a_vnf: a_vnf["id"] == vnfd_id)
2396 member_vnf_index = str(vnf_profile["id"])
tiernod8323042019-08-09 11:32:23 +00002397 db_vnfr = db_vnfrs[member_vnf_index]
2398 base_folder = vnfd["_admin"]["storage"]
2399 vdu_id = None
2400 vdu_index = 0
tierno98ad6ea2019-05-30 17:16:28 +00002401 vdu_name = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01002402 kdu_name = None
tierno59d22d22018-09-25 18:10:19 +02002403
tierno8a518872018-12-21 13:42:14 +00002404 # Get additional parameters
bravof922c4172020-11-24 21:21:43 -03002405 deploy_params = {"OSM": get_osm_params(db_vnfr)}
tiernod8323042019-08-09 11:32:23 +00002406 if db_vnfr.get("additionalParamsForVnf"):
garciadeblas5697b8b2021-03-24 09:17:02 +01002407 deploy_params.update(
2408 parse_yaml_strings(db_vnfr["additionalParamsForVnf"].copy())
2409 )
tierno8a518872018-12-21 13:42:14 +00002410
bravofe5a31bc2021-02-17 19:09:12 -03002411 descriptor_config = get_configuration(vnfd, vnfd["id"])
tierno588547c2020-07-01 15:30:20 +00002412 if descriptor_config:
quilesj7e13aeb2019-10-08 13:34:55 +02002413 self._deploy_n2vc(
garciadeblas5697b8b2021-03-24 09:17:02 +01002414 logging_text=logging_text
2415 + "member_vnf_index={} ".format(member_vnf_index),
quilesj7e13aeb2019-10-08 13:34:55 +02002416 db_nsr=db_nsr,
2417 db_vnfr=db_vnfr,
2418 nslcmop_id=nslcmop_id,
2419 nsr_id=nsr_id,
2420 nsi_id=nsi_id,
2421 vnfd_id=vnfd_id,
2422 vdu_id=vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002423 kdu_name=kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02002424 member_vnf_index=member_vnf_index,
2425 vdu_index=vdu_index,
2426 vdu_name=vdu_name,
2427 deploy_params=deploy_params,
2428 descriptor_config=descriptor_config,
2429 base_folder=base_folder,
tiernoe876f672020-02-13 14:34:48 +00002430 task_instantiation_info=tasks_dict_info,
garciadeblas5697b8b2021-03-24 09:17:02 +01002431 stage=stage,
quilesj7e13aeb2019-10-08 13:34:55 +02002432 )
tierno59d22d22018-09-25 18:10:19 +02002433
2434 # Deploy charms for each VDU that supports one.
bravof922c4172020-11-24 21:21:43 -03002435 for vdud in get_vdu_list(vnfd):
tiernod8323042019-08-09 11:32:23 +00002436 vdu_id = vdud["id"]
bravofe5a31bc2021-02-17 19:09:12 -03002437 descriptor_config = get_configuration(vnfd, vdu_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01002438 vdur = find_in_list(
2439 db_vnfr["vdur"], lambda vdu: vdu["vdu-id-ref"] == vdu_id
2440 )
bravof922c4172020-11-24 21:21:43 -03002441
tierno626e0152019-11-29 14:16:16 +00002442 if vdur.get("additionalParams"):
bravof922c4172020-11-24 21:21:43 -03002443 deploy_params_vdu = parse_yaml_strings(vdur["additionalParams"])
tierno626e0152019-11-29 14:16:16 +00002444 else:
2445 deploy_params_vdu = deploy_params
garciadeblas5697b8b2021-03-24 09:17:02 +01002446 deploy_params_vdu["OSM"] = get_osm_params(
2447 db_vnfr, vdu_id, vdu_count_index=0
2448 )
endika85d73a62021-06-21 18:55:07 +02002449 vdud_count = get_number_of_instances(vnfd, vdu_id)
bravof922c4172020-11-24 21:21:43 -03002450
2451 self.logger.debug("VDUD > {}".format(vdud))
garciadeblas5697b8b2021-03-24 09:17:02 +01002452 self.logger.debug(
2453 "Descriptor config > {}".format(descriptor_config)
2454 )
tierno588547c2020-07-01 15:30:20 +00002455 if descriptor_config:
tiernod8323042019-08-09 11:32:23 +00002456 vdu_name = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01002457 kdu_name = None
bravof922c4172020-11-24 21:21:43 -03002458 for vdu_index in range(vdud_count):
tiernod8323042019-08-09 11:32:23 +00002459 # TODO vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
quilesj7e13aeb2019-10-08 13:34:55 +02002460 self._deploy_n2vc(
garciadeblas5697b8b2021-03-24 09:17:02 +01002461 logging_text=logging_text
2462 + "member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
2463 member_vnf_index, vdu_id, vdu_index
2464 ),
quilesj7e13aeb2019-10-08 13:34:55 +02002465 db_nsr=db_nsr,
2466 db_vnfr=db_vnfr,
2467 nslcmop_id=nslcmop_id,
2468 nsr_id=nsr_id,
2469 nsi_id=nsi_id,
2470 vnfd_id=vnfd_id,
2471 vdu_id=vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002472 kdu_name=kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02002473 member_vnf_index=member_vnf_index,
2474 vdu_index=vdu_index,
2475 vdu_name=vdu_name,
tierno626e0152019-11-29 14:16:16 +00002476 deploy_params=deploy_params_vdu,
quilesj7e13aeb2019-10-08 13:34:55 +02002477 descriptor_config=descriptor_config,
2478 base_folder=base_folder,
tierno8e2fae72020-04-01 15:21:15 +00002479 task_instantiation_info=tasks_dict_info,
garciadeblas5697b8b2021-03-24 09:17:02 +01002480 stage=stage,
quilesj7e13aeb2019-10-08 13:34:55 +02002481 )
bravof922c4172020-11-24 21:21:43 -03002482 for kdud in get_kdu_list(vnfd):
calvinosanch9f9c6f22019-11-04 13:37:39 +01002483 kdu_name = kdud["name"]
bravofe5a31bc2021-02-17 19:09:12 -03002484 descriptor_config = get_configuration(vnfd, kdu_name)
tierno588547c2020-07-01 15:30:20 +00002485 if descriptor_config:
calvinosanch9f9c6f22019-11-04 13:37:39 +01002486 vdu_id = None
2487 vdu_index = 0
2488 vdu_name = None
garciadeblas5697b8b2021-03-24 09:17:02 +01002489 kdur = next(
2490 x for x in db_vnfr["kdur"] if x["kdu-name"] == kdu_name
2491 )
bravof922c4172020-11-24 21:21:43 -03002492 deploy_params_kdu = {"OSM": get_osm_params(db_vnfr)}
tierno72ef84f2020-10-06 08:22:07 +00002493 if kdur.get("additionalParams"):
garciadeblas5697b8b2021-03-24 09:17:02 +01002494 deploy_params_kdu = parse_yaml_strings(
2495 kdur["additionalParams"]
2496 )
tierno59d22d22018-09-25 18:10:19 +02002497
calvinosanch9f9c6f22019-11-04 13:37:39 +01002498 self._deploy_n2vc(
2499 logging_text=logging_text,
2500 db_nsr=db_nsr,
2501 db_vnfr=db_vnfr,
2502 nslcmop_id=nslcmop_id,
2503 nsr_id=nsr_id,
2504 nsi_id=nsi_id,
2505 vnfd_id=vnfd_id,
2506 vdu_id=vdu_id,
2507 kdu_name=kdu_name,
2508 member_vnf_index=member_vnf_index,
2509 vdu_index=vdu_index,
2510 vdu_name=vdu_name,
tierno72ef84f2020-10-06 08:22:07 +00002511 deploy_params=deploy_params_kdu,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002512 descriptor_config=descriptor_config,
2513 base_folder=base_folder,
tierno8e2fae72020-04-01 15:21:15 +00002514 task_instantiation_info=tasks_dict_info,
garciadeblas5697b8b2021-03-24 09:17:02 +01002515 stage=stage,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002516 )
tierno59d22d22018-09-25 18:10:19 +02002517
tierno1b633412019-02-25 16:48:23 +00002518 # Check if this NS has a charm configuration
tiernod8323042019-08-09 11:32:23 +00002519 descriptor_config = nsd.get("ns-configuration")
2520 if descriptor_config and descriptor_config.get("juju"):
2521 vnfd_id = None
2522 db_vnfr = None
2523 member_vnf_index = None
2524 vdu_id = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01002525 kdu_name = None
tiernod8323042019-08-09 11:32:23 +00002526 vdu_index = 0
2527 vdu_name = None
tierno1b633412019-02-25 16:48:23 +00002528
tiernod8323042019-08-09 11:32:23 +00002529 # Get additional parameters
David Garcia40603572020-12-10 20:10:53 +01002530 deploy_params = {"OSM": {"vim_account_id": ns_params["vimAccountId"]}}
tiernod8323042019-08-09 11:32:23 +00002531 if db_nsr.get("additionalParamsForNs"):
garciadeblas5697b8b2021-03-24 09:17:02 +01002532 deploy_params.update(
2533 parse_yaml_strings(db_nsr["additionalParamsForNs"].copy())
2534 )
tiernod8323042019-08-09 11:32:23 +00002535 base_folder = nsd["_admin"]["storage"]
quilesj7e13aeb2019-10-08 13:34:55 +02002536 self._deploy_n2vc(
2537 logging_text=logging_text,
2538 db_nsr=db_nsr,
2539 db_vnfr=db_vnfr,
2540 nslcmop_id=nslcmop_id,
2541 nsr_id=nsr_id,
2542 nsi_id=nsi_id,
2543 vnfd_id=vnfd_id,
2544 vdu_id=vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002545 kdu_name=kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02002546 member_vnf_index=member_vnf_index,
2547 vdu_index=vdu_index,
2548 vdu_name=vdu_name,
2549 deploy_params=deploy_params,
2550 descriptor_config=descriptor_config,
2551 base_folder=base_folder,
tierno8e2fae72020-04-01 15:21:15 +00002552 task_instantiation_info=tasks_dict_info,
garciadeblas5697b8b2021-03-24 09:17:02 +01002553 stage=stage,
quilesj7e13aeb2019-10-08 13:34:55 +02002554 )
tierno1b633412019-02-25 16:48:23 +00002555
tiernoe876f672020-02-13 14:34:48 +00002556 # rest of staff will be done at finally
tierno1b633412019-02-25 16:48:23 +00002557
garciadeblas5697b8b2021-03-24 09:17:02 +01002558 except (
2559 ROclient.ROClientException,
2560 DbException,
2561 LcmException,
2562 N2VCException,
2563 ) as e:
2564 self.logger.error(
2565 logging_text + "Exit Exception while '{}': {}".format(stage[1], e)
2566 )
tierno59d22d22018-09-25 18:10:19 +02002567 exc = e
2568 except asyncio.CancelledError:
garciadeblas5697b8b2021-03-24 09:17:02 +01002569 self.logger.error(
2570 logging_text + "Cancelled Exception while '{}'".format(stage[1])
2571 )
tierno59d22d22018-09-25 18:10:19 +02002572 exc = "Operation was cancelled"
2573 except Exception as e:
2574 exc = traceback.format_exc()
garciadeblas5697b8b2021-03-24 09:17:02 +01002575 self.logger.critical(
2576 logging_text + "Exit Exception while '{}': {}".format(stage[1], e),
2577 exc_info=True,
2578 )
tierno59d22d22018-09-25 18:10:19 +02002579 finally:
2580 if exc:
tiernoe876f672020-02-13 14:34:48 +00002581 error_list.append(str(exc))
tiernobaa51102018-12-14 13:16:18 +00002582 try:
tiernoe876f672020-02-13 14:34:48 +00002583 # wait for pending tasks
2584 if tasks_dict_info:
2585 stage[1] = "Waiting for instantiate pending tasks."
2586 self.logger.debug(logging_text + stage[1])
garciadeblas5697b8b2021-03-24 09:17:02 +01002587 error_list += await self._wait_for_tasks(
2588 logging_text,
2589 tasks_dict_info,
2590 timeout_ns_deploy,
2591 stage,
2592 nslcmop_id,
2593 nsr_id=nsr_id,
2594 )
tiernoe876f672020-02-13 14:34:48 +00002595 stage[1] = stage[2] = ""
2596 except asyncio.CancelledError:
2597 error_list.append("Cancelled")
2598 # TODO cancel all tasks
2599 except Exception as exc:
2600 error_list.append(str(exc))
quilesj4cda56b2019-12-05 10:02:20 +00002601
tiernoe876f672020-02-13 14:34:48 +00002602 # update operation-status
2603 db_nsr_update["operational-status"] = "running"
2604 # let's begin with VCA 'configured' status (later we can change it)
2605 db_nsr_update["config-status"] = "configured"
2606 for task, task_name in tasks_dict_info.items():
2607 if not task.done() or task.cancelled() or task.exception():
2608 if task_name.startswith(self.task_name_deploy_vca):
2609 # A N2VC task is pending
2610 db_nsr_update["config-status"] = "failed"
quilesj4cda56b2019-12-05 10:02:20 +00002611 else:
tiernoe876f672020-02-13 14:34:48 +00002612 # RO or KDU task is pending
2613 db_nsr_update["operational-status"] = "failed"
quilesj3655ae02019-12-12 16:08:35 +00002614
tiernoe876f672020-02-13 14:34:48 +00002615 # update status at database
2616 if error_list:
tiernoa2143262020-03-27 16:20:40 +00002617 error_detail = ". ".join(error_list)
tiernoe876f672020-02-13 14:34:48 +00002618 self.logger.error(logging_text + error_detail)
garciadeblas5697b8b2021-03-24 09:17:02 +01002619 error_description_nslcmop = "{} Detail: {}".format(
2620 stage[0], error_detail
2621 )
2622 error_description_nsr = "Operation: INSTANTIATING.{}, {}".format(
2623 nslcmop_id, stage[0]
2624 )
quilesj3655ae02019-12-12 16:08:35 +00002625
garciadeblas5697b8b2021-03-24 09:17:02 +01002626 db_nsr_update["detailed-status"] = (
2627 error_description_nsr + " Detail: " + error_detail
2628 )
tiernoe876f672020-02-13 14:34:48 +00002629 db_nslcmop_update["detailed-status"] = error_detail
2630 nslcmop_operation_state = "FAILED"
2631 ns_state = "BROKEN"
2632 else:
tiernoa2143262020-03-27 16:20:40 +00002633 error_detail = None
tiernoe876f672020-02-13 14:34:48 +00002634 error_description_nsr = error_description_nslcmop = None
2635 ns_state = "READY"
2636 db_nsr_update["detailed-status"] = "Done"
2637 db_nslcmop_update["detailed-status"] = "Done"
2638 nslcmop_operation_state = "COMPLETED"
quilesj4cda56b2019-12-05 10:02:20 +00002639
tiernoe876f672020-02-13 14:34:48 +00002640 if db_nsr:
2641 self._write_ns_status(
2642 nsr_id=nsr_id,
2643 ns_state=ns_state,
2644 current_operation="IDLE",
2645 current_operation_id=None,
2646 error_description=error_description_nsr,
tiernoa2143262020-03-27 16:20:40 +00002647 error_detail=error_detail,
garciadeblas5697b8b2021-03-24 09:17:02 +01002648 other_update=db_nsr_update,
tiernoe876f672020-02-13 14:34:48 +00002649 )
tiernoa17d4f42020-04-28 09:59:23 +00002650 self._write_op_status(
2651 op_id=nslcmop_id,
2652 stage="",
2653 error_message=error_description_nslcmop,
2654 operation_state=nslcmop_operation_state,
2655 other_update=db_nslcmop_update,
2656 )
quilesj3655ae02019-12-12 16:08:35 +00002657
tierno59d22d22018-09-25 18:10:19 +02002658 if nslcmop_operation_state:
2659 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01002660 await self.msg.aiowrite(
2661 "ns",
2662 "instantiated",
2663 {
2664 "nsr_id": nsr_id,
2665 "nslcmop_id": nslcmop_id,
2666 "operationState": nslcmop_operation_state,
2667 },
2668 loop=self.loop,
2669 )
tierno59d22d22018-09-25 18:10:19 +02002670 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002671 self.logger.error(
2672 logging_text + "kafka_write notification Exception {}".format(e)
2673 )
tierno59d22d22018-09-25 18:10:19 +02002674
2675 self.logger.debug(logging_text + "Exit")
2676 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_instantiate")
2677
David Garciac1fe90a2021-03-31 19:12:02 +02002678 async def _add_vca_relations(
2679 self,
2680 logging_text,
2681 nsr_id,
2682 vca_index: int,
2683 timeout: int = 3600,
2684 vca_type: str = None,
2685 vca_id: str = None,
2686 ) -> bool:
quilesj63f90042020-01-17 09:53:55 +00002687
2688 # steps:
2689 # 1. find all relations for this VCA
2690 # 2. wait for other peers related
2691 # 3. add relations
2692
2693 try:
tierno588547c2020-07-01 15:30:20 +00002694 vca_type = vca_type or "lxc_proxy_charm"
quilesj63f90042020-01-17 09:53:55 +00002695
2696 # STEP 1: find all relations for this VCA
2697
2698 # read nsr record
2699 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
David Garcia171f3542020-05-21 16:41:07 +02002700 nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
quilesj63f90042020-01-17 09:53:55 +00002701
2702 # this VCA data
garciadeblas5697b8b2021-03-24 09:17:02 +01002703 my_vca = deep_get(db_nsr, ("_admin", "deployed", "VCA"))[vca_index]
quilesj63f90042020-01-17 09:53:55 +00002704
2705 # read all ns-configuration relations
2706 ns_relations = list()
garciadeblas5697b8b2021-03-24 09:17:02 +01002707 db_ns_relations = deep_get(nsd, ("ns-configuration", "relation"))
quilesj63f90042020-01-17 09:53:55 +00002708 if db_ns_relations:
2709 for r in db_ns_relations:
2710 # check if this VCA is in the relation
garciadeblas5697b8b2021-03-24 09:17:02 +01002711 if my_vca.get("member-vnf-index") in (
2712 r.get("entities")[0].get("id"),
2713 r.get("entities")[1].get("id"),
2714 ):
quilesj63f90042020-01-17 09:53:55 +00002715 ns_relations.append(r)
2716
2717 # read all vnf-configuration relations
2718 vnf_relations = list()
garciadeblas5697b8b2021-03-24 09:17:02 +01002719 db_vnfd_list = db_nsr.get("vnfd-id")
quilesj63f90042020-01-17 09:53:55 +00002720 if db_vnfd_list:
2721 for vnfd in db_vnfd_list:
aktas45966a02021-05-04 19:32:45 +03002722 db_vnf_relations = None
quilesj63f90042020-01-17 09:53:55 +00002723 db_vnfd = self.db.get_one("vnfds", {"_id": vnfd})
aktas45966a02021-05-04 19:32:45 +03002724 db_vnf_configuration = get_configuration(db_vnfd, db_vnfd["id"])
2725 if db_vnf_configuration:
2726 db_vnf_relations = db_vnf_configuration.get("relation", [])
quilesj63f90042020-01-17 09:53:55 +00002727 if db_vnf_relations:
2728 for r in db_vnf_relations:
2729 # check if this VCA is in the relation
garciadeblas5697b8b2021-03-24 09:17:02 +01002730 if my_vca.get("vdu_id") in (
2731 r.get("entities")[0].get("id"),
2732 r.get("entities")[1].get("id"),
2733 ):
quilesj63f90042020-01-17 09:53:55 +00002734 vnf_relations.append(r)
2735
2736 # if no relations, terminate
2737 if not ns_relations and not vnf_relations:
garciadeblas5697b8b2021-03-24 09:17:02 +01002738 self.logger.debug(logging_text + " No relations")
quilesj63f90042020-01-17 09:53:55 +00002739 return True
2740
garciadeblas5697b8b2021-03-24 09:17:02 +01002741 self.logger.debug(
2742 logging_text
2743 + " adding relations\n {}\n {}".format(
2744 ns_relations, vnf_relations
2745 )
2746 )
quilesj63f90042020-01-17 09:53:55 +00002747
2748 # add all relations
2749 start = time()
2750 while True:
2751 # check timeout
2752 now = time()
2753 if now - start >= timeout:
garciadeblas5697b8b2021-03-24 09:17:02 +01002754 self.logger.error(logging_text + " : timeout adding relations")
quilesj63f90042020-01-17 09:53:55 +00002755 return False
2756
2757 # reload nsr from database (we need to update record: _admin.deloyed.VCA)
2758 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2759
2760 # for each defined NS relation, find the VCA's related
tierno364c4572020-09-14 12:11:32 +00002761 for r in ns_relations.copy():
quilesj63f90042020-01-17 09:53:55 +00002762 from_vca_ee_id = None
2763 to_vca_ee_id = None
2764 from_vca_endpoint = None
2765 to_vca_endpoint = None
garciadeblas5697b8b2021-03-24 09:17:02 +01002766 vca_list = deep_get(db_nsr, ("_admin", "deployed", "VCA"))
quilesj63f90042020-01-17 09:53:55 +00002767 for vca in vca_list:
garciadeblas5697b8b2021-03-24 09:17:02 +01002768 if vca.get("member-vnf-index") == r.get("entities")[0].get(
2769 "id"
2770 ) and vca.get("config_sw_installed"):
2771 from_vca_ee_id = vca.get("ee_id")
2772 from_vca_endpoint = r.get("entities")[0].get("endpoint")
2773 if vca.get("member-vnf-index") == r.get("entities")[1].get(
2774 "id"
2775 ) and vca.get("config_sw_installed"):
2776 to_vca_ee_id = vca.get("ee_id")
2777 to_vca_endpoint = r.get("entities")[1].get("endpoint")
quilesj63f90042020-01-17 09:53:55 +00002778 if from_vca_ee_id and to_vca_ee_id:
2779 # add relation
tierno588547c2020-07-01 15:30:20 +00002780 await self.vca_map[vca_type].add_relation(
quilesj63f90042020-01-17 09:53:55 +00002781 ee_id_1=from_vca_ee_id,
2782 ee_id_2=to_vca_ee_id,
2783 endpoint_1=from_vca_endpoint,
David Garciac1fe90a2021-03-31 19:12:02 +02002784 endpoint_2=to_vca_endpoint,
2785 vca_id=vca_id,
2786 )
quilesj63f90042020-01-17 09:53:55 +00002787 # remove entry from relations list
2788 ns_relations.remove(r)
2789 else:
2790 # check failed peers
2791 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01002792 vca_status_list = db_nsr.get("configurationStatus")
quilesj63f90042020-01-17 09:53:55 +00002793 if vca_status_list:
2794 for i in range(len(vca_list)):
2795 vca = vca_list[i]
2796 vca_status = vca_status_list[i]
garciadeblas5697b8b2021-03-24 09:17:02 +01002797 if vca.get("member-vnf-index") == r.get("entities")[
2798 0
2799 ].get("id"):
2800 if vca_status.get("status") == "BROKEN":
quilesj63f90042020-01-17 09:53:55 +00002801 # peer broken: remove relation from list
2802 ns_relations.remove(r)
garciadeblas5697b8b2021-03-24 09:17:02 +01002803 if vca.get("member-vnf-index") == r.get("entities")[
2804 1
2805 ].get("id"):
2806 if vca_status.get("status") == "BROKEN":
quilesj63f90042020-01-17 09:53:55 +00002807 # peer broken: remove relation from list
2808 ns_relations.remove(r)
2809 except Exception:
2810 # ignore
2811 pass
2812
2813 # for each defined VNF relation, find the VCA's related
tierno364c4572020-09-14 12:11:32 +00002814 for r in vnf_relations.copy():
quilesj63f90042020-01-17 09:53:55 +00002815 from_vca_ee_id = None
2816 to_vca_ee_id = None
2817 from_vca_endpoint = None
2818 to_vca_endpoint = None
garciadeblas5697b8b2021-03-24 09:17:02 +01002819 vca_list = deep_get(db_nsr, ("_admin", "deployed", "VCA"))
quilesj63f90042020-01-17 09:53:55 +00002820 for vca in vca_list:
David Garcia97be6832020-09-09 15:40:44 +02002821 key_to_check = "vdu_id"
2822 if vca.get("vdu_id") is None:
2823 key_to_check = "vnfd_id"
garciadeblas5697b8b2021-03-24 09:17:02 +01002824 if vca.get(key_to_check) == r.get("entities")[0].get(
2825 "id"
2826 ) and vca.get("config_sw_installed"):
2827 from_vca_ee_id = vca.get("ee_id")
2828 from_vca_endpoint = r.get("entities")[0].get("endpoint")
2829 if vca.get(key_to_check) == r.get("entities")[1].get(
2830 "id"
2831 ) and vca.get("config_sw_installed"):
2832 to_vca_ee_id = vca.get("ee_id")
2833 to_vca_endpoint = r.get("entities")[1].get("endpoint")
quilesj63f90042020-01-17 09:53:55 +00002834 if from_vca_ee_id and to_vca_ee_id:
2835 # add relation
tierno588547c2020-07-01 15:30:20 +00002836 await self.vca_map[vca_type].add_relation(
quilesj63f90042020-01-17 09:53:55 +00002837 ee_id_1=from_vca_ee_id,
2838 ee_id_2=to_vca_ee_id,
2839 endpoint_1=from_vca_endpoint,
David Garciac1fe90a2021-03-31 19:12:02 +02002840 endpoint_2=to_vca_endpoint,
2841 vca_id=vca_id,
2842 )
quilesj63f90042020-01-17 09:53:55 +00002843 # remove entry from relations list
2844 vnf_relations.remove(r)
2845 else:
2846 # check failed peers
2847 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01002848 vca_status_list = db_nsr.get("configurationStatus")
quilesj63f90042020-01-17 09:53:55 +00002849 if vca_status_list:
2850 for i in range(len(vca_list)):
2851 vca = vca_list[i]
2852 vca_status = vca_status_list[i]
garciadeblas5697b8b2021-03-24 09:17:02 +01002853 if vca.get("vdu_id") == r.get("entities")[0].get(
2854 "id"
2855 ):
2856 if vca_status.get("status") == "BROKEN":
quilesj63f90042020-01-17 09:53:55 +00002857 # peer broken: remove relation from list
David Garcia092afbd2020-08-25 13:17:25 +02002858 vnf_relations.remove(r)
garciadeblas5697b8b2021-03-24 09:17:02 +01002859 if vca.get("vdu_id") == r.get("entities")[1].get(
2860 "id"
2861 ):
2862 if vca_status.get("status") == "BROKEN":
quilesj63f90042020-01-17 09:53:55 +00002863 # peer broken: remove relation from list
David Garcia092afbd2020-08-25 13:17:25 +02002864 vnf_relations.remove(r)
quilesj63f90042020-01-17 09:53:55 +00002865 except Exception:
2866 # ignore
2867 pass
2868
2869 # wait for next try
2870 await asyncio.sleep(5.0)
2871
2872 if not ns_relations and not vnf_relations:
garciadeblas5697b8b2021-03-24 09:17:02 +01002873 self.logger.debug("Relations added")
quilesj63f90042020-01-17 09:53:55 +00002874 break
2875
2876 return True
2877
2878 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002879 self.logger.warn(logging_text + " ERROR adding relations: {}".format(e))
quilesj63f90042020-01-17 09:53:55 +00002880 return False
2881
garciadeblas5697b8b2021-03-24 09:17:02 +01002882 async def _install_kdu(
2883 self,
2884 nsr_id: str,
2885 nsr_db_path: str,
2886 vnfr_data: dict,
2887 kdu_index: int,
2888 kdud: dict,
2889 vnfd: dict,
2890 k8s_instance_info: dict,
2891 k8params: dict = None,
2892 timeout: int = 600,
2893 vca_id: str = None,
2894 ):
lloretgalleg7c121132020-07-08 07:53:22 +00002895
tiernob9018152020-04-16 14:18:24 +00002896 try:
lloretgalleg7c121132020-07-08 07:53:22 +00002897 k8sclustertype = k8s_instance_info["k8scluster-type"]
2898 # Instantiate kdu
garciadeblas5697b8b2021-03-24 09:17:02 +01002899 db_dict_install = {
2900 "collection": "nsrs",
2901 "filter": {"_id": nsr_id},
2902 "path": nsr_db_path,
2903 }
lloretgalleg7c121132020-07-08 07:53:22 +00002904
romeromonser4e71ab62021-05-28 12:06:34 +02002905 if k8s_instance_info.get("kdu-deployment-name"):
2906 kdu_instance = k8s_instance_info.get("kdu-deployment-name")
2907 else:
2908 kdu_instance = self.k8scluster_map[
2909 k8sclustertype
2910 ].generate_kdu_instance_name(
2911 db_dict=db_dict_install,
2912 kdu_model=k8s_instance_info["kdu-model"],
2913 kdu_name=k8s_instance_info["kdu-name"],
2914 )
garciadeblas5697b8b2021-03-24 09:17:02 +01002915 self.update_db_2(
2916 "nsrs", nsr_id, {nsr_db_path + ".kdu-instance": kdu_instance}
2917 )
David Garciad64e2742021-02-25 20:19:18 +01002918 await self.k8scluster_map[k8sclustertype].install(
lloretgalleg7c121132020-07-08 07:53:22 +00002919 cluster_uuid=k8s_instance_info["k8scluster-uuid"],
2920 kdu_model=k8s_instance_info["kdu-model"],
2921 atomic=True,
2922 params=k8params,
2923 db_dict=db_dict_install,
2924 timeout=timeout,
2925 kdu_name=k8s_instance_info["kdu-name"],
David Garciad64e2742021-02-25 20:19:18 +01002926 namespace=k8s_instance_info["namespace"],
2927 kdu_instance=kdu_instance,
David Garciac1fe90a2021-03-31 19:12:02 +02002928 vca_id=vca_id,
David Garciad64e2742021-02-25 20:19:18 +01002929 )
garciadeblas5697b8b2021-03-24 09:17:02 +01002930 self.update_db_2(
2931 "nsrs", nsr_id, {nsr_db_path + ".kdu-instance": kdu_instance}
2932 )
lloretgalleg7c121132020-07-08 07:53:22 +00002933
2934 # Obtain services to obtain management service ip
2935 services = await self.k8scluster_map[k8sclustertype].get_services(
2936 cluster_uuid=k8s_instance_info["k8scluster-uuid"],
2937 kdu_instance=kdu_instance,
garciadeblas5697b8b2021-03-24 09:17:02 +01002938 namespace=k8s_instance_info["namespace"],
2939 )
lloretgalleg7c121132020-07-08 07:53:22 +00002940
2941 # Obtain management service info (if exists)
tierno7ecbc342020-09-21 14:05:39 +00002942 vnfr_update_dict = {}
bravof6ec62b72021-02-25 17:20:35 -03002943 kdu_config = get_configuration(vnfd, kdud["name"])
2944 if kdu_config:
2945 target_ee_list = kdu_config.get("execution-environment-list", [])
2946 else:
2947 target_ee_list = []
2948
lloretgalleg7c121132020-07-08 07:53:22 +00002949 if services:
tierno7ecbc342020-09-21 14:05:39 +00002950 vnfr_update_dict["kdur.{}.services".format(kdu_index)] = services
garciadeblas5697b8b2021-03-24 09:17:02 +01002951 mgmt_services = [
2952 service
2953 for service in kdud.get("service", [])
2954 if service.get("mgmt-service")
2955 ]
lloretgalleg7c121132020-07-08 07:53:22 +00002956 for mgmt_service in mgmt_services:
2957 for service in services:
2958 if service["name"].startswith(mgmt_service["name"]):
2959 # Mgmt service found, Obtain service ip
2960 ip = service.get("external_ip", service.get("cluster_ip"))
2961 if isinstance(ip, list) and len(ip) == 1:
2962 ip = ip[0]
2963
garciadeblas5697b8b2021-03-24 09:17:02 +01002964 vnfr_update_dict[
2965 "kdur.{}.ip-address".format(kdu_index)
2966 ] = ip
lloretgalleg7c121132020-07-08 07:53:22 +00002967
2968 # Check if must update also mgmt ip at the vnf
garciadeblas5697b8b2021-03-24 09:17:02 +01002969 service_external_cp = mgmt_service.get(
2970 "external-connection-point-ref"
2971 )
lloretgalleg7c121132020-07-08 07:53:22 +00002972 if service_external_cp:
garciadeblas5697b8b2021-03-24 09:17:02 +01002973 if (
2974 deep_get(vnfd, ("mgmt-interface", "cp"))
2975 == service_external_cp
2976 ):
lloretgalleg7c121132020-07-08 07:53:22 +00002977 vnfr_update_dict["ip-address"] = ip
2978
bravof6ec62b72021-02-25 17:20:35 -03002979 if find_in_list(
2980 target_ee_list,
garciadeblas5697b8b2021-03-24 09:17:02 +01002981 lambda ee: ee.get(
2982 "external-connection-point-ref", ""
2983 )
2984 == service_external_cp,
bravof6ec62b72021-02-25 17:20:35 -03002985 ):
garciadeblas5697b8b2021-03-24 09:17:02 +01002986 vnfr_update_dict[
2987 "kdur.{}.ip-address".format(kdu_index)
2988 ] = ip
lloretgalleg7c121132020-07-08 07:53:22 +00002989 break
2990 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01002991 self.logger.warn(
2992 "Mgmt service name: {} not found".format(
2993 mgmt_service["name"]
2994 )
2995 )
lloretgalleg7c121132020-07-08 07:53:22 +00002996
tierno7ecbc342020-09-21 14:05:39 +00002997 vnfr_update_dict["kdur.{}.status".format(kdu_index)] = "READY"
2998 self.update_db_2("vnfrs", vnfr_data.get("_id"), vnfr_update_dict)
lloretgalleg7c121132020-07-08 07:53:22 +00002999
bravof9a256db2021-02-22 18:02:07 -03003000 kdu_config = get_configuration(vnfd, k8s_instance_info["kdu-name"])
garciadeblas5697b8b2021-03-24 09:17:02 +01003001 if (
3002 kdu_config
3003 and kdu_config.get("initial-config-primitive")
3004 and get_juju_ee_ref(vnfd, k8s_instance_info["kdu-name"]) is None
3005 ):
3006 initial_config_primitive_list = kdu_config.get(
3007 "initial-config-primitive"
3008 )
Dominik Fleischmannc1975dd2020-08-19 12:17:51 +02003009 initial_config_primitive_list.sort(key=lambda val: int(val["seq"]))
3010
3011 for initial_config_primitive in initial_config_primitive_list:
garciadeblas5697b8b2021-03-24 09:17:02 +01003012 primitive_params_ = self._map_primitive_params(
3013 initial_config_primitive, {}, {}
3014 )
Dominik Fleischmannc1975dd2020-08-19 12:17:51 +02003015
3016 await asyncio.wait_for(
3017 self.k8scluster_map[k8sclustertype].exec_primitive(
3018 cluster_uuid=k8s_instance_info["k8scluster-uuid"],
3019 kdu_instance=kdu_instance,
3020 primitive_name=initial_config_primitive["name"],
garciadeblas5697b8b2021-03-24 09:17:02 +01003021 params=primitive_params_,
3022 db_dict=db_dict_install,
David Garciac1fe90a2021-03-31 19:12:02 +02003023 vca_id=vca_id,
3024 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01003025 timeout=timeout,
David Garciac1fe90a2021-03-31 19:12:02 +02003026 )
Dominik Fleischmannc1975dd2020-08-19 12:17:51 +02003027
tiernob9018152020-04-16 14:18:24 +00003028 except Exception as e:
lloretgalleg7c121132020-07-08 07:53:22 +00003029 # Prepare update db with error and raise exception
tiernob9018152020-04-16 14:18:24 +00003030 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01003031 self.update_db_2(
3032 "nsrs", nsr_id, {nsr_db_path + ".detailed-status": str(e)}
3033 )
3034 self.update_db_2(
3035 "vnfrs",
3036 vnfr_data.get("_id"),
3037 {"kdur.{}.status".format(kdu_index): "ERROR"},
3038 )
tiernob9018152020-04-16 14:18:24 +00003039 except Exception:
lloretgalleg7c121132020-07-08 07:53:22 +00003040 # ignore to keep original exception
tiernob9018152020-04-16 14:18:24 +00003041 pass
lloretgalleg7c121132020-07-08 07:53:22 +00003042 # reraise original error
3043 raise
3044
3045 return kdu_instance
tiernob9018152020-04-16 14:18:24 +00003046
garciadeblas5697b8b2021-03-24 09:17:02 +01003047 async def deploy_kdus(
3048 self,
3049 logging_text,
3050 nsr_id,
3051 nslcmop_id,
3052 db_vnfrs,
3053 db_vnfds,
3054 task_instantiation_info,
3055 ):
calvinosanch9f9c6f22019-11-04 13:37:39 +01003056 # Launch kdus if present in the descriptor
tierno626e0152019-11-29 14:16:16 +00003057
garciadeblas5697b8b2021-03-24 09:17:02 +01003058 k8scluster_id_2_uuic = {
3059 "helm-chart-v3": {},
3060 "helm-chart": {},
3061 "juju-bundle": {},
3062 }
tierno626e0152019-11-29 14:16:16 +00003063
tierno16f4a4e2020-07-20 09:05:51 +00003064 async def _get_cluster_id(cluster_id, cluster_type):
tierno626e0152019-11-29 14:16:16 +00003065 nonlocal k8scluster_id_2_uuic
3066 if cluster_id in k8scluster_id_2_uuic[cluster_type]:
3067 return k8scluster_id_2_uuic[cluster_type][cluster_id]
3068
tierno16f4a4e2020-07-20 09:05:51 +00003069 # check if K8scluster is creating and wait look if previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +01003070 task_name, task_dependency = self.lcm_tasks.lookfor_related(
3071 "k8scluster", cluster_id
3072 )
tierno16f4a4e2020-07-20 09:05:51 +00003073 if task_dependency:
garciadeblas5697b8b2021-03-24 09:17:02 +01003074 text = "Waiting for related tasks '{}' on k8scluster {} to be completed".format(
3075 task_name, cluster_id
3076 )
tierno16f4a4e2020-07-20 09:05:51 +00003077 self.logger.debug(logging_text + text)
3078 await asyncio.wait(task_dependency, timeout=3600)
3079
garciadeblas5697b8b2021-03-24 09:17:02 +01003080 db_k8scluster = self.db.get_one(
3081 "k8sclusters", {"_id": cluster_id}, fail_on_empty=False
3082 )
tierno626e0152019-11-29 14:16:16 +00003083 if not db_k8scluster:
3084 raise LcmException("K8s cluster {} cannot be found".format(cluster_id))
tierno16f4a4e2020-07-20 09:05:51 +00003085
tierno626e0152019-11-29 14:16:16 +00003086 k8s_id = deep_get(db_k8scluster, ("_admin", cluster_type, "id"))
3087 if not k8s_id:
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003088 if cluster_type == "helm-chart-v3":
3089 try:
3090 # backward compatibility for existing clusters that have not been initialized for helm v3
garciadeblas5697b8b2021-03-24 09:17:02 +01003091 k8s_credentials = yaml.safe_dump(
3092 db_k8scluster.get("credentials")
3093 )
3094 k8s_id, uninstall_sw = await self.k8sclusterhelm3.init_env(
3095 k8s_credentials, reuse_cluster_uuid=cluster_id
3096 )
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003097 db_k8scluster_update = {}
3098 db_k8scluster_update["_admin.helm-chart-v3.error_msg"] = None
3099 db_k8scluster_update["_admin.helm-chart-v3.id"] = k8s_id
garciadeblas5697b8b2021-03-24 09:17:02 +01003100 db_k8scluster_update[
3101 "_admin.helm-chart-v3.created"
3102 ] = uninstall_sw
3103 db_k8scluster_update[
3104 "_admin.helm-chart-v3.operationalState"
3105 ] = "ENABLED"
3106 self.update_db_2(
3107 "k8sclusters", cluster_id, db_k8scluster_update
3108 )
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003109 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01003110 self.logger.error(
3111 logging_text
3112 + "error initializing helm-v3 cluster: {}".format(str(e))
3113 )
3114 raise LcmException(
3115 "K8s cluster '{}' has not been initialized for '{}'".format(
3116 cluster_id, cluster_type
3117 )
3118 )
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003119 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01003120 raise LcmException(
3121 "K8s cluster '{}' has not been initialized for '{}'".format(
3122 cluster_id, cluster_type
3123 )
3124 )
tierno626e0152019-11-29 14:16:16 +00003125 k8scluster_id_2_uuic[cluster_type][cluster_id] = k8s_id
3126 return k8s_id
3127
3128 logging_text += "Deploy kdus: "
tiernoe876f672020-02-13 14:34:48 +00003129 step = ""
calvinosanch9f9c6f22019-11-04 13:37:39 +01003130 try:
tierno626e0152019-11-29 14:16:16 +00003131 db_nsr_update = {"_admin.deployed.K8s": []}
calvinosanch9f9c6f22019-11-04 13:37:39 +01003132 self.update_db_2("nsrs", nsr_id, db_nsr_update)
calvinosanch9f9c6f22019-11-04 13:37:39 +01003133
tierno626e0152019-11-29 14:16:16 +00003134 index = 0
tiernoe876f672020-02-13 14:34:48 +00003135 updated_cluster_list = []
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003136 updated_v3_cluster_list = []
tiernoe876f672020-02-13 14:34:48 +00003137
tierno626e0152019-11-29 14:16:16 +00003138 for vnfr_data in db_vnfrs.values():
David Garciac1fe90a2021-03-31 19:12:02 +02003139 vca_id = self.get_vca_id(vnfr_data, {})
lloretgalleg7c121132020-07-08 07:53:22 +00003140 for kdu_index, kdur in enumerate(get_iterable(vnfr_data, "kdur")):
3141 # Step 0: Prepare and set parameters
bravof922c4172020-11-24 21:21:43 -03003142 desc_params = parse_yaml_strings(kdur.get("additionalParams"))
garciadeblas5697b8b2021-03-24 09:17:02 +01003143 vnfd_id = vnfr_data.get("vnfd-id")
3144 vnfd_with_id = find_in_list(
3145 db_vnfds, lambda vnfd: vnfd["_id"] == vnfd_id
3146 )
3147 kdud = next(
3148 kdud
3149 for kdud in vnfd_with_id["kdu"]
3150 if kdud["name"] == kdur["kdu-name"]
3151 )
tiernode1584f2020-04-07 09:07:33 +00003152 namespace = kdur.get("k8s-namespace")
romeromonser4e71ab62021-05-28 12:06:34 +02003153 kdu_deployment_name = kdur.get("kdu-deployment-name")
tierno626e0152019-11-29 14:16:16 +00003154 if kdur.get("helm-chart"):
lloretgalleg07e53f52020-12-15 10:54:02 +00003155 kdumodel = kdur["helm-chart"]
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003156 # Default version: helm3, if helm-version is v2 assign v2
3157 k8sclustertype = "helm-chart-v3"
3158 self.logger.debug("kdur: {}".format(kdur))
garciadeblas5697b8b2021-03-24 09:17:02 +01003159 if (
3160 kdur.get("helm-version")
3161 and kdur.get("helm-version") == "v2"
3162 ):
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003163 k8sclustertype = "helm-chart"
tierno626e0152019-11-29 14:16:16 +00003164 elif kdur.get("juju-bundle"):
lloretgalleg07e53f52020-12-15 10:54:02 +00003165 kdumodel = kdur["juju-bundle"]
tiernoe876f672020-02-13 14:34:48 +00003166 k8sclustertype = "juju-bundle"
tierno626e0152019-11-29 14:16:16 +00003167 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01003168 raise LcmException(
3169 "kdu type for kdu='{}.{}' is neither helm-chart nor "
3170 "juju-bundle. Maybe an old NBI version is running".format(
3171 vnfr_data["member-vnf-index-ref"], kdur["kdu-name"]
3172 )
3173 )
quilesjacde94f2020-01-23 10:07:08 +00003174 # check if kdumodel is a file and exists
3175 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01003176 vnfd_with_id = find_in_list(
3177 db_vnfds, lambda vnfd: vnfd["_id"] == vnfd_id
3178 )
3179 storage = deep_get(vnfd_with_id, ("_admin", "storage"))
3180 if storage and storage.get(
3181 "pkg-dir"
3182 ): # may be not present if vnfd has not artifacts
tierno51183952020-04-03 15:48:18 +00003183 # path format: /vnfdid/pkkdir/helm-charts|juju-bundles/kdumodel
garciadeblas5697b8b2021-03-24 09:17:02 +01003184 filename = "{}/{}/{}s/{}".format(
3185 storage["folder"],
3186 storage["pkg-dir"],
3187 k8sclustertype,
3188 kdumodel,
3189 )
3190 if self.fs.file_exists(
3191 filename, mode="file"
3192 ) or self.fs.file_exists(filename, mode="dir"):
tierno51183952020-04-03 15:48:18 +00003193 kdumodel = self.fs.path + filename
3194 except (asyncio.TimeoutError, asyncio.CancelledError):
tiernoe876f672020-02-13 14:34:48 +00003195 raise
garciadeblas5697b8b2021-03-24 09:17:02 +01003196 except Exception: # it is not a file
quilesjacde94f2020-01-23 10:07:08 +00003197 pass
lloretgallegedc5f332020-02-20 11:50:50 +01003198
tiernoe876f672020-02-13 14:34:48 +00003199 k8s_cluster_id = kdur["k8s-cluster"]["id"]
garciadeblas5697b8b2021-03-24 09:17:02 +01003200 step = "Synchronize repos for k8s cluster '{}'".format(
3201 k8s_cluster_id
3202 )
tierno16f4a4e2020-07-20 09:05:51 +00003203 cluster_uuid = await _get_cluster_id(k8s_cluster_id, k8sclustertype)
lloretgallegedc5f332020-02-20 11:50:50 +01003204
lloretgalleg7c121132020-07-08 07:53:22 +00003205 # Synchronize repos
garciadeblas5697b8b2021-03-24 09:17:02 +01003206 if (
3207 k8sclustertype == "helm-chart"
3208 and cluster_uuid not in updated_cluster_list
3209 ) or (
3210 k8sclustertype == "helm-chart-v3"
3211 and cluster_uuid not in updated_v3_cluster_list
3212 ):
tiernoe876f672020-02-13 14:34:48 +00003213 del_repo_list, added_repo_dict = await asyncio.ensure_future(
garciadeblas5697b8b2021-03-24 09:17:02 +01003214 self.k8scluster_map[k8sclustertype].synchronize_repos(
3215 cluster_uuid=cluster_uuid
3216 )
3217 )
tiernoe876f672020-02-13 14:34:48 +00003218 if del_repo_list or added_repo_dict:
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003219 if k8sclustertype == "helm-chart":
garciadeblas5697b8b2021-03-24 09:17:02 +01003220 unset = {
3221 "_admin.helm_charts_added." + item: None
3222 for item in del_repo_list
3223 }
3224 updated = {
3225 "_admin.helm_charts_added." + item: name
3226 for item, name in added_repo_dict.items()
3227 }
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003228 updated_cluster_list.append(cluster_uuid)
3229 elif k8sclustertype == "helm-chart-v3":
garciadeblas5697b8b2021-03-24 09:17:02 +01003230 unset = {
3231 "_admin.helm_charts_v3_added." + item: None
3232 for item in del_repo_list
3233 }
3234 updated = {
3235 "_admin.helm_charts_v3_added." + item: name
3236 for item, name in added_repo_dict.items()
3237 }
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003238 updated_v3_cluster_list.append(cluster_uuid)
garciadeblas5697b8b2021-03-24 09:17:02 +01003239 self.logger.debug(
3240 logging_text + "repos synchronized on k8s cluster "
3241 "'{}' to_delete: {}, to_add: {}".format(
3242 k8s_cluster_id, del_repo_list, added_repo_dict
3243 )
3244 )
3245 self.db.set_one(
3246 "k8sclusters",
3247 {"_id": k8s_cluster_id},
3248 updated,
3249 unset=unset,
3250 )
lloretgallegedc5f332020-02-20 11:50:50 +01003251
lloretgalleg7c121132020-07-08 07:53:22 +00003252 # Instantiate kdu
garciadeblas5697b8b2021-03-24 09:17:02 +01003253 step = "Instantiating KDU {}.{} in k8s cluster {}".format(
3254 vnfr_data["member-vnf-index-ref"],
3255 kdur["kdu-name"],
3256 k8s_cluster_id,
3257 )
3258 k8s_instance_info = {
3259 "kdu-instance": None,
3260 "k8scluster-uuid": cluster_uuid,
3261 "k8scluster-type": k8sclustertype,
3262 "member-vnf-index": vnfr_data["member-vnf-index-ref"],
3263 "kdu-name": kdur["kdu-name"],
3264 "kdu-model": kdumodel,
3265 "namespace": namespace,
romeromonser4e71ab62021-05-28 12:06:34 +02003266 "kdu-deployment-name": kdu_deployment_name,
garciadeblas5697b8b2021-03-24 09:17:02 +01003267 }
tiernob9018152020-04-16 14:18:24 +00003268 db_path = "_admin.deployed.K8s.{}".format(index)
lloretgalleg7c121132020-07-08 07:53:22 +00003269 db_nsr_update[db_path] = k8s_instance_info
tierno626e0152019-11-29 14:16:16 +00003270 self.update_db_2("nsrs", nsr_id, db_nsr_update)
garciadeblas5697b8b2021-03-24 09:17:02 +01003271 vnfd_with_id = find_in_list(
3272 db_vnfds, lambda vnf: vnf["_id"] == vnfd_id
3273 )
tiernoa2143262020-03-27 16:20:40 +00003274 task = asyncio.ensure_future(
garciadeblas5697b8b2021-03-24 09:17:02 +01003275 self._install_kdu(
3276 nsr_id,
3277 db_path,
3278 vnfr_data,
3279 kdu_index,
3280 kdud,
3281 vnfd_with_id,
3282 k8s_instance_info,
3283 k8params=desc_params,
3284 timeout=600,
3285 vca_id=vca_id,
3286 )
3287 )
3288 self.lcm_tasks.register(
3289 "ns",
3290 nsr_id,
3291 nslcmop_id,
3292 "instantiate_KDU-{}".format(index),
3293 task,
3294 )
3295 task_instantiation_info[task] = "Deploying KDU {}".format(
3296 kdur["kdu-name"]
3297 )
tiernoe876f672020-02-13 14:34:48 +00003298
tierno626e0152019-11-29 14:16:16 +00003299 index += 1
quilesjdd799ac2020-01-23 16:31:11 +00003300
tiernoe876f672020-02-13 14:34:48 +00003301 except (LcmException, asyncio.CancelledError):
3302 raise
calvinosanch9f9c6f22019-11-04 13:37:39 +01003303 except Exception as e:
tiernoe876f672020-02-13 14:34:48 +00003304 msg = "Exception {} while {}: {}".format(type(e).__name__, step, e)
3305 if isinstance(e, (N2VCException, DbException)):
3306 self.logger.error(logging_text + msg)
3307 else:
3308 self.logger.critical(logging_text + msg, exc_info=True)
quilesjdd799ac2020-01-23 16:31:11 +00003309 raise LcmException(msg)
calvinosanch9f9c6f22019-11-04 13:37:39 +01003310 finally:
calvinosanch9f9c6f22019-11-04 13:37:39 +01003311 if db_nsr_update:
3312 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernoda6fb102019-11-23 00:36:52 +00003313
garciadeblas5697b8b2021-03-24 09:17:02 +01003314 def _deploy_n2vc(
3315 self,
3316 logging_text,
3317 db_nsr,
3318 db_vnfr,
3319 nslcmop_id,
3320 nsr_id,
3321 nsi_id,
3322 vnfd_id,
3323 vdu_id,
3324 kdu_name,
3325 member_vnf_index,
3326 vdu_index,
3327 vdu_name,
3328 deploy_params,
3329 descriptor_config,
3330 base_folder,
3331 task_instantiation_info,
3332 stage,
3333 ):
quilesj7e13aeb2019-10-08 13:34:55 +02003334 # launch instantiate_N2VC in a asyncio task and register task object
3335 # Look where information of this charm is at database <nsrs>._admin.deployed.VCA
3336 # if not found, create one entry and update database
quilesj7e13aeb2019-10-08 13:34:55 +02003337 # fill db_nsr._admin.deployed.VCA.<index>
tierno588547c2020-07-01 15:30:20 +00003338
garciadeblas5697b8b2021-03-24 09:17:02 +01003339 self.logger.debug(
3340 logging_text + "_deploy_n2vc vnfd_id={}, vdu_id={}".format(vnfd_id, vdu_id)
3341 )
bravof9a256db2021-02-22 18:02:07 -03003342 if "execution-environment-list" in descriptor_config:
3343 ee_list = descriptor_config.get("execution-environment-list", [])
David Garciab76442a2021-05-28 12:08:18 +02003344 elif "juju" in descriptor_config:
3345 ee_list = [descriptor_config] # ns charms
tierno588547c2020-07-01 15:30:20 +00003346 else: # other types as script are not supported
3347 ee_list = []
3348
3349 for ee_item in ee_list:
garciadeblas5697b8b2021-03-24 09:17:02 +01003350 self.logger.debug(
3351 logging_text
3352 + "_deploy_n2vc ee_item juju={}, helm={}".format(
3353 ee_item.get("juju"), ee_item.get("helm-chart")
3354 )
3355 )
tiernoa278b842020-07-08 15:33:55 +00003356 ee_descriptor_id = ee_item.get("id")
tierno588547c2020-07-01 15:30:20 +00003357 if ee_item.get("juju"):
garciadeblas5697b8b2021-03-24 09:17:02 +01003358 vca_name = ee_item["juju"].get("charm")
3359 vca_type = (
3360 "lxc_proxy_charm"
3361 if ee_item["juju"].get("charm") is not None
3362 else "native_charm"
3363 )
3364 if ee_item["juju"].get("cloud") == "k8s":
tierno588547c2020-07-01 15:30:20 +00003365 vca_type = "k8s_proxy_charm"
garciadeblas5697b8b2021-03-24 09:17:02 +01003366 elif ee_item["juju"].get("proxy") is False:
tierno588547c2020-07-01 15:30:20 +00003367 vca_type = "native_charm"
3368 elif ee_item.get("helm-chart"):
garciadeblas5697b8b2021-03-24 09:17:02 +01003369 vca_name = ee_item["helm-chart"]
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003370 if ee_item.get("helm-version") and ee_item.get("helm-version") == "v2":
3371 vca_type = "helm"
3372 else:
3373 vca_type = "helm-v3"
tierno588547c2020-07-01 15:30:20 +00003374 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01003375 self.logger.debug(
3376 logging_text + "skipping non juju neither charm configuration"
3377 )
quilesj7e13aeb2019-10-08 13:34:55 +02003378 continue
quilesj3655ae02019-12-12 16:08:35 +00003379
tierno588547c2020-07-01 15:30:20 +00003380 vca_index = -1
garciadeblas5697b8b2021-03-24 09:17:02 +01003381 for vca_index, vca_deployed in enumerate(
3382 db_nsr["_admin"]["deployed"]["VCA"]
3383 ):
tierno588547c2020-07-01 15:30:20 +00003384 if not vca_deployed:
3385 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01003386 if (
3387 vca_deployed.get("member-vnf-index") == member_vnf_index
3388 and vca_deployed.get("vdu_id") == vdu_id
3389 and vca_deployed.get("kdu_name") == kdu_name
3390 and vca_deployed.get("vdu_count_index", 0) == vdu_index
3391 and vca_deployed.get("ee_descriptor_id") == ee_descriptor_id
3392 ):
tierno588547c2020-07-01 15:30:20 +00003393 break
3394 else:
3395 # not found, create one.
garciadeblas5697b8b2021-03-24 09:17:02 +01003396 target = (
3397 "ns" if not member_vnf_index else "vnf/{}".format(member_vnf_index)
3398 )
tiernoa278b842020-07-08 15:33:55 +00003399 if vdu_id:
3400 target += "/vdu/{}/{}".format(vdu_id, vdu_index or 0)
3401 elif kdu_name:
3402 target += "/kdu/{}".format(kdu_name)
tierno588547c2020-07-01 15:30:20 +00003403 vca_deployed = {
tiernoa278b842020-07-08 15:33:55 +00003404 "target_element": target,
3405 # ^ target_element will replace member-vnf-index, kdu_name, vdu_id ... in a single string
tierno588547c2020-07-01 15:30:20 +00003406 "member-vnf-index": member_vnf_index,
3407 "vdu_id": vdu_id,
3408 "kdu_name": kdu_name,
3409 "vdu_count_index": vdu_index,
3410 "operational-status": "init", # TODO revise
3411 "detailed-status": "", # TODO revise
garciadeblas5697b8b2021-03-24 09:17:02 +01003412 "step": "initial-deploy", # TODO revise
tierno588547c2020-07-01 15:30:20 +00003413 "vnfd_id": vnfd_id,
3414 "vdu_name": vdu_name,
tiernoa278b842020-07-08 15:33:55 +00003415 "type": vca_type,
garciadeblas5697b8b2021-03-24 09:17:02 +01003416 "ee_descriptor_id": ee_descriptor_id,
tierno588547c2020-07-01 15:30:20 +00003417 }
3418 vca_index += 1
quilesj3655ae02019-12-12 16:08:35 +00003419
tierno588547c2020-07-01 15:30:20 +00003420 # create VCA and configurationStatus in db
3421 db_dict = {
3422 "_admin.deployed.VCA.{}".format(vca_index): vca_deployed,
garciadeblas5697b8b2021-03-24 09:17:02 +01003423 "configurationStatus.{}".format(vca_index): dict(),
tierno588547c2020-07-01 15:30:20 +00003424 }
3425 self.update_db_2("nsrs", nsr_id, db_dict)
quilesj7e13aeb2019-10-08 13:34:55 +02003426
tierno588547c2020-07-01 15:30:20 +00003427 db_nsr["_admin"]["deployed"]["VCA"].append(vca_deployed)
3428
bravof922c4172020-11-24 21:21:43 -03003429 self.logger.debug("N2VC > NSR_ID > {}".format(nsr_id))
3430 self.logger.debug("N2VC > DB_NSR > {}".format(db_nsr))
3431 self.logger.debug("N2VC > VCA_DEPLOYED > {}".format(vca_deployed))
3432
tierno588547c2020-07-01 15:30:20 +00003433 # Launch task
3434 task_n2vc = asyncio.ensure_future(
3435 self.instantiate_N2VC(
3436 logging_text=logging_text,
3437 vca_index=vca_index,
3438 nsi_id=nsi_id,
3439 db_nsr=db_nsr,
3440 db_vnfr=db_vnfr,
3441 vdu_id=vdu_id,
3442 kdu_name=kdu_name,
3443 vdu_index=vdu_index,
3444 deploy_params=deploy_params,
3445 config_descriptor=descriptor_config,
3446 base_folder=base_folder,
3447 nslcmop_id=nslcmop_id,
3448 stage=stage,
3449 vca_type=vca_type,
tiernob996d942020-07-03 14:52:28 +00003450 vca_name=vca_name,
garciadeblas5697b8b2021-03-24 09:17:02 +01003451 ee_config_descriptor=ee_item,
tierno588547c2020-07-01 15:30:20 +00003452 )
quilesj7e13aeb2019-10-08 13:34:55 +02003453 )
garciadeblas5697b8b2021-03-24 09:17:02 +01003454 self.lcm_tasks.register(
3455 "ns",
3456 nsr_id,
3457 nslcmop_id,
3458 "instantiate_N2VC-{}".format(vca_index),
3459 task_n2vc,
3460 )
3461 task_instantiation_info[
3462 task_n2vc
3463 ] = self.task_name_deploy_vca + " {}.{}".format(
3464 member_vnf_index or "", vdu_id or ""
3465 )
tiernobaa51102018-12-14 13:16:18 +00003466
tiernoc9556972019-07-05 15:25:25 +00003467 @staticmethod
kuuse0ca67472019-05-13 15:59:27 +02003468 def _create_nslcmop(nsr_id, operation, params):
3469 """
3470 Creates a ns-lcm-opp content to be stored at database.
3471 :param nsr_id: internal id of the instance
3472 :param operation: instantiate, terminate, scale, action, ...
3473 :param params: user parameters for the operation
3474 :return: dictionary following SOL005 format
3475 """
3476 # Raise exception if invalid arguments
3477 if not (nsr_id and operation and params):
3478 raise LcmException(
garciadeblas5697b8b2021-03-24 09:17:02 +01003479 "Parameters 'nsr_id', 'operation' and 'params' needed to create primitive not provided"
3480 )
kuuse0ca67472019-05-13 15:59:27 +02003481 now = time()
3482 _id = str(uuid4())
3483 nslcmop = {
3484 "id": _id,
3485 "_id": _id,
3486 # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
3487 "operationState": "PROCESSING",
3488 "statusEnteredTime": now,
3489 "nsInstanceId": nsr_id,
3490 "lcmOperationType": operation,
3491 "startTime": now,
3492 "isAutomaticInvocation": False,
3493 "operationParams": params,
3494 "isCancelPending": False,
3495 "links": {
3496 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
3497 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01003498 },
kuuse0ca67472019-05-13 15:59:27 +02003499 }
3500 return nslcmop
3501
calvinosanch9f9c6f22019-11-04 13:37:39 +01003502 def _format_additional_params(self, params):
tierno626e0152019-11-29 14:16:16 +00003503 params = params or {}
calvinosanch9f9c6f22019-11-04 13:37:39 +01003504 for key, value in params.items():
3505 if str(value).startswith("!!yaml "):
3506 params[key] = yaml.safe_load(value[7:])
calvinosanch9f9c6f22019-11-04 13:37:39 +01003507 return params
3508
kuuse8b998e42019-07-30 15:22:16 +02003509 def _get_terminate_primitive_params(self, seq, vnf_index):
garciadeblas5697b8b2021-03-24 09:17:02 +01003510 primitive = seq.get("name")
kuuse8b998e42019-07-30 15:22:16 +02003511 primitive_params = {}
3512 params = {
3513 "member_vnf_index": vnf_index,
3514 "primitive": primitive,
3515 "primitive_params": primitive_params,
3516 }
3517 desc_params = {}
3518 return self._map_primitive_params(seq, params, desc_params)
3519
kuuseac3a8882019-10-03 10:48:06 +02003520 # sub-operations
3521
tierno51183952020-04-03 15:48:18 +00003522 def _retry_or_skip_suboperation(self, db_nslcmop, op_index):
garciadeblas5697b8b2021-03-24 09:17:02 +01003523 op = deep_get(db_nslcmop, ("_admin", "operations"), [])[op_index]
3524 if op.get("operationState") == "COMPLETED":
kuuseac3a8882019-10-03 10:48:06 +02003525 # b. Skip sub-operation
3526 # _ns_execute_primitive() or RO.create_action() will NOT be executed
3527 return self.SUBOPERATION_STATUS_SKIP
3528 else:
tierno7c4e24c2020-05-13 08:41:35 +00003529 # c. retry executing sub-operation
kuuseac3a8882019-10-03 10:48:06 +02003530 # The sub-operation exists, and operationState != 'COMPLETED'
tierno7c4e24c2020-05-13 08:41:35 +00003531 # Update operationState = 'PROCESSING' to indicate a retry.
garciadeblas5697b8b2021-03-24 09:17:02 +01003532 operationState = "PROCESSING"
3533 detailed_status = "In progress"
kuuseac3a8882019-10-03 10:48:06 +02003534 self._update_suboperation_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01003535 db_nslcmop, op_index, operationState, detailed_status
3536 )
kuuseac3a8882019-10-03 10:48:06 +02003537 # Return the sub-operation index
3538 # _ns_execute_primitive() or RO.create_action() will be called from scale()
3539 # with arguments extracted from the sub-operation
3540 return op_index
3541
3542 # Find a sub-operation where all keys in a matching dictionary must match
3543 # Returns the index of the matching sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if no match
3544 def _find_suboperation(self, db_nslcmop, match):
tierno7c4e24c2020-05-13 08:41:35 +00003545 if db_nslcmop and match:
garciadeblas5697b8b2021-03-24 09:17:02 +01003546 op_list = db_nslcmop.get("_admin", {}).get("operations", [])
kuuseac3a8882019-10-03 10:48:06 +02003547 for i, op in enumerate(op_list):
3548 if all(op.get(k) == match[k] for k in match):
3549 return i
3550 return self.SUBOPERATION_STATUS_NOT_FOUND
3551
3552 # Update status for a sub-operation given its index
garciadeblas5697b8b2021-03-24 09:17:02 +01003553 def _update_suboperation_status(
3554 self, db_nslcmop, op_index, operationState, detailed_status
3555 ):
kuuseac3a8882019-10-03 10:48:06 +02003556 # Update DB for HA tasks
garciadeblas5697b8b2021-03-24 09:17:02 +01003557 q_filter = {"_id": db_nslcmop["_id"]}
3558 update_dict = {
3559 "_admin.operations.{}.operationState".format(op_index): operationState,
3560 "_admin.operations.{}.detailed-status".format(op_index): detailed_status,
3561 }
3562 self.db.set_one(
3563 "nslcmops", q_filter=q_filter, update_dict=update_dict, fail_on_empty=False
3564 )
kuuseac3a8882019-10-03 10:48:06 +02003565
3566 # Add sub-operation, return the index of the added sub-operation
3567 # Optionally, set operationState, detailed-status, and operationType
3568 # Status and type are currently set for 'scale' sub-operations:
3569 # 'operationState' : 'PROCESSING' | 'COMPLETED' | 'FAILED'
3570 # 'detailed-status' : status message
3571 # 'operationType': may be any type, in the case of scaling: 'PRE-SCALE' | 'POST-SCALE'
3572 # Status and operation type are currently only used for 'scale', but NOT for 'terminate' sub-operations.
garciadeblas5697b8b2021-03-24 09:17:02 +01003573 def _add_suboperation(
3574 self,
3575 db_nslcmop,
3576 vnf_index,
3577 vdu_id,
3578 vdu_count_index,
3579 vdu_name,
3580 primitive,
3581 mapped_primitive_params,
3582 operationState=None,
3583 detailed_status=None,
3584 operationType=None,
3585 RO_nsr_id=None,
3586 RO_scaling_info=None,
3587 ):
tiernoe876f672020-02-13 14:34:48 +00003588 if not db_nslcmop:
kuuseac3a8882019-10-03 10:48:06 +02003589 return self.SUBOPERATION_STATUS_NOT_FOUND
3590 # Get the "_admin.operations" list, if it exists
garciadeblas5697b8b2021-03-24 09:17:02 +01003591 db_nslcmop_admin = db_nslcmop.get("_admin", {})
3592 op_list = db_nslcmop_admin.get("operations")
kuuseac3a8882019-10-03 10:48:06 +02003593 # Create or append to the "_admin.operations" list
garciadeblas5697b8b2021-03-24 09:17:02 +01003594 new_op = {
3595 "member_vnf_index": vnf_index,
3596 "vdu_id": vdu_id,
3597 "vdu_count_index": vdu_count_index,
3598 "primitive": primitive,
3599 "primitive_params": mapped_primitive_params,
3600 }
kuuseac3a8882019-10-03 10:48:06 +02003601 if operationState:
garciadeblas5697b8b2021-03-24 09:17:02 +01003602 new_op["operationState"] = operationState
kuuseac3a8882019-10-03 10:48:06 +02003603 if detailed_status:
garciadeblas5697b8b2021-03-24 09:17:02 +01003604 new_op["detailed-status"] = detailed_status
kuuseac3a8882019-10-03 10:48:06 +02003605 if operationType:
garciadeblas5697b8b2021-03-24 09:17:02 +01003606 new_op["lcmOperationType"] = operationType
kuuseac3a8882019-10-03 10:48:06 +02003607 if RO_nsr_id:
garciadeblas5697b8b2021-03-24 09:17:02 +01003608 new_op["RO_nsr_id"] = RO_nsr_id
kuuseac3a8882019-10-03 10:48:06 +02003609 if RO_scaling_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01003610 new_op["RO_scaling_info"] = RO_scaling_info
kuuseac3a8882019-10-03 10:48:06 +02003611 if not op_list:
3612 # No existing operations, create key 'operations' with current operation as first list element
garciadeblas5697b8b2021-03-24 09:17:02 +01003613 db_nslcmop_admin.update({"operations": [new_op]})
3614 op_list = db_nslcmop_admin.get("operations")
kuuseac3a8882019-10-03 10:48:06 +02003615 else:
3616 # Existing operations, append operation to list
3617 op_list.append(new_op)
kuuse8b998e42019-07-30 15:22:16 +02003618
garciadeblas5697b8b2021-03-24 09:17:02 +01003619 db_nslcmop_update = {"_admin.operations": op_list}
3620 self.update_db_2("nslcmops", db_nslcmop["_id"], db_nslcmop_update)
kuuseac3a8882019-10-03 10:48:06 +02003621 op_index = len(op_list) - 1
3622 return op_index
3623
3624 # Helper methods for scale() sub-operations
3625
3626 # pre-scale/post-scale:
3627 # Check for 3 different cases:
3628 # a. New: First time execution, return SUBOPERATION_STATUS_NEW
3629 # b. Skip: Existing sub-operation exists, operationState == 'COMPLETED', return SUBOPERATION_STATUS_SKIP
tierno7c4e24c2020-05-13 08:41:35 +00003630 # c. retry: Existing sub-operation exists, operationState != 'COMPLETED', return op_index to re-execute
garciadeblas5697b8b2021-03-24 09:17:02 +01003631 def _check_or_add_scale_suboperation(
3632 self,
3633 db_nslcmop,
3634 vnf_index,
3635 vnf_config_primitive,
3636 primitive_params,
3637 operationType,
3638 RO_nsr_id=None,
3639 RO_scaling_info=None,
3640 ):
kuuseac3a8882019-10-03 10:48:06 +02003641 # Find this sub-operation
tierno7c4e24c2020-05-13 08:41:35 +00003642 if RO_nsr_id and RO_scaling_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01003643 operationType = "SCALE-RO"
kuuseac3a8882019-10-03 10:48:06 +02003644 match = {
garciadeblas5697b8b2021-03-24 09:17:02 +01003645 "member_vnf_index": vnf_index,
3646 "RO_nsr_id": RO_nsr_id,
3647 "RO_scaling_info": RO_scaling_info,
kuuseac3a8882019-10-03 10:48:06 +02003648 }
3649 else:
3650 match = {
garciadeblas5697b8b2021-03-24 09:17:02 +01003651 "member_vnf_index": vnf_index,
3652 "primitive": vnf_config_primitive,
3653 "primitive_params": primitive_params,
3654 "lcmOperationType": operationType,
kuuseac3a8882019-10-03 10:48:06 +02003655 }
3656 op_index = self._find_suboperation(db_nslcmop, match)
tierno51183952020-04-03 15:48:18 +00003657 if op_index == self.SUBOPERATION_STATUS_NOT_FOUND:
kuuseac3a8882019-10-03 10:48:06 +02003658 # a. New sub-operation
3659 # The sub-operation does not exist, add it.
3660 # _ns_execute_primitive() will be called from scale() as usual, with non-modified arguments
3661 # The following parameters are set to None for all kind of scaling:
3662 vdu_id = None
3663 vdu_count_index = None
3664 vdu_name = None
tierno51183952020-04-03 15:48:18 +00003665 if RO_nsr_id and RO_scaling_info:
kuuseac3a8882019-10-03 10:48:06 +02003666 vnf_config_primitive = None
3667 primitive_params = None
3668 else:
3669 RO_nsr_id = None
3670 RO_scaling_info = None
3671 # Initial status for sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01003672 operationState = "PROCESSING"
3673 detailed_status = "In progress"
kuuseac3a8882019-10-03 10:48:06 +02003674 # Add sub-operation for pre/post-scaling (zero or more operations)
garciadeblas5697b8b2021-03-24 09:17:02 +01003675 self._add_suboperation(
3676 db_nslcmop,
3677 vnf_index,
3678 vdu_id,
3679 vdu_count_index,
3680 vdu_name,
3681 vnf_config_primitive,
3682 primitive_params,
3683 operationState,
3684 detailed_status,
3685 operationType,
3686 RO_nsr_id,
3687 RO_scaling_info,
3688 )
kuuseac3a8882019-10-03 10:48:06 +02003689 return self.SUBOPERATION_STATUS_NEW
3690 else:
3691 # Return either SUBOPERATION_STATUS_SKIP (operationState == 'COMPLETED'),
3692 # or op_index (operationState != 'COMPLETED')
tierno51183952020-04-03 15:48:18 +00003693 return self._retry_or_skip_suboperation(db_nslcmop, op_index)
kuuseac3a8882019-10-03 10:48:06 +02003694
preethika.pdf7d8e02019-12-10 13:10:48 +00003695 # Function to return execution_environment id
3696
3697 def _get_ee_id(self, vnf_index, vdu_id, vca_deployed_list):
tiernoe876f672020-02-13 14:34:48 +00003698 # TODO vdu_index_count
preethika.pdf7d8e02019-12-10 13:10:48 +00003699 for vca in vca_deployed_list:
3700 if vca["member-vnf-index"] == vnf_index and vca["vdu_id"] == vdu_id:
3701 return vca["ee_id"]
3702
David Garciac1fe90a2021-03-31 19:12:02 +02003703 async def destroy_N2VC(
3704 self,
3705 logging_text,
3706 db_nslcmop,
3707 vca_deployed,
3708 config_descriptor,
3709 vca_index,
3710 destroy_ee=True,
3711 exec_primitives=True,
3712 scaling_in=False,
3713 vca_id: str = None,
3714 ):
tiernoe876f672020-02-13 14:34:48 +00003715 """
3716 Execute the terminate primitives and destroy the execution environment (if destroy_ee=False
3717 :param logging_text:
3718 :param db_nslcmop:
3719 :param vca_deployed: Dictionary of deployment info at db_nsr._admin.depoloyed.VCA.<INDEX>
3720 :param config_descriptor: Configuration descriptor of the NSD, VNFD, VNFD.vdu or VNFD.kdu
3721 :param vca_index: index in the database _admin.deployed.VCA
3722 :param destroy_ee: False to do not destroy, because it will be destroyed all of then at once
tierno588547c2020-07-01 15:30:20 +00003723 :param exec_primitives: False to do not execute terminate primitives, because the config is not completed or has
3724 not executed properly
aktas13251562021-02-12 22:19:10 +03003725 :param scaling_in: True destroys the application, False destroys the model
tiernoe876f672020-02-13 14:34:48 +00003726 :return: None or exception
3727 """
tiernoe876f672020-02-13 14:34:48 +00003728
tierno588547c2020-07-01 15:30:20 +00003729 self.logger.debug(
garciadeblas5697b8b2021-03-24 09:17:02 +01003730 logging_text
3731 + " vca_index: {}, vca_deployed: {}, config_descriptor: {}, destroy_ee: {}".format(
tierno588547c2020-07-01 15:30:20 +00003732 vca_index, vca_deployed, config_descriptor, destroy_ee
3733 )
3734 )
3735
3736 vca_type = vca_deployed.get("type", "lxc_proxy_charm")
3737
3738 # execute terminate_primitives
3739 if exec_primitives:
bravof922c4172020-11-24 21:21:43 -03003740 terminate_primitives = get_ee_sorted_terminate_config_primitive_list(
garciadeblas5697b8b2021-03-24 09:17:02 +01003741 config_descriptor.get("terminate-config-primitive"),
3742 vca_deployed.get("ee_descriptor_id"),
3743 )
tierno588547c2020-07-01 15:30:20 +00003744 vdu_id = vca_deployed.get("vdu_id")
3745 vdu_count_index = vca_deployed.get("vdu_count_index")
3746 vdu_name = vca_deployed.get("vdu_name")
3747 vnf_index = vca_deployed.get("member-vnf-index")
3748 if terminate_primitives and vca_deployed.get("needed_terminate"):
tierno588547c2020-07-01 15:30:20 +00003749 for seq in terminate_primitives:
3750 # For each sequence in list, get primitive and call _ns_execute_primitive()
3751 step = "Calling terminate action for vnf_member_index={} primitive={}".format(
garciadeblas5697b8b2021-03-24 09:17:02 +01003752 vnf_index, seq.get("name")
3753 )
tierno588547c2020-07-01 15:30:20 +00003754 self.logger.debug(logging_text + step)
3755 # Create the primitive for each sequence, i.e. "primitive": "touch"
garciadeblas5697b8b2021-03-24 09:17:02 +01003756 primitive = seq.get("name")
3757 mapped_primitive_params = self._get_terminate_primitive_params(
3758 seq, vnf_index
3759 )
tierno588547c2020-07-01 15:30:20 +00003760
3761 # Add sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01003762 self._add_suboperation(
3763 db_nslcmop,
3764 vnf_index,
3765 vdu_id,
3766 vdu_count_index,
3767 vdu_name,
3768 primitive,
3769 mapped_primitive_params,
3770 )
tierno588547c2020-07-01 15:30:20 +00003771 # Sub-operations: Call _ns_execute_primitive() instead of action()
3772 try:
David Garciac1fe90a2021-03-31 19:12:02 +02003773 result, result_detail = await self._ns_execute_primitive(
garciadeblas5697b8b2021-03-24 09:17:02 +01003774 vca_deployed["ee_id"],
3775 primitive,
David Garciac1fe90a2021-03-31 19:12:02 +02003776 mapped_primitive_params,
3777 vca_type=vca_type,
3778 vca_id=vca_id,
3779 )
tierno588547c2020-07-01 15:30:20 +00003780 except LcmException:
3781 # this happens when VCA is not deployed. In this case it is not needed to terminate
3782 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01003783 result_ok = ["COMPLETED", "PARTIALLY_COMPLETED"]
tierno588547c2020-07-01 15:30:20 +00003784 if result not in result_ok:
garciadeblas5697b8b2021-03-24 09:17:02 +01003785 raise LcmException(
3786 "terminate_primitive {} for vnf_member_index={} fails with "
3787 "error {}".format(seq.get("name"), vnf_index, result_detail)
3788 )
tierno588547c2020-07-01 15:30:20 +00003789 # set that this VCA do not need terminated
garciadeblas5697b8b2021-03-24 09:17:02 +01003790 db_update_entry = "_admin.deployed.VCA.{}.needed_terminate".format(
3791 vca_index
3792 )
3793 self.update_db_2(
3794 "nsrs", db_nslcmop["nsInstanceId"], {db_update_entry: False}
3795 )
tiernoe876f672020-02-13 14:34:48 +00003796
tiernob996d942020-07-03 14:52:28 +00003797 if vca_deployed.get("prometheus_jobs") and self.prometheus:
3798 await self.prometheus.update(remove_jobs=vca_deployed["prometheus_jobs"])
3799
tiernoe876f672020-02-13 14:34:48 +00003800 if destroy_ee:
David Garciac1fe90a2021-03-31 19:12:02 +02003801 await self.vca_map[vca_type].delete_execution_environment(
3802 vca_deployed["ee_id"],
3803 scaling_in=scaling_in,
aktas730569b2021-07-29 17:42:49 +03003804 vca_type=vca_type,
David Garciac1fe90a2021-03-31 19:12:02 +02003805 vca_id=vca_id,
3806 )
kuuse0ca67472019-05-13 15:59:27 +02003807
David Garciac1fe90a2021-03-31 19:12:02 +02003808 async def _delete_all_N2VC(self, db_nsr: dict, vca_id: str = None):
garciadeblas5697b8b2021-03-24 09:17:02 +01003809 self._write_all_config_status(db_nsr=db_nsr, status="TERMINATING")
tierno51183952020-04-03 15:48:18 +00003810 namespace = "." + db_nsr["_id"]
tiernof59ad6c2020-04-08 12:50:52 +00003811 try:
David Garciac1fe90a2021-03-31 19:12:02 +02003812 await self.n2vc.delete_namespace(
3813 namespace=namespace,
3814 total_timeout=self.timeout_charm_delete,
3815 vca_id=vca_id,
3816 )
tiernof59ad6c2020-04-08 12:50:52 +00003817 except N2VCNotFound: # already deleted. Skip
3818 pass
garciadeblas5697b8b2021-03-24 09:17:02 +01003819 self._write_all_config_status(db_nsr=db_nsr, status="DELETED")
quilesj3655ae02019-12-12 16:08:35 +00003820
garciadeblas5697b8b2021-03-24 09:17:02 +01003821 async def _terminate_RO(
3822 self, logging_text, nsr_deployed, nsr_id, nslcmop_id, stage
3823 ):
tiernoe876f672020-02-13 14:34:48 +00003824 """
3825 Terminates a deployment from RO
3826 :param logging_text:
3827 :param nsr_deployed: db_nsr._admin.deployed
3828 :param nsr_id:
3829 :param nslcmop_id:
3830 :param stage: list of string with the content to write on db_nslcmop.detailed-status.
3831 this method will update only the index 2, but it will write on database the concatenated content of the list
3832 :return:
3833 """
3834 db_nsr_update = {}
3835 failed_detail = []
3836 ro_nsr_id = ro_delete_action = None
3837 if nsr_deployed and nsr_deployed.get("RO"):
3838 ro_nsr_id = nsr_deployed["RO"].get("nsr_id")
3839 ro_delete_action = nsr_deployed["RO"].get("nsr_delete_action_id")
3840 try:
3841 if ro_nsr_id:
3842 stage[2] = "Deleting ns from VIM."
3843 db_nsr_update["detailed-status"] = " ".join(stage)
3844 self._write_op_status(nslcmop_id, stage)
3845 self.logger.debug(logging_text + stage[2])
3846 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3847 self._write_op_status(nslcmop_id, stage)
3848 desc = await self.RO.delete("ns", ro_nsr_id)
3849 ro_delete_action = desc["action_id"]
garciadeblas5697b8b2021-03-24 09:17:02 +01003850 db_nsr_update[
3851 "_admin.deployed.RO.nsr_delete_action_id"
3852 ] = ro_delete_action
tiernoe876f672020-02-13 14:34:48 +00003853 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
3854 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
3855 if ro_delete_action:
3856 # wait until NS is deleted from VIM
3857 stage[2] = "Waiting ns deleted from VIM."
3858 detailed_status_old = None
garciadeblas5697b8b2021-03-24 09:17:02 +01003859 self.logger.debug(
3860 logging_text
3861 + stage[2]
3862 + " RO_id={} ro_delete_action={}".format(
3863 ro_nsr_id, ro_delete_action
3864 )
3865 )
tiernoe876f672020-02-13 14:34:48 +00003866 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3867 self._write_op_status(nslcmop_id, stage)
kuused124bfe2019-06-18 12:09:24 +02003868
tiernoe876f672020-02-13 14:34:48 +00003869 delete_timeout = 20 * 60 # 20 minutes
3870 while delete_timeout > 0:
3871 desc = await self.RO.show(
3872 "ns",
3873 item_id_name=ro_nsr_id,
3874 extra_item="action",
garciadeblas5697b8b2021-03-24 09:17:02 +01003875 extra_item_id=ro_delete_action,
3876 )
tiernoe876f672020-02-13 14:34:48 +00003877
3878 # deploymentStatus
3879 self._on_update_ro_db(nsrs_id=nsr_id, ro_descriptor=desc)
3880
3881 ns_status, ns_status_info = self.RO.check_action_status(desc)
3882 if ns_status == "ERROR":
3883 raise ROclient.ROClientException(ns_status_info)
3884 elif ns_status == "BUILD":
3885 stage[2] = "Deleting from VIM {}".format(ns_status_info)
3886 elif ns_status == "ACTIVE":
3887 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
3888 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
3889 break
3890 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01003891 assert (
3892 False
3893 ), "ROclient.check_action_status returns unknown {}".format(
3894 ns_status
3895 )
tiernoe876f672020-02-13 14:34:48 +00003896 if stage[2] != detailed_status_old:
3897 detailed_status_old = stage[2]
3898 db_nsr_update["detailed-status"] = " ".join(stage)
3899 self._write_op_status(nslcmop_id, stage)
3900 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3901 await asyncio.sleep(5, loop=self.loop)
3902 delete_timeout -= 5
3903 else: # delete_timeout <= 0:
garciadeblas5697b8b2021-03-24 09:17:02 +01003904 raise ROclient.ROClientException(
3905 "Timeout waiting ns deleted from VIM"
3906 )
tiernoe876f672020-02-13 14:34:48 +00003907
3908 except Exception as e:
3909 self.update_db_2("nsrs", nsr_id, db_nsr_update)
garciadeblas5697b8b2021-03-24 09:17:02 +01003910 if (
3911 isinstance(e, ROclient.ROClientException) and e.http_code == 404
3912 ): # not found
tiernoe876f672020-02-13 14:34:48 +00003913 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
3914 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
3915 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
garciadeblas5697b8b2021-03-24 09:17:02 +01003916 self.logger.debug(
3917 logging_text + "RO_ns_id={} already deleted".format(ro_nsr_id)
3918 )
3919 elif (
3920 isinstance(e, ROclient.ROClientException) and e.http_code == 409
3921 ): # conflict
tiernoa2143262020-03-27 16:20:40 +00003922 failed_detail.append("delete conflict: {}".format(e))
garciadeblas5697b8b2021-03-24 09:17:02 +01003923 self.logger.debug(
3924 logging_text
3925 + "RO_ns_id={} delete conflict: {}".format(ro_nsr_id, e)
3926 )
tiernoe876f672020-02-13 14:34:48 +00003927 else:
tiernoa2143262020-03-27 16:20:40 +00003928 failed_detail.append("delete error: {}".format(e))
garciadeblas5697b8b2021-03-24 09:17:02 +01003929 self.logger.error(
3930 logging_text + "RO_ns_id={} delete error: {}".format(ro_nsr_id, e)
3931 )
tiernoe876f672020-02-13 14:34:48 +00003932
3933 # Delete nsd
3934 if not failed_detail and deep_get(nsr_deployed, ("RO", "nsd_id")):
3935 ro_nsd_id = nsr_deployed["RO"]["nsd_id"]
3936 try:
3937 stage[2] = "Deleting nsd from RO."
3938 db_nsr_update["detailed-status"] = " ".join(stage)
3939 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3940 self._write_op_status(nslcmop_id, stage)
3941 await self.RO.delete("nsd", ro_nsd_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01003942 self.logger.debug(
3943 logging_text + "ro_nsd_id={} deleted".format(ro_nsd_id)
3944 )
tiernoe876f672020-02-13 14:34:48 +00003945 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
3946 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01003947 if (
3948 isinstance(e, ROclient.ROClientException) and e.http_code == 404
3949 ): # not found
tiernoe876f672020-02-13 14:34:48 +00003950 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
garciadeblas5697b8b2021-03-24 09:17:02 +01003951 self.logger.debug(
3952 logging_text + "ro_nsd_id={} already deleted".format(ro_nsd_id)
3953 )
3954 elif (
3955 isinstance(e, ROclient.ROClientException) and e.http_code == 409
3956 ): # conflict
3957 failed_detail.append(
3958 "ro_nsd_id={} delete conflict: {}".format(ro_nsd_id, e)
3959 )
tiernoe876f672020-02-13 14:34:48 +00003960 self.logger.debug(logging_text + failed_detail[-1])
3961 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01003962 failed_detail.append(
3963 "ro_nsd_id={} delete error: {}".format(ro_nsd_id, e)
3964 )
tiernoe876f672020-02-13 14:34:48 +00003965 self.logger.error(logging_text + failed_detail[-1])
3966
3967 if not failed_detail and deep_get(nsr_deployed, ("RO", "vnfd")):
3968 for index, vnf_deployed in enumerate(nsr_deployed["RO"]["vnfd"]):
3969 if not vnf_deployed or not vnf_deployed["id"]:
3970 continue
3971 try:
3972 ro_vnfd_id = vnf_deployed["id"]
garciadeblas5697b8b2021-03-24 09:17:02 +01003973 stage[
3974 2
3975 ] = "Deleting member_vnf_index={} ro_vnfd_id={} from RO.".format(
3976 vnf_deployed["member-vnf-index"], ro_vnfd_id
3977 )
tiernoe876f672020-02-13 14:34:48 +00003978 db_nsr_update["detailed-status"] = " ".join(stage)
3979 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3980 self._write_op_status(nslcmop_id, stage)
3981 await self.RO.delete("vnfd", ro_vnfd_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01003982 self.logger.debug(
3983 logging_text + "ro_vnfd_id={} deleted".format(ro_vnfd_id)
3984 )
tiernoe876f672020-02-13 14:34:48 +00003985 db_nsr_update["_admin.deployed.RO.vnfd.{}.id".format(index)] = None
3986 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01003987 if (
3988 isinstance(e, ROclient.ROClientException) and e.http_code == 404
3989 ): # not found
3990 db_nsr_update[
3991 "_admin.deployed.RO.vnfd.{}.id".format(index)
3992 ] = None
3993 self.logger.debug(
3994 logging_text
3995 + "ro_vnfd_id={} already deleted ".format(ro_vnfd_id)
3996 )
3997 elif (
3998 isinstance(e, ROclient.ROClientException) and e.http_code == 409
3999 ): # conflict
4000 failed_detail.append(
4001 "ro_vnfd_id={} delete conflict: {}".format(ro_vnfd_id, e)
4002 )
tiernoe876f672020-02-13 14:34:48 +00004003 self.logger.debug(logging_text + failed_detail[-1])
4004 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004005 failed_detail.append(
4006 "ro_vnfd_id={} delete error: {}".format(ro_vnfd_id, e)
4007 )
tiernoe876f672020-02-13 14:34:48 +00004008 self.logger.error(logging_text + failed_detail[-1])
4009
tiernoa2143262020-03-27 16:20:40 +00004010 if failed_detail:
4011 stage[2] = "Error deleting from VIM"
4012 else:
4013 stage[2] = "Deleted from VIM"
tiernoe876f672020-02-13 14:34:48 +00004014 db_nsr_update["detailed-status"] = " ".join(stage)
4015 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4016 self._write_op_status(nslcmop_id, stage)
4017
4018 if failed_detail:
tiernoa2143262020-03-27 16:20:40 +00004019 raise LcmException("; ".join(failed_detail))
tiernoe876f672020-02-13 14:34:48 +00004020
4021 async def terminate(self, nsr_id, nslcmop_id):
kuused124bfe2019-06-18 12:09:24 +02004022 # Try to lock HA task here
garciadeblas5697b8b2021-03-24 09:17:02 +01004023 task_is_locked_by_me = self.lcm_tasks.lock_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02004024 if not task_is_locked_by_me:
4025 return
4026
tierno59d22d22018-09-25 18:10:19 +02004027 logging_text = "Task ns={} terminate={} ".format(nsr_id, nslcmop_id)
4028 self.logger.debug(logging_text + "Enter")
tiernoe876f672020-02-13 14:34:48 +00004029 timeout_ns_terminate = self.timeout_ns_terminate
tierno59d22d22018-09-25 18:10:19 +02004030 db_nsr = None
4031 db_nslcmop = None
tiernoa17d4f42020-04-28 09:59:23 +00004032 operation_params = None
tierno59d22d22018-09-25 18:10:19 +02004033 exc = None
garciadeblas5697b8b2021-03-24 09:17:02 +01004034 error_list = [] # annotates all failed error messages
tierno59d22d22018-09-25 18:10:19 +02004035 db_nslcmop_update = {}
tiernoc2564fe2019-01-28 16:18:56 +00004036 autoremove = False # autoremove after terminated
tiernoe876f672020-02-13 14:34:48 +00004037 tasks_dict_info = {}
4038 db_nsr_update = {}
garciadeblas5697b8b2021-03-24 09:17:02 +01004039 stage = [
4040 "Stage 1/3: Preparing task.",
4041 "Waiting for previous operations to terminate.",
4042 "",
4043 ]
tiernoe876f672020-02-13 14:34:48 +00004044 # ^ contains [stage, step, VIM-status]
tierno59d22d22018-09-25 18:10:19 +02004045 try:
kuused124bfe2019-06-18 12:09:24 +02004046 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +01004047 await self.lcm_tasks.waitfor_related_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02004048
tiernoe876f672020-02-13 14:34:48 +00004049 stage[1] = "Getting nslcmop={} from db.".format(nslcmop_id)
4050 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
4051 operation_params = db_nslcmop.get("operationParams") or {}
4052 if operation_params.get("timeout_ns_terminate"):
4053 timeout_ns_terminate = operation_params["timeout_ns_terminate"]
4054 stage[1] = "Getting nsr={} from db.".format(nsr_id)
4055 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
4056
4057 db_nsr_update["operational-status"] = "terminating"
4058 db_nsr_update["config-status"] = "terminating"
quilesj4cda56b2019-12-05 10:02:20 +00004059 self._write_ns_status(
4060 nsr_id=nsr_id,
4061 ns_state="TERMINATING",
4062 current_operation="TERMINATING",
tiernoe876f672020-02-13 14:34:48 +00004063 current_operation_id=nslcmop_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01004064 other_update=db_nsr_update,
quilesj4cda56b2019-12-05 10:02:20 +00004065 )
garciadeblas5697b8b2021-03-24 09:17:02 +01004066 self._write_op_status(op_id=nslcmop_id, queuePosition=0, stage=stage)
tiernoe876f672020-02-13 14:34:48 +00004067 nsr_deployed = deepcopy(db_nsr["_admin"].get("deployed")) or {}
tierno59d22d22018-09-25 18:10:19 +02004068 if db_nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
4069 return
tierno59d22d22018-09-25 18:10:19 +02004070
tiernoe876f672020-02-13 14:34:48 +00004071 stage[1] = "Getting vnf descriptors from db."
4072 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
garciadeblas5697b8b2021-03-24 09:17:02 +01004073 db_vnfrs_dict = {
4074 db_vnfr["member-vnf-index-ref"]: db_vnfr for db_vnfr in db_vnfrs_list
4075 }
tiernoe876f672020-02-13 14:34:48 +00004076 db_vnfds_from_id = {}
4077 db_vnfds_from_member_index = {}
4078 # Loop over VNFRs
4079 for vnfr in db_vnfrs_list:
4080 vnfd_id = vnfr["vnfd-id"]
4081 if vnfd_id not in db_vnfds_from_id:
4082 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
4083 db_vnfds_from_id[vnfd_id] = vnfd
garciadeblas5697b8b2021-03-24 09:17:02 +01004084 db_vnfds_from_member_index[
4085 vnfr["member-vnf-index-ref"]
4086 ] = db_vnfds_from_id[vnfd_id]
calvinosanch9f9c6f22019-11-04 13:37:39 +01004087
tiernoe876f672020-02-13 14:34:48 +00004088 # Destroy individual execution environments when there are terminating primitives.
4089 # Rest of EE will be deleted at once
tierno588547c2020-07-01 15:30:20 +00004090 # TODO - check before calling _destroy_N2VC
4091 # if not operation_params.get("skip_terminate_primitives"):#
4092 # or not vca.get("needed_terminate"):
4093 stage[0] = "Stage 2/3 execute terminating primitives."
4094 self.logger.debug(logging_text + stage[0])
4095 stage[1] = "Looking execution environment that needs terminate."
4096 self.logger.debug(logging_text + stage[1])
bravof922c4172020-11-24 21:21:43 -03004097
tierno588547c2020-07-01 15:30:20 +00004098 for vca_index, vca in enumerate(get_iterable(nsr_deployed, "VCA")):
tierno588547c2020-07-01 15:30:20 +00004099 config_descriptor = None
David Garciab76442a2021-05-28 12:08:18 +02004100 vca_member_vnf_index = vca.get("member-vnf-index")
4101 vca_id = self.get_vca_id(
4102 db_vnfrs_dict.get(vca_member_vnf_index)
4103 if vca_member_vnf_index
4104 else None,
4105 db_nsr,
4106 )
tierno588547c2020-07-01 15:30:20 +00004107 if not vca or not vca.get("ee_id"):
4108 continue
4109 if not vca.get("member-vnf-index"):
4110 # ns
4111 config_descriptor = db_nsr.get("ns-configuration")
4112 elif vca.get("vdu_id"):
4113 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
bravofe5a31bc2021-02-17 19:09:12 -03004114 config_descriptor = get_configuration(db_vnfd, vca.get("vdu_id"))
tierno588547c2020-07-01 15:30:20 +00004115 elif vca.get("kdu_name"):
4116 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
bravofe5a31bc2021-02-17 19:09:12 -03004117 config_descriptor = get_configuration(db_vnfd, vca.get("kdu_name"))
tierno588547c2020-07-01 15:30:20 +00004118 else:
bravofe5a31bc2021-02-17 19:09:12 -03004119 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
aktas13251562021-02-12 22:19:10 +03004120 config_descriptor = get_configuration(db_vnfd, db_vnfd["id"])
tierno588547c2020-07-01 15:30:20 +00004121 vca_type = vca.get("type")
garciadeblas5697b8b2021-03-24 09:17:02 +01004122 exec_terminate_primitives = not operation_params.get(
4123 "skip_terminate_primitives"
4124 ) and vca.get("needed_terminate")
tiernoaebd7da2020-08-07 06:36:38 +00004125 # For helm we must destroy_ee. Also for native_charm, as juju_model cannot be deleted if there are
4126 # pending native charms
garciadeblas5697b8b2021-03-24 09:17:02 +01004127 destroy_ee = (
4128 True if vca_type in ("helm", "helm-v3", "native_charm") else False
4129 )
tierno86e33612020-09-16 14:13:06 +00004130 # self.logger.debug(logging_text + "vca_index: {}, ee_id: {}, vca_type: {} destroy_ee: {}".format(
4131 # vca_index, vca.get("ee_id"), vca_type, destroy_ee))
tiernob996d942020-07-03 14:52:28 +00004132 task = asyncio.ensure_future(
David Garciac1fe90a2021-03-31 19:12:02 +02004133 self.destroy_N2VC(
4134 logging_text,
4135 db_nslcmop,
4136 vca,
4137 config_descriptor,
4138 vca_index,
4139 destroy_ee,
4140 exec_terminate_primitives,
4141 vca_id=vca_id,
4142 )
4143 )
tierno588547c2020-07-01 15:30:20 +00004144 tasks_dict_info[task] = "Terminating VCA {}".format(vca.get("ee_id"))
tierno59d22d22018-09-25 18:10:19 +02004145
tierno588547c2020-07-01 15:30:20 +00004146 # wait for pending tasks of terminate primitives
4147 if tasks_dict_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01004148 self.logger.debug(
4149 logging_text
4150 + "Waiting for tasks {}".format(list(tasks_dict_info.keys()))
4151 )
4152 error_list = await self._wait_for_tasks(
4153 logging_text,
4154 tasks_dict_info,
4155 min(self.timeout_charm_delete, timeout_ns_terminate),
4156 stage,
4157 nslcmop_id,
4158 )
tierno86e33612020-09-16 14:13:06 +00004159 tasks_dict_info.clear()
tierno588547c2020-07-01 15:30:20 +00004160 if error_list:
garciadeblas5697b8b2021-03-24 09:17:02 +01004161 return # raise LcmException("; ".join(error_list))
tierno82974b22018-11-27 21:55:36 +00004162
tiernoe876f672020-02-13 14:34:48 +00004163 # remove All execution environments at once
4164 stage[0] = "Stage 3/3 delete all."
quilesj3655ae02019-12-12 16:08:35 +00004165
tierno49676be2020-04-07 16:34:35 +00004166 if nsr_deployed.get("VCA"):
4167 stage[1] = "Deleting all execution environments."
4168 self.logger.debug(logging_text + stage[1])
David Garciac1fe90a2021-03-31 19:12:02 +02004169 vca_id = self.get_vca_id({}, db_nsr)
4170 task_delete_ee = asyncio.ensure_future(
4171 asyncio.wait_for(
4172 self._delete_all_N2VC(db_nsr=db_nsr, vca_id=vca_id),
garciadeblas5697b8b2021-03-24 09:17:02 +01004173 timeout=self.timeout_charm_delete,
David Garciac1fe90a2021-03-31 19:12:02 +02004174 )
4175 )
tierno49676be2020-04-07 16:34:35 +00004176 # task_delete_ee = asyncio.ensure_future(self.n2vc.delete_namespace(namespace="." + nsr_id))
4177 tasks_dict_info[task_delete_ee] = "Terminating all VCA"
tierno59d22d22018-09-25 18:10:19 +02004178
tiernoe876f672020-02-13 14:34:48 +00004179 # Delete from k8scluster
4180 stage[1] = "Deleting KDUs."
4181 self.logger.debug(logging_text + stage[1])
4182 # print(nsr_deployed)
4183 for kdu in get_iterable(nsr_deployed, "K8s"):
4184 if not kdu or not kdu.get("kdu-instance"):
4185 continue
4186 kdu_instance = kdu.get("kdu-instance")
tiernoa2143262020-03-27 16:20:40 +00004187 if kdu.get("k8scluster-type") in self.k8scluster_map:
David Garciac1fe90a2021-03-31 19:12:02 +02004188 # TODO: Uninstall kdu instances taking into account they could be deployed in different VIMs
4189 vca_id = self.get_vca_id({}, db_nsr)
tiernoe876f672020-02-13 14:34:48 +00004190 task_delete_kdu_instance = asyncio.ensure_future(
tiernoa2143262020-03-27 16:20:40 +00004191 self.k8scluster_map[kdu["k8scluster-type"]].uninstall(
4192 cluster_uuid=kdu.get("k8scluster-uuid"),
David Garciac1fe90a2021-03-31 19:12:02 +02004193 kdu_instance=kdu_instance,
4194 vca_id=vca_id,
4195 )
4196 )
tiernoe876f672020-02-13 14:34:48 +00004197 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004198 self.logger.error(
4199 logging_text
4200 + "Unknown k8s deployment type {}".format(
4201 kdu.get("k8scluster-type")
4202 )
4203 )
tiernoe876f672020-02-13 14:34:48 +00004204 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01004205 tasks_dict_info[
4206 task_delete_kdu_instance
4207 ] = "Terminating KDU '{}'".format(kdu.get("kdu-name"))
tierno59d22d22018-09-25 18:10:19 +02004208
4209 # remove from RO
tiernoe876f672020-02-13 14:34:48 +00004210 stage[1] = "Deleting ns from VIM."
tierno69f0d382020-05-07 13:08:09 +00004211 if self.ng_ro:
4212 task_delete_ro = asyncio.ensure_future(
garciadeblas5697b8b2021-03-24 09:17:02 +01004213 self._terminate_ng_ro(
4214 logging_text, nsr_deployed, nsr_id, nslcmop_id, stage
4215 )
4216 )
tierno69f0d382020-05-07 13:08:09 +00004217 else:
4218 task_delete_ro = asyncio.ensure_future(
garciadeblas5697b8b2021-03-24 09:17:02 +01004219 self._terminate_RO(
4220 logging_text, nsr_deployed, nsr_id, nslcmop_id, stage
4221 )
4222 )
tiernoe876f672020-02-13 14:34:48 +00004223 tasks_dict_info[task_delete_ro] = "Removing deployment from VIM"
tierno59d22d22018-09-25 18:10:19 +02004224
tiernoe876f672020-02-13 14:34:48 +00004225 # rest of staff will be done at finally
4226
garciadeblas5697b8b2021-03-24 09:17:02 +01004227 except (
4228 ROclient.ROClientException,
4229 DbException,
4230 LcmException,
4231 N2VCException,
4232 ) as e:
tiernoe876f672020-02-13 14:34:48 +00004233 self.logger.error(logging_text + "Exit Exception {}".format(e))
4234 exc = e
4235 except asyncio.CancelledError:
garciadeblas5697b8b2021-03-24 09:17:02 +01004236 self.logger.error(
4237 logging_text + "Cancelled Exception while '{}'".format(stage[1])
4238 )
tiernoe876f672020-02-13 14:34:48 +00004239 exc = "Operation was cancelled"
4240 except Exception as e:
4241 exc = traceback.format_exc()
garciadeblas5697b8b2021-03-24 09:17:02 +01004242 self.logger.critical(
4243 logging_text + "Exit Exception while '{}': {}".format(stage[1], e),
4244 exc_info=True,
4245 )
tiernoe876f672020-02-13 14:34:48 +00004246 finally:
4247 if exc:
4248 error_list.append(str(exc))
tierno59d22d22018-09-25 18:10:19 +02004249 try:
tiernoe876f672020-02-13 14:34:48 +00004250 # wait for pending tasks
4251 if tasks_dict_info:
4252 stage[1] = "Waiting for terminate pending tasks."
4253 self.logger.debug(logging_text + stage[1])
garciadeblas5697b8b2021-03-24 09:17:02 +01004254 error_list += await self._wait_for_tasks(
4255 logging_text,
4256 tasks_dict_info,
4257 timeout_ns_terminate,
4258 stage,
4259 nslcmop_id,
4260 )
tiernoe876f672020-02-13 14:34:48 +00004261 stage[1] = stage[2] = ""
4262 except asyncio.CancelledError:
4263 error_list.append("Cancelled")
4264 # TODO cancell all tasks
4265 except Exception as exc:
4266 error_list.append(str(exc))
4267 # update status at database
4268 if error_list:
4269 error_detail = "; ".join(error_list)
4270 # self.logger.error(logging_text + error_detail)
garciadeblas5697b8b2021-03-24 09:17:02 +01004271 error_description_nslcmop = "{} Detail: {}".format(
4272 stage[0], error_detail
4273 )
4274 error_description_nsr = "Operation: TERMINATING.{}, {}.".format(
4275 nslcmop_id, stage[0]
4276 )
tierno59d22d22018-09-25 18:10:19 +02004277
tierno59d22d22018-09-25 18:10:19 +02004278 db_nsr_update["operational-status"] = "failed"
garciadeblas5697b8b2021-03-24 09:17:02 +01004279 db_nsr_update["detailed-status"] = (
4280 error_description_nsr + " Detail: " + error_detail
4281 )
tiernoe876f672020-02-13 14:34:48 +00004282 db_nslcmop_update["detailed-status"] = error_detail
4283 nslcmop_operation_state = "FAILED"
4284 ns_state = "BROKEN"
tierno59d22d22018-09-25 18:10:19 +02004285 else:
tiernoa2143262020-03-27 16:20:40 +00004286 error_detail = None
tiernoe876f672020-02-13 14:34:48 +00004287 error_description_nsr = error_description_nslcmop = None
4288 ns_state = "NOT_INSTANTIATED"
tierno59d22d22018-09-25 18:10:19 +02004289 db_nsr_update["operational-status"] = "terminated"
4290 db_nsr_update["detailed-status"] = "Done"
4291 db_nsr_update["_admin.nsState"] = "NOT_INSTANTIATED"
4292 db_nslcmop_update["detailed-status"] = "Done"
tiernoe876f672020-02-13 14:34:48 +00004293 nslcmop_operation_state = "COMPLETED"
tierno59d22d22018-09-25 18:10:19 +02004294
tiernoe876f672020-02-13 14:34:48 +00004295 if db_nsr:
4296 self._write_ns_status(
4297 nsr_id=nsr_id,
4298 ns_state=ns_state,
4299 current_operation="IDLE",
4300 current_operation_id=None,
4301 error_description=error_description_nsr,
tiernoa2143262020-03-27 16:20:40 +00004302 error_detail=error_detail,
garciadeblas5697b8b2021-03-24 09:17:02 +01004303 other_update=db_nsr_update,
tiernoe876f672020-02-13 14:34:48 +00004304 )
tiernoa17d4f42020-04-28 09:59:23 +00004305 self._write_op_status(
4306 op_id=nslcmop_id,
4307 stage="",
4308 error_message=error_description_nslcmop,
4309 operation_state=nslcmop_operation_state,
4310 other_update=db_nslcmop_update,
4311 )
lloretgalleg6d488782020-07-22 10:13:46 +00004312 if ns_state == "NOT_INSTANTIATED":
4313 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01004314 self.db.set_list(
4315 "vnfrs",
4316 {"nsr-id-ref": nsr_id},
4317 {"_admin.nsState": "NOT_INSTANTIATED"},
4318 )
lloretgalleg6d488782020-07-22 10:13:46 +00004319 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01004320 self.logger.warn(
4321 logging_text
4322 + "Error writing VNFR status for nsr-id-ref: {} -> {}".format(
4323 nsr_id, e
4324 )
4325 )
tiernoa17d4f42020-04-28 09:59:23 +00004326 if operation_params:
tiernoe876f672020-02-13 14:34:48 +00004327 autoremove = operation_params.get("autoremove", False)
tierno59d22d22018-09-25 18:10:19 +02004328 if nslcmop_operation_state:
4329 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01004330 await self.msg.aiowrite(
4331 "ns",
4332 "terminated",
4333 {
4334 "nsr_id": nsr_id,
4335 "nslcmop_id": nslcmop_id,
4336 "operationState": nslcmop_operation_state,
4337 "autoremove": autoremove,
4338 },
4339 loop=self.loop,
4340 )
tierno59d22d22018-09-25 18:10:19 +02004341 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01004342 self.logger.error(
4343 logging_text + "kafka_write notification Exception {}".format(e)
4344 )
quilesj7e13aeb2019-10-08 13:34:55 +02004345
tierno59d22d22018-09-25 18:10:19 +02004346 self.logger.debug(logging_text + "Exit")
4347 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_terminate")
4348
garciadeblas5697b8b2021-03-24 09:17:02 +01004349 async def _wait_for_tasks(
4350 self, logging_text, created_tasks_info, timeout, stage, nslcmop_id, nsr_id=None
4351 ):
tiernoe876f672020-02-13 14:34:48 +00004352 time_start = time()
tiernoa2143262020-03-27 16:20:40 +00004353 error_detail_list = []
tiernoe876f672020-02-13 14:34:48 +00004354 error_list = []
4355 pending_tasks = list(created_tasks_info.keys())
4356 num_tasks = len(pending_tasks)
4357 num_done = 0
4358 stage[1] = "{}/{}.".format(num_done, num_tasks)
4359 self._write_op_status(nslcmop_id, stage)
tiernoe876f672020-02-13 14:34:48 +00004360 while pending_tasks:
tiernoa2143262020-03-27 16:20:40 +00004361 new_error = None
tiernoe876f672020-02-13 14:34:48 +00004362 _timeout = timeout + time_start - time()
garciadeblas5697b8b2021-03-24 09:17:02 +01004363 done, pending_tasks = await asyncio.wait(
4364 pending_tasks, timeout=_timeout, return_when=asyncio.FIRST_COMPLETED
4365 )
tiernoe876f672020-02-13 14:34:48 +00004366 num_done += len(done)
garciadeblas5697b8b2021-03-24 09:17:02 +01004367 if not done: # Timeout
tiernoe876f672020-02-13 14:34:48 +00004368 for task in pending_tasks:
tiernoa2143262020-03-27 16:20:40 +00004369 new_error = created_tasks_info[task] + ": Timeout"
4370 error_detail_list.append(new_error)
4371 error_list.append(new_error)
tiernoe876f672020-02-13 14:34:48 +00004372 break
4373 for task in done:
4374 if task.cancelled():
tierno067e04a2020-03-31 12:53:13 +00004375 exc = "Cancelled"
tiernoe876f672020-02-13 14:34:48 +00004376 else:
4377 exc = task.exception()
tierno067e04a2020-03-31 12:53:13 +00004378 if exc:
4379 if isinstance(exc, asyncio.TimeoutError):
4380 exc = "Timeout"
4381 new_error = created_tasks_info[task] + ": {}".format(exc)
4382 error_list.append(created_tasks_info[task])
4383 error_detail_list.append(new_error)
garciadeblas5697b8b2021-03-24 09:17:02 +01004384 if isinstance(
4385 exc,
4386 (
4387 str,
4388 DbException,
4389 N2VCException,
4390 ROclient.ROClientException,
4391 LcmException,
4392 K8sException,
4393 NgRoException,
4394 ),
4395 ):
tierno067e04a2020-03-31 12:53:13 +00004396 self.logger.error(logging_text + new_error)
tiernoe876f672020-02-13 14:34:48 +00004397 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004398 exc_traceback = "".join(
4399 traceback.format_exception(None, exc, exc.__traceback__)
4400 )
4401 self.logger.error(
4402 logging_text
4403 + created_tasks_info[task]
4404 + " "
4405 + exc_traceback
4406 )
tierno067e04a2020-03-31 12:53:13 +00004407 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004408 self.logger.debug(
4409 logging_text + created_tasks_info[task] + ": Done"
4410 )
tiernoe876f672020-02-13 14:34:48 +00004411 stage[1] = "{}/{}.".format(num_done, num_tasks)
4412 if new_error:
tiernoa2143262020-03-27 16:20:40 +00004413 stage[1] += " Errors: " + ". ".join(error_detail_list) + "."
tiernoe876f672020-02-13 14:34:48 +00004414 if nsr_id: # update also nsr
garciadeblas5697b8b2021-03-24 09:17:02 +01004415 self.update_db_2(
4416 "nsrs",
4417 nsr_id,
4418 {
4419 "errorDescription": "Error at: " + ", ".join(error_list),
4420 "errorDetail": ". ".join(error_detail_list),
4421 },
4422 )
tiernoe876f672020-02-13 14:34:48 +00004423 self._write_op_status(nslcmop_id, stage)
tiernoa2143262020-03-27 16:20:40 +00004424 return error_detail_list
tiernoe876f672020-02-13 14:34:48 +00004425
tiernoda1ff8c2020-10-22 14:12:46 +00004426 @staticmethod
4427 def _map_primitive_params(primitive_desc, params, instantiation_params):
tiernoda964822019-01-14 15:53:47 +00004428 """
4429 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
4430 The default-value is used. If it is between < > it look for a value at instantiation_params
4431 :param primitive_desc: portion of VNFD/NSD that describes primitive
4432 :param params: Params provided by user
4433 :param instantiation_params: Instantiation params provided by user
4434 :return: a dictionary with the calculated params
4435 """
4436 calculated_params = {}
4437 for parameter in primitive_desc.get("parameter", ()):
4438 param_name = parameter["name"]
4439 if param_name in params:
4440 calculated_params[param_name] = params[param_name]
tierno98ad6ea2019-05-30 17:16:28 +00004441 elif "default-value" in parameter or "value" in parameter:
4442 if "value" in parameter:
4443 calculated_params[param_name] = parameter["value"]
4444 else:
4445 calculated_params[param_name] = parameter["default-value"]
garciadeblas5697b8b2021-03-24 09:17:02 +01004446 if (
4447 isinstance(calculated_params[param_name], str)
4448 and calculated_params[param_name].startswith("<")
4449 and calculated_params[param_name].endswith(">")
4450 ):
tierno98ad6ea2019-05-30 17:16:28 +00004451 if calculated_params[param_name][1:-1] in instantiation_params:
garciadeblas5697b8b2021-03-24 09:17:02 +01004452 calculated_params[param_name] = instantiation_params[
4453 calculated_params[param_name][1:-1]
4454 ]
tiernoda964822019-01-14 15:53:47 +00004455 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004456 raise LcmException(
4457 "Parameter {} needed to execute primitive {} not provided".format(
4458 calculated_params[param_name], primitive_desc["name"]
4459 )
4460 )
tiernoda964822019-01-14 15:53:47 +00004461 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004462 raise LcmException(
4463 "Parameter {} needed to execute primitive {} not provided".format(
4464 param_name, primitive_desc["name"]
4465 )
4466 )
tierno59d22d22018-09-25 18:10:19 +02004467
tiernoda964822019-01-14 15:53:47 +00004468 if isinstance(calculated_params[param_name], (dict, list, tuple)):
garciadeblas5697b8b2021-03-24 09:17:02 +01004469 calculated_params[param_name] = yaml.safe_dump(
4470 calculated_params[param_name], default_flow_style=True, width=256
4471 )
4472 elif isinstance(calculated_params[param_name], str) and calculated_params[
4473 param_name
4474 ].startswith("!!yaml "):
tiernoda964822019-01-14 15:53:47 +00004475 calculated_params[param_name] = calculated_params[param_name][7:]
tiernofa40e692020-10-14 14:59:36 +00004476 if parameter.get("data-type") == "INTEGER":
4477 try:
4478 calculated_params[param_name] = int(calculated_params[param_name])
4479 except ValueError: # error converting string to int
4480 raise LcmException(
garciadeblas5697b8b2021-03-24 09:17:02 +01004481 "Parameter {} of primitive {} must be integer".format(
4482 param_name, primitive_desc["name"]
4483 )
4484 )
tiernofa40e692020-10-14 14:59:36 +00004485 elif parameter.get("data-type") == "BOOLEAN":
garciadeblas5697b8b2021-03-24 09:17:02 +01004486 calculated_params[param_name] = not (
4487 (str(calculated_params[param_name])).lower() == "false"
4488 )
tiernoc3f2a822019-11-05 13:45:04 +00004489
4490 # add always ns_config_info if primitive name is config
4491 if primitive_desc["name"] == "config":
4492 if "ns_config_info" in instantiation_params:
garciadeblas5697b8b2021-03-24 09:17:02 +01004493 calculated_params["ns_config_info"] = instantiation_params[
4494 "ns_config_info"
4495 ]
tiernoda964822019-01-14 15:53:47 +00004496 return calculated_params
4497
garciadeblas5697b8b2021-03-24 09:17:02 +01004498 def _look_for_deployed_vca(
4499 self,
4500 deployed_vca,
4501 member_vnf_index,
4502 vdu_id,
4503 vdu_count_index,
4504 kdu_name=None,
4505 ee_descriptor_id=None,
4506 ):
tiernoe876f672020-02-13 14:34:48 +00004507 # find vca_deployed record for this action. Raise LcmException if not found or there is not any id.
4508 for vca in deployed_vca:
4509 if not vca:
4510 continue
4511 if member_vnf_index != vca["member-vnf-index"] or vdu_id != vca["vdu_id"]:
4512 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01004513 if (
4514 vdu_count_index is not None
4515 and vdu_count_index != vca["vdu_count_index"]
4516 ):
tiernoe876f672020-02-13 14:34:48 +00004517 continue
4518 if kdu_name and kdu_name != vca["kdu_name"]:
4519 continue
tiernoa278b842020-07-08 15:33:55 +00004520 if ee_descriptor_id and ee_descriptor_id != vca["ee_descriptor_id"]:
4521 continue
tiernoe876f672020-02-13 14:34:48 +00004522 break
4523 else:
4524 # vca_deployed not found
garciadeblas5697b8b2021-03-24 09:17:02 +01004525 raise LcmException(
4526 "charm for member_vnf_index={} vdu_id={}.{} kdu_name={} execution-environment-list.id={}"
4527 " is not deployed".format(
4528 member_vnf_index,
4529 vdu_id,
4530 vdu_count_index,
4531 kdu_name,
4532 ee_descriptor_id,
4533 )
4534 )
tiernoe876f672020-02-13 14:34:48 +00004535 # get ee_id
4536 ee_id = vca.get("ee_id")
garciadeblas5697b8b2021-03-24 09:17:02 +01004537 vca_type = vca.get(
4538 "type", "lxc_proxy_charm"
4539 ) # default value for backward compatibility - proxy charm
tiernoe876f672020-02-13 14:34:48 +00004540 if not ee_id:
garciadeblas5697b8b2021-03-24 09:17:02 +01004541 raise LcmException(
4542 "charm for member_vnf_index={} vdu_id={} kdu_name={} vdu_count_index={} has not "
4543 "execution environment".format(
4544 member_vnf_index, vdu_id, kdu_name, vdu_count_index
4545 )
4546 )
tierno588547c2020-07-01 15:30:20 +00004547 return ee_id, vca_type
tiernoe876f672020-02-13 14:34:48 +00004548
David Garciac1fe90a2021-03-31 19:12:02 +02004549 async def _ns_execute_primitive(
4550 self,
4551 ee_id,
4552 primitive,
4553 primitive_params,
4554 retries=0,
4555 retries_interval=30,
4556 timeout=None,
4557 vca_type=None,
4558 db_dict=None,
4559 vca_id: str = None,
4560 ) -> (str, str):
tiernoda964822019-01-14 15:53:47 +00004561 try:
tierno98ad6ea2019-05-30 17:16:28 +00004562 if primitive == "config":
4563 primitive_params = {"params": primitive_params}
tierno2fc7ce52019-06-11 22:50:01 +00004564
tierno588547c2020-07-01 15:30:20 +00004565 vca_type = vca_type or "lxc_proxy_charm"
4566
quilesj7e13aeb2019-10-08 13:34:55 +02004567 while retries >= 0:
4568 try:
tierno067e04a2020-03-31 12:53:13 +00004569 output = await asyncio.wait_for(
tierno588547c2020-07-01 15:30:20 +00004570 self.vca_map[vca_type].exec_primitive(
tierno067e04a2020-03-31 12:53:13 +00004571 ee_id=ee_id,
4572 primitive_name=primitive,
4573 params_dict=primitive_params,
4574 progress_timeout=self.timeout_progress_primitive,
tierno588547c2020-07-01 15:30:20 +00004575 total_timeout=self.timeout_primitive,
David Garciac1fe90a2021-03-31 19:12:02 +02004576 db_dict=db_dict,
4577 vca_id=vca_id,
aktas730569b2021-07-29 17:42:49 +03004578 vca_type=vca_type,
David Garciac1fe90a2021-03-31 19:12:02 +02004579 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01004580 timeout=timeout or self.timeout_primitive,
4581 )
quilesj7e13aeb2019-10-08 13:34:55 +02004582 # execution was OK
4583 break
tierno067e04a2020-03-31 12:53:13 +00004584 except asyncio.CancelledError:
4585 raise
4586 except Exception as e: # asyncio.TimeoutError
4587 if isinstance(e, asyncio.TimeoutError):
4588 e = "Timeout"
quilesj7e13aeb2019-10-08 13:34:55 +02004589 retries -= 1
4590 if retries >= 0:
garciadeblas5697b8b2021-03-24 09:17:02 +01004591 self.logger.debug(
4592 "Error executing action {} on {} -> {}".format(
4593 primitive, ee_id, e
4594 )
4595 )
quilesj7e13aeb2019-10-08 13:34:55 +02004596 # wait and retry
4597 await asyncio.sleep(retries_interval, loop=self.loop)
tierno73d8bd02019-11-18 17:33:27 +00004598 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004599 return "FAILED", str(e)
quilesj7e13aeb2019-10-08 13:34:55 +02004600
garciadeblas5697b8b2021-03-24 09:17:02 +01004601 return "COMPLETED", output
quilesj7e13aeb2019-10-08 13:34:55 +02004602
tierno067e04a2020-03-31 12:53:13 +00004603 except (LcmException, asyncio.CancelledError):
tiernoe876f672020-02-13 14:34:48 +00004604 raise
quilesj7e13aeb2019-10-08 13:34:55 +02004605 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01004606 return "FAIL", "Error executing action {}: {}".format(primitive, e)
tierno59d22d22018-09-25 18:10:19 +02004607
ksaikiranr3fde2c72021-03-15 10:39:06 +05304608 async def vca_status_refresh(self, nsr_id, nslcmop_id):
4609 """
4610 Updating the vca_status with latest juju information in nsrs record
4611 :param: nsr_id: Id of the nsr
4612 :param: nslcmop_id: Id of the nslcmop
4613 :return: None
4614 """
4615
4616 self.logger.debug("Task ns={} action={} Enter".format(nsr_id, nslcmop_id))
4617 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
David Garciac1fe90a2021-03-31 19:12:02 +02004618 vca_id = self.get_vca_id({}, db_nsr)
garciadeblas5697b8b2021-03-24 09:17:02 +01004619 if db_nsr["_admin"]["deployed"]["K8s"]:
4620 for k8s_index, k8s in enumerate(db_nsr["_admin"]["deployed"]["K8s"]):
ksaikiranr656b6dd2021-02-19 10:25:18 +05304621 cluster_uuid, kdu_instance = k8s["k8scluster-uuid"], k8s["kdu-instance"]
garciadeblas5697b8b2021-03-24 09:17:02 +01004622 await self._on_update_k8s_db(
4623 cluster_uuid, kdu_instance, filter={"_id": nsr_id}, vca_id=vca_id
4624 )
ksaikiranr656b6dd2021-02-19 10:25:18 +05304625 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004626 for vca_index, _ in enumerate(db_nsr["_admin"]["deployed"]["VCA"]):
ksaikiranr656b6dd2021-02-19 10:25:18 +05304627 table, filter = "nsrs", {"_id": nsr_id}
4628 path = "_admin.deployed.VCA.{}.".format(vca_index)
4629 await self._on_update_n2vc_db(table, filter, path, {})
ksaikiranr3fde2c72021-03-15 10:39:06 +05304630
4631 self.logger.debug("Task ns={} action={} Exit".format(nsr_id, nslcmop_id))
4632 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_vca_status_refresh")
4633
tierno59d22d22018-09-25 18:10:19 +02004634 async def action(self, nsr_id, nslcmop_id):
kuused124bfe2019-06-18 12:09:24 +02004635 # Try to lock HA task here
garciadeblas5697b8b2021-03-24 09:17:02 +01004636 task_is_locked_by_me = self.lcm_tasks.lock_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02004637 if not task_is_locked_by_me:
4638 return
4639
tierno59d22d22018-09-25 18:10:19 +02004640 logging_text = "Task ns={} action={} ".format(nsr_id, nslcmop_id)
4641 self.logger.debug(logging_text + "Enter")
4642 # get all needed from database
4643 db_nsr = None
4644 db_nslcmop = None
tiernoe876f672020-02-13 14:34:48 +00004645 db_nsr_update = {}
tierno59d22d22018-09-25 18:10:19 +02004646 db_nslcmop_update = {}
4647 nslcmop_operation_state = None
tierno067e04a2020-03-31 12:53:13 +00004648 error_description_nslcmop = None
tierno59d22d22018-09-25 18:10:19 +02004649 exc = None
4650 try:
kuused124bfe2019-06-18 12:09:24 +02004651 # wait for any previous tasks in process
tierno3cf81a32019-11-11 17:07:00 +00004652 step = "Waiting for previous operations to terminate"
garciadeblas5697b8b2021-03-24 09:17:02 +01004653 await self.lcm_tasks.waitfor_related_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02004654
quilesj4cda56b2019-12-05 10:02:20 +00004655 self._write_ns_status(
4656 nsr_id=nsr_id,
4657 ns_state=None,
4658 current_operation="RUNNING ACTION",
garciadeblas5697b8b2021-03-24 09:17:02 +01004659 current_operation_id=nslcmop_id,
quilesj4cda56b2019-12-05 10:02:20 +00004660 )
4661
tierno59d22d22018-09-25 18:10:19 +02004662 step = "Getting information from database"
4663 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
4664 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
Guillermo Calvinofbf294c2022-01-26 17:40:31 +01004665 if db_nslcmop["operationParams"].get("primitive_params"):
4666 db_nslcmop["operationParams"]["primitive_params"] = json.loads(
4667 db_nslcmop["operationParams"]["primitive_params"]
4668 )
tiernoda964822019-01-14 15:53:47 +00004669
tiernoe4f7e6c2018-11-27 14:55:30 +00004670 nsr_deployed = db_nsr["_admin"].get("deployed")
tierno1b633412019-02-25 16:48:23 +00004671 vnf_index = db_nslcmop["operationParams"].get("member_vnf_index")
tierno59d22d22018-09-25 18:10:19 +02004672 vdu_id = db_nslcmop["operationParams"].get("vdu_id")
calvinosanch9f9c6f22019-11-04 13:37:39 +01004673 kdu_name = db_nslcmop["operationParams"].get("kdu_name")
tiernoe4f7e6c2018-11-27 14:55:30 +00004674 vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
tierno067e04a2020-03-31 12:53:13 +00004675 primitive = db_nslcmop["operationParams"]["primitive"]
4676 primitive_params = db_nslcmop["operationParams"]["primitive_params"]
garciadeblas5697b8b2021-03-24 09:17:02 +01004677 timeout_ns_action = db_nslcmop["operationParams"].get(
4678 "timeout_ns_action", self.timeout_primitive
4679 )
tierno59d22d22018-09-25 18:10:19 +02004680
tierno1b633412019-02-25 16:48:23 +00004681 if vnf_index:
4682 step = "Getting vnfr from database"
garciadeblas5697b8b2021-03-24 09:17:02 +01004683 db_vnfr = self.db.get_one(
4684 "vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id}
4685 )
Guillermo Calvino98a3bd12022-02-01 18:59:50 +01004686 if db_vnfr.get("kdur"):
4687 kdur_list = []
4688 for kdur in db_vnfr["kdur"]:
4689 if kdur.get("additionalParams"):
4690 kdur["additionalParams"] = json.loads(kdur["additionalParams"])
4691 kdur_list.append(kdur)
4692 db_vnfr["kdur"] = kdur_list
tierno1b633412019-02-25 16:48:23 +00004693 step = "Getting vnfd from database"
4694 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
4695 else:
tierno067e04a2020-03-31 12:53:13 +00004696 step = "Getting nsd from database"
4697 db_nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
tiernoda964822019-01-14 15:53:47 +00004698
David Garciac1fe90a2021-03-31 19:12:02 +02004699 vca_id = self.get_vca_id(db_vnfr, db_nsr)
tierno82974b22018-11-27 21:55:36 +00004700 # for backward compatibility
4701 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
4702 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
4703 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
4704 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4705
tiernoda964822019-01-14 15:53:47 +00004706 # look for primitive
tiernoa278b842020-07-08 15:33:55 +00004707 config_primitive_desc = descriptor_configuration = None
tiernoda964822019-01-14 15:53:47 +00004708 if vdu_id:
bravofe5a31bc2021-02-17 19:09:12 -03004709 descriptor_configuration = get_configuration(db_vnfd, vdu_id)
calvinosanch9f9c6f22019-11-04 13:37:39 +01004710 elif kdu_name:
bravofe5a31bc2021-02-17 19:09:12 -03004711 descriptor_configuration = get_configuration(db_vnfd, kdu_name)
tierno1b633412019-02-25 16:48:23 +00004712 elif vnf_index:
bravofe5a31bc2021-02-17 19:09:12 -03004713 descriptor_configuration = get_configuration(db_vnfd, db_vnfd["id"])
tierno1b633412019-02-25 16:48:23 +00004714 else:
tiernoa278b842020-07-08 15:33:55 +00004715 descriptor_configuration = db_nsd.get("ns-configuration")
4716
garciadeblas5697b8b2021-03-24 09:17:02 +01004717 if descriptor_configuration and descriptor_configuration.get(
4718 "config-primitive"
4719 ):
tiernoa278b842020-07-08 15:33:55 +00004720 for config_primitive in descriptor_configuration["config-primitive"]:
tierno1b633412019-02-25 16:48:23 +00004721 if config_primitive["name"] == primitive:
4722 config_primitive_desc = config_primitive
4723 break
tiernoda964822019-01-14 15:53:47 +00004724
garciadeblas6bed6b32020-07-20 11:05:42 +00004725 if not config_primitive_desc:
4726 if not (kdu_name and primitive in ("upgrade", "rollback", "status")):
garciadeblas5697b8b2021-03-24 09:17:02 +01004727 raise LcmException(
4728 "Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".format(
4729 primitive
4730 )
4731 )
garciadeblas6bed6b32020-07-20 11:05:42 +00004732 primitive_name = primitive
4733 ee_descriptor_id = None
4734 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004735 primitive_name = config_primitive_desc.get(
4736 "execution-environment-primitive", primitive
4737 )
4738 ee_descriptor_id = config_primitive_desc.get(
4739 "execution-environment-ref"
4740 )
tierno1b633412019-02-25 16:48:23 +00004741
tierno1b633412019-02-25 16:48:23 +00004742 if vnf_index:
tierno626e0152019-11-29 14:16:16 +00004743 if vdu_id:
garciadeblas5697b8b2021-03-24 09:17:02 +01004744 vdur = next(
4745 (x for x in db_vnfr["vdur"] if x["vdu-id-ref"] == vdu_id), None
4746 )
bravof922c4172020-11-24 21:21:43 -03004747 desc_params = parse_yaml_strings(vdur.get("additionalParams"))
tierno067e04a2020-03-31 12:53:13 +00004748 elif kdu_name:
garciadeblas5697b8b2021-03-24 09:17:02 +01004749 kdur = next(
4750 (x for x in db_vnfr["kdur"] if x["kdu-name"] == kdu_name), None
4751 )
bravof922c4172020-11-24 21:21:43 -03004752 desc_params = parse_yaml_strings(kdur.get("additionalParams"))
tierno067e04a2020-03-31 12:53:13 +00004753 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004754 desc_params = parse_yaml_strings(
4755 db_vnfr.get("additionalParamsForVnf")
4756 )
tierno1b633412019-02-25 16:48:23 +00004757 else:
bravof922c4172020-11-24 21:21:43 -03004758 desc_params = parse_yaml_strings(db_nsr.get("additionalParamsForNs"))
bravofe5a31bc2021-02-17 19:09:12 -03004759 if kdu_name and get_configuration(db_vnfd, kdu_name):
4760 kdu_configuration = get_configuration(db_vnfd, kdu_name)
David Garciad41dbd62020-12-10 12:52:52 +01004761 actions = set()
David Garciaa1003662021-02-16 21:07:58 +01004762 for primitive in kdu_configuration.get("initial-config-primitive", []):
David Garciad41dbd62020-12-10 12:52:52 +01004763 actions.add(primitive["name"])
David Garciaa1003662021-02-16 21:07:58 +01004764 for primitive in kdu_configuration.get("config-primitive", []):
David Garciad41dbd62020-12-10 12:52:52 +01004765 actions.add(primitive["name"])
4766 kdu_action = True if primitive_name in actions else False
Dominik Fleischmann771c32b2020-04-07 12:39:36 +02004767
tiernoda964822019-01-14 15:53:47 +00004768 # TODO check if ns is in a proper status
garciadeblas5697b8b2021-03-24 09:17:02 +01004769 if kdu_name and (
4770 primitive_name in ("upgrade", "rollback", "status") or kdu_action
4771 ):
tierno067e04a2020-03-31 12:53:13 +00004772 # kdur and desc_params already set from before
4773 if primitive_params:
4774 desc_params.update(primitive_params)
4775 # TODO Check if we will need something at vnf level
4776 for index, kdu in enumerate(get_iterable(nsr_deployed, "K8s")):
garciadeblas5697b8b2021-03-24 09:17:02 +01004777 if (
4778 kdu_name == kdu["kdu-name"]
4779 and kdu["member-vnf-index"] == vnf_index
4780 ):
tierno067e04a2020-03-31 12:53:13 +00004781 break
4782 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004783 raise LcmException(
4784 "KDU '{}' for vnf '{}' not deployed".format(kdu_name, vnf_index)
4785 )
quilesj7e13aeb2019-10-08 13:34:55 +02004786
tierno067e04a2020-03-31 12:53:13 +00004787 if kdu.get("k8scluster-type") not in self.k8scluster_map:
garciadeblas5697b8b2021-03-24 09:17:02 +01004788 msg = "unknown k8scluster-type '{}'".format(
4789 kdu.get("k8scluster-type")
4790 )
tierno067e04a2020-03-31 12:53:13 +00004791 raise LcmException(msg)
4792
garciadeblas5697b8b2021-03-24 09:17:02 +01004793 db_dict = {
4794 "collection": "nsrs",
4795 "filter": {"_id": nsr_id},
4796 "path": "_admin.deployed.K8s.{}".format(index),
4797 }
4798 self.logger.debug(
4799 logging_text
4800 + "Exec k8s {} on {}.{}".format(primitive_name, vnf_index, kdu_name)
4801 )
tiernoa278b842020-07-08 15:33:55 +00004802 step = "Executing kdu {}".format(primitive_name)
4803 if primitive_name == "upgrade":
tierno067e04a2020-03-31 12:53:13 +00004804 if desc_params.get("kdu_model"):
4805 kdu_model = desc_params.get("kdu_model")
4806 del desc_params["kdu_model"]
4807 else:
4808 kdu_model = kdu.get("kdu-model")
4809 parts = kdu_model.split(sep=":")
4810 if len(parts) == 2:
4811 kdu_model = parts[0]
4812
4813 detailed_status = await asyncio.wait_for(
4814 self.k8scluster_map[kdu["k8scluster-type"]].upgrade(
4815 cluster_uuid=kdu.get("k8scluster-uuid"),
4816 kdu_instance=kdu.get("kdu-instance"),
garciadeblas5697b8b2021-03-24 09:17:02 +01004817 atomic=True,
4818 kdu_model=kdu_model,
4819 params=desc_params,
4820 db_dict=db_dict,
4821 timeout=timeout_ns_action,
4822 ),
4823 timeout=timeout_ns_action + 10,
4824 )
4825 self.logger.debug(
4826 logging_text + " Upgrade of kdu {} done".format(detailed_status)
4827 )
tiernoa278b842020-07-08 15:33:55 +00004828 elif primitive_name == "rollback":
tierno067e04a2020-03-31 12:53:13 +00004829 detailed_status = await asyncio.wait_for(
4830 self.k8scluster_map[kdu["k8scluster-type"]].rollback(
4831 cluster_uuid=kdu.get("k8scluster-uuid"),
4832 kdu_instance=kdu.get("kdu-instance"),
garciadeblas5697b8b2021-03-24 09:17:02 +01004833 db_dict=db_dict,
4834 ),
4835 timeout=timeout_ns_action,
4836 )
tiernoa278b842020-07-08 15:33:55 +00004837 elif primitive_name == "status":
tierno067e04a2020-03-31 12:53:13 +00004838 detailed_status = await asyncio.wait_for(
4839 self.k8scluster_map[kdu["k8scluster-type"]].status_kdu(
4840 cluster_uuid=kdu.get("k8scluster-uuid"),
David Garciac1fe90a2021-03-31 19:12:02 +02004841 kdu_instance=kdu.get("kdu-instance"),
4842 vca_id=vca_id,
4843 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01004844 timeout=timeout_ns_action,
David Garciac1fe90a2021-03-31 19:12:02 +02004845 )
Dominik Fleischmann771c32b2020-04-07 12:39:36 +02004846 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004847 kdu_instance = kdu.get("kdu-instance") or "{}-{}".format(
4848 kdu["kdu-name"], nsr_id
4849 )
4850 params = self._map_primitive_params(
4851 config_primitive_desc, primitive_params, desc_params
4852 )
Dominik Fleischmann771c32b2020-04-07 12:39:36 +02004853
4854 detailed_status = await asyncio.wait_for(
4855 self.k8scluster_map[kdu["k8scluster-type"]].exec_primitive(
4856 cluster_uuid=kdu.get("k8scluster-uuid"),
4857 kdu_instance=kdu_instance,
tiernoa278b842020-07-08 15:33:55 +00004858 primitive_name=primitive_name,
garciadeblas5697b8b2021-03-24 09:17:02 +01004859 params=params,
4860 db_dict=db_dict,
David Garciac1fe90a2021-03-31 19:12:02 +02004861 timeout=timeout_ns_action,
4862 vca_id=vca_id,
4863 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01004864 timeout=timeout_ns_action,
David Garciac1fe90a2021-03-31 19:12:02 +02004865 )
tierno067e04a2020-03-31 12:53:13 +00004866
4867 if detailed_status:
garciadeblas5697b8b2021-03-24 09:17:02 +01004868 nslcmop_operation_state = "COMPLETED"
tierno067e04a2020-03-31 12:53:13 +00004869 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004870 detailed_status = ""
4871 nslcmop_operation_state = "FAILED"
tierno067e04a2020-03-31 12:53:13 +00004872 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004873 ee_id, vca_type = self._look_for_deployed_vca(
4874 nsr_deployed["VCA"],
4875 member_vnf_index=vnf_index,
4876 vdu_id=vdu_id,
4877 vdu_count_index=vdu_count_index,
4878 ee_descriptor_id=ee_descriptor_id,
4879 )
4880 for vca_index, vca_deployed in enumerate(
4881 db_nsr["_admin"]["deployed"]["VCA"]
4882 ):
ksaikiranrb1c9f372021-03-15 11:07:29 +05304883 if vca_deployed.get("member-vnf-index") == vnf_index:
garciadeblas5697b8b2021-03-24 09:17:02 +01004884 db_dict = {
4885 "collection": "nsrs",
4886 "filter": {"_id": nsr_id},
4887 "path": "_admin.deployed.VCA.{}.".format(vca_index),
4888 }
ksaikiranrb1c9f372021-03-15 11:07:29 +05304889 break
garciadeblas5697b8b2021-03-24 09:17:02 +01004890 (
4891 nslcmop_operation_state,
4892 detailed_status,
4893 ) = await self._ns_execute_primitive(
tierno588547c2020-07-01 15:30:20 +00004894 ee_id,
tiernoa278b842020-07-08 15:33:55 +00004895 primitive=primitive_name,
garciadeblas5697b8b2021-03-24 09:17:02 +01004896 primitive_params=self._map_primitive_params(
4897 config_primitive_desc, primitive_params, desc_params
4898 ),
tierno588547c2020-07-01 15:30:20 +00004899 timeout=timeout_ns_action,
4900 vca_type=vca_type,
David Garciac1fe90a2021-03-31 19:12:02 +02004901 db_dict=db_dict,
4902 vca_id=vca_id,
4903 )
tierno067e04a2020-03-31 12:53:13 +00004904
4905 db_nslcmop_update["detailed-status"] = detailed_status
garciadeblas5697b8b2021-03-24 09:17:02 +01004906 error_description_nslcmop = (
4907 detailed_status if nslcmop_operation_state == "FAILED" else ""
4908 )
4909 self.logger.debug(
4910 logging_text
4911 + " task Done with result {} {}".format(
4912 nslcmop_operation_state, detailed_status
4913 )
4914 )
tierno59d22d22018-09-25 18:10:19 +02004915 return # database update is called inside finally
4916
tiernof59ad6c2020-04-08 12:50:52 +00004917 except (DbException, LcmException, N2VCException, K8sException) as e:
tierno59d22d22018-09-25 18:10:19 +02004918 self.logger.error(logging_text + "Exit Exception {}".format(e))
4919 exc = e
4920 except asyncio.CancelledError:
garciadeblas5697b8b2021-03-24 09:17:02 +01004921 self.logger.error(
4922 logging_text + "Cancelled Exception while '{}'".format(step)
4923 )
tierno59d22d22018-09-25 18:10:19 +02004924 exc = "Operation was cancelled"
tierno067e04a2020-03-31 12:53:13 +00004925 except asyncio.TimeoutError:
4926 self.logger.error(logging_text + "Timeout while '{}'".format(step))
4927 exc = "Timeout"
tierno59d22d22018-09-25 18:10:19 +02004928 except Exception as e:
4929 exc = traceback.format_exc()
garciadeblas5697b8b2021-03-24 09:17:02 +01004930 self.logger.critical(
4931 logging_text + "Exit Exception {} {}".format(type(e).__name__, e),
4932 exc_info=True,
4933 )
tierno59d22d22018-09-25 18:10:19 +02004934 finally:
tierno067e04a2020-03-31 12:53:13 +00004935 if exc:
garciadeblas5697b8b2021-03-24 09:17:02 +01004936 db_nslcmop_update[
4937 "detailed-status"
4938 ] = (
4939 detailed_status
4940 ) = error_description_nslcmop = "FAILED {}: {}".format(step, exc)
tierno067e04a2020-03-31 12:53:13 +00004941 nslcmop_operation_state = "FAILED"
4942 if db_nsr:
4943 self._write_ns_status(
4944 nsr_id=nsr_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01004945 ns_state=db_nsr[
4946 "nsState"
4947 ], # TODO check if degraded. For the moment use previous status
tierno067e04a2020-03-31 12:53:13 +00004948 current_operation="IDLE",
4949 current_operation_id=None,
4950 # error_description=error_description_nsr,
4951 # error_detail=error_detail,
garciadeblas5697b8b2021-03-24 09:17:02 +01004952 other_update=db_nsr_update,
tierno067e04a2020-03-31 12:53:13 +00004953 )
4954
garciadeblas5697b8b2021-03-24 09:17:02 +01004955 self._write_op_status(
4956 op_id=nslcmop_id,
4957 stage="",
4958 error_message=error_description_nslcmop,
4959 operation_state=nslcmop_operation_state,
4960 other_update=db_nslcmop_update,
4961 )
tierno067e04a2020-03-31 12:53:13 +00004962
tierno59d22d22018-09-25 18:10:19 +02004963 if nslcmop_operation_state:
4964 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01004965 await self.msg.aiowrite(
4966 "ns",
4967 "actioned",
4968 {
4969 "nsr_id": nsr_id,
4970 "nslcmop_id": nslcmop_id,
4971 "operationState": nslcmop_operation_state,
4972 },
4973 loop=self.loop,
4974 )
tierno59d22d22018-09-25 18:10:19 +02004975 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01004976 self.logger.error(
4977 logging_text + "kafka_write notification Exception {}".format(e)
4978 )
tierno59d22d22018-09-25 18:10:19 +02004979 self.logger.debug(logging_text + "Exit")
4980 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_action")
tierno067e04a2020-03-31 12:53:13 +00004981 return nslcmop_operation_state, detailed_status
tierno59d22d22018-09-25 18:10:19 +02004982
4983 async def scale(self, nsr_id, nslcmop_id):
kuused124bfe2019-06-18 12:09:24 +02004984 # Try to lock HA task here
garciadeblas5697b8b2021-03-24 09:17:02 +01004985 task_is_locked_by_me = self.lcm_tasks.lock_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02004986 if not task_is_locked_by_me:
4987 return
4988
tierno59d22d22018-09-25 18:10:19 +02004989 logging_text = "Task ns={} scale={} ".format(nsr_id, nslcmop_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01004990 stage = ["", "", ""]
aktas13251562021-02-12 22:19:10 +03004991 tasks_dict_info = {}
tierno2357f4e2020-10-19 16:38:59 +00004992 # ^ stage, step, VIM progress
tierno59d22d22018-09-25 18:10:19 +02004993 self.logger.debug(logging_text + "Enter")
4994 # get all needed from database
4995 db_nsr = None
tierno59d22d22018-09-25 18:10:19 +02004996 db_nslcmop_update = {}
tiernoe876f672020-02-13 14:34:48 +00004997 db_nsr_update = {}
tierno59d22d22018-09-25 18:10:19 +02004998 exc = None
tierno9ab95942018-10-10 16:44:22 +02004999 # in case of error, indicates what part of scale was failed to put nsr at error status
5000 scale_process = None
tiernod6de1992018-10-11 13:05:52 +02005001 old_operational_status = ""
5002 old_config_status = ""
aktas13251562021-02-12 22:19:10 +03005003 nsi_id = None
tierno59d22d22018-09-25 18:10:19 +02005004 try:
kuused124bfe2019-06-18 12:09:24 +02005005 # wait for any previous tasks in process
tierno3cf81a32019-11-11 17:07:00 +00005006 step = "Waiting for previous operations to terminate"
garciadeblas5697b8b2021-03-24 09:17:02 +01005007 await self.lcm_tasks.waitfor_related_HA("ns", "nslcmops", nslcmop_id)
5008 self._write_ns_status(
5009 nsr_id=nsr_id,
5010 ns_state=None,
5011 current_operation="SCALING",
5012 current_operation_id=nslcmop_id,
5013 )
quilesj4cda56b2019-12-05 10:02:20 +00005014
ikalyvas02d9e7b2019-05-27 18:16:01 +03005015 step = "Getting nslcmop from database"
garciadeblas5697b8b2021-03-24 09:17:02 +01005016 self.logger.debug(
5017 step + " after having waited for previous tasks to be completed"
5018 )
ikalyvas02d9e7b2019-05-27 18:16:01 +03005019 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
bravof922c4172020-11-24 21:21:43 -03005020
ikalyvas02d9e7b2019-05-27 18:16:01 +03005021 step = "Getting nsr from database"
5022 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
ikalyvas02d9e7b2019-05-27 18:16:01 +03005023 old_operational_status = db_nsr["operational-status"]
5024 old_config_status = db_nsr["config-status"]
bravof922c4172020-11-24 21:21:43 -03005025
tierno59d22d22018-09-25 18:10:19 +02005026 step = "Parsing scaling parameters"
5027 db_nsr_update["operational-status"] = "scaling"
5028 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernoe4f7e6c2018-11-27 14:55:30 +00005029 nsr_deployed = db_nsr["_admin"].get("deployed")
calvinosanch9f9c6f22019-11-04 13:37:39 +01005030
garciadeblas5697b8b2021-03-24 09:17:02 +01005031 vnf_index = db_nslcmop["operationParams"]["scaleVnfData"][
5032 "scaleByStepData"
5033 ]["member-vnf-index"]
5034 scaling_group = db_nslcmop["operationParams"]["scaleVnfData"][
5035 "scaleByStepData"
5036 ]["scaling-group-descriptor"]
tierno59d22d22018-09-25 18:10:19 +02005037 scaling_type = db_nslcmop["operationParams"]["scaleVnfData"]["scaleVnfType"]
tierno82974b22018-11-27 21:55:36 +00005038 # for backward compatibility
5039 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
5040 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
5041 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
5042 self.update_db_2("nsrs", nsr_id, db_nsr_update)
5043
tierno59d22d22018-09-25 18:10:19 +02005044 step = "Getting vnfr from database"
garciadeblas5697b8b2021-03-24 09:17:02 +01005045 db_vnfr = self.db.get_one(
5046 "vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id}
5047 )
bravof922c4172020-11-24 21:21:43 -03005048
David Garciac1fe90a2021-03-31 19:12:02 +02005049 vca_id = self.get_vca_id(db_vnfr, db_nsr)
5050
tierno59d22d22018-09-25 18:10:19 +02005051 step = "Getting vnfd from database"
5052 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
ikalyvas02d9e7b2019-05-27 18:16:01 +03005053
aktas13251562021-02-12 22:19:10 +03005054 base_folder = db_vnfd["_admin"]["storage"]
5055
tierno59d22d22018-09-25 18:10:19 +02005056 step = "Getting scaling-group-descriptor"
bravof832f8992020-12-07 12:57:31 -03005057 scaling_descriptor = find_in_list(
garciadeblas5697b8b2021-03-24 09:17:02 +01005058 get_scaling_aspect(db_vnfd),
5059 lambda scale_desc: scale_desc["name"] == scaling_group,
bravof832f8992020-12-07 12:57:31 -03005060 )
5061 if not scaling_descriptor:
garciadeblas5697b8b2021-03-24 09:17:02 +01005062 raise LcmException(
5063 "input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
5064 "at vnfd:scaling-group-descriptor".format(scaling_group)
5065 )
ikalyvas02d9e7b2019-05-27 18:16:01 +03005066
tierno15b1cf12019-08-29 13:21:40 +00005067 step = "Sending scale order to VIM"
bravof922c4172020-11-24 21:21:43 -03005068 # TODO check if ns is in a proper status
tierno59d22d22018-09-25 18:10:19 +02005069 nb_scale_op = 0
5070 if not db_nsr["_admin"].get("scaling-group"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005071 self.update_db_2(
5072 "nsrs",
5073 nsr_id,
5074 {
5075 "_admin.scaling-group": [
5076 {"name": scaling_group, "nb-scale-op": 0}
5077 ]
5078 },
5079 )
tierno59d22d22018-09-25 18:10:19 +02005080 admin_scale_index = 0
5081 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01005082 for admin_scale_index, admin_scale_info in enumerate(
5083 db_nsr["_admin"]["scaling-group"]
5084 ):
tierno59d22d22018-09-25 18:10:19 +02005085 if admin_scale_info["name"] == scaling_group:
5086 nb_scale_op = admin_scale_info.get("nb-scale-op", 0)
5087 break
tierno9ab95942018-10-10 16:44:22 +02005088 else: # not found, set index one plus last element and add new entry with the name
5089 admin_scale_index += 1
garciadeblas5697b8b2021-03-24 09:17:02 +01005090 db_nsr_update[
5091 "_admin.scaling-group.{}.name".format(admin_scale_index)
5092 ] = scaling_group
aktas5f75f102021-03-15 11:26:10 +03005093
5094 vca_scaling_info = []
5095 scaling_info = {"scaling_group_name": scaling_group, "vdu": [], "kdu": []}
tierno59d22d22018-09-25 18:10:19 +02005096 if scaling_type == "SCALE_OUT":
bravof832f8992020-12-07 12:57:31 -03005097 if "aspect-delta-details" not in scaling_descriptor:
5098 raise LcmException(
5099 "Aspect delta details not fount in scaling descriptor {}".format(
5100 scaling_descriptor["name"]
5101 )
5102 )
tierno59d22d22018-09-25 18:10:19 +02005103 # count if max-instance-count is reached
bravof832f8992020-12-07 12:57:31 -03005104 deltas = scaling_descriptor.get("aspect-delta-details")["deltas"]
kuuse8b998e42019-07-30 15:22:16 +02005105
aktas5f75f102021-03-15 11:26:10 +03005106 scaling_info["scaling_direction"] = "OUT"
5107 scaling_info["vdu-create"] = {}
5108 scaling_info["kdu-create"] = {}
bravof832f8992020-12-07 12:57:31 -03005109 for delta in deltas:
aktas5f75f102021-03-15 11:26:10 +03005110 for vdu_delta in delta.get("vdu-delta", {}):
bravof832f8992020-12-07 12:57:31 -03005111 vdud = get_vdu(db_vnfd, vdu_delta["id"])
aktas5f75f102021-03-15 11:26:10 +03005112 # vdu_index also provides the number of instance of the targeted vdu
5113 vdu_count = vdu_index = get_vdur_index(db_vnfr, vdu_delta)
garciadeblas5697b8b2021-03-24 09:17:02 +01005114 cloud_init_text = self._get_vdu_cloud_init_content(
5115 vdud, db_vnfd
5116 )
tierno72ef84f2020-10-06 08:22:07 +00005117 if cloud_init_text:
garciadeblas5697b8b2021-03-24 09:17:02 +01005118 additional_params = (
5119 self._get_vdu_additional_params(db_vnfr, vdud["id"])
5120 or {}
5121 )
bravof832f8992020-12-07 12:57:31 -03005122 cloud_init_list = []
5123
5124 vdu_profile = get_vdu_profile(db_vnfd, vdu_delta["id"])
5125 max_instance_count = 10
5126 if vdu_profile and "max-number-of-instances" in vdu_profile:
garciadeblas5697b8b2021-03-24 09:17:02 +01005127 max_instance_count = vdu_profile.get(
5128 "max-number-of-instances", 10
5129 )
5130
5131 default_instance_num = get_number_of_instances(
5132 db_vnfd, vdud["id"]
5133 )
aktas5f75f102021-03-15 11:26:10 +03005134 instances_number = vdu_delta.get("number-of-instances", 1)
5135 nb_scale_op += instances_number
bravof832f8992020-12-07 12:57:31 -03005136
aktas5f75f102021-03-15 11:26:10 +03005137 new_instance_count = nb_scale_op + default_instance_num
5138 # Control if new count is over max and vdu count is less than max.
5139 # Then assign new instance count
5140 if new_instance_count > max_instance_count > vdu_count:
5141 instances_number = new_instance_count - max_instance_count
5142 else:
5143 instances_number = instances_number
bravof832f8992020-12-07 12:57:31 -03005144
aktas5f75f102021-03-15 11:26:10 +03005145 if new_instance_count > max_instance_count:
bravof832f8992020-12-07 12:57:31 -03005146 raise LcmException(
5147 "reached the limit of {} (max-instance-count) "
5148 "scaling-out operations for the "
garciadeblas5697b8b2021-03-24 09:17:02 +01005149 "scaling-group-descriptor '{}'".format(
5150 nb_scale_op, scaling_group
5151 )
bravof922c4172020-11-24 21:21:43 -03005152 )
bravof832f8992020-12-07 12:57:31 -03005153 for x in range(vdu_delta.get("number-of-instances", 1)):
5154 if cloud_init_text:
5155 # TODO Information of its own ip is not available because db_vnfr is not updated.
5156 additional_params["OSM"] = get_osm_params(
garciadeblas5697b8b2021-03-24 09:17:02 +01005157 db_vnfr, vdu_delta["id"], vdu_index + x
bravof922c4172020-11-24 21:21:43 -03005158 )
bravof832f8992020-12-07 12:57:31 -03005159 cloud_init_list.append(
5160 self._parse_cloud_init(
5161 cloud_init_text,
5162 additional_params,
5163 db_vnfd["id"],
garciadeblas5697b8b2021-03-24 09:17:02 +01005164 vdud["id"],
bravof832f8992020-12-07 12:57:31 -03005165 )
5166 )
aktas5f75f102021-03-15 11:26:10 +03005167 vca_scaling_info.append(
aktas13251562021-02-12 22:19:10 +03005168 {
5169 "osm_vdu_id": vdu_delta["id"],
5170 "member-vnf-index": vnf_index,
5171 "type": "create",
garciadeblas5697b8b2021-03-24 09:17:02 +01005172 "vdu_index": vdu_index + x,
aktas13251562021-02-12 22:19:10 +03005173 }
5174 )
aktas5f75f102021-03-15 11:26:10 +03005175 scaling_info["vdu-create"][vdu_delta["id"]] = instances_number
5176 for kdu_delta in delta.get("kdu-resource-delta", {}):
5177 kdu_profile = get_kdu_profile(db_vnfd, kdu_delta["id"])
5178 kdu_name = kdu_profile["kdu-name"]
5179 resource_name = kdu_profile["resource-name"]
5180
5181 # Might have different kdus in the same delta
5182 # Should have list for each kdu
5183 if not scaling_info["kdu-create"].get(kdu_name, None):
5184 scaling_info["kdu-create"][kdu_name] = []
5185
5186 kdur = get_kdur(db_vnfr, kdu_name)
5187 if kdur.get("helm-chart"):
5188 k8s_cluster_type = "helm-chart-v3"
5189 self.logger.debug("kdur: {}".format(kdur))
5190 if (
5191 kdur.get("helm-version")
5192 and kdur.get("helm-version") == "v2"
5193 ):
5194 k8s_cluster_type = "helm-chart"
5195 raise NotImplementedError
5196 elif kdur.get("juju-bundle"):
5197 k8s_cluster_type = "juju-bundle"
5198 else:
5199 raise LcmException(
5200 "kdu type for kdu='{}.{}' is neither helm-chart nor "
5201 "juju-bundle. Maybe an old NBI version is running".format(
5202 db_vnfr["member-vnf-index-ref"], kdu_name
5203 )
5204 )
5205
5206 max_instance_count = 10
5207 if kdu_profile and "max-number-of-instances" in kdu_profile:
5208 max_instance_count = kdu_profile.get(
5209 "max-number-of-instances", 10
5210 )
5211
5212 nb_scale_op += kdu_delta.get("number-of-instances", 1)
5213 deployed_kdu, _ = get_deployed_kdu(
5214 nsr_deployed, kdu_name, vnf_index
bravof832f8992020-12-07 12:57:31 -03005215 )
aktas5f75f102021-03-15 11:26:10 +03005216 if deployed_kdu is None:
5217 raise LcmException(
5218 "KDU '{}' for vnf '{}' not deployed".format(
5219 kdu_name, vnf_index
5220 )
5221 )
5222 kdu_instance = deployed_kdu.get("kdu-instance")
5223 instance_num = await self.k8scluster_map[
5224 k8s_cluster_type
5225 ].get_scale_count(resource_name, kdu_instance, vca_id=vca_id)
5226 kdu_replica_count = instance_num + kdu_delta.get(
garciadeblas5697b8b2021-03-24 09:17:02 +01005227 "number-of-instances", 1
5228 )
ikalyvas02d9e7b2019-05-27 18:16:01 +03005229
aktas5f75f102021-03-15 11:26:10 +03005230 # Control if new count is over max and instance_num is less than max.
5231 # Then assign max instance number to kdu replica count
5232 if kdu_replica_count > max_instance_count > instance_num:
5233 kdu_replica_count = max_instance_count
5234 if kdu_replica_count > max_instance_count:
5235 raise LcmException(
5236 "reached the limit of {} (max-instance-count) "
5237 "scaling-out operations for the "
5238 "scaling-group-descriptor '{}'".format(
5239 instance_num, scaling_group
5240 )
5241 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005242
aktas5f75f102021-03-15 11:26:10 +03005243 for x in range(kdu_delta.get("number-of-instances", 1)):
5244 vca_scaling_info.append(
5245 {
5246 "osm_kdu_id": kdu_name,
5247 "member-vnf-index": vnf_index,
5248 "type": "create",
5249 "kdu_index": instance_num + x - 1,
5250 }
5251 )
5252 scaling_info["kdu-create"][kdu_name].append(
5253 {
5254 "member-vnf-index": vnf_index,
5255 "type": "create",
5256 "k8s-cluster-type": k8s_cluster_type,
5257 "resource-name": resource_name,
5258 "scale": kdu_replica_count,
5259 }
5260 )
5261 elif scaling_type == "SCALE_IN":
bravof832f8992020-12-07 12:57:31 -03005262 deltas = scaling_descriptor.get("aspect-delta-details")["deltas"]
aktas5f75f102021-03-15 11:26:10 +03005263
5264 scaling_info["scaling_direction"] = "IN"
5265 scaling_info["vdu-delete"] = {}
5266 scaling_info["kdu-delete"] = {}
5267
bravof832f8992020-12-07 12:57:31 -03005268 for delta in deltas:
aktas5f75f102021-03-15 11:26:10 +03005269 for vdu_delta in delta.get("vdu-delta", {}):
5270 vdu_count = vdu_index = get_vdur_index(db_vnfr, vdu_delta)
bravof832f8992020-12-07 12:57:31 -03005271 min_instance_count = 0
5272 vdu_profile = get_vdu_profile(db_vnfd, vdu_delta["id"])
5273 if vdu_profile and "min-number-of-instances" in vdu_profile:
5274 min_instance_count = vdu_profile["min-number-of-instances"]
5275
garciadeblas5697b8b2021-03-24 09:17:02 +01005276 default_instance_num = get_number_of_instances(
5277 db_vnfd, vdu_delta["id"]
5278 )
aktas5f75f102021-03-15 11:26:10 +03005279 instance_num = vdu_delta.get("number-of-instances", 1)
5280 nb_scale_op -= instance_num
bravof832f8992020-12-07 12:57:31 -03005281
aktas5f75f102021-03-15 11:26:10 +03005282 new_instance_count = nb_scale_op + default_instance_num
5283
5284 if new_instance_count < min_instance_count < vdu_count:
5285 instances_number = min_instance_count - new_instance_count
5286 else:
5287 instances_number = instance_num
5288
5289 if new_instance_count < min_instance_count:
bravof832f8992020-12-07 12:57:31 -03005290 raise LcmException(
5291 "reached the limit of {} (min-instance-count) scaling-in operations for the "
garciadeblas5697b8b2021-03-24 09:17:02 +01005292 "scaling-group-descriptor '{}'".format(
5293 nb_scale_op, scaling_group
5294 )
bravof832f8992020-12-07 12:57:31 -03005295 )
aktas13251562021-02-12 22:19:10 +03005296 for x in range(vdu_delta.get("number-of-instances", 1)):
aktas5f75f102021-03-15 11:26:10 +03005297 vca_scaling_info.append(
aktas13251562021-02-12 22:19:10 +03005298 {
5299 "osm_vdu_id": vdu_delta["id"],
5300 "member-vnf-index": vnf_index,
5301 "type": "delete",
garciadeblas5697b8b2021-03-24 09:17:02 +01005302 "vdu_index": vdu_index - 1 - x,
aktas13251562021-02-12 22:19:10 +03005303 }
5304 )
aktas5f75f102021-03-15 11:26:10 +03005305 scaling_info["vdu-delete"][vdu_delta["id"]] = instances_number
5306 for kdu_delta in delta.get("kdu-resource-delta", {}):
5307 kdu_profile = get_kdu_profile(db_vnfd, kdu_delta["id"])
5308 kdu_name = kdu_profile["kdu-name"]
5309 resource_name = kdu_profile["resource-name"]
5310
5311 if not scaling_info["kdu-delete"].get(kdu_name, None):
5312 scaling_info["kdu-delete"][kdu_name] = []
5313
5314 kdur = get_kdur(db_vnfr, kdu_name)
5315 if kdur.get("helm-chart"):
5316 k8s_cluster_type = "helm-chart-v3"
5317 self.logger.debug("kdur: {}".format(kdur))
5318 if (
5319 kdur.get("helm-version")
5320 and kdur.get("helm-version") == "v2"
5321 ):
5322 k8s_cluster_type = "helm-chart"
5323 raise NotImplementedError
5324 elif kdur.get("juju-bundle"):
5325 k8s_cluster_type = "juju-bundle"
5326 else:
5327 raise LcmException(
5328 "kdu type for kdu='{}.{}' is neither helm-chart nor "
5329 "juju-bundle. Maybe an old NBI version is running".format(
5330 db_vnfr["member-vnf-index-ref"], kdur["kdu-name"]
5331 )
5332 )
5333
5334 min_instance_count = 0
5335 if kdu_profile and "min-number-of-instances" in kdu_profile:
5336 min_instance_count = kdu_profile["min-number-of-instances"]
5337
5338 nb_scale_op -= kdu_delta.get("number-of-instances", 1)
5339 deployed_kdu, _ = get_deployed_kdu(
5340 nsr_deployed, kdu_name, vnf_index
5341 )
5342 if deployed_kdu is None:
5343 raise LcmException(
5344 "KDU '{}' for vnf '{}' not deployed".format(
5345 kdu_name, vnf_index
5346 )
5347 )
5348 kdu_instance = deployed_kdu.get("kdu-instance")
5349 instance_num = await self.k8scluster_map[
5350 k8s_cluster_type
5351 ].get_scale_count(resource_name, kdu_instance, vca_id=vca_id)
5352 kdu_replica_count = instance_num - kdu_delta.get(
garciadeblas5697b8b2021-03-24 09:17:02 +01005353 "number-of-instances", 1
5354 )
tierno59d22d22018-09-25 18:10:19 +02005355
aktas5f75f102021-03-15 11:26:10 +03005356 if kdu_replica_count < min_instance_count < instance_num:
5357 kdu_replica_count = min_instance_count
5358 if kdu_replica_count < min_instance_count:
5359 raise LcmException(
5360 "reached the limit of {} (min-instance-count) scaling-in operations for the "
5361 "scaling-group-descriptor '{}'".format(
5362 instance_num, scaling_group
5363 )
5364 )
5365
5366 for x in range(kdu_delta.get("number-of-instances", 1)):
5367 vca_scaling_info.append(
5368 {
5369 "osm_kdu_id": kdu_name,
5370 "member-vnf-index": vnf_index,
5371 "type": "delete",
5372 "kdu_index": instance_num - x - 1,
5373 }
5374 )
5375 scaling_info["kdu-delete"][kdu_name].append(
5376 {
5377 "member-vnf-index": vnf_index,
5378 "type": "delete",
5379 "k8s-cluster-type": k8s_cluster_type,
5380 "resource-name": resource_name,
5381 "scale": kdu_replica_count,
5382 }
5383 )
5384
tierno59d22d22018-09-25 18:10:19 +02005385 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
aktas5f75f102021-03-15 11:26:10 +03005386 vdu_delete = copy(scaling_info.get("vdu-delete"))
5387 if scaling_info["scaling_direction"] == "IN":
tierno59d22d22018-09-25 18:10:19 +02005388 for vdur in reversed(db_vnfr["vdur"]):
tierno27246d82018-09-27 15:59:09 +02005389 if vdu_delete.get(vdur["vdu-id-ref"]):
5390 vdu_delete[vdur["vdu-id-ref"]] -= 1
aktas5f75f102021-03-15 11:26:10 +03005391 scaling_info["vdu"].append(
garciadeblas5697b8b2021-03-24 09:17:02 +01005392 {
5393 "name": vdur.get("name") or vdur.get("vdu-name"),
5394 "vdu_id": vdur["vdu-id-ref"],
5395 "interface": [],
5396 }
5397 )
tierno59d22d22018-09-25 18:10:19 +02005398 for interface in vdur["interfaces"]:
aktas5f75f102021-03-15 11:26:10 +03005399 scaling_info["vdu"][-1]["interface"].append(
garciadeblas5697b8b2021-03-24 09:17:02 +01005400 {
5401 "name": interface["name"],
5402 "ip_address": interface["ip-address"],
5403 "mac_address": interface.get("mac-address"),
5404 }
5405 )
tierno2357f4e2020-10-19 16:38:59 +00005406 # vdu_delete = vdu_scaling_info.pop("vdu-delete")
tierno59d22d22018-09-25 18:10:19 +02005407
kuuseac3a8882019-10-03 10:48:06 +02005408 # PRE-SCALE BEGIN
tierno59d22d22018-09-25 18:10:19 +02005409 step = "Executing pre-scale vnf-config-primitive"
5410 if scaling_descriptor.get("scaling-config-action"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005411 for scaling_config_action in scaling_descriptor[
5412 "scaling-config-action"
5413 ]:
5414 if (
5415 scaling_config_action.get("trigger") == "pre-scale-in"
5416 and scaling_type == "SCALE_IN"
5417 ) or (
5418 scaling_config_action.get("trigger") == "pre-scale-out"
5419 and scaling_type == "SCALE_OUT"
5420 ):
5421 vnf_config_primitive = scaling_config_action[
5422 "vnf-config-primitive-name-ref"
5423 ]
5424 step = db_nslcmop_update[
5425 "detailed-status"
5426 ] = "executing pre-scale scaling-config-action '{}'".format(
5427 vnf_config_primitive
5428 )
tiernoda964822019-01-14 15:53:47 +00005429
tierno59d22d22018-09-25 18:10:19 +02005430 # look for primitive
garciadeblas5697b8b2021-03-24 09:17:02 +01005431 for config_primitive in (
5432 get_configuration(db_vnfd, db_vnfd["id"]) or {}
5433 ).get("config-primitive", ()):
tierno59d22d22018-09-25 18:10:19 +02005434 if config_primitive["name"] == vnf_config_primitive:
tierno59d22d22018-09-25 18:10:19 +02005435 break
5436 else:
5437 raise LcmException(
5438 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
tiernoda964822019-01-14 15:53:47 +00005439 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
garciadeblas5697b8b2021-03-24 09:17:02 +01005440 "primitive".format(scaling_group, vnf_config_primitive)
5441 )
tiernoda964822019-01-14 15:53:47 +00005442
aktas5f75f102021-03-15 11:26:10 +03005443 vnfr_params = {"VDU_SCALE_INFO": scaling_info}
tiernoda964822019-01-14 15:53:47 +00005444 if db_vnfr.get("additionalParamsForVnf"):
5445 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
quilesj7e13aeb2019-10-08 13:34:55 +02005446
tierno9ab95942018-10-10 16:44:22 +02005447 scale_process = "VCA"
tiernod6de1992018-10-11 13:05:52 +02005448 db_nsr_update["config-status"] = "configuring pre-scaling"
garciadeblas5697b8b2021-03-24 09:17:02 +01005449 primitive_params = self._map_primitive_params(
5450 config_primitive, {}, vnfr_params
5451 )
kuuseac3a8882019-10-03 10:48:06 +02005452
tierno7c4e24c2020-05-13 08:41:35 +00005453 # Pre-scale retry check: Check if this sub-operation has been executed before
kuuseac3a8882019-10-03 10:48:06 +02005454 op_index = self._check_or_add_scale_suboperation(
garciadeblas5697b8b2021-03-24 09:17:02 +01005455 db_nslcmop,
garciadeblas5697b8b2021-03-24 09:17:02 +01005456 vnf_index,
5457 vnf_config_primitive,
5458 primitive_params,
5459 "PRE-SCALE",
5460 )
tierno7c4e24c2020-05-13 08:41:35 +00005461 if op_index == self.SUBOPERATION_STATUS_SKIP:
kuuseac3a8882019-10-03 10:48:06 +02005462 # Skip sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01005463 result = "COMPLETED"
5464 result_detail = "Done"
5465 self.logger.debug(
5466 logging_text
5467 + "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
5468 vnf_config_primitive, result, result_detail
5469 )
5470 )
kuuseac3a8882019-10-03 10:48:06 +02005471 else:
tierno7c4e24c2020-05-13 08:41:35 +00005472 if op_index == self.SUBOPERATION_STATUS_NEW:
kuuseac3a8882019-10-03 10:48:06 +02005473 # New sub-operation: Get index of this sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01005474 op_index = (
5475 len(db_nslcmop.get("_admin", {}).get("operations"))
5476 - 1
5477 )
5478 self.logger.debug(
5479 logging_text
5480 + "vnf_config_primitive={} New sub-operation".format(
5481 vnf_config_primitive
5482 )
5483 )
kuuseac3a8882019-10-03 10:48:06 +02005484 else:
tierno7c4e24c2020-05-13 08:41:35 +00005485 # retry: Get registered params for this existing sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01005486 op = db_nslcmop.get("_admin", {}).get("operations", [])[
5487 op_index
5488 ]
5489 vnf_index = op.get("member_vnf_index")
5490 vnf_config_primitive = op.get("primitive")
5491 primitive_params = op.get("primitive_params")
5492 self.logger.debug(
5493 logging_text
5494 + "vnf_config_primitive={} Sub-operation retry".format(
5495 vnf_config_primitive
5496 )
5497 )
tierno588547c2020-07-01 15:30:20 +00005498 # Execute the primitive, either with new (first-time) or registered (reintent) args
garciadeblas5697b8b2021-03-24 09:17:02 +01005499 ee_descriptor_id = config_primitive.get(
5500 "execution-environment-ref"
5501 )
5502 primitive_name = config_primitive.get(
5503 "execution-environment-primitive", vnf_config_primitive
5504 )
5505 ee_id, vca_type = self._look_for_deployed_vca(
5506 nsr_deployed["VCA"],
5507 member_vnf_index=vnf_index,
5508 vdu_id=None,
5509 vdu_count_index=None,
5510 ee_descriptor_id=ee_descriptor_id,
5511 )
kuuseac3a8882019-10-03 10:48:06 +02005512 result, result_detail = await self._ns_execute_primitive(
garciadeblas5697b8b2021-03-24 09:17:02 +01005513 ee_id,
5514 primitive_name,
David Garciac1fe90a2021-03-31 19:12:02 +02005515 primitive_params,
5516 vca_type=vca_type,
5517 vca_id=vca_id,
5518 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005519 self.logger.debug(
5520 logging_text
5521 + "vnf_config_primitive={} Done with result {} {}".format(
5522 vnf_config_primitive, result, result_detail
5523 )
5524 )
kuuseac3a8882019-10-03 10:48:06 +02005525 # Update operationState = COMPLETED | FAILED
5526 self._update_suboperation_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01005527 db_nslcmop, op_index, result, result_detail
5528 )
kuuseac3a8882019-10-03 10:48:06 +02005529
tierno59d22d22018-09-25 18:10:19 +02005530 if result == "FAILED":
5531 raise LcmException(result_detail)
tiernod6de1992018-10-11 13:05:52 +02005532 db_nsr_update["config-status"] = old_config_status
5533 scale_process = None
kuuseac3a8882019-10-03 10:48:06 +02005534 # PRE-SCALE END
tierno59d22d22018-09-25 18:10:19 +02005535
garciadeblas5697b8b2021-03-24 09:17:02 +01005536 db_nsr_update[
5537 "_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index)
5538 ] = nb_scale_op
5539 db_nsr_update[
5540 "_admin.scaling-group.{}.time".format(admin_scale_index)
5541 ] = time()
tierno2357f4e2020-10-19 16:38:59 +00005542
aktas13251562021-02-12 22:19:10 +03005543 # SCALE-IN VCA - BEGIN
aktas5f75f102021-03-15 11:26:10 +03005544 if vca_scaling_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01005545 step = db_nslcmop_update[
5546 "detailed-status"
5547 ] = "Deleting the execution environments"
aktas13251562021-02-12 22:19:10 +03005548 scale_process = "VCA"
aktas5f75f102021-03-15 11:26:10 +03005549 for vca_info in vca_scaling_info:
5550 if vca_info["type"] == "delete":
5551 member_vnf_index = str(vca_info["member-vnf-index"])
garciadeblas5697b8b2021-03-24 09:17:02 +01005552 self.logger.debug(
aktas5f75f102021-03-15 11:26:10 +03005553 logging_text + "vdu info: {}".format(vca_info)
garciadeblas5697b8b2021-03-24 09:17:02 +01005554 )
aktas5f75f102021-03-15 11:26:10 +03005555 if vca_info.get("osm_vdu_id"):
5556 vdu_id = vca_info["osm_vdu_id"]
5557 vdu_index = int(vca_info["vdu_index"])
5558 stage[
5559 1
5560 ] = "Scaling member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
5561 member_vnf_index, vdu_id, vdu_index
5562 )
5563 else:
5564 vdu_index = 0
5565 kdu_id = vca_info["osm_kdu_id"]
5566 stage[
5567 1
5568 ] = "Scaling member_vnf_index={}, kdu_id={}, vdu_index={} ".format(
5569 member_vnf_index, kdu_id, vdu_index
5570 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005571 stage[2] = step = "Scaling in VCA"
5572 self._write_op_status(op_id=nslcmop_id, stage=stage)
aktas13251562021-02-12 22:19:10 +03005573 vca_update = db_nsr["_admin"]["deployed"]["VCA"]
5574 config_update = db_nsr["configurationStatus"]
5575 for vca_index, vca in enumerate(vca_update):
garciadeblas5697b8b2021-03-24 09:17:02 +01005576 if (
5577 (vca or vca.get("ee_id"))
5578 and vca["member-vnf-index"] == member_vnf_index
5579 and vca["vdu_count_index"] == vdu_index
5580 ):
aktas13251562021-02-12 22:19:10 +03005581 if vca.get("vdu_id"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005582 config_descriptor = get_configuration(
5583 db_vnfd, vca.get("vdu_id")
5584 )
aktas13251562021-02-12 22:19:10 +03005585 elif vca.get("kdu_name"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005586 config_descriptor = get_configuration(
5587 db_vnfd, vca.get("kdu_name")
5588 )
aktas13251562021-02-12 22:19:10 +03005589 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01005590 config_descriptor = get_configuration(
5591 db_vnfd, db_vnfd["id"]
5592 )
5593 operation_params = (
5594 db_nslcmop.get("operationParams") or {}
5595 )
5596 exec_terminate_primitives = not operation_params.get(
5597 "skip_terminate_primitives"
5598 ) and vca.get("needed_terminate")
David Garciac1fe90a2021-03-31 19:12:02 +02005599 task = asyncio.ensure_future(
5600 asyncio.wait_for(
5601 self.destroy_N2VC(
5602 logging_text,
5603 db_nslcmop,
5604 vca,
5605 config_descriptor,
5606 vca_index,
5607 destroy_ee=True,
5608 exec_primitives=exec_terminate_primitives,
5609 scaling_in=True,
5610 vca_id=vca_id,
5611 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01005612 timeout=self.timeout_charm_delete,
David Garciac1fe90a2021-03-31 19:12:02 +02005613 )
5614 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005615 tasks_dict_info[task] = "Terminating VCA {}".format(
5616 vca.get("ee_id")
5617 )
aktas13251562021-02-12 22:19:10 +03005618 del vca_update[vca_index]
5619 del config_update[vca_index]
5620 # wait for pending tasks of terminate primitives
5621 if tasks_dict_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01005622 self.logger.debug(
5623 logging_text
5624 + "Waiting for tasks {}".format(
5625 list(tasks_dict_info.keys())
5626 )
5627 )
5628 error_list = await self._wait_for_tasks(
5629 logging_text,
5630 tasks_dict_info,
5631 min(
5632 self.timeout_charm_delete, self.timeout_ns_terminate
5633 ),
5634 stage,
5635 nslcmop_id,
5636 )
aktas13251562021-02-12 22:19:10 +03005637 tasks_dict_info.clear()
5638 if error_list:
5639 raise LcmException("; ".join(error_list))
5640
5641 db_vca_and_config_update = {
5642 "_admin.deployed.VCA": vca_update,
garciadeblas5697b8b2021-03-24 09:17:02 +01005643 "configurationStatus": config_update,
aktas13251562021-02-12 22:19:10 +03005644 }
garciadeblas5697b8b2021-03-24 09:17:02 +01005645 self.update_db_2(
5646 "nsrs", db_nsr["_id"], db_vca_and_config_update
5647 )
aktas13251562021-02-12 22:19:10 +03005648 scale_process = None
5649 # SCALE-IN VCA - END
5650
kuuseac3a8882019-10-03 10:48:06 +02005651 # SCALE RO - BEGIN
aktas5f75f102021-03-15 11:26:10 +03005652 if scaling_info.get("vdu-create") or scaling_info.get("vdu-delete"):
tierno9ab95942018-10-10 16:44:22 +02005653 scale_process = "RO"
tierno2357f4e2020-10-19 16:38:59 +00005654 if self.ro_config.get("ng"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005655 await self._scale_ng_ro(
aktas5f75f102021-03-15 11:26:10 +03005656 logging_text, db_nsr, db_nslcmop, db_vnfr, scaling_info, stage
garciadeblas5697b8b2021-03-24 09:17:02 +01005657 )
aktas5f75f102021-03-15 11:26:10 +03005658 scaling_info.pop("vdu-create", None)
5659 scaling_info.pop("vdu-delete", None)
tierno59d22d22018-09-25 18:10:19 +02005660
tierno9ab95942018-10-10 16:44:22 +02005661 scale_process = None
aktas13251562021-02-12 22:19:10 +03005662 # SCALE RO - END
5663
aktas5f75f102021-03-15 11:26:10 +03005664 # SCALE KDU - BEGIN
5665 if scaling_info.get("kdu-create") or scaling_info.get("kdu-delete"):
5666 scale_process = "KDU"
5667 await self._scale_kdu(
5668 logging_text, nsr_id, nsr_deployed, db_vnfd, vca_id, scaling_info
5669 )
5670 scaling_info.pop("kdu-create", None)
5671 scaling_info.pop("kdu-delete", None)
5672
5673 scale_process = None
5674 # SCALE KDU - END
5675
5676 if db_nsr_update:
5677 self.update_db_2("nsrs", nsr_id, db_nsr_update)
5678
aktas13251562021-02-12 22:19:10 +03005679 # SCALE-UP VCA - BEGIN
aktas5f75f102021-03-15 11:26:10 +03005680 if vca_scaling_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01005681 step = db_nslcmop_update[
5682 "detailed-status"
5683 ] = "Creating new execution environments"
aktas13251562021-02-12 22:19:10 +03005684 scale_process = "VCA"
aktas5f75f102021-03-15 11:26:10 +03005685 for vca_info in vca_scaling_info:
5686 if vca_info["type"] == "create":
5687 member_vnf_index = str(vca_info["member-vnf-index"])
garciadeblas5697b8b2021-03-24 09:17:02 +01005688 self.logger.debug(
aktas5f75f102021-03-15 11:26:10 +03005689 logging_text + "vdu info: {}".format(vca_info)
garciadeblas5697b8b2021-03-24 09:17:02 +01005690 )
aktas13251562021-02-12 22:19:10 +03005691 vnfd_id = db_vnfr["vnfd-ref"]
aktas5f75f102021-03-15 11:26:10 +03005692 if vca_info.get("osm_vdu_id"):
5693 vdu_index = int(vca_info["vdu_index"])
5694 deploy_params = {"OSM": get_osm_params(db_vnfr)}
5695 if db_vnfr.get("additionalParamsForVnf"):
5696 deploy_params.update(
5697 parse_yaml_strings(
5698 db_vnfr["additionalParamsForVnf"].copy()
5699 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005700 )
aktas5f75f102021-03-15 11:26:10 +03005701 descriptor_config = get_configuration(
5702 db_vnfd, db_vnfd["id"]
garciadeblas5697b8b2021-03-24 09:17:02 +01005703 )
aktas5f75f102021-03-15 11:26:10 +03005704 if descriptor_config:
5705 vdu_id = None
5706 vdu_name = None
5707 kdu_name = None
5708 self._deploy_n2vc(
5709 logging_text=logging_text
5710 + "member_vnf_index={} ".format(member_vnf_index),
5711 db_nsr=db_nsr,
5712 db_vnfr=db_vnfr,
5713 nslcmop_id=nslcmop_id,
5714 nsr_id=nsr_id,
5715 nsi_id=nsi_id,
5716 vnfd_id=vnfd_id,
5717 vdu_id=vdu_id,
5718 kdu_name=kdu_name,
5719 member_vnf_index=member_vnf_index,
5720 vdu_index=vdu_index,
5721 vdu_name=vdu_name,
5722 deploy_params=deploy_params,
5723 descriptor_config=descriptor_config,
5724 base_folder=base_folder,
5725 task_instantiation_info=tasks_dict_info,
5726 stage=stage,
5727 )
5728 vdu_id = vca_info["osm_vdu_id"]
5729 vdur = find_in_list(
5730 db_vnfr["vdur"], lambda vdu: vdu["vdu-id-ref"] == vdu_id
aktas13251562021-02-12 22:19:10 +03005731 )
aktas5f75f102021-03-15 11:26:10 +03005732 descriptor_config = get_configuration(db_vnfd, vdu_id)
5733 if vdur.get("additionalParams"):
5734 deploy_params_vdu = parse_yaml_strings(
5735 vdur["additionalParams"]
5736 )
5737 else:
5738 deploy_params_vdu = deploy_params
5739 deploy_params_vdu["OSM"] = get_osm_params(
5740 db_vnfr, vdu_id, vdu_count_index=vdu_index
garciadeblas5697b8b2021-03-24 09:17:02 +01005741 )
aktas5f75f102021-03-15 11:26:10 +03005742 if descriptor_config:
5743 vdu_name = None
5744 kdu_name = None
5745 stage[
5746 1
5747 ] = "Scaling member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
garciadeblas5697b8b2021-03-24 09:17:02 +01005748 member_vnf_index, vdu_id, vdu_index
aktas5f75f102021-03-15 11:26:10 +03005749 )
5750 stage[2] = step = "Scaling out VCA"
5751 self._write_op_status(op_id=nslcmop_id, stage=stage)
5752 self._deploy_n2vc(
5753 logging_text=logging_text
5754 + "member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
5755 member_vnf_index, vdu_id, vdu_index
5756 ),
5757 db_nsr=db_nsr,
5758 db_vnfr=db_vnfr,
5759 nslcmop_id=nslcmop_id,
5760 nsr_id=nsr_id,
5761 nsi_id=nsi_id,
5762 vnfd_id=vnfd_id,
5763 vdu_id=vdu_id,
5764 kdu_name=kdu_name,
5765 member_vnf_index=member_vnf_index,
5766 vdu_index=vdu_index,
5767 vdu_name=vdu_name,
5768 deploy_params=deploy_params_vdu,
5769 descriptor_config=descriptor_config,
5770 base_folder=base_folder,
5771 task_instantiation_info=tasks_dict_info,
5772 stage=stage,
5773 )
5774 else:
5775 kdu_name = vca_info["osm_kdu_id"]
5776 descriptor_config = get_configuration(db_vnfd, kdu_name)
5777 if descriptor_config:
5778 vdu_id = None
5779 kdu_index = int(vca_info["kdu_index"])
5780 vdu_name = None
5781 kdur = next(
5782 x
5783 for x in db_vnfr["kdur"]
5784 if x["kdu-name"] == kdu_name
5785 )
5786 deploy_params_kdu = {"OSM": get_osm_params(db_vnfr)}
5787 if kdur.get("additionalParams"):
5788 deploy_params_kdu = parse_yaml_strings(
5789 kdur["additionalParams"]
5790 )
5791
5792 self._deploy_n2vc(
5793 logging_text=logging_text,
5794 db_nsr=db_nsr,
5795 db_vnfr=db_vnfr,
5796 nslcmop_id=nslcmop_id,
5797 nsr_id=nsr_id,
5798 nsi_id=nsi_id,
5799 vnfd_id=vnfd_id,
5800 vdu_id=vdu_id,
5801 kdu_name=kdu_name,
5802 member_vnf_index=member_vnf_index,
5803 vdu_index=kdu_index,
5804 vdu_name=vdu_name,
5805 deploy_params=deploy_params_kdu,
5806 descriptor_config=descriptor_config,
5807 base_folder=base_folder,
5808 task_instantiation_info=tasks_dict_info,
5809 stage=stage,
5810 )
aktas13251562021-02-12 22:19:10 +03005811 # SCALE-UP VCA - END
5812 scale_process = None
tierno59d22d22018-09-25 18:10:19 +02005813
kuuseac3a8882019-10-03 10:48:06 +02005814 # POST-SCALE BEGIN
tierno59d22d22018-09-25 18:10:19 +02005815 # execute primitive service POST-SCALING
5816 step = "Executing post-scale vnf-config-primitive"
5817 if scaling_descriptor.get("scaling-config-action"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005818 for scaling_config_action in scaling_descriptor[
5819 "scaling-config-action"
5820 ]:
5821 if (
5822 scaling_config_action.get("trigger") == "post-scale-in"
5823 and scaling_type == "SCALE_IN"
5824 ) or (
5825 scaling_config_action.get("trigger") == "post-scale-out"
5826 and scaling_type == "SCALE_OUT"
5827 ):
5828 vnf_config_primitive = scaling_config_action[
5829 "vnf-config-primitive-name-ref"
5830 ]
5831 step = db_nslcmop_update[
5832 "detailed-status"
5833 ] = "executing post-scale scaling-config-action '{}'".format(
5834 vnf_config_primitive
5835 )
tiernoda964822019-01-14 15:53:47 +00005836
aktas5f75f102021-03-15 11:26:10 +03005837 vnfr_params = {"VDU_SCALE_INFO": scaling_info}
tiernoda964822019-01-14 15:53:47 +00005838 if db_vnfr.get("additionalParamsForVnf"):
5839 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
5840
tierno59d22d22018-09-25 18:10:19 +02005841 # look for primitive
bravof9a256db2021-02-22 18:02:07 -03005842 for config_primitive in (
5843 get_configuration(db_vnfd, db_vnfd["id"]) or {}
5844 ).get("config-primitive", ()):
tierno59d22d22018-09-25 18:10:19 +02005845 if config_primitive["name"] == vnf_config_primitive:
tierno59d22d22018-09-25 18:10:19 +02005846 break
5847 else:
tiernoa278b842020-07-08 15:33:55 +00005848 raise LcmException(
5849 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-"
5850 "action[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:"
garciadeblas5697b8b2021-03-24 09:17:02 +01005851 "config-primitive".format(
5852 scaling_group, vnf_config_primitive
5853 )
5854 )
tierno9ab95942018-10-10 16:44:22 +02005855 scale_process = "VCA"
tiernod6de1992018-10-11 13:05:52 +02005856 db_nsr_update["config-status"] = "configuring post-scaling"
garciadeblas5697b8b2021-03-24 09:17:02 +01005857 primitive_params = self._map_primitive_params(
5858 config_primitive, {}, vnfr_params
5859 )
tiernod6de1992018-10-11 13:05:52 +02005860
tierno7c4e24c2020-05-13 08:41:35 +00005861 # Post-scale retry check: Check if this sub-operation has been executed before
kuuseac3a8882019-10-03 10:48:06 +02005862 op_index = self._check_or_add_scale_suboperation(
garciadeblas5697b8b2021-03-24 09:17:02 +01005863 db_nslcmop,
garciadeblas5697b8b2021-03-24 09:17:02 +01005864 vnf_index,
5865 vnf_config_primitive,
5866 primitive_params,
5867 "POST-SCALE",
5868 )
quilesj4cda56b2019-12-05 10:02:20 +00005869 if op_index == self.SUBOPERATION_STATUS_SKIP:
kuuseac3a8882019-10-03 10:48:06 +02005870 # Skip sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01005871 result = "COMPLETED"
5872 result_detail = "Done"
5873 self.logger.debug(
5874 logging_text
5875 + "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
5876 vnf_config_primitive, result, result_detail
5877 )
5878 )
kuuseac3a8882019-10-03 10:48:06 +02005879 else:
quilesj4cda56b2019-12-05 10:02:20 +00005880 if op_index == self.SUBOPERATION_STATUS_NEW:
kuuseac3a8882019-10-03 10:48:06 +02005881 # New sub-operation: Get index of this sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01005882 op_index = (
5883 len(db_nslcmop.get("_admin", {}).get("operations"))
5884 - 1
5885 )
5886 self.logger.debug(
5887 logging_text
5888 + "vnf_config_primitive={} New sub-operation".format(
5889 vnf_config_primitive
5890 )
5891 )
kuuseac3a8882019-10-03 10:48:06 +02005892 else:
tierno7c4e24c2020-05-13 08:41:35 +00005893 # retry: Get registered params for this existing sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01005894 op = db_nslcmop.get("_admin", {}).get("operations", [])[
5895 op_index
5896 ]
5897 vnf_index = op.get("member_vnf_index")
5898 vnf_config_primitive = op.get("primitive")
5899 primitive_params = op.get("primitive_params")
5900 self.logger.debug(
5901 logging_text
5902 + "vnf_config_primitive={} Sub-operation retry".format(
5903 vnf_config_primitive
5904 )
5905 )
tierno588547c2020-07-01 15:30:20 +00005906 # Execute the primitive, either with new (first-time) or registered (reintent) args
garciadeblas5697b8b2021-03-24 09:17:02 +01005907 ee_descriptor_id = config_primitive.get(
5908 "execution-environment-ref"
5909 )
5910 primitive_name = config_primitive.get(
5911 "execution-environment-primitive", vnf_config_primitive
5912 )
5913 ee_id, vca_type = self._look_for_deployed_vca(
5914 nsr_deployed["VCA"],
5915 member_vnf_index=vnf_index,
5916 vdu_id=None,
5917 vdu_count_index=None,
5918 ee_descriptor_id=ee_descriptor_id,
5919 )
kuuseac3a8882019-10-03 10:48:06 +02005920 result, result_detail = await self._ns_execute_primitive(
David Garciac1fe90a2021-03-31 19:12:02 +02005921 ee_id,
5922 primitive_name,
5923 primitive_params,
5924 vca_type=vca_type,
5925 vca_id=vca_id,
5926 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005927 self.logger.debug(
5928 logging_text
5929 + "vnf_config_primitive={} Done with result {} {}".format(
5930 vnf_config_primitive, result, result_detail
5931 )
5932 )
kuuseac3a8882019-10-03 10:48:06 +02005933 # Update operationState = COMPLETED | FAILED
5934 self._update_suboperation_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01005935 db_nslcmop, op_index, result, result_detail
5936 )
kuuseac3a8882019-10-03 10:48:06 +02005937
tierno59d22d22018-09-25 18:10:19 +02005938 if result == "FAILED":
5939 raise LcmException(result_detail)
tiernod6de1992018-10-11 13:05:52 +02005940 db_nsr_update["config-status"] = old_config_status
5941 scale_process = None
kuuseac3a8882019-10-03 10:48:06 +02005942 # POST-SCALE END
tierno59d22d22018-09-25 18:10:19 +02005943
garciadeblas5697b8b2021-03-24 09:17:02 +01005944 db_nsr_update[
5945 "detailed-status"
5946 ] = "" # "scaled {} {}".format(scaling_group, scaling_type)
5947 db_nsr_update["operational-status"] = (
5948 "running"
5949 if old_operational_status == "failed"
ikalyvas02d9e7b2019-05-27 18:16:01 +03005950 else old_operational_status
garciadeblas5697b8b2021-03-24 09:17:02 +01005951 )
tiernod6de1992018-10-11 13:05:52 +02005952 db_nsr_update["config-status"] = old_config_status
tierno59d22d22018-09-25 18:10:19 +02005953 return
garciadeblas5697b8b2021-03-24 09:17:02 +01005954 except (
5955 ROclient.ROClientException,
5956 DbException,
5957 LcmException,
5958 NgRoException,
5959 ) as e:
tierno59d22d22018-09-25 18:10:19 +02005960 self.logger.error(logging_text + "Exit Exception {}".format(e))
5961 exc = e
5962 except asyncio.CancelledError:
garciadeblas5697b8b2021-03-24 09:17:02 +01005963 self.logger.error(
5964 logging_text + "Cancelled Exception while '{}'".format(step)
5965 )
tierno59d22d22018-09-25 18:10:19 +02005966 exc = "Operation was cancelled"
5967 except Exception as e:
5968 exc = traceback.format_exc()
garciadeblas5697b8b2021-03-24 09:17:02 +01005969 self.logger.critical(
5970 logging_text + "Exit Exception {} {}".format(type(e).__name__, e),
5971 exc_info=True,
5972 )
tierno59d22d22018-09-25 18:10:19 +02005973 finally:
garciadeblas5697b8b2021-03-24 09:17:02 +01005974 self._write_ns_status(
5975 nsr_id=nsr_id,
5976 ns_state=None,
5977 current_operation="IDLE",
5978 current_operation_id=None,
5979 )
aktas13251562021-02-12 22:19:10 +03005980 if tasks_dict_info:
5981 stage[1] = "Waiting for instantiate pending tasks."
5982 self.logger.debug(logging_text + stage[1])
garciadeblas5697b8b2021-03-24 09:17:02 +01005983 exc = await self._wait_for_tasks(
5984 logging_text,
5985 tasks_dict_info,
5986 self.timeout_ns_deploy,
5987 stage,
5988 nslcmop_id,
5989 nsr_id=nsr_id,
5990 )
tierno59d22d22018-09-25 18:10:19 +02005991 if exc:
garciadeblas5697b8b2021-03-24 09:17:02 +01005992 db_nslcmop_update[
5993 "detailed-status"
5994 ] = error_description_nslcmop = "FAILED {}: {}".format(step, exc)
tiernoa17d4f42020-04-28 09:59:23 +00005995 nslcmop_operation_state = "FAILED"
tierno59d22d22018-09-25 18:10:19 +02005996 if db_nsr:
tiernod6de1992018-10-11 13:05:52 +02005997 db_nsr_update["operational-status"] = old_operational_status
5998 db_nsr_update["config-status"] = old_config_status
5999 db_nsr_update["detailed-status"] = ""
6000 if scale_process:
6001 if "VCA" in scale_process:
6002 db_nsr_update["config-status"] = "failed"
6003 if "RO" in scale_process:
6004 db_nsr_update["operational-status"] = "failed"
garciadeblas5697b8b2021-03-24 09:17:02 +01006005 db_nsr_update[
6006 "detailed-status"
6007 ] = "FAILED scaling nslcmop={} {}: {}".format(
6008 nslcmop_id, step, exc
6009 )
tiernoa17d4f42020-04-28 09:59:23 +00006010 else:
6011 error_description_nslcmop = None
6012 nslcmop_operation_state = "COMPLETED"
6013 db_nslcmop_update["detailed-status"] = "Done"
quilesj4cda56b2019-12-05 10:02:20 +00006014
garciadeblas5697b8b2021-03-24 09:17:02 +01006015 self._write_op_status(
6016 op_id=nslcmop_id,
6017 stage="",
6018 error_message=error_description_nslcmop,
6019 operation_state=nslcmop_operation_state,
6020 other_update=db_nslcmop_update,
6021 )
tiernoa17d4f42020-04-28 09:59:23 +00006022 if db_nsr:
garciadeblas5697b8b2021-03-24 09:17:02 +01006023 self._write_ns_status(
6024 nsr_id=nsr_id,
6025 ns_state=None,
6026 current_operation="IDLE",
6027 current_operation_id=None,
6028 other_update=db_nsr_update,
6029 )
tiernoa17d4f42020-04-28 09:59:23 +00006030
tierno59d22d22018-09-25 18:10:19 +02006031 if nslcmop_operation_state:
6032 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01006033 msg = {
6034 "nsr_id": nsr_id,
6035 "nslcmop_id": nslcmop_id,
6036 "operationState": nslcmop_operation_state,
6037 }
bravof922c4172020-11-24 21:21:43 -03006038 await self.msg.aiowrite("ns", "scaled", msg, loop=self.loop)
tierno59d22d22018-09-25 18:10:19 +02006039 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01006040 self.logger.error(
6041 logging_text + "kafka_write notification Exception {}".format(e)
6042 )
tierno59d22d22018-09-25 18:10:19 +02006043 self.logger.debug(logging_text + "Exit")
6044 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_scale")
tiernob996d942020-07-03 14:52:28 +00006045
aktas5f75f102021-03-15 11:26:10 +03006046 async def _scale_kdu(
6047 self, logging_text, nsr_id, nsr_deployed, db_vnfd, vca_id, scaling_info
6048 ):
6049 _scaling_info = scaling_info.get("kdu-create") or scaling_info.get("kdu-delete")
6050 for kdu_name in _scaling_info:
6051 for kdu_scaling_info in _scaling_info[kdu_name]:
6052 deployed_kdu, index = get_deployed_kdu(
6053 nsr_deployed, kdu_name, kdu_scaling_info["member-vnf-index"]
6054 )
6055 cluster_uuid = deployed_kdu["k8scluster-uuid"]
6056 kdu_instance = deployed_kdu["kdu-instance"]
6057 scale = int(kdu_scaling_info["scale"])
6058 k8s_cluster_type = kdu_scaling_info["k8s-cluster-type"]
6059
6060 db_dict = {
6061 "collection": "nsrs",
6062 "filter": {"_id": nsr_id},
6063 "path": "_admin.deployed.K8s.{}".format(index),
6064 }
6065
6066 step = "scaling application {}".format(
6067 kdu_scaling_info["resource-name"]
6068 )
6069 self.logger.debug(logging_text + step)
6070
6071 if kdu_scaling_info["type"] == "delete":
6072 kdu_config = get_configuration(db_vnfd, kdu_name)
6073 if (
6074 kdu_config
6075 and kdu_config.get("terminate-config-primitive")
6076 and get_juju_ee_ref(db_vnfd, kdu_name) is None
6077 ):
6078 terminate_config_primitive_list = kdu_config.get(
6079 "terminate-config-primitive"
6080 )
6081 terminate_config_primitive_list.sort(
6082 key=lambda val: int(val["seq"])
6083 )
6084
6085 for (
6086 terminate_config_primitive
6087 ) in terminate_config_primitive_list:
6088 primitive_params_ = self._map_primitive_params(
6089 terminate_config_primitive, {}, {}
6090 )
6091 step = "execute terminate config primitive"
6092 self.logger.debug(logging_text + step)
6093 await asyncio.wait_for(
6094 self.k8scluster_map[k8s_cluster_type].exec_primitive(
6095 cluster_uuid=cluster_uuid,
6096 kdu_instance=kdu_instance,
6097 primitive_name=terminate_config_primitive["name"],
6098 params=primitive_params_,
6099 db_dict=db_dict,
6100 vca_id=vca_id,
6101 ),
6102 timeout=600,
6103 )
6104
6105 await asyncio.wait_for(
6106 self.k8scluster_map[k8s_cluster_type].scale(
6107 kdu_instance,
6108 scale,
6109 kdu_scaling_info["resource-name"],
6110 vca_id=vca_id,
6111 ),
6112 timeout=self.timeout_vca_on_error,
6113 )
6114
6115 if kdu_scaling_info["type"] == "create":
6116 kdu_config = get_configuration(db_vnfd, kdu_name)
6117 if (
6118 kdu_config
6119 and kdu_config.get("initial-config-primitive")
6120 and get_juju_ee_ref(db_vnfd, kdu_name) is None
6121 ):
6122 initial_config_primitive_list = kdu_config.get(
6123 "initial-config-primitive"
6124 )
6125 initial_config_primitive_list.sort(
6126 key=lambda val: int(val["seq"])
6127 )
6128
6129 for initial_config_primitive in initial_config_primitive_list:
6130 primitive_params_ = self._map_primitive_params(
6131 initial_config_primitive, {}, {}
6132 )
6133 step = "execute initial config primitive"
6134 self.logger.debug(logging_text + step)
6135 await asyncio.wait_for(
6136 self.k8scluster_map[k8s_cluster_type].exec_primitive(
6137 cluster_uuid=cluster_uuid,
6138 kdu_instance=kdu_instance,
6139 primitive_name=initial_config_primitive["name"],
6140 params=primitive_params_,
6141 db_dict=db_dict,
6142 vca_id=vca_id,
6143 ),
6144 timeout=600,
6145 )
6146
garciadeblas5697b8b2021-03-24 09:17:02 +01006147 async def _scale_ng_ro(
6148 self, logging_text, db_nsr, db_nslcmop, db_vnfr, vdu_scaling_info, stage
6149 ):
tierno2357f4e2020-10-19 16:38:59 +00006150 nsr_id = db_nslcmop["nsInstanceId"]
6151 db_nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
6152 db_vnfrs = {}
6153
6154 # read from db: vnfd's for every vnf
bravof832f8992020-12-07 12:57:31 -03006155 db_vnfds = []
tierno2357f4e2020-10-19 16:38:59 +00006156
6157 # for each vnf in ns, read vnfd
6158 for vnfr in self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id}):
6159 db_vnfrs[vnfr["member-vnf-index-ref"]] = vnfr
6160 vnfd_id = vnfr["vnfd-id"] # vnfd uuid for this vnf
tierno2357f4e2020-10-19 16:38:59 +00006161 # if we haven't this vnfd, read it from db
bravof832f8992020-12-07 12:57:31 -03006162 if not find_in_list(db_vnfds, lambda a_vnfd: a_vnfd["id"] == vnfd_id):
tierno2357f4e2020-10-19 16:38:59 +00006163 # read from db
6164 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
bravof832f8992020-12-07 12:57:31 -03006165 db_vnfds.append(vnfd)
tierno2357f4e2020-10-19 16:38:59 +00006166 n2vc_key = self.n2vc.get_public_key()
6167 n2vc_key_list = [n2vc_key]
garciadeblas5697b8b2021-03-24 09:17:02 +01006168 self.scale_vnfr(
6169 db_vnfr,
6170 vdu_scaling_info.get("vdu-create"),
6171 vdu_scaling_info.get("vdu-delete"),
6172 mark_delete=True,
6173 )
tierno2357f4e2020-10-19 16:38:59 +00006174 # db_vnfr has been updated, update db_vnfrs to use it
6175 db_vnfrs[db_vnfr["member-vnf-index-ref"]] = db_vnfr
garciadeblas5697b8b2021-03-24 09:17:02 +01006176 await self._instantiate_ng_ro(
6177 logging_text,
6178 nsr_id,
6179 db_nsd,
6180 db_nsr,
6181 db_nslcmop,
6182 db_vnfrs,
6183 db_vnfds,
6184 n2vc_key_list,
6185 stage=stage,
6186 start_deploy=time(),
6187 timeout_ns_deploy=self.timeout_ns_deploy,
6188 )
tierno2357f4e2020-10-19 16:38:59 +00006189 if vdu_scaling_info.get("vdu-delete"):
garciadeblas5697b8b2021-03-24 09:17:02 +01006190 self.scale_vnfr(
6191 db_vnfr, None, vdu_scaling_info["vdu-delete"], mark_delete=False
6192 )
tierno2357f4e2020-10-19 16:38:59 +00006193
garciadeblas5697b8b2021-03-24 09:17:02 +01006194 async def add_prometheus_metrics(
6195 self, ee_id, artifact_path, ee_config_descriptor, vnfr_id, nsr_id, target_ip
6196 ):
tiernob996d942020-07-03 14:52:28 +00006197 if not self.prometheus:
6198 return
6199 # look if exist a file called 'prometheus*.j2' and
6200 artifact_content = self.fs.dir_ls(artifact_path)
garciadeblas5697b8b2021-03-24 09:17:02 +01006201 job_file = next(
6202 (
6203 f
6204 for f in artifact_content
6205 if f.startswith("prometheus") and f.endswith(".j2")
6206 ),
6207 None,
6208 )
tiernob996d942020-07-03 14:52:28 +00006209 if not job_file:
6210 return
6211 with self.fs.file_open((artifact_path, job_file), "r") as f:
6212 job_data = f.read()
6213
6214 # TODO get_service
garciadeblas5697b8b2021-03-24 09:17:02 +01006215 _, _, service = ee_id.partition(".") # remove prefix "namespace."
tiernob996d942020-07-03 14:52:28 +00006216 host_name = "{}-{}".format(service, ee_config_descriptor["metric-service"])
6217 host_port = "80"
6218 vnfr_id = vnfr_id.replace("-", "")
6219 variables = {
6220 "JOB_NAME": vnfr_id,
6221 "TARGET_IP": target_ip,
6222 "EXPORTER_POD_IP": host_name,
6223 "EXPORTER_POD_PORT": host_port,
6224 }
6225 job_list = self.prometheus.parse_job(job_data, variables)
6226 # ensure job_name is using the vnfr_id. Adding the metadata nsr_id
6227 for job in job_list:
garciadeblas5697b8b2021-03-24 09:17:02 +01006228 if (
6229 not isinstance(job.get("job_name"), str)
6230 or vnfr_id not in job["job_name"]
6231 ):
tiernob996d942020-07-03 14:52:28 +00006232 job["job_name"] = vnfr_id + "_" + str(randint(1, 10000))
6233 job["nsr_id"] = nsr_id
6234 job_dict = {jl["job_name"]: jl for jl in job_list}
6235 if await self.prometheus.update(job_dict):
6236 return list(job_dict.keys())
David Garciaaae391f2020-11-09 11:12:54 +01006237
6238 def get_vca_cloud_and_credentials(self, vim_account_id: str) -> (str, str):
6239 """
6240 Get VCA Cloud and VCA Cloud Credentials for the VIM account
6241
6242 :param: vim_account_id: VIM Account ID
6243
6244 :return: (cloud_name, cloud_credential)
6245 """
bravof922c4172020-11-24 21:21:43 -03006246 config = VimAccountDB.get_vim_account_with_id(vim_account_id).get("config", {})
David Garciaaae391f2020-11-09 11:12:54 +01006247 return config.get("vca_cloud"), config.get("vca_cloud_credential")
6248
6249 def get_vca_k8s_cloud_and_credentials(self, vim_account_id: str) -> (str, str):
6250 """
6251 Get VCA K8s Cloud and VCA K8s Cloud Credentials for the VIM account
6252
6253 :param: vim_account_id: VIM Account ID
6254
6255 :return: (cloud_name, cloud_credential)
6256 """
bravof922c4172020-11-24 21:21:43 -03006257 config = VimAccountDB.get_vim_account_with_id(vim_account_id).get("config", {})
David Garciaaae391f2020-11-09 11:12:54 +01006258 return config.get("vca_k8s_cloud"), config.get("vca_k8s_cloud_credential")