blob: 0e1402f6436eaf744f6041fb2526dc58e7cd65fb [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(
Pedro Escaleira064c6442022-04-01 01:49:22 +0100331 self, cluster_uuid, kdu_instance, filter=None, vca_id=None, cluster_type="juju"
garciadeblas5697b8b2021-03-24 09:17:02 +0100332 ):
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
Pedro Escaleira064c6442022-04-01 01:49:22 +0100338 :cluster_type: The cluster type (juju, k8s)
ksaikiranr656b6dd2021-02-19 10:25:18 +0530339 :return: none
340 """
341
342 # self.logger.debug("_on_update_k8s_db(cluster_uuid={}, kdu_instance={}, filter={}"
343 # .format(cluster_uuid, kdu_instance, filter))
344
Pedro Escaleira064c6442022-04-01 01:49:22 +0100345 nsr_id = filter.get("_id")
ksaikiranr656b6dd2021-02-19 10:25:18 +0530346 try:
Pedro Escaleira064c6442022-04-01 01:49:22 +0100347 vca_status = await self.k8scluster_map[cluster_type].status_kdu(
348 cluster_uuid=cluster_uuid,
349 kdu_instance=kdu_instance,
David Garciac1fe90a2021-03-31 19:12:02 +0200350 yaml_format=False,
Pedro Escaleira064c6442022-04-01 01:49:22 +0100351 complete_status=True,
David Garciac1fe90a2021-03-31 19:12:02 +0200352 vca_id=vca_id,
353 )
Pedro Escaleira064c6442022-04-01 01:49:22 +0100354
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
Pedro Escaleira064c6442022-04-01 01:49:22 +0100359 if cluster_type in ("juju-bundle", "juju"):
360 # TODO -> this should be done in a more uniform way, I think in N2VC, in order to update the K8s VCA
361 # status in a similar way between Juju Bundles and Helm Charts on this side
362 await self.k8sclusterjuju.update_vca_status(
363 db_dict["vcaStatus"],
364 kdu_instance,
365 vca_id=vca_id,
366 )
367
368 self.logger.debug(
369 f"Obtained VCA status for cluster type '{cluster_type}': {vca_status}"
David Garciac1fe90a2021-03-31 19:12:02 +0200370 )
ksaikiranr656b6dd2021-02-19 10:25:18 +0530371
372 # write to database
373 self.update_db_2("nsrs", nsr_id, db_dict)
ksaikiranr656b6dd2021-02-19 10:25:18 +0530374 except (asyncio.CancelledError, asyncio.TimeoutError):
375 raise
376 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100377 self.logger.warn("Error updating NS state for ns={}: {}".format(nsr_id, e))
ksaikiranr656b6dd2021-02-19 10:25:18 +0530378
tierno72ef84f2020-10-06 08:22:07 +0000379 @staticmethod
380 def _parse_cloud_init(cloud_init_text, additional_params, vnfd_id, vdu_id):
381 try:
382 env = Environment(undefined=StrictUndefined)
383 template = env.from_string(cloud_init_text)
384 return template.render(additional_params or {})
385 except UndefinedError as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100386 raise LcmException(
387 "Variable {} at vnfd[id={}]:vdu[id={}]:cloud-init/cloud-init-"
388 "file, must be provided in the instantiation parameters inside the "
389 "'additionalParamsForVnf/Vdu' block".format(e, vnfd_id, vdu_id)
390 )
tierno72ef84f2020-10-06 08:22:07 +0000391 except (TemplateError, TemplateNotFound) as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100392 raise LcmException(
393 "Error parsing Jinja2 to cloud-init content at vnfd[id={}]:vdu[id={}]: {}".format(
394 vnfd_id, vdu_id, e
395 )
396 )
tierno72ef84f2020-10-06 08:22:07 +0000397
bravof922c4172020-11-24 21:21:43 -0300398 def _get_vdu_cloud_init_content(self, vdu, vnfd):
399 cloud_init_content = cloud_init_file = None
tierno72ef84f2020-10-06 08:22:07 +0000400 try:
tierno72ef84f2020-10-06 08:22:07 +0000401 if vdu.get("cloud-init-file"):
402 base_folder = vnfd["_admin"]["storage"]
garciadeblas5697b8b2021-03-24 09:17:02 +0100403 cloud_init_file = "{}/{}/cloud_init/{}".format(
404 base_folder["folder"],
405 base_folder["pkg-dir"],
406 vdu["cloud-init-file"],
407 )
tierno72ef84f2020-10-06 08:22:07 +0000408 with self.fs.file_open(cloud_init_file, "r") as ci_file:
409 cloud_init_content = ci_file.read()
410 elif vdu.get("cloud-init"):
411 cloud_init_content = vdu["cloud-init"]
412
413 return cloud_init_content
414 except FsException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100415 raise LcmException(
416 "Error reading vnfd[id={}]:vdu[id={}]:cloud-init-file={}: {}".format(
417 vnfd["id"], vdu["id"], cloud_init_file, e
418 )
419 )
tierno72ef84f2020-10-06 08:22:07 +0000420
tierno72ef84f2020-10-06 08:22:07 +0000421 def _get_vdu_additional_params(self, db_vnfr, vdu_id):
garciadeblas5697b8b2021-03-24 09:17:02 +0100422 vdur = next(
vegalld68fab32022-03-22 16:23:30 +0000423 (vdur for vdur in db_vnfr.get("vdur") if vdu_id == vdur["vdu-id-ref"]),
424 {}
garciadeblas5697b8b2021-03-24 09:17:02 +0100425 )
tierno72ef84f2020-10-06 08:22:07 +0000426 additional_params = vdur.get("additionalParams")
bravof922c4172020-11-24 21:21:43 -0300427 return parse_yaml_strings(additional_params)
tierno72ef84f2020-10-06 08:22:07 +0000428
gcalvino35be9152018-12-20 09:33:12 +0100429 def vnfd2RO(self, vnfd, new_id=None, additionalParams=None, nsrId=None):
tierno59d22d22018-09-25 18:10:19 +0200430 """
431 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
432 :param vnfd: input vnfd
433 :param new_id: overrides vnf id if provided
tierno8a518872018-12-21 13:42:14 +0000434 :param additionalParams: Instantiation params for VNFs provided
gcalvino35be9152018-12-20 09:33:12 +0100435 :param nsrId: Id of the NSR
tierno59d22d22018-09-25 18:10:19 +0200436 :return: copy of vnfd
437 """
tierno72ef84f2020-10-06 08:22:07 +0000438 vnfd_RO = deepcopy(vnfd)
439 # remove unused by RO configuration, monitoring, scaling and internal keys
440 vnfd_RO.pop("_id", None)
441 vnfd_RO.pop("_admin", None)
tierno72ef84f2020-10-06 08:22:07 +0000442 vnfd_RO.pop("monitoring-param", None)
443 vnfd_RO.pop("scaling-group-descriptor", None)
444 vnfd_RO.pop("kdu", None)
445 vnfd_RO.pop("k8s-cluster", None)
446 if new_id:
447 vnfd_RO["id"] = new_id
tierno8a518872018-12-21 13:42:14 +0000448
tierno72ef84f2020-10-06 08:22:07 +0000449 # parse cloud-init or cloud-init-file with the provided variables using Jinja2
450 for vdu in get_iterable(vnfd_RO, "vdu"):
451 vdu.pop("cloud-init-file", None)
452 vdu.pop("cloud-init", None)
453 return vnfd_RO
tierno59d22d22018-09-25 18:10:19 +0200454
tierno2357f4e2020-10-19 16:38:59 +0000455 @staticmethod
456 def ip_profile_2_RO(ip_profile):
457 RO_ip_profile = deepcopy(ip_profile)
458 if "dns-server" in RO_ip_profile:
459 if isinstance(RO_ip_profile["dns-server"], list):
460 RO_ip_profile["dns-address"] = []
461 for ds in RO_ip_profile.pop("dns-server"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100462 RO_ip_profile["dns-address"].append(ds["address"])
tierno2357f4e2020-10-19 16:38:59 +0000463 else:
464 RO_ip_profile["dns-address"] = RO_ip_profile.pop("dns-server")
465 if RO_ip_profile.get("ip-version") == "ipv4":
466 RO_ip_profile["ip-version"] = "IPv4"
467 if RO_ip_profile.get("ip-version") == "ipv6":
468 RO_ip_profile["ip-version"] = "IPv6"
469 if "dhcp-params" in RO_ip_profile:
470 RO_ip_profile["dhcp"] = RO_ip_profile.pop("dhcp-params")
471 return RO_ip_profile
472
bravof922c4172020-11-24 21:21:43 -0300473 def _get_ro_vim_id_for_vim_account(self, vim_account):
474 db_vim = self.db.get_one("vim_accounts", {"_id": vim_account})
475 if db_vim["_admin"]["operationalState"] != "ENABLED":
garciadeblas5697b8b2021-03-24 09:17:02 +0100476 raise LcmException(
477 "VIM={} is not available. operationalState={}".format(
478 vim_account, db_vim["_admin"]["operationalState"]
479 )
480 )
bravof922c4172020-11-24 21:21:43 -0300481 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
482 return RO_vim_id
tierno59d22d22018-09-25 18:10:19 +0200483
bravof922c4172020-11-24 21:21:43 -0300484 def get_ro_wim_id_for_wim_account(self, wim_account):
485 if isinstance(wim_account, str):
486 db_wim = self.db.get_one("wim_accounts", {"_id": wim_account})
487 if db_wim["_admin"]["operationalState"] != "ENABLED":
garciadeblas5697b8b2021-03-24 09:17:02 +0100488 raise LcmException(
489 "WIM={} is not available. operationalState={}".format(
490 wim_account, db_wim["_admin"]["operationalState"]
491 )
492 )
bravof922c4172020-11-24 21:21:43 -0300493 RO_wim_id = db_wim["_admin"]["deployed"]["RO-account"]
494 return RO_wim_id
495 else:
496 return wim_account
tierno59d22d22018-09-25 18:10:19 +0200497
tierno2357f4e2020-10-19 16:38:59 +0000498 def scale_vnfr(self, db_vnfr, vdu_create=None, vdu_delete=None, mark_delete=False):
tierno27246d82018-09-27 15:59:09 +0200499
tierno2357f4e2020-10-19 16:38:59 +0000500 db_vdu_push_list = []
vegalld68fab32022-03-22 16:23:30 +0000501 template_vdur = []
tierno2357f4e2020-10-19 16:38:59 +0000502 db_update = {"_admin.modified": time()}
503 if vdu_create:
504 for vdu_id, vdu_count in vdu_create.items():
garciadeblas5697b8b2021-03-24 09:17:02 +0100505 vdur = next(
506 (
507 vdur
508 for vdur in reversed(db_vnfr["vdur"])
509 if vdur["vdu-id-ref"] == vdu_id
510 ),
511 None,
512 )
tierno2357f4e2020-10-19 16:38:59 +0000513 if not vdur:
vegalld68fab32022-03-22 16:23:30 +0000514 # Read the template saved in the db:
515 self.logger.debug(f"No vdur in the database. Using the vdur-template to scale")
516 vdur_template = db_vnfr.get("vdur-template")
517 if not vdur_template:
518 raise LcmException(
519 "Error scaling OUT VNFR for {}. No vnfr or template exists".format(
garciadeblas5697b8b2021-03-24 09:17:02 +0100520 vdu_id
vegalld68fab32022-03-22 16:23:30 +0000521 )
garciadeblas5697b8b2021-03-24 09:17:02 +0100522 )
vegalld68fab32022-03-22 16:23:30 +0000523 vdur = vdur_template[0]
524 #Delete a template from the database after using it
525 self.db.set_one("vnfrs",
526 {"_id": db_vnfr["_id"]},
527 None,
528 pull={"vdur-template": {"_id": vdur['_id']}}
529 )
tierno2357f4e2020-10-19 16:38:59 +0000530 for count in range(vdu_count):
531 vdur_copy = deepcopy(vdur)
532 vdur_copy["status"] = "BUILD"
533 vdur_copy["status-detailed"] = None
Guillermo Calvinofbf294c2022-01-26 17:40:31 +0100534 vdur_copy["ip-address"] = None
tierno683eb392020-09-25 12:33:15 +0000535 vdur_copy["_id"] = str(uuid4())
tierno2357f4e2020-10-19 16:38:59 +0000536 vdur_copy["count-index"] += count + 1
garciadeblas5697b8b2021-03-24 09:17:02 +0100537 vdur_copy["id"] = "{}-{}".format(
538 vdur_copy["vdu-id-ref"], vdur_copy["count-index"]
539 )
tierno2357f4e2020-10-19 16:38:59 +0000540 vdur_copy.pop("vim_info", None)
541 for iface in vdur_copy["interfaces"]:
542 if iface.get("fixed-ip"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100543 iface["ip-address"] = self.increment_ip_mac(
544 iface["ip-address"], count + 1
545 )
tierno2357f4e2020-10-19 16:38:59 +0000546 else:
547 iface.pop("ip-address", None)
548 if iface.get("fixed-mac"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100549 iface["mac-address"] = self.increment_ip_mac(
550 iface["mac-address"], count + 1
551 )
tierno2357f4e2020-10-19 16:38:59 +0000552 else:
553 iface.pop("mac-address", None)
vegalld68fab32022-03-22 16:23:30 +0000554 if db_vnfr["vdur"]:
555 iface.pop(
556 "mgmt_vnf", None
557 ) # only first vdu can be managment of vnf
tierno2357f4e2020-10-19 16:38:59 +0000558 db_vdu_push_list.append(vdur_copy)
559 # self.logger.debug("scale out, adding vdu={}".format(vdur_copy))
tierno27246d82018-09-27 15:59:09 +0200560 if vdu_delete:
vegalld68fab32022-03-22 16:23:30 +0000561 if len(db_vnfr["vdur"]) == 1:
562 # The scale will move to 0 instances
563 self.logger.debug(f"Scaling to 0 !, creating the template with the last vdur")
564 template_vdur = [db_vnfr["vdur"][0]]
tierno2357f4e2020-10-19 16:38:59 +0000565 for vdu_id, vdu_count in vdu_delete.items():
566 if mark_delete:
garciadeblas5697b8b2021-03-24 09:17:02 +0100567 indexes_to_delete = [
568 iv[0]
569 for iv in enumerate(db_vnfr["vdur"])
570 if iv[1]["vdu-id-ref"] == vdu_id
571 ]
572 db_update.update(
573 {
574 "vdur.{}.status".format(i): "DELETING"
575 for i in indexes_to_delete[-vdu_count:]
576 }
577 )
tierno2357f4e2020-10-19 16:38:59 +0000578 else:
579 # it must be deleted one by one because common.db does not allow otherwise
garciadeblas5697b8b2021-03-24 09:17:02 +0100580 vdus_to_delete = [
581 v
582 for v in reversed(db_vnfr["vdur"])
583 if v["vdu-id-ref"] == vdu_id
584 ]
tierno2357f4e2020-10-19 16:38:59 +0000585 for vdu in vdus_to_delete[:vdu_count]:
garciadeblas5697b8b2021-03-24 09:17:02 +0100586 self.db.set_one(
587 "vnfrs",
588 {"_id": db_vnfr["_id"]},
589 None,
590 pull={"vdur": {"_id": vdu["_id"]}},
591 )
vegalld68fab32022-03-22 16:23:30 +0000592 db_push = {}
593 if db_vdu_push_list:
594 db_push["vdur"] = db_vdu_push_list
595 if template_vdur:
596 db_push["vdur-template"] = template_vdur
597 if not db_push:
598 db_push = None
599 db_vnfr["vdur-template"] = template_vdur
tierno2357f4e2020-10-19 16:38:59 +0000600 self.db.set_one("vnfrs", {"_id": db_vnfr["_id"]}, db_update, push_list=db_push)
601 # modify passed dictionary db_vnfr
602 db_vnfr_ = self.db.get_one("vnfrs", {"_id": db_vnfr["_id"]})
603 db_vnfr["vdur"] = db_vnfr_["vdur"]
tierno27246d82018-09-27 15:59:09 +0200604
tiernof578e552018-11-08 19:07:20 +0100605 def ns_update_nsr(self, ns_update_nsr, db_nsr, nsr_desc_RO):
606 """
607 Updates database nsr with the RO info for the created vld
608 :param ns_update_nsr: dictionary to be filled with the updated info
609 :param db_nsr: content of db_nsr. This is also modified
610 :param nsr_desc_RO: nsr descriptor from RO
611 :return: Nothing, LcmException is raised on errors
612 """
613
614 for vld_index, vld in enumerate(get_iterable(db_nsr, "vld")):
615 for net_RO in get_iterable(nsr_desc_RO, "nets"):
616 if vld["id"] != net_RO.get("ns_net_osm_id"):
617 continue
618 vld["vim-id"] = net_RO.get("vim_net_id")
619 vld["name"] = net_RO.get("vim_name")
620 vld["status"] = net_RO.get("status")
621 vld["status-detailed"] = net_RO.get("error_msg")
622 ns_update_nsr["vld.{}".format(vld_index)] = vld
623 break
624 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100625 raise LcmException(
626 "ns_update_nsr: Not found vld={} at RO info".format(vld["id"])
627 )
tiernof578e552018-11-08 19:07:20 +0100628
tiernoe876f672020-02-13 14:34:48 +0000629 def set_vnfr_at_error(self, db_vnfrs, error_text):
630 try:
631 for db_vnfr in db_vnfrs.values():
632 vnfr_update = {"status": "ERROR"}
633 for vdu_index, vdur in enumerate(get_iterable(db_vnfr, "vdur")):
634 if "status" not in vdur:
635 vdur["status"] = "ERROR"
636 vnfr_update["vdur.{}.status".format(vdu_index)] = "ERROR"
637 if error_text:
638 vdur["status-detailed"] = str(error_text)
garciadeblas5697b8b2021-03-24 09:17:02 +0100639 vnfr_update[
640 "vdur.{}.status-detailed".format(vdu_index)
641 ] = "ERROR"
tiernoe876f672020-02-13 14:34:48 +0000642 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
643 except DbException as e:
644 self.logger.error("Cannot update vnf. {}".format(e))
645
tierno59d22d22018-09-25 18:10:19 +0200646 def ns_update_vnfr(self, db_vnfrs, nsr_desc_RO):
647 """
648 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 +0200649 :param db_vnfrs: dictionary with member-vnf-index: vnfr-content
650 :param nsr_desc_RO: nsr descriptor from RO
651 :return: Nothing, LcmException is raised on errors
tierno59d22d22018-09-25 18:10:19 +0200652 """
653 for vnf_index, db_vnfr in db_vnfrs.items():
654 for vnf_RO in nsr_desc_RO["vnfs"]:
tierno27246d82018-09-27 15:59:09 +0200655 if vnf_RO["member_vnf_index"] != vnf_index:
656 continue
657 vnfr_update = {}
tiernof578e552018-11-08 19:07:20 +0100658 if vnf_RO.get("ip_address"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100659 db_vnfr["ip-address"] = vnfr_update["ip-address"] = vnf_RO[
660 "ip_address"
661 ].split(";")[0]
tiernof578e552018-11-08 19:07:20 +0100662 elif not db_vnfr.get("ip-address"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100663 if db_vnfr.get("vdur"): # if not VDUs, there is not ip_address
664 raise LcmExceptionNoMgmtIP(
665 "ns member_vnf_index '{}' has no IP address".format(
666 vnf_index
667 )
668 )
tierno59d22d22018-09-25 18:10:19 +0200669
tierno27246d82018-09-27 15:59:09 +0200670 for vdu_index, vdur in enumerate(get_iterable(db_vnfr, "vdur")):
671 vdur_RO_count_index = 0
672 if vdur.get("pdu-type"):
673 continue
674 for vdur_RO in get_iterable(vnf_RO, "vms"):
675 if vdur["vdu-id-ref"] != vdur_RO["vdu_osm_id"]:
676 continue
677 if vdur["count-index"] != vdur_RO_count_index:
678 vdur_RO_count_index += 1
679 continue
680 vdur["vim-id"] = vdur_RO.get("vim_vm_id")
tierno1674de82019-04-09 13:03:14 +0000681 if vdur_RO.get("ip_address"):
682 vdur["ip-address"] = vdur_RO["ip_address"].split(";")[0]
tierno274ed572019-04-04 13:33:27 +0000683 else:
684 vdur["ip-address"] = None
tierno27246d82018-09-27 15:59:09 +0200685 vdur["vdu-id-ref"] = vdur_RO.get("vdu_osm_id")
686 vdur["name"] = vdur_RO.get("vim_name")
687 vdur["status"] = vdur_RO.get("status")
688 vdur["status-detailed"] = vdur_RO.get("error_msg")
689 for ifacer in get_iterable(vdur, "interfaces"):
690 for interface_RO in get_iterable(vdur_RO, "interfaces"):
691 if ifacer["name"] == interface_RO.get("internal_name"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100692 ifacer["ip-address"] = interface_RO.get(
693 "ip_address"
694 )
695 ifacer["mac-address"] = interface_RO.get(
696 "mac_address"
697 )
tierno27246d82018-09-27 15:59:09 +0200698 break
699 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100700 raise LcmException(
701 "ns_update_vnfr: Not found member_vnf_index={} vdur={} interface={} "
702 "from VIM info".format(
703 vnf_index, vdur["vdu-id-ref"], ifacer["name"]
704 )
705 )
tierno27246d82018-09-27 15:59:09 +0200706 vnfr_update["vdur.{}".format(vdu_index)] = vdur
707 break
708 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100709 raise LcmException(
710 "ns_update_vnfr: Not found member_vnf_index={} vdur={} count_index={} from "
711 "VIM info".format(
712 vnf_index, vdur["vdu-id-ref"], vdur["count-index"]
713 )
714 )
tiernof578e552018-11-08 19:07:20 +0100715
716 for vld_index, vld in enumerate(get_iterable(db_vnfr, "vld")):
717 for net_RO in get_iterable(nsr_desc_RO, "nets"):
718 if vld["id"] != net_RO.get("vnf_net_osm_id"):
719 continue
720 vld["vim-id"] = net_RO.get("vim_net_id")
721 vld["name"] = net_RO.get("vim_name")
722 vld["status"] = net_RO.get("status")
723 vld["status-detailed"] = net_RO.get("error_msg")
724 vnfr_update["vld.{}".format(vld_index)] = vld
725 break
726 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100727 raise LcmException(
728 "ns_update_vnfr: Not found member_vnf_index={} vld={} from VIM info".format(
729 vnf_index, vld["id"]
730 )
731 )
tiernof578e552018-11-08 19:07:20 +0100732
tierno27246d82018-09-27 15:59:09 +0200733 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
734 break
tierno59d22d22018-09-25 18:10:19 +0200735
736 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100737 raise LcmException(
738 "ns_update_vnfr: Not found member_vnf_index={} from VIM info".format(
739 vnf_index
740 )
741 )
tierno59d22d22018-09-25 18:10:19 +0200742
tierno5ee02052019-12-05 19:55:02 +0000743 def _get_ns_config_info(self, nsr_id):
tiernoc3f2a822019-11-05 13:45:04 +0000744 """
745 Generates a mapping between vnf,vdu elements and the N2VC id
tierno5ee02052019-12-05 19:55:02 +0000746 :param nsr_id: id of nsr to get last database _admin.deployed.VCA that contains this list
tiernoc3f2a822019-11-05 13:45:04 +0000747 :return: a dictionary with {osm-config-mapping: {}} where its element contains:
748 "<member-vnf-index>": <N2VC-id> for a vnf configuration, or
749 "<member-vnf-index>.<vdu.id>.<vdu replica(0, 1,..)>": <N2VC-id> for a vdu configuration
750 """
tierno5ee02052019-12-05 19:55:02 +0000751 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
752 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
tiernoc3f2a822019-11-05 13:45:04 +0000753 mapping = {}
754 ns_config_info = {"osm-config-mapping": mapping}
755 for vca in vca_deployed_list:
756 if not vca["member-vnf-index"]:
757 continue
758 if not vca["vdu_id"]:
759 mapping[vca["member-vnf-index"]] = vca["application"]
760 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100761 mapping[
762 "{}.{}.{}".format(
763 vca["member-vnf-index"], vca["vdu_id"], vca["vdu_count_index"]
764 )
765 ] = vca["application"]
tiernoc3f2a822019-11-05 13:45:04 +0000766 return ns_config_info
767
garciadeblas5697b8b2021-03-24 09:17:02 +0100768 async def _instantiate_ng_ro(
769 self,
770 logging_text,
771 nsr_id,
772 nsd,
773 db_nsr,
774 db_nslcmop,
775 db_vnfrs,
776 db_vnfds,
777 n2vc_key_list,
778 stage,
779 start_deploy,
780 timeout_ns_deploy,
781 ):
tierno2357f4e2020-10-19 16:38:59 +0000782
783 db_vims = {}
784
785 def get_vim_account(vim_account_id):
786 nonlocal db_vims
787 if vim_account_id in db_vims:
788 return db_vims[vim_account_id]
789 db_vim = self.db.get_one("vim_accounts", {"_id": vim_account_id})
790 db_vims[vim_account_id] = db_vim
791 return db_vim
792
793 # modify target_vld info with instantiation parameters
garciadeblas5697b8b2021-03-24 09:17:02 +0100794 def parse_vld_instantiation_params(
795 target_vim, target_vld, vld_params, target_sdn
796 ):
tierno2357f4e2020-10-19 16:38:59 +0000797 if vld_params.get("ip-profile"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100798 target_vld["vim_info"][target_vim]["ip_profile"] = vld_params[
799 "ip-profile"
800 ]
tierno2357f4e2020-10-19 16:38:59 +0000801 if vld_params.get("provider-network"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100802 target_vld["vim_info"][target_vim]["provider_network"] = vld_params[
803 "provider-network"
804 ]
tierno2357f4e2020-10-19 16:38:59 +0000805 if "sdn-ports" in vld_params["provider-network"] and target_sdn:
garciadeblas5697b8b2021-03-24 09:17:02 +0100806 target_vld["vim_info"][target_sdn]["sdn-ports"] = vld_params[
807 "provider-network"
808 ]["sdn-ports"]
cubag034dd2b2022-05-20 01:07:56 +0200809 if vld_params.get("wimAccountId"):
810 target_wim = "wim:{}".format(vld_params["wimAccountId"])
811 target_vld["vim_info"][target_wim] = {}
tierno2357f4e2020-10-19 16:38:59 +0000812 for param in ("vim-network-name", "vim-network-id"):
813 if vld_params.get(param):
814 if isinstance(vld_params[param], dict):
garciaale04694c62021-03-02 10:49:28 -0300815 for vim, vim_net in vld_params[param].items():
bravof922c4172020-11-24 21:21:43 -0300816 other_target_vim = "vim:" + vim
garciadeblas5697b8b2021-03-24 09:17:02 +0100817 populate_dict(
818 target_vld["vim_info"],
819 (other_target_vim, param.replace("-", "_")),
820 vim_net,
821 )
tierno2357f4e2020-10-19 16:38:59 +0000822 else: # isinstance str
garciadeblas5697b8b2021-03-24 09:17:02 +0100823 target_vld["vim_info"][target_vim][
824 param.replace("-", "_")
825 ] = vld_params[param]
bravof922c4172020-11-24 21:21:43 -0300826 if vld_params.get("common_id"):
827 target_vld["common_id"] = vld_params.get("common_id")
tierno2357f4e2020-10-19 16:38:59 +0000828
aticigc90db8e2022-03-11 21:14:22 +0300829 # modify target["ns"]["vld"] with instantiation parameters to override vnf vim-account
830 def update_ns_vld_target(target, ns_params):
831 for vnf_params in ns_params.get("vnf", ()):
832 if vnf_params.get("vimAccountId"):
833 target_vnf = next(
834 (
835 vnfr
836 for vnfr in db_vnfrs.values()
837 if vnf_params["member-vnf-index"]
838 == vnfr["member-vnf-index-ref"]
839 ),
840 None,
841 )
842 vdur = next((vdur for vdur in target_vnf.get("vdur", ())), None)
Pedro Escaleira46a01a62022-09-12 00:14:41 +0100843 if not vdur:
844 return
aticigc90db8e2022-03-11 21:14:22 +0300845 for a_index, a_vld in enumerate(target["ns"]["vld"]):
846 target_vld = find_in_list(
847 get_iterable(vdur, "interfaces"),
848 lambda iface: iface.get("ns-vld-id") == a_vld["name"],
849 )
850 if target_vld:
851 if vnf_params.get("vimAccountId") not in a_vld.get(
852 "vim_info", {}
853 ):
854 target["ns"]["vld"][a_index].get("vim_info").update(
855 {
856 "vim:{}".format(vnf_params["vimAccountId"]): {
857 "vim_network_name": ""
858 }
859 }
860 )
861
tierno69f0d382020-05-07 13:08:09 +0000862 nslcmop_id = db_nslcmop["_id"]
863 target = {
864 "name": db_nsr["name"],
865 "ns": {"vld": []},
866 "vnf": [],
867 "image": deepcopy(db_nsr["image"]),
868 "flavor": deepcopy(db_nsr["flavor"]),
869 "action_id": nslcmop_id,
tierno2357f4e2020-10-19 16:38:59 +0000870 "cloud_init_content": {},
tierno69f0d382020-05-07 13:08:09 +0000871 }
872 for image in target["image"]:
tierno2357f4e2020-10-19 16:38:59 +0000873 image["vim_info"] = {}
tierno69f0d382020-05-07 13:08:09 +0000874 for flavor in target["flavor"]:
tierno2357f4e2020-10-19 16:38:59 +0000875 flavor["vim_info"] = {}
Alexis Romeroef16c402022-03-11 15:29:18 +0100876 if db_nsr.get("affinity-or-anti-affinity-group"):
877 target["affinity-or-anti-affinity-group"] = deepcopy(db_nsr["affinity-or-anti-affinity-group"])
878 for affinity_or_anti_affinity_group in target["affinity-or-anti-affinity-group"]:
879 affinity_or_anti_affinity_group["vim_info"] = {}
tierno69f0d382020-05-07 13:08:09 +0000880
tierno2357f4e2020-10-19 16:38:59 +0000881 if db_nslcmop.get("lcmOperationType") != "instantiate":
882 # get parameters of instantiation:
garciadeblas5697b8b2021-03-24 09:17:02 +0100883 db_nslcmop_instantiate = self.db.get_list(
884 "nslcmops",
885 {
886 "nsInstanceId": db_nslcmop["nsInstanceId"],
887 "lcmOperationType": "instantiate",
888 },
889 )[-1]
tierno2357f4e2020-10-19 16:38:59 +0000890 ns_params = db_nslcmop_instantiate.get("operationParams")
891 else:
892 ns_params = db_nslcmop.get("operationParams")
bravof922c4172020-11-24 21:21:43 -0300893 ssh_keys_instantiation = ns_params.get("ssh_keys") or []
894 ssh_keys_all = ssh_keys_instantiation + (n2vc_key_list or [])
tierno69f0d382020-05-07 13:08:09 +0000895
896 cp2target = {}
tierno2357f4e2020-10-19 16:38:59 +0000897 for vld_index, vld in enumerate(db_nsr.get("vld")):
898 target_vim = "vim:{}".format(ns_params["vimAccountId"])
899 target_vld = {
900 "id": vld["id"],
901 "name": vld["name"],
902 "mgmt-network": vld.get("mgmt-network", False),
903 "type": vld.get("type"),
904 "vim_info": {
bravof922c4172020-11-24 21:21:43 -0300905 target_vim: {
906 "vim_network_name": vld.get("vim-network-name"),
garciadeblas5697b8b2021-03-24 09:17:02 +0100907 "vim_account_id": ns_params["vimAccountId"],
bravof922c4172020-11-24 21:21:43 -0300908 }
garciadeblas5697b8b2021-03-24 09:17:02 +0100909 },
tierno2357f4e2020-10-19 16:38:59 +0000910 }
911 # check if this network needs SDN assist
tierno2357f4e2020-10-19 16:38:59 +0000912 if vld.get("pci-interfaces"):
garciadeblasa5ae90b2021-02-12 11:26:46 +0000913 db_vim = get_vim_account(ns_params["vimAccountId"])
Gulsum Atici5ce6ea82023-01-10 14:10:42 +0300914 if vim_config := db_vim.get("config"):
915 if sdnc_id := vim_config.get("sdn-controller"):
916 sdn_vld = "nsrs:{}:vld.{}".format(nsr_id, vld["id"])
917 target_sdn = "sdn:{}".format(sdnc_id)
918 target_vld["vim_info"][target_sdn] = {
919 "sdn": True,
920 "target_vim": target_vim,
921 "vlds": [sdn_vld],
922 "type": vld.get("type"),
923 }
tierno2357f4e2020-10-19 16:38:59 +0000924
bravof922c4172020-11-24 21:21:43 -0300925 nsd_vnf_profiles = get_vnf_profiles(nsd)
926 for nsd_vnf_profile in nsd_vnf_profiles:
927 for cp in nsd_vnf_profile["virtual-link-connectivity"]:
928 if cp["virtual-link-profile-id"] == vld["id"]:
garciadeblas5697b8b2021-03-24 09:17:02 +0100929 cp2target[
930 "member_vnf:{}.{}".format(
931 cp["constituent-cpd-id"][0][
932 "constituent-base-element-id"
933 ],
934 cp["constituent-cpd-id"][0]["constituent-cpd-id"],
935 )
936 ] = "nsrs:{}:vld.{}".format(nsr_id, vld_index)
tierno2357f4e2020-10-19 16:38:59 +0000937
938 # check at nsd descriptor, if there is an ip-profile
939 vld_params = {}
lloretgalleg19008482021-04-19 11:40:18 +0000940 nsd_vlp = find_in_list(
941 get_virtual_link_profiles(nsd),
garciadeblas5697b8b2021-03-24 09:17:02 +0100942 lambda a_link_profile: a_link_profile["virtual-link-desc-id"]
943 == vld["id"],
944 )
945 if (
946 nsd_vlp
947 and nsd_vlp.get("virtual-link-protocol-data")
948 and nsd_vlp["virtual-link-protocol-data"].get("l3-protocol-data")
949 ):
950 ip_profile_source_data = nsd_vlp["virtual-link-protocol-data"][
951 "l3-protocol-data"
952 ]
lloretgalleg19008482021-04-19 11:40:18 +0000953 ip_profile_dest_data = {}
954 if "ip-version" in ip_profile_source_data:
garciadeblas5697b8b2021-03-24 09:17:02 +0100955 ip_profile_dest_data["ip-version"] = ip_profile_source_data[
956 "ip-version"
957 ]
lloretgalleg19008482021-04-19 11:40:18 +0000958 if "cidr" in ip_profile_source_data:
garciadeblas5697b8b2021-03-24 09:17:02 +0100959 ip_profile_dest_data["subnet-address"] = ip_profile_source_data[
960 "cidr"
961 ]
lloretgalleg19008482021-04-19 11:40:18 +0000962 if "gateway-ip" in ip_profile_source_data:
garciadeblas5697b8b2021-03-24 09:17:02 +0100963 ip_profile_dest_data["gateway-address"] = ip_profile_source_data[
964 "gateway-ip"
965 ]
lloretgalleg19008482021-04-19 11:40:18 +0000966 if "dhcp-enabled" in ip_profile_source_data:
967 ip_profile_dest_data["dhcp-params"] = {
968 "enabled": ip_profile_source_data["dhcp-enabled"]
969 }
970 vld_params["ip-profile"] = ip_profile_dest_data
bravof922c4172020-11-24 21:21:43 -0300971
tierno2357f4e2020-10-19 16:38:59 +0000972 # update vld_params with instantiation params
garciadeblas5697b8b2021-03-24 09:17:02 +0100973 vld_instantiation_params = find_in_list(
974 get_iterable(ns_params, "vld"),
975 lambda a_vld: a_vld["name"] in (vld["name"], vld["id"]),
976 )
tierno2357f4e2020-10-19 16:38:59 +0000977 if vld_instantiation_params:
978 vld_params.update(vld_instantiation_params)
bravof922c4172020-11-24 21:21:43 -0300979 parse_vld_instantiation_params(target_vim, target_vld, vld_params, None)
tierno69f0d382020-05-07 13:08:09 +0000980 target["ns"]["vld"].append(target_vld)
aticigc90db8e2022-03-11 21:14:22 +0300981 # Update the target ns_vld if vnf vim_account is overriden by instantiation params
982 update_ns_vld_target(target, ns_params)
bravof922c4172020-11-24 21:21:43 -0300983
tierno69f0d382020-05-07 13:08:09 +0000984 for vnfr in db_vnfrs.values():
garciadeblas5697b8b2021-03-24 09:17:02 +0100985 vnfd = find_in_list(
986 db_vnfds, lambda db_vnf: db_vnf["id"] == vnfr["vnfd-ref"]
987 )
988 vnf_params = find_in_list(
989 get_iterable(ns_params, "vnf"),
990 lambda a_vnf: a_vnf["member-vnf-index"] == vnfr["member-vnf-index-ref"],
991 )
tierno69f0d382020-05-07 13:08:09 +0000992 target_vnf = deepcopy(vnfr)
tierno2357f4e2020-10-19 16:38:59 +0000993 target_vim = "vim:{}".format(vnfr["vim-account-id"])
tierno69f0d382020-05-07 13:08:09 +0000994 for vld in target_vnf.get("vld", ()):
tierno2357f4e2020-10-19 16:38:59 +0000995 # check if connected to a ns.vld, to fill target'
garciadeblas5697b8b2021-03-24 09:17:02 +0100996 vnf_cp = find_in_list(
997 vnfd.get("int-virtual-link-desc", ()),
998 lambda cpd: cpd.get("id") == vld["id"],
999 )
tierno69f0d382020-05-07 13:08:09 +00001000 if vnf_cp:
garciadeblas5697b8b2021-03-24 09:17:02 +01001001 ns_cp = "member_vnf:{}.{}".format(
1002 vnfr["member-vnf-index-ref"], vnf_cp["id"]
1003 )
tierno69f0d382020-05-07 13:08:09 +00001004 if cp2target.get(ns_cp):
1005 vld["target"] = cp2target[ns_cp]
bravof922c4172020-11-24 21:21:43 -03001006
garciadeblas5697b8b2021-03-24 09:17:02 +01001007 vld["vim_info"] = {
1008 target_vim: {"vim_network_name": vld.get("vim-network-name")}
1009 }
tierno2357f4e2020-10-19 16:38:59 +00001010 # check if this network needs SDN assist
1011 target_sdn = None
1012 if vld.get("pci-interfaces"):
1013 db_vim = get_vim_account(vnfr["vim-account-id"])
1014 sdnc_id = db_vim["config"].get("sdn-controller")
1015 if sdnc_id:
1016 sdn_vld = "vnfrs:{}:vld.{}".format(target_vnf["_id"], vld["id"])
1017 target_sdn = "sdn:{}".format(sdnc_id)
1018 vld["vim_info"][target_sdn] = {
garciadeblas5697b8b2021-03-24 09:17:02 +01001019 "sdn": True,
1020 "target_vim": target_vim,
1021 "vlds": [sdn_vld],
1022 "type": vld.get("type"),
1023 }
tierno69f0d382020-05-07 13:08:09 +00001024
tierno2357f4e2020-10-19 16:38:59 +00001025 # check at vnfd descriptor, if there is an ip-profile
1026 vld_params = {}
bravof922c4172020-11-24 21:21:43 -03001027 vnfd_vlp = find_in_list(
1028 get_virtual_link_profiles(vnfd),
garciadeblas5697b8b2021-03-24 09:17:02 +01001029 lambda a_link_profile: a_link_profile["id"] == vld["id"],
bravof922c4172020-11-24 21:21:43 -03001030 )
garciadeblas5697b8b2021-03-24 09:17:02 +01001031 if (
1032 vnfd_vlp
1033 and vnfd_vlp.get("virtual-link-protocol-data")
1034 and vnfd_vlp["virtual-link-protocol-data"].get("l3-protocol-data")
1035 ):
1036 ip_profile_source_data = vnfd_vlp["virtual-link-protocol-data"][
1037 "l3-protocol-data"
1038 ]
bravof922c4172020-11-24 21:21:43 -03001039 ip_profile_dest_data = {}
1040 if "ip-version" in ip_profile_source_data:
garciadeblas5697b8b2021-03-24 09:17:02 +01001041 ip_profile_dest_data["ip-version"] = ip_profile_source_data[
1042 "ip-version"
1043 ]
bravof922c4172020-11-24 21:21:43 -03001044 if "cidr" in ip_profile_source_data:
garciadeblas5697b8b2021-03-24 09:17:02 +01001045 ip_profile_dest_data["subnet-address"] = ip_profile_source_data[
1046 "cidr"
1047 ]
bravof922c4172020-11-24 21:21:43 -03001048 if "gateway-ip" in ip_profile_source_data:
garciadeblas5697b8b2021-03-24 09:17:02 +01001049 ip_profile_dest_data[
1050 "gateway-address"
1051 ] = ip_profile_source_data["gateway-ip"]
bravof922c4172020-11-24 21:21:43 -03001052 if "dhcp-enabled" in ip_profile_source_data:
1053 ip_profile_dest_data["dhcp-params"] = {
1054 "enabled": ip_profile_source_data["dhcp-enabled"]
1055 }
1056
1057 vld_params["ip-profile"] = ip_profile_dest_data
tierno2357f4e2020-10-19 16:38:59 +00001058 # update vld_params with instantiation params
1059 if vnf_params:
garciadeblas5697b8b2021-03-24 09:17:02 +01001060 vld_instantiation_params = find_in_list(
1061 get_iterable(vnf_params, "internal-vld"),
1062 lambda i_vld: i_vld["name"] == vld["id"],
1063 )
tierno2357f4e2020-10-19 16:38:59 +00001064 if vld_instantiation_params:
1065 vld_params.update(vld_instantiation_params)
1066 parse_vld_instantiation_params(target_vim, vld, vld_params, target_sdn)
1067
1068 vdur_list = []
tierno69f0d382020-05-07 13:08:09 +00001069 for vdur in target_vnf.get("vdur", ()):
tierno2357f4e2020-10-19 16:38:59 +00001070 if vdur.get("status") == "DELETING" or vdur.get("pdu-type"):
1071 continue # This vdu must not be created
bravof922c4172020-11-24 21:21:43 -03001072 vdur["vim_info"] = {"vim_account_id": vnfr["vim-account-id"]}
tierno69f0d382020-05-07 13:08:09 +00001073
bravof922c4172020-11-24 21:21:43 -03001074 self.logger.debug("NS > ssh_keys > {}".format(ssh_keys_all))
1075
1076 if ssh_keys_all:
bravofe5a31bc2021-02-17 19:09:12 -03001077 vdu_configuration = get_configuration(vnfd, vdur["vdu-id-ref"])
1078 vnf_configuration = get_configuration(vnfd, vnfd["id"])
garciadeblas5697b8b2021-03-24 09:17:02 +01001079 if (
1080 vdu_configuration
1081 and vdu_configuration.get("config-access")
1082 and vdu_configuration.get("config-access").get("ssh-access")
1083 ):
bravof922c4172020-11-24 21:21:43 -03001084 vdur["ssh-keys"] = ssh_keys_all
garciadeblas5697b8b2021-03-24 09:17:02 +01001085 vdur["ssh-access-required"] = vdu_configuration[
1086 "config-access"
1087 ]["ssh-access"]["required"]
1088 elif (
1089 vnf_configuration
1090 and vnf_configuration.get("config-access")
1091 and vnf_configuration.get("config-access").get("ssh-access")
1092 and any(iface.get("mgmt-vnf") for iface in vdur["interfaces"])
1093 ):
bravof922c4172020-11-24 21:21:43 -03001094 vdur["ssh-keys"] = ssh_keys_all
garciadeblas5697b8b2021-03-24 09:17:02 +01001095 vdur["ssh-access-required"] = vnf_configuration[
1096 "config-access"
1097 ]["ssh-access"]["required"]
1098 elif ssh_keys_instantiation and find_in_list(
1099 vdur["interfaces"], lambda iface: iface.get("mgmt-vnf")
1100 ):
bravof922c4172020-11-24 21:21:43 -03001101 vdur["ssh-keys"] = ssh_keys_instantiation
tierno69f0d382020-05-07 13:08:09 +00001102
bravof922c4172020-11-24 21:21:43 -03001103 self.logger.debug("NS > vdur > {}".format(vdur))
1104
1105 vdud = get_vdu(vnfd, vdur["vdu-id-ref"])
tierno69f0d382020-05-07 13:08:09 +00001106 # cloud-init
1107 if vdud.get("cloud-init-file"):
garciadeblas5697b8b2021-03-24 09:17:02 +01001108 vdur["cloud-init"] = "{}:file:{}".format(
1109 vnfd["_id"], vdud.get("cloud-init-file")
1110 )
tierno2357f4e2020-10-19 16:38:59 +00001111 # read file and put content at target.cloul_init_content. Avoid ng_ro to use shared package system
1112 if vdur["cloud-init"] not in target["cloud_init_content"]:
1113 base_folder = vnfd["_admin"]["storage"]
garciadeblas5697b8b2021-03-24 09:17:02 +01001114 cloud_init_file = "{}/{}/cloud_init/{}".format(
1115 base_folder["folder"],
1116 base_folder["pkg-dir"],
1117 vdud.get("cloud-init-file"),
1118 )
tierno2357f4e2020-10-19 16:38:59 +00001119 with self.fs.file_open(cloud_init_file, "r") as ci_file:
garciadeblas5697b8b2021-03-24 09:17:02 +01001120 target["cloud_init_content"][
1121 vdur["cloud-init"]
1122 ] = ci_file.read()
tierno69f0d382020-05-07 13:08:09 +00001123 elif vdud.get("cloud-init"):
garciadeblas5697b8b2021-03-24 09:17:02 +01001124 vdur["cloud-init"] = "{}:vdu:{}".format(
1125 vnfd["_id"], get_vdu_index(vnfd, vdur["vdu-id-ref"])
1126 )
tierno2357f4e2020-10-19 16:38:59 +00001127 # put content at target.cloul_init_content. Avoid ng_ro read vnfd descriptor
garciadeblas5697b8b2021-03-24 09:17:02 +01001128 target["cloud_init_content"][vdur["cloud-init"]] = vdud[
1129 "cloud-init"
1130 ]
tierno2357f4e2020-10-19 16:38:59 +00001131 vdur["additionalParams"] = vdur.get("additionalParams") or {}
garciadeblas5697b8b2021-03-24 09:17:02 +01001132 deploy_params_vdu = self._format_additional_params(
1133 vdur.get("additionalParams") or {}
1134 )
1135 deploy_params_vdu["OSM"] = get_osm_params(
1136 vnfr, vdur["vdu-id-ref"], vdur["count-index"]
1137 )
tierno2357f4e2020-10-19 16:38:59 +00001138 vdur["additionalParams"] = deploy_params_vdu
tierno69f0d382020-05-07 13:08:09 +00001139
1140 # flavor
1141 ns_flavor = target["flavor"][int(vdur["ns-flavor-id"])]
tierno2357f4e2020-10-19 16:38:59 +00001142 if target_vim not in ns_flavor["vim_info"]:
1143 ns_flavor["vim_info"][target_vim] = {}
lloretgalleg7dc94672021-02-08 11:49:50 +00001144
1145 # deal with images
1146 # in case alternative images are provided we must check if they should be applied
1147 # for the vim_type, modify the vim_type taking into account
1148 ns_image_id = int(vdur["ns-image-id"])
1149 if vdur.get("alt-image-ids"):
1150 db_vim = get_vim_account(vnfr["vim-account-id"])
1151 vim_type = db_vim["vim_type"]
1152 for alt_image_id in vdur.get("alt-image-ids"):
1153 ns_alt_image = target["image"][int(alt_image_id)]
1154 if vim_type == ns_alt_image.get("vim-type"):
1155 # must use alternative image
garciadeblas5697b8b2021-03-24 09:17:02 +01001156 self.logger.debug(
1157 "use alternative image id: {}".format(alt_image_id)
1158 )
lloretgalleg7dc94672021-02-08 11:49:50 +00001159 ns_image_id = alt_image_id
1160 vdur["ns-image-id"] = ns_image_id
1161 break
1162 ns_image = target["image"][int(ns_image_id)]
tierno2357f4e2020-10-19 16:38:59 +00001163 if target_vim not in ns_image["vim_info"]:
1164 ns_image["vim_info"][target_vim] = {}
tierno69f0d382020-05-07 13:08:09 +00001165
Alexis Romeroef16c402022-03-11 15:29:18 +01001166 # Affinity groups
1167 if vdur.get("affinity-or-anti-affinity-group-id"):
1168 for ags_id in vdur["affinity-or-anti-affinity-group-id"]:
1169 ns_ags = target["affinity-or-anti-affinity-group"][int(ags_id)]
1170 if target_vim not in ns_ags["vim_info"]:
1171 ns_ags["vim_info"][target_vim] = {}
1172
tierno2357f4e2020-10-19 16:38:59 +00001173 vdur["vim_info"] = {target_vim: {}}
1174 # instantiation parameters
1175 # if vnf_params:
1176 # vdu_instantiation_params = next((v for v in get_iterable(vnf_params, "vdu") if v["id"] ==
1177 # vdud["id"]), None)
1178 vdur_list.append(vdur)
1179 target_vnf["vdur"] = vdur_list
tierno69f0d382020-05-07 13:08:09 +00001180 target["vnf"].append(target_vnf)
1181
1182 desc = await self.RO.deploy(nsr_id, target)
bravof922c4172020-11-24 21:21:43 -03001183 self.logger.debug("RO return > {}".format(desc))
tierno69f0d382020-05-07 13:08:09 +00001184 action_id = desc["action_id"]
garciadeblas5697b8b2021-03-24 09:17:02 +01001185 await self._wait_ng_ro(
1186 nsr_id, action_id, nslcmop_id, start_deploy, timeout_ns_deploy, stage
1187 )
tierno69f0d382020-05-07 13:08:09 +00001188
1189 # Updating NSR
1190 db_nsr_update = {
1191 "_admin.deployed.RO.operational-status": "running",
garciadeblas5697b8b2021-03-24 09:17:02 +01001192 "detailed-status": " ".join(stage),
tierno69f0d382020-05-07 13:08:09 +00001193 }
1194 # db_nsr["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
1195 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1196 self._write_op_status(nslcmop_id, stage)
garciadeblas5697b8b2021-03-24 09:17:02 +01001197 self.logger.debug(
1198 logging_text + "ns deployed at RO. RO_id={}".format(action_id)
1199 )
tierno69f0d382020-05-07 13:08:09 +00001200 return
1201
garciadeblas5697b8b2021-03-24 09:17:02 +01001202 async def _wait_ng_ro(
1203 self,
1204 nsr_id,
1205 action_id,
1206 nslcmop_id=None,
1207 start_time=None,
1208 timeout=600,
1209 stage=None,
1210 ):
tierno69f0d382020-05-07 13:08:09 +00001211 detailed_status_old = None
1212 db_nsr_update = {}
tierno2357f4e2020-10-19 16:38:59 +00001213 start_time = start_time or time()
tierno69f0d382020-05-07 13:08:09 +00001214 while time() <= start_time + timeout:
1215 desc_status = await self.RO.status(nsr_id, action_id)
bravof922c4172020-11-24 21:21:43 -03001216 self.logger.debug("Wait NG RO > {}".format(desc_status))
tierno69f0d382020-05-07 13:08:09 +00001217 if desc_status["status"] == "FAILED":
1218 raise NgRoException(desc_status["details"])
1219 elif desc_status["status"] == "BUILD":
tierno2357f4e2020-10-19 16:38:59 +00001220 if stage:
1221 stage[2] = "VIM: ({})".format(desc_status["details"])
tierno69f0d382020-05-07 13:08:09 +00001222 elif desc_status["status"] == "DONE":
tierno2357f4e2020-10-19 16:38:59 +00001223 if stage:
1224 stage[2] = "Deployed at VIM"
tierno69f0d382020-05-07 13:08:09 +00001225 break
1226 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001227 assert False, "ROclient.check_ns_status returns unknown {}".format(
1228 desc_status["status"]
1229 )
tierno2357f4e2020-10-19 16:38:59 +00001230 if stage and nslcmop_id and stage[2] != detailed_status_old:
tierno69f0d382020-05-07 13:08:09 +00001231 detailed_status_old = stage[2]
1232 db_nsr_update["detailed-status"] = " ".join(stage)
1233 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1234 self._write_op_status(nslcmop_id, stage)
bravof922c4172020-11-24 21:21:43 -03001235 await asyncio.sleep(15, loop=self.loop)
tierno69f0d382020-05-07 13:08:09 +00001236 else: # timeout_ns_deploy
1237 raise NgRoException("Timeout waiting ns to deploy")
1238
garciadeblas5697b8b2021-03-24 09:17:02 +01001239 async def _terminate_ng_ro(
1240 self, logging_text, nsr_deployed, nsr_id, nslcmop_id, stage
1241 ):
tierno69f0d382020-05-07 13:08:09 +00001242 db_nsr_update = {}
1243 failed_detail = []
1244 action_id = None
1245 start_deploy = time()
1246 try:
1247 target = {
1248 "ns": {"vld": []},
1249 "vnf": [],
1250 "image": [],
1251 "flavor": [],
garciadeblas5697b8b2021-03-24 09:17:02 +01001252 "action_id": nslcmop_id,
tierno69f0d382020-05-07 13:08:09 +00001253 }
1254 desc = await self.RO.deploy(nsr_id, target)
1255 action_id = desc["action_id"]
1256 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = action_id
1257 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETING"
garciadeblas5697b8b2021-03-24 09:17:02 +01001258 self.logger.debug(
1259 logging_text
1260 + "ns terminate action at RO. action_id={}".format(action_id)
1261 )
tierno69f0d382020-05-07 13:08:09 +00001262
1263 # wait until done
1264 delete_timeout = 20 * 60 # 20 minutes
garciadeblas5697b8b2021-03-24 09:17:02 +01001265 await self._wait_ng_ro(
1266 nsr_id, action_id, nslcmop_id, start_deploy, delete_timeout, stage
1267 )
tierno69f0d382020-05-07 13:08:09 +00001268
1269 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
1270 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
1271 # delete all nsr
1272 await self.RO.delete(nsr_id)
1273 except Exception as e:
1274 if isinstance(e, NgRoException) and e.http_code == 404: # not found
1275 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
1276 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
1277 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
garciadeblas5697b8b2021-03-24 09:17:02 +01001278 self.logger.debug(
1279 logging_text + "RO_action_id={} already deleted".format(action_id)
1280 )
tierno69f0d382020-05-07 13:08:09 +00001281 elif isinstance(e, NgRoException) and e.http_code == 409: # conflict
1282 failed_detail.append("delete conflict: {}".format(e))
garciadeblas5697b8b2021-03-24 09:17:02 +01001283 self.logger.debug(
1284 logging_text
1285 + "RO_action_id={} delete conflict: {}".format(action_id, e)
1286 )
tierno69f0d382020-05-07 13:08:09 +00001287 else:
1288 failed_detail.append("delete error: {}".format(e))
garciadeblas5697b8b2021-03-24 09:17:02 +01001289 self.logger.error(
1290 logging_text
1291 + "RO_action_id={} delete error: {}".format(action_id, e)
1292 )
tierno69f0d382020-05-07 13:08:09 +00001293
1294 if failed_detail:
1295 stage[2] = "Error deleting from VIM"
1296 else:
1297 stage[2] = "Deleted from VIM"
1298 db_nsr_update["detailed-status"] = " ".join(stage)
1299 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1300 self._write_op_status(nslcmop_id, stage)
1301
1302 if failed_detail:
1303 raise LcmException("; ".join(failed_detail))
1304 return
1305
garciadeblas5697b8b2021-03-24 09:17:02 +01001306 async def instantiate_RO(
1307 self,
1308 logging_text,
1309 nsr_id,
1310 nsd,
1311 db_nsr,
1312 db_nslcmop,
1313 db_vnfrs,
1314 db_vnfds,
1315 n2vc_key_list,
1316 stage,
1317 ):
tiernoe95ed362020-04-23 08:24:57 +00001318 """
1319 Instantiate at RO
1320 :param logging_text: preffix text to use at logging
1321 :param nsr_id: nsr identity
1322 :param nsd: database content of ns descriptor
1323 :param db_nsr: database content of ns record
1324 :param db_nslcmop: database content of ns operation, in this case, 'instantiate'
1325 :param db_vnfrs:
bravof922c4172020-11-24 21:21:43 -03001326 :param db_vnfds: database content of vnfds, indexed by id (not _id). {id: {vnfd_object}, ...}
tiernoe95ed362020-04-23 08:24:57 +00001327 :param n2vc_key_list: ssh-public-key list to be inserted to management vdus via cloud-init
1328 :param stage: list with 3 items: [general stage, tasks, vim_specific]. This task will write over vim_specific
1329 :return: None or exception
1330 """
tiernoe876f672020-02-13 14:34:48 +00001331 try:
tiernoe876f672020-02-13 14:34:48 +00001332 start_deploy = time()
1333 ns_params = db_nslcmop.get("operationParams")
1334 if ns_params and ns_params.get("timeout_ns_deploy"):
1335 timeout_ns_deploy = ns_params["timeout_ns_deploy"]
1336 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001337 timeout_ns_deploy = self.timeout.get(
1338 "ns_deploy", self.timeout_ns_deploy
1339 )
quilesj7e13aeb2019-10-08 13:34:55 +02001340
tiernoe876f672020-02-13 14:34:48 +00001341 # Check for and optionally request placement optimization. Database will be updated if placement activated
1342 stage[2] = "Waiting for Placement."
tierno8790a3d2020-04-23 22:49:52 +00001343 if await self._do_placement(logging_text, db_nslcmop, db_vnfrs):
1344 # in case of placement change ns_params[vimAcountId) if not present at any vnfrs
1345 for vnfr in db_vnfrs.values():
1346 if ns_params["vimAccountId"] == vnfr["vim-account-id"]:
1347 break
1348 else:
1349 ns_params["vimAccountId"] == vnfr["vim-account-id"]
quilesj7e13aeb2019-10-08 13:34:55 +02001350
garciadeblas5697b8b2021-03-24 09:17:02 +01001351 return await self._instantiate_ng_ro(
1352 logging_text,
1353 nsr_id,
1354 nsd,
1355 db_nsr,
1356 db_nslcmop,
1357 db_vnfrs,
1358 db_vnfds,
1359 n2vc_key_list,
1360 stage,
1361 start_deploy,
1362 timeout_ns_deploy,
1363 )
tierno2357f4e2020-10-19 16:38:59 +00001364 except Exception as e:
tierno067e04a2020-03-31 12:53:13 +00001365 stage[2] = "ERROR deploying at VIM"
tiernoe876f672020-02-13 14:34:48 +00001366 self.set_vnfr_at_error(db_vnfrs, str(e))
garciadeblas5697b8b2021-03-24 09:17:02 +01001367 self.logger.error(
1368 "Error deploying at VIM {}".format(e),
1369 exc_info=not isinstance(
1370 e,
1371 (
1372 ROclient.ROClientException,
1373 LcmException,
1374 DbException,
1375 NgRoException,
1376 ),
1377 ),
1378 )
tiernoe876f672020-02-13 14:34:48 +00001379 raise
quilesj7e13aeb2019-10-08 13:34:55 +02001380
tierno7ecbc342020-09-21 14:05:39 +00001381 async def wait_kdu_up(self, logging_text, nsr_id, vnfr_id, kdu_name):
1382 """
1383 Wait for kdu to be up, get ip address
1384 :param logging_text: prefix use for logging
1385 :param nsr_id:
1386 :param vnfr_id:
1387 :param kdu_name:
1388 :return: IP address
1389 """
1390
1391 # self.logger.debug(logging_text + "Starting wait_kdu_up")
1392 nb_tries = 0
1393
1394 while nb_tries < 360:
1395 db_vnfr = self.db.get_one("vnfrs", {"_id": vnfr_id})
garciadeblas5697b8b2021-03-24 09:17:02 +01001396 kdur = next(
1397 (
1398 x
1399 for x in get_iterable(db_vnfr, "kdur")
1400 if x.get("kdu-name") == kdu_name
1401 ),
1402 None,
1403 )
tierno7ecbc342020-09-21 14:05:39 +00001404 if not kdur:
garciadeblas5697b8b2021-03-24 09:17:02 +01001405 raise LcmException(
1406 "Not found vnfr_id={}, kdu_name={}".format(vnfr_id, kdu_name)
1407 )
tierno7ecbc342020-09-21 14:05:39 +00001408 if kdur.get("status"):
1409 if kdur["status"] in ("READY", "ENABLED"):
1410 return kdur.get("ip-address")
1411 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001412 raise LcmException(
1413 "target KDU={} is in error state".format(kdu_name)
1414 )
tierno7ecbc342020-09-21 14:05:39 +00001415
1416 await asyncio.sleep(10, loop=self.loop)
1417 nb_tries += 1
1418 raise LcmException("Timeout waiting KDU={} instantiated".format(kdu_name))
1419
garciadeblas5697b8b2021-03-24 09:17:02 +01001420 async def wait_vm_up_insert_key_ro(
1421 self, logging_text, nsr_id, vnfr_id, vdu_id, vdu_index, pub_key=None, user=None
1422 ):
tiernoa5088192019-11-26 16:12:53 +00001423 """
1424 Wait for ip addres at RO, and optionally, insert public key in virtual machine
1425 :param logging_text: prefix use for logging
1426 :param nsr_id:
1427 :param vnfr_id:
1428 :param vdu_id:
1429 :param vdu_index:
1430 :param pub_key: public ssh key to inject, None to skip
1431 :param user: user to apply the public ssh key
1432 :return: IP address
1433 """
quilesj7e13aeb2019-10-08 13:34:55 +02001434
tierno2357f4e2020-10-19 16:38:59 +00001435 self.logger.debug(logging_text + "Starting wait_vm_up_insert_key_ro")
tiernod8323042019-08-09 11:32:23 +00001436 ro_nsr_id = None
1437 ip_address = None
1438 nb_tries = 0
1439 target_vdu_id = None
quilesj3149f262019-12-03 10:58:10 +00001440 ro_retries = 0
quilesj7e13aeb2019-10-08 13:34:55 +02001441
tiernod8323042019-08-09 11:32:23 +00001442 while True:
quilesj7e13aeb2019-10-08 13:34:55 +02001443
quilesj3149f262019-12-03 10:58:10 +00001444 ro_retries += 1
1445 if ro_retries >= 360: # 1 hour
garciadeblas5697b8b2021-03-24 09:17:02 +01001446 raise LcmException(
1447 "Not found _admin.deployed.RO.nsr_id for nsr_id: {}".format(nsr_id)
1448 )
quilesj3149f262019-12-03 10:58:10 +00001449
tiernod8323042019-08-09 11:32:23 +00001450 await asyncio.sleep(10, loop=self.loop)
quilesj7e13aeb2019-10-08 13:34:55 +02001451
1452 # get ip address
tiernod8323042019-08-09 11:32:23 +00001453 if not target_vdu_id:
1454 db_vnfr = self.db.get_one("vnfrs", {"_id": vnfr_id})
quilesj3149f262019-12-03 10:58:10 +00001455
1456 if not vdu_id: # for the VNF case
tiernoe876f672020-02-13 14:34:48 +00001457 if db_vnfr.get("status") == "ERROR":
garciadeblas5697b8b2021-03-24 09:17:02 +01001458 raise LcmException(
1459 "Cannot inject ssh-key because target VNF is in error state"
1460 )
tiernod8323042019-08-09 11:32:23 +00001461 ip_address = db_vnfr.get("ip-address")
1462 if not ip_address:
1463 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01001464 vdur = next(
1465 (
1466 x
1467 for x in get_iterable(db_vnfr, "vdur")
1468 if x.get("ip-address") == ip_address
1469 ),
1470 None,
1471 )
quilesj3149f262019-12-03 10:58:10 +00001472 else: # VDU case
garciadeblas5697b8b2021-03-24 09:17:02 +01001473 vdur = next(
1474 (
1475 x
1476 for x in get_iterable(db_vnfr, "vdur")
1477 if x.get("vdu-id-ref") == vdu_id
1478 and x.get("count-index") == vdu_index
1479 ),
1480 None,
1481 )
quilesj3149f262019-12-03 10:58:10 +00001482
garciadeblas5697b8b2021-03-24 09:17:02 +01001483 if (
1484 not vdur and len(db_vnfr.get("vdur", ())) == 1
1485 ): # If only one, this should be the target vdu
tierno0e8c3f02020-03-12 17:18:21 +00001486 vdur = db_vnfr["vdur"][0]
quilesj3149f262019-12-03 10:58:10 +00001487 if not vdur:
garciadeblas5697b8b2021-03-24 09:17:02 +01001488 raise LcmException(
1489 "Not found vnfr_id={}, vdu_id={}, vdu_index={}".format(
1490 vnfr_id, vdu_id, vdu_index
1491 )
1492 )
tierno2357f4e2020-10-19 16:38:59 +00001493 # New generation RO stores information at "vim_info"
1494 ng_ro_status = None
David Garciaa8bbe672020-11-19 13:06:54 +01001495 target_vim = None
tierno2357f4e2020-10-19 16:38:59 +00001496 if vdur.get("vim_info"):
garciadeblas5697b8b2021-03-24 09:17:02 +01001497 target_vim = next(
1498 t for t in vdur["vim_info"]
1499 ) # there should be only one key
tierno2357f4e2020-10-19 16:38:59 +00001500 ng_ro_status = vdur["vim_info"][target_vim].get("vim_status")
garciadeblas5697b8b2021-03-24 09:17:02 +01001501 if (
1502 vdur.get("pdu-type")
1503 or vdur.get("status") == "ACTIVE"
1504 or ng_ro_status == "ACTIVE"
1505 ):
quilesj3149f262019-12-03 10:58:10 +00001506 ip_address = vdur.get("ip-address")
1507 if not ip_address:
1508 continue
1509 target_vdu_id = vdur["vdu-id-ref"]
bravof922c4172020-11-24 21:21:43 -03001510 elif vdur.get("status") == "ERROR" or ng_ro_status == "ERROR":
garciadeblas5697b8b2021-03-24 09:17:02 +01001511 raise LcmException(
1512 "Cannot inject ssh-key because target VM is in error state"
1513 )
quilesj3149f262019-12-03 10:58:10 +00001514
tiernod8323042019-08-09 11:32:23 +00001515 if not target_vdu_id:
1516 continue
tiernod8323042019-08-09 11:32:23 +00001517
quilesj7e13aeb2019-10-08 13:34:55 +02001518 # inject public key into machine
1519 if pub_key and user:
tierno2357f4e2020-10-19 16:38:59 +00001520 self.logger.debug(logging_text + "Inserting RO key")
bravof922c4172020-11-24 21:21:43 -03001521 self.logger.debug("SSH > PubKey > {}".format(pub_key))
tierno0e8c3f02020-03-12 17:18:21 +00001522 if vdur.get("pdu-type"):
1523 self.logger.error(logging_text + "Cannot inject ssh-ky to a PDU")
1524 return ip_address
quilesj7e13aeb2019-10-08 13:34:55 +02001525 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01001526 ro_vm_id = "{}-{}".format(
1527 db_vnfr["member-vnf-index-ref"], target_vdu_id
1528 ) # TODO add vdu_index
tierno69f0d382020-05-07 13:08:09 +00001529 if self.ng_ro:
garciadeblas5697b8b2021-03-24 09:17:02 +01001530 target = {
1531 "action": {
1532 "action": "inject_ssh_key",
1533 "key": pub_key,
1534 "user": user,
1535 },
1536 "vnf": [{"_id": vnfr_id, "vdur": [{"id": vdur["id"]}]}],
1537 }
tierno2357f4e2020-10-19 16:38:59 +00001538 desc = await self.RO.deploy(nsr_id, target)
1539 action_id = desc["action_id"]
1540 await self._wait_ng_ro(nsr_id, action_id, timeout=600)
1541 break
tierno69f0d382020-05-07 13:08:09 +00001542 else:
tierno2357f4e2020-10-19 16:38:59 +00001543 # wait until NS is deployed at RO
1544 if not ro_nsr_id:
1545 db_nsrs = self.db.get_one("nsrs", {"_id": nsr_id})
garciadeblas5697b8b2021-03-24 09:17:02 +01001546 ro_nsr_id = deep_get(
1547 db_nsrs, ("_admin", "deployed", "RO", "nsr_id")
1548 )
tierno2357f4e2020-10-19 16:38:59 +00001549 if not ro_nsr_id:
1550 continue
tierno69f0d382020-05-07 13:08:09 +00001551 result_dict = await self.RO.create_action(
1552 item="ns",
1553 item_id_name=ro_nsr_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01001554 descriptor={
1555 "add_public_key": pub_key,
1556 "vms": [ro_vm_id],
1557 "user": user,
1558 },
tierno69f0d382020-05-07 13:08:09 +00001559 )
1560 # result_dict contains the format {VM-id: {vim_result: 200, description: text}}
1561 if not result_dict or not isinstance(result_dict, dict):
garciadeblas5697b8b2021-03-24 09:17:02 +01001562 raise LcmException(
1563 "Unknown response from RO when injecting key"
1564 )
tierno69f0d382020-05-07 13:08:09 +00001565 for result in result_dict.values():
1566 if result.get("vim_result") == 200:
1567 break
1568 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001569 raise ROclient.ROClientException(
1570 "error injecting key: {}".format(
1571 result.get("description")
1572 )
1573 )
tierno69f0d382020-05-07 13:08:09 +00001574 break
1575 except NgRoException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001576 raise LcmException(
1577 "Reaching max tries injecting key. Error: {}".format(e)
1578 )
quilesj7e13aeb2019-10-08 13:34:55 +02001579 except ROclient.ROClientException as e:
tiernoa5088192019-11-26 16:12:53 +00001580 if not nb_tries:
garciadeblas5697b8b2021-03-24 09:17:02 +01001581 self.logger.debug(
1582 logging_text
1583 + "error injecting key: {}. Retrying until {} seconds".format(
1584 e, 20 * 10
1585 )
1586 )
quilesj7e13aeb2019-10-08 13:34:55 +02001587 nb_tries += 1
tiernoa5088192019-11-26 16:12:53 +00001588 if nb_tries >= 20:
garciadeblas5697b8b2021-03-24 09:17:02 +01001589 raise LcmException(
1590 "Reaching max tries injecting key. Error: {}".format(e)
1591 )
quilesj7e13aeb2019-10-08 13:34:55 +02001592 else:
quilesj7e13aeb2019-10-08 13:34:55 +02001593 break
1594
1595 return ip_address
1596
tierno5ee02052019-12-05 19:55:02 +00001597 async def _wait_dependent_n2vc(self, nsr_id, vca_deployed_list, vca_index):
1598 """
1599 Wait until dependent VCA deployments have been finished. NS wait for VNFs and VDUs. VNFs for VDUs
1600 """
1601 my_vca = vca_deployed_list[vca_index]
1602 if my_vca.get("vdu_id") or my_vca.get("kdu_name"):
quilesj3655ae02019-12-12 16:08:35 +00001603 # vdu or kdu: no dependencies
tierno5ee02052019-12-05 19:55:02 +00001604 return
1605 timeout = 300
1606 while timeout >= 0:
quilesj3655ae02019-12-12 16:08:35 +00001607 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1608 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
1609 configuration_status_list = db_nsr["configurationStatus"]
1610 for index, vca_deployed in enumerate(configuration_status_list):
tierno5ee02052019-12-05 19:55:02 +00001611 if index == vca_index:
quilesj3655ae02019-12-12 16:08:35 +00001612 # myself
tierno5ee02052019-12-05 19:55:02 +00001613 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01001614 if not my_vca.get("member-vnf-index") or (
1615 vca_deployed.get("member-vnf-index")
1616 == my_vca.get("member-vnf-index")
1617 ):
quilesj3655ae02019-12-12 16:08:35 +00001618 internal_status = configuration_status_list[index].get("status")
garciadeblas5697b8b2021-03-24 09:17:02 +01001619 if internal_status == "READY":
quilesj3655ae02019-12-12 16:08:35 +00001620 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01001621 elif internal_status == "BROKEN":
1622 raise LcmException(
1623 "Configuration aborted because dependent charm/s has failed"
1624 )
quilesj3655ae02019-12-12 16:08:35 +00001625 else:
1626 break
tierno5ee02052019-12-05 19:55:02 +00001627 else:
quilesj3655ae02019-12-12 16:08:35 +00001628 # no dependencies, return
tierno5ee02052019-12-05 19:55:02 +00001629 return
1630 await asyncio.sleep(10)
1631 timeout -= 1
tierno5ee02052019-12-05 19:55:02 +00001632
1633 raise LcmException("Configuration aborted because dependent charm/s timeout")
1634
David Garciac1fe90a2021-03-31 19:12:02 +02001635 def get_vca_id(self, db_vnfr: dict, db_nsr: dict):
David Garcia0b2b1882021-10-21 17:03:48 +02001636 vca_id = None
1637 if db_vnfr:
1638 vca_id = deep_get(db_vnfr, ("vca-id",))
1639 elif db_nsr:
1640 vim_account_id = deep_get(db_nsr, ("instantiate_params", "vimAccountId"))
1641 vca_id = VimAccountDB.get_vim_account_with_id(vim_account_id).get("vca")
1642 return vca_id
David Garciac1fe90a2021-03-31 19:12:02 +02001643
garciadeblas5697b8b2021-03-24 09:17:02 +01001644 async def instantiate_N2VC(
1645 self,
1646 logging_text,
1647 vca_index,
1648 nsi_id,
1649 db_nsr,
1650 db_vnfr,
1651 vdu_id,
1652 kdu_name,
1653 vdu_index,
1654 config_descriptor,
1655 deploy_params,
1656 base_folder,
1657 nslcmop_id,
1658 stage,
1659 vca_type,
1660 vca_name,
1661 ee_config_descriptor,
1662 ):
tiernod8323042019-08-09 11:32:23 +00001663 nsr_id = db_nsr["_id"]
1664 db_update_entry = "_admin.deployed.VCA.{}.".format(vca_index)
tiernoda6fb102019-11-23 00:36:52 +00001665 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
tiernod8323042019-08-09 11:32:23 +00001666 vca_deployed = db_nsr["_admin"]["deployed"]["VCA"][vca_index]
tiernob996d942020-07-03 14:52:28 +00001667 osm_config = {"osm": {"ns_id": db_nsr["_id"]}}
quilesj7e13aeb2019-10-08 13:34:55 +02001668 db_dict = {
garciadeblas5697b8b2021-03-24 09:17:02 +01001669 "collection": "nsrs",
1670 "filter": {"_id": nsr_id},
1671 "path": db_update_entry,
quilesj7e13aeb2019-10-08 13:34:55 +02001672 }
tiernod8323042019-08-09 11:32:23 +00001673 step = ""
1674 try:
quilesj3655ae02019-12-12 16:08:35 +00001675
garciadeblas5697b8b2021-03-24 09:17:02 +01001676 element_type = "NS"
quilesj3655ae02019-12-12 16:08:35 +00001677 element_under_configuration = nsr_id
1678
tiernod8323042019-08-09 11:32:23 +00001679 vnfr_id = None
1680 if db_vnfr:
1681 vnfr_id = db_vnfr["_id"]
tiernob996d942020-07-03 14:52:28 +00001682 osm_config["osm"]["vnf_id"] = vnfr_id
tiernod8323042019-08-09 11:32:23 +00001683
garciadeblas5697b8b2021-03-24 09:17:02 +01001684 namespace = "{nsi}.{ns}".format(nsi=nsi_id if nsi_id else "", ns=nsr_id)
quilesj3655ae02019-12-12 16:08:35 +00001685
aktas730569b2021-07-29 17:42:49 +03001686 if vca_type == "native_charm":
1687 index_number = 0
1688 else:
1689 index_number = vdu_index or 0
1690
tiernod8323042019-08-09 11:32:23 +00001691 if vnfr_id:
garciadeblas5697b8b2021-03-24 09:17:02 +01001692 element_type = "VNF"
quilesj3655ae02019-12-12 16:08:35 +00001693 element_under_configuration = vnfr_id
aktas730569b2021-07-29 17:42:49 +03001694 namespace += ".{}-{}".format(vnfr_id, index_number)
tiernod8323042019-08-09 11:32:23 +00001695 if vdu_id:
aktas730569b2021-07-29 17:42:49 +03001696 namespace += ".{}-{}".format(vdu_id, index_number)
garciadeblas5697b8b2021-03-24 09:17:02 +01001697 element_type = "VDU"
aktas730569b2021-07-29 17:42:49 +03001698 element_under_configuration = "{}-{}".format(vdu_id, index_number)
tiernob996d942020-07-03 14:52:28 +00001699 osm_config["osm"]["vdu_id"] = vdu_id
tierno51183952020-04-03 15:48:18 +00001700 elif kdu_name:
aktas730569b2021-07-29 17:42:49 +03001701 namespace += ".{}".format(kdu_name)
garciadeblas5697b8b2021-03-24 09:17:02 +01001702 element_type = "KDU"
tierno51183952020-04-03 15:48:18 +00001703 element_under_configuration = kdu_name
tiernob996d942020-07-03 14:52:28 +00001704 osm_config["osm"]["kdu_name"] = kdu_name
tiernod8323042019-08-09 11:32:23 +00001705
1706 # Get artifact path
tierno588547c2020-07-01 15:30:20 +00001707 artifact_path = "{}/{}/{}/{}".format(
tiernod8323042019-08-09 11:32:23 +00001708 base_folder["folder"],
1709 base_folder["pkg-dir"],
garciadeblas5697b8b2021-03-24 09:17:02 +01001710 "charms"
1711 if vca_type in ("native_charm", "lxc_proxy_charm", "k8s_proxy_charm")
1712 else "helm-charts",
1713 vca_name,
tiernod8323042019-08-09 11:32:23 +00001714 )
bravof922c4172020-11-24 21:21:43 -03001715
1716 self.logger.debug("Artifact path > {}".format(artifact_path))
1717
tiernoa278b842020-07-08 15:33:55 +00001718 # get initial_config_primitive_list that applies to this element
garciadeblas5697b8b2021-03-24 09:17:02 +01001719 initial_config_primitive_list = config_descriptor.get(
1720 "initial-config-primitive"
1721 )
tiernoa278b842020-07-08 15:33:55 +00001722
garciadeblas5697b8b2021-03-24 09:17:02 +01001723 self.logger.debug(
1724 "Initial config primitive list > {}".format(
1725 initial_config_primitive_list
1726 )
1727 )
bravof922c4172020-11-24 21:21:43 -03001728
tiernoa278b842020-07-08 15:33:55 +00001729 # add config if not present for NS charm
1730 ee_descriptor_id = ee_config_descriptor.get("id")
bravof922c4172020-11-24 21:21:43 -03001731 self.logger.debug("EE Descriptor > {}".format(ee_descriptor_id))
garciadeblas5697b8b2021-03-24 09:17:02 +01001732 initial_config_primitive_list = get_ee_sorted_initial_config_primitive_list(
1733 initial_config_primitive_list, vca_deployed, ee_descriptor_id
1734 )
tiernod8323042019-08-09 11:32:23 +00001735
garciadeblas5697b8b2021-03-24 09:17:02 +01001736 self.logger.debug(
1737 "Initial config primitive list #2 > {}".format(
1738 initial_config_primitive_list
1739 )
1740 )
tierno588547c2020-07-01 15:30:20 +00001741 # n2vc_redesign STEP 3.1
tierno588547c2020-07-01 15:30:20 +00001742 # find old ee_id if exists
1743 ee_id = vca_deployed.get("ee_id")
tiernod8323042019-08-09 11:32:23 +00001744
David Garciac1fe90a2021-03-31 19:12:02 +02001745 vca_id = self.get_vca_id(db_vnfr, db_nsr)
tierno588547c2020-07-01 15:30:20 +00001746 # create or register execution environment in VCA
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001747 if vca_type in ("lxc_proxy_charm", "k8s_proxy_charm", "helm", "helm-v3"):
quilesj7e13aeb2019-10-08 13:34:55 +02001748
tierno588547c2020-07-01 15:30:20 +00001749 self._write_configuration_status(
1750 nsr_id=nsr_id,
1751 vca_index=vca_index,
garciadeblas5697b8b2021-03-24 09:17:02 +01001752 status="CREATING",
tierno588547c2020-07-01 15:30:20 +00001753 element_under_configuration=element_under_configuration,
garciadeblas5697b8b2021-03-24 09:17:02 +01001754 element_type=element_type,
tierno588547c2020-07-01 15:30:20 +00001755 )
tiernod8323042019-08-09 11:32:23 +00001756
tierno588547c2020-07-01 15:30:20 +00001757 step = "create execution environment"
garciadeblas5697b8b2021-03-24 09:17:02 +01001758 self.logger.debug(logging_text + step)
David Garciaaae391f2020-11-09 11:12:54 +01001759
1760 ee_id = None
1761 credentials = None
1762 if vca_type == "k8s_proxy_charm":
1763 ee_id = await self.vca_map[vca_type].install_k8s_proxy_charm(
garciadeblas5697b8b2021-03-24 09:17:02 +01001764 charm_name=artifact_path[artifact_path.rfind("/") + 1 :],
David Garciaaae391f2020-11-09 11:12:54 +01001765 namespace=namespace,
1766 artifact_path=artifact_path,
1767 db_dict=db_dict,
David Garciac1fe90a2021-03-31 19:12:02 +02001768 vca_id=vca_id,
David Garciaaae391f2020-11-09 11:12:54 +01001769 )
garciadeblas5697b8b2021-03-24 09:17:02 +01001770 elif vca_type == "helm" or vca_type == "helm-v3":
1771 ee_id, credentials = await self.vca_map[
1772 vca_type
1773 ].create_execution_environment(
bravof922c4172020-11-24 21:21:43 -03001774 namespace=namespace,
1775 reuse_ee_id=ee_id,
1776 db_dict=db_dict,
lloretgalleg18cb3cb2020-12-10 14:21:10 +00001777 config=osm_config,
1778 artifact_path=artifact_path,
garciadeblas5697b8b2021-03-24 09:17:02 +01001779 vca_type=vca_type,
bravof922c4172020-11-24 21:21:43 -03001780 )
garciadeblas5697b8b2021-03-24 09:17:02 +01001781 else:
1782 ee_id, credentials = await self.vca_map[
1783 vca_type
1784 ].create_execution_environment(
David Garciaaae391f2020-11-09 11:12:54 +01001785 namespace=namespace,
1786 reuse_ee_id=ee_id,
1787 db_dict=db_dict,
David Garciac1fe90a2021-03-31 19:12:02 +02001788 vca_id=vca_id,
David Garciaaae391f2020-11-09 11:12:54 +01001789 )
quilesj3655ae02019-12-12 16:08:35 +00001790
tierno588547c2020-07-01 15:30:20 +00001791 elif vca_type == "native_charm":
1792 step = "Waiting to VM being up and getting IP address"
1793 self.logger.debug(logging_text + step)
garciadeblas5697b8b2021-03-24 09:17:02 +01001794 rw_mgmt_ip = await self.wait_vm_up_insert_key_ro(
1795 logging_text,
1796 nsr_id,
1797 vnfr_id,
1798 vdu_id,
1799 vdu_index,
1800 user=None,
1801 pub_key=None,
1802 )
tierno588547c2020-07-01 15:30:20 +00001803 credentials = {"hostname": rw_mgmt_ip}
1804 # get username
garciadeblas5697b8b2021-03-24 09:17:02 +01001805 username = deep_get(
1806 config_descriptor, ("config-access", "ssh-access", "default-user")
1807 )
tierno588547c2020-07-01 15:30:20 +00001808 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1809 # merged. Meanwhile let's get username from initial-config-primitive
tiernoa278b842020-07-08 15:33:55 +00001810 if not username and initial_config_primitive_list:
1811 for config_primitive in initial_config_primitive_list:
tierno588547c2020-07-01 15:30:20 +00001812 for param in config_primitive.get("parameter", ()):
1813 if param["name"] == "ssh-username":
1814 username = param["value"]
1815 break
1816 if not username:
garciadeblas5697b8b2021-03-24 09:17:02 +01001817 raise LcmException(
1818 "Cannot determine the username neither with 'initial-config-primitive' nor with "
1819 "'config-access.ssh-access.default-user'"
1820 )
tierno588547c2020-07-01 15:30:20 +00001821 credentials["username"] = username
1822 # n2vc_redesign STEP 3.2
quilesj3655ae02019-12-12 16:08:35 +00001823
tierno588547c2020-07-01 15:30:20 +00001824 self._write_configuration_status(
1825 nsr_id=nsr_id,
1826 vca_index=vca_index,
garciadeblas5697b8b2021-03-24 09:17:02 +01001827 status="REGISTERING",
tierno588547c2020-07-01 15:30:20 +00001828 element_under_configuration=element_under_configuration,
garciadeblas5697b8b2021-03-24 09:17:02 +01001829 element_type=element_type,
tierno588547c2020-07-01 15:30:20 +00001830 )
quilesj3655ae02019-12-12 16:08:35 +00001831
tierno588547c2020-07-01 15:30:20 +00001832 step = "register execution environment {}".format(credentials)
1833 self.logger.debug(logging_text + step)
1834 ee_id = await self.vca_map[vca_type].register_execution_environment(
David Garciaaae391f2020-11-09 11:12:54 +01001835 credentials=credentials,
1836 namespace=namespace,
1837 db_dict=db_dict,
David Garciac1fe90a2021-03-31 19:12:02 +02001838 vca_id=vca_id,
David Garciaaae391f2020-11-09 11:12:54 +01001839 )
tierno3bedc9b2019-11-27 15:46:57 +00001840
tierno588547c2020-07-01 15:30:20 +00001841 # for compatibility with MON/POL modules, the need model and application name at database
1842 # TODO ask MON/POL if needed to not assuming anymore the format "model_name.application_name"
garciadeblas5697b8b2021-03-24 09:17:02 +01001843 ee_id_parts = ee_id.split(".")
tierno588547c2020-07-01 15:30:20 +00001844 db_nsr_update = {db_update_entry + "ee_id": ee_id}
1845 if len(ee_id_parts) >= 2:
1846 model_name = ee_id_parts[0]
1847 application_name = ee_id_parts[1]
1848 db_nsr_update[db_update_entry + "model"] = model_name
1849 db_nsr_update[db_update_entry + "application"] = application_name
tiernod8323042019-08-09 11:32:23 +00001850
1851 # n2vc_redesign STEP 3.3
tiernod8323042019-08-09 11:32:23 +00001852 step = "Install configuration Software"
quilesj3655ae02019-12-12 16:08:35 +00001853
tiernoc231a872020-01-21 08:49:05 +00001854 self._write_configuration_status(
quilesj3655ae02019-12-12 16:08:35 +00001855 nsr_id=nsr_id,
1856 vca_index=vca_index,
garciadeblas5697b8b2021-03-24 09:17:02 +01001857 status="INSTALLING SW",
quilesj3655ae02019-12-12 16:08:35 +00001858 element_under_configuration=element_under_configuration,
tierno51183952020-04-03 15:48:18 +00001859 element_type=element_type,
garciadeblas5697b8b2021-03-24 09:17:02 +01001860 other_update=db_nsr_update,
quilesj3655ae02019-12-12 16:08:35 +00001861 )
1862
tierno3bedc9b2019-11-27 15:46:57 +00001863 # TODO check if already done
quilesj7e13aeb2019-10-08 13:34:55 +02001864 self.logger.debug(logging_text + step)
David Garcia18a63322020-04-01 16:14:59 +02001865 config = None
tierno588547c2020-07-01 15:30:20 +00001866 if vca_type == "native_charm":
garciadeblas5697b8b2021-03-24 09:17:02 +01001867 config_primitive = next(
1868 (p for p in initial_config_primitive_list if p["name"] == "config"),
1869 None,
1870 )
tiernoa278b842020-07-08 15:33:55 +00001871 if config_primitive:
1872 config = self._map_primitive_params(
garciadeblas5697b8b2021-03-24 09:17:02 +01001873 config_primitive, {}, deploy_params
tiernoa278b842020-07-08 15:33:55 +00001874 )
tierno588547c2020-07-01 15:30:20 +00001875 num_units = 1
1876 if vca_type == "lxc_proxy_charm":
1877 if element_type == "NS":
1878 num_units = db_nsr.get("config-units") or 1
1879 elif element_type == "VNF":
1880 num_units = db_vnfr.get("config-units") or 1
1881 elif element_type == "VDU":
1882 for v in db_vnfr["vdur"]:
1883 if vdu_id == v["vdu-id-ref"]:
1884 num_units = v.get("config-units") or 1
1885 break
David Garciaaae391f2020-11-09 11:12:54 +01001886 if vca_type != "k8s_proxy_charm":
1887 await self.vca_map[vca_type].install_configuration_sw(
1888 ee_id=ee_id,
1889 artifact_path=artifact_path,
1890 db_dict=db_dict,
1891 config=config,
1892 num_units=num_units,
David Garciac1fe90a2021-03-31 19:12:02 +02001893 vca_id=vca_id,
aktas730569b2021-07-29 17:42:49 +03001894 vca_type=vca_type,
David Garciaaae391f2020-11-09 11:12:54 +01001895 )
quilesj7e13aeb2019-10-08 13:34:55 +02001896
quilesj63f90042020-01-17 09:53:55 +00001897 # write in db flag of configuration_sw already installed
garciadeblas5697b8b2021-03-24 09:17:02 +01001898 self.update_db_2(
1899 "nsrs", nsr_id, {db_update_entry + "config_sw_installed": True}
1900 )
quilesj63f90042020-01-17 09:53:55 +00001901
1902 # add relations for this VCA (wait for other peers related with this VCA)
garciadeblas5697b8b2021-03-24 09:17:02 +01001903 await self._add_vca_relations(
1904 logging_text=logging_text,
1905 nsr_id=nsr_id,
1906 vca_index=vca_index,
1907 vca_id=vca_id,
1908 vca_type=vca_type,
1909 )
quilesj63f90042020-01-17 09:53:55 +00001910
quilesj7e13aeb2019-10-08 13:34:55 +02001911 # if SSH access is required, then get execution environment SSH public
David Garciaa27e20a2020-07-10 13:12:44 +02001912 # if native charm we have waited already to VM be UP
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001913 if vca_type in ("k8s_proxy_charm", "lxc_proxy_charm", "helm", "helm-v3"):
tierno3bedc9b2019-11-27 15:46:57 +00001914 pub_key = None
1915 user = None
tierno588547c2020-07-01 15:30:20 +00001916 # self.logger.debug("get ssh key block")
garciadeblas5697b8b2021-03-24 09:17:02 +01001917 if deep_get(
1918 config_descriptor, ("config-access", "ssh-access", "required")
1919 ):
tierno588547c2020-07-01 15:30:20 +00001920 # self.logger.debug("ssh key needed")
tierno3bedc9b2019-11-27 15:46:57 +00001921 # Needed to inject a ssh key
garciadeblas5697b8b2021-03-24 09:17:02 +01001922 user = deep_get(
1923 config_descriptor,
1924 ("config-access", "ssh-access", "default-user"),
1925 )
tierno3bedc9b2019-11-27 15:46:57 +00001926 step = "Install configuration Software, getting public ssh key"
David Garciac1fe90a2021-03-31 19:12:02 +02001927 pub_key = await self.vca_map[vca_type].get_ee_ssh_public__key(
garciadeblas5697b8b2021-03-24 09:17:02 +01001928 ee_id=ee_id, db_dict=db_dict, vca_id=vca_id
David Garciac1fe90a2021-03-31 19:12:02 +02001929 )
quilesj7e13aeb2019-10-08 13:34:55 +02001930
garciadeblas5697b8b2021-03-24 09:17:02 +01001931 step = "Insert public key into VM user={} ssh_key={}".format(
1932 user, pub_key
1933 )
tierno3bedc9b2019-11-27 15:46:57 +00001934 else:
tierno588547c2020-07-01 15:30:20 +00001935 # self.logger.debug("no need to get ssh key")
tierno3bedc9b2019-11-27 15:46:57 +00001936 step = "Waiting to VM being up and getting IP address"
1937 self.logger.debug(logging_text + step)
quilesj7e13aeb2019-10-08 13:34:55 +02001938
Pedro Escaleira042edbf2022-05-30 15:37:01 +01001939 # default rw_mgmt_ip to None, avoiding the non definition of the variable
1940 rw_mgmt_ip = None
1941
tierno3bedc9b2019-11-27 15:46:57 +00001942 # n2vc_redesign STEP 5.1
1943 # wait for RO (ip-address) Insert pub_key into VM
tierno5ee02052019-12-05 19:55:02 +00001944 if vnfr_id:
tierno7ecbc342020-09-21 14:05:39 +00001945 if kdu_name:
garciadeblas5697b8b2021-03-24 09:17:02 +01001946 rw_mgmt_ip = await self.wait_kdu_up(
1947 logging_text, nsr_id, vnfr_id, kdu_name
1948 )
Pedro Escaleira042edbf2022-05-30 15:37:01 +01001949
1950 # This verification is needed in order to avoid trying to add a public key
1951 # to a VM, when the VNF is a KNF (in the edge case where the user creates a VCA
1952 # for a KNF and not for its KDUs, the previous verification gives False, and the code
1953 # jumps to this block, meaning that there is the need to verify if the VNF is actually a VNF
1954 # or it is a KNF)
1955 elif db_vnfr.get('vdur'):
garciadeblas5697b8b2021-03-24 09:17:02 +01001956 rw_mgmt_ip = await self.wait_vm_up_insert_key_ro(
1957 logging_text,
1958 nsr_id,
1959 vnfr_id,
1960 vdu_id,
1961 vdu_index,
1962 user=user,
1963 pub_key=pub_key,
1964 )
tierno3bedc9b2019-11-27 15:46:57 +00001965
garciadeblas5697b8b2021-03-24 09:17:02 +01001966 self.logger.debug(logging_text + " VM_ip_address={}".format(rw_mgmt_ip))
quilesj7e13aeb2019-10-08 13:34:55 +02001967
tiernoa5088192019-11-26 16:12:53 +00001968 # store rw_mgmt_ip in deploy params for later replacement
quilesj7e13aeb2019-10-08 13:34:55 +02001969 deploy_params["rw_mgmt_ip"] = rw_mgmt_ip
tiernod8323042019-08-09 11:32:23 +00001970
1971 # n2vc_redesign STEP 6 Execute initial config primitive
garciadeblas5697b8b2021-03-24 09:17:02 +01001972 step = "execute initial config primitive"
quilesj3655ae02019-12-12 16:08:35 +00001973
1974 # wait for dependent primitives execution (NS -> VNF -> VDU)
tierno5ee02052019-12-05 19:55:02 +00001975 if initial_config_primitive_list:
1976 await self._wait_dependent_n2vc(nsr_id, vca_deployed_list, vca_index)
quilesj3655ae02019-12-12 16:08:35 +00001977
1978 # stage, in function of element type: vdu, kdu, vnf or ns
1979 my_vca = vca_deployed_list[vca_index]
1980 if my_vca.get("vdu_id") or my_vca.get("kdu_name"):
1981 # VDU or KDU
garciadeblas5697b8b2021-03-24 09:17:02 +01001982 stage[0] = "Stage 3/5: running Day-1 primitives for VDU."
quilesj3655ae02019-12-12 16:08:35 +00001983 elif my_vca.get("member-vnf-index"):
1984 # VNF
garciadeblas5697b8b2021-03-24 09:17:02 +01001985 stage[0] = "Stage 4/5: running Day-1 primitives for VNF."
quilesj3655ae02019-12-12 16:08:35 +00001986 else:
1987 # NS
garciadeblas5697b8b2021-03-24 09:17:02 +01001988 stage[0] = "Stage 5/5: running Day-1 primitives for NS."
quilesj3655ae02019-12-12 16:08:35 +00001989
tiernoc231a872020-01-21 08:49:05 +00001990 self._write_configuration_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01001991 nsr_id=nsr_id, vca_index=vca_index, status="EXECUTING PRIMITIVE"
quilesj3655ae02019-12-12 16:08:35 +00001992 )
1993
garciadeblas5697b8b2021-03-24 09:17:02 +01001994 self._write_op_status(op_id=nslcmop_id, stage=stage)
quilesj3655ae02019-12-12 16:08:35 +00001995
tiernoe876f672020-02-13 14:34:48 +00001996 check_if_terminated_needed = True
tiernod8323042019-08-09 11:32:23 +00001997 for initial_config_primitive in initial_config_primitive_list:
tiernoda6fb102019-11-23 00:36:52 +00001998 # adding information on the vca_deployed if it is a NS execution environment
1999 if not vca_deployed["member-vnf-index"]:
garciadeblas5697b8b2021-03-24 09:17:02 +01002000 deploy_params["ns_config_info"] = json.dumps(
2001 self._get_ns_config_info(nsr_id)
2002 )
tiernod8323042019-08-09 11:32:23 +00002003 # TODO check if already done
garciadeblas5697b8b2021-03-24 09:17:02 +01002004 primitive_params_ = self._map_primitive_params(
2005 initial_config_primitive, {}, deploy_params
2006 )
tierno3bedc9b2019-11-27 15:46:57 +00002007
garciadeblas5697b8b2021-03-24 09:17:02 +01002008 step = "execute primitive '{}' params '{}'".format(
2009 initial_config_primitive["name"], primitive_params_
2010 )
tiernod8323042019-08-09 11:32:23 +00002011 self.logger.debug(logging_text + step)
tierno588547c2020-07-01 15:30:20 +00002012 await self.vca_map[vca_type].exec_primitive(
quilesj7e13aeb2019-10-08 13:34:55 +02002013 ee_id=ee_id,
2014 primitive_name=initial_config_primitive["name"],
2015 params_dict=primitive_params_,
David Garciac1fe90a2021-03-31 19:12:02 +02002016 db_dict=db_dict,
2017 vca_id=vca_id,
aktas730569b2021-07-29 17:42:49 +03002018 vca_type=vca_type,
quilesj7e13aeb2019-10-08 13:34:55 +02002019 )
tiernoe876f672020-02-13 14:34:48 +00002020 # Once some primitive has been exec, check and write at db if it needs to exec terminated primitives
2021 if check_if_terminated_needed:
garciadeblas5697b8b2021-03-24 09:17:02 +01002022 if config_descriptor.get("terminate-config-primitive"):
2023 self.update_db_2(
2024 "nsrs", nsr_id, {db_update_entry + "needed_terminate": True}
2025 )
tiernoe876f672020-02-13 14:34:48 +00002026 check_if_terminated_needed = False
quilesj3655ae02019-12-12 16:08:35 +00002027
tiernod8323042019-08-09 11:32:23 +00002028 # TODO register in database that primitive is done
quilesj7e13aeb2019-10-08 13:34:55 +02002029
tiernob996d942020-07-03 14:52:28 +00002030 # STEP 7 Configure metrics
lloretgalleg18ebc3a2020-10-22 09:54:51 +00002031 if vca_type == "helm" or vca_type == "helm-v3":
tiernob996d942020-07-03 14:52:28 +00002032 prometheus_jobs = await self.add_prometheus_metrics(
2033 ee_id=ee_id,
2034 artifact_path=artifact_path,
2035 ee_config_descriptor=ee_config_descriptor,
2036 vnfr_id=vnfr_id,
2037 nsr_id=nsr_id,
2038 target_ip=rw_mgmt_ip,
2039 )
2040 if prometheus_jobs:
garciadeblas5697b8b2021-03-24 09:17:02 +01002041 self.update_db_2(
2042 "nsrs",
2043 nsr_id,
2044 {db_update_entry + "prometheus_jobs": prometheus_jobs},
2045 )
tiernob996d942020-07-03 14:52:28 +00002046
quilesj7e13aeb2019-10-08 13:34:55 +02002047 step = "instantiated at VCA"
2048 self.logger.debug(logging_text + step)
2049
tiernoc231a872020-01-21 08:49:05 +00002050 self._write_configuration_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01002051 nsr_id=nsr_id, vca_index=vca_index, status="READY"
quilesj3655ae02019-12-12 16:08:35 +00002052 )
2053
tiernod8323042019-08-09 11:32:23 +00002054 except Exception as e: # TODO not use Exception but N2VC exception
quilesj3655ae02019-12-12 16:08:35 +00002055 # self.update_db_2("nsrs", nsr_id, {db_update_entry + "instantiation": "FAILED"})
garciadeblas5697b8b2021-03-24 09:17:02 +01002056 if not isinstance(
2057 e, (DbException, N2VCException, LcmException, asyncio.CancelledError)
2058 ):
2059 self.logger.error(
2060 "Exception while {} : {}".format(step, e), exc_info=True
2061 )
tiernoc231a872020-01-21 08:49:05 +00002062 self._write_configuration_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01002063 nsr_id=nsr_id, vca_index=vca_index, status="BROKEN"
quilesj3655ae02019-12-12 16:08:35 +00002064 )
tiernoe876f672020-02-13 14:34:48 +00002065 raise LcmException("{} {}".format(step, e)) from e
tiernod8323042019-08-09 11:32:23 +00002066
garciadeblas5697b8b2021-03-24 09:17:02 +01002067 def _write_ns_status(
2068 self,
2069 nsr_id: str,
2070 ns_state: str,
2071 current_operation: str,
2072 current_operation_id: str,
2073 error_description: str = None,
2074 error_detail: str = None,
2075 other_update: dict = None,
2076 ):
tiernoe876f672020-02-13 14:34:48 +00002077 """
2078 Update db_nsr fields.
2079 :param nsr_id:
2080 :param ns_state:
2081 :param current_operation:
2082 :param current_operation_id:
2083 :param error_description:
tiernoa2143262020-03-27 16:20:40 +00002084 :param error_detail:
tiernoe876f672020-02-13 14:34:48 +00002085 :param other_update: Other required changes at database if provided, will be cleared
2086 :return:
2087 """
quilesj4cda56b2019-12-05 10:02:20 +00002088 try:
tiernoe876f672020-02-13 14:34:48 +00002089 db_dict = other_update or {}
garciadeblas5697b8b2021-03-24 09:17:02 +01002090 db_dict[
2091 "_admin.nslcmop"
2092 ] = current_operation_id # for backward compatibility
tiernoe876f672020-02-13 14:34:48 +00002093 db_dict["_admin.current-operation"] = current_operation_id
garciadeblas5697b8b2021-03-24 09:17:02 +01002094 db_dict["_admin.operation-type"] = (
2095 current_operation if current_operation != "IDLE" else None
2096 )
quilesj4cda56b2019-12-05 10:02:20 +00002097 db_dict["currentOperation"] = current_operation
2098 db_dict["currentOperationID"] = current_operation_id
2099 db_dict["errorDescription"] = error_description
tiernoa2143262020-03-27 16:20:40 +00002100 db_dict["errorDetail"] = error_detail
tiernoe876f672020-02-13 14:34:48 +00002101
2102 if ns_state:
2103 db_dict["nsState"] = ns_state
quilesj4cda56b2019-12-05 10:02:20 +00002104 self.update_db_2("nsrs", nsr_id, db_dict)
tiernoe876f672020-02-13 14:34:48 +00002105 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002106 self.logger.warn("Error writing NS status, ns={}: {}".format(nsr_id, e))
quilesj3655ae02019-12-12 16:08:35 +00002107
garciadeblas5697b8b2021-03-24 09:17:02 +01002108 def _write_op_status(
2109 self,
2110 op_id: str,
2111 stage: list = None,
2112 error_message: str = None,
2113 queuePosition: int = 0,
2114 operation_state: str = None,
2115 other_update: dict = None,
2116 ):
quilesj3655ae02019-12-12 16:08:35 +00002117 try:
tiernoe876f672020-02-13 14:34:48 +00002118 db_dict = other_update or {}
garciadeblas5697b8b2021-03-24 09:17:02 +01002119 db_dict["queuePosition"] = queuePosition
tiernoe876f672020-02-13 14:34:48 +00002120 if isinstance(stage, list):
garciadeblas5697b8b2021-03-24 09:17:02 +01002121 db_dict["stage"] = stage[0]
2122 db_dict["detailed-status"] = " ".join(stage)
tiernoe876f672020-02-13 14:34:48 +00002123 elif stage is not None:
garciadeblas5697b8b2021-03-24 09:17:02 +01002124 db_dict["stage"] = str(stage)
tiernoe876f672020-02-13 14:34:48 +00002125
2126 if error_message is not None:
garciadeblas5697b8b2021-03-24 09:17:02 +01002127 db_dict["errorMessage"] = error_message
tiernoe876f672020-02-13 14:34:48 +00002128 if operation_state is not None:
garciadeblas5697b8b2021-03-24 09:17:02 +01002129 db_dict["operationState"] = operation_state
tiernoe876f672020-02-13 14:34:48 +00002130 db_dict["statusEnteredTime"] = time()
quilesj3655ae02019-12-12 16:08:35 +00002131 self.update_db_2("nslcmops", op_id, db_dict)
tiernoe876f672020-02-13 14:34:48 +00002132 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002133 self.logger.warn(
2134 "Error writing OPERATION status for op_id: {} -> {}".format(op_id, e)
2135 )
quilesj3655ae02019-12-12 16:08:35 +00002136
tierno51183952020-04-03 15:48:18 +00002137 def _write_all_config_status(self, db_nsr: dict, status: str):
quilesj3655ae02019-12-12 16:08:35 +00002138 try:
tierno51183952020-04-03 15:48:18 +00002139 nsr_id = db_nsr["_id"]
quilesj3655ae02019-12-12 16:08:35 +00002140 # configurationStatus
garciadeblas5697b8b2021-03-24 09:17:02 +01002141 config_status = db_nsr.get("configurationStatus")
quilesj3655ae02019-12-12 16:08:35 +00002142 if config_status:
garciadeblas5697b8b2021-03-24 09:17:02 +01002143 db_nsr_update = {
2144 "configurationStatus.{}.status".format(index): status
2145 for index, v in enumerate(config_status)
2146 if v
2147 }
quilesj3655ae02019-12-12 16:08:35 +00002148 # update status
tierno51183952020-04-03 15:48:18 +00002149 self.update_db_2("nsrs", nsr_id, db_nsr_update)
quilesj3655ae02019-12-12 16:08:35 +00002150
tiernoe876f672020-02-13 14:34:48 +00002151 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002152 self.logger.warn(
2153 "Error writing all configuration status, ns={}: {}".format(nsr_id, e)
2154 )
quilesj3655ae02019-12-12 16:08:35 +00002155
garciadeblas5697b8b2021-03-24 09:17:02 +01002156 def _write_configuration_status(
2157 self,
2158 nsr_id: str,
2159 vca_index: int,
2160 status: str = None,
2161 element_under_configuration: str = None,
2162 element_type: str = None,
2163 other_update: dict = None,
2164 ):
quilesj3655ae02019-12-12 16:08:35 +00002165
2166 # self.logger.debug('_write_configuration_status(): vca_index={}, status={}'
2167 # .format(vca_index, status))
2168
2169 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01002170 db_path = "configurationStatus.{}.".format(vca_index)
tierno51183952020-04-03 15:48:18 +00002171 db_dict = other_update or {}
quilesj63f90042020-01-17 09:53:55 +00002172 if status:
garciadeblas5697b8b2021-03-24 09:17:02 +01002173 db_dict[db_path + "status"] = status
quilesj3655ae02019-12-12 16:08:35 +00002174 if element_under_configuration:
garciadeblas5697b8b2021-03-24 09:17:02 +01002175 db_dict[
2176 db_path + "elementUnderConfiguration"
2177 ] = element_under_configuration
quilesj3655ae02019-12-12 16:08:35 +00002178 if element_type:
garciadeblas5697b8b2021-03-24 09:17:02 +01002179 db_dict[db_path + "elementType"] = element_type
quilesj3655ae02019-12-12 16:08:35 +00002180 self.update_db_2("nsrs", nsr_id, db_dict)
tiernoe876f672020-02-13 14:34:48 +00002181 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002182 self.logger.warn(
2183 "Error writing configuration status={}, ns={}, vca_index={}: {}".format(
2184 status, nsr_id, vca_index, e
2185 )
2186 )
quilesj4cda56b2019-12-05 10:02:20 +00002187
tierno38089af2020-04-16 07:56:58 +00002188 async def _do_placement(self, logging_text, db_nslcmop, db_vnfrs):
2189 """
2190 Check and computes the placement, (vim account where to deploy). If it is decided by an external tool, it
2191 sends the request via kafka and wait until the result is wrote at database (nslcmops _admin.plca).
2192 Database is used because the result can be obtained from a different LCM worker in case of HA.
2193 :param logging_text: contains the prefix for logging, with the ns and nslcmop identifiers
2194 :param db_nslcmop: database content of nslcmop
2195 :param db_vnfrs: database content of vnfrs, indexed by member-vnf-index.
tierno8790a3d2020-04-23 22:49:52 +00002196 :return: True if some modification is done. Modifies database vnfrs and parameter db_vnfr with the
2197 computed 'vim-account-id'
tierno38089af2020-04-16 07:56:58 +00002198 """
tierno8790a3d2020-04-23 22:49:52 +00002199 modified = False
garciadeblas5697b8b2021-03-24 09:17:02 +01002200 nslcmop_id = db_nslcmop["_id"]
2201 placement_engine = deep_get(db_nslcmop, ("operationParams", "placement-engine"))
magnussonle9198bb2020-01-21 13:00:51 +01002202 if placement_engine == "PLA":
garciadeblas5697b8b2021-03-24 09:17:02 +01002203 self.logger.debug(
2204 logging_text + "Invoke and wait for placement optimization"
2205 )
2206 await self.msg.aiowrite(
2207 "pla", "get_placement", {"nslcmopId": nslcmop_id}, loop=self.loop
2208 )
magnussonle9198bb2020-01-21 13:00:51 +01002209 db_poll_interval = 5
tierno38089af2020-04-16 07:56:58 +00002210 wait = db_poll_interval * 10
magnussonle9198bb2020-01-21 13:00:51 +01002211 pla_result = None
2212 while not pla_result and wait >= 0:
2213 await asyncio.sleep(db_poll_interval)
2214 wait -= db_poll_interval
tierno38089af2020-04-16 07:56:58 +00002215 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
garciadeblas5697b8b2021-03-24 09:17:02 +01002216 pla_result = deep_get(db_nslcmop, ("_admin", "pla"))
magnussonle9198bb2020-01-21 13:00:51 +01002217
2218 if not pla_result:
garciadeblas5697b8b2021-03-24 09:17:02 +01002219 raise LcmException(
2220 "Placement timeout for nslcmopId={}".format(nslcmop_id)
2221 )
magnussonle9198bb2020-01-21 13:00:51 +01002222
garciadeblas5697b8b2021-03-24 09:17:02 +01002223 for pla_vnf in pla_result["vnf"]:
2224 vnfr = db_vnfrs.get(pla_vnf["member-vnf-index"])
2225 if not pla_vnf.get("vimAccountId") or not vnfr:
magnussonle9198bb2020-01-21 13:00:51 +01002226 continue
tierno8790a3d2020-04-23 22:49:52 +00002227 modified = True
garciadeblas5697b8b2021-03-24 09:17:02 +01002228 self.db.set_one(
2229 "vnfrs",
2230 {"_id": vnfr["_id"]},
2231 {"vim-account-id": pla_vnf["vimAccountId"]},
2232 )
tierno38089af2020-04-16 07:56:58 +00002233 # Modifies db_vnfrs
garciadeblas5697b8b2021-03-24 09:17:02 +01002234 vnfr["vim-account-id"] = pla_vnf["vimAccountId"]
tierno8790a3d2020-04-23 22:49:52 +00002235 return modified
magnussonle9198bb2020-01-21 13:00:51 +01002236
2237 def update_nsrs_with_pla_result(self, params):
2238 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01002239 nslcmop_id = deep_get(params, ("placement", "nslcmopId"))
2240 self.update_db_2(
2241 "nslcmops", nslcmop_id, {"_admin.pla": params.get("placement")}
2242 )
magnussonle9198bb2020-01-21 13:00:51 +01002243 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002244 self.logger.warn("Update failed for nslcmop_id={}:{}".format(nslcmop_id, e))
magnussonle9198bb2020-01-21 13:00:51 +01002245
tierno59d22d22018-09-25 18:10:19 +02002246 async def instantiate(self, nsr_id, nslcmop_id):
quilesj7e13aeb2019-10-08 13:34:55 +02002247 """
2248
2249 :param nsr_id: ns instance to deploy
2250 :param nslcmop_id: operation to run
2251 :return:
2252 """
kuused124bfe2019-06-18 12:09:24 +02002253
2254 # Try to lock HA task here
garciadeblas5697b8b2021-03-24 09:17:02 +01002255 task_is_locked_by_me = self.lcm_tasks.lock_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02002256 if not task_is_locked_by_me:
garciadeblas5697b8b2021-03-24 09:17:02 +01002257 self.logger.debug(
2258 "instantiate() task is not locked by me, ns={}".format(nsr_id)
2259 )
kuused124bfe2019-06-18 12:09:24 +02002260 return
2261
tierno59d22d22018-09-25 18:10:19 +02002262 logging_text = "Task ns={} instantiate={} ".format(nsr_id, nslcmop_id)
2263 self.logger.debug(logging_text + "Enter")
quilesj7e13aeb2019-10-08 13:34:55 +02002264
tierno59d22d22018-09-25 18:10:19 +02002265 # get all needed from database
quilesj7e13aeb2019-10-08 13:34:55 +02002266
2267 # database nsrs record
tierno59d22d22018-09-25 18:10:19 +02002268 db_nsr = None
quilesj7e13aeb2019-10-08 13:34:55 +02002269
2270 # database nslcmops record
tierno59d22d22018-09-25 18:10:19 +02002271 db_nslcmop = None
quilesj7e13aeb2019-10-08 13:34:55 +02002272
2273 # update operation on nsrs
tiernoe876f672020-02-13 14:34:48 +00002274 db_nsr_update = {}
quilesj7e13aeb2019-10-08 13:34:55 +02002275 # update operation on nslcmops
tierno59d22d22018-09-25 18:10:19 +02002276 db_nslcmop_update = {}
quilesj7e13aeb2019-10-08 13:34:55 +02002277
tierno59d22d22018-09-25 18:10:19 +02002278 nslcmop_operation_state = None
garciadeblas5697b8b2021-03-24 09:17:02 +01002279 db_vnfrs = {} # vnf's info indexed by member-index
quilesj7e13aeb2019-10-08 13:34:55 +02002280 # n2vc_info = {}
tiernoe876f672020-02-13 14:34:48 +00002281 tasks_dict_info = {} # from task to info text
tierno59d22d22018-09-25 18:10:19 +02002282 exc = None
tiernoe876f672020-02-13 14:34:48 +00002283 error_list = []
garciadeblas5697b8b2021-03-24 09:17:02 +01002284 stage = [
2285 "Stage 1/5: preparation of the environment.",
2286 "Waiting for previous operations to terminate.",
2287 "",
2288 ]
tiernoe876f672020-02-13 14:34:48 +00002289 # ^ stage, step, VIM progress
tierno59d22d22018-09-25 18:10:19 +02002290 try:
kuused124bfe2019-06-18 12:09:24 +02002291 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +01002292 await self.lcm_tasks.waitfor_related_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02002293
quilesj7e13aeb2019-10-08 13:34:55 +02002294 # STEP 0: Reading database (nslcmops, nsrs, nsds, vnfrs, vnfds)
tiernob5203912020-08-11 11:20:13 +00002295 stage[1] = "Reading from database."
quilesj4cda56b2019-12-05 10:02:20 +00002296 # nsState="BUILDING", currentOperation="INSTANTIATING", currentOperationID=nslcmop_id
tiernoe876f672020-02-13 14:34:48 +00002297 db_nsr_update["detailed-status"] = "creating"
2298 db_nsr_update["operational-status"] = "init"
quilesj4cda56b2019-12-05 10:02:20 +00002299 self._write_ns_status(
2300 nsr_id=nsr_id,
2301 ns_state="BUILDING",
2302 current_operation="INSTANTIATING",
tiernoe876f672020-02-13 14:34:48 +00002303 current_operation_id=nslcmop_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01002304 other_update=db_nsr_update,
tiernoe876f672020-02-13 14:34:48 +00002305 )
garciadeblas5697b8b2021-03-24 09:17:02 +01002306 self._write_op_status(op_id=nslcmop_id, stage=stage, queuePosition=0)
quilesj4cda56b2019-12-05 10:02:20 +00002307
quilesj7e13aeb2019-10-08 13:34:55 +02002308 # read from db: operation
tiernob5203912020-08-11 11:20:13 +00002309 stage[1] = "Getting nslcmop={} from db.".format(nslcmop_id)
tierno59d22d22018-09-25 18:10:19 +02002310 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
Guillermo Calvinofbf294c2022-01-26 17:40:31 +01002311 if db_nslcmop["operationParams"].get("additionalParamsForVnf"):
2312 db_nslcmop["operationParams"]["additionalParamsForVnf"] = json.loads(
2313 db_nslcmop["operationParams"]["additionalParamsForVnf"]
2314 )
tierno744303e2020-01-13 16:46:31 +00002315 ns_params = db_nslcmop.get("operationParams")
2316 if ns_params and ns_params.get("timeout_ns_deploy"):
2317 timeout_ns_deploy = ns_params["timeout_ns_deploy"]
2318 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01002319 timeout_ns_deploy = self.timeout.get(
2320 "ns_deploy", self.timeout_ns_deploy
2321 )
quilesj7e13aeb2019-10-08 13:34:55 +02002322
2323 # read from db: ns
tiernob5203912020-08-11 11:20:13 +00002324 stage[1] = "Getting nsr={} from db.".format(nsr_id)
tierno59d22d22018-09-25 18:10:19 +02002325 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
tiernob5203912020-08-11 11:20:13 +00002326 stage[1] = "Getting nsd={} from db.".format(db_nsr["nsd-id"])
tiernod732fb82020-05-21 13:18:23 +00002327 nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
bravof021e70d2021-03-11 12:03:30 -03002328 self.fs.sync(db_nsr["nsd-id"])
tiernod732fb82020-05-21 13:18:23 +00002329 db_nsr["nsd"] = nsd
tiernod8323042019-08-09 11:32:23 +00002330 # nsr_name = db_nsr["name"] # TODO short-name??
tierno47e86b52018-10-10 14:05:55 +02002331
quilesj7e13aeb2019-10-08 13:34:55 +02002332 # read from db: vnf's of this ns
tiernob5203912020-08-11 11:20:13 +00002333 stage[1] = "Getting vnfrs from db."
tiernoe876f672020-02-13 14:34:48 +00002334 self.logger.debug(logging_text + stage[1])
tierno27246d82018-09-27 15:59:09 +02002335 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
tierno27246d82018-09-27 15:59:09 +02002336
quilesj7e13aeb2019-10-08 13:34:55 +02002337 # read from db: vnfd's for every vnf
garciadeblas5697b8b2021-03-24 09:17:02 +01002338 db_vnfds = [] # every vnfd data
quilesj7e13aeb2019-10-08 13:34:55 +02002339
2340 # for each vnf in ns, read vnfd
tierno27246d82018-09-27 15:59:09 +02002341 for vnfr in db_vnfrs_list:
Guillermo Calvinofbf294c2022-01-26 17:40:31 +01002342 if vnfr.get("kdur"):
2343 kdur_list = []
2344 for kdur in vnfr["kdur"]:
2345 if kdur.get("additionalParams"):
Pedro Escaleirab1679e42022-03-31 00:08:05 +01002346 kdur["additionalParams"] = json.loads(
2347 kdur["additionalParams"]
2348 )
Guillermo Calvinofbf294c2022-01-26 17:40:31 +01002349 kdur_list.append(kdur)
2350 vnfr["kdur"] = kdur_list
2351
bravof922c4172020-11-24 21:21:43 -03002352 db_vnfrs[vnfr["member-vnf-index-ref"]] = vnfr
2353 vnfd_id = vnfr["vnfd-id"]
2354 vnfd_ref = vnfr["vnfd-ref"]
bravof021e70d2021-03-11 12:03:30 -03002355 self.fs.sync(vnfd_id)
lloretgalleg6d488782020-07-22 10:13:46 +00002356
quilesj7e13aeb2019-10-08 13:34:55 +02002357 # if we haven't this vnfd, read it from db
tierno27246d82018-09-27 15:59:09 +02002358 if vnfd_id not in db_vnfds:
quilesj63f90042020-01-17 09:53:55 +00002359 # read from db
garciadeblas5697b8b2021-03-24 09:17:02 +01002360 stage[1] = "Getting vnfd={} id='{}' from db.".format(
2361 vnfd_id, vnfd_ref
2362 )
tiernoe876f672020-02-13 14:34:48 +00002363 self.logger.debug(logging_text + stage[1])
tierno27246d82018-09-27 15:59:09 +02002364 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
tierno27246d82018-09-27 15:59:09 +02002365
quilesj7e13aeb2019-10-08 13:34:55 +02002366 # store vnfd
David Garciad41dbd62020-12-10 12:52:52 +01002367 db_vnfds.append(vnfd)
quilesj7e13aeb2019-10-08 13:34:55 +02002368
2369 # Get or generates the _admin.deployed.VCA list
tiernoe4f7e6c2018-11-27 14:55:30 +00002370 vca_deployed_list = None
2371 if db_nsr["_admin"].get("deployed"):
2372 vca_deployed_list = db_nsr["_admin"]["deployed"].get("VCA")
2373 if vca_deployed_list is None:
2374 vca_deployed_list = []
quilesj3655ae02019-12-12 16:08:35 +00002375 configuration_status_list = []
tiernoe4f7e6c2018-11-27 14:55:30 +00002376 db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
quilesj3655ae02019-12-12 16:08:35 +00002377 db_nsr_update["configurationStatus"] = configuration_status_list
quilesj7e13aeb2019-10-08 13:34:55 +02002378 # add _admin.deployed.VCA to db_nsr dictionary, value=vca_deployed_list
tierno98ad6ea2019-05-30 17:16:28 +00002379 populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
tiernoe4f7e6c2018-11-27 14:55:30 +00002380 elif isinstance(vca_deployed_list, dict):
2381 # maintain backward compatibility. Change a dict to list at database
2382 vca_deployed_list = list(vca_deployed_list.values())
2383 db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
tierno98ad6ea2019-05-30 17:16:28 +00002384 populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
tiernoe4f7e6c2018-11-27 14:55:30 +00002385
garciadeblas5697b8b2021-03-24 09:17:02 +01002386 if not isinstance(
2387 deep_get(db_nsr, ("_admin", "deployed", "RO", "vnfd")), list
2388 ):
tiernoa009e552019-01-30 16:45:44 +00002389 populate_dict(db_nsr, ("_admin", "deployed", "RO", "vnfd"), [])
2390 db_nsr_update["_admin.deployed.RO.vnfd"] = []
tierno59d22d22018-09-25 18:10:19 +02002391
tiernobaa51102018-12-14 13:16:18 +00002392 # set state to INSTANTIATED. When instantiated NBI will not delete directly
2393 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
2394 self.update_db_2("nsrs", nsr_id, db_nsr_update)
garciadeblas5697b8b2021-03-24 09:17:02 +01002395 self.db.set_list(
2396 "vnfrs", {"nsr-id-ref": nsr_id}, {"_admin.nsState": "INSTANTIATED"}
2397 )
quilesj3655ae02019-12-12 16:08:35 +00002398
2399 # n2vc_redesign STEP 2 Deploy Network Scenario
garciadeblas5697b8b2021-03-24 09:17:02 +01002400 stage[0] = "Stage 2/5: deployment of KDUs, VMs and execution environments."
2401 self._write_op_status(op_id=nslcmop_id, stage=stage)
quilesj3655ae02019-12-12 16:08:35 +00002402
tiernob5203912020-08-11 11:20:13 +00002403 stage[1] = "Deploying KDUs."
tiernoe876f672020-02-13 14:34:48 +00002404 # self.logger.debug(logging_text + "Before deploy_kdus")
calvinosanch9f9c6f22019-11-04 13:37:39 +01002405 # Call to deploy_kdus in case exists the "vdu:kdu" param
tiernoe876f672020-02-13 14:34:48 +00002406 await self.deploy_kdus(
2407 logging_text=logging_text,
2408 nsr_id=nsr_id,
2409 nslcmop_id=nslcmop_id,
2410 db_vnfrs=db_vnfrs,
2411 db_vnfds=db_vnfds,
2412 task_instantiation_info=tasks_dict_info,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002413 )
tiernoe876f672020-02-13 14:34:48 +00002414
2415 stage[1] = "Getting VCA public key."
tiernod8323042019-08-09 11:32:23 +00002416 # n2vc_redesign STEP 1 Get VCA public ssh-key
2417 # feature 1429. Add n2vc public key to needed VMs
tierno3bedc9b2019-11-27 15:46:57 +00002418 n2vc_key = self.n2vc.get_public_key()
tiernoa5088192019-11-26 16:12:53 +00002419 n2vc_key_list = [n2vc_key]
2420 if self.vca_config.get("public_key"):
2421 n2vc_key_list.append(self.vca_config["public_key"])
tierno98ad6ea2019-05-30 17:16:28 +00002422
tiernoe876f672020-02-13 14:34:48 +00002423 stage[1] = "Deploying NS at VIM."
tiernod8323042019-08-09 11:32:23 +00002424 task_ro = asyncio.ensure_future(
quilesj7e13aeb2019-10-08 13:34:55 +02002425 self.instantiate_RO(
2426 logging_text=logging_text,
2427 nsr_id=nsr_id,
2428 nsd=nsd,
2429 db_nsr=db_nsr,
2430 db_nslcmop=db_nslcmop,
2431 db_vnfrs=db_vnfrs,
bravof922c4172020-11-24 21:21:43 -03002432 db_vnfds=db_vnfds,
tiernoe876f672020-02-13 14:34:48 +00002433 n2vc_key_list=n2vc_key_list,
garciadeblas5697b8b2021-03-24 09:17:02 +01002434 stage=stage,
tierno98ad6ea2019-05-30 17:16:28 +00002435 )
tiernod8323042019-08-09 11:32:23 +00002436 )
2437 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "instantiate_RO", task_ro)
tiernoa2143262020-03-27 16:20:40 +00002438 tasks_dict_info[task_ro] = "Deploying at VIM"
tierno98ad6ea2019-05-30 17:16:28 +00002439
tiernod8323042019-08-09 11:32:23 +00002440 # n2vc_redesign STEP 3 to 6 Deploy N2VC
tiernoe876f672020-02-13 14:34:48 +00002441 stage[1] = "Deploying Execution Environments."
2442 self.logger.debug(logging_text + stage[1])
tierno98ad6ea2019-05-30 17:16:28 +00002443
tiernod8323042019-08-09 11:32:23 +00002444 nsi_id = None # TODO put nsi_id when this nsr belongs to a NSI
bravof922c4172020-11-24 21:21:43 -03002445 for vnf_profile in get_vnf_profiles(nsd):
2446 vnfd_id = vnf_profile["vnfd-id"]
2447 vnfd = find_in_list(db_vnfds, lambda a_vnf: a_vnf["id"] == vnfd_id)
2448 member_vnf_index = str(vnf_profile["id"])
tiernod8323042019-08-09 11:32:23 +00002449 db_vnfr = db_vnfrs[member_vnf_index]
2450 base_folder = vnfd["_admin"]["storage"]
2451 vdu_id = None
2452 vdu_index = 0
tierno98ad6ea2019-05-30 17:16:28 +00002453 vdu_name = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01002454 kdu_name = None
tierno59d22d22018-09-25 18:10:19 +02002455
tierno8a518872018-12-21 13:42:14 +00002456 # Get additional parameters
bravof922c4172020-11-24 21:21:43 -03002457 deploy_params = {"OSM": get_osm_params(db_vnfr)}
tiernod8323042019-08-09 11:32:23 +00002458 if db_vnfr.get("additionalParamsForVnf"):
garciadeblas5697b8b2021-03-24 09:17:02 +01002459 deploy_params.update(
2460 parse_yaml_strings(db_vnfr["additionalParamsForVnf"].copy())
2461 )
tierno8a518872018-12-21 13:42:14 +00002462
bravofe5a31bc2021-02-17 19:09:12 -03002463 descriptor_config = get_configuration(vnfd, vnfd["id"])
tierno588547c2020-07-01 15:30:20 +00002464 if descriptor_config:
quilesj7e13aeb2019-10-08 13:34:55 +02002465 self._deploy_n2vc(
garciadeblas5697b8b2021-03-24 09:17:02 +01002466 logging_text=logging_text
2467 + "member_vnf_index={} ".format(member_vnf_index),
quilesj7e13aeb2019-10-08 13:34:55 +02002468 db_nsr=db_nsr,
2469 db_vnfr=db_vnfr,
2470 nslcmop_id=nslcmop_id,
2471 nsr_id=nsr_id,
2472 nsi_id=nsi_id,
2473 vnfd_id=vnfd_id,
2474 vdu_id=vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002475 kdu_name=kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02002476 member_vnf_index=member_vnf_index,
2477 vdu_index=vdu_index,
2478 vdu_name=vdu_name,
2479 deploy_params=deploy_params,
2480 descriptor_config=descriptor_config,
2481 base_folder=base_folder,
tiernoe876f672020-02-13 14:34:48 +00002482 task_instantiation_info=tasks_dict_info,
garciadeblas5697b8b2021-03-24 09:17:02 +01002483 stage=stage,
quilesj7e13aeb2019-10-08 13:34:55 +02002484 )
tierno59d22d22018-09-25 18:10:19 +02002485
2486 # Deploy charms for each VDU that supports one.
bravof922c4172020-11-24 21:21:43 -03002487 for vdud in get_vdu_list(vnfd):
tiernod8323042019-08-09 11:32:23 +00002488 vdu_id = vdud["id"]
bravofe5a31bc2021-02-17 19:09:12 -03002489 descriptor_config = get_configuration(vnfd, vdu_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01002490 vdur = find_in_list(
2491 db_vnfr["vdur"], lambda vdu: vdu["vdu-id-ref"] == vdu_id
2492 )
bravof922c4172020-11-24 21:21:43 -03002493
tierno626e0152019-11-29 14:16:16 +00002494 if vdur.get("additionalParams"):
bravof922c4172020-11-24 21:21:43 -03002495 deploy_params_vdu = parse_yaml_strings(vdur["additionalParams"])
tierno626e0152019-11-29 14:16:16 +00002496 else:
2497 deploy_params_vdu = deploy_params
garciadeblas5697b8b2021-03-24 09:17:02 +01002498 deploy_params_vdu["OSM"] = get_osm_params(
2499 db_vnfr, vdu_id, vdu_count_index=0
2500 )
endika85d73a62021-06-21 18:55:07 +02002501 vdud_count = get_number_of_instances(vnfd, vdu_id)
bravof922c4172020-11-24 21:21:43 -03002502
2503 self.logger.debug("VDUD > {}".format(vdud))
garciadeblas5697b8b2021-03-24 09:17:02 +01002504 self.logger.debug(
2505 "Descriptor config > {}".format(descriptor_config)
2506 )
tierno588547c2020-07-01 15:30:20 +00002507 if descriptor_config:
tiernod8323042019-08-09 11:32:23 +00002508 vdu_name = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01002509 kdu_name = None
bravof922c4172020-11-24 21:21:43 -03002510 for vdu_index in range(vdud_count):
tiernod8323042019-08-09 11:32:23 +00002511 # TODO vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
quilesj7e13aeb2019-10-08 13:34:55 +02002512 self._deploy_n2vc(
garciadeblas5697b8b2021-03-24 09:17:02 +01002513 logging_text=logging_text
2514 + "member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
2515 member_vnf_index, vdu_id, vdu_index
2516 ),
quilesj7e13aeb2019-10-08 13:34:55 +02002517 db_nsr=db_nsr,
2518 db_vnfr=db_vnfr,
2519 nslcmop_id=nslcmop_id,
2520 nsr_id=nsr_id,
2521 nsi_id=nsi_id,
2522 vnfd_id=vnfd_id,
2523 vdu_id=vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002524 kdu_name=kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02002525 member_vnf_index=member_vnf_index,
2526 vdu_index=vdu_index,
2527 vdu_name=vdu_name,
tierno626e0152019-11-29 14:16:16 +00002528 deploy_params=deploy_params_vdu,
quilesj7e13aeb2019-10-08 13:34:55 +02002529 descriptor_config=descriptor_config,
2530 base_folder=base_folder,
tierno8e2fae72020-04-01 15:21:15 +00002531 task_instantiation_info=tasks_dict_info,
garciadeblas5697b8b2021-03-24 09:17:02 +01002532 stage=stage,
quilesj7e13aeb2019-10-08 13:34:55 +02002533 )
bravof922c4172020-11-24 21:21:43 -03002534 for kdud in get_kdu_list(vnfd):
calvinosanch9f9c6f22019-11-04 13:37:39 +01002535 kdu_name = kdud["name"]
bravofe5a31bc2021-02-17 19:09:12 -03002536 descriptor_config = get_configuration(vnfd, kdu_name)
tierno588547c2020-07-01 15:30:20 +00002537 if descriptor_config:
calvinosanch9f9c6f22019-11-04 13:37:39 +01002538 vdu_id = None
2539 vdu_index = 0
2540 vdu_name = None
garciadeblas5697b8b2021-03-24 09:17:02 +01002541 kdur = next(
2542 x for x in db_vnfr["kdur"] if x["kdu-name"] == kdu_name
2543 )
bravof922c4172020-11-24 21:21:43 -03002544 deploy_params_kdu = {"OSM": get_osm_params(db_vnfr)}
tierno72ef84f2020-10-06 08:22:07 +00002545 if kdur.get("additionalParams"):
Pedro Escaleirab1679e42022-03-31 00:08:05 +01002546 deploy_params_kdu.update(
2547 parse_yaml_strings(kdur["additionalParams"].copy())
garciadeblas5697b8b2021-03-24 09:17:02 +01002548 )
tierno59d22d22018-09-25 18:10:19 +02002549
calvinosanch9f9c6f22019-11-04 13:37:39 +01002550 self._deploy_n2vc(
2551 logging_text=logging_text,
2552 db_nsr=db_nsr,
2553 db_vnfr=db_vnfr,
2554 nslcmop_id=nslcmop_id,
2555 nsr_id=nsr_id,
2556 nsi_id=nsi_id,
2557 vnfd_id=vnfd_id,
2558 vdu_id=vdu_id,
2559 kdu_name=kdu_name,
2560 member_vnf_index=member_vnf_index,
2561 vdu_index=vdu_index,
2562 vdu_name=vdu_name,
tierno72ef84f2020-10-06 08:22:07 +00002563 deploy_params=deploy_params_kdu,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002564 descriptor_config=descriptor_config,
2565 base_folder=base_folder,
tierno8e2fae72020-04-01 15:21:15 +00002566 task_instantiation_info=tasks_dict_info,
garciadeblas5697b8b2021-03-24 09:17:02 +01002567 stage=stage,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002568 )
tierno59d22d22018-09-25 18:10:19 +02002569
tierno1b633412019-02-25 16:48:23 +00002570 # Check if this NS has a charm configuration
tiernod8323042019-08-09 11:32:23 +00002571 descriptor_config = nsd.get("ns-configuration")
2572 if descriptor_config and descriptor_config.get("juju"):
2573 vnfd_id = None
2574 db_vnfr = None
2575 member_vnf_index = None
2576 vdu_id = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01002577 kdu_name = None
tiernod8323042019-08-09 11:32:23 +00002578 vdu_index = 0
2579 vdu_name = None
tierno1b633412019-02-25 16:48:23 +00002580
tiernod8323042019-08-09 11:32:23 +00002581 # Get additional parameters
David Garcia40603572020-12-10 20:10:53 +01002582 deploy_params = {"OSM": {"vim_account_id": ns_params["vimAccountId"]}}
tiernod8323042019-08-09 11:32:23 +00002583 if db_nsr.get("additionalParamsForNs"):
garciadeblas5697b8b2021-03-24 09:17:02 +01002584 deploy_params.update(
2585 parse_yaml_strings(db_nsr["additionalParamsForNs"].copy())
2586 )
tiernod8323042019-08-09 11:32:23 +00002587 base_folder = nsd["_admin"]["storage"]
quilesj7e13aeb2019-10-08 13:34:55 +02002588 self._deploy_n2vc(
2589 logging_text=logging_text,
2590 db_nsr=db_nsr,
2591 db_vnfr=db_vnfr,
2592 nslcmop_id=nslcmop_id,
2593 nsr_id=nsr_id,
2594 nsi_id=nsi_id,
2595 vnfd_id=vnfd_id,
2596 vdu_id=vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002597 kdu_name=kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02002598 member_vnf_index=member_vnf_index,
2599 vdu_index=vdu_index,
2600 vdu_name=vdu_name,
2601 deploy_params=deploy_params,
2602 descriptor_config=descriptor_config,
2603 base_folder=base_folder,
tierno8e2fae72020-04-01 15:21:15 +00002604 task_instantiation_info=tasks_dict_info,
garciadeblas5697b8b2021-03-24 09:17:02 +01002605 stage=stage,
quilesj7e13aeb2019-10-08 13:34:55 +02002606 )
tierno1b633412019-02-25 16:48:23 +00002607
tiernoe876f672020-02-13 14:34:48 +00002608 # rest of staff will be done at finally
tierno1b633412019-02-25 16:48:23 +00002609
garciadeblas5697b8b2021-03-24 09:17:02 +01002610 except (
2611 ROclient.ROClientException,
2612 DbException,
2613 LcmException,
2614 N2VCException,
2615 ) as e:
2616 self.logger.error(
2617 logging_text + "Exit Exception while '{}': {}".format(stage[1], e)
2618 )
tierno59d22d22018-09-25 18:10:19 +02002619 exc = e
2620 except asyncio.CancelledError:
garciadeblas5697b8b2021-03-24 09:17:02 +01002621 self.logger.error(
2622 logging_text + "Cancelled Exception while '{}'".format(stage[1])
2623 )
tierno59d22d22018-09-25 18:10:19 +02002624 exc = "Operation was cancelled"
2625 except Exception as e:
2626 exc = traceback.format_exc()
garciadeblas5697b8b2021-03-24 09:17:02 +01002627 self.logger.critical(
2628 logging_text + "Exit Exception while '{}': {}".format(stage[1], e),
2629 exc_info=True,
2630 )
tierno59d22d22018-09-25 18:10:19 +02002631 finally:
2632 if exc:
tiernoe876f672020-02-13 14:34:48 +00002633 error_list.append(str(exc))
tiernobaa51102018-12-14 13:16:18 +00002634 try:
tiernoe876f672020-02-13 14:34:48 +00002635 # wait for pending tasks
2636 if tasks_dict_info:
2637 stage[1] = "Waiting for instantiate pending tasks."
2638 self.logger.debug(logging_text + stage[1])
garciadeblas5697b8b2021-03-24 09:17:02 +01002639 error_list += await self._wait_for_tasks(
2640 logging_text,
2641 tasks_dict_info,
2642 timeout_ns_deploy,
2643 stage,
2644 nslcmop_id,
2645 nsr_id=nsr_id,
2646 )
tiernoe876f672020-02-13 14:34:48 +00002647 stage[1] = stage[2] = ""
2648 except asyncio.CancelledError:
2649 error_list.append("Cancelled")
2650 # TODO cancel all tasks
2651 except Exception as exc:
2652 error_list.append(str(exc))
quilesj4cda56b2019-12-05 10:02:20 +00002653
tiernoe876f672020-02-13 14:34:48 +00002654 # update operation-status
2655 db_nsr_update["operational-status"] = "running"
2656 # let's begin with VCA 'configured' status (later we can change it)
2657 db_nsr_update["config-status"] = "configured"
2658 for task, task_name in tasks_dict_info.items():
2659 if not task.done() or task.cancelled() or task.exception():
2660 if task_name.startswith(self.task_name_deploy_vca):
2661 # A N2VC task is pending
2662 db_nsr_update["config-status"] = "failed"
quilesj4cda56b2019-12-05 10:02:20 +00002663 else:
tiernoe876f672020-02-13 14:34:48 +00002664 # RO or KDU task is pending
2665 db_nsr_update["operational-status"] = "failed"
quilesj3655ae02019-12-12 16:08:35 +00002666
tiernoe876f672020-02-13 14:34:48 +00002667 # update status at database
2668 if error_list:
tiernoa2143262020-03-27 16:20:40 +00002669 error_detail = ". ".join(error_list)
tiernoe876f672020-02-13 14:34:48 +00002670 self.logger.error(logging_text + error_detail)
garciadeblas5697b8b2021-03-24 09:17:02 +01002671 error_description_nslcmop = "{} Detail: {}".format(
2672 stage[0], error_detail
2673 )
2674 error_description_nsr = "Operation: INSTANTIATING.{}, {}".format(
2675 nslcmop_id, stage[0]
2676 )
quilesj3655ae02019-12-12 16:08:35 +00002677
garciadeblas5697b8b2021-03-24 09:17:02 +01002678 db_nsr_update["detailed-status"] = (
2679 error_description_nsr + " Detail: " + error_detail
2680 )
tiernoe876f672020-02-13 14:34:48 +00002681 db_nslcmop_update["detailed-status"] = error_detail
2682 nslcmop_operation_state = "FAILED"
2683 ns_state = "BROKEN"
2684 else:
tiernoa2143262020-03-27 16:20:40 +00002685 error_detail = None
tiernoe876f672020-02-13 14:34:48 +00002686 error_description_nsr = error_description_nslcmop = None
2687 ns_state = "READY"
2688 db_nsr_update["detailed-status"] = "Done"
2689 db_nslcmop_update["detailed-status"] = "Done"
2690 nslcmop_operation_state = "COMPLETED"
quilesj4cda56b2019-12-05 10:02:20 +00002691
tiernoe876f672020-02-13 14:34:48 +00002692 if db_nsr:
2693 self._write_ns_status(
2694 nsr_id=nsr_id,
2695 ns_state=ns_state,
2696 current_operation="IDLE",
2697 current_operation_id=None,
2698 error_description=error_description_nsr,
tiernoa2143262020-03-27 16:20:40 +00002699 error_detail=error_detail,
garciadeblas5697b8b2021-03-24 09:17:02 +01002700 other_update=db_nsr_update,
tiernoe876f672020-02-13 14:34:48 +00002701 )
tiernoa17d4f42020-04-28 09:59:23 +00002702 self._write_op_status(
2703 op_id=nslcmop_id,
2704 stage="",
2705 error_message=error_description_nslcmop,
2706 operation_state=nslcmop_operation_state,
2707 other_update=db_nslcmop_update,
2708 )
quilesj3655ae02019-12-12 16:08:35 +00002709
tierno59d22d22018-09-25 18:10:19 +02002710 if nslcmop_operation_state:
2711 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01002712 await self.msg.aiowrite(
2713 "ns",
2714 "instantiated",
2715 {
2716 "nsr_id": nsr_id,
2717 "nslcmop_id": nslcmop_id,
2718 "operationState": nslcmop_operation_state,
2719 },
2720 loop=self.loop,
2721 )
tierno59d22d22018-09-25 18:10:19 +02002722 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002723 self.logger.error(
2724 logging_text + "kafka_write notification Exception {}".format(e)
2725 )
tierno59d22d22018-09-25 18:10:19 +02002726
2727 self.logger.debug(logging_text + "Exit")
2728 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_instantiate")
2729
David Garciac1fe90a2021-03-31 19:12:02 +02002730 async def _add_vca_relations(
2731 self,
2732 logging_text,
2733 nsr_id,
2734 vca_index: int,
2735 timeout: int = 3600,
2736 vca_type: str = None,
2737 vca_id: str = None,
2738 ) -> bool:
quilesj63f90042020-01-17 09:53:55 +00002739
2740 # steps:
2741 # 1. find all relations for this VCA
2742 # 2. wait for other peers related
2743 # 3. add relations
2744
2745 try:
tierno588547c2020-07-01 15:30:20 +00002746 vca_type = vca_type or "lxc_proxy_charm"
quilesj63f90042020-01-17 09:53:55 +00002747
2748 # STEP 1: find all relations for this VCA
2749
2750 # read nsr record
2751 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
David Garcia171f3542020-05-21 16:41:07 +02002752 nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
quilesj63f90042020-01-17 09:53:55 +00002753
2754 # this VCA data
garciadeblas5697b8b2021-03-24 09:17:02 +01002755 my_vca = deep_get(db_nsr, ("_admin", "deployed", "VCA"))[vca_index]
quilesj63f90042020-01-17 09:53:55 +00002756
2757 # read all ns-configuration relations
2758 ns_relations = list()
garciadeblas5697b8b2021-03-24 09:17:02 +01002759 db_ns_relations = deep_get(nsd, ("ns-configuration", "relation"))
quilesj63f90042020-01-17 09:53:55 +00002760 if db_ns_relations:
2761 for r in db_ns_relations:
2762 # check if this VCA is in the relation
garciadeblas5697b8b2021-03-24 09:17:02 +01002763 if my_vca.get("member-vnf-index") in (
2764 r.get("entities")[0].get("id"),
2765 r.get("entities")[1].get("id"),
2766 ):
quilesj63f90042020-01-17 09:53:55 +00002767 ns_relations.append(r)
2768
2769 # read all vnf-configuration relations
2770 vnf_relations = list()
garciadeblas5697b8b2021-03-24 09:17:02 +01002771 db_vnfd_list = db_nsr.get("vnfd-id")
quilesj63f90042020-01-17 09:53:55 +00002772 if db_vnfd_list:
2773 for vnfd in db_vnfd_list:
aktas45966a02021-05-04 19:32:45 +03002774 db_vnf_relations = None
quilesj63f90042020-01-17 09:53:55 +00002775 db_vnfd = self.db.get_one("vnfds", {"_id": vnfd})
aktas45966a02021-05-04 19:32:45 +03002776 db_vnf_configuration = get_configuration(db_vnfd, db_vnfd["id"])
2777 if db_vnf_configuration:
2778 db_vnf_relations = db_vnf_configuration.get("relation", [])
quilesj63f90042020-01-17 09:53:55 +00002779 if db_vnf_relations:
2780 for r in db_vnf_relations:
2781 # check if this VCA is in the relation
garciadeblas5697b8b2021-03-24 09:17:02 +01002782 if my_vca.get("vdu_id") in (
2783 r.get("entities")[0].get("id"),
2784 r.get("entities")[1].get("id"),
2785 ):
quilesj63f90042020-01-17 09:53:55 +00002786 vnf_relations.append(r)
2787
2788 # if no relations, terminate
2789 if not ns_relations and not vnf_relations:
garciadeblas5697b8b2021-03-24 09:17:02 +01002790 self.logger.debug(logging_text + " No relations")
quilesj63f90042020-01-17 09:53:55 +00002791 return True
2792
garciadeblas5697b8b2021-03-24 09:17:02 +01002793 self.logger.debug(
2794 logging_text
2795 + " adding relations\n {}\n {}".format(
2796 ns_relations, vnf_relations
2797 )
2798 )
quilesj63f90042020-01-17 09:53:55 +00002799
2800 # add all relations
2801 start = time()
2802 while True:
2803 # check timeout
2804 now = time()
2805 if now - start >= timeout:
garciadeblas5697b8b2021-03-24 09:17:02 +01002806 self.logger.error(logging_text + " : timeout adding relations")
quilesj63f90042020-01-17 09:53:55 +00002807 return False
2808
2809 # reload nsr from database (we need to update record: _admin.deloyed.VCA)
2810 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2811
2812 # for each defined NS relation, find the VCA's related
tierno364c4572020-09-14 12:11:32 +00002813 for r in ns_relations.copy():
quilesj63f90042020-01-17 09:53:55 +00002814 from_vca_ee_id = None
2815 to_vca_ee_id = None
2816 from_vca_endpoint = None
2817 to_vca_endpoint = None
garciadeblas5697b8b2021-03-24 09:17:02 +01002818 vca_list = deep_get(db_nsr, ("_admin", "deployed", "VCA"))
quilesj63f90042020-01-17 09:53:55 +00002819 for vca in vca_list:
garciadeblas5697b8b2021-03-24 09:17:02 +01002820 if vca.get("member-vnf-index") == r.get("entities")[0].get(
2821 "id"
2822 ) and vca.get("config_sw_installed"):
2823 from_vca_ee_id = vca.get("ee_id")
2824 from_vca_endpoint = r.get("entities")[0].get("endpoint")
2825 if vca.get("member-vnf-index") == r.get("entities")[1].get(
2826 "id"
2827 ) and vca.get("config_sw_installed"):
2828 to_vca_ee_id = vca.get("ee_id")
2829 to_vca_endpoint = r.get("entities")[1].get("endpoint")
quilesj63f90042020-01-17 09:53:55 +00002830 if from_vca_ee_id and to_vca_ee_id:
2831 # add relation
tierno588547c2020-07-01 15:30:20 +00002832 await self.vca_map[vca_type].add_relation(
quilesj63f90042020-01-17 09:53:55 +00002833 ee_id_1=from_vca_ee_id,
2834 ee_id_2=to_vca_ee_id,
2835 endpoint_1=from_vca_endpoint,
David Garciac1fe90a2021-03-31 19:12:02 +02002836 endpoint_2=to_vca_endpoint,
2837 vca_id=vca_id,
2838 )
quilesj63f90042020-01-17 09:53:55 +00002839 # remove entry from relations list
2840 ns_relations.remove(r)
2841 else:
2842 # check failed peers
2843 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01002844 vca_status_list = db_nsr.get("configurationStatus")
quilesj63f90042020-01-17 09:53:55 +00002845 if vca_status_list:
2846 for i in range(len(vca_list)):
2847 vca = vca_list[i]
2848 vca_status = vca_status_list[i]
garciadeblas5697b8b2021-03-24 09:17:02 +01002849 if vca.get("member-vnf-index") == r.get("entities")[
2850 0
2851 ].get("id"):
2852 if vca_status.get("status") == "BROKEN":
quilesj63f90042020-01-17 09:53:55 +00002853 # peer broken: remove relation from list
2854 ns_relations.remove(r)
garciadeblas5697b8b2021-03-24 09:17:02 +01002855 if vca.get("member-vnf-index") == r.get("entities")[
2856 1
2857 ].get("id"):
2858 if vca_status.get("status") == "BROKEN":
quilesj63f90042020-01-17 09:53:55 +00002859 # peer broken: remove relation from list
2860 ns_relations.remove(r)
2861 except Exception:
2862 # ignore
2863 pass
2864
2865 # for each defined VNF relation, find the VCA's related
tierno364c4572020-09-14 12:11:32 +00002866 for r in vnf_relations.copy():
quilesj63f90042020-01-17 09:53:55 +00002867 from_vca_ee_id = None
2868 to_vca_ee_id = None
2869 from_vca_endpoint = None
2870 to_vca_endpoint = None
garciadeblas5697b8b2021-03-24 09:17:02 +01002871 vca_list = deep_get(db_nsr, ("_admin", "deployed", "VCA"))
quilesj63f90042020-01-17 09:53:55 +00002872 for vca in vca_list:
David Garcia97be6832020-09-09 15:40:44 +02002873 key_to_check = "vdu_id"
2874 if vca.get("vdu_id") is None:
2875 key_to_check = "vnfd_id"
garciadeblas5697b8b2021-03-24 09:17:02 +01002876 if vca.get(key_to_check) == r.get("entities")[0].get(
2877 "id"
2878 ) and vca.get("config_sw_installed"):
2879 from_vca_ee_id = vca.get("ee_id")
2880 from_vca_endpoint = r.get("entities")[0].get("endpoint")
2881 if vca.get(key_to_check) == r.get("entities")[1].get(
2882 "id"
2883 ) and vca.get("config_sw_installed"):
2884 to_vca_ee_id = vca.get("ee_id")
2885 to_vca_endpoint = r.get("entities")[1].get("endpoint")
quilesj63f90042020-01-17 09:53:55 +00002886 if from_vca_ee_id and to_vca_ee_id:
2887 # add relation
tierno588547c2020-07-01 15:30:20 +00002888 await self.vca_map[vca_type].add_relation(
quilesj63f90042020-01-17 09:53:55 +00002889 ee_id_1=from_vca_ee_id,
2890 ee_id_2=to_vca_ee_id,
2891 endpoint_1=from_vca_endpoint,
David Garciac1fe90a2021-03-31 19:12:02 +02002892 endpoint_2=to_vca_endpoint,
2893 vca_id=vca_id,
2894 )
quilesj63f90042020-01-17 09:53:55 +00002895 # remove entry from relations list
2896 vnf_relations.remove(r)
2897 else:
2898 # check failed peers
2899 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01002900 vca_status_list = db_nsr.get("configurationStatus")
quilesj63f90042020-01-17 09:53:55 +00002901 if vca_status_list:
2902 for i in range(len(vca_list)):
2903 vca = vca_list[i]
2904 vca_status = vca_status_list[i]
garciadeblas5697b8b2021-03-24 09:17:02 +01002905 if vca.get("vdu_id") == r.get("entities")[0].get(
2906 "id"
2907 ):
2908 if vca_status.get("status") == "BROKEN":
quilesj63f90042020-01-17 09:53:55 +00002909 # peer broken: remove relation from list
David Garcia092afbd2020-08-25 13:17:25 +02002910 vnf_relations.remove(r)
garciadeblas5697b8b2021-03-24 09:17:02 +01002911 if vca.get("vdu_id") == r.get("entities")[1].get(
2912 "id"
2913 ):
2914 if vca_status.get("status") == "BROKEN":
quilesj63f90042020-01-17 09:53:55 +00002915 # peer broken: remove relation from list
David Garcia092afbd2020-08-25 13:17:25 +02002916 vnf_relations.remove(r)
quilesj63f90042020-01-17 09:53:55 +00002917 except Exception:
2918 # ignore
2919 pass
2920
2921 # wait for next try
2922 await asyncio.sleep(5.0)
2923
2924 if not ns_relations and not vnf_relations:
garciadeblas5697b8b2021-03-24 09:17:02 +01002925 self.logger.debug("Relations added")
quilesj63f90042020-01-17 09:53:55 +00002926 break
2927
2928 return True
2929
2930 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01002931 self.logger.warn(logging_text + " ERROR adding relations: {}".format(e))
quilesj63f90042020-01-17 09:53:55 +00002932 return False
2933
garciadeblas5697b8b2021-03-24 09:17:02 +01002934 async def _install_kdu(
2935 self,
2936 nsr_id: str,
2937 nsr_db_path: str,
2938 vnfr_data: dict,
2939 kdu_index: int,
2940 kdud: dict,
2941 vnfd: dict,
2942 k8s_instance_info: dict,
2943 k8params: dict = None,
2944 timeout: int = 600,
2945 vca_id: str = None,
2946 ):
lloretgalleg7c121132020-07-08 07:53:22 +00002947
tiernob9018152020-04-16 14:18:24 +00002948 try:
lloretgalleg7c121132020-07-08 07:53:22 +00002949 k8sclustertype = k8s_instance_info["k8scluster-type"]
2950 # Instantiate kdu
garciadeblas5697b8b2021-03-24 09:17:02 +01002951 db_dict_install = {
2952 "collection": "nsrs",
2953 "filter": {"_id": nsr_id},
2954 "path": nsr_db_path,
2955 }
lloretgalleg7c121132020-07-08 07:53:22 +00002956
romeromonser4e71ab62021-05-28 12:06:34 +02002957 if k8s_instance_info.get("kdu-deployment-name"):
2958 kdu_instance = k8s_instance_info.get("kdu-deployment-name")
2959 else:
2960 kdu_instance = self.k8scluster_map[
2961 k8sclustertype
2962 ].generate_kdu_instance_name(
2963 db_dict=db_dict_install,
2964 kdu_model=k8s_instance_info["kdu-model"],
2965 kdu_name=k8s_instance_info["kdu-name"],
2966 )
Pedro Escaleira1a122f32022-04-21 16:31:06 +01002967
2968 # Update the nsrs table with the kdu-instance value
garciadeblas5697b8b2021-03-24 09:17:02 +01002969 self.update_db_2(
Pedro Escaleira1a122f32022-04-21 16:31:06 +01002970 item="nsrs",
2971 _id=nsr_id,
2972 _desc={nsr_db_path + ".kdu-instance": kdu_instance},
garciadeblas5697b8b2021-03-24 09:17:02 +01002973 )
Pedro Escaleira1a122f32022-04-21 16:31:06 +01002974
2975 # Update the nsrs table with the actual namespace being used, if the k8scluster-type is `juju` or
2976 # `juju-bundle`. This verification is needed because there is not a standard/homogeneous namespace
2977 # between the Helm Charts and Juju Bundles-based KNFs. If we found a way of having an homogeneous
2978 # namespace, this first verification could be removed, and the next step would be done for any kind
2979 # of KNF.
2980 # TODO -> find a way to have an homogeneous namespace between the Helm Charts and Juju Bundles-based
2981 # KNFs (Bug 2027: https://osm.etsi.org/bugzilla/show_bug.cgi?id=2027)
2982 if k8sclustertype in ("juju", "juju-bundle"):
2983 # First, verify if the current namespace is present in the `_admin.projects_read` (if not, it means
2984 # that the user passed a namespace which he wants its KDU to be deployed in)
2985 if (
2986 self.db.count(
2987 table="nsrs",
2988 q_filter={
2989 "_id": nsr_id,
2990 "_admin.projects_write": k8s_instance_info["namespace"],
2991 "_admin.projects_read": k8s_instance_info["namespace"],
2992 },
2993 )
2994 > 0
2995 ):
2996 self.logger.debug(
2997 f"Updating namespace/model for Juju Bundle from {k8s_instance_info['namespace']} to {kdu_instance}"
2998 )
2999 self.update_db_2(
3000 item="nsrs",
3001 _id=nsr_id,
3002 _desc={f"{nsr_db_path}.namespace": kdu_instance},
3003 )
3004 k8s_instance_info["namespace"] = kdu_instance
3005
David Garciad64e2742021-02-25 20:19:18 +01003006 await self.k8scluster_map[k8sclustertype].install(
lloretgalleg7c121132020-07-08 07:53:22 +00003007 cluster_uuid=k8s_instance_info["k8scluster-uuid"],
3008 kdu_model=k8s_instance_info["kdu-model"],
3009 atomic=True,
3010 params=k8params,
3011 db_dict=db_dict_install,
3012 timeout=timeout,
3013 kdu_name=k8s_instance_info["kdu-name"],
David Garciad64e2742021-02-25 20:19:18 +01003014 namespace=k8s_instance_info["namespace"],
3015 kdu_instance=kdu_instance,
David Garciac1fe90a2021-03-31 19:12:02 +02003016 vca_id=vca_id,
David Garciad64e2742021-02-25 20:19:18 +01003017 )
lloretgalleg7c121132020-07-08 07:53:22 +00003018
3019 # Obtain services to obtain management service ip
3020 services = await self.k8scluster_map[k8sclustertype].get_services(
3021 cluster_uuid=k8s_instance_info["k8scluster-uuid"],
3022 kdu_instance=kdu_instance,
garciadeblas5697b8b2021-03-24 09:17:02 +01003023 namespace=k8s_instance_info["namespace"],
3024 )
lloretgalleg7c121132020-07-08 07:53:22 +00003025
3026 # Obtain management service info (if exists)
tierno7ecbc342020-09-21 14:05:39 +00003027 vnfr_update_dict = {}
bravof6ec62b72021-02-25 17:20:35 -03003028 kdu_config = get_configuration(vnfd, kdud["name"])
3029 if kdu_config:
3030 target_ee_list = kdu_config.get("execution-environment-list", [])
3031 else:
3032 target_ee_list = []
3033
lloretgalleg7c121132020-07-08 07:53:22 +00003034 if services:
tierno7ecbc342020-09-21 14:05:39 +00003035 vnfr_update_dict["kdur.{}.services".format(kdu_index)] = services
garciadeblas5697b8b2021-03-24 09:17:02 +01003036 mgmt_services = [
3037 service
3038 for service in kdud.get("service", [])
3039 if service.get("mgmt-service")
3040 ]
lloretgalleg7c121132020-07-08 07:53:22 +00003041 for mgmt_service in mgmt_services:
3042 for service in services:
3043 if service["name"].startswith(mgmt_service["name"]):
3044 # Mgmt service found, Obtain service ip
3045 ip = service.get("external_ip", service.get("cluster_ip"))
3046 if isinstance(ip, list) and len(ip) == 1:
3047 ip = ip[0]
3048
garciadeblas5697b8b2021-03-24 09:17:02 +01003049 vnfr_update_dict[
3050 "kdur.{}.ip-address".format(kdu_index)
3051 ] = ip
lloretgalleg7c121132020-07-08 07:53:22 +00003052
3053 # Check if must update also mgmt ip at the vnf
garciadeblas5697b8b2021-03-24 09:17:02 +01003054 service_external_cp = mgmt_service.get(
3055 "external-connection-point-ref"
3056 )
lloretgalleg7c121132020-07-08 07:53:22 +00003057 if service_external_cp:
garciadeblas5697b8b2021-03-24 09:17:02 +01003058 if (
3059 deep_get(vnfd, ("mgmt-interface", "cp"))
3060 == service_external_cp
3061 ):
lloretgalleg7c121132020-07-08 07:53:22 +00003062 vnfr_update_dict["ip-address"] = ip
3063
bravof6ec62b72021-02-25 17:20:35 -03003064 if find_in_list(
3065 target_ee_list,
garciadeblas5697b8b2021-03-24 09:17:02 +01003066 lambda ee: ee.get(
3067 "external-connection-point-ref", ""
3068 )
3069 == service_external_cp,
bravof6ec62b72021-02-25 17:20:35 -03003070 ):
garciadeblas5697b8b2021-03-24 09:17:02 +01003071 vnfr_update_dict[
3072 "kdur.{}.ip-address".format(kdu_index)
3073 ] = ip
lloretgalleg7c121132020-07-08 07:53:22 +00003074 break
3075 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01003076 self.logger.warn(
3077 "Mgmt service name: {} not found".format(
3078 mgmt_service["name"]
3079 )
3080 )
lloretgalleg7c121132020-07-08 07:53:22 +00003081
tierno7ecbc342020-09-21 14:05:39 +00003082 vnfr_update_dict["kdur.{}.status".format(kdu_index)] = "READY"
3083 self.update_db_2("vnfrs", vnfr_data.get("_id"), vnfr_update_dict)
lloretgalleg7c121132020-07-08 07:53:22 +00003084
bravof9a256db2021-02-22 18:02:07 -03003085 kdu_config = get_configuration(vnfd, k8s_instance_info["kdu-name"])
garciadeblas5697b8b2021-03-24 09:17:02 +01003086 if (
3087 kdu_config
3088 and kdu_config.get("initial-config-primitive")
3089 and get_juju_ee_ref(vnfd, k8s_instance_info["kdu-name"]) is None
3090 ):
3091 initial_config_primitive_list = kdu_config.get(
3092 "initial-config-primitive"
3093 )
Dominik Fleischmannc1975dd2020-08-19 12:17:51 +02003094 initial_config_primitive_list.sort(key=lambda val: int(val["seq"]))
3095
3096 for initial_config_primitive in initial_config_primitive_list:
garciadeblas5697b8b2021-03-24 09:17:02 +01003097 primitive_params_ = self._map_primitive_params(
3098 initial_config_primitive, {}, {}
3099 )
Dominik Fleischmannc1975dd2020-08-19 12:17:51 +02003100
3101 await asyncio.wait_for(
3102 self.k8scluster_map[k8sclustertype].exec_primitive(
3103 cluster_uuid=k8s_instance_info["k8scluster-uuid"],
3104 kdu_instance=kdu_instance,
3105 primitive_name=initial_config_primitive["name"],
garciadeblas5697b8b2021-03-24 09:17:02 +01003106 params=primitive_params_,
3107 db_dict=db_dict_install,
David Garciac1fe90a2021-03-31 19:12:02 +02003108 vca_id=vca_id,
3109 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01003110 timeout=timeout,
David Garciac1fe90a2021-03-31 19:12:02 +02003111 )
Dominik Fleischmannc1975dd2020-08-19 12:17:51 +02003112
tiernob9018152020-04-16 14:18:24 +00003113 except Exception as e:
lloretgalleg7c121132020-07-08 07:53:22 +00003114 # Prepare update db with error and raise exception
tiernob9018152020-04-16 14:18:24 +00003115 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01003116 self.update_db_2(
3117 "nsrs", nsr_id, {nsr_db_path + ".detailed-status": str(e)}
3118 )
3119 self.update_db_2(
3120 "vnfrs",
3121 vnfr_data.get("_id"),
3122 {"kdur.{}.status".format(kdu_index): "ERROR"},
3123 )
tiernob9018152020-04-16 14:18:24 +00003124 except Exception:
lloretgalleg7c121132020-07-08 07:53:22 +00003125 # ignore to keep original exception
tiernob9018152020-04-16 14:18:24 +00003126 pass
lloretgalleg7c121132020-07-08 07:53:22 +00003127 # reraise original error
3128 raise
3129
3130 return kdu_instance
tiernob9018152020-04-16 14:18:24 +00003131
garciadeblas5697b8b2021-03-24 09:17:02 +01003132 async def deploy_kdus(
3133 self,
3134 logging_text,
3135 nsr_id,
3136 nslcmop_id,
3137 db_vnfrs,
3138 db_vnfds,
3139 task_instantiation_info,
3140 ):
calvinosanch9f9c6f22019-11-04 13:37:39 +01003141 # Launch kdus if present in the descriptor
tierno626e0152019-11-29 14:16:16 +00003142
garciadeblas5697b8b2021-03-24 09:17:02 +01003143 k8scluster_id_2_uuic = {
3144 "helm-chart-v3": {},
3145 "helm-chart": {},
3146 "juju-bundle": {},
3147 }
tierno626e0152019-11-29 14:16:16 +00003148
tierno16f4a4e2020-07-20 09:05:51 +00003149 async def _get_cluster_id(cluster_id, cluster_type):
tierno626e0152019-11-29 14:16:16 +00003150 nonlocal k8scluster_id_2_uuic
3151 if cluster_id in k8scluster_id_2_uuic[cluster_type]:
3152 return k8scluster_id_2_uuic[cluster_type][cluster_id]
3153
tierno16f4a4e2020-07-20 09:05:51 +00003154 # check if K8scluster is creating and wait look if previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +01003155 task_name, task_dependency = self.lcm_tasks.lookfor_related(
3156 "k8scluster", cluster_id
3157 )
tierno16f4a4e2020-07-20 09:05:51 +00003158 if task_dependency:
garciadeblas5697b8b2021-03-24 09:17:02 +01003159 text = "Waiting for related tasks '{}' on k8scluster {} to be completed".format(
3160 task_name, cluster_id
3161 )
tierno16f4a4e2020-07-20 09:05:51 +00003162 self.logger.debug(logging_text + text)
3163 await asyncio.wait(task_dependency, timeout=3600)
3164
garciadeblas5697b8b2021-03-24 09:17:02 +01003165 db_k8scluster = self.db.get_one(
3166 "k8sclusters", {"_id": cluster_id}, fail_on_empty=False
3167 )
tierno626e0152019-11-29 14:16:16 +00003168 if not db_k8scluster:
3169 raise LcmException("K8s cluster {} cannot be found".format(cluster_id))
tierno16f4a4e2020-07-20 09:05:51 +00003170
tierno626e0152019-11-29 14:16:16 +00003171 k8s_id = deep_get(db_k8scluster, ("_admin", cluster_type, "id"))
3172 if not k8s_id:
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003173 if cluster_type == "helm-chart-v3":
3174 try:
3175 # backward compatibility for existing clusters that have not been initialized for helm v3
garciadeblas5697b8b2021-03-24 09:17:02 +01003176 k8s_credentials = yaml.safe_dump(
3177 db_k8scluster.get("credentials")
3178 )
3179 k8s_id, uninstall_sw = await self.k8sclusterhelm3.init_env(
3180 k8s_credentials, reuse_cluster_uuid=cluster_id
3181 )
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003182 db_k8scluster_update = {}
3183 db_k8scluster_update["_admin.helm-chart-v3.error_msg"] = None
3184 db_k8scluster_update["_admin.helm-chart-v3.id"] = k8s_id
garciadeblas5697b8b2021-03-24 09:17:02 +01003185 db_k8scluster_update[
3186 "_admin.helm-chart-v3.created"
3187 ] = uninstall_sw
3188 db_k8scluster_update[
3189 "_admin.helm-chart-v3.operationalState"
3190 ] = "ENABLED"
3191 self.update_db_2(
3192 "k8sclusters", cluster_id, db_k8scluster_update
3193 )
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003194 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01003195 self.logger.error(
3196 logging_text
3197 + "error initializing helm-v3 cluster: {}".format(str(e))
3198 )
3199 raise LcmException(
3200 "K8s cluster '{}' has not been initialized for '{}'".format(
3201 cluster_id, cluster_type
3202 )
3203 )
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003204 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01003205 raise LcmException(
3206 "K8s cluster '{}' has not been initialized for '{}'".format(
3207 cluster_id, cluster_type
3208 )
3209 )
tierno626e0152019-11-29 14:16:16 +00003210 k8scluster_id_2_uuic[cluster_type][cluster_id] = k8s_id
3211 return k8s_id
3212
3213 logging_text += "Deploy kdus: "
tiernoe876f672020-02-13 14:34:48 +00003214 step = ""
calvinosanch9f9c6f22019-11-04 13:37:39 +01003215 try:
tierno626e0152019-11-29 14:16:16 +00003216 db_nsr_update = {"_admin.deployed.K8s": []}
calvinosanch9f9c6f22019-11-04 13:37:39 +01003217 self.update_db_2("nsrs", nsr_id, db_nsr_update)
calvinosanch9f9c6f22019-11-04 13:37:39 +01003218
tierno626e0152019-11-29 14:16:16 +00003219 index = 0
tiernoe876f672020-02-13 14:34:48 +00003220 updated_cluster_list = []
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003221 updated_v3_cluster_list = []
tiernoe876f672020-02-13 14:34:48 +00003222
tierno626e0152019-11-29 14:16:16 +00003223 for vnfr_data in db_vnfrs.values():
David Garciac1fe90a2021-03-31 19:12:02 +02003224 vca_id = self.get_vca_id(vnfr_data, {})
lloretgalleg7c121132020-07-08 07:53:22 +00003225 for kdu_index, kdur in enumerate(get_iterable(vnfr_data, "kdur")):
3226 # Step 0: Prepare and set parameters
bravof922c4172020-11-24 21:21:43 -03003227 desc_params = parse_yaml_strings(kdur.get("additionalParams"))
garciadeblas5697b8b2021-03-24 09:17:02 +01003228 vnfd_id = vnfr_data.get("vnfd-id")
3229 vnfd_with_id = find_in_list(
3230 db_vnfds, lambda vnfd: vnfd["_id"] == vnfd_id
3231 )
3232 kdud = next(
3233 kdud
3234 for kdud in vnfd_with_id["kdu"]
3235 if kdud["name"] == kdur["kdu-name"]
3236 )
tiernode1584f2020-04-07 09:07:33 +00003237 namespace = kdur.get("k8s-namespace")
romeromonser4e71ab62021-05-28 12:06:34 +02003238 kdu_deployment_name = kdur.get("kdu-deployment-name")
tierno626e0152019-11-29 14:16:16 +00003239 if kdur.get("helm-chart"):
lloretgalleg07e53f52020-12-15 10:54:02 +00003240 kdumodel = kdur["helm-chart"]
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003241 # Default version: helm3, if helm-version is v2 assign v2
3242 k8sclustertype = "helm-chart-v3"
3243 self.logger.debug("kdur: {}".format(kdur))
garciadeblas5697b8b2021-03-24 09:17:02 +01003244 if (
3245 kdur.get("helm-version")
3246 and kdur.get("helm-version") == "v2"
3247 ):
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003248 k8sclustertype = "helm-chart"
tierno626e0152019-11-29 14:16:16 +00003249 elif kdur.get("juju-bundle"):
lloretgalleg07e53f52020-12-15 10:54:02 +00003250 kdumodel = kdur["juju-bundle"]
tiernoe876f672020-02-13 14:34:48 +00003251 k8sclustertype = "juju-bundle"
tierno626e0152019-11-29 14:16:16 +00003252 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01003253 raise LcmException(
3254 "kdu type for kdu='{}.{}' is neither helm-chart nor "
3255 "juju-bundle. Maybe an old NBI version is running".format(
3256 vnfr_data["member-vnf-index-ref"], kdur["kdu-name"]
3257 )
3258 )
quilesjacde94f2020-01-23 10:07:08 +00003259 # check if kdumodel is a file and exists
3260 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01003261 vnfd_with_id = find_in_list(
3262 db_vnfds, lambda vnfd: vnfd["_id"] == vnfd_id
3263 )
3264 storage = deep_get(vnfd_with_id, ("_admin", "storage"))
3265 if storage and storage.get(
3266 "pkg-dir"
3267 ): # may be not present if vnfd has not artifacts
tierno51183952020-04-03 15:48:18 +00003268 # path format: /vnfdid/pkkdir/helm-charts|juju-bundles/kdumodel
garciadeblas5697b8b2021-03-24 09:17:02 +01003269 filename = "{}/{}/{}s/{}".format(
3270 storage["folder"],
3271 storage["pkg-dir"],
3272 k8sclustertype,
3273 kdumodel,
3274 )
3275 if self.fs.file_exists(
3276 filename, mode="file"
3277 ) or self.fs.file_exists(filename, mode="dir"):
tierno51183952020-04-03 15:48:18 +00003278 kdumodel = self.fs.path + filename
3279 except (asyncio.TimeoutError, asyncio.CancelledError):
tiernoe876f672020-02-13 14:34:48 +00003280 raise
garciadeblas5697b8b2021-03-24 09:17:02 +01003281 except Exception: # it is not a file
quilesjacde94f2020-01-23 10:07:08 +00003282 pass
lloretgallegedc5f332020-02-20 11:50:50 +01003283
tiernoe876f672020-02-13 14:34:48 +00003284 k8s_cluster_id = kdur["k8s-cluster"]["id"]
garciadeblas5697b8b2021-03-24 09:17:02 +01003285 step = "Synchronize repos for k8s cluster '{}'".format(
3286 k8s_cluster_id
3287 )
tierno16f4a4e2020-07-20 09:05:51 +00003288 cluster_uuid = await _get_cluster_id(k8s_cluster_id, k8sclustertype)
lloretgallegedc5f332020-02-20 11:50:50 +01003289
lloretgalleg7c121132020-07-08 07:53:22 +00003290 # Synchronize repos
garciadeblas5697b8b2021-03-24 09:17:02 +01003291 if (
3292 k8sclustertype == "helm-chart"
3293 and cluster_uuid not in updated_cluster_list
3294 ) or (
3295 k8sclustertype == "helm-chart-v3"
3296 and cluster_uuid not in updated_v3_cluster_list
3297 ):
tiernoe876f672020-02-13 14:34:48 +00003298 del_repo_list, added_repo_dict = await asyncio.ensure_future(
garciadeblas5697b8b2021-03-24 09:17:02 +01003299 self.k8scluster_map[k8sclustertype].synchronize_repos(
3300 cluster_uuid=cluster_uuid
3301 )
3302 )
tiernoe876f672020-02-13 14:34:48 +00003303 if del_repo_list or added_repo_dict:
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003304 if k8sclustertype == "helm-chart":
garciadeblas5697b8b2021-03-24 09:17:02 +01003305 unset = {
3306 "_admin.helm_charts_added." + item: None
3307 for item in del_repo_list
3308 }
3309 updated = {
3310 "_admin.helm_charts_added." + item: name
3311 for item, name in added_repo_dict.items()
3312 }
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003313 updated_cluster_list.append(cluster_uuid)
3314 elif k8sclustertype == "helm-chart-v3":
garciadeblas5697b8b2021-03-24 09:17:02 +01003315 unset = {
3316 "_admin.helm_charts_v3_added." + item: None
3317 for item in del_repo_list
3318 }
3319 updated = {
3320 "_admin.helm_charts_v3_added." + item: name
3321 for item, name in added_repo_dict.items()
3322 }
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003323 updated_v3_cluster_list.append(cluster_uuid)
garciadeblas5697b8b2021-03-24 09:17:02 +01003324 self.logger.debug(
3325 logging_text + "repos synchronized on k8s cluster "
3326 "'{}' to_delete: {}, to_add: {}".format(
3327 k8s_cluster_id, del_repo_list, added_repo_dict
3328 )
3329 )
3330 self.db.set_one(
3331 "k8sclusters",
3332 {"_id": k8s_cluster_id},
3333 updated,
3334 unset=unset,
3335 )
lloretgallegedc5f332020-02-20 11:50:50 +01003336
lloretgalleg7c121132020-07-08 07:53:22 +00003337 # Instantiate kdu
garciadeblas5697b8b2021-03-24 09:17:02 +01003338 step = "Instantiating KDU {}.{} in k8s cluster {}".format(
3339 vnfr_data["member-vnf-index-ref"],
3340 kdur["kdu-name"],
3341 k8s_cluster_id,
3342 )
3343 k8s_instance_info = {
3344 "kdu-instance": None,
3345 "k8scluster-uuid": cluster_uuid,
3346 "k8scluster-type": k8sclustertype,
3347 "member-vnf-index": vnfr_data["member-vnf-index-ref"],
3348 "kdu-name": kdur["kdu-name"],
3349 "kdu-model": kdumodel,
3350 "namespace": namespace,
romeromonser4e71ab62021-05-28 12:06:34 +02003351 "kdu-deployment-name": kdu_deployment_name,
garciadeblas5697b8b2021-03-24 09:17:02 +01003352 }
tiernob9018152020-04-16 14:18:24 +00003353 db_path = "_admin.deployed.K8s.{}".format(index)
lloretgalleg7c121132020-07-08 07:53:22 +00003354 db_nsr_update[db_path] = k8s_instance_info
tierno626e0152019-11-29 14:16:16 +00003355 self.update_db_2("nsrs", nsr_id, db_nsr_update)
garciadeblas5697b8b2021-03-24 09:17:02 +01003356 vnfd_with_id = find_in_list(
3357 db_vnfds, lambda vnf: vnf["_id"] == vnfd_id
3358 )
tiernoa2143262020-03-27 16:20:40 +00003359 task = asyncio.ensure_future(
garciadeblas5697b8b2021-03-24 09:17:02 +01003360 self._install_kdu(
3361 nsr_id,
3362 db_path,
3363 vnfr_data,
3364 kdu_index,
3365 kdud,
3366 vnfd_with_id,
3367 k8s_instance_info,
3368 k8params=desc_params,
Alexis Romero1b9c6ab2022-05-17 18:18:02 +02003369 timeout=1800,
garciadeblas5697b8b2021-03-24 09:17:02 +01003370 vca_id=vca_id,
3371 )
3372 )
3373 self.lcm_tasks.register(
3374 "ns",
3375 nsr_id,
3376 nslcmop_id,
3377 "instantiate_KDU-{}".format(index),
3378 task,
3379 )
3380 task_instantiation_info[task] = "Deploying KDU {}".format(
3381 kdur["kdu-name"]
3382 )
tiernoe876f672020-02-13 14:34:48 +00003383
tierno626e0152019-11-29 14:16:16 +00003384 index += 1
quilesjdd799ac2020-01-23 16:31:11 +00003385
tiernoe876f672020-02-13 14:34:48 +00003386 except (LcmException, asyncio.CancelledError):
3387 raise
calvinosanch9f9c6f22019-11-04 13:37:39 +01003388 except Exception as e:
tiernoe876f672020-02-13 14:34:48 +00003389 msg = "Exception {} while {}: {}".format(type(e).__name__, step, e)
3390 if isinstance(e, (N2VCException, DbException)):
3391 self.logger.error(logging_text + msg)
3392 else:
3393 self.logger.critical(logging_text + msg, exc_info=True)
quilesjdd799ac2020-01-23 16:31:11 +00003394 raise LcmException(msg)
calvinosanch9f9c6f22019-11-04 13:37:39 +01003395 finally:
calvinosanch9f9c6f22019-11-04 13:37:39 +01003396 if db_nsr_update:
3397 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernoda6fb102019-11-23 00:36:52 +00003398
garciadeblas5697b8b2021-03-24 09:17:02 +01003399 def _deploy_n2vc(
3400 self,
3401 logging_text,
3402 db_nsr,
3403 db_vnfr,
3404 nslcmop_id,
3405 nsr_id,
3406 nsi_id,
3407 vnfd_id,
3408 vdu_id,
3409 kdu_name,
3410 member_vnf_index,
3411 vdu_index,
3412 vdu_name,
3413 deploy_params,
3414 descriptor_config,
3415 base_folder,
3416 task_instantiation_info,
3417 stage,
3418 ):
quilesj7e13aeb2019-10-08 13:34:55 +02003419 # launch instantiate_N2VC in a asyncio task and register task object
3420 # Look where information of this charm is at database <nsrs>._admin.deployed.VCA
3421 # if not found, create one entry and update database
quilesj7e13aeb2019-10-08 13:34:55 +02003422 # fill db_nsr._admin.deployed.VCA.<index>
tierno588547c2020-07-01 15:30:20 +00003423
garciadeblas5697b8b2021-03-24 09:17:02 +01003424 self.logger.debug(
3425 logging_text + "_deploy_n2vc vnfd_id={}, vdu_id={}".format(vnfd_id, vdu_id)
3426 )
bravof9a256db2021-02-22 18:02:07 -03003427 if "execution-environment-list" in descriptor_config:
3428 ee_list = descriptor_config.get("execution-environment-list", [])
David Garciab76442a2021-05-28 12:08:18 +02003429 elif "juju" in descriptor_config:
3430 ee_list = [descriptor_config] # ns charms
tierno588547c2020-07-01 15:30:20 +00003431 else: # other types as script are not supported
3432 ee_list = []
3433
3434 for ee_item in ee_list:
garciadeblas5697b8b2021-03-24 09:17:02 +01003435 self.logger.debug(
3436 logging_text
3437 + "_deploy_n2vc ee_item juju={}, helm={}".format(
3438 ee_item.get("juju"), ee_item.get("helm-chart")
3439 )
3440 )
tiernoa278b842020-07-08 15:33:55 +00003441 ee_descriptor_id = ee_item.get("id")
tierno588547c2020-07-01 15:30:20 +00003442 if ee_item.get("juju"):
garciadeblas5697b8b2021-03-24 09:17:02 +01003443 vca_name = ee_item["juju"].get("charm")
3444 vca_type = (
3445 "lxc_proxy_charm"
3446 if ee_item["juju"].get("charm") is not None
3447 else "native_charm"
3448 )
3449 if ee_item["juju"].get("cloud") == "k8s":
tierno588547c2020-07-01 15:30:20 +00003450 vca_type = "k8s_proxy_charm"
garciadeblas5697b8b2021-03-24 09:17:02 +01003451 elif ee_item["juju"].get("proxy") is False:
tierno588547c2020-07-01 15:30:20 +00003452 vca_type = "native_charm"
3453 elif ee_item.get("helm-chart"):
garciadeblas5697b8b2021-03-24 09:17:02 +01003454 vca_name = ee_item["helm-chart"]
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003455 if ee_item.get("helm-version") and ee_item.get("helm-version") == "v2":
3456 vca_type = "helm"
3457 else:
3458 vca_type = "helm-v3"
tierno588547c2020-07-01 15:30:20 +00003459 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01003460 self.logger.debug(
3461 logging_text + "skipping non juju neither charm configuration"
3462 )
quilesj7e13aeb2019-10-08 13:34:55 +02003463 continue
quilesj3655ae02019-12-12 16:08:35 +00003464
tierno588547c2020-07-01 15:30:20 +00003465 vca_index = -1
garciadeblas5697b8b2021-03-24 09:17:02 +01003466 for vca_index, vca_deployed in enumerate(
3467 db_nsr["_admin"]["deployed"]["VCA"]
3468 ):
tierno588547c2020-07-01 15:30:20 +00003469 if not vca_deployed:
3470 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01003471 if (
3472 vca_deployed.get("member-vnf-index") == member_vnf_index
3473 and vca_deployed.get("vdu_id") == vdu_id
3474 and vca_deployed.get("kdu_name") == kdu_name
3475 and vca_deployed.get("vdu_count_index", 0) == vdu_index
3476 and vca_deployed.get("ee_descriptor_id") == ee_descriptor_id
3477 ):
tierno588547c2020-07-01 15:30:20 +00003478 break
3479 else:
3480 # not found, create one.
garciadeblas5697b8b2021-03-24 09:17:02 +01003481 target = (
3482 "ns" if not member_vnf_index else "vnf/{}".format(member_vnf_index)
3483 )
tiernoa278b842020-07-08 15:33:55 +00003484 if vdu_id:
3485 target += "/vdu/{}/{}".format(vdu_id, vdu_index or 0)
3486 elif kdu_name:
3487 target += "/kdu/{}".format(kdu_name)
tierno588547c2020-07-01 15:30:20 +00003488 vca_deployed = {
tiernoa278b842020-07-08 15:33:55 +00003489 "target_element": target,
3490 # ^ target_element will replace member-vnf-index, kdu_name, vdu_id ... in a single string
tierno588547c2020-07-01 15:30:20 +00003491 "member-vnf-index": member_vnf_index,
3492 "vdu_id": vdu_id,
3493 "kdu_name": kdu_name,
3494 "vdu_count_index": vdu_index,
3495 "operational-status": "init", # TODO revise
3496 "detailed-status": "", # TODO revise
garciadeblas5697b8b2021-03-24 09:17:02 +01003497 "step": "initial-deploy", # TODO revise
tierno588547c2020-07-01 15:30:20 +00003498 "vnfd_id": vnfd_id,
3499 "vdu_name": vdu_name,
tiernoa278b842020-07-08 15:33:55 +00003500 "type": vca_type,
garciadeblas5697b8b2021-03-24 09:17:02 +01003501 "ee_descriptor_id": ee_descriptor_id,
tierno588547c2020-07-01 15:30:20 +00003502 }
3503 vca_index += 1
quilesj3655ae02019-12-12 16:08:35 +00003504
tierno588547c2020-07-01 15:30:20 +00003505 # create VCA and configurationStatus in db
3506 db_dict = {
3507 "_admin.deployed.VCA.{}".format(vca_index): vca_deployed,
garciadeblas5697b8b2021-03-24 09:17:02 +01003508 "configurationStatus.{}".format(vca_index): dict(),
tierno588547c2020-07-01 15:30:20 +00003509 }
3510 self.update_db_2("nsrs", nsr_id, db_dict)
quilesj7e13aeb2019-10-08 13:34:55 +02003511
tierno588547c2020-07-01 15:30:20 +00003512 db_nsr["_admin"]["deployed"]["VCA"].append(vca_deployed)
3513
bravof922c4172020-11-24 21:21:43 -03003514 self.logger.debug("N2VC > NSR_ID > {}".format(nsr_id))
3515 self.logger.debug("N2VC > DB_NSR > {}".format(db_nsr))
3516 self.logger.debug("N2VC > VCA_DEPLOYED > {}".format(vca_deployed))
3517
tierno588547c2020-07-01 15:30:20 +00003518 # Launch task
3519 task_n2vc = asyncio.ensure_future(
3520 self.instantiate_N2VC(
3521 logging_text=logging_text,
3522 vca_index=vca_index,
3523 nsi_id=nsi_id,
3524 db_nsr=db_nsr,
3525 db_vnfr=db_vnfr,
3526 vdu_id=vdu_id,
3527 kdu_name=kdu_name,
3528 vdu_index=vdu_index,
3529 deploy_params=deploy_params,
3530 config_descriptor=descriptor_config,
3531 base_folder=base_folder,
3532 nslcmop_id=nslcmop_id,
3533 stage=stage,
3534 vca_type=vca_type,
tiernob996d942020-07-03 14:52:28 +00003535 vca_name=vca_name,
garciadeblas5697b8b2021-03-24 09:17:02 +01003536 ee_config_descriptor=ee_item,
tierno588547c2020-07-01 15:30:20 +00003537 )
quilesj7e13aeb2019-10-08 13:34:55 +02003538 )
garciadeblas5697b8b2021-03-24 09:17:02 +01003539 self.lcm_tasks.register(
3540 "ns",
3541 nsr_id,
3542 nslcmop_id,
3543 "instantiate_N2VC-{}".format(vca_index),
3544 task_n2vc,
3545 )
3546 task_instantiation_info[
3547 task_n2vc
3548 ] = self.task_name_deploy_vca + " {}.{}".format(
3549 member_vnf_index or "", vdu_id or ""
3550 )
tiernobaa51102018-12-14 13:16:18 +00003551
tiernoc9556972019-07-05 15:25:25 +00003552 @staticmethod
kuuse0ca67472019-05-13 15:59:27 +02003553 def _create_nslcmop(nsr_id, operation, params):
3554 """
3555 Creates a ns-lcm-opp content to be stored at database.
3556 :param nsr_id: internal id of the instance
3557 :param operation: instantiate, terminate, scale, action, ...
3558 :param params: user parameters for the operation
3559 :return: dictionary following SOL005 format
3560 """
3561 # Raise exception if invalid arguments
3562 if not (nsr_id and operation and params):
3563 raise LcmException(
garciadeblas5697b8b2021-03-24 09:17:02 +01003564 "Parameters 'nsr_id', 'operation' and 'params' needed to create primitive not provided"
3565 )
kuuse0ca67472019-05-13 15:59:27 +02003566 now = time()
3567 _id = str(uuid4())
3568 nslcmop = {
3569 "id": _id,
3570 "_id": _id,
3571 # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
3572 "operationState": "PROCESSING",
3573 "statusEnteredTime": now,
3574 "nsInstanceId": nsr_id,
3575 "lcmOperationType": operation,
3576 "startTime": now,
3577 "isAutomaticInvocation": False,
3578 "operationParams": params,
3579 "isCancelPending": False,
3580 "links": {
3581 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
3582 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01003583 },
kuuse0ca67472019-05-13 15:59:27 +02003584 }
3585 return nslcmop
3586
calvinosanch9f9c6f22019-11-04 13:37:39 +01003587 def _format_additional_params(self, params):
tierno626e0152019-11-29 14:16:16 +00003588 params = params or {}
calvinosanch9f9c6f22019-11-04 13:37:39 +01003589 for key, value in params.items():
3590 if str(value).startswith("!!yaml "):
3591 params[key] = yaml.safe_load(value[7:])
calvinosanch9f9c6f22019-11-04 13:37:39 +01003592 return params
3593
kuuse8b998e42019-07-30 15:22:16 +02003594 def _get_terminate_primitive_params(self, seq, vnf_index):
garciadeblas5697b8b2021-03-24 09:17:02 +01003595 primitive = seq.get("name")
kuuse8b998e42019-07-30 15:22:16 +02003596 primitive_params = {}
3597 params = {
3598 "member_vnf_index": vnf_index,
3599 "primitive": primitive,
3600 "primitive_params": primitive_params,
3601 }
3602 desc_params = {}
3603 return self._map_primitive_params(seq, params, desc_params)
3604
kuuseac3a8882019-10-03 10:48:06 +02003605 # sub-operations
3606
tierno51183952020-04-03 15:48:18 +00003607 def _retry_or_skip_suboperation(self, db_nslcmop, op_index):
garciadeblas5697b8b2021-03-24 09:17:02 +01003608 op = deep_get(db_nslcmop, ("_admin", "operations"), [])[op_index]
3609 if op.get("operationState") == "COMPLETED":
kuuseac3a8882019-10-03 10:48:06 +02003610 # b. Skip sub-operation
3611 # _ns_execute_primitive() or RO.create_action() will NOT be executed
3612 return self.SUBOPERATION_STATUS_SKIP
3613 else:
tierno7c4e24c2020-05-13 08:41:35 +00003614 # c. retry executing sub-operation
kuuseac3a8882019-10-03 10:48:06 +02003615 # The sub-operation exists, and operationState != 'COMPLETED'
tierno7c4e24c2020-05-13 08:41:35 +00003616 # Update operationState = 'PROCESSING' to indicate a retry.
garciadeblas5697b8b2021-03-24 09:17:02 +01003617 operationState = "PROCESSING"
3618 detailed_status = "In progress"
kuuseac3a8882019-10-03 10:48:06 +02003619 self._update_suboperation_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01003620 db_nslcmop, op_index, operationState, detailed_status
3621 )
kuuseac3a8882019-10-03 10:48:06 +02003622 # Return the sub-operation index
3623 # _ns_execute_primitive() or RO.create_action() will be called from scale()
3624 # with arguments extracted from the sub-operation
3625 return op_index
3626
3627 # Find a sub-operation where all keys in a matching dictionary must match
3628 # Returns the index of the matching sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if no match
3629 def _find_suboperation(self, db_nslcmop, match):
tierno7c4e24c2020-05-13 08:41:35 +00003630 if db_nslcmop and match:
garciadeblas5697b8b2021-03-24 09:17:02 +01003631 op_list = db_nslcmop.get("_admin", {}).get("operations", [])
kuuseac3a8882019-10-03 10:48:06 +02003632 for i, op in enumerate(op_list):
3633 if all(op.get(k) == match[k] for k in match):
3634 return i
3635 return self.SUBOPERATION_STATUS_NOT_FOUND
3636
3637 # Update status for a sub-operation given its index
garciadeblas5697b8b2021-03-24 09:17:02 +01003638 def _update_suboperation_status(
3639 self, db_nslcmop, op_index, operationState, detailed_status
3640 ):
kuuseac3a8882019-10-03 10:48:06 +02003641 # Update DB for HA tasks
garciadeblas5697b8b2021-03-24 09:17:02 +01003642 q_filter = {"_id": db_nslcmop["_id"]}
3643 update_dict = {
3644 "_admin.operations.{}.operationState".format(op_index): operationState,
3645 "_admin.operations.{}.detailed-status".format(op_index): detailed_status,
3646 }
3647 self.db.set_one(
3648 "nslcmops", q_filter=q_filter, update_dict=update_dict, fail_on_empty=False
3649 )
kuuseac3a8882019-10-03 10:48:06 +02003650
3651 # Add sub-operation, return the index of the added sub-operation
3652 # Optionally, set operationState, detailed-status, and operationType
3653 # Status and type are currently set for 'scale' sub-operations:
3654 # 'operationState' : 'PROCESSING' | 'COMPLETED' | 'FAILED'
3655 # 'detailed-status' : status message
3656 # 'operationType': may be any type, in the case of scaling: 'PRE-SCALE' | 'POST-SCALE'
3657 # Status and operation type are currently only used for 'scale', but NOT for 'terminate' sub-operations.
garciadeblas5697b8b2021-03-24 09:17:02 +01003658 def _add_suboperation(
3659 self,
3660 db_nslcmop,
3661 vnf_index,
3662 vdu_id,
3663 vdu_count_index,
3664 vdu_name,
3665 primitive,
3666 mapped_primitive_params,
3667 operationState=None,
3668 detailed_status=None,
3669 operationType=None,
3670 RO_nsr_id=None,
3671 RO_scaling_info=None,
3672 ):
tiernoe876f672020-02-13 14:34:48 +00003673 if not db_nslcmop:
kuuseac3a8882019-10-03 10:48:06 +02003674 return self.SUBOPERATION_STATUS_NOT_FOUND
3675 # Get the "_admin.operations" list, if it exists
garciadeblas5697b8b2021-03-24 09:17:02 +01003676 db_nslcmop_admin = db_nslcmop.get("_admin", {})
3677 op_list = db_nslcmop_admin.get("operations")
kuuseac3a8882019-10-03 10:48:06 +02003678 # Create or append to the "_admin.operations" list
garciadeblas5697b8b2021-03-24 09:17:02 +01003679 new_op = {
3680 "member_vnf_index": vnf_index,
3681 "vdu_id": vdu_id,
3682 "vdu_count_index": vdu_count_index,
3683 "primitive": primitive,
3684 "primitive_params": mapped_primitive_params,
3685 }
kuuseac3a8882019-10-03 10:48:06 +02003686 if operationState:
garciadeblas5697b8b2021-03-24 09:17:02 +01003687 new_op["operationState"] = operationState
kuuseac3a8882019-10-03 10:48:06 +02003688 if detailed_status:
garciadeblas5697b8b2021-03-24 09:17:02 +01003689 new_op["detailed-status"] = detailed_status
kuuseac3a8882019-10-03 10:48:06 +02003690 if operationType:
garciadeblas5697b8b2021-03-24 09:17:02 +01003691 new_op["lcmOperationType"] = operationType
kuuseac3a8882019-10-03 10:48:06 +02003692 if RO_nsr_id:
garciadeblas5697b8b2021-03-24 09:17:02 +01003693 new_op["RO_nsr_id"] = RO_nsr_id
kuuseac3a8882019-10-03 10:48:06 +02003694 if RO_scaling_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01003695 new_op["RO_scaling_info"] = RO_scaling_info
kuuseac3a8882019-10-03 10:48:06 +02003696 if not op_list:
3697 # No existing operations, create key 'operations' with current operation as first list element
garciadeblas5697b8b2021-03-24 09:17:02 +01003698 db_nslcmop_admin.update({"operations": [new_op]})
3699 op_list = db_nslcmop_admin.get("operations")
kuuseac3a8882019-10-03 10:48:06 +02003700 else:
3701 # Existing operations, append operation to list
3702 op_list.append(new_op)
kuuse8b998e42019-07-30 15:22:16 +02003703
garciadeblas5697b8b2021-03-24 09:17:02 +01003704 db_nslcmop_update = {"_admin.operations": op_list}
3705 self.update_db_2("nslcmops", db_nslcmop["_id"], db_nslcmop_update)
kuuseac3a8882019-10-03 10:48:06 +02003706 op_index = len(op_list) - 1
3707 return op_index
3708
3709 # Helper methods for scale() sub-operations
3710
3711 # pre-scale/post-scale:
3712 # Check for 3 different cases:
3713 # a. New: First time execution, return SUBOPERATION_STATUS_NEW
3714 # b. Skip: Existing sub-operation exists, operationState == 'COMPLETED', return SUBOPERATION_STATUS_SKIP
tierno7c4e24c2020-05-13 08:41:35 +00003715 # c. retry: Existing sub-operation exists, operationState != 'COMPLETED', return op_index to re-execute
garciadeblas5697b8b2021-03-24 09:17:02 +01003716 def _check_or_add_scale_suboperation(
3717 self,
3718 db_nslcmop,
3719 vnf_index,
3720 vnf_config_primitive,
3721 primitive_params,
3722 operationType,
3723 RO_nsr_id=None,
3724 RO_scaling_info=None,
3725 ):
kuuseac3a8882019-10-03 10:48:06 +02003726 # Find this sub-operation
tierno7c4e24c2020-05-13 08:41:35 +00003727 if RO_nsr_id and RO_scaling_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01003728 operationType = "SCALE-RO"
kuuseac3a8882019-10-03 10:48:06 +02003729 match = {
garciadeblas5697b8b2021-03-24 09:17:02 +01003730 "member_vnf_index": vnf_index,
3731 "RO_nsr_id": RO_nsr_id,
3732 "RO_scaling_info": RO_scaling_info,
kuuseac3a8882019-10-03 10:48:06 +02003733 }
3734 else:
3735 match = {
garciadeblas5697b8b2021-03-24 09:17:02 +01003736 "member_vnf_index": vnf_index,
3737 "primitive": vnf_config_primitive,
3738 "primitive_params": primitive_params,
3739 "lcmOperationType": operationType,
kuuseac3a8882019-10-03 10:48:06 +02003740 }
3741 op_index = self._find_suboperation(db_nslcmop, match)
tierno51183952020-04-03 15:48:18 +00003742 if op_index == self.SUBOPERATION_STATUS_NOT_FOUND:
kuuseac3a8882019-10-03 10:48:06 +02003743 # a. New sub-operation
3744 # The sub-operation does not exist, add it.
3745 # _ns_execute_primitive() will be called from scale() as usual, with non-modified arguments
3746 # The following parameters are set to None for all kind of scaling:
3747 vdu_id = None
3748 vdu_count_index = None
3749 vdu_name = None
tierno51183952020-04-03 15:48:18 +00003750 if RO_nsr_id and RO_scaling_info:
kuuseac3a8882019-10-03 10:48:06 +02003751 vnf_config_primitive = None
3752 primitive_params = None
3753 else:
3754 RO_nsr_id = None
3755 RO_scaling_info = None
3756 # Initial status for sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01003757 operationState = "PROCESSING"
3758 detailed_status = "In progress"
kuuseac3a8882019-10-03 10:48:06 +02003759 # Add sub-operation for pre/post-scaling (zero or more operations)
garciadeblas5697b8b2021-03-24 09:17:02 +01003760 self._add_suboperation(
3761 db_nslcmop,
3762 vnf_index,
3763 vdu_id,
3764 vdu_count_index,
3765 vdu_name,
3766 vnf_config_primitive,
3767 primitive_params,
3768 operationState,
3769 detailed_status,
3770 operationType,
3771 RO_nsr_id,
3772 RO_scaling_info,
3773 )
kuuseac3a8882019-10-03 10:48:06 +02003774 return self.SUBOPERATION_STATUS_NEW
3775 else:
3776 # Return either SUBOPERATION_STATUS_SKIP (operationState == 'COMPLETED'),
3777 # or op_index (operationState != 'COMPLETED')
tierno51183952020-04-03 15:48:18 +00003778 return self._retry_or_skip_suboperation(db_nslcmop, op_index)
kuuseac3a8882019-10-03 10:48:06 +02003779
preethika.pdf7d8e02019-12-10 13:10:48 +00003780 # Function to return execution_environment id
3781
3782 def _get_ee_id(self, vnf_index, vdu_id, vca_deployed_list):
tiernoe876f672020-02-13 14:34:48 +00003783 # TODO vdu_index_count
preethika.pdf7d8e02019-12-10 13:10:48 +00003784 for vca in vca_deployed_list:
3785 if vca["member-vnf-index"] == vnf_index and vca["vdu_id"] == vdu_id:
3786 return vca["ee_id"]
3787
David Garciac1fe90a2021-03-31 19:12:02 +02003788 async def destroy_N2VC(
3789 self,
3790 logging_text,
3791 db_nslcmop,
3792 vca_deployed,
3793 config_descriptor,
3794 vca_index,
3795 destroy_ee=True,
3796 exec_primitives=True,
3797 scaling_in=False,
3798 vca_id: str = None,
3799 ):
tiernoe876f672020-02-13 14:34:48 +00003800 """
3801 Execute the terminate primitives and destroy the execution environment (if destroy_ee=False
3802 :param logging_text:
3803 :param db_nslcmop:
3804 :param vca_deployed: Dictionary of deployment info at db_nsr._admin.depoloyed.VCA.<INDEX>
3805 :param config_descriptor: Configuration descriptor of the NSD, VNFD, VNFD.vdu or VNFD.kdu
3806 :param vca_index: index in the database _admin.deployed.VCA
3807 :param destroy_ee: False to do not destroy, because it will be destroyed all of then at once
tierno588547c2020-07-01 15:30:20 +00003808 :param exec_primitives: False to do not execute terminate primitives, because the config is not completed or has
3809 not executed properly
aktas13251562021-02-12 22:19:10 +03003810 :param scaling_in: True destroys the application, False destroys the model
tiernoe876f672020-02-13 14:34:48 +00003811 :return: None or exception
3812 """
tiernoe876f672020-02-13 14:34:48 +00003813
tierno588547c2020-07-01 15:30:20 +00003814 self.logger.debug(
garciadeblas5697b8b2021-03-24 09:17:02 +01003815 logging_text
3816 + " vca_index: {}, vca_deployed: {}, config_descriptor: {}, destroy_ee: {}".format(
tierno588547c2020-07-01 15:30:20 +00003817 vca_index, vca_deployed, config_descriptor, destroy_ee
3818 )
3819 )
3820
3821 vca_type = vca_deployed.get("type", "lxc_proxy_charm")
3822
3823 # execute terminate_primitives
3824 if exec_primitives:
bravof922c4172020-11-24 21:21:43 -03003825 terminate_primitives = get_ee_sorted_terminate_config_primitive_list(
garciadeblas5697b8b2021-03-24 09:17:02 +01003826 config_descriptor.get("terminate-config-primitive"),
3827 vca_deployed.get("ee_descriptor_id"),
3828 )
tierno588547c2020-07-01 15:30:20 +00003829 vdu_id = vca_deployed.get("vdu_id")
3830 vdu_count_index = vca_deployed.get("vdu_count_index")
3831 vdu_name = vca_deployed.get("vdu_name")
3832 vnf_index = vca_deployed.get("member-vnf-index")
3833 if terminate_primitives and vca_deployed.get("needed_terminate"):
tierno588547c2020-07-01 15:30:20 +00003834 for seq in terminate_primitives:
3835 # For each sequence in list, get primitive and call _ns_execute_primitive()
3836 step = "Calling terminate action for vnf_member_index={} primitive={}".format(
garciadeblas5697b8b2021-03-24 09:17:02 +01003837 vnf_index, seq.get("name")
3838 )
tierno588547c2020-07-01 15:30:20 +00003839 self.logger.debug(logging_text + step)
3840 # Create the primitive for each sequence, i.e. "primitive": "touch"
garciadeblas5697b8b2021-03-24 09:17:02 +01003841 primitive = seq.get("name")
3842 mapped_primitive_params = self._get_terminate_primitive_params(
3843 seq, vnf_index
3844 )
tierno588547c2020-07-01 15:30:20 +00003845
3846 # Add sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01003847 self._add_suboperation(
3848 db_nslcmop,
3849 vnf_index,
3850 vdu_id,
3851 vdu_count_index,
3852 vdu_name,
3853 primitive,
3854 mapped_primitive_params,
3855 )
tierno588547c2020-07-01 15:30:20 +00003856 # Sub-operations: Call _ns_execute_primitive() instead of action()
3857 try:
David Garciac1fe90a2021-03-31 19:12:02 +02003858 result, result_detail = await self._ns_execute_primitive(
garciadeblas5697b8b2021-03-24 09:17:02 +01003859 vca_deployed["ee_id"],
3860 primitive,
David Garciac1fe90a2021-03-31 19:12:02 +02003861 mapped_primitive_params,
3862 vca_type=vca_type,
3863 vca_id=vca_id,
3864 )
tierno588547c2020-07-01 15:30:20 +00003865 except LcmException:
3866 # this happens when VCA is not deployed. In this case it is not needed to terminate
3867 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01003868 result_ok = ["COMPLETED", "PARTIALLY_COMPLETED"]
tierno588547c2020-07-01 15:30:20 +00003869 if result not in result_ok:
garciadeblas5697b8b2021-03-24 09:17:02 +01003870 raise LcmException(
3871 "terminate_primitive {} for vnf_member_index={} fails with "
3872 "error {}".format(seq.get("name"), vnf_index, result_detail)
3873 )
tierno588547c2020-07-01 15:30:20 +00003874 # set that this VCA do not need terminated
garciadeblas5697b8b2021-03-24 09:17:02 +01003875 db_update_entry = "_admin.deployed.VCA.{}.needed_terminate".format(
3876 vca_index
3877 )
3878 self.update_db_2(
3879 "nsrs", db_nslcmop["nsInstanceId"], {db_update_entry: False}
3880 )
tiernoe876f672020-02-13 14:34:48 +00003881
tiernob996d942020-07-03 14:52:28 +00003882 if vca_deployed.get("prometheus_jobs") and self.prometheus:
3883 await self.prometheus.update(remove_jobs=vca_deployed["prometheus_jobs"])
3884
tiernoe876f672020-02-13 14:34:48 +00003885 if destroy_ee:
David Garciac1fe90a2021-03-31 19:12:02 +02003886 await self.vca_map[vca_type].delete_execution_environment(
3887 vca_deployed["ee_id"],
3888 scaling_in=scaling_in,
aktas730569b2021-07-29 17:42:49 +03003889 vca_type=vca_type,
David Garciac1fe90a2021-03-31 19:12:02 +02003890 vca_id=vca_id,
3891 )
kuuse0ca67472019-05-13 15:59:27 +02003892
David Garciac1fe90a2021-03-31 19:12:02 +02003893 async def _delete_all_N2VC(self, db_nsr: dict, vca_id: str = None):
garciadeblas5697b8b2021-03-24 09:17:02 +01003894 self._write_all_config_status(db_nsr=db_nsr, status="TERMINATING")
tierno51183952020-04-03 15:48:18 +00003895 namespace = "." + db_nsr["_id"]
tiernof59ad6c2020-04-08 12:50:52 +00003896 try:
David Garciac1fe90a2021-03-31 19:12:02 +02003897 await self.n2vc.delete_namespace(
3898 namespace=namespace,
3899 total_timeout=self.timeout_charm_delete,
3900 vca_id=vca_id,
3901 )
tiernof59ad6c2020-04-08 12:50:52 +00003902 except N2VCNotFound: # already deleted. Skip
3903 pass
garciadeblas5697b8b2021-03-24 09:17:02 +01003904 self._write_all_config_status(db_nsr=db_nsr, status="DELETED")
quilesj3655ae02019-12-12 16:08:35 +00003905
garciadeblas5697b8b2021-03-24 09:17:02 +01003906 async def _terminate_RO(
3907 self, logging_text, nsr_deployed, nsr_id, nslcmop_id, stage
3908 ):
tiernoe876f672020-02-13 14:34:48 +00003909 """
3910 Terminates a deployment from RO
3911 :param logging_text:
3912 :param nsr_deployed: db_nsr._admin.deployed
3913 :param nsr_id:
3914 :param nslcmop_id:
3915 :param stage: list of string with the content to write on db_nslcmop.detailed-status.
3916 this method will update only the index 2, but it will write on database the concatenated content of the list
3917 :return:
3918 """
3919 db_nsr_update = {}
3920 failed_detail = []
3921 ro_nsr_id = ro_delete_action = None
3922 if nsr_deployed and nsr_deployed.get("RO"):
3923 ro_nsr_id = nsr_deployed["RO"].get("nsr_id")
3924 ro_delete_action = nsr_deployed["RO"].get("nsr_delete_action_id")
3925 try:
3926 if ro_nsr_id:
3927 stage[2] = "Deleting ns from VIM."
3928 db_nsr_update["detailed-status"] = " ".join(stage)
3929 self._write_op_status(nslcmop_id, stage)
3930 self.logger.debug(logging_text + stage[2])
3931 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3932 self._write_op_status(nslcmop_id, stage)
3933 desc = await self.RO.delete("ns", ro_nsr_id)
3934 ro_delete_action = desc["action_id"]
garciadeblas5697b8b2021-03-24 09:17:02 +01003935 db_nsr_update[
3936 "_admin.deployed.RO.nsr_delete_action_id"
3937 ] = ro_delete_action
tiernoe876f672020-02-13 14:34:48 +00003938 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
3939 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
3940 if ro_delete_action:
3941 # wait until NS is deleted from VIM
3942 stage[2] = "Waiting ns deleted from VIM."
3943 detailed_status_old = None
garciadeblas5697b8b2021-03-24 09:17:02 +01003944 self.logger.debug(
3945 logging_text
3946 + stage[2]
3947 + " RO_id={} ro_delete_action={}".format(
3948 ro_nsr_id, ro_delete_action
3949 )
3950 )
tiernoe876f672020-02-13 14:34:48 +00003951 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3952 self._write_op_status(nslcmop_id, stage)
kuused124bfe2019-06-18 12:09:24 +02003953
tiernoe876f672020-02-13 14:34:48 +00003954 delete_timeout = 20 * 60 # 20 minutes
3955 while delete_timeout > 0:
3956 desc = await self.RO.show(
3957 "ns",
3958 item_id_name=ro_nsr_id,
3959 extra_item="action",
garciadeblas5697b8b2021-03-24 09:17:02 +01003960 extra_item_id=ro_delete_action,
3961 )
tiernoe876f672020-02-13 14:34:48 +00003962
3963 # deploymentStatus
3964 self._on_update_ro_db(nsrs_id=nsr_id, ro_descriptor=desc)
3965
3966 ns_status, ns_status_info = self.RO.check_action_status(desc)
3967 if ns_status == "ERROR":
3968 raise ROclient.ROClientException(ns_status_info)
3969 elif ns_status == "BUILD":
3970 stage[2] = "Deleting from VIM {}".format(ns_status_info)
3971 elif ns_status == "ACTIVE":
3972 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
3973 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
3974 break
3975 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01003976 assert (
3977 False
3978 ), "ROclient.check_action_status returns unknown {}".format(
3979 ns_status
3980 )
tiernoe876f672020-02-13 14:34:48 +00003981 if stage[2] != detailed_status_old:
3982 detailed_status_old = stage[2]
3983 db_nsr_update["detailed-status"] = " ".join(stage)
3984 self._write_op_status(nslcmop_id, stage)
3985 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3986 await asyncio.sleep(5, loop=self.loop)
3987 delete_timeout -= 5
3988 else: # delete_timeout <= 0:
garciadeblas5697b8b2021-03-24 09:17:02 +01003989 raise ROclient.ROClientException(
3990 "Timeout waiting ns deleted from VIM"
3991 )
tiernoe876f672020-02-13 14:34:48 +00003992
3993 except Exception as e:
3994 self.update_db_2("nsrs", nsr_id, db_nsr_update)
garciadeblas5697b8b2021-03-24 09:17:02 +01003995 if (
3996 isinstance(e, ROclient.ROClientException) and e.http_code == 404
3997 ): # not found
tiernoe876f672020-02-13 14:34:48 +00003998 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
3999 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
4000 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
garciadeblas5697b8b2021-03-24 09:17:02 +01004001 self.logger.debug(
4002 logging_text + "RO_ns_id={} already deleted".format(ro_nsr_id)
4003 )
4004 elif (
4005 isinstance(e, ROclient.ROClientException) and e.http_code == 409
4006 ): # conflict
tiernoa2143262020-03-27 16:20:40 +00004007 failed_detail.append("delete conflict: {}".format(e))
garciadeblas5697b8b2021-03-24 09:17:02 +01004008 self.logger.debug(
4009 logging_text
4010 + "RO_ns_id={} delete conflict: {}".format(ro_nsr_id, e)
4011 )
tiernoe876f672020-02-13 14:34:48 +00004012 else:
tiernoa2143262020-03-27 16:20:40 +00004013 failed_detail.append("delete error: {}".format(e))
garciadeblas5697b8b2021-03-24 09:17:02 +01004014 self.logger.error(
4015 logging_text + "RO_ns_id={} delete error: {}".format(ro_nsr_id, e)
4016 )
tiernoe876f672020-02-13 14:34:48 +00004017
4018 # Delete nsd
4019 if not failed_detail and deep_get(nsr_deployed, ("RO", "nsd_id")):
4020 ro_nsd_id = nsr_deployed["RO"]["nsd_id"]
4021 try:
4022 stage[2] = "Deleting nsd from RO."
4023 db_nsr_update["detailed-status"] = " ".join(stage)
4024 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4025 self._write_op_status(nslcmop_id, stage)
4026 await self.RO.delete("nsd", ro_nsd_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01004027 self.logger.debug(
4028 logging_text + "ro_nsd_id={} deleted".format(ro_nsd_id)
4029 )
tiernoe876f672020-02-13 14:34:48 +00004030 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
4031 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01004032 if (
4033 isinstance(e, ROclient.ROClientException) and e.http_code == 404
4034 ): # not found
tiernoe876f672020-02-13 14:34:48 +00004035 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
garciadeblas5697b8b2021-03-24 09:17:02 +01004036 self.logger.debug(
4037 logging_text + "ro_nsd_id={} already deleted".format(ro_nsd_id)
4038 )
4039 elif (
4040 isinstance(e, ROclient.ROClientException) and e.http_code == 409
4041 ): # conflict
4042 failed_detail.append(
4043 "ro_nsd_id={} delete conflict: {}".format(ro_nsd_id, e)
4044 )
tiernoe876f672020-02-13 14:34:48 +00004045 self.logger.debug(logging_text + failed_detail[-1])
4046 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004047 failed_detail.append(
4048 "ro_nsd_id={} delete error: {}".format(ro_nsd_id, e)
4049 )
tiernoe876f672020-02-13 14:34:48 +00004050 self.logger.error(logging_text + failed_detail[-1])
4051
4052 if not failed_detail and deep_get(nsr_deployed, ("RO", "vnfd")):
4053 for index, vnf_deployed in enumerate(nsr_deployed["RO"]["vnfd"]):
4054 if not vnf_deployed or not vnf_deployed["id"]:
4055 continue
4056 try:
4057 ro_vnfd_id = vnf_deployed["id"]
garciadeblas5697b8b2021-03-24 09:17:02 +01004058 stage[
4059 2
4060 ] = "Deleting member_vnf_index={} ro_vnfd_id={} from RO.".format(
4061 vnf_deployed["member-vnf-index"], ro_vnfd_id
4062 )
tiernoe876f672020-02-13 14:34:48 +00004063 db_nsr_update["detailed-status"] = " ".join(stage)
4064 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4065 self._write_op_status(nslcmop_id, stage)
4066 await self.RO.delete("vnfd", ro_vnfd_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01004067 self.logger.debug(
4068 logging_text + "ro_vnfd_id={} deleted".format(ro_vnfd_id)
4069 )
tiernoe876f672020-02-13 14:34:48 +00004070 db_nsr_update["_admin.deployed.RO.vnfd.{}.id".format(index)] = None
4071 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01004072 if (
4073 isinstance(e, ROclient.ROClientException) and e.http_code == 404
4074 ): # not found
4075 db_nsr_update[
4076 "_admin.deployed.RO.vnfd.{}.id".format(index)
4077 ] = None
4078 self.logger.debug(
4079 logging_text
4080 + "ro_vnfd_id={} already deleted ".format(ro_vnfd_id)
4081 )
4082 elif (
4083 isinstance(e, ROclient.ROClientException) and e.http_code == 409
4084 ): # conflict
4085 failed_detail.append(
4086 "ro_vnfd_id={} delete conflict: {}".format(ro_vnfd_id, e)
4087 )
tiernoe876f672020-02-13 14:34:48 +00004088 self.logger.debug(logging_text + failed_detail[-1])
4089 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004090 failed_detail.append(
4091 "ro_vnfd_id={} delete error: {}".format(ro_vnfd_id, e)
4092 )
tiernoe876f672020-02-13 14:34:48 +00004093 self.logger.error(logging_text + failed_detail[-1])
4094
tiernoa2143262020-03-27 16:20:40 +00004095 if failed_detail:
4096 stage[2] = "Error deleting from VIM"
4097 else:
4098 stage[2] = "Deleted from VIM"
tiernoe876f672020-02-13 14:34:48 +00004099 db_nsr_update["detailed-status"] = " ".join(stage)
4100 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4101 self._write_op_status(nslcmop_id, stage)
4102
4103 if failed_detail:
tiernoa2143262020-03-27 16:20:40 +00004104 raise LcmException("; ".join(failed_detail))
tiernoe876f672020-02-13 14:34:48 +00004105
4106 async def terminate(self, nsr_id, nslcmop_id):
kuused124bfe2019-06-18 12:09:24 +02004107 # Try to lock HA task here
garciadeblas5697b8b2021-03-24 09:17:02 +01004108 task_is_locked_by_me = self.lcm_tasks.lock_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02004109 if not task_is_locked_by_me:
4110 return
4111
tierno59d22d22018-09-25 18:10:19 +02004112 logging_text = "Task ns={} terminate={} ".format(nsr_id, nslcmop_id)
4113 self.logger.debug(logging_text + "Enter")
tiernoe876f672020-02-13 14:34:48 +00004114 timeout_ns_terminate = self.timeout_ns_terminate
tierno59d22d22018-09-25 18:10:19 +02004115 db_nsr = None
4116 db_nslcmop = None
tiernoa17d4f42020-04-28 09:59:23 +00004117 operation_params = None
tierno59d22d22018-09-25 18:10:19 +02004118 exc = None
garciadeblas5697b8b2021-03-24 09:17:02 +01004119 error_list = [] # annotates all failed error messages
tierno59d22d22018-09-25 18:10:19 +02004120 db_nslcmop_update = {}
tiernoc2564fe2019-01-28 16:18:56 +00004121 autoremove = False # autoremove after terminated
tiernoe876f672020-02-13 14:34:48 +00004122 tasks_dict_info = {}
4123 db_nsr_update = {}
garciadeblas5697b8b2021-03-24 09:17:02 +01004124 stage = [
4125 "Stage 1/3: Preparing task.",
4126 "Waiting for previous operations to terminate.",
4127 "",
4128 ]
tiernoe876f672020-02-13 14:34:48 +00004129 # ^ contains [stage, step, VIM-status]
tierno59d22d22018-09-25 18:10:19 +02004130 try:
kuused124bfe2019-06-18 12:09:24 +02004131 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +01004132 await self.lcm_tasks.waitfor_related_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02004133
tiernoe876f672020-02-13 14:34:48 +00004134 stage[1] = "Getting nslcmop={} from db.".format(nslcmop_id)
4135 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
4136 operation_params = db_nslcmop.get("operationParams") or {}
4137 if operation_params.get("timeout_ns_terminate"):
4138 timeout_ns_terminate = operation_params["timeout_ns_terminate"]
4139 stage[1] = "Getting nsr={} from db.".format(nsr_id)
4140 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
4141
4142 db_nsr_update["operational-status"] = "terminating"
4143 db_nsr_update["config-status"] = "terminating"
quilesj4cda56b2019-12-05 10:02:20 +00004144 self._write_ns_status(
4145 nsr_id=nsr_id,
4146 ns_state="TERMINATING",
4147 current_operation="TERMINATING",
tiernoe876f672020-02-13 14:34:48 +00004148 current_operation_id=nslcmop_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01004149 other_update=db_nsr_update,
quilesj4cda56b2019-12-05 10:02:20 +00004150 )
garciadeblas5697b8b2021-03-24 09:17:02 +01004151 self._write_op_status(op_id=nslcmop_id, queuePosition=0, stage=stage)
tiernoe876f672020-02-13 14:34:48 +00004152 nsr_deployed = deepcopy(db_nsr["_admin"].get("deployed")) or {}
tierno59d22d22018-09-25 18:10:19 +02004153 if db_nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
4154 return
tierno59d22d22018-09-25 18:10:19 +02004155
tiernoe876f672020-02-13 14:34:48 +00004156 stage[1] = "Getting vnf descriptors from db."
4157 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
garciadeblas5697b8b2021-03-24 09:17:02 +01004158 db_vnfrs_dict = {
4159 db_vnfr["member-vnf-index-ref"]: db_vnfr for db_vnfr in db_vnfrs_list
4160 }
tiernoe876f672020-02-13 14:34:48 +00004161 db_vnfds_from_id = {}
4162 db_vnfds_from_member_index = {}
4163 # Loop over VNFRs
4164 for vnfr in db_vnfrs_list:
4165 vnfd_id = vnfr["vnfd-id"]
4166 if vnfd_id not in db_vnfds_from_id:
4167 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
4168 db_vnfds_from_id[vnfd_id] = vnfd
garciadeblas5697b8b2021-03-24 09:17:02 +01004169 db_vnfds_from_member_index[
4170 vnfr["member-vnf-index-ref"]
4171 ] = db_vnfds_from_id[vnfd_id]
calvinosanch9f9c6f22019-11-04 13:37:39 +01004172
tiernoe876f672020-02-13 14:34:48 +00004173 # Destroy individual execution environments when there are terminating primitives.
4174 # Rest of EE will be deleted at once
tierno588547c2020-07-01 15:30:20 +00004175 # TODO - check before calling _destroy_N2VC
4176 # if not operation_params.get("skip_terminate_primitives"):#
4177 # or not vca.get("needed_terminate"):
4178 stage[0] = "Stage 2/3 execute terminating primitives."
4179 self.logger.debug(logging_text + stage[0])
4180 stage[1] = "Looking execution environment that needs terminate."
4181 self.logger.debug(logging_text + stage[1])
bravof922c4172020-11-24 21:21:43 -03004182
tierno588547c2020-07-01 15:30:20 +00004183 for vca_index, vca in enumerate(get_iterable(nsr_deployed, "VCA")):
tierno588547c2020-07-01 15:30:20 +00004184 config_descriptor = None
David Garciab76442a2021-05-28 12:08:18 +02004185 vca_member_vnf_index = vca.get("member-vnf-index")
4186 vca_id = self.get_vca_id(
4187 db_vnfrs_dict.get(vca_member_vnf_index)
4188 if vca_member_vnf_index
4189 else None,
4190 db_nsr,
4191 )
tierno588547c2020-07-01 15:30:20 +00004192 if not vca or not vca.get("ee_id"):
4193 continue
4194 if not vca.get("member-vnf-index"):
4195 # ns
4196 config_descriptor = db_nsr.get("ns-configuration")
4197 elif vca.get("vdu_id"):
4198 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
bravofe5a31bc2021-02-17 19:09:12 -03004199 config_descriptor = get_configuration(db_vnfd, vca.get("vdu_id"))
tierno588547c2020-07-01 15:30:20 +00004200 elif vca.get("kdu_name"):
4201 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
bravofe5a31bc2021-02-17 19:09:12 -03004202 config_descriptor = get_configuration(db_vnfd, vca.get("kdu_name"))
tierno588547c2020-07-01 15:30:20 +00004203 else:
bravofe5a31bc2021-02-17 19:09:12 -03004204 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
aktas13251562021-02-12 22:19:10 +03004205 config_descriptor = get_configuration(db_vnfd, db_vnfd["id"])
tierno588547c2020-07-01 15:30:20 +00004206 vca_type = vca.get("type")
garciadeblas5697b8b2021-03-24 09:17:02 +01004207 exec_terminate_primitives = not operation_params.get(
4208 "skip_terminate_primitives"
4209 ) and vca.get("needed_terminate")
tiernoaebd7da2020-08-07 06:36:38 +00004210 # For helm we must destroy_ee. Also for native_charm, as juju_model cannot be deleted if there are
4211 # pending native charms
garciadeblas5697b8b2021-03-24 09:17:02 +01004212 destroy_ee = (
4213 True if vca_type in ("helm", "helm-v3", "native_charm") else False
4214 )
tierno86e33612020-09-16 14:13:06 +00004215 # self.logger.debug(logging_text + "vca_index: {}, ee_id: {}, vca_type: {} destroy_ee: {}".format(
4216 # vca_index, vca.get("ee_id"), vca_type, destroy_ee))
tiernob996d942020-07-03 14:52:28 +00004217 task = asyncio.ensure_future(
David Garciac1fe90a2021-03-31 19:12:02 +02004218 self.destroy_N2VC(
4219 logging_text,
4220 db_nslcmop,
4221 vca,
4222 config_descriptor,
4223 vca_index,
4224 destroy_ee,
4225 exec_terminate_primitives,
4226 vca_id=vca_id,
4227 )
4228 )
tierno588547c2020-07-01 15:30:20 +00004229 tasks_dict_info[task] = "Terminating VCA {}".format(vca.get("ee_id"))
tierno59d22d22018-09-25 18:10:19 +02004230
tierno588547c2020-07-01 15:30:20 +00004231 # wait for pending tasks of terminate primitives
4232 if tasks_dict_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01004233 self.logger.debug(
4234 logging_text
4235 + "Waiting for tasks {}".format(list(tasks_dict_info.keys()))
4236 )
4237 error_list = await self._wait_for_tasks(
4238 logging_text,
4239 tasks_dict_info,
4240 min(self.timeout_charm_delete, timeout_ns_terminate),
4241 stage,
4242 nslcmop_id,
4243 )
tierno86e33612020-09-16 14:13:06 +00004244 tasks_dict_info.clear()
tierno588547c2020-07-01 15:30:20 +00004245 if error_list:
garciadeblas5697b8b2021-03-24 09:17:02 +01004246 return # raise LcmException("; ".join(error_list))
tierno82974b22018-11-27 21:55:36 +00004247
tiernoe876f672020-02-13 14:34:48 +00004248 # remove All execution environments at once
4249 stage[0] = "Stage 3/3 delete all."
quilesj3655ae02019-12-12 16:08:35 +00004250
tierno49676be2020-04-07 16:34:35 +00004251 if nsr_deployed.get("VCA"):
4252 stage[1] = "Deleting all execution environments."
4253 self.logger.debug(logging_text + stage[1])
David Garciac1fe90a2021-03-31 19:12:02 +02004254 vca_id = self.get_vca_id({}, db_nsr)
4255 task_delete_ee = asyncio.ensure_future(
4256 asyncio.wait_for(
4257 self._delete_all_N2VC(db_nsr=db_nsr, vca_id=vca_id),
garciadeblas5697b8b2021-03-24 09:17:02 +01004258 timeout=self.timeout_charm_delete,
David Garciac1fe90a2021-03-31 19:12:02 +02004259 )
4260 )
tierno49676be2020-04-07 16:34:35 +00004261 # task_delete_ee = asyncio.ensure_future(self.n2vc.delete_namespace(namespace="." + nsr_id))
4262 tasks_dict_info[task_delete_ee] = "Terminating all VCA"
tierno59d22d22018-09-25 18:10:19 +02004263
tiernoe876f672020-02-13 14:34:48 +00004264 # Delete from k8scluster
4265 stage[1] = "Deleting KDUs."
4266 self.logger.debug(logging_text + stage[1])
4267 # print(nsr_deployed)
4268 for kdu in get_iterable(nsr_deployed, "K8s"):
4269 if not kdu or not kdu.get("kdu-instance"):
4270 continue
4271 kdu_instance = kdu.get("kdu-instance")
tiernoa2143262020-03-27 16:20:40 +00004272 if kdu.get("k8scluster-type") in self.k8scluster_map:
David Garciac1fe90a2021-03-31 19:12:02 +02004273 # TODO: Uninstall kdu instances taking into account they could be deployed in different VIMs
4274 vca_id = self.get_vca_id({}, db_nsr)
tiernoe876f672020-02-13 14:34:48 +00004275 task_delete_kdu_instance = asyncio.ensure_future(
tiernoa2143262020-03-27 16:20:40 +00004276 self.k8scluster_map[kdu["k8scluster-type"]].uninstall(
4277 cluster_uuid=kdu.get("k8scluster-uuid"),
David Garciac1fe90a2021-03-31 19:12:02 +02004278 kdu_instance=kdu_instance,
4279 vca_id=vca_id,
4280 )
4281 )
tiernoe876f672020-02-13 14:34:48 +00004282 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004283 self.logger.error(
4284 logging_text
4285 + "Unknown k8s deployment type {}".format(
4286 kdu.get("k8scluster-type")
4287 )
4288 )
tiernoe876f672020-02-13 14:34:48 +00004289 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01004290 tasks_dict_info[
4291 task_delete_kdu_instance
4292 ] = "Terminating KDU '{}'".format(kdu.get("kdu-name"))
tierno59d22d22018-09-25 18:10:19 +02004293
4294 # remove from RO
tiernoe876f672020-02-13 14:34:48 +00004295 stage[1] = "Deleting ns from VIM."
tierno69f0d382020-05-07 13:08:09 +00004296 if self.ng_ro:
4297 task_delete_ro = asyncio.ensure_future(
garciadeblas5697b8b2021-03-24 09:17:02 +01004298 self._terminate_ng_ro(
4299 logging_text, nsr_deployed, nsr_id, nslcmop_id, stage
4300 )
4301 )
tierno69f0d382020-05-07 13:08:09 +00004302 else:
4303 task_delete_ro = asyncio.ensure_future(
garciadeblas5697b8b2021-03-24 09:17:02 +01004304 self._terminate_RO(
4305 logging_text, nsr_deployed, nsr_id, nslcmop_id, stage
4306 )
4307 )
tiernoe876f672020-02-13 14:34:48 +00004308 tasks_dict_info[task_delete_ro] = "Removing deployment from VIM"
tierno59d22d22018-09-25 18:10:19 +02004309
tiernoe876f672020-02-13 14:34:48 +00004310 # rest of staff will be done at finally
4311
garciadeblas5697b8b2021-03-24 09:17:02 +01004312 except (
4313 ROclient.ROClientException,
4314 DbException,
4315 LcmException,
4316 N2VCException,
4317 ) as e:
tiernoe876f672020-02-13 14:34:48 +00004318 self.logger.error(logging_text + "Exit Exception {}".format(e))
4319 exc = e
4320 except asyncio.CancelledError:
garciadeblas5697b8b2021-03-24 09:17:02 +01004321 self.logger.error(
4322 logging_text + "Cancelled Exception while '{}'".format(stage[1])
4323 )
tiernoe876f672020-02-13 14:34:48 +00004324 exc = "Operation was cancelled"
4325 except Exception as e:
4326 exc = traceback.format_exc()
garciadeblas5697b8b2021-03-24 09:17:02 +01004327 self.logger.critical(
4328 logging_text + "Exit Exception while '{}': {}".format(stage[1], e),
4329 exc_info=True,
4330 )
tiernoe876f672020-02-13 14:34:48 +00004331 finally:
4332 if exc:
4333 error_list.append(str(exc))
tierno59d22d22018-09-25 18:10:19 +02004334 try:
tiernoe876f672020-02-13 14:34:48 +00004335 # wait for pending tasks
4336 if tasks_dict_info:
4337 stage[1] = "Waiting for terminate pending tasks."
4338 self.logger.debug(logging_text + stage[1])
garciadeblas5697b8b2021-03-24 09:17:02 +01004339 error_list += await self._wait_for_tasks(
4340 logging_text,
4341 tasks_dict_info,
4342 timeout_ns_terminate,
4343 stage,
4344 nslcmop_id,
4345 )
tiernoe876f672020-02-13 14:34:48 +00004346 stage[1] = stage[2] = ""
4347 except asyncio.CancelledError:
4348 error_list.append("Cancelled")
4349 # TODO cancell all tasks
4350 except Exception as exc:
4351 error_list.append(str(exc))
4352 # update status at database
4353 if error_list:
4354 error_detail = "; ".join(error_list)
4355 # self.logger.error(logging_text + error_detail)
garciadeblas5697b8b2021-03-24 09:17:02 +01004356 error_description_nslcmop = "{} Detail: {}".format(
4357 stage[0], error_detail
4358 )
4359 error_description_nsr = "Operation: TERMINATING.{}, {}.".format(
4360 nslcmop_id, stage[0]
4361 )
tierno59d22d22018-09-25 18:10:19 +02004362
tierno59d22d22018-09-25 18:10:19 +02004363 db_nsr_update["operational-status"] = "failed"
garciadeblas5697b8b2021-03-24 09:17:02 +01004364 db_nsr_update["detailed-status"] = (
4365 error_description_nsr + " Detail: " + error_detail
4366 )
tiernoe876f672020-02-13 14:34:48 +00004367 db_nslcmop_update["detailed-status"] = error_detail
4368 nslcmop_operation_state = "FAILED"
4369 ns_state = "BROKEN"
tierno59d22d22018-09-25 18:10:19 +02004370 else:
tiernoa2143262020-03-27 16:20:40 +00004371 error_detail = None
tiernoe876f672020-02-13 14:34:48 +00004372 error_description_nsr = error_description_nslcmop = None
4373 ns_state = "NOT_INSTANTIATED"
tierno59d22d22018-09-25 18:10:19 +02004374 db_nsr_update["operational-status"] = "terminated"
4375 db_nsr_update["detailed-status"] = "Done"
4376 db_nsr_update["_admin.nsState"] = "NOT_INSTANTIATED"
4377 db_nslcmop_update["detailed-status"] = "Done"
tiernoe876f672020-02-13 14:34:48 +00004378 nslcmop_operation_state = "COMPLETED"
tierno59d22d22018-09-25 18:10:19 +02004379
tiernoe876f672020-02-13 14:34:48 +00004380 if db_nsr:
4381 self._write_ns_status(
4382 nsr_id=nsr_id,
4383 ns_state=ns_state,
4384 current_operation="IDLE",
4385 current_operation_id=None,
4386 error_description=error_description_nsr,
tiernoa2143262020-03-27 16:20:40 +00004387 error_detail=error_detail,
garciadeblas5697b8b2021-03-24 09:17:02 +01004388 other_update=db_nsr_update,
tiernoe876f672020-02-13 14:34:48 +00004389 )
tiernoa17d4f42020-04-28 09:59:23 +00004390 self._write_op_status(
4391 op_id=nslcmop_id,
4392 stage="",
4393 error_message=error_description_nslcmop,
4394 operation_state=nslcmop_operation_state,
4395 other_update=db_nslcmop_update,
4396 )
lloretgalleg6d488782020-07-22 10:13:46 +00004397 if ns_state == "NOT_INSTANTIATED":
4398 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01004399 self.db.set_list(
4400 "vnfrs",
4401 {"nsr-id-ref": nsr_id},
4402 {"_admin.nsState": "NOT_INSTANTIATED"},
4403 )
lloretgalleg6d488782020-07-22 10:13:46 +00004404 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01004405 self.logger.warn(
4406 logging_text
4407 + "Error writing VNFR status for nsr-id-ref: {} -> {}".format(
4408 nsr_id, e
4409 )
4410 )
tiernoa17d4f42020-04-28 09:59:23 +00004411 if operation_params:
tiernoe876f672020-02-13 14:34:48 +00004412 autoremove = operation_params.get("autoremove", False)
tierno59d22d22018-09-25 18:10:19 +02004413 if nslcmop_operation_state:
4414 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01004415 await self.msg.aiowrite(
4416 "ns",
4417 "terminated",
4418 {
4419 "nsr_id": nsr_id,
4420 "nslcmop_id": nslcmop_id,
4421 "operationState": nslcmop_operation_state,
4422 "autoremove": autoremove,
4423 },
4424 loop=self.loop,
4425 )
tierno59d22d22018-09-25 18:10:19 +02004426 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01004427 self.logger.error(
4428 logging_text + "kafka_write notification Exception {}".format(e)
4429 )
quilesj7e13aeb2019-10-08 13:34:55 +02004430
tierno59d22d22018-09-25 18:10:19 +02004431 self.logger.debug(logging_text + "Exit")
4432 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_terminate")
4433
garciadeblas5697b8b2021-03-24 09:17:02 +01004434 async def _wait_for_tasks(
4435 self, logging_text, created_tasks_info, timeout, stage, nslcmop_id, nsr_id=None
4436 ):
tiernoe876f672020-02-13 14:34:48 +00004437 time_start = time()
tiernoa2143262020-03-27 16:20:40 +00004438 error_detail_list = []
tiernoe876f672020-02-13 14:34:48 +00004439 error_list = []
4440 pending_tasks = list(created_tasks_info.keys())
4441 num_tasks = len(pending_tasks)
4442 num_done = 0
4443 stage[1] = "{}/{}.".format(num_done, num_tasks)
4444 self._write_op_status(nslcmop_id, stage)
tiernoe876f672020-02-13 14:34:48 +00004445 while pending_tasks:
tiernoa2143262020-03-27 16:20:40 +00004446 new_error = None
tiernoe876f672020-02-13 14:34:48 +00004447 _timeout = timeout + time_start - time()
garciadeblas5697b8b2021-03-24 09:17:02 +01004448 done, pending_tasks = await asyncio.wait(
4449 pending_tasks, timeout=_timeout, return_when=asyncio.FIRST_COMPLETED
4450 )
tiernoe876f672020-02-13 14:34:48 +00004451 num_done += len(done)
garciadeblas5697b8b2021-03-24 09:17:02 +01004452 if not done: # Timeout
tiernoe876f672020-02-13 14:34:48 +00004453 for task in pending_tasks:
tiernoa2143262020-03-27 16:20:40 +00004454 new_error = created_tasks_info[task] + ": Timeout"
4455 error_detail_list.append(new_error)
4456 error_list.append(new_error)
tiernoe876f672020-02-13 14:34:48 +00004457 break
4458 for task in done:
4459 if task.cancelled():
tierno067e04a2020-03-31 12:53:13 +00004460 exc = "Cancelled"
tiernoe876f672020-02-13 14:34:48 +00004461 else:
4462 exc = task.exception()
tierno067e04a2020-03-31 12:53:13 +00004463 if exc:
4464 if isinstance(exc, asyncio.TimeoutError):
4465 exc = "Timeout"
4466 new_error = created_tasks_info[task] + ": {}".format(exc)
4467 error_list.append(created_tasks_info[task])
4468 error_detail_list.append(new_error)
garciadeblas5697b8b2021-03-24 09:17:02 +01004469 if isinstance(
4470 exc,
4471 (
4472 str,
4473 DbException,
4474 N2VCException,
4475 ROclient.ROClientException,
4476 LcmException,
4477 K8sException,
4478 NgRoException,
4479 ),
4480 ):
tierno067e04a2020-03-31 12:53:13 +00004481 self.logger.error(logging_text + new_error)
tiernoe876f672020-02-13 14:34:48 +00004482 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004483 exc_traceback = "".join(
4484 traceback.format_exception(None, exc, exc.__traceback__)
4485 )
4486 self.logger.error(
4487 logging_text
4488 + created_tasks_info[task]
4489 + " "
4490 + exc_traceback
4491 )
tierno067e04a2020-03-31 12:53:13 +00004492 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004493 self.logger.debug(
4494 logging_text + created_tasks_info[task] + ": Done"
4495 )
tiernoe876f672020-02-13 14:34:48 +00004496 stage[1] = "{}/{}.".format(num_done, num_tasks)
4497 if new_error:
tiernoa2143262020-03-27 16:20:40 +00004498 stage[1] += " Errors: " + ". ".join(error_detail_list) + "."
tiernoe876f672020-02-13 14:34:48 +00004499 if nsr_id: # update also nsr
garciadeblas5697b8b2021-03-24 09:17:02 +01004500 self.update_db_2(
4501 "nsrs",
4502 nsr_id,
4503 {
4504 "errorDescription": "Error at: " + ", ".join(error_list),
4505 "errorDetail": ". ".join(error_detail_list),
4506 },
4507 )
tiernoe876f672020-02-13 14:34:48 +00004508 self._write_op_status(nslcmop_id, stage)
tiernoa2143262020-03-27 16:20:40 +00004509 return error_detail_list
tiernoe876f672020-02-13 14:34:48 +00004510
tiernoda1ff8c2020-10-22 14:12:46 +00004511 @staticmethod
4512 def _map_primitive_params(primitive_desc, params, instantiation_params):
tiernoda964822019-01-14 15:53:47 +00004513 """
4514 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
4515 The default-value is used. If it is between < > it look for a value at instantiation_params
4516 :param primitive_desc: portion of VNFD/NSD that describes primitive
4517 :param params: Params provided by user
4518 :param instantiation_params: Instantiation params provided by user
4519 :return: a dictionary with the calculated params
4520 """
4521 calculated_params = {}
4522 for parameter in primitive_desc.get("parameter", ()):
4523 param_name = parameter["name"]
4524 if param_name in params:
4525 calculated_params[param_name] = params[param_name]
tierno98ad6ea2019-05-30 17:16:28 +00004526 elif "default-value" in parameter or "value" in parameter:
4527 if "value" in parameter:
4528 calculated_params[param_name] = parameter["value"]
4529 else:
4530 calculated_params[param_name] = parameter["default-value"]
garciadeblas5697b8b2021-03-24 09:17:02 +01004531 if (
4532 isinstance(calculated_params[param_name], str)
4533 and calculated_params[param_name].startswith("<")
4534 and calculated_params[param_name].endswith(">")
4535 ):
tierno98ad6ea2019-05-30 17:16:28 +00004536 if calculated_params[param_name][1:-1] in instantiation_params:
garciadeblas5697b8b2021-03-24 09:17:02 +01004537 calculated_params[param_name] = instantiation_params[
4538 calculated_params[param_name][1:-1]
4539 ]
tiernoda964822019-01-14 15:53:47 +00004540 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004541 raise LcmException(
4542 "Parameter {} needed to execute primitive {} not provided".format(
4543 calculated_params[param_name], primitive_desc["name"]
4544 )
4545 )
tiernoda964822019-01-14 15:53:47 +00004546 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004547 raise LcmException(
4548 "Parameter {} needed to execute primitive {} not provided".format(
4549 param_name, primitive_desc["name"]
4550 )
4551 )
tierno59d22d22018-09-25 18:10:19 +02004552
tiernoda964822019-01-14 15:53:47 +00004553 if isinstance(calculated_params[param_name], (dict, list, tuple)):
garciadeblas5697b8b2021-03-24 09:17:02 +01004554 calculated_params[param_name] = yaml.safe_dump(
4555 calculated_params[param_name], default_flow_style=True, width=256
4556 )
4557 elif isinstance(calculated_params[param_name], str) and calculated_params[
4558 param_name
4559 ].startswith("!!yaml "):
tiernoda964822019-01-14 15:53:47 +00004560 calculated_params[param_name] = calculated_params[param_name][7:]
tiernofa40e692020-10-14 14:59:36 +00004561 if parameter.get("data-type") == "INTEGER":
4562 try:
4563 calculated_params[param_name] = int(calculated_params[param_name])
4564 except ValueError: # error converting string to int
4565 raise LcmException(
garciadeblas5697b8b2021-03-24 09:17:02 +01004566 "Parameter {} of primitive {} must be integer".format(
4567 param_name, primitive_desc["name"]
4568 )
4569 )
tiernofa40e692020-10-14 14:59:36 +00004570 elif parameter.get("data-type") == "BOOLEAN":
garciadeblas5697b8b2021-03-24 09:17:02 +01004571 calculated_params[param_name] = not (
4572 (str(calculated_params[param_name])).lower() == "false"
4573 )
tiernoc3f2a822019-11-05 13:45:04 +00004574
4575 # add always ns_config_info if primitive name is config
4576 if primitive_desc["name"] == "config":
4577 if "ns_config_info" in instantiation_params:
garciadeblas5697b8b2021-03-24 09:17:02 +01004578 calculated_params["ns_config_info"] = instantiation_params[
4579 "ns_config_info"
4580 ]
tiernoda964822019-01-14 15:53:47 +00004581 return calculated_params
4582
garciadeblas5697b8b2021-03-24 09:17:02 +01004583 def _look_for_deployed_vca(
4584 self,
4585 deployed_vca,
4586 member_vnf_index,
4587 vdu_id,
4588 vdu_count_index,
4589 kdu_name=None,
4590 ee_descriptor_id=None,
4591 ):
tiernoe876f672020-02-13 14:34:48 +00004592 # find vca_deployed record for this action. Raise LcmException if not found or there is not any id.
4593 for vca in deployed_vca:
4594 if not vca:
4595 continue
4596 if member_vnf_index != vca["member-vnf-index"] or vdu_id != vca["vdu_id"]:
4597 continue
garciadeblas5697b8b2021-03-24 09:17:02 +01004598 if (
4599 vdu_count_index is not None
4600 and vdu_count_index != vca["vdu_count_index"]
4601 ):
tiernoe876f672020-02-13 14:34:48 +00004602 continue
4603 if kdu_name and kdu_name != vca["kdu_name"]:
4604 continue
tiernoa278b842020-07-08 15:33:55 +00004605 if ee_descriptor_id and ee_descriptor_id != vca["ee_descriptor_id"]:
4606 continue
tiernoe876f672020-02-13 14:34:48 +00004607 break
4608 else:
4609 # vca_deployed not found
garciadeblas5697b8b2021-03-24 09:17:02 +01004610 raise LcmException(
4611 "charm for member_vnf_index={} vdu_id={}.{} kdu_name={} execution-environment-list.id={}"
4612 " is not deployed".format(
4613 member_vnf_index,
4614 vdu_id,
4615 vdu_count_index,
4616 kdu_name,
4617 ee_descriptor_id,
4618 )
4619 )
tiernoe876f672020-02-13 14:34:48 +00004620 # get ee_id
4621 ee_id = vca.get("ee_id")
garciadeblas5697b8b2021-03-24 09:17:02 +01004622 vca_type = vca.get(
4623 "type", "lxc_proxy_charm"
4624 ) # default value for backward compatibility - proxy charm
tiernoe876f672020-02-13 14:34:48 +00004625 if not ee_id:
garciadeblas5697b8b2021-03-24 09:17:02 +01004626 raise LcmException(
4627 "charm for member_vnf_index={} vdu_id={} kdu_name={} vdu_count_index={} has not "
4628 "execution environment".format(
4629 member_vnf_index, vdu_id, kdu_name, vdu_count_index
4630 )
4631 )
tierno588547c2020-07-01 15:30:20 +00004632 return ee_id, vca_type
tiernoe876f672020-02-13 14:34:48 +00004633
David Garciac1fe90a2021-03-31 19:12:02 +02004634 async def _ns_execute_primitive(
4635 self,
4636 ee_id,
4637 primitive,
4638 primitive_params,
4639 retries=0,
4640 retries_interval=30,
4641 timeout=None,
4642 vca_type=None,
4643 db_dict=None,
4644 vca_id: str = None,
4645 ) -> (str, str):
tiernoda964822019-01-14 15:53:47 +00004646 try:
tierno98ad6ea2019-05-30 17:16:28 +00004647 if primitive == "config":
4648 primitive_params = {"params": primitive_params}
tierno2fc7ce52019-06-11 22:50:01 +00004649
tierno588547c2020-07-01 15:30:20 +00004650 vca_type = vca_type or "lxc_proxy_charm"
4651
quilesj7e13aeb2019-10-08 13:34:55 +02004652 while retries >= 0:
4653 try:
tierno067e04a2020-03-31 12:53:13 +00004654 output = await asyncio.wait_for(
tierno588547c2020-07-01 15:30:20 +00004655 self.vca_map[vca_type].exec_primitive(
tierno067e04a2020-03-31 12:53:13 +00004656 ee_id=ee_id,
4657 primitive_name=primitive,
4658 params_dict=primitive_params,
4659 progress_timeout=self.timeout_progress_primitive,
tierno588547c2020-07-01 15:30:20 +00004660 total_timeout=self.timeout_primitive,
David Garciac1fe90a2021-03-31 19:12:02 +02004661 db_dict=db_dict,
4662 vca_id=vca_id,
aktas730569b2021-07-29 17:42:49 +03004663 vca_type=vca_type,
David Garciac1fe90a2021-03-31 19:12:02 +02004664 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01004665 timeout=timeout or self.timeout_primitive,
4666 )
quilesj7e13aeb2019-10-08 13:34:55 +02004667 # execution was OK
4668 break
tierno067e04a2020-03-31 12:53:13 +00004669 except asyncio.CancelledError:
4670 raise
4671 except Exception as e: # asyncio.TimeoutError
4672 if isinstance(e, asyncio.TimeoutError):
4673 e = "Timeout"
quilesj7e13aeb2019-10-08 13:34:55 +02004674 retries -= 1
4675 if retries >= 0:
garciadeblas5697b8b2021-03-24 09:17:02 +01004676 self.logger.debug(
4677 "Error executing action {} on {} -> {}".format(
4678 primitive, ee_id, e
4679 )
4680 )
quilesj7e13aeb2019-10-08 13:34:55 +02004681 # wait and retry
4682 await asyncio.sleep(retries_interval, loop=self.loop)
tierno73d8bd02019-11-18 17:33:27 +00004683 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004684 return "FAILED", str(e)
quilesj7e13aeb2019-10-08 13:34:55 +02004685
garciadeblas5697b8b2021-03-24 09:17:02 +01004686 return "COMPLETED", output
quilesj7e13aeb2019-10-08 13:34:55 +02004687
tierno067e04a2020-03-31 12:53:13 +00004688 except (LcmException, asyncio.CancelledError):
tiernoe876f672020-02-13 14:34:48 +00004689 raise
quilesj7e13aeb2019-10-08 13:34:55 +02004690 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01004691 return "FAIL", "Error executing action {}: {}".format(primitive, e)
tierno59d22d22018-09-25 18:10:19 +02004692
ksaikiranr3fde2c72021-03-15 10:39:06 +05304693 async def vca_status_refresh(self, nsr_id, nslcmop_id):
4694 """
4695 Updating the vca_status with latest juju information in nsrs record
4696 :param: nsr_id: Id of the nsr
4697 :param: nslcmop_id: Id of the nslcmop
4698 :return: None
4699 """
4700
4701 self.logger.debug("Task ns={} action={} Enter".format(nsr_id, nslcmop_id))
4702 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
David Garciac1fe90a2021-03-31 19:12:02 +02004703 vca_id = self.get_vca_id({}, db_nsr)
garciadeblas5697b8b2021-03-24 09:17:02 +01004704 if db_nsr["_admin"]["deployed"]["K8s"]:
Pedro Escaleira064c6442022-04-01 01:49:22 +01004705 for _, k8s in enumerate(db_nsr["_admin"]["deployed"]["K8s"]):
4706 cluster_uuid, kdu_instance, cluster_type = (
4707 k8s["k8scluster-uuid"],
4708 k8s["kdu-instance"],
4709 k8s["k8scluster-type"],
4710 )
garciadeblas5697b8b2021-03-24 09:17:02 +01004711 await self._on_update_k8s_db(
Pedro Escaleira064c6442022-04-01 01:49:22 +01004712 cluster_uuid=cluster_uuid,
4713 kdu_instance=kdu_instance,
4714 filter={"_id": nsr_id},
4715 vca_id=vca_id,
4716 cluster_type=cluster_type,
garciadeblas5697b8b2021-03-24 09:17:02 +01004717 )
ksaikiranr656b6dd2021-02-19 10:25:18 +05304718 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004719 for vca_index, _ in enumerate(db_nsr["_admin"]["deployed"]["VCA"]):
ksaikiranr656b6dd2021-02-19 10:25:18 +05304720 table, filter = "nsrs", {"_id": nsr_id}
4721 path = "_admin.deployed.VCA.{}.".format(vca_index)
4722 await self._on_update_n2vc_db(table, filter, path, {})
ksaikiranr3fde2c72021-03-15 10:39:06 +05304723
4724 self.logger.debug("Task ns={} action={} Exit".format(nsr_id, nslcmop_id))
4725 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_vca_status_refresh")
4726
tierno59d22d22018-09-25 18:10:19 +02004727 async def action(self, nsr_id, nslcmop_id):
kuused124bfe2019-06-18 12:09:24 +02004728 # Try to lock HA task here
garciadeblas5697b8b2021-03-24 09:17:02 +01004729 task_is_locked_by_me = self.lcm_tasks.lock_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02004730 if not task_is_locked_by_me:
4731 return
4732
tierno59d22d22018-09-25 18:10:19 +02004733 logging_text = "Task ns={} action={} ".format(nsr_id, nslcmop_id)
4734 self.logger.debug(logging_text + "Enter")
4735 # get all needed from database
4736 db_nsr = None
4737 db_nslcmop = None
tiernoe876f672020-02-13 14:34:48 +00004738 db_nsr_update = {}
tierno59d22d22018-09-25 18:10:19 +02004739 db_nslcmop_update = {}
4740 nslcmop_operation_state = None
tierno067e04a2020-03-31 12:53:13 +00004741 error_description_nslcmop = None
tierno59d22d22018-09-25 18:10:19 +02004742 exc = None
4743 try:
kuused124bfe2019-06-18 12:09:24 +02004744 # wait for any previous tasks in process
tierno3cf81a32019-11-11 17:07:00 +00004745 step = "Waiting for previous operations to terminate"
garciadeblas5697b8b2021-03-24 09:17:02 +01004746 await self.lcm_tasks.waitfor_related_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02004747
quilesj4cda56b2019-12-05 10:02:20 +00004748 self._write_ns_status(
4749 nsr_id=nsr_id,
4750 ns_state=None,
4751 current_operation="RUNNING ACTION",
garciadeblas5697b8b2021-03-24 09:17:02 +01004752 current_operation_id=nslcmop_id,
quilesj4cda56b2019-12-05 10:02:20 +00004753 )
4754
tierno59d22d22018-09-25 18:10:19 +02004755 step = "Getting information from database"
4756 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
4757 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
Guillermo Calvinofbf294c2022-01-26 17:40:31 +01004758 if db_nslcmop["operationParams"].get("primitive_params"):
4759 db_nslcmop["operationParams"]["primitive_params"] = json.loads(
4760 db_nslcmop["operationParams"]["primitive_params"]
4761 )
tiernoda964822019-01-14 15:53:47 +00004762
tiernoe4f7e6c2018-11-27 14:55:30 +00004763 nsr_deployed = db_nsr["_admin"].get("deployed")
tierno1b633412019-02-25 16:48:23 +00004764 vnf_index = db_nslcmop["operationParams"].get("member_vnf_index")
tierno59d22d22018-09-25 18:10:19 +02004765 vdu_id = db_nslcmop["operationParams"].get("vdu_id")
calvinosanch9f9c6f22019-11-04 13:37:39 +01004766 kdu_name = db_nslcmop["operationParams"].get("kdu_name")
tiernoe4f7e6c2018-11-27 14:55:30 +00004767 vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
tierno067e04a2020-03-31 12:53:13 +00004768 primitive = db_nslcmop["operationParams"]["primitive"]
4769 primitive_params = db_nslcmop["operationParams"]["primitive_params"]
garciadeblas5697b8b2021-03-24 09:17:02 +01004770 timeout_ns_action = db_nslcmop["operationParams"].get(
4771 "timeout_ns_action", self.timeout_primitive
4772 )
tierno59d22d22018-09-25 18:10:19 +02004773
tierno1b633412019-02-25 16:48:23 +00004774 if vnf_index:
4775 step = "Getting vnfr from database"
garciadeblas5697b8b2021-03-24 09:17:02 +01004776 db_vnfr = self.db.get_one(
4777 "vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id}
4778 )
Guillermo Calvino98a3bd12022-02-01 18:59:50 +01004779 if db_vnfr.get("kdur"):
4780 kdur_list = []
4781 for kdur in db_vnfr["kdur"]:
4782 if kdur.get("additionalParams"):
Pedro Escaleirab1679e42022-03-31 00:08:05 +01004783 kdur["additionalParams"] = json.loads(
4784 kdur["additionalParams"]
4785 )
Guillermo Calvino98a3bd12022-02-01 18:59:50 +01004786 kdur_list.append(kdur)
4787 db_vnfr["kdur"] = kdur_list
tierno1b633412019-02-25 16:48:23 +00004788 step = "Getting vnfd from database"
4789 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
4790 else:
tierno067e04a2020-03-31 12:53:13 +00004791 step = "Getting nsd from database"
4792 db_nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
tiernoda964822019-01-14 15:53:47 +00004793
David Garciac1fe90a2021-03-31 19:12:02 +02004794 vca_id = self.get_vca_id(db_vnfr, db_nsr)
tierno82974b22018-11-27 21:55:36 +00004795 # for backward compatibility
4796 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
4797 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
4798 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
4799 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4800
tiernoda964822019-01-14 15:53:47 +00004801 # look for primitive
tiernoa278b842020-07-08 15:33:55 +00004802 config_primitive_desc = descriptor_configuration = None
tiernoda964822019-01-14 15:53:47 +00004803 if vdu_id:
bravofe5a31bc2021-02-17 19:09:12 -03004804 descriptor_configuration = get_configuration(db_vnfd, vdu_id)
calvinosanch9f9c6f22019-11-04 13:37:39 +01004805 elif kdu_name:
bravofe5a31bc2021-02-17 19:09:12 -03004806 descriptor_configuration = get_configuration(db_vnfd, kdu_name)
tierno1b633412019-02-25 16:48:23 +00004807 elif vnf_index:
bravofe5a31bc2021-02-17 19:09:12 -03004808 descriptor_configuration = get_configuration(db_vnfd, db_vnfd["id"])
tierno1b633412019-02-25 16:48:23 +00004809 else:
tiernoa278b842020-07-08 15:33:55 +00004810 descriptor_configuration = db_nsd.get("ns-configuration")
4811
garciadeblas5697b8b2021-03-24 09:17:02 +01004812 if descriptor_configuration and descriptor_configuration.get(
4813 "config-primitive"
4814 ):
tiernoa278b842020-07-08 15:33:55 +00004815 for config_primitive in descriptor_configuration["config-primitive"]:
tierno1b633412019-02-25 16:48:23 +00004816 if config_primitive["name"] == primitive:
4817 config_primitive_desc = config_primitive
4818 break
tiernoda964822019-01-14 15:53:47 +00004819
garciadeblas6bed6b32020-07-20 11:05:42 +00004820 if not config_primitive_desc:
4821 if not (kdu_name and primitive in ("upgrade", "rollback", "status")):
garciadeblas5697b8b2021-03-24 09:17:02 +01004822 raise LcmException(
4823 "Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".format(
4824 primitive
4825 )
4826 )
garciadeblas6bed6b32020-07-20 11:05:42 +00004827 primitive_name = primitive
4828 ee_descriptor_id = None
4829 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004830 primitive_name = config_primitive_desc.get(
4831 "execution-environment-primitive", primitive
4832 )
4833 ee_descriptor_id = config_primitive_desc.get(
4834 "execution-environment-ref"
4835 )
tierno1b633412019-02-25 16:48:23 +00004836
tierno1b633412019-02-25 16:48:23 +00004837 if vnf_index:
tierno626e0152019-11-29 14:16:16 +00004838 if vdu_id:
garciadeblas5697b8b2021-03-24 09:17:02 +01004839 vdur = next(
4840 (x for x in db_vnfr["vdur"] if x["vdu-id-ref"] == vdu_id), None
4841 )
bravof922c4172020-11-24 21:21:43 -03004842 desc_params = parse_yaml_strings(vdur.get("additionalParams"))
tierno067e04a2020-03-31 12:53:13 +00004843 elif kdu_name:
garciadeblas5697b8b2021-03-24 09:17:02 +01004844 kdur = next(
4845 (x for x in db_vnfr["kdur"] if x["kdu-name"] == kdu_name), None
4846 )
bravof922c4172020-11-24 21:21:43 -03004847 desc_params = parse_yaml_strings(kdur.get("additionalParams"))
tierno067e04a2020-03-31 12:53:13 +00004848 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004849 desc_params = parse_yaml_strings(
4850 db_vnfr.get("additionalParamsForVnf")
4851 )
tierno1b633412019-02-25 16:48:23 +00004852 else:
bravof922c4172020-11-24 21:21:43 -03004853 desc_params = parse_yaml_strings(db_nsr.get("additionalParamsForNs"))
bravofe5a31bc2021-02-17 19:09:12 -03004854 if kdu_name and get_configuration(db_vnfd, kdu_name):
4855 kdu_configuration = get_configuration(db_vnfd, kdu_name)
David Garciad41dbd62020-12-10 12:52:52 +01004856 actions = set()
David Garciaa1003662021-02-16 21:07:58 +01004857 for primitive in kdu_configuration.get("initial-config-primitive", []):
David Garciad41dbd62020-12-10 12:52:52 +01004858 actions.add(primitive["name"])
David Garciaa1003662021-02-16 21:07:58 +01004859 for primitive in kdu_configuration.get("config-primitive", []):
David Garciad41dbd62020-12-10 12:52:52 +01004860 actions.add(primitive["name"])
4861 kdu_action = True if primitive_name in actions else False
Dominik Fleischmann771c32b2020-04-07 12:39:36 +02004862
tiernoda964822019-01-14 15:53:47 +00004863 # TODO check if ns is in a proper status
garciadeblas5697b8b2021-03-24 09:17:02 +01004864 if kdu_name and (
4865 primitive_name in ("upgrade", "rollback", "status") or kdu_action
4866 ):
tierno067e04a2020-03-31 12:53:13 +00004867 # kdur and desc_params already set from before
4868 if primitive_params:
4869 desc_params.update(primitive_params)
4870 # TODO Check if we will need something at vnf level
4871 for index, kdu in enumerate(get_iterable(nsr_deployed, "K8s")):
garciadeblas5697b8b2021-03-24 09:17:02 +01004872 if (
4873 kdu_name == kdu["kdu-name"]
4874 and kdu["member-vnf-index"] == vnf_index
4875 ):
tierno067e04a2020-03-31 12:53:13 +00004876 break
4877 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004878 raise LcmException(
4879 "KDU '{}' for vnf '{}' not deployed".format(kdu_name, vnf_index)
4880 )
quilesj7e13aeb2019-10-08 13:34:55 +02004881
tierno067e04a2020-03-31 12:53:13 +00004882 if kdu.get("k8scluster-type") not in self.k8scluster_map:
garciadeblas5697b8b2021-03-24 09:17:02 +01004883 msg = "unknown k8scluster-type '{}'".format(
4884 kdu.get("k8scluster-type")
4885 )
tierno067e04a2020-03-31 12:53:13 +00004886 raise LcmException(msg)
4887
garciadeblas5697b8b2021-03-24 09:17:02 +01004888 db_dict = {
4889 "collection": "nsrs",
4890 "filter": {"_id": nsr_id},
4891 "path": "_admin.deployed.K8s.{}".format(index),
4892 }
4893 self.logger.debug(
4894 logging_text
4895 + "Exec k8s {} on {}.{}".format(primitive_name, vnf_index, kdu_name)
4896 )
tiernoa278b842020-07-08 15:33:55 +00004897 step = "Executing kdu {}".format(primitive_name)
4898 if primitive_name == "upgrade":
tierno067e04a2020-03-31 12:53:13 +00004899 if desc_params.get("kdu_model"):
4900 kdu_model = desc_params.get("kdu_model")
4901 del desc_params["kdu_model"]
4902 else:
4903 kdu_model = kdu.get("kdu-model")
4904 parts = kdu_model.split(sep=":")
4905 if len(parts) == 2:
4906 kdu_model = parts[0]
limon96cb6d82022-10-28 10:39:16 +02004907 if desc_params.get("kdu_atomic_upgrade"):
4908 atomic_upgrade = desc_params.get("kdu_atomic_upgrade").lower() in ("yes", "true", "1")
4909 del desc_params["kdu_atomic_upgrade"]
4910 else:
4911 atomic_upgrade = True
tierno067e04a2020-03-31 12:53:13 +00004912
4913 detailed_status = await asyncio.wait_for(
4914 self.k8scluster_map[kdu["k8scluster-type"]].upgrade(
4915 cluster_uuid=kdu.get("k8scluster-uuid"),
4916 kdu_instance=kdu.get("kdu-instance"),
limon96cb6d82022-10-28 10:39:16 +02004917 atomic=atomic_upgrade,
garciadeblas5697b8b2021-03-24 09:17:02 +01004918 kdu_model=kdu_model,
4919 params=desc_params,
4920 db_dict=db_dict,
4921 timeout=timeout_ns_action,
4922 ),
4923 timeout=timeout_ns_action + 10,
4924 )
4925 self.logger.debug(
4926 logging_text + " Upgrade of kdu {} done".format(detailed_status)
4927 )
tiernoa278b842020-07-08 15:33:55 +00004928 elif primitive_name == "rollback":
tierno067e04a2020-03-31 12:53:13 +00004929 detailed_status = await asyncio.wait_for(
4930 self.k8scluster_map[kdu["k8scluster-type"]].rollback(
4931 cluster_uuid=kdu.get("k8scluster-uuid"),
4932 kdu_instance=kdu.get("kdu-instance"),
garciadeblas5697b8b2021-03-24 09:17:02 +01004933 db_dict=db_dict,
4934 ),
4935 timeout=timeout_ns_action,
4936 )
tiernoa278b842020-07-08 15:33:55 +00004937 elif primitive_name == "status":
tierno067e04a2020-03-31 12:53:13 +00004938 detailed_status = await asyncio.wait_for(
4939 self.k8scluster_map[kdu["k8scluster-type"]].status_kdu(
4940 cluster_uuid=kdu.get("k8scluster-uuid"),
David Garciac1fe90a2021-03-31 19:12:02 +02004941 kdu_instance=kdu.get("kdu-instance"),
4942 vca_id=vca_id,
4943 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01004944 timeout=timeout_ns_action,
David Garciac1fe90a2021-03-31 19:12:02 +02004945 )
Dominik Fleischmann771c32b2020-04-07 12:39:36 +02004946 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004947 kdu_instance = kdu.get("kdu-instance") or "{}-{}".format(
4948 kdu["kdu-name"], nsr_id
4949 )
4950 params = self._map_primitive_params(
4951 config_primitive_desc, primitive_params, desc_params
4952 )
Dominik Fleischmann771c32b2020-04-07 12:39:36 +02004953
4954 detailed_status = await asyncio.wait_for(
4955 self.k8scluster_map[kdu["k8scluster-type"]].exec_primitive(
4956 cluster_uuid=kdu.get("k8scluster-uuid"),
4957 kdu_instance=kdu_instance,
tiernoa278b842020-07-08 15:33:55 +00004958 primitive_name=primitive_name,
garciadeblas5697b8b2021-03-24 09:17:02 +01004959 params=params,
4960 db_dict=db_dict,
David Garciac1fe90a2021-03-31 19:12:02 +02004961 timeout=timeout_ns_action,
4962 vca_id=vca_id,
4963 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01004964 timeout=timeout_ns_action,
David Garciac1fe90a2021-03-31 19:12:02 +02004965 )
tierno067e04a2020-03-31 12:53:13 +00004966
4967 if detailed_status:
garciadeblas5697b8b2021-03-24 09:17:02 +01004968 nslcmop_operation_state = "COMPLETED"
tierno067e04a2020-03-31 12:53:13 +00004969 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004970 detailed_status = ""
4971 nslcmop_operation_state = "FAILED"
tierno067e04a2020-03-31 12:53:13 +00004972 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01004973 ee_id, vca_type = self._look_for_deployed_vca(
4974 nsr_deployed["VCA"],
4975 member_vnf_index=vnf_index,
4976 vdu_id=vdu_id,
4977 vdu_count_index=vdu_count_index,
4978 ee_descriptor_id=ee_descriptor_id,
4979 )
4980 for vca_index, vca_deployed in enumerate(
4981 db_nsr["_admin"]["deployed"]["VCA"]
4982 ):
ksaikiranrb1c9f372021-03-15 11:07:29 +05304983 if vca_deployed.get("member-vnf-index") == vnf_index:
garciadeblas5697b8b2021-03-24 09:17:02 +01004984 db_dict = {
4985 "collection": "nsrs",
4986 "filter": {"_id": nsr_id},
4987 "path": "_admin.deployed.VCA.{}.".format(vca_index),
4988 }
ksaikiranrb1c9f372021-03-15 11:07:29 +05304989 break
garciadeblas5697b8b2021-03-24 09:17:02 +01004990 (
4991 nslcmop_operation_state,
4992 detailed_status,
4993 ) = await self._ns_execute_primitive(
tierno588547c2020-07-01 15:30:20 +00004994 ee_id,
tiernoa278b842020-07-08 15:33:55 +00004995 primitive=primitive_name,
garciadeblas5697b8b2021-03-24 09:17:02 +01004996 primitive_params=self._map_primitive_params(
4997 config_primitive_desc, primitive_params, desc_params
4998 ),
tierno588547c2020-07-01 15:30:20 +00004999 timeout=timeout_ns_action,
5000 vca_type=vca_type,
David Garciac1fe90a2021-03-31 19:12:02 +02005001 db_dict=db_dict,
5002 vca_id=vca_id,
5003 )
tierno067e04a2020-03-31 12:53:13 +00005004
5005 db_nslcmop_update["detailed-status"] = detailed_status
garciadeblas5697b8b2021-03-24 09:17:02 +01005006 error_description_nslcmop = (
5007 detailed_status if nslcmop_operation_state == "FAILED" else ""
5008 )
5009 self.logger.debug(
5010 logging_text
5011 + " task Done with result {} {}".format(
5012 nslcmop_operation_state, detailed_status
5013 )
5014 )
tierno59d22d22018-09-25 18:10:19 +02005015 return # database update is called inside finally
5016
tiernof59ad6c2020-04-08 12:50:52 +00005017 except (DbException, LcmException, N2VCException, K8sException) as e:
tierno59d22d22018-09-25 18:10:19 +02005018 self.logger.error(logging_text + "Exit Exception {}".format(e))
5019 exc = e
5020 except asyncio.CancelledError:
garciadeblas5697b8b2021-03-24 09:17:02 +01005021 self.logger.error(
5022 logging_text + "Cancelled Exception while '{}'".format(step)
5023 )
tierno59d22d22018-09-25 18:10:19 +02005024 exc = "Operation was cancelled"
tierno067e04a2020-03-31 12:53:13 +00005025 except asyncio.TimeoutError:
5026 self.logger.error(logging_text + "Timeout while '{}'".format(step))
5027 exc = "Timeout"
tierno59d22d22018-09-25 18:10:19 +02005028 except Exception as e:
5029 exc = traceback.format_exc()
garciadeblas5697b8b2021-03-24 09:17:02 +01005030 self.logger.critical(
5031 logging_text + "Exit Exception {} {}".format(type(e).__name__, e),
5032 exc_info=True,
5033 )
tierno59d22d22018-09-25 18:10:19 +02005034 finally:
tierno067e04a2020-03-31 12:53:13 +00005035 if exc:
garciadeblas5697b8b2021-03-24 09:17:02 +01005036 db_nslcmop_update[
5037 "detailed-status"
5038 ] = (
5039 detailed_status
5040 ) = error_description_nslcmop = "FAILED {}: {}".format(step, exc)
tierno067e04a2020-03-31 12:53:13 +00005041 nslcmop_operation_state = "FAILED"
5042 if db_nsr:
5043 self._write_ns_status(
5044 nsr_id=nsr_id,
garciadeblas5697b8b2021-03-24 09:17:02 +01005045 ns_state=db_nsr[
5046 "nsState"
5047 ], # TODO check if degraded. For the moment use previous status
tierno067e04a2020-03-31 12:53:13 +00005048 current_operation="IDLE",
5049 current_operation_id=None,
5050 # error_description=error_description_nsr,
5051 # error_detail=error_detail,
garciadeblas5697b8b2021-03-24 09:17:02 +01005052 other_update=db_nsr_update,
tierno067e04a2020-03-31 12:53:13 +00005053 )
5054
garciadeblas5697b8b2021-03-24 09:17:02 +01005055 self._write_op_status(
5056 op_id=nslcmop_id,
5057 stage="",
5058 error_message=error_description_nslcmop,
5059 operation_state=nslcmop_operation_state,
5060 other_update=db_nslcmop_update,
5061 )
tierno067e04a2020-03-31 12:53:13 +00005062
tierno59d22d22018-09-25 18:10:19 +02005063 if nslcmop_operation_state:
5064 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01005065 await self.msg.aiowrite(
5066 "ns",
5067 "actioned",
5068 {
5069 "nsr_id": nsr_id,
5070 "nslcmop_id": nslcmop_id,
5071 "operationState": nslcmop_operation_state,
5072 },
5073 loop=self.loop,
5074 )
tierno59d22d22018-09-25 18:10:19 +02005075 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01005076 self.logger.error(
5077 logging_text + "kafka_write notification Exception {}".format(e)
5078 )
tierno59d22d22018-09-25 18:10:19 +02005079 self.logger.debug(logging_text + "Exit")
5080 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_action")
tierno067e04a2020-03-31 12:53:13 +00005081 return nslcmop_operation_state, detailed_status
tierno59d22d22018-09-25 18:10:19 +02005082
5083 async def scale(self, nsr_id, nslcmop_id):
kuused124bfe2019-06-18 12:09:24 +02005084 # Try to lock HA task here
garciadeblas5697b8b2021-03-24 09:17:02 +01005085 task_is_locked_by_me = self.lcm_tasks.lock_HA("ns", "nslcmops", nslcmop_id)
kuused124bfe2019-06-18 12:09:24 +02005086 if not task_is_locked_by_me:
5087 return
5088
tierno59d22d22018-09-25 18:10:19 +02005089 logging_text = "Task ns={} scale={} ".format(nsr_id, nslcmop_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01005090 stage = ["", "", ""]
aktas13251562021-02-12 22:19:10 +03005091 tasks_dict_info = {}
tierno2357f4e2020-10-19 16:38:59 +00005092 # ^ stage, step, VIM progress
tierno59d22d22018-09-25 18:10:19 +02005093 self.logger.debug(logging_text + "Enter")
5094 # get all needed from database
5095 db_nsr = None
tierno59d22d22018-09-25 18:10:19 +02005096 db_nslcmop_update = {}
tiernoe876f672020-02-13 14:34:48 +00005097 db_nsr_update = {}
tierno59d22d22018-09-25 18:10:19 +02005098 exc = None
tierno9ab95942018-10-10 16:44:22 +02005099 # in case of error, indicates what part of scale was failed to put nsr at error status
5100 scale_process = None
tiernod6de1992018-10-11 13:05:52 +02005101 old_operational_status = ""
5102 old_config_status = ""
aktas13251562021-02-12 22:19:10 +03005103 nsi_id = None
tierno59d22d22018-09-25 18:10:19 +02005104 try:
kuused124bfe2019-06-18 12:09:24 +02005105 # wait for any previous tasks in process
tierno3cf81a32019-11-11 17:07:00 +00005106 step = "Waiting for previous operations to terminate"
garciadeblas5697b8b2021-03-24 09:17:02 +01005107 await self.lcm_tasks.waitfor_related_HA("ns", "nslcmops", nslcmop_id)
5108 self._write_ns_status(
5109 nsr_id=nsr_id,
5110 ns_state=None,
5111 current_operation="SCALING",
5112 current_operation_id=nslcmop_id,
5113 )
quilesj4cda56b2019-12-05 10:02:20 +00005114
ikalyvas02d9e7b2019-05-27 18:16:01 +03005115 step = "Getting nslcmop from database"
garciadeblas5697b8b2021-03-24 09:17:02 +01005116 self.logger.debug(
5117 step + " after having waited for previous tasks to be completed"
5118 )
ikalyvas02d9e7b2019-05-27 18:16:01 +03005119 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
bravof922c4172020-11-24 21:21:43 -03005120
ikalyvas02d9e7b2019-05-27 18:16:01 +03005121 step = "Getting nsr from database"
5122 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
ikalyvas02d9e7b2019-05-27 18:16:01 +03005123 old_operational_status = db_nsr["operational-status"]
5124 old_config_status = db_nsr["config-status"]
bravof922c4172020-11-24 21:21:43 -03005125
tierno59d22d22018-09-25 18:10:19 +02005126 step = "Parsing scaling parameters"
5127 db_nsr_update["operational-status"] = "scaling"
5128 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernoe4f7e6c2018-11-27 14:55:30 +00005129 nsr_deployed = db_nsr["_admin"].get("deployed")
calvinosanch9f9c6f22019-11-04 13:37:39 +01005130
garciadeblas5697b8b2021-03-24 09:17:02 +01005131 vnf_index = db_nslcmop["operationParams"]["scaleVnfData"][
5132 "scaleByStepData"
5133 ]["member-vnf-index"]
5134 scaling_group = db_nslcmop["operationParams"]["scaleVnfData"][
5135 "scaleByStepData"
5136 ]["scaling-group-descriptor"]
tierno59d22d22018-09-25 18:10:19 +02005137 scaling_type = db_nslcmop["operationParams"]["scaleVnfData"]["scaleVnfType"]
tierno82974b22018-11-27 21:55:36 +00005138 # for backward compatibility
5139 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
5140 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
5141 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
5142 self.update_db_2("nsrs", nsr_id, db_nsr_update)
5143
tierno59d22d22018-09-25 18:10:19 +02005144 step = "Getting vnfr from database"
garciadeblas5697b8b2021-03-24 09:17:02 +01005145 db_vnfr = self.db.get_one(
5146 "vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id}
5147 )
bravof922c4172020-11-24 21:21:43 -03005148
David Garciac1fe90a2021-03-31 19:12:02 +02005149 vca_id = self.get_vca_id(db_vnfr, db_nsr)
5150
tierno59d22d22018-09-25 18:10:19 +02005151 step = "Getting vnfd from database"
5152 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
ikalyvas02d9e7b2019-05-27 18:16:01 +03005153
aktas13251562021-02-12 22:19:10 +03005154 base_folder = db_vnfd["_admin"]["storage"]
5155
tierno59d22d22018-09-25 18:10:19 +02005156 step = "Getting scaling-group-descriptor"
bravof832f8992020-12-07 12:57:31 -03005157 scaling_descriptor = find_in_list(
garciadeblas5697b8b2021-03-24 09:17:02 +01005158 get_scaling_aspect(db_vnfd),
5159 lambda scale_desc: scale_desc["name"] == scaling_group,
bravof832f8992020-12-07 12:57:31 -03005160 )
5161 if not scaling_descriptor:
garciadeblas5697b8b2021-03-24 09:17:02 +01005162 raise LcmException(
5163 "input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
5164 "at vnfd:scaling-group-descriptor".format(scaling_group)
5165 )
ikalyvas02d9e7b2019-05-27 18:16:01 +03005166
tierno15b1cf12019-08-29 13:21:40 +00005167 step = "Sending scale order to VIM"
bravof922c4172020-11-24 21:21:43 -03005168 # TODO check if ns is in a proper status
tierno59d22d22018-09-25 18:10:19 +02005169 nb_scale_op = 0
5170 if not db_nsr["_admin"].get("scaling-group"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005171 self.update_db_2(
5172 "nsrs",
5173 nsr_id,
5174 {
5175 "_admin.scaling-group": [
5176 {"name": scaling_group, "nb-scale-op": 0}
5177 ]
5178 },
5179 )
tierno59d22d22018-09-25 18:10:19 +02005180 admin_scale_index = 0
5181 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01005182 for admin_scale_index, admin_scale_info in enumerate(
5183 db_nsr["_admin"]["scaling-group"]
5184 ):
tierno59d22d22018-09-25 18:10:19 +02005185 if admin_scale_info["name"] == scaling_group:
5186 nb_scale_op = admin_scale_info.get("nb-scale-op", 0)
5187 break
tierno9ab95942018-10-10 16:44:22 +02005188 else: # not found, set index one plus last element and add new entry with the name
5189 admin_scale_index += 1
garciadeblas5697b8b2021-03-24 09:17:02 +01005190 db_nsr_update[
5191 "_admin.scaling-group.{}.name".format(admin_scale_index)
5192 ] = scaling_group
aktas5f75f102021-03-15 11:26:10 +03005193
5194 vca_scaling_info = []
5195 scaling_info = {"scaling_group_name": scaling_group, "vdu": [], "kdu": []}
tierno59d22d22018-09-25 18:10:19 +02005196 if scaling_type == "SCALE_OUT":
bravof832f8992020-12-07 12:57:31 -03005197 if "aspect-delta-details" not in scaling_descriptor:
5198 raise LcmException(
5199 "Aspect delta details not fount in scaling descriptor {}".format(
5200 scaling_descriptor["name"]
5201 )
5202 )
tierno59d22d22018-09-25 18:10:19 +02005203 # count if max-instance-count is reached
bravof832f8992020-12-07 12:57:31 -03005204 deltas = scaling_descriptor.get("aspect-delta-details")["deltas"]
kuuse8b998e42019-07-30 15:22:16 +02005205
aktas5f75f102021-03-15 11:26:10 +03005206 scaling_info["scaling_direction"] = "OUT"
5207 scaling_info["vdu-create"] = {}
5208 scaling_info["kdu-create"] = {}
bravof832f8992020-12-07 12:57:31 -03005209 for delta in deltas:
aktas5f75f102021-03-15 11:26:10 +03005210 for vdu_delta in delta.get("vdu-delta", {}):
bravof832f8992020-12-07 12:57:31 -03005211 vdud = get_vdu(db_vnfd, vdu_delta["id"])
aktas5f75f102021-03-15 11:26:10 +03005212 # vdu_index also provides the number of instance of the targeted vdu
5213 vdu_count = vdu_index = get_vdur_index(db_vnfr, vdu_delta)
garciadeblas5697b8b2021-03-24 09:17:02 +01005214 cloud_init_text = self._get_vdu_cloud_init_content(
5215 vdud, db_vnfd
5216 )
tierno72ef84f2020-10-06 08:22:07 +00005217 if cloud_init_text:
garciadeblas5697b8b2021-03-24 09:17:02 +01005218 additional_params = (
5219 self._get_vdu_additional_params(db_vnfr, vdud["id"])
5220 or {}
5221 )
bravof832f8992020-12-07 12:57:31 -03005222 cloud_init_list = []
5223
5224 vdu_profile = get_vdu_profile(db_vnfd, vdu_delta["id"])
5225 max_instance_count = 10
5226 if vdu_profile and "max-number-of-instances" in vdu_profile:
garciadeblas5697b8b2021-03-24 09:17:02 +01005227 max_instance_count = vdu_profile.get(
5228 "max-number-of-instances", 10
5229 )
5230
5231 default_instance_num = get_number_of_instances(
5232 db_vnfd, vdud["id"]
5233 )
aktas5f75f102021-03-15 11:26:10 +03005234 instances_number = vdu_delta.get("number-of-instances", 1)
5235 nb_scale_op += instances_number
bravof832f8992020-12-07 12:57:31 -03005236
aktas5f75f102021-03-15 11:26:10 +03005237 new_instance_count = nb_scale_op + default_instance_num
5238 # Control if new count is over max and vdu count is less than max.
5239 # Then assign new instance count
5240 if new_instance_count > max_instance_count > vdu_count:
5241 instances_number = new_instance_count - max_instance_count
5242 else:
5243 instances_number = instances_number
bravof832f8992020-12-07 12:57:31 -03005244
aktas5f75f102021-03-15 11:26:10 +03005245 if new_instance_count > max_instance_count:
bravof832f8992020-12-07 12:57:31 -03005246 raise LcmException(
5247 "reached the limit of {} (max-instance-count) "
5248 "scaling-out operations for the "
garciadeblas5697b8b2021-03-24 09:17:02 +01005249 "scaling-group-descriptor '{}'".format(
5250 nb_scale_op, scaling_group
5251 )
bravof922c4172020-11-24 21:21:43 -03005252 )
bravof832f8992020-12-07 12:57:31 -03005253 for x in range(vdu_delta.get("number-of-instances", 1)):
5254 if cloud_init_text:
5255 # TODO Information of its own ip is not available because db_vnfr is not updated.
5256 additional_params["OSM"] = get_osm_params(
garciadeblas5697b8b2021-03-24 09:17:02 +01005257 db_vnfr, vdu_delta["id"], vdu_index + x
bravof922c4172020-11-24 21:21:43 -03005258 )
bravof832f8992020-12-07 12:57:31 -03005259 cloud_init_list.append(
5260 self._parse_cloud_init(
5261 cloud_init_text,
5262 additional_params,
5263 db_vnfd["id"],
garciadeblas5697b8b2021-03-24 09:17:02 +01005264 vdud["id"],
bravof832f8992020-12-07 12:57:31 -03005265 )
5266 )
aktas5f75f102021-03-15 11:26:10 +03005267 vca_scaling_info.append(
aktas13251562021-02-12 22:19:10 +03005268 {
5269 "osm_vdu_id": vdu_delta["id"],
5270 "member-vnf-index": vnf_index,
5271 "type": "create",
garciadeblas5697b8b2021-03-24 09:17:02 +01005272 "vdu_index": vdu_index + x,
aktas13251562021-02-12 22:19:10 +03005273 }
5274 )
aktas5f75f102021-03-15 11:26:10 +03005275 scaling_info["vdu-create"][vdu_delta["id"]] = instances_number
5276 for kdu_delta in delta.get("kdu-resource-delta", {}):
5277 kdu_profile = get_kdu_profile(db_vnfd, kdu_delta["id"])
5278 kdu_name = kdu_profile["kdu-name"]
5279 resource_name = kdu_profile["resource-name"]
5280
5281 # Might have different kdus in the same delta
5282 # Should have list for each kdu
5283 if not scaling_info["kdu-create"].get(kdu_name, None):
5284 scaling_info["kdu-create"][kdu_name] = []
5285
5286 kdur = get_kdur(db_vnfr, kdu_name)
5287 if kdur.get("helm-chart"):
5288 k8s_cluster_type = "helm-chart-v3"
5289 self.logger.debug("kdur: {}".format(kdur))
5290 if (
5291 kdur.get("helm-version")
5292 and kdur.get("helm-version") == "v2"
5293 ):
5294 k8s_cluster_type = "helm-chart"
5295 raise NotImplementedError
5296 elif kdur.get("juju-bundle"):
5297 k8s_cluster_type = "juju-bundle"
5298 else:
5299 raise LcmException(
5300 "kdu type for kdu='{}.{}' is neither helm-chart nor "
5301 "juju-bundle. Maybe an old NBI version is running".format(
5302 db_vnfr["member-vnf-index-ref"], kdu_name
5303 )
5304 )
5305
5306 max_instance_count = 10
5307 if kdu_profile and "max-number-of-instances" in kdu_profile:
5308 max_instance_count = kdu_profile.get(
5309 "max-number-of-instances", 10
5310 )
5311
5312 nb_scale_op += kdu_delta.get("number-of-instances", 1)
5313 deployed_kdu, _ = get_deployed_kdu(
5314 nsr_deployed, kdu_name, vnf_index
bravof832f8992020-12-07 12:57:31 -03005315 )
aktas5f75f102021-03-15 11:26:10 +03005316 if deployed_kdu is None:
5317 raise LcmException(
5318 "KDU '{}' for vnf '{}' not deployed".format(
5319 kdu_name, vnf_index
5320 )
5321 )
5322 kdu_instance = deployed_kdu.get("kdu-instance")
5323 instance_num = await self.k8scluster_map[
5324 k8s_cluster_type
5325 ].get_scale_count(resource_name, kdu_instance, vca_id=vca_id)
5326 kdu_replica_count = instance_num + kdu_delta.get(
garciadeblas5697b8b2021-03-24 09:17:02 +01005327 "number-of-instances", 1
5328 )
ikalyvas02d9e7b2019-05-27 18:16:01 +03005329
aktas5f75f102021-03-15 11:26:10 +03005330 # Control if new count is over max and instance_num is less than max.
5331 # Then assign max instance number to kdu replica count
5332 if kdu_replica_count > max_instance_count > instance_num:
5333 kdu_replica_count = max_instance_count
5334 if kdu_replica_count > max_instance_count:
5335 raise LcmException(
5336 "reached the limit of {} (max-instance-count) "
5337 "scaling-out operations for the "
5338 "scaling-group-descriptor '{}'".format(
5339 instance_num, scaling_group
5340 )
5341 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005342
aktas5f75f102021-03-15 11:26:10 +03005343 for x in range(kdu_delta.get("number-of-instances", 1)):
5344 vca_scaling_info.append(
5345 {
5346 "osm_kdu_id": kdu_name,
5347 "member-vnf-index": vnf_index,
5348 "type": "create",
5349 "kdu_index": instance_num + x - 1,
5350 }
5351 )
5352 scaling_info["kdu-create"][kdu_name].append(
5353 {
5354 "member-vnf-index": vnf_index,
5355 "type": "create",
5356 "k8s-cluster-type": k8s_cluster_type,
5357 "resource-name": resource_name,
5358 "scale": kdu_replica_count,
5359 }
5360 )
5361 elif scaling_type == "SCALE_IN":
bravof832f8992020-12-07 12:57:31 -03005362 deltas = scaling_descriptor.get("aspect-delta-details")["deltas"]
aktas5f75f102021-03-15 11:26:10 +03005363
5364 scaling_info["scaling_direction"] = "IN"
5365 scaling_info["vdu-delete"] = {}
5366 scaling_info["kdu-delete"] = {}
5367
bravof832f8992020-12-07 12:57:31 -03005368 for delta in deltas:
aktas5f75f102021-03-15 11:26:10 +03005369 for vdu_delta in delta.get("vdu-delta", {}):
5370 vdu_count = vdu_index = get_vdur_index(db_vnfr, vdu_delta)
bravof832f8992020-12-07 12:57:31 -03005371 min_instance_count = 0
5372 vdu_profile = get_vdu_profile(db_vnfd, vdu_delta["id"])
5373 if vdu_profile and "min-number-of-instances" in vdu_profile:
5374 min_instance_count = vdu_profile["min-number-of-instances"]
5375
garciadeblas5697b8b2021-03-24 09:17:02 +01005376 default_instance_num = get_number_of_instances(
5377 db_vnfd, vdu_delta["id"]
5378 )
aktas5f75f102021-03-15 11:26:10 +03005379 instance_num = vdu_delta.get("number-of-instances", 1)
5380 nb_scale_op -= instance_num
bravof832f8992020-12-07 12:57:31 -03005381
aktas5f75f102021-03-15 11:26:10 +03005382 new_instance_count = nb_scale_op + default_instance_num
5383
5384 if new_instance_count < min_instance_count < vdu_count:
5385 instances_number = min_instance_count - new_instance_count
5386 else:
5387 instances_number = instance_num
5388
5389 if new_instance_count < min_instance_count:
bravof832f8992020-12-07 12:57:31 -03005390 raise LcmException(
5391 "reached the limit of {} (min-instance-count) scaling-in operations for the "
garciadeblas5697b8b2021-03-24 09:17:02 +01005392 "scaling-group-descriptor '{}'".format(
5393 nb_scale_op, scaling_group
5394 )
bravof832f8992020-12-07 12:57:31 -03005395 )
aktas13251562021-02-12 22:19:10 +03005396 for x in range(vdu_delta.get("number-of-instances", 1)):
aktas5f75f102021-03-15 11:26:10 +03005397 vca_scaling_info.append(
aktas13251562021-02-12 22:19:10 +03005398 {
5399 "osm_vdu_id": vdu_delta["id"],
5400 "member-vnf-index": vnf_index,
5401 "type": "delete",
garciadeblas5697b8b2021-03-24 09:17:02 +01005402 "vdu_index": vdu_index - 1 - x,
aktas13251562021-02-12 22:19:10 +03005403 }
5404 )
aktas5f75f102021-03-15 11:26:10 +03005405 scaling_info["vdu-delete"][vdu_delta["id"]] = instances_number
5406 for kdu_delta in delta.get("kdu-resource-delta", {}):
5407 kdu_profile = get_kdu_profile(db_vnfd, kdu_delta["id"])
5408 kdu_name = kdu_profile["kdu-name"]
5409 resource_name = kdu_profile["resource-name"]
5410
5411 if not scaling_info["kdu-delete"].get(kdu_name, None):
5412 scaling_info["kdu-delete"][kdu_name] = []
5413
5414 kdur = get_kdur(db_vnfr, kdu_name)
5415 if kdur.get("helm-chart"):
5416 k8s_cluster_type = "helm-chart-v3"
5417 self.logger.debug("kdur: {}".format(kdur))
5418 if (
5419 kdur.get("helm-version")
5420 and kdur.get("helm-version") == "v2"
5421 ):
5422 k8s_cluster_type = "helm-chart"
5423 raise NotImplementedError
5424 elif kdur.get("juju-bundle"):
5425 k8s_cluster_type = "juju-bundle"
5426 else:
5427 raise LcmException(
5428 "kdu type for kdu='{}.{}' is neither helm-chart nor "
5429 "juju-bundle. Maybe an old NBI version is running".format(
5430 db_vnfr["member-vnf-index-ref"], kdur["kdu-name"]
5431 )
5432 )
5433
5434 min_instance_count = 0
5435 if kdu_profile and "min-number-of-instances" in kdu_profile:
5436 min_instance_count = kdu_profile["min-number-of-instances"]
5437
5438 nb_scale_op -= kdu_delta.get("number-of-instances", 1)
5439 deployed_kdu, _ = get_deployed_kdu(
5440 nsr_deployed, kdu_name, vnf_index
5441 )
5442 if deployed_kdu is None:
5443 raise LcmException(
5444 "KDU '{}' for vnf '{}' not deployed".format(
5445 kdu_name, vnf_index
5446 )
5447 )
5448 kdu_instance = deployed_kdu.get("kdu-instance")
5449 instance_num = await self.k8scluster_map[
5450 k8s_cluster_type
5451 ].get_scale_count(resource_name, kdu_instance, vca_id=vca_id)
5452 kdu_replica_count = instance_num - kdu_delta.get(
garciadeblas5697b8b2021-03-24 09:17:02 +01005453 "number-of-instances", 1
5454 )
tierno59d22d22018-09-25 18:10:19 +02005455
aktas5f75f102021-03-15 11:26:10 +03005456 if kdu_replica_count < min_instance_count < instance_num:
5457 kdu_replica_count = min_instance_count
5458 if kdu_replica_count < min_instance_count:
5459 raise LcmException(
5460 "reached the limit of {} (min-instance-count) scaling-in operations for the "
5461 "scaling-group-descriptor '{}'".format(
5462 instance_num, scaling_group
5463 )
5464 )
5465
5466 for x in range(kdu_delta.get("number-of-instances", 1)):
5467 vca_scaling_info.append(
5468 {
5469 "osm_kdu_id": kdu_name,
5470 "member-vnf-index": vnf_index,
5471 "type": "delete",
5472 "kdu_index": instance_num - x - 1,
5473 }
5474 )
5475 scaling_info["kdu-delete"][kdu_name].append(
5476 {
5477 "member-vnf-index": vnf_index,
5478 "type": "delete",
5479 "k8s-cluster-type": k8s_cluster_type,
5480 "resource-name": resource_name,
5481 "scale": kdu_replica_count,
5482 }
5483 )
5484
tierno59d22d22018-09-25 18:10:19 +02005485 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
aktas5f75f102021-03-15 11:26:10 +03005486 vdu_delete = copy(scaling_info.get("vdu-delete"))
5487 if scaling_info["scaling_direction"] == "IN":
tierno59d22d22018-09-25 18:10:19 +02005488 for vdur in reversed(db_vnfr["vdur"]):
tierno27246d82018-09-27 15:59:09 +02005489 if vdu_delete.get(vdur["vdu-id-ref"]):
5490 vdu_delete[vdur["vdu-id-ref"]] -= 1
aktas5f75f102021-03-15 11:26:10 +03005491 scaling_info["vdu"].append(
garciadeblas5697b8b2021-03-24 09:17:02 +01005492 {
5493 "name": vdur.get("name") or vdur.get("vdu-name"),
5494 "vdu_id": vdur["vdu-id-ref"],
5495 "interface": [],
5496 }
5497 )
tierno59d22d22018-09-25 18:10:19 +02005498 for interface in vdur["interfaces"]:
aktas5f75f102021-03-15 11:26:10 +03005499 scaling_info["vdu"][-1]["interface"].append(
garciadeblas5697b8b2021-03-24 09:17:02 +01005500 {
5501 "name": interface["name"],
5502 "ip_address": interface["ip-address"],
5503 "mac_address": interface.get("mac-address"),
5504 }
5505 )
tierno2357f4e2020-10-19 16:38:59 +00005506 # vdu_delete = vdu_scaling_info.pop("vdu-delete")
tierno59d22d22018-09-25 18:10:19 +02005507
kuuseac3a8882019-10-03 10:48:06 +02005508 # PRE-SCALE BEGIN
tierno59d22d22018-09-25 18:10:19 +02005509 step = "Executing pre-scale vnf-config-primitive"
5510 if scaling_descriptor.get("scaling-config-action"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005511 for scaling_config_action in scaling_descriptor[
5512 "scaling-config-action"
5513 ]:
5514 if (
5515 scaling_config_action.get("trigger") == "pre-scale-in"
5516 and scaling_type == "SCALE_IN"
5517 ) or (
5518 scaling_config_action.get("trigger") == "pre-scale-out"
5519 and scaling_type == "SCALE_OUT"
5520 ):
5521 vnf_config_primitive = scaling_config_action[
5522 "vnf-config-primitive-name-ref"
5523 ]
5524 step = db_nslcmop_update[
5525 "detailed-status"
5526 ] = "executing pre-scale scaling-config-action '{}'".format(
5527 vnf_config_primitive
5528 )
tiernoda964822019-01-14 15:53:47 +00005529
tierno59d22d22018-09-25 18:10:19 +02005530 # look for primitive
garciadeblas5697b8b2021-03-24 09:17:02 +01005531 for config_primitive in (
5532 get_configuration(db_vnfd, db_vnfd["id"]) or {}
5533 ).get("config-primitive", ()):
tierno59d22d22018-09-25 18:10:19 +02005534 if config_primitive["name"] == vnf_config_primitive:
tierno59d22d22018-09-25 18:10:19 +02005535 break
5536 else:
5537 raise LcmException(
5538 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
tiernoda964822019-01-14 15:53:47 +00005539 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
garciadeblas5697b8b2021-03-24 09:17:02 +01005540 "primitive".format(scaling_group, vnf_config_primitive)
5541 )
tiernoda964822019-01-14 15:53:47 +00005542
aktas5f75f102021-03-15 11:26:10 +03005543 vnfr_params = {"VDU_SCALE_INFO": scaling_info}
tiernoda964822019-01-14 15:53:47 +00005544 if db_vnfr.get("additionalParamsForVnf"):
5545 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
quilesj7e13aeb2019-10-08 13:34:55 +02005546
tierno9ab95942018-10-10 16:44:22 +02005547 scale_process = "VCA"
tiernod6de1992018-10-11 13:05:52 +02005548 db_nsr_update["config-status"] = "configuring pre-scaling"
garciadeblas5697b8b2021-03-24 09:17:02 +01005549 primitive_params = self._map_primitive_params(
5550 config_primitive, {}, vnfr_params
5551 )
kuuseac3a8882019-10-03 10:48:06 +02005552
tierno7c4e24c2020-05-13 08:41:35 +00005553 # Pre-scale retry check: Check if this sub-operation has been executed before
kuuseac3a8882019-10-03 10:48:06 +02005554 op_index = self._check_or_add_scale_suboperation(
garciadeblas5697b8b2021-03-24 09:17:02 +01005555 db_nslcmop,
garciadeblas5697b8b2021-03-24 09:17:02 +01005556 vnf_index,
5557 vnf_config_primitive,
5558 primitive_params,
5559 "PRE-SCALE",
5560 )
tierno7c4e24c2020-05-13 08:41:35 +00005561 if op_index == self.SUBOPERATION_STATUS_SKIP:
kuuseac3a8882019-10-03 10:48:06 +02005562 # Skip sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01005563 result = "COMPLETED"
5564 result_detail = "Done"
5565 self.logger.debug(
5566 logging_text
5567 + "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
5568 vnf_config_primitive, result, result_detail
5569 )
5570 )
kuuseac3a8882019-10-03 10:48:06 +02005571 else:
tierno7c4e24c2020-05-13 08:41:35 +00005572 if op_index == self.SUBOPERATION_STATUS_NEW:
kuuseac3a8882019-10-03 10:48:06 +02005573 # New sub-operation: Get index of this sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01005574 op_index = (
5575 len(db_nslcmop.get("_admin", {}).get("operations"))
5576 - 1
5577 )
5578 self.logger.debug(
5579 logging_text
5580 + "vnf_config_primitive={} New sub-operation".format(
5581 vnf_config_primitive
5582 )
5583 )
kuuseac3a8882019-10-03 10:48:06 +02005584 else:
tierno7c4e24c2020-05-13 08:41:35 +00005585 # retry: Get registered params for this existing sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01005586 op = db_nslcmop.get("_admin", {}).get("operations", [])[
5587 op_index
5588 ]
5589 vnf_index = op.get("member_vnf_index")
5590 vnf_config_primitive = op.get("primitive")
5591 primitive_params = op.get("primitive_params")
5592 self.logger.debug(
5593 logging_text
5594 + "vnf_config_primitive={} Sub-operation retry".format(
5595 vnf_config_primitive
5596 )
5597 )
tierno588547c2020-07-01 15:30:20 +00005598 # Execute the primitive, either with new (first-time) or registered (reintent) args
garciadeblas5697b8b2021-03-24 09:17:02 +01005599 ee_descriptor_id = config_primitive.get(
5600 "execution-environment-ref"
5601 )
5602 primitive_name = config_primitive.get(
5603 "execution-environment-primitive", vnf_config_primitive
5604 )
5605 ee_id, vca_type = self._look_for_deployed_vca(
5606 nsr_deployed["VCA"],
5607 member_vnf_index=vnf_index,
5608 vdu_id=None,
5609 vdu_count_index=None,
5610 ee_descriptor_id=ee_descriptor_id,
5611 )
kuuseac3a8882019-10-03 10:48:06 +02005612 result, result_detail = await self._ns_execute_primitive(
garciadeblas5697b8b2021-03-24 09:17:02 +01005613 ee_id,
5614 primitive_name,
David Garciac1fe90a2021-03-31 19:12:02 +02005615 primitive_params,
5616 vca_type=vca_type,
5617 vca_id=vca_id,
5618 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005619 self.logger.debug(
5620 logging_text
5621 + "vnf_config_primitive={} Done with result {} {}".format(
5622 vnf_config_primitive, result, result_detail
5623 )
5624 )
kuuseac3a8882019-10-03 10:48:06 +02005625 # Update operationState = COMPLETED | FAILED
5626 self._update_suboperation_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01005627 db_nslcmop, op_index, result, result_detail
5628 )
kuuseac3a8882019-10-03 10:48:06 +02005629
tierno59d22d22018-09-25 18:10:19 +02005630 if result == "FAILED":
5631 raise LcmException(result_detail)
tiernod6de1992018-10-11 13:05:52 +02005632 db_nsr_update["config-status"] = old_config_status
5633 scale_process = None
kuuseac3a8882019-10-03 10:48:06 +02005634 # PRE-SCALE END
tierno59d22d22018-09-25 18:10:19 +02005635
garciadeblas5697b8b2021-03-24 09:17:02 +01005636 db_nsr_update[
5637 "_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index)
5638 ] = nb_scale_op
5639 db_nsr_update[
5640 "_admin.scaling-group.{}.time".format(admin_scale_index)
5641 ] = time()
tierno2357f4e2020-10-19 16:38:59 +00005642
aktas13251562021-02-12 22:19:10 +03005643 # SCALE-IN VCA - BEGIN
aktas5f75f102021-03-15 11:26:10 +03005644 if vca_scaling_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01005645 step = db_nslcmop_update[
5646 "detailed-status"
5647 ] = "Deleting the execution environments"
aktas13251562021-02-12 22:19:10 +03005648 scale_process = "VCA"
aktas5f75f102021-03-15 11:26:10 +03005649 for vca_info in vca_scaling_info:
5650 if vca_info["type"] == "delete":
5651 member_vnf_index = str(vca_info["member-vnf-index"])
garciadeblas5697b8b2021-03-24 09:17:02 +01005652 self.logger.debug(
aktas5f75f102021-03-15 11:26:10 +03005653 logging_text + "vdu info: {}".format(vca_info)
garciadeblas5697b8b2021-03-24 09:17:02 +01005654 )
aktas5f75f102021-03-15 11:26:10 +03005655 if vca_info.get("osm_vdu_id"):
5656 vdu_id = vca_info["osm_vdu_id"]
5657 vdu_index = int(vca_info["vdu_index"])
5658 stage[
5659 1
5660 ] = "Scaling member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
5661 member_vnf_index, vdu_id, vdu_index
5662 )
5663 else:
5664 vdu_index = 0
5665 kdu_id = vca_info["osm_kdu_id"]
5666 stage[
5667 1
5668 ] = "Scaling member_vnf_index={}, kdu_id={}, vdu_index={} ".format(
5669 member_vnf_index, kdu_id, vdu_index
5670 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005671 stage[2] = step = "Scaling in VCA"
5672 self._write_op_status(op_id=nslcmop_id, stage=stage)
aktas13251562021-02-12 22:19:10 +03005673 vca_update = db_nsr["_admin"]["deployed"]["VCA"]
5674 config_update = db_nsr["configurationStatus"]
5675 for vca_index, vca in enumerate(vca_update):
garciadeblas5697b8b2021-03-24 09:17:02 +01005676 if (
5677 (vca or vca.get("ee_id"))
5678 and vca["member-vnf-index"] == member_vnf_index
5679 and vca["vdu_count_index"] == vdu_index
5680 ):
aktas13251562021-02-12 22:19:10 +03005681 if vca.get("vdu_id"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005682 config_descriptor = get_configuration(
5683 db_vnfd, vca.get("vdu_id")
5684 )
aktas13251562021-02-12 22:19:10 +03005685 elif vca.get("kdu_name"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005686 config_descriptor = get_configuration(
5687 db_vnfd, vca.get("kdu_name")
5688 )
aktas13251562021-02-12 22:19:10 +03005689 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01005690 config_descriptor = get_configuration(
5691 db_vnfd, db_vnfd["id"]
5692 )
5693 operation_params = (
5694 db_nslcmop.get("operationParams") or {}
5695 )
5696 exec_terminate_primitives = not operation_params.get(
5697 "skip_terminate_primitives"
5698 ) and vca.get("needed_terminate")
David Garciac1fe90a2021-03-31 19:12:02 +02005699 task = asyncio.ensure_future(
5700 asyncio.wait_for(
5701 self.destroy_N2VC(
5702 logging_text,
5703 db_nslcmop,
5704 vca,
5705 config_descriptor,
5706 vca_index,
5707 destroy_ee=True,
5708 exec_primitives=exec_terminate_primitives,
5709 scaling_in=True,
5710 vca_id=vca_id,
5711 ),
garciadeblas5697b8b2021-03-24 09:17:02 +01005712 timeout=self.timeout_charm_delete,
David Garciac1fe90a2021-03-31 19:12:02 +02005713 )
5714 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005715 tasks_dict_info[task] = "Terminating VCA {}".format(
5716 vca.get("ee_id")
5717 )
aktas13251562021-02-12 22:19:10 +03005718 del vca_update[vca_index]
5719 del config_update[vca_index]
5720 # wait for pending tasks of terminate primitives
5721 if tasks_dict_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01005722 self.logger.debug(
5723 logging_text
5724 + "Waiting for tasks {}".format(
5725 list(tasks_dict_info.keys())
5726 )
5727 )
5728 error_list = await self._wait_for_tasks(
5729 logging_text,
5730 tasks_dict_info,
5731 min(
5732 self.timeout_charm_delete, self.timeout_ns_terminate
5733 ),
5734 stage,
5735 nslcmop_id,
5736 )
aktas13251562021-02-12 22:19:10 +03005737 tasks_dict_info.clear()
5738 if error_list:
5739 raise LcmException("; ".join(error_list))
5740
5741 db_vca_and_config_update = {
5742 "_admin.deployed.VCA": vca_update,
garciadeblas5697b8b2021-03-24 09:17:02 +01005743 "configurationStatus": config_update,
aktas13251562021-02-12 22:19:10 +03005744 }
garciadeblas5697b8b2021-03-24 09:17:02 +01005745 self.update_db_2(
5746 "nsrs", db_nsr["_id"], db_vca_and_config_update
5747 )
aktas13251562021-02-12 22:19:10 +03005748 scale_process = None
5749 # SCALE-IN VCA - END
5750
kuuseac3a8882019-10-03 10:48:06 +02005751 # SCALE RO - BEGIN
aktas5f75f102021-03-15 11:26:10 +03005752 if scaling_info.get("vdu-create") or scaling_info.get("vdu-delete"):
tierno9ab95942018-10-10 16:44:22 +02005753 scale_process = "RO"
tierno2357f4e2020-10-19 16:38:59 +00005754 if self.ro_config.get("ng"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005755 await self._scale_ng_ro(
aktas5f75f102021-03-15 11:26:10 +03005756 logging_text, db_nsr, db_nslcmop, db_vnfr, scaling_info, stage
garciadeblas5697b8b2021-03-24 09:17:02 +01005757 )
aktas5f75f102021-03-15 11:26:10 +03005758 scaling_info.pop("vdu-create", None)
5759 scaling_info.pop("vdu-delete", None)
tierno59d22d22018-09-25 18:10:19 +02005760
tierno9ab95942018-10-10 16:44:22 +02005761 scale_process = None
aktas13251562021-02-12 22:19:10 +03005762 # SCALE RO - END
5763
aktas5f75f102021-03-15 11:26:10 +03005764 # SCALE KDU - BEGIN
5765 if scaling_info.get("kdu-create") or scaling_info.get("kdu-delete"):
5766 scale_process = "KDU"
5767 await self._scale_kdu(
5768 logging_text, nsr_id, nsr_deployed, db_vnfd, vca_id, scaling_info
5769 )
5770 scaling_info.pop("kdu-create", None)
5771 scaling_info.pop("kdu-delete", None)
5772
5773 scale_process = None
5774 # SCALE KDU - END
5775
5776 if db_nsr_update:
5777 self.update_db_2("nsrs", nsr_id, db_nsr_update)
5778
aktas13251562021-02-12 22:19:10 +03005779 # SCALE-UP VCA - BEGIN
aktas5f75f102021-03-15 11:26:10 +03005780 if vca_scaling_info:
garciadeblas5697b8b2021-03-24 09:17:02 +01005781 step = db_nslcmop_update[
5782 "detailed-status"
5783 ] = "Creating new execution environments"
aktas13251562021-02-12 22:19:10 +03005784 scale_process = "VCA"
aktas5f75f102021-03-15 11:26:10 +03005785 for vca_info in vca_scaling_info:
5786 if vca_info["type"] == "create":
5787 member_vnf_index = str(vca_info["member-vnf-index"])
garciadeblas5697b8b2021-03-24 09:17:02 +01005788 self.logger.debug(
aktas5f75f102021-03-15 11:26:10 +03005789 logging_text + "vdu info: {}".format(vca_info)
garciadeblas5697b8b2021-03-24 09:17:02 +01005790 )
aktas13251562021-02-12 22:19:10 +03005791 vnfd_id = db_vnfr["vnfd-ref"]
aktas5f75f102021-03-15 11:26:10 +03005792 if vca_info.get("osm_vdu_id"):
5793 vdu_index = int(vca_info["vdu_index"])
5794 deploy_params = {"OSM": get_osm_params(db_vnfr)}
5795 if db_vnfr.get("additionalParamsForVnf"):
5796 deploy_params.update(
5797 parse_yaml_strings(
5798 db_vnfr["additionalParamsForVnf"].copy()
5799 )
garciadeblas5697b8b2021-03-24 09:17:02 +01005800 )
aktas5f75f102021-03-15 11:26:10 +03005801 descriptor_config = get_configuration(
5802 db_vnfd, db_vnfd["id"]
garciadeblas5697b8b2021-03-24 09:17:02 +01005803 )
aktas5f75f102021-03-15 11:26:10 +03005804 if descriptor_config:
5805 vdu_id = None
5806 vdu_name = None
5807 kdu_name = None
5808 self._deploy_n2vc(
5809 logging_text=logging_text
5810 + "member_vnf_index={} ".format(member_vnf_index),
5811 db_nsr=db_nsr,
5812 db_vnfr=db_vnfr,
5813 nslcmop_id=nslcmop_id,
5814 nsr_id=nsr_id,
5815 nsi_id=nsi_id,
5816 vnfd_id=vnfd_id,
5817 vdu_id=vdu_id,
5818 kdu_name=kdu_name,
5819 member_vnf_index=member_vnf_index,
5820 vdu_index=vdu_index,
5821 vdu_name=vdu_name,
5822 deploy_params=deploy_params,
5823 descriptor_config=descriptor_config,
5824 base_folder=base_folder,
5825 task_instantiation_info=tasks_dict_info,
5826 stage=stage,
5827 )
5828 vdu_id = vca_info["osm_vdu_id"]
5829 vdur = find_in_list(
5830 db_vnfr["vdur"], lambda vdu: vdu["vdu-id-ref"] == vdu_id
aktas13251562021-02-12 22:19:10 +03005831 )
aktas5f75f102021-03-15 11:26:10 +03005832 descriptor_config = get_configuration(db_vnfd, vdu_id)
5833 if vdur.get("additionalParams"):
5834 deploy_params_vdu = parse_yaml_strings(
5835 vdur["additionalParams"]
5836 )
5837 else:
5838 deploy_params_vdu = deploy_params
5839 deploy_params_vdu["OSM"] = get_osm_params(
5840 db_vnfr, vdu_id, vdu_count_index=vdu_index
garciadeblas5697b8b2021-03-24 09:17:02 +01005841 )
aktas5f75f102021-03-15 11:26:10 +03005842 if descriptor_config:
5843 vdu_name = None
5844 kdu_name = None
5845 stage[
5846 1
5847 ] = "Scaling member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
garciadeblas5697b8b2021-03-24 09:17:02 +01005848 member_vnf_index, vdu_id, vdu_index
aktas5f75f102021-03-15 11:26:10 +03005849 )
5850 stage[2] = step = "Scaling out VCA"
5851 self._write_op_status(op_id=nslcmop_id, stage=stage)
5852 self._deploy_n2vc(
5853 logging_text=logging_text
5854 + "member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
5855 member_vnf_index, vdu_id, vdu_index
5856 ),
5857 db_nsr=db_nsr,
5858 db_vnfr=db_vnfr,
5859 nslcmop_id=nslcmop_id,
5860 nsr_id=nsr_id,
5861 nsi_id=nsi_id,
5862 vnfd_id=vnfd_id,
5863 vdu_id=vdu_id,
5864 kdu_name=kdu_name,
5865 member_vnf_index=member_vnf_index,
5866 vdu_index=vdu_index,
5867 vdu_name=vdu_name,
5868 deploy_params=deploy_params_vdu,
5869 descriptor_config=descriptor_config,
5870 base_folder=base_folder,
5871 task_instantiation_info=tasks_dict_info,
5872 stage=stage,
5873 )
5874 else:
5875 kdu_name = vca_info["osm_kdu_id"]
5876 descriptor_config = get_configuration(db_vnfd, kdu_name)
5877 if descriptor_config:
5878 vdu_id = None
5879 kdu_index = int(vca_info["kdu_index"])
5880 vdu_name = None
5881 kdur = next(
5882 x
5883 for x in db_vnfr["kdur"]
5884 if x["kdu-name"] == kdu_name
5885 )
5886 deploy_params_kdu = {"OSM": get_osm_params(db_vnfr)}
5887 if kdur.get("additionalParams"):
5888 deploy_params_kdu = parse_yaml_strings(
5889 kdur["additionalParams"]
5890 )
5891
5892 self._deploy_n2vc(
5893 logging_text=logging_text,
5894 db_nsr=db_nsr,
5895 db_vnfr=db_vnfr,
5896 nslcmop_id=nslcmop_id,
5897 nsr_id=nsr_id,
5898 nsi_id=nsi_id,
5899 vnfd_id=vnfd_id,
5900 vdu_id=vdu_id,
5901 kdu_name=kdu_name,
5902 member_vnf_index=member_vnf_index,
5903 vdu_index=kdu_index,
5904 vdu_name=vdu_name,
5905 deploy_params=deploy_params_kdu,
5906 descriptor_config=descriptor_config,
5907 base_folder=base_folder,
5908 task_instantiation_info=tasks_dict_info,
5909 stage=stage,
5910 )
aktas13251562021-02-12 22:19:10 +03005911 # SCALE-UP VCA - END
5912 scale_process = None
tierno59d22d22018-09-25 18:10:19 +02005913
kuuseac3a8882019-10-03 10:48:06 +02005914 # POST-SCALE BEGIN
tierno59d22d22018-09-25 18:10:19 +02005915 # execute primitive service POST-SCALING
5916 step = "Executing post-scale vnf-config-primitive"
5917 if scaling_descriptor.get("scaling-config-action"):
garciadeblas5697b8b2021-03-24 09:17:02 +01005918 for scaling_config_action in scaling_descriptor[
5919 "scaling-config-action"
5920 ]:
5921 if (
5922 scaling_config_action.get("trigger") == "post-scale-in"
5923 and scaling_type == "SCALE_IN"
5924 ) or (
5925 scaling_config_action.get("trigger") == "post-scale-out"
5926 and scaling_type == "SCALE_OUT"
5927 ):
5928 vnf_config_primitive = scaling_config_action[
5929 "vnf-config-primitive-name-ref"
5930 ]
5931 step = db_nslcmop_update[
5932 "detailed-status"
5933 ] = "executing post-scale scaling-config-action '{}'".format(
5934 vnf_config_primitive
5935 )
tiernoda964822019-01-14 15:53:47 +00005936
aktas5f75f102021-03-15 11:26:10 +03005937 vnfr_params = {"VDU_SCALE_INFO": scaling_info}
tiernoda964822019-01-14 15:53:47 +00005938 if db_vnfr.get("additionalParamsForVnf"):
5939 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
5940
tierno59d22d22018-09-25 18:10:19 +02005941 # look for primitive
bravof9a256db2021-02-22 18:02:07 -03005942 for config_primitive in (
5943 get_configuration(db_vnfd, db_vnfd["id"]) or {}
5944 ).get("config-primitive", ()):
tierno59d22d22018-09-25 18:10:19 +02005945 if config_primitive["name"] == vnf_config_primitive:
tierno59d22d22018-09-25 18:10:19 +02005946 break
5947 else:
tiernoa278b842020-07-08 15:33:55 +00005948 raise LcmException(
5949 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-"
5950 "action[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:"
garciadeblas5697b8b2021-03-24 09:17:02 +01005951 "config-primitive".format(
5952 scaling_group, vnf_config_primitive
5953 )
5954 )
tierno9ab95942018-10-10 16:44:22 +02005955 scale_process = "VCA"
tiernod6de1992018-10-11 13:05:52 +02005956 db_nsr_update["config-status"] = "configuring post-scaling"
garciadeblas5697b8b2021-03-24 09:17:02 +01005957 primitive_params = self._map_primitive_params(
5958 config_primitive, {}, vnfr_params
5959 )
tiernod6de1992018-10-11 13:05:52 +02005960
tierno7c4e24c2020-05-13 08:41:35 +00005961 # Post-scale retry check: Check if this sub-operation has been executed before
kuuseac3a8882019-10-03 10:48:06 +02005962 op_index = self._check_or_add_scale_suboperation(
garciadeblas5697b8b2021-03-24 09:17:02 +01005963 db_nslcmop,
garciadeblas5697b8b2021-03-24 09:17:02 +01005964 vnf_index,
5965 vnf_config_primitive,
5966 primitive_params,
5967 "POST-SCALE",
5968 )
quilesj4cda56b2019-12-05 10:02:20 +00005969 if op_index == self.SUBOPERATION_STATUS_SKIP:
kuuseac3a8882019-10-03 10:48:06 +02005970 # Skip sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01005971 result = "COMPLETED"
5972 result_detail = "Done"
5973 self.logger.debug(
5974 logging_text
5975 + "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
5976 vnf_config_primitive, result, result_detail
5977 )
5978 )
kuuseac3a8882019-10-03 10:48:06 +02005979 else:
quilesj4cda56b2019-12-05 10:02:20 +00005980 if op_index == self.SUBOPERATION_STATUS_NEW:
kuuseac3a8882019-10-03 10:48:06 +02005981 # New sub-operation: Get index of this sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01005982 op_index = (
5983 len(db_nslcmop.get("_admin", {}).get("operations"))
5984 - 1
5985 )
5986 self.logger.debug(
5987 logging_text
5988 + "vnf_config_primitive={} New sub-operation".format(
5989 vnf_config_primitive
5990 )
5991 )
kuuseac3a8882019-10-03 10:48:06 +02005992 else:
tierno7c4e24c2020-05-13 08:41:35 +00005993 # retry: Get registered params for this existing sub-operation
garciadeblas5697b8b2021-03-24 09:17:02 +01005994 op = db_nslcmop.get("_admin", {}).get("operations", [])[
5995 op_index
5996 ]
5997 vnf_index = op.get("member_vnf_index")
5998 vnf_config_primitive = op.get("primitive")
5999 primitive_params = op.get("primitive_params")
6000 self.logger.debug(
6001 logging_text
6002 + "vnf_config_primitive={} Sub-operation retry".format(
6003 vnf_config_primitive
6004 )
6005 )
tierno588547c2020-07-01 15:30:20 +00006006 # Execute the primitive, either with new (first-time) or registered (reintent) args
garciadeblas5697b8b2021-03-24 09:17:02 +01006007 ee_descriptor_id = config_primitive.get(
6008 "execution-environment-ref"
6009 )
6010 primitive_name = config_primitive.get(
6011 "execution-environment-primitive", vnf_config_primitive
6012 )
6013 ee_id, vca_type = self._look_for_deployed_vca(
6014 nsr_deployed["VCA"],
6015 member_vnf_index=vnf_index,
6016 vdu_id=None,
6017 vdu_count_index=None,
6018 ee_descriptor_id=ee_descriptor_id,
6019 )
kuuseac3a8882019-10-03 10:48:06 +02006020 result, result_detail = await self._ns_execute_primitive(
David Garciac1fe90a2021-03-31 19:12:02 +02006021 ee_id,
6022 primitive_name,
6023 primitive_params,
6024 vca_type=vca_type,
6025 vca_id=vca_id,
6026 )
garciadeblas5697b8b2021-03-24 09:17:02 +01006027 self.logger.debug(
6028 logging_text
6029 + "vnf_config_primitive={} Done with result {} {}".format(
6030 vnf_config_primitive, result, result_detail
6031 )
6032 )
kuuseac3a8882019-10-03 10:48:06 +02006033 # Update operationState = COMPLETED | FAILED
6034 self._update_suboperation_status(
garciadeblas5697b8b2021-03-24 09:17:02 +01006035 db_nslcmop, op_index, result, result_detail
6036 )
kuuseac3a8882019-10-03 10:48:06 +02006037
tierno59d22d22018-09-25 18:10:19 +02006038 if result == "FAILED":
6039 raise LcmException(result_detail)
tiernod6de1992018-10-11 13:05:52 +02006040 db_nsr_update["config-status"] = old_config_status
6041 scale_process = None
kuuseac3a8882019-10-03 10:48:06 +02006042 # POST-SCALE END
tierno59d22d22018-09-25 18:10:19 +02006043
garciadeblas5697b8b2021-03-24 09:17:02 +01006044 db_nsr_update[
6045 "detailed-status"
6046 ] = "" # "scaled {} {}".format(scaling_group, scaling_type)
6047 db_nsr_update["operational-status"] = (
6048 "running"
6049 if old_operational_status == "failed"
ikalyvas02d9e7b2019-05-27 18:16:01 +03006050 else old_operational_status
garciadeblas5697b8b2021-03-24 09:17:02 +01006051 )
tiernod6de1992018-10-11 13:05:52 +02006052 db_nsr_update["config-status"] = old_config_status
tierno59d22d22018-09-25 18:10:19 +02006053 return
garciadeblas5697b8b2021-03-24 09:17:02 +01006054 except (
6055 ROclient.ROClientException,
6056 DbException,
6057 LcmException,
6058 NgRoException,
6059 ) as e:
tierno59d22d22018-09-25 18:10:19 +02006060 self.logger.error(logging_text + "Exit Exception {}".format(e))
6061 exc = e
6062 except asyncio.CancelledError:
garciadeblas5697b8b2021-03-24 09:17:02 +01006063 self.logger.error(
6064 logging_text + "Cancelled Exception while '{}'".format(step)
6065 )
tierno59d22d22018-09-25 18:10:19 +02006066 exc = "Operation was cancelled"
6067 except Exception as e:
6068 exc = traceback.format_exc()
garciadeblas5697b8b2021-03-24 09:17:02 +01006069 self.logger.critical(
6070 logging_text + "Exit Exception {} {}".format(type(e).__name__, e),
6071 exc_info=True,
6072 )
tierno59d22d22018-09-25 18:10:19 +02006073 finally:
garciadeblas5697b8b2021-03-24 09:17:02 +01006074 self._write_ns_status(
6075 nsr_id=nsr_id,
6076 ns_state=None,
6077 current_operation="IDLE",
6078 current_operation_id=None,
6079 )
aktas13251562021-02-12 22:19:10 +03006080 if tasks_dict_info:
6081 stage[1] = "Waiting for instantiate pending tasks."
6082 self.logger.debug(logging_text + stage[1])
garciadeblas5697b8b2021-03-24 09:17:02 +01006083 exc = await self._wait_for_tasks(
6084 logging_text,
6085 tasks_dict_info,
6086 self.timeout_ns_deploy,
6087 stage,
6088 nslcmop_id,
6089 nsr_id=nsr_id,
6090 )
tierno59d22d22018-09-25 18:10:19 +02006091 if exc:
garciadeblas5697b8b2021-03-24 09:17:02 +01006092 db_nslcmop_update[
6093 "detailed-status"
6094 ] = error_description_nslcmop = "FAILED {}: {}".format(step, exc)
tiernoa17d4f42020-04-28 09:59:23 +00006095 nslcmop_operation_state = "FAILED"
tierno59d22d22018-09-25 18:10:19 +02006096 if db_nsr:
tiernod6de1992018-10-11 13:05:52 +02006097 db_nsr_update["operational-status"] = old_operational_status
6098 db_nsr_update["config-status"] = old_config_status
6099 db_nsr_update["detailed-status"] = ""
6100 if scale_process:
6101 if "VCA" in scale_process:
6102 db_nsr_update["config-status"] = "failed"
6103 if "RO" in scale_process:
6104 db_nsr_update["operational-status"] = "failed"
garciadeblas5697b8b2021-03-24 09:17:02 +01006105 db_nsr_update[
6106 "detailed-status"
6107 ] = "FAILED scaling nslcmop={} {}: {}".format(
6108 nslcmop_id, step, exc
6109 )
tiernoa17d4f42020-04-28 09:59:23 +00006110 else:
6111 error_description_nslcmop = None
6112 nslcmop_operation_state = "COMPLETED"
6113 db_nslcmop_update["detailed-status"] = "Done"
quilesj4cda56b2019-12-05 10:02:20 +00006114
garciadeblas5697b8b2021-03-24 09:17:02 +01006115 self._write_op_status(
6116 op_id=nslcmop_id,
6117 stage="",
6118 error_message=error_description_nslcmop,
6119 operation_state=nslcmop_operation_state,
6120 other_update=db_nslcmop_update,
6121 )
tiernoa17d4f42020-04-28 09:59:23 +00006122 if db_nsr:
garciadeblas5697b8b2021-03-24 09:17:02 +01006123 self._write_ns_status(
6124 nsr_id=nsr_id,
6125 ns_state=None,
6126 current_operation="IDLE",
6127 current_operation_id=None,
6128 other_update=db_nsr_update,
6129 )
tiernoa17d4f42020-04-28 09:59:23 +00006130
tierno59d22d22018-09-25 18:10:19 +02006131 if nslcmop_operation_state:
6132 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01006133 msg = {
6134 "nsr_id": nsr_id,
6135 "nslcmop_id": nslcmop_id,
6136 "operationState": nslcmop_operation_state,
6137 }
bravof922c4172020-11-24 21:21:43 -03006138 await self.msg.aiowrite("ns", "scaled", msg, loop=self.loop)
tierno59d22d22018-09-25 18:10:19 +02006139 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01006140 self.logger.error(
6141 logging_text + "kafka_write notification Exception {}".format(e)
6142 )
tierno59d22d22018-09-25 18:10:19 +02006143 self.logger.debug(logging_text + "Exit")
6144 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_scale")
tiernob996d942020-07-03 14:52:28 +00006145
aktas5f75f102021-03-15 11:26:10 +03006146 async def _scale_kdu(
6147 self, logging_text, nsr_id, nsr_deployed, db_vnfd, vca_id, scaling_info
6148 ):
6149 _scaling_info = scaling_info.get("kdu-create") or scaling_info.get("kdu-delete")
6150 for kdu_name in _scaling_info:
6151 for kdu_scaling_info in _scaling_info[kdu_name]:
6152 deployed_kdu, index = get_deployed_kdu(
6153 nsr_deployed, kdu_name, kdu_scaling_info["member-vnf-index"]
6154 )
6155 cluster_uuid = deployed_kdu["k8scluster-uuid"]
6156 kdu_instance = deployed_kdu["kdu-instance"]
6157 scale = int(kdu_scaling_info["scale"])
6158 k8s_cluster_type = kdu_scaling_info["k8s-cluster-type"]
6159
6160 db_dict = {
6161 "collection": "nsrs",
6162 "filter": {"_id": nsr_id},
6163 "path": "_admin.deployed.K8s.{}".format(index),
6164 }
6165
6166 step = "scaling application {}".format(
6167 kdu_scaling_info["resource-name"]
6168 )
6169 self.logger.debug(logging_text + step)
6170
6171 if kdu_scaling_info["type"] == "delete":
6172 kdu_config = get_configuration(db_vnfd, kdu_name)
6173 if (
6174 kdu_config
6175 and kdu_config.get("terminate-config-primitive")
6176 and get_juju_ee_ref(db_vnfd, kdu_name) is None
6177 ):
6178 terminate_config_primitive_list = kdu_config.get(
6179 "terminate-config-primitive"
6180 )
6181 terminate_config_primitive_list.sort(
6182 key=lambda val: int(val["seq"])
6183 )
6184
6185 for (
6186 terminate_config_primitive
6187 ) in terminate_config_primitive_list:
6188 primitive_params_ = self._map_primitive_params(
6189 terminate_config_primitive, {}, {}
6190 )
6191 step = "execute terminate config primitive"
6192 self.logger.debug(logging_text + step)
6193 await asyncio.wait_for(
6194 self.k8scluster_map[k8s_cluster_type].exec_primitive(
6195 cluster_uuid=cluster_uuid,
6196 kdu_instance=kdu_instance,
6197 primitive_name=terminate_config_primitive["name"],
6198 params=primitive_params_,
6199 db_dict=db_dict,
6200 vca_id=vca_id,
6201 ),
6202 timeout=600,
6203 )
6204
6205 await asyncio.wait_for(
6206 self.k8scluster_map[k8s_cluster_type].scale(
6207 kdu_instance,
6208 scale,
6209 kdu_scaling_info["resource-name"],
6210 vca_id=vca_id,
6211 ),
6212 timeout=self.timeout_vca_on_error,
6213 )
6214
6215 if kdu_scaling_info["type"] == "create":
6216 kdu_config = get_configuration(db_vnfd, kdu_name)
6217 if (
6218 kdu_config
6219 and kdu_config.get("initial-config-primitive")
6220 and get_juju_ee_ref(db_vnfd, kdu_name) is None
6221 ):
6222 initial_config_primitive_list = kdu_config.get(
6223 "initial-config-primitive"
6224 )
6225 initial_config_primitive_list.sort(
6226 key=lambda val: int(val["seq"])
6227 )
6228
6229 for initial_config_primitive in initial_config_primitive_list:
6230 primitive_params_ = self._map_primitive_params(
6231 initial_config_primitive, {}, {}
6232 )
6233 step = "execute initial config primitive"
6234 self.logger.debug(logging_text + step)
6235 await asyncio.wait_for(
6236 self.k8scluster_map[k8s_cluster_type].exec_primitive(
6237 cluster_uuid=cluster_uuid,
6238 kdu_instance=kdu_instance,
6239 primitive_name=initial_config_primitive["name"],
6240 params=primitive_params_,
6241 db_dict=db_dict,
6242 vca_id=vca_id,
6243 ),
6244 timeout=600,
6245 )
6246
garciadeblas5697b8b2021-03-24 09:17:02 +01006247 async def _scale_ng_ro(
6248 self, logging_text, db_nsr, db_nslcmop, db_vnfr, vdu_scaling_info, stage
6249 ):
tierno2357f4e2020-10-19 16:38:59 +00006250 nsr_id = db_nslcmop["nsInstanceId"]
6251 db_nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
6252 db_vnfrs = {}
6253
6254 # read from db: vnfd's for every vnf
bravof832f8992020-12-07 12:57:31 -03006255 db_vnfds = []
tierno2357f4e2020-10-19 16:38:59 +00006256
6257 # for each vnf in ns, read vnfd
6258 for vnfr in self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id}):
6259 db_vnfrs[vnfr["member-vnf-index-ref"]] = vnfr
6260 vnfd_id = vnfr["vnfd-id"] # vnfd uuid for this vnf
tierno2357f4e2020-10-19 16:38:59 +00006261 # if we haven't this vnfd, read it from db
bravof832f8992020-12-07 12:57:31 -03006262 if not find_in_list(db_vnfds, lambda a_vnfd: a_vnfd["id"] == vnfd_id):
tierno2357f4e2020-10-19 16:38:59 +00006263 # read from db
6264 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
bravof832f8992020-12-07 12:57:31 -03006265 db_vnfds.append(vnfd)
tierno2357f4e2020-10-19 16:38:59 +00006266 n2vc_key = self.n2vc.get_public_key()
6267 n2vc_key_list = [n2vc_key]
garciadeblas5697b8b2021-03-24 09:17:02 +01006268 self.scale_vnfr(
6269 db_vnfr,
6270 vdu_scaling_info.get("vdu-create"),
6271 vdu_scaling_info.get("vdu-delete"),
6272 mark_delete=True,
6273 )
tierno2357f4e2020-10-19 16:38:59 +00006274 # db_vnfr has been updated, update db_vnfrs to use it
6275 db_vnfrs[db_vnfr["member-vnf-index-ref"]] = db_vnfr
garciadeblas5697b8b2021-03-24 09:17:02 +01006276 await self._instantiate_ng_ro(
6277 logging_text,
6278 nsr_id,
6279 db_nsd,
6280 db_nsr,
6281 db_nslcmop,
6282 db_vnfrs,
6283 db_vnfds,
6284 n2vc_key_list,
6285 stage=stage,
6286 start_deploy=time(),
6287 timeout_ns_deploy=self.timeout_ns_deploy,
6288 )
tierno2357f4e2020-10-19 16:38:59 +00006289 if vdu_scaling_info.get("vdu-delete"):
garciadeblas5697b8b2021-03-24 09:17:02 +01006290 self.scale_vnfr(
6291 db_vnfr, None, vdu_scaling_info["vdu-delete"], mark_delete=False
6292 )
tierno2357f4e2020-10-19 16:38:59 +00006293
garciadeblas5697b8b2021-03-24 09:17:02 +01006294 async def add_prometheus_metrics(
6295 self, ee_id, artifact_path, ee_config_descriptor, vnfr_id, nsr_id, target_ip
6296 ):
tiernob996d942020-07-03 14:52:28 +00006297 if not self.prometheus:
6298 return
6299 # look if exist a file called 'prometheus*.j2' and
6300 artifact_content = self.fs.dir_ls(artifact_path)
garciadeblas5697b8b2021-03-24 09:17:02 +01006301 job_file = next(
6302 (
6303 f
6304 for f in artifact_content
6305 if f.startswith("prometheus") and f.endswith(".j2")
6306 ),
6307 None,
6308 )
tiernob996d942020-07-03 14:52:28 +00006309 if not job_file:
6310 return
6311 with self.fs.file_open((artifact_path, job_file), "r") as f:
6312 job_data = f.read()
6313
6314 # TODO get_service
garciadeblas5697b8b2021-03-24 09:17:02 +01006315 _, _, service = ee_id.partition(".") # remove prefix "namespace."
tiernob996d942020-07-03 14:52:28 +00006316 host_name = "{}-{}".format(service, ee_config_descriptor["metric-service"])
6317 host_port = "80"
6318 vnfr_id = vnfr_id.replace("-", "")
6319 variables = {
6320 "JOB_NAME": vnfr_id,
6321 "TARGET_IP": target_ip,
6322 "EXPORTER_POD_IP": host_name,
6323 "EXPORTER_POD_PORT": host_port,
6324 }
6325 job_list = self.prometheus.parse_job(job_data, variables)
6326 # ensure job_name is using the vnfr_id. Adding the metadata nsr_id
6327 for job in job_list:
garciadeblas5697b8b2021-03-24 09:17:02 +01006328 if (
6329 not isinstance(job.get("job_name"), str)
6330 or vnfr_id not in job["job_name"]
6331 ):
tiernob996d942020-07-03 14:52:28 +00006332 job["job_name"] = vnfr_id + "_" + str(randint(1, 10000))
6333 job["nsr_id"] = nsr_id
6334 job_dict = {jl["job_name"]: jl for jl in job_list}
6335 if await self.prometheus.update(job_dict):
6336 return list(job_dict.keys())
David Garciaaae391f2020-11-09 11:12:54 +01006337
6338 def get_vca_cloud_and_credentials(self, vim_account_id: str) -> (str, str):
6339 """
6340 Get VCA Cloud and VCA Cloud Credentials for the VIM account
6341
6342 :param: vim_account_id: VIM Account ID
6343
6344 :return: (cloud_name, cloud_credential)
6345 """
bravof922c4172020-11-24 21:21:43 -03006346 config = VimAccountDB.get_vim_account_with_id(vim_account_id).get("config", {})
David Garciaaae391f2020-11-09 11:12:54 +01006347 return config.get("vca_cloud"), config.get("vca_cloud_credential")
6348
6349 def get_vca_k8s_cloud_and_credentials(self, vim_account_id: str) -> (str, str):
6350 """
6351 Get VCA K8s Cloud and VCA K8s Cloud Credentials for the VIM account
6352
6353 :param: vim_account_id: VIM Account ID
6354
6355 :return: (cloud_name, cloud_credential)
6356 """
bravof922c4172020-11-24 21:21:43 -03006357 config = VimAccountDB.get_vim_account_with_id(vim_account_id).get("config", {})
David Garciaaae391f2020-11-09 11:12:54 +01006358 return config.get("vca_k8s_cloud"), config.get("vca_k8s_cloud_credential")