blob: f5bdff3f6ee173198d9c14b84f70d7753fdfd6a3 [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
tierno72ef84f2020-10-06 08:22:07 +000025from jinja2 import Environment, TemplateError, TemplateNotFound, StrictUndefined, UndefinedError
tierno59d22d22018-09-25 18:10:19 +020026
tierno77677d92019-08-22 13:46:35 +000027from osm_lcm import ROclient
tierno69f0d382020-05-07 13:08:09 +000028from osm_lcm.ng_ro import NgRoClient, NgRoException
tierno744303e2020-01-13 16:46:31 +000029from osm_lcm.lcm_utils import LcmException, LcmExceptionNoMgmtIP, LcmBase, deep_get, get_iterable, populate_dict
bravof922c4172020-11-24 21:21:43 -030030from osm_lcm.data_utils.nsd import get_vnf_profiles
bravofe5a31bc2021-02-17 19:09:12 -030031from osm_lcm.data_utils.vnfd import get_vdu_list, get_vdu_profile, \
bravof922c4172020-11-24 21:21:43 -030032 get_ee_sorted_initial_config_primitive_list, get_ee_sorted_terminate_config_primitive_list, \
bravofe5a31bc2021-02-17 19:09:12 -030033 get_kdu_list, get_virtual_link_profiles, get_vdu, get_configuration, \
bravof832f8992020-12-07 12:57:31 -030034 get_vdu_index, get_scaling_aspect, get_number_of_instances
bravof922c4172020-11-24 21:21:43 -030035from osm_lcm.data_utils.list_utils import find_in_list
36from osm_lcm.data_utils.vnfr import get_osm_params
37from osm_lcm.data_utils.dict_utils import parse_yaml_strings
38from osm_lcm.data_utils.database.vim_account import VimAccountDB
calvinosanch9f9c6f22019-11-04 13:37:39 +010039from n2vc.k8s_helm_conn import K8sHelmConnector
lloretgalleg18ebc3a2020-10-22 09:54:51 +000040from n2vc.k8s_helm3_conn import K8sHelm3Connector
Adam Israelbaacc302019-12-01 12:41:39 -050041from n2vc.k8s_juju_conn import K8sJujuConnector
tierno59d22d22018-09-25 18:10:19 +020042
tierno27246d82018-09-27 15:59:09 +020043from osm_common.dbbase import DbException
tierno59d22d22018-09-25 18:10:19 +020044from osm_common.fsbase import FsException
quilesj7e13aeb2019-10-08 13:34:55 +020045
bravof922c4172020-11-24 21:21:43 -030046from osm_lcm.data_utils.database.database import Database
47from osm_lcm.data_utils.filesystem.filesystem import Filesystem
48
quilesj7e13aeb2019-10-08 13:34:55 +020049from n2vc.n2vc_juju_conn import N2VCJujuConnector
tiernof59ad6c2020-04-08 12:50:52 +000050from n2vc.exceptions import N2VCException, N2VCNotFound, K8sException
tierno59d22d22018-09-25 18:10:19 +020051
tierno588547c2020-07-01 15:30:20 +000052from osm_lcm.lcm_helm_conn import LCMHelmConn
53
tierno27246d82018-09-27 15:59:09 +020054from copy import copy, deepcopy
tierno59d22d22018-09-25 18:10:19 +020055from time import time
tierno27246d82018-09-27 15:59:09 +020056from uuid import uuid4
lloretgalleg7c121132020-07-08 07:53:22 +000057
tiernob996d942020-07-03 14:52:28 +000058from random import randint
tierno59d22d22018-09-25 18:10:19 +020059
tierno69f0d382020-05-07 13:08:09 +000060__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
tierno59d22d22018-09-25 18:10:19 +020061
62
63class NsLcm(LcmBase):
tierno63de62e2018-10-31 16:38:52 +010064 timeout_vca_on_error = 5 * 60 # Time for charm from first time at blocked,error status to mark as failed
tierno744303e2020-01-13 16:46:31 +000065 timeout_ns_deploy = 2 * 3600 # default global timeout for deployment a ns
tiernoe876f672020-02-13 14:34:48 +000066 timeout_ns_terminate = 1800 # default global timeout for un deployment a ns
garciadeblasf9b04952019-04-09 18:53:58 +020067 timeout_charm_delete = 10 * 60
David Garciaf6919842020-05-21 16:41:07 +020068 timeout_primitive = 30 * 60 # timeout for primitive execution
69 timeout_progress_primitive = 10 * 60 # timeout for some progress in a primitive execution
tierno59d22d22018-09-25 18:10:19 +020070
kuuseac3a8882019-10-03 10:48:06 +020071 SUBOPERATION_STATUS_NOT_FOUND = -1
72 SUBOPERATION_STATUS_NEW = -2
73 SUBOPERATION_STATUS_SKIP = -3
tiernoa2143262020-03-27 16:20:40 +000074 task_name_deploy_vca = "Deploying VCA"
kuuseac3a8882019-10-03 10:48:06 +020075
bravof922c4172020-11-24 21:21:43 -030076 def __init__(self, msg, lcm_tasks, config, loop, prometheus=None):
tierno59d22d22018-09-25 18:10:19 +020077 """
78 Init, Connect to database, filesystem storage, and messaging
79 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
80 :return: None
81 """
quilesj7e13aeb2019-10-08 13:34:55 +020082 super().__init__(
quilesj7e13aeb2019-10-08 13:34:55 +020083 msg=msg,
quilesj7e13aeb2019-10-08 13:34:55 +020084 logger=logging.getLogger('lcm.ns')
85 )
86
bravof922c4172020-11-24 21:21:43 -030087 self.db = Database().instance.db
88 self.fs = Filesystem().instance.fs
tierno59d22d22018-09-25 18:10:19 +020089 self.loop = loop
90 self.lcm_tasks = lcm_tasks
tierno744303e2020-01-13 16:46:31 +000091 self.timeout = config["timeout"]
92 self.ro_config = config["ro_config"]
tierno69f0d382020-05-07 13:08:09 +000093 self.ng_ro = config["ro_config"].get("ng")
tierno744303e2020-01-13 16:46:31 +000094 self.vca_config = config["VCA"].copy()
tierno59d22d22018-09-25 18:10:19 +020095
quilesj7e13aeb2019-10-08 13:34:55 +020096 # create N2VC connector
David Garciaaae391f2020-11-09 11:12:54 +010097 self.n2vc = N2VCJujuConnector(
tierno59d22d22018-09-25 18:10:19 +020098 log=self.logger,
quilesj7e13aeb2019-10-08 13:34:55 +020099 loop=self.loop,
100 url='{}:{}'.format(self.vca_config['host'], self.vca_config['port']),
101 username=self.vca_config.get('user', None),
102 vca_config=self.vca_config,
bravof922c4172020-11-24 21:21:43 -0300103 on_update_db=self._on_update_n2vc_db,
104 fs=self.fs,
105 db=self.db
tierno59d22d22018-09-25 18:10:19 +0200106 )
quilesj7e13aeb2019-10-08 13:34:55 +0200107
tierno588547c2020-07-01 15:30:20 +0000108 self.conn_helm_ee = LCMHelmConn(
tierno588547c2020-07-01 15:30:20 +0000109 log=self.logger,
110 loop=self.loop,
111 url=None,
112 username=None,
113 vca_config=self.vca_config,
114 on_update_db=self._on_update_n2vc_db
115 )
116
lloretgalleg18ebc3a2020-10-22 09:54:51 +0000117 self.k8sclusterhelm2 = K8sHelmConnector(
calvinosanch9f9c6f22019-11-04 13:37:39 +0100118 kubectl_command=self.vca_config.get("kubectlpath"),
119 helm_command=self.vca_config.get("helmpath"),
calvinosanch9f9c6f22019-11-04 13:37:39 +0100120 log=self.logger,
calvinosanch9f9c6f22019-11-04 13:37:39 +0100121 on_update_db=None,
bravof922c4172020-11-24 21:21:43 -0300122 fs=self.fs,
123 db=self.db
calvinosanch9f9c6f22019-11-04 13:37:39 +0100124 )
125
lloretgalleg18ebc3a2020-10-22 09:54:51 +0000126 self.k8sclusterhelm3 = K8sHelm3Connector(
127 kubectl_command=self.vca_config.get("kubectlpath"),
128 helm_command=self.vca_config.get("helm3path"),
129 fs=self.fs,
130 log=self.logger,
131 db=self.db,
132 on_update_db=None,
133 )
134
Adam Israelbaacc302019-12-01 12:41:39 -0500135 self.k8sclusterjuju = K8sJujuConnector(
136 kubectl_command=self.vca_config.get("kubectlpath"),
137 juju_command=self.vca_config.get("jujupath"),
Adam Israelbaacc302019-12-01 12:41:39 -0500138 log=self.logger,
David Garciaba89cbb2020-10-16 13:05:34 +0200139 loop=self.loop,
Adam Israelbaacc302019-12-01 12:41:39 -0500140 on_update_db=None,
David Garciaba89cbb2020-10-16 13:05:34 +0200141 vca_config=self.vca_config,
bravof922c4172020-11-24 21:21:43 -0300142 fs=self.fs,
143 db=self.db
Adam Israelbaacc302019-12-01 12:41:39 -0500144 )
145
tiernoa2143262020-03-27 16:20:40 +0000146 self.k8scluster_map = {
lloretgalleg18ebc3a2020-10-22 09:54:51 +0000147 "helm-chart": self.k8sclusterhelm2,
148 "helm-chart-v3": self.k8sclusterhelm3,
149 "chart": self.k8sclusterhelm3,
tiernoa2143262020-03-27 16:20:40 +0000150 "juju-bundle": self.k8sclusterjuju,
151 "juju": self.k8sclusterjuju,
152 }
tierno588547c2020-07-01 15:30:20 +0000153
154 self.vca_map = {
155 "lxc_proxy_charm": self.n2vc,
156 "native_charm": self.n2vc,
157 "k8s_proxy_charm": self.n2vc,
lloretgalleg18ebc3a2020-10-22 09:54:51 +0000158 "helm": self.conn_helm_ee,
159 "helm-v3": self.conn_helm_ee
tierno588547c2020-07-01 15:30:20 +0000160 }
161
tiernob996d942020-07-03 14:52:28 +0000162 self.prometheus = prometheus
163
quilesj7e13aeb2019-10-08 13:34:55 +0200164 # create RO client
bravof922c4172020-11-24 21:21:43 -0300165 self.RO = NgRoClient(self.loop, **self.ro_config)
tierno59d22d22018-09-25 18:10:19 +0200166
tierno2357f4e2020-10-19 16:38:59 +0000167 @staticmethod
168 def increment_ip_mac(ip_mac, vm_index=1):
169 if not isinstance(ip_mac, str):
170 return ip_mac
171 try:
172 # try with ipv4 look for last dot
173 i = ip_mac.rfind(".")
174 if i > 0:
175 i += 1
176 return "{}{}".format(ip_mac[:i], int(ip_mac[i:]) + vm_index)
177 # try with ipv6 or mac look for last colon. Operate in hex
178 i = ip_mac.rfind(":")
179 if i > 0:
180 i += 1
181 # format in hex, len can be 2 for mac or 4 for ipv6
182 return ("{}{:0" + str(len(ip_mac) - i) + "x}").format(ip_mac[:i], int(ip_mac[i:], 16) + vm_index)
183 except Exception:
184 pass
185 return None
186
quilesj3655ae02019-12-12 16:08:35 +0000187 def _on_update_ro_db(self, nsrs_id, ro_descriptor):
quilesj7e13aeb2019-10-08 13:34:55 +0200188
quilesj3655ae02019-12-12 16:08:35 +0000189 # self.logger.debug('_on_update_ro_db(nsrs_id={}'.format(nsrs_id))
190
191 try:
192 # TODO filter RO descriptor fields...
193
194 # write to database
195 db_dict = dict()
196 # db_dict['deploymentStatus'] = yaml.dump(ro_descriptor, default_flow_style=False, indent=2)
197 db_dict['deploymentStatus'] = ro_descriptor
198 self.update_db_2("nsrs", nsrs_id, db_dict)
199
200 except Exception as e:
201 self.logger.warn('Cannot write database RO deployment for ns={} -> {}'.format(nsrs_id, e))
202
203 async def _on_update_n2vc_db(self, table, filter, path, updated_data):
204
quilesj69a722c2020-01-09 08:30:17 +0000205 # remove last dot from path (if exists)
206 if path.endswith('.'):
207 path = path[:-1]
208
quilesj3655ae02019-12-12 16:08:35 +0000209 # self.logger.debug('_on_update_n2vc_db(table={}, filter={}, path={}, updated_data={}'
210 # .format(table, filter, path, updated_data))
211
212 try:
213
214 nsr_id = filter.get('_id')
215
216 # read ns record from database
217 nsr = self.db.get_one(table='nsrs', q_filter=filter)
218 current_ns_status = nsr.get('nsState')
219
220 # get vca status for NS
quilesj69a722c2020-01-09 08:30:17 +0000221 status_dict = await self.n2vc.get_status(namespace='.' + nsr_id, yaml_format=False)
quilesj3655ae02019-12-12 16:08:35 +0000222
223 # vcaStatus
224 db_dict = dict()
225 db_dict['vcaStatus'] = status_dict
226
227 # update configurationStatus for this VCA
228 try:
229 vca_index = int(path[path.rfind(".")+1:])
230
231 vca_list = deep_get(target_dict=nsr, key_list=('_admin', 'deployed', 'VCA'))
232 vca_status = vca_list[vca_index].get('status')
233
234 configuration_status_list = nsr.get('configurationStatus')
235 config_status = configuration_status_list[vca_index].get('status')
236
237 if config_status == 'BROKEN' and vca_status != 'failed':
238 db_dict['configurationStatus'][vca_index] = 'READY'
239 elif config_status != 'BROKEN' and vca_status == 'failed':
240 db_dict['configurationStatus'][vca_index] = 'BROKEN'
241 except Exception as e:
242 # not update configurationStatus
243 self.logger.debug('Error updating vca_index (ignore): {}'.format(e))
244
245 # if nsState = 'READY' check if juju is reporting some error => nsState = 'DEGRADED'
246 # if nsState = 'DEGRADED' check if all is OK
247 is_degraded = False
248 if current_ns_status in ('READY', 'DEGRADED'):
249 error_description = ''
250 # check machines
251 if status_dict.get('machines'):
252 for machine_id in status_dict.get('machines'):
253 machine = status_dict.get('machines').get(machine_id)
254 # check machine agent-status
255 if machine.get('agent-status'):
256 s = machine.get('agent-status').get('status')
257 if s != 'started':
258 is_degraded = True
259 error_description += 'machine {} agent-status={} ; '.format(machine_id, s)
260 # check machine instance status
261 if machine.get('instance-status'):
262 s = machine.get('instance-status').get('status')
263 if s != 'running':
264 is_degraded = True
265 error_description += 'machine {} instance-status={} ; '.format(machine_id, s)
266 # check applications
267 if status_dict.get('applications'):
268 for app_id in status_dict.get('applications'):
269 app = status_dict.get('applications').get(app_id)
270 # check application status
271 if app.get('status'):
272 s = app.get('status').get('status')
273 if s != 'active':
274 is_degraded = True
275 error_description += 'application {} status={} ; '.format(app_id, s)
276
277 if error_description:
278 db_dict['errorDescription'] = error_description
279 if current_ns_status == 'READY' and is_degraded:
280 db_dict['nsState'] = 'DEGRADED'
281 if current_ns_status == 'DEGRADED' and not is_degraded:
282 db_dict['nsState'] = 'READY'
283
284 # write to database
285 self.update_db_2("nsrs", nsr_id, db_dict)
286
tierno51183952020-04-03 15:48:18 +0000287 except (asyncio.CancelledError, asyncio.TimeoutError):
288 raise
quilesj3655ae02019-12-12 16:08:35 +0000289 except Exception as e:
290 self.logger.warn('Error updating NS state for ns={}: {}'.format(nsr_id, e))
quilesj7e13aeb2019-10-08 13:34:55 +0200291
tierno72ef84f2020-10-06 08:22:07 +0000292 @staticmethod
293 def _parse_cloud_init(cloud_init_text, additional_params, vnfd_id, vdu_id):
294 try:
295 env = Environment(undefined=StrictUndefined)
296 template = env.from_string(cloud_init_text)
297 return template.render(additional_params or {})
298 except UndefinedError as e:
299 raise LcmException("Variable {} at vnfd[id={}]:vdu[id={}]:cloud-init/cloud-init-"
300 "file, must be provided in the instantiation parameters inside the "
301 "'additionalParamsForVnf/Vdu' block".format(e, vnfd_id, vdu_id))
302 except (TemplateError, TemplateNotFound) as e:
303 raise LcmException("Error parsing Jinja2 to cloud-init content at vnfd[id={}]:vdu[id={}]: {}".
304 format(vnfd_id, vdu_id, e))
305
bravof922c4172020-11-24 21:21:43 -0300306 def _get_vdu_cloud_init_content(self, vdu, vnfd):
307 cloud_init_content = cloud_init_file = None
tierno72ef84f2020-10-06 08:22:07 +0000308 try:
tierno72ef84f2020-10-06 08:22:07 +0000309 if vdu.get("cloud-init-file"):
310 base_folder = vnfd["_admin"]["storage"]
311 cloud_init_file = "{}/{}/cloud_init/{}".format(base_folder["folder"], base_folder["pkg-dir"],
312 vdu["cloud-init-file"])
313 with self.fs.file_open(cloud_init_file, "r") as ci_file:
314 cloud_init_content = ci_file.read()
315 elif vdu.get("cloud-init"):
316 cloud_init_content = vdu["cloud-init"]
317
318 return cloud_init_content
319 except FsException as e:
320 raise LcmException("Error reading vnfd[id={}]:vdu[id={}]:cloud-init-file={}: {}".
321 format(vnfd["id"], vdu["id"], cloud_init_file, e))
322
tierno72ef84f2020-10-06 08:22:07 +0000323 def _get_vdu_additional_params(self, db_vnfr, vdu_id):
324 vdur = next(vdur for vdur in db_vnfr.get("vdur") if vdu_id == vdur["vdu-id-ref"])
325 additional_params = vdur.get("additionalParams")
bravof922c4172020-11-24 21:21:43 -0300326 return parse_yaml_strings(additional_params)
tierno72ef84f2020-10-06 08:22:07 +0000327
gcalvino35be9152018-12-20 09:33:12 +0100328 def vnfd2RO(self, vnfd, new_id=None, additionalParams=None, nsrId=None):
tierno59d22d22018-09-25 18:10:19 +0200329 """
330 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
331 :param vnfd: input vnfd
332 :param new_id: overrides vnf id if provided
tierno8a518872018-12-21 13:42:14 +0000333 :param additionalParams: Instantiation params for VNFs provided
gcalvino35be9152018-12-20 09:33:12 +0100334 :param nsrId: Id of the NSR
tierno59d22d22018-09-25 18:10:19 +0200335 :return: copy of vnfd
336 """
tierno72ef84f2020-10-06 08:22:07 +0000337 vnfd_RO = deepcopy(vnfd)
338 # remove unused by RO configuration, monitoring, scaling and internal keys
339 vnfd_RO.pop("_id", None)
340 vnfd_RO.pop("_admin", None)
tierno72ef84f2020-10-06 08:22:07 +0000341 vnfd_RO.pop("monitoring-param", None)
342 vnfd_RO.pop("scaling-group-descriptor", None)
343 vnfd_RO.pop("kdu", None)
344 vnfd_RO.pop("k8s-cluster", None)
345 if new_id:
346 vnfd_RO["id"] = new_id
tierno8a518872018-12-21 13:42:14 +0000347
tierno72ef84f2020-10-06 08:22:07 +0000348 # parse cloud-init or cloud-init-file with the provided variables using Jinja2
349 for vdu in get_iterable(vnfd_RO, "vdu"):
350 vdu.pop("cloud-init-file", None)
351 vdu.pop("cloud-init", None)
352 return vnfd_RO
tierno59d22d22018-09-25 18:10:19 +0200353
tierno2357f4e2020-10-19 16:38:59 +0000354 @staticmethod
355 def ip_profile_2_RO(ip_profile):
356 RO_ip_profile = deepcopy(ip_profile)
357 if "dns-server" in RO_ip_profile:
358 if isinstance(RO_ip_profile["dns-server"], list):
359 RO_ip_profile["dns-address"] = []
360 for ds in RO_ip_profile.pop("dns-server"):
361 RO_ip_profile["dns-address"].append(ds['address'])
362 else:
363 RO_ip_profile["dns-address"] = RO_ip_profile.pop("dns-server")
364 if RO_ip_profile.get("ip-version") == "ipv4":
365 RO_ip_profile["ip-version"] = "IPv4"
366 if RO_ip_profile.get("ip-version") == "ipv6":
367 RO_ip_profile["ip-version"] = "IPv6"
368 if "dhcp-params" in RO_ip_profile:
369 RO_ip_profile["dhcp"] = RO_ip_profile.pop("dhcp-params")
370 return RO_ip_profile
371
bravof922c4172020-11-24 21:21:43 -0300372 def _get_ro_vim_id_for_vim_account(self, vim_account):
373 db_vim = self.db.get_one("vim_accounts", {"_id": vim_account})
374 if db_vim["_admin"]["operationalState"] != "ENABLED":
375 raise LcmException("VIM={} is not available. operationalState={}".format(
376 vim_account, db_vim["_admin"]["operationalState"]))
377 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
378 return RO_vim_id
tierno59d22d22018-09-25 18:10:19 +0200379
bravof922c4172020-11-24 21:21:43 -0300380 def get_ro_wim_id_for_wim_account(self, wim_account):
381 if isinstance(wim_account, str):
382 db_wim = self.db.get_one("wim_accounts", {"_id": wim_account})
383 if db_wim["_admin"]["operationalState"] != "ENABLED":
384 raise LcmException("WIM={} is not available. operationalState={}".format(
385 wim_account, db_wim["_admin"]["operationalState"]))
386 RO_wim_id = db_wim["_admin"]["deployed"]["RO-account"]
387 return RO_wim_id
388 else:
389 return wim_account
tierno59d22d22018-09-25 18:10:19 +0200390
tierno2357f4e2020-10-19 16:38:59 +0000391 def scale_vnfr(self, db_vnfr, vdu_create=None, vdu_delete=None, mark_delete=False):
tierno27246d82018-09-27 15:59:09 +0200392
tierno2357f4e2020-10-19 16:38:59 +0000393 db_vdu_push_list = []
394 db_update = {"_admin.modified": time()}
395 if vdu_create:
396 for vdu_id, vdu_count in vdu_create.items():
397 vdur = next((vdur for vdur in reversed(db_vnfr["vdur"]) if vdur["vdu-id-ref"] == vdu_id), None)
398 if not vdur:
399 raise LcmException("Error scaling OUT VNFR for {}. There is not any existing vnfr. Scaled to 0?".
400 format(vdu_id))
401
402 for count in range(vdu_count):
403 vdur_copy = deepcopy(vdur)
404 vdur_copy["status"] = "BUILD"
405 vdur_copy["status-detailed"] = None
406 vdur_copy["ip-address"]: None
tierno683eb392020-09-25 12:33:15 +0000407 vdur_copy["_id"] = str(uuid4())
tierno2357f4e2020-10-19 16:38:59 +0000408 vdur_copy["count-index"] += count + 1
409 vdur_copy["id"] = "{}-{}".format(vdur_copy["vdu-id-ref"], vdur_copy["count-index"])
410 vdur_copy.pop("vim_info", None)
411 for iface in vdur_copy["interfaces"]:
412 if iface.get("fixed-ip"):
413 iface["ip-address"] = self.increment_ip_mac(iface["ip-address"], count+1)
414 else:
415 iface.pop("ip-address", None)
416 if iface.get("fixed-mac"):
417 iface["mac-address"] = self.increment_ip_mac(iface["mac-address"], count+1)
418 else:
419 iface.pop("mac-address", None)
420 iface.pop("mgmt_vnf", None) # only first vdu can be managment of vnf
421 db_vdu_push_list.append(vdur_copy)
422 # self.logger.debug("scale out, adding vdu={}".format(vdur_copy))
tierno27246d82018-09-27 15:59:09 +0200423 if vdu_delete:
tierno2357f4e2020-10-19 16:38:59 +0000424 for vdu_id, vdu_count in vdu_delete.items():
425 if mark_delete:
426 indexes_to_delete = [iv[0] for iv in enumerate(db_vnfr["vdur"]) if iv[1]["vdu-id-ref"] == vdu_id]
427 db_update.update({"vdur.{}.status".format(i): "DELETING" for i in indexes_to_delete[-vdu_count:]})
428 else:
429 # it must be deleted one by one because common.db does not allow otherwise
430 vdus_to_delete = [v for v in reversed(db_vnfr["vdur"]) if v["vdu-id-ref"] == vdu_id]
431 for vdu in vdus_to_delete[:vdu_count]:
432 self.db.set_one("vnfrs", {"_id": db_vnfr["_id"]}, None, pull={"vdur": {"_id": vdu["_id"]}})
433 db_push = {"vdur": db_vdu_push_list} if db_vdu_push_list else None
434 self.db.set_one("vnfrs", {"_id": db_vnfr["_id"]}, db_update, push_list=db_push)
435 # modify passed dictionary db_vnfr
436 db_vnfr_ = self.db.get_one("vnfrs", {"_id": db_vnfr["_id"]})
437 db_vnfr["vdur"] = db_vnfr_["vdur"]
tierno27246d82018-09-27 15:59:09 +0200438
tiernof578e552018-11-08 19:07:20 +0100439 def ns_update_nsr(self, ns_update_nsr, db_nsr, nsr_desc_RO):
440 """
441 Updates database nsr with the RO info for the created vld
442 :param ns_update_nsr: dictionary to be filled with the updated info
443 :param db_nsr: content of db_nsr. This is also modified
444 :param nsr_desc_RO: nsr descriptor from RO
445 :return: Nothing, LcmException is raised on errors
446 """
447
448 for vld_index, vld in enumerate(get_iterable(db_nsr, "vld")):
449 for net_RO in get_iterable(nsr_desc_RO, "nets"):
450 if vld["id"] != net_RO.get("ns_net_osm_id"):
451 continue
452 vld["vim-id"] = net_RO.get("vim_net_id")
453 vld["name"] = net_RO.get("vim_name")
454 vld["status"] = net_RO.get("status")
455 vld["status-detailed"] = net_RO.get("error_msg")
456 ns_update_nsr["vld.{}".format(vld_index)] = vld
457 break
458 else:
459 raise LcmException("ns_update_nsr: Not found vld={} at RO info".format(vld["id"]))
460
tiernoe876f672020-02-13 14:34:48 +0000461 def set_vnfr_at_error(self, db_vnfrs, error_text):
462 try:
463 for db_vnfr in db_vnfrs.values():
464 vnfr_update = {"status": "ERROR"}
465 for vdu_index, vdur in enumerate(get_iterable(db_vnfr, "vdur")):
466 if "status" not in vdur:
467 vdur["status"] = "ERROR"
468 vnfr_update["vdur.{}.status".format(vdu_index)] = "ERROR"
469 if error_text:
470 vdur["status-detailed"] = str(error_text)
471 vnfr_update["vdur.{}.status-detailed".format(vdu_index)] = "ERROR"
472 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
473 except DbException as e:
474 self.logger.error("Cannot update vnf. {}".format(e))
475
tierno59d22d22018-09-25 18:10:19 +0200476 def ns_update_vnfr(self, db_vnfrs, nsr_desc_RO):
477 """
478 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 +0200479 :param db_vnfrs: dictionary with member-vnf-index: vnfr-content
480 :param nsr_desc_RO: nsr descriptor from RO
481 :return: Nothing, LcmException is raised on errors
tierno59d22d22018-09-25 18:10:19 +0200482 """
483 for vnf_index, db_vnfr in db_vnfrs.items():
484 for vnf_RO in nsr_desc_RO["vnfs"]:
tierno27246d82018-09-27 15:59:09 +0200485 if vnf_RO["member_vnf_index"] != vnf_index:
486 continue
487 vnfr_update = {}
tiernof578e552018-11-08 19:07:20 +0100488 if vnf_RO.get("ip_address"):
tierno1674de82019-04-09 13:03:14 +0000489 db_vnfr["ip-address"] = vnfr_update["ip-address"] = vnf_RO["ip_address"].split(";")[0]
tiernof578e552018-11-08 19:07:20 +0100490 elif not db_vnfr.get("ip-address"):
tierno0ec0c272020-02-19 17:43:01 +0000491 if db_vnfr.get("vdur"): # if not VDUs, there is not ip_address
492 raise LcmExceptionNoMgmtIP("ns member_vnf_index '{}' has no IP address".format(vnf_index))
tierno59d22d22018-09-25 18:10:19 +0200493
tierno27246d82018-09-27 15:59:09 +0200494 for vdu_index, vdur in enumerate(get_iterable(db_vnfr, "vdur")):
495 vdur_RO_count_index = 0
496 if vdur.get("pdu-type"):
497 continue
498 for vdur_RO in get_iterable(vnf_RO, "vms"):
499 if vdur["vdu-id-ref"] != vdur_RO["vdu_osm_id"]:
500 continue
501 if vdur["count-index"] != vdur_RO_count_index:
502 vdur_RO_count_index += 1
503 continue
504 vdur["vim-id"] = vdur_RO.get("vim_vm_id")
tierno1674de82019-04-09 13:03:14 +0000505 if vdur_RO.get("ip_address"):
506 vdur["ip-address"] = vdur_RO["ip_address"].split(";")[0]
tierno274ed572019-04-04 13:33:27 +0000507 else:
508 vdur["ip-address"] = None
tierno27246d82018-09-27 15:59:09 +0200509 vdur["vdu-id-ref"] = vdur_RO.get("vdu_osm_id")
510 vdur["name"] = vdur_RO.get("vim_name")
511 vdur["status"] = vdur_RO.get("status")
512 vdur["status-detailed"] = vdur_RO.get("error_msg")
513 for ifacer in get_iterable(vdur, "interfaces"):
514 for interface_RO in get_iterable(vdur_RO, "interfaces"):
515 if ifacer["name"] == interface_RO.get("internal_name"):
516 ifacer["ip-address"] = interface_RO.get("ip_address")
517 ifacer["mac-address"] = interface_RO.get("mac_address")
518 break
519 else:
520 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} interface={} "
quilesj7e13aeb2019-10-08 13:34:55 +0200521 "from VIM info"
522 .format(vnf_index, vdur["vdu-id-ref"], ifacer["name"]))
tierno27246d82018-09-27 15:59:09 +0200523 vnfr_update["vdur.{}".format(vdu_index)] = vdur
524 break
525 else:
tierno15b1cf12019-08-29 13:21:40 +0000526 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} count_index={} from "
527 "VIM info".format(vnf_index, vdur["vdu-id-ref"], vdur["count-index"]))
tiernof578e552018-11-08 19:07:20 +0100528
529 for vld_index, vld in enumerate(get_iterable(db_vnfr, "vld")):
530 for net_RO in get_iterable(nsr_desc_RO, "nets"):
531 if vld["id"] != net_RO.get("vnf_net_osm_id"):
532 continue
533 vld["vim-id"] = net_RO.get("vim_net_id")
534 vld["name"] = net_RO.get("vim_name")
535 vld["status"] = net_RO.get("status")
536 vld["status-detailed"] = net_RO.get("error_msg")
537 vnfr_update["vld.{}".format(vld_index)] = vld
538 break
539 else:
tierno15b1cf12019-08-29 13:21:40 +0000540 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vld={} from VIM info".format(
tiernof578e552018-11-08 19:07:20 +0100541 vnf_index, vld["id"]))
542
tierno27246d82018-09-27 15:59:09 +0200543 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
544 break
tierno59d22d22018-09-25 18:10:19 +0200545
546 else:
tierno15b1cf12019-08-29 13:21:40 +0000547 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} from VIM info".format(vnf_index))
tierno59d22d22018-09-25 18:10:19 +0200548
tierno5ee02052019-12-05 19:55:02 +0000549 def _get_ns_config_info(self, nsr_id):
tiernoc3f2a822019-11-05 13:45:04 +0000550 """
551 Generates a mapping between vnf,vdu elements and the N2VC id
tierno5ee02052019-12-05 19:55:02 +0000552 :param nsr_id: id of nsr to get last database _admin.deployed.VCA that contains this list
tiernoc3f2a822019-11-05 13:45:04 +0000553 :return: a dictionary with {osm-config-mapping: {}} where its element contains:
554 "<member-vnf-index>": <N2VC-id> for a vnf configuration, or
555 "<member-vnf-index>.<vdu.id>.<vdu replica(0, 1,..)>": <N2VC-id> for a vdu configuration
556 """
tierno5ee02052019-12-05 19:55:02 +0000557 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
558 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
tiernoc3f2a822019-11-05 13:45:04 +0000559 mapping = {}
560 ns_config_info = {"osm-config-mapping": mapping}
561 for vca in vca_deployed_list:
562 if not vca["member-vnf-index"]:
563 continue
564 if not vca["vdu_id"]:
565 mapping[vca["member-vnf-index"]] = vca["application"]
566 else:
567 mapping["{}.{}.{}".format(vca["member-vnf-index"], vca["vdu_id"], vca["vdu_count_index"])] =\
568 vca["application"]
569 return ns_config_info
570
bravof922c4172020-11-24 21:21:43 -0300571 async def _instantiate_ng_ro(self, logging_text, nsr_id, nsd, db_nsr, db_nslcmop, db_vnfrs, db_vnfds,
tierno69f0d382020-05-07 13:08:09 +0000572 n2vc_key_list, stage, start_deploy, timeout_ns_deploy):
tierno2357f4e2020-10-19 16:38:59 +0000573
574 db_vims = {}
575
576 def get_vim_account(vim_account_id):
577 nonlocal db_vims
578 if vim_account_id in db_vims:
579 return db_vims[vim_account_id]
580 db_vim = self.db.get_one("vim_accounts", {"_id": vim_account_id})
581 db_vims[vim_account_id] = db_vim
582 return db_vim
583
584 # modify target_vld info with instantiation parameters
585 def parse_vld_instantiation_params(target_vim, target_vld, vld_params, target_sdn):
586 if vld_params.get("ip-profile"):
587 target_vld["vim_info"][target_vim]["ip_profile"] = vld_params["ip-profile"]
588 if vld_params.get("provider-network"):
589 target_vld["vim_info"][target_vim]["provider_network"] = vld_params["provider-network"]
590 if "sdn-ports" in vld_params["provider-network"] and target_sdn:
591 target_vld["vim_info"][target_sdn]["sdn-ports"] = vld_params["provider-network"]["sdn-ports"]
592 if vld_params.get("wimAccountId"):
593 target_wim = "wim:{}".format(vld_params["wimAccountId"])
594 target_vld["vim_info"][target_wim] = {}
595 for param in ("vim-network-name", "vim-network-id"):
596 if vld_params.get(param):
597 if isinstance(vld_params[param], dict):
bravof922c4172020-11-24 21:21:43 -0300598 for vim, vim_net in vld_params[param]:
599 other_target_vim = "vim:" + vim
600 populate_dict(target_vld["vim_info"], (other_target_vim, param.replace("-", "_")), vim_net)
tierno2357f4e2020-10-19 16:38:59 +0000601 else: # isinstance str
602 target_vld["vim_info"][target_vim][param.replace("-", "_")] = vld_params[param]
bravof922c4172020-11-24 21:21:43 -0300603 if vld_params.get("common_id"):
604 target_vld["common_id"] = vld_params.get("common_id")
tierno2357f4e2020-10-19 16:38:59 +0000605
tierno69f0d382020-05-07 13:08:09 +0000606 nslcmop_id = db_nslcmop["_id"]
607 target = {
608 "name": db_nsr["name"],
609 "ns": {"vld": []},
610 "vnf": [],
611 "image": deepcopy(db_nsr["image"]),
612 "flavor": deepcopy(db_nsr["flavor"]),
613 "action_id": nslcmop_id,
tierno2357f4e2020-10-19 16:38:59 +0000614 "cloud_init_content": {},
tierno69f0d382020-05-07 13:08:09 +0000615 }
616 for image in target["image"]:
tierno2357f4e2020-10-19 16:38:59 +0000617 image["vim_info"] = {}
tierno69f0d382020-05-07 13:08:09 +0000618 for flavor in target["flavor"]:
tierno2357f4e2020-10-19 16:38:59 +0000619 flavor["vim_info"] = {}
tierno69f0d382020-05-07 13:08:09 +0000620
tierno2357f4e2020-10-19 16:38:59 +0000621 if db_nslcmop.get("lcmOperationType") != "instantiate":
622 # get parameters of instantiation:
623 db_nslcmop_instantiate = self.db.get_list("nslcmops", {"nsInstanceId": db_nslcmop["nsInstanceId"],
624 "lcmOperationType": "instantiate"})[-1]
625 ns_params = db_nslcmop_instantiate.get("operationParams")
626 else:
627 ns_params = db_nslcmop.get("operationParams")
bravof922c4172020-11-24 21:21:43 -0300628 ssh_keys_instantiation = ns_params.get("ssh_keys") or []
629 ssh_keys_all = ssh_keys_instantiation + (n2vc_key_list or [])
tierno69f0d382020-05-07 13:08:09 +0000630
631 cp2target = {}
tierno2357f4e2020-10-19 16:38:59 +0000632 for vld_index, vld in enumerate(db_nsr.get("vld")):
633 target_vim = "vim:{}".format(ns_params["vimAccountId"])
634 target_vld = {
635 "id": vld["id"],
636 "name": vld["name"],
637 "mgmt-network": vld.get("mgmt-network", False),
638 "type": vld.get("type"),
639 "vim_info": {
bravof922c4172020-11-24 21:21:43 -0300640 target_vim: {
641 "vim_network_name": vld.get("vim-network-name"),
642 "vim_account_id": ns_params["vimAccountId"]
643 }
tierno2357f4e2020-10-19 16:38:59 +0000644 }
645 }
646 # check if this network needs SDN assist
tierno2357f4e2020-10-19 16:38:59 +0000647 if vld.get("pci-interfaces"):
garciadeblasa5ae90b2021-02-12 11:26:46 +0000648 db_vim = get_vim_account(ns_params["vimAccountId"])
tierno2357f4e2020-10-19 16:38:59 +0000649 sdnc_id = db_vim["config"].get("sdn-controller")
650 if sdnc_id:
garciadeblasa5ae90b2021-02-12 11:26:46 +0000651 sdn_vld = "nsrs:{}:vld.{}".format(nsr_id, vld["id"])
652 target_sdn = "sdn:{}".format(sdnc_id)
653 target_vld["vim_info"][target_sdn] = {
654 "sdn": True, "target_vim": target_vim, "vlds": [sdn_vld], "type": vld.get("type")}
tierno2357f4e2020-10-19 16:38:59 +0000655
bravof922c4172020-11-24 21:21:43 -0300656 nsd_vnf_profiles = get_vnf_profiles(nsd)
657 for nsd_vnf_profile in nsd_vnf_profiles:
658 for cp in nsd_vnf_profile["virtual-link-connectivity"]:
659 if cp["virtual-link-profile-id"] == vld["id"]:
660 cp2target["member_vnf:{}.{}".format(
661 cp["constituent-cpd-id"][0]["constituent-base-element-id"],
662 cp["constituent-cpd-id"][0]["constituent-cpd-id"]
663 )] = "nsrs:{}:vld.{}".format(nsr_id, vld_index)
tierno2357f4e2020-10-19 16:38:59 +0000664
665 # check at nsd descriptor, if there is an ip-profile
666 vld_params = {}
bravof922c4172020-11-24 21:21:43 -0300667 virtual_link_profiles = get_virtual_link_profiles(nsd)
668
669 for vlp in virtual_link_profiles:
670 ip_profile = find_in_list(nsd["ip-profiles"],
671 lambda profile: profile["name"] == vlp["ip-profile-ref"])
tierno2357f4e2020-10-19 16:38:59 +0000672 vld_params["ip-profile"] = ip_profile["ip-profile-params"]
673 # update vld_params with instantiation params
bravof922c4172020-11-24 21:21:43 -0300674 vld_instantiation_params = find_in_list(get_iterable(ns_params, "vld"),
675 lambda a_vld: a_vld["name"] in (vld["name"], vld["id"]))
tierno2357f4e2020-10-19 16:38:59 +0000676 if vld_instantiation_params:
677 vld_params.update(vld_instantiation_params)
bravof922c4172020-11-24 21:21:43 -0300678 parse_vld_instantiation_params(target_vim, target_vld, vld_params, None)
tierno69f0d382020-05-07 13:08:09 +0000679 target["ns"]["vld"].append(target_vld)
bravof922c4172020-11-24 21:21:43 -0300680
tierno69f0d382020-05-07 13:08:09 +0000681 for vnfr in db_vnfrs.values():
bravof922c4172020-11-24 21:21:43 -0300682 vnfd = find_in_list(db_vnfds, lambda db_vnf: db_vnf["id"] == vnfr["vnfd-ref"])
683 vnf_params = find_in_list(get_iterable(ns_params, "vnf"),
684 lambda a_vnf: a_vnf["member-vnf-index"] == vnfr["member-vnf-index-ref"])
tierno69f0d382020-05-07 13:08:09 +0000685 target_vnf = deepcopy(vnfr)
tierno2357f4e2020-10-19 16:38:59 +0000686 target_vim = "vim:{}".format(vnfr["vim-account-id"])
tierno69f0d382020-05-07 13:08:09 +0000687 for vld in target_vnf.get("vld", ()):
tierno2357f4e2020-10-19 16:38:59 +0000688 # check if connected to a ns.vld, to fill target'
bravof922c4172020-11-24 21:21:43 -0300689 vnf_cp = find_in_list(vnfd.get("int-virtual-link-desc", ()),
690 lambda cpd: cpd.get("id") == vld["id"])
tierno69f0d382020-05-07 13:08:09 +0000691 if vnf_cp:
692 ns_cp = "member_vnf:{}.{}".format(vnfr["member-vnf-index-ref"], vnf_cp["id"])
693 if cp2target.get(ns_cp):
694 vld["target"] = cp2target[ns_cp]
bravof922c4172020-11-24 21:21:43 -0300695
696 vld["vim_info"] = {target_vim: {"vim_network_name": vld.get("vim-network-name")}}
tierno2357f4e2020-10-19 16:38:59 +0000697 # check if this network needs SDN assist
698 target_sdn = None
699 if vld.get("pci-interfaces"):
700 db_vim = get_vim_account(vnfr["vim-account-id"])
701 sdnc_id = db_vim["config"].get("sdn-controller")
702 if sdnc_id:
703 sdn_vld = "vnfrs:{}:vld.{}".format(target_vnf["_id"], vld["id"])
704 target_sdn = "sdn:{}".format(sdnc_id)
705 vld["vim_info"][target_sdn] = {
706 "sdn": True, "target_vim": target_vim, "vlds": [sdn_vld], "type": vld.get("type")}
tierno69f0d382020-05-07 13:08:09 +0000707
tierno2357f4e2020-10-19 16:38:59 +0000708 # check at vnfd descriptor, if there is an ip-profile
709 vld_params = {}
bravof922c4172020-11-24 21:21:43 -0300710 vnfd_vlp = find_in_list(
711 get_virtual_link_profiles(vnfd),
712 lambda a_link_profile: a_link_profile["id"] == vld["id"]
713 )
714 if vnfd_vlp and vnfd_vlp.get("virtual-link-protocol-data") and \
715 vnfd_vlp["virtual-link-protocol-data"].get("l3-protocol-data"):
716 ip_profile_source_data = vnfd_vlp["virtual-link-protocol-data"]["l3-protocol-data"]
717 ip_profile_dest_data = {}
718 if "ip-version" in ip_profile_source_data:
719 ip_profile_dest_data["ip-version"] = ip_profile_source_data["ip-version"]
720 if "cidr" in ip_profile_source_data:
721 ip_profile_dest_data["subnet-address"] = ip_profile_source_data["cidr"]
722 if "gateway-ip" in ip_profile_source_data:
723 ip_profile_dest_data["gateway-address"] = ip_profile_source_data["gateway-ip"]
724 if "dhcp-enabled" in ip_profile_source_data:
725 ip_profile_dest_data["dhcp-params"] = {
726 "enabled": ip_profile_source_data["dhcp-enabled"]
727 }
728
729 vld_params["ip-profile"] = ip_profile_dest_data
tierno2357f4e2020-10-19 16:38:59 +0000730 # update vld_params with instantiation params
731 if vnf_params:
bravof922c4172020-11-24 21:21:43 -0300732 vld_instantiation_params = find_in_list(get_iterable(vnf_params, "internal-vld"),
733 lambda i_vld: i_vld["name"] == vld["id"])
tierno2357f4e2020-10-19 16:38:59 +0000734 if vld_instantiation_params:
735 vld_params.update(vld_instantiation_params)
736 parse_vld_instantiation_params(target_vim, vld, vld_params, target_sdn)
737
738 vdur_list = []
tierno69f0d382020-05-07 13:08:09 +0000739 for vdur in target_vnf.get("vdur", ()):
tierno2357f4e2020-10-19 16:38:59 +0000740 if vdur.get("status") == "DELETING" or vdur.get("pdu-type"):
741 continue # This vdu must not be created
bravof922c4172020-11-24 21:21:43 -0300742 vdur["vim_info"] = {"vim_account_id": vnfr["vim-account-id"]}
tierno69f0d382020-05-07 13:08:09 +0000743
bravof922c4172020-11-24 21:21:43 -0300744 self.logger.debug("NS > ssh_keys > {}".format(ssh_keys_all))
745
746 if ssh_keys_all:
bravofe5a31bc2021-02-17 19:09:12 -0300747 vdu_configuration = get_configuration(vnfd, vdur["vdu-id-ref"])
748 vnf_configuration = get_configuration(vnfd, vnfd["id"])
bravof922c4172020-11-24 21:21:43 -0300749 if vdu_configuration and vdu_configuration.get("config-access") and \
750 vdu_configuration.get("config-access").get("ssh-access"):
751 vdur["ssh-keys"] = ssh_keys_all
752 vdur["ssh-access-required"] = vdu_configuration["config-access"]["ssh-access"]["required"]
753 elif vnf_configuration and vnf_configuration.get("config-access") and \
754 vnf_configuration.get("config-access").get("ssh-access") and \
tierno69f0d382020-05-07 13:08:09 +0000755 any(iface.get("mgmt-vnf") for iface in vdur["interfaces"]):
bravof922c4172020-11-24 21:21:43 -0300756 vdur["ssh-keys"] = ssh_keys_all
757 vdur["ssh-access-required"] = vnf_configuration["config-access"]["ssh-access"]["required"]
758 elif ssh_keys_instantiation and \
759 find_in_list(vdur["interfaces"], lambda iface: iface.get("mgmt-vnf")):
760 vdur["ssh-keys"] = ssh_keys_instantiation
tierno69f0d382020-05-07 13:08:09 +0000761
bravof922c4172020-11-24 21:21:43 -0300762 self.logger.debug("NS > vdur > {}".format(vdur))
763
764 vdud = get_vdu(vnfd, vdur["vdu-id-ref"])
tierno69f0d382020-05-07 13:08:09 +0000765 # cloud-init
766 if vdud.get("cloud-init-file"):
767 vdur["cloud-init"] = "{}:file:{}".format(vnfd["_id"], vdud.get("cloud-init-file"))
tierno2357f4e2020-10-19 16:38:59 +0000768 # read file and put content at target.cloul_init_content. Avoid ng_ro to use shared package system
769 if vdur["cloud-init"] not in target["cloud_init_content"]:
770 base_folder = vnfd["_admin"]["storage"]
771 cloud_init_file = "{}/{}/cloud_init/{}".format(base_folder["folder"], base_folder["pkg-dir"],
772 vdud.get("cloud-init-file"))
773 with self.fs.file_open(cloud_init_file, "r") as ci_file:
774 target["cloud_init_content"][vdur["cloud-init"]] = ci_file.read()
tierno69f0d382020-05-07 13:08:09 +0000775 elif vdud.get("cloud-init"):
bravof922c4172020-11-24 21:21:43 -0300776 vdur["cloud-init"] = "{}:vdu:{}".format(vnfd["_id"], get_vdu_index(vnfd, vdur["vdu-id-ref"]))
tierno2357f4e2020-10-19 16:38:59 +0000777 # put content at target.cloul_init_content. Avoid ng_ro read vnfd descriptor
778 target["cloud_init_content"][vdur["cloud-init"]] = vdud["cloud-init"]
779 vdur["additionalParams"] = vdur.get("additionalParams") or {}
780 deploy_params_vdu = self._format_additional_params(vdur.get("additionalParams") or {})
bravof922c4172020-11-24 21:21:43 -0300781 deploy_params_vdu["OSM"] = get_osm_params(vnfr, vdur["vdu-id-ref"], vdur["count-index"])
tierno2357f4e2020-10-19 16:38:59 +0000782 vdur["additionalParams"] = deploy_params_vdu
tierno69f0d382020-05-07 13:08:09 +0000783
784 # flavor
785 ns_flavor = target["flavor"][int(vdur["ns-flavor-id"])]
tierno2357f4e2020-10-19 16:38:59 +0000786 if target_vim not in ns_flavor["vim_info"]:
787 ns_flavor["vim_info"][target_vim] = {}
lloretgalleg7dc94672021-02-08 11:49:50 +0000788
789 # deal with images
790 # in case alternative images are provided we must check if they should be applied
791 # for the vim_type, modify the vim_type taking into account
792 ns_image_id = int(vdur["ns-image-id"])
793 if vdur.get("alt-image-ids"):
794 db_vim = get_vim_account(vnfr["vim-account-id"])
795 vim_type = db_vim["vim_type"]
796 for alt_image_id in vdur.get("alt-image-ids"):
797 ns_alt_image = target["image"][int(alt_image_id)]
798 if vim_type == ns_alt_image.get("vim-type"):
799 # must use alternative image
800 self.logger.debug("use alternative image id: {}".format(alt_image_id))
801 ns_image_id = alt_image_id
802 vdur["ns-image-id"] = ns_image_id
803 break
804 ns_image = target["image"][int(ns_image_id)]
tierno2357f4e2020-10-19 16:38:59 +0000805 if target_vim not in ns_image["vim_info"]:
806 ns_image["vim_info"][target_vim] = {}
tierno69f0d382020-05-07 13:08:09 +0000807
tierno2357f4e2020-10-19 16:38:59 +0000808 vdur["vim_info"] = {target_vim: {}}
809 # instantiation parameters
810 # if vnf_params:
811 # vdu_instantiation_params = next((v for v in get_iterable(vnf_params, "vdu") if v["id"] ==
812 # vdud["id"]), None)
813 vdur_list.append(vdur)
814 target_vnf["vdur"] = vdur_list
tierno69f0d382020-05-07 13:08:09 +0000815 target["vnf"].append(target_vnf)
816
817 desc = await self.RO.deploy(nsr_id, target)
bravof922c4172020-11-24 21:21:43 -0300818 self.logger.debug("RO return > {}".format(desc))
tierno69f0d382020-05-07 13:08:09 +0000819 action_id = desc["action_id"]
tierno2357f4e2020-10-19 16:38:59 +0000820 await self._wait_ng_ro(nsr_id, action_id, nslcmop_id, start_deploy, timeout_ns_deploy, stage)
tierno69f0d382020-05-07 13:08:09 +0000821
822 # Updating NSR
823 db_nsr_update = {
824 "_admin.deployed.RO.operational-status": "running",
825 "detailed-status": " ".join(stage)
826 }
827 # db_nsr["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
828 self.update_db_2("nsrs", nsr_id, db_nsr_update)
829 self._write_op_status(nslcmop_id, stage)
830 self.logger.debug(logging_text + "ns deployed at RO. RO_id={}".format(action_id))
831 return
832
tierno2357f4e2020-10-19 16:38:59 +0000833 async def _wait_ng_ro(self, nsr_id, action_id, nslcmop_id=None, start_time=None, timeout=600, stage=None):
tierno69f0d382020-05-07 13:08:09 +0000834 detailed_status_old = None
835 db_nsr_update = {}
tierno2357f4e2020-10-19 16:38:59 +0000836 start_time = start_time or time()
tierno69f0d382020-05-07 13:08:09 +0000837 while time() <= start_time + timeout:
838 desc_status = await self.RO.status(nsr_id, action_id)
bravof922c4172020-11-24 21:21:43 -0300839 self.logger.debug("Wait NG RO > {}".format(desc_status))
tierno69f0d382020-05-07 13:08:09 +0000840 if desc_status["status"] == "FAILED":
841 raise NgRoException(desc_status["details"])
842 elif desc_status["status"] == "BUILD":
tierno2357f4e2020-10-19 16:38:59 +0000843 if stage:
844 stage[2] = "VIM: ({})".format(desc_status["details"])
tierno69f0d382020-05-07 13:08:09 +0000845 elif desc_status["status"] == "DONE":
tierno2357f4e2020-10-19 16:38:59 +0000846 if stage:
847 stage[2] = "Deployed at VIM"
tierno69f0d382020-05-07 13:08:09 +0000848 break
849 else:
850 assert False, "ROclient.check_ns_status returns unknown {}".format(desc_status["status"])
tierno2357f4e2020-10-19 16:38:59 +0000851 if stage and nslcmop_id and stage[2] != detailed_status_old:
tierno69f0d382020-05-07 13:08:09 +0000852 detailed_status_old = stage[2]
853 db_nsr_update["detailed-status"] = " ".join(stage)
854 self.update_db_2("nsrs", nsr_id, db_nsr_update)
855 self._write_op_status(nslcmop_id, stage)
bravof922c4172020-11-24 21:21:43 -0300856 await asyncio.sleep(15, loop=self.loop)
tierno69f0d382020-05-07 13:08:09 +0000857 else: # timeout_ns_deploy
858 raise NgRoException("Timeout waiting ns to deploy")
859
860 async def _terminate_ng_ro(self, logging_text, nsr_deployed, nsr_id, nslcmop_id, stage):
861 db_nsr_update = {}
862 failed_detail = []
863 action_id = None
864 start_deploy = time()
865 try:
866 target = {
867 "ns": {"vld": []},
868 "vnf": [],
869 "image": [],
870 "flavor": [],
tierno2357f4e2020-10-19 16:38:59 +0000871 "action_id": nslcmop_id
tierno69f0d382020-05-07 13:08:09 +0000872 }
873 desc = await self.RO.deploy(nsr_id, target)
874 action_id = desc["action_id"]
875 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = action_id
876 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETING"
877 self.logger.debug(logging_text + "ns terminate action at RO. action_id={}".format(action_id))
878
879 # wait until done
880 delete_timeout = 20 * 60 # 20 minutes
tierno2357f4e2020-10-19 16:38:59 +0000881 await self._wait_ng_ro(nsr_id, action_id, nslcmop_id, start_deploy, delete_timeout, stage)
tierno69f0d382020-05-07 13:08:09 +0000882
883 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
884 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
885 # delete all nsr
886 await self.RO.delete(nsr_id)
887 except Exception as e:
888 if isinstance(e, NgRoException) and e.http_code == 404: # not found
889 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
890 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
891 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
892 self.logger.debug(logging_text + "RO_action_id={} already deleted".format(action_id))
893 elif isinstance(e, NgRoException) and e.http_code == 409: # conflict
894 failed_detail.append("delete conflict: {}".format(e))
895 self.logger.debug(logging_text + "RO_action_id={} delete conflict: {}".format(action_id, e))
896 else:
897 failed_detail.append("delete error: {}".format(e))
898 self.logger.error(logging_text + "RO_action_id={} delete error: {}".format(action_id, e))
899
900 if failed_detail:
901 stage[2] = "Error deleting from VIM"
902 else:
903 stage[2] = "Deleted from VIM"
904 db_nsr_update["detailed-status"] = " ".join(stage)
905 self.update_db_2("nsrs", nsr_id, db_nsr_update)
906 self._write_op_status(nslcmop_id, stage)
907
908 if failed_detail:
909 raise LcmException("; ".join(failed_detail))
910 return
911
bravof922c4172020-11-24 21:21:43 -0300912 async def instantiate_RO(self, logging_text, nsr_id, nsd, db_nsr, db_nslcmop, db_vnfrs, db_vnfds,
tiernoe876f672020-02-13 14:34:48 +0000913 n2vc_key_list, stage):
tiernoe95ed362020-04-23 08:24:57 +0000914 """
915 Instantiate at RO
916 :param logging_text: preffix text to use at logging
917 :param nsr_id: nsr identity
918 :param nsd: database content of ns descriptor
919 :param db_nsr: database content of ns record
920 :param db_nslcmop: database content of ns operation, in this case, 'instantiate'
921 :param db_vnfrs:
bravof922c4172020-11-24 21:21:43 -0300922 :param db_vnfds: database content of vnfds, indexed by id (not _id). {id: {vnfd_object}, ...}
tiernoe95ed362020-04-23 08:24:57 +0000923 :param n2vc_key_list: ssh-public-key list to be inserted to management vdus via cloud-init
924 :param stage: list with 3 items: [general stage, tasks, vim_specific]. This task will write over vim_specific
925 :return: None or exception
926 """
tiernoe876f672020-02-13 14:34:48 +0000927 try:
tiernoe876f672020-02-13 14:34:48 +0000928 start_deploy = time()
929 ns_params = db_nslcmop.get("operationParams")
930 if ns_params and ns_params.get("timeout_ns_deploy"):
931 timeout_ns_deploy = ns_params["timeout_ns_deploy"]
932 else:
933 timeout_ns_deploy = self.timeout.get("ns_deploy", self.timeout_ns_deploy)
quilesj7e13aeb2019-10-08 13:34:55 +0200934
tiernoe876f672020-02-13 14:34:48 +0000935 # Check for and optionally request placement optimization. Database will be updated if placement activated
936 stage[2] = "Waiting for Placement."
tierno8790a3d2020-04-23 22:49:52 +0000937 if await self._do_placement(logging_text, db_nslcmop, db_vnfrs):
938 # in case of placement change ns_params[vimAcountId) if not present at any vnfrs
939 for vnfr in db_vnfrs.values():
940 if ns_params["vimAccountId"] == vnfr["vim-account-id"]:
941 break
942 else:
943 ns_params["vimAccountId"] == vnfr["vim-account-id"]
quilesj7e13aeb2019-10-08 13:34:55 +0200944
bravof922c4172020-11-24 21:21:43 -0300945 return await self._instantiate_ng_ro(logging_text, nsr_id, nsd, db_nsr, db_nslcmop, db_vnfrs,
946 db_vnfds, n2vc_key_list, stage, start_deploy, timeout_ns_deploy)
tierno2357f4e2020-10-19 16:38:59 +0000947 except Exception as e:
tierno067e04a2020-03-31 12:53:13 +0000948 stage[2] = "ERROR deploying at VIM"
tiernoe876f672020-02-13 14:34:48 +0000949 self.set_vnfr_at_error(db_vnfrs, str(e))
tierno2357f4e2020-10-19 16:38:59 +0000950 self.logger.error("Error deploying at VIM {}".format(e),
951 exc_info=not isinstance(e, (ROclient.ROClientException, LcmException, DbException,
952 NgRoException)))
tiernoe876f672020-02-13 14:34:48 +0000953 raise
quilesj7e13aeb2019-10-08 13:34:55 +0200954
tierno7ecbc342020-09-21 14:05:39 +0000955 async def wait_kdu_up(self, logging_text, nsr_id, vnfr_id, kdu_name):
956 """
957 Wait for kdu to be up, get ip address
958 :param logging_text: prefix use for logging
959 :param nsr_id:
960 :param vnfr_id:
961 :param kdu_name:
962 :return: IP address
963 """
964
965 # self.logger.debug(logging_text + "Starting wait_kdu_up")
966 nb_tries = 0
967
968 while nb_tries < 360:
969 db_vnfr = self.db.get_one("vnfrs", {"_id": vnfr_id})
tiernoe5d05972020-10-09 12:03:24 +0000970 kdur = next((x for x in get_iterable(db_vnfr, "kdur") if x.get("kdu-name") == kdu_name), None)
tierno7ecbc342020-09-21 14:05:39 +0000971 if not kdur:
972 raise LcmException("Not found vnfr_id={}, kdu_name={}".format(vnfr_id, kdu_name))
973 if kdur.get("status"):
974 if kdur["status"] in ("READY", "ENABLED"):
975 return kdur.get("ip-address")
976 else:
977 raise LcmException("target KDU={} is in error state".format(kdu_name))
978
979 await asyncio.sleep(10, loop=self.loop)
980 nb_tries += 1
981 raise LcmException("Timeout waiting KDU={} instantiated".format(kdu_name))
982
tiernoa5088192019-11-26 16:12:53 +0000983 async def wait_vm_up_insert_key_ro(self, logging_text, nsr_id, vnfr_id, vdu_id, vdu_index, pub_key=None, user=None):
984 """
985 Wait for ip addres at RO, and optionally, insert public key in virtual machine
986 :param logging_text: prefix use for logging
987 :param nsr_id:
988 :param vnfr_id:
989 :param vdu_id:
990 :param vdu_index:
991 :param pub_key: public ssh key to inject, None to skip
992 :param user: user to apply the public ssh key
993 :return: IP address
994 """
quilesj7e13aeb2019-10-08 13:34:55 +0200995
tierno2357f4e2020-10-19 16:38:59 +0000996 self.logger.debug(logging_text + "Starting wait_vm_up_insert_key_ro")
tiernod8323042019-08-09 11:32:23 +0000997 ro_nsr_id = None
998 ip_address = None
999 nb_tries = 0
1000 target_vdu_id = None
quilesj3149f262019-12-03 10:58:10 +00001001 ro_retries = 0
quilesj7e13aeb2019-10-08 13:34:55 +02001002
tiernod8323042019-08-09 11:32:23 +00001003 while True:
quilesj7e13aeb2019-10-08 13:34:55 +02001004
quilesj3149f262019-12-03 10:58:10 +00001005 ro_retries += 1
1006 if ro_retries >= 360: # 1 hour
1007 raise LcmException("Not found _admin.deployed.RO.nsr_id for nsr_id: {}".format(nsr_id))
1008
tiernod8323042019-08-09 11:32:23 +00001009 await asyncio.sleep(10, loop=self.loop)
quilesj7e13aeb2019-10-08 13:34:55 +02001010
1011 # get ip address
tiernod8323042019-08-09 11:32:23 +00001012 if not target_vdu_id:
1013 db_vnfr = self.db.get_one("vnfrs", {"_id": vnfr_id})
quilesj3149f262019-12-03 10:58:10 +00001014
1015 if not vdu_id: # for the VNF case
tiernoe876f672020-02-13 14:34:48 +00001016 if db_vnfr.get("status") == "ERROR":
1017 raise LcmException("Cannot inject ssh-key because target VNF is in error state")
tiernod8323042019-08-09 11:32:23 +00001018 ip_address = db_vnfr.get("ip-address")
1019 if not ip_address:
1020 continue
quilesj3149f262019-12-03 10:58:10 +00001021 vdur = next((x for x in get_iterable(db_vnfr, "vdur") if x.get("ip-address") == ip_address), None)
1022 else: # VDU case
1023 vdur = next((x for x in get_iterable(db_vnfr, "vdur")
1024 if x.get("vdu-id-ref") == vdu_id and x.get("count-index") == vdu_index), None)
1025
tierno0e8c3f02020-03-12 17:18:21 +00001026 if not vdur and len(db_vnfr.get("vdur", ())) == 1: # If only one, this should be the target vdu
1027 vdur = db_vnfr["vdur"][0]
quilesj3149f262019-12-03 10:58:10 +00001028 if not vdur:
tierno0e8c3f02020-03-12 17:18:21 +00001029 raise LcmException("Not found vnfr_id={}, vdu_id={}, vdu_index={}".format(vnfr_id, vdu_id,
1030 vdu_index))
tierno2357f4e2020-10-19 16:38:59 +00001031 # New generation RO stores information at "vim_info"
1032 ng_ro_status = None
David Garciaa8bbe672020-11-19 13:06:54 +01001033 target_vim = None
tierno2357f4e2020-10-19 16:38:59 +00001034 if vdur.get("vim_info"):
1035 target_vim = next(t for t in vdur["vim_info"]) # there should be only one key
1036 ng_ro_status = vdur["vim_info"][target_vim].get("vim_status")
1037 if vdur.get("pdu-type") or vdur.get("status") == "ACTIVE" or ng_ro_status == "ACTIVE":
quilesj3149f262019-12-03 10:58:10 +00001038 ip_address = vdur.get("ip-address")
1039 if not ip_address:
1040 continue
1041 target_vdu_id = vdur["vdu-id-ref"]
bravof922c4172020-11-24 21:21:43 -03001042 elif vdur.get("status") == "ERROR" or ng_ro_status == "ERROR":
quilesj3149f262019-12-03 10:58:10 +00001043 raise LcmException("Cannot inject ssh-key because target VM is in error state")
1044
tiernod8323042019-08-09 11:32:23 +00001045 if not target_vdu_id:
1046 continue
tiernod8323042019-08-09 11:32:23 +00001047
quilesj7e13aeb2019-10-08 13:34:55 +02001048 # inject public key into machine
1049 if pub_key and user:
tierno2357f4e2020-10-19 16:38:59 +00001050 self.logger.debug(logging_text + "Inserting RO key")
bravof922c4172020-11-24 21:21:43 -03001051 self.logger.debug("SSH > PubKey > {}".format(pub_key))
tierno0e8c3f02020-03-12 17:18:21 +00001052 if vdur.get("pdu-type"):
1053 self.logger.error(logging_text + "Cannot inject ssh-ky to a PDU")
1054 return ip_address
quilesj7e13aeb2019-10-08 13:34:55 +02001055 try:
1056 ro_vm_id = "{}-{}".format(db_vnfr["member-vnf-index-ref"], target_vdu_id) # TODO add vdu_index
tierno69f0d382020-05-07 13:08:09 +00001057 if self.ng_ro:
bravof922c4172020-11-24 21:21:43 -03001058 target = {"action": {"action": "inject_ssh_key", "key": pub_key, "user": user},
tierno2357f4e2020-10-19 16:38:59 +00001059 "vnf": [{"_id": vnfr_id, "vdur": [{"id": vdur["id"]}]}],
tierno69f0d382020-05-07 13:08:09 +00001060 }
tierno2357f4e2020-10-19 16:38:59 +00001061 desc = await self.RO.deploy(nsr_id, target)
1062 action_id = desc["action_id"]
1063 await self._wait_ng_ro(nsr_id, action_id, timeout=600)
1064 break
tierno69f0d382020-05-07 13:08:09 +00001065 else:
tierno2357f4e2020-10-19 16:38:59 +00001066 # wait until NS is deployed at RO
1067 if not ro_nsr_id:
1068 db_nsrs = self.db.get_one("nsrs", {"_id": nsr_id})
1069 ro_nsr_id = deep_get(db_nsrs, ("_admin", "deployed", "RO", "nsr_id"))
1070 if not ro_nsr_id:
1071 continue
tierno69f0d382020-05-07 13:08:09 +00001072 result_dict = await self.RO.create_action(
1073 item="ns",
1074 item_id_name=ro_nsr_id,
1075 descriptor={"add_public_key": pub_key, "vms": [ro_vm_id], "user": user}
1076 )
1077 # result_dict contains the format {VM-id: {vim_result: 200, description: text}}
1078 if not result_dict or not isinstance(result_dict, dict):
1079 raise LcmException("Unknown response from RO when injecting key")
1080 for result in result_dict.values():
1081 if result.get("vim_result") == 200:
1082 break
1083 else:
1084 raise ROclient.ROClientException("error injecting key: {}".format(
1085 result.get("description")))
1086 break
1087 except NgRoException as e:
1088 raise LcmException("Reaching max tries injecting key. Error: {}".format(e))
quilesj7e13aeb2019-10-08 13:34:55 +02001089 except ROclient.ROClientException as e:
tiernoa5088192019-11-26 16:12:53 +00001090 if not nb_tries:
1091 self.logger.debug(logging_text + "error injecting key: {}. Retrying until {} seconds".
1092 format(e, 20*10))
quilesj7e13aeb2019-10-08 13:34:55 +02001093 nb_tries += 1
tiernoa5088192019-11-26 16:12:53 +00001094 if nb_tries >= 20:
quilesj7e13aeb2019-10-08 13:34:55 +02001095 raise LcmException("Reaching max tries injecting key. Error: {}".format(e))
quilesj7e13aeb2019-10-08 13:34:55 +02001096 else:
quilesj7e13aeb2019-10-08 13:34:55 +02001097 break
1098
1099 return ip_address
1100
tierno5ee02052019-12-05 19:55:02 +00001101 async def _wait_dependent_n2vc(self, nsr_id, vca_deployed_list, vca_index):
1102 """
1103 Wait until dependent VCA deployments have been finished. NS wait for VNFs and VDUs. VNFs for VDUs
1104 """
1105 my_vca = vca_deployed_list[vca_index]
1106 if my_vca.get("vdu_id") or my_vca.get("kdu_name"):
quilesj3655ae02019-12-12 16:08:35 +00001107 # vdu or kdu: no dependencies
tierno5ee02052019-12-05 19:55:02 +00001108 return
1109 timeout = 300
1110 while timeout >= 0:
quilesj3655ae02019-12-12 16:08:35 +00001111 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1112 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
1113 configuration_status_list = db_nsr["configurationStatus"]
1114 for index, vca_deployed in enumerate(configuration_status_list):
tierno5ee02052019-12-05 19:55:02 +00001115 if index == vca_index:
quilesj3655ae02019-12-12 16:08:35 +00001116 # myself
tierno5ee02052019-12-05 19:55:02 +00001117 continue
1118 if not my_vca.get("member-vnf-index") or \
1119 (vca_deployed.get("member-vnf-index") == my_vca.get("member-vnf-index")):
quilesj3655ae02019-12-12 16:08:35 +00001120 internal_status = configuration_status_list[index].get("status")
1121 if internal_status == 'READY':
1122 continue
1123 elif internal_status == 'BROKEN':
tierno5ee02052019-12-05 19:55:02 +00001124 raise LcmException("Configuration aborted because dependent charm/s has failed")
quilesj3655ae02019-12-12 16:08:35 +00001125 else:
1126 break
tierno5ee02052019-12-05 19:55:02 +00001127 else:
quilesj3655ae02019-12-12 16:08:35 +00001128 # no dependencies, return
tierno5ee02052019-12-05 19:55:02 +00001129 return
1130 await asyncio.sleep(10)
1131 timeout -= 1
tierno5ee02052019-12-05 19:55:02 +00001132
1133 raise LcmException("Configuration aborted because dependent charm/s timeout")
1134
tiernoe876f672020-02-13 14:34:48 +00001135 async def instantiate_N2VC(self, logging_text, vca_index, nsi_id, db_nsr, db_vnfr, vdu_id, kdu_name, vdu_index,
tiernob996d942020-07-03 14:52:28 +00001136 config_descriptor, deploy_params, base_folder, nslcmop_id, stage, vca_type, vca_name,
1137 ee_config_descriptor):
tiernod8323042019-08-09 11:32:23 +00001138 nsr_id = db_nsr["_id"]
1139 db_update_entry = "_admin.deployed.VCA.{}.".format(vca_index)
tiernoda6fb102019-11-23 00:36:52 +00001140 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
tiernod8323042019-08-09 11:32:23 +00001141 vca_deployed = db_nsr["_admin"]["deployed"]["VCA"][vca_index]
tiernob996d942020-07-03 14:52:28 +00001142 osm_config = {"osm": {"ns_id": db_nsr["_id"]}}
quilesj7e13aeb2019-10-08 13:34:55 +02001143 db_dict = {
1144 'collection': 'nsrs',
1145 'filter': {'_id': nsr_id},
1146 'path': db_update_entry
1147 }
tiernod8323042019-08-09 11:32:23 +00001148 step = ""
1149 try:
quilesj3655ae02019-12-12 16:08:35 +00001150
1151 element_type = 'NS'
1152 element_under_configuration = nsr_id
1153
tiernod8323042019-08-09 11:32:23 +00001154 vnfr_id = None
1155 if db_vnfr:
1156 vnfr_id = db_vnfr["_id"]
tiernob996d942020-07-03 14:52:28 +00001157 osm_config["osm"]["vnf_id"] = vnfr_id
tiernod8323042019-08-09 11:32:23 +00001158
1159 namespace = "{nsi}.{ns}".format(
1160 nsi=nsi_id if nsi_id else "",
1161 ns=nsr_id)
quilesj3655ae02019-12-12 16:08:35 +00001162
tiernod8323042019-08-09 11:32:23 +00001163 if vnfr_id:
quilesj3655ae02019-12-12 16:08:35 +00001164 element_type = 'VNF'
1165 element_under_configuration = vnfr_id
quilesjb8a35dd2020-01-09 15:10:14 +00001166 namespace += ".{}".format(vnfr_id)
tiernod8323042019-08-09 11:32:23 +00001167 if vdu_id:
1168 namespace += ".{}-{}".format(vdu_id, vdu_index or 0)
quilesj3655ae02019-12-12 16:08:35 +00001169 element_type = 'VDU'
quilesjb8a35dd2020-01-09 15:10:14 +00001170 element_under_configuration = "{}-{}".format(vdu_id, vdu_index or 0)
tiernob996d942020-07-03 14:52:28 +00001171 osm_config["osm"]["vdu_id"] = vdu_id
tierno51183952020-04-03 15:48:18 +00001172 elif kdu_name:
1173 namespace += ".{}".format(kdu_name)
1174 element_type = 'KDU'
1175 element_under_configuration = kdu_name
tiernob996d942020-07-03 14:52:28 +00001176 osm_config["osm"]["kdu_name"] = kdu_name
tiernod8323042019-08-09 11:32:23 +00001177
1178 # Get artifact path
tierno588547c2020-07-01 15:30:20 +00001179 artifact_path = "{}/{}/{}/{}".format(
tiernod8323042019-08-09 11:32:23 +00001180 base_folder["folder"],
1181 base_folder["pkg-dir"],
tierno588547c2020-07-01 15:30:20 +00001182 "charms" if vca_type in ("native_charm", "lxc_proxy_charm", "k8s_proxy_charm") else "helm-charts",
1183 vca_name
tiernod8323042019-08-09 11:32:23 +00001184 )
bravof922c4172020-11-24 21:21:43 -03001185
1186 self.logger.debug("Artifact path > {}".format(artifact_path))
1187
tiernoa278b842020-07-08 15:33:55 +00001188 # get initial_config_primitive_list that applies to this element
1189 initial_config_primitive_list = config_descriptor.get('initial-config-primitive')
1190
bravof922c4172020-11-24 21:21:43 -03001191 self.logger.debug("Initial config primitive list > {}".format(initial_config_primitive_list))
1192
tiernoa278b842020-07-08 15:33:55 +00001193 # add config if not present for NS charm
1194 ee_descriptor_id = ee_config_descriptor.get("id")
bravof922c4172020-11-24 21:21:43 -03001195 self.logger.debug("EE Descriptor > {}".format(ee_descriptor_id))
1196 initial_config_primitive_list = get_ee_sorted_initial_config_primitive_list(initial_config_primitive_list,
1197 vca_deployed, ee_descriptor_id)
tiernod8323042019-08-09 11:32:23 +00001198
bravof922c4172020-11-24 21:21:43 -03001199 self.logger.debug("Initial config primitive list #2 > {}".format(initial_config_primitive_list))
tierno588547c2020-07-01 15:30:20 +00001200 # n2vc_redesign STEP 3.1
tierno588547c2020-07-01 15:30:20 +00001201 # find old ee_id if exists
1202 ee_id = vca_deployed.get("ee_id")
tiernod8323042019-08-09 11:32:23 +00001203
David Garciaaae391f2020-11-09 11:12:54 +01001204 vim_account_id = (
1205 deep_get(db_vnfr, ("vim-account-id",)) or
1206 deep_get(deploy_params, ("OSM", "vim_account_id"))
1207 )
1208 vca_cloud, vca_cloud_credential = self.get_vca_cloud_and_credentials(vim_account_id)
1209 vca_k8s_cloud, vca_k8s_cloud_credential = self.get_vca_k8s_cloud_and_credentials(vim_account_id)
tierno588547c2020-07-01 15:30:20 +00001210 # create or register execution environment in VCA
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001211 if vca_type in ("lxc_proxy_charm", "k8s_proxy_charm", "helm", "helm-v3"):
quilesj7e13aeb2019-10-08 13:34:55 +02001212
tierno588547c2020-07-01 15:30:20 +00001213 self._write_configuration_status(
1214 nsr_id=nsr_id,
1215 vca_index=vca_index,
1216 status='CREATING',
1217 element_under_configuration=element_under_configuration,
1218 element_type=element_type
1219 )
tiernod8323042019-08-09 11:32:23 +00001220
tierno588547c2020-07-01 15:30:20 +00001221 step = "create execution environment"
lloretgalleg18cb3cb2020-12-10 14:21:10 +00001222 self.logger.debug(logging_text + step)
David Garciaaae391f2020-11-09 11:12:54 +01001223
1224 ee_id = None
1225 credentials = None
1226 if vca_type == "k8s_proxy_charm":
1227 ee_id = await self.vca_map[vca_type].install_k8s_proxy_charm(
1228 charm_name=artifact_path[artifact_path.rfind("/") + 1:],
1229 namespace=namespace,
1230 artifact_path=artifact_path,
1231 db_dict=db_dict,
1232 cloud_name=vca_k8s_cloud,
1233 credential_name=vca_k8s_cloud_credential,
1234 )
lloretgalleg18cb3cb2020-12-10 14:21:10 +00001235 elif vca_type == "helm" or vca_type == "helm-v3":
bravof922c4172020-11-24 21:21:43 -03001236 ee_id, credentials = await self.vca_map[vca_type].create_execution_environment(
1237 namespace=namespace,
1238 reuse_ee_id=ee_id,
1239 db_dict=db_dict,
lloretgalleg18cb3cb2020-12-10 14:21:10 +00001240 config=osm_config,
1241 artifact_path=artifact_path,
1242 vca_type=vca_type
bravof922c4172020-11-24 21:21:43 -03001243 )
lloretgalleg18cb3cb2020-12-10 14:21:10 +00001244 else:
David Garciaaae391f2020-11-09 11:12:54 +01001245 ee_id, credentials = await self.vca_map[vca_type].create_execution_environment(
1246 namespace=namespace,
1247 reuse_ee_id=ee_id,
1248 db_dict=db_dict,
David Garciaaae391f2020-11-09 11:12:54 +01001249 cloud_name=vca_cloud,
1250 credential_name=vca_cloud_credential,
1251 )
quilesj3655ae02019-12-12 16:08:35 +00001252
tierno588547c2020-07-01 15:30:20 +00001253 elif vca_type == "native_charm":
1254 step = "Waiting to VM being up and getting IP address"
1255 self.logger.debug(logging_text + step)
1256 rw_mgmt_ip = await self.wait_vm_up_insert_key_ro(logging_text, nsr_id, vnfr_id, vdu_id, vdu_index,
1257 user=None, pub_key=None)
1258 credentials = {"hostname": rw_mgmt_ip}
1259 # get username
1260 username = deep_get(config_descriptor, ("config-access", "ssh-access", "default-user"))
1261 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1262 # merged. Meanwhile let's get username from initial-config-primitive
tiernoa278b842020-07-08 15:33:55 +00001263 if not username and initial_config_primitive_list:
1264 for config_primitive in initial_config_primitive_list:
tierno588547c2020-07-01 15:30:20 +00001265 for param in config_primitive.get("parameter", ()):
1266 if param["name"] == "ssh-username":
1267 username = param["value"]
1268 break
1269 if not username:
tiernoa278b842020-07-08 15:33:55 +00001270 raise LcmException("Cannot determine the username neither with 'initial-config-primitive' nor with "
tierno588547c2020-07-01 15:30:20 +00001271 "'config-access.ssh-access.default-user'")
1272 credentials["username"] = username
1273 # n2vc_redesign STEP 3.2
quilesj3655ae02019-12-12 16:08:35 +00001274
tierno588547c2020-07-01 15:30:20 +00001275 self._write_configuration_status(
1276 nsr_id=nsr_id,
1277 vca_index=vca_index,
1278 status='REGISTERING',
1279 element_under_configuration=element_under_configuration,
1280 element_type=element_type
1281 )
quilesj3655ae02019-12-12 16:08:35 +00001282
tierno588547c2020-07-01 15:30:20 +00001283 step = "register execution environment {}".format(credentials)
1284 self.logger.debug(logging_text + step)
1285 ee_id = await self.vca_map[vca_type].register_execution_environment(
David Garciaaae391f2020-11-09 11:12:54 +01001286 credentials=credentials,
1287 namespace=namespace,
1288 db_dict=db_dict,
1289 cloud_name=vca_cloud,
1290 credential_name=vca_cloud_credential,
1291 )
tierno3bedc9b2019-11-27 15:46:57 +00001292
tierno588547c2020-07-01 15:30:20 +00001293 # for compatibility with MON/POL modules, the need model and application name at database
1294 # TODO ask MON/POL if needed to not assuming anymore the format "model_name.application_name"
1295 ee_id_parts = ee_id.split('.')
1296 db_nsr_update = {db_update_entry + "ee_id": ee_id}
1297 if len(ee_id_parts) >= 2:
1298 model_name = ee_id_parts[0]
1299 application_name = ee_id_parts[1]
1300 db_nsr_update[db_update_entry + "model"] = model_name
1301 db_nsr_update[db_update_entry + "application"] = application_name
tiernod8323042019-08-09 11:32:23 +00001302
1303 # n2vc_redesign STEP 3.3
tiernod8323042019-08-09 11:32:23 +00001304 step = "Install configuration Software"
quilesj3655ae02019-12-12 16:08:35 +00001305
tiernoc231a872020-01-21 08:49:05 +00001306 self._write_configuration_status(
quilesj3655ae02019-12-12 16:08:35 +00001307 nsr_id=nsr_id,
1308 vca_index=vca_index,
1309 status='INSTALLING SW',
1310 element_under_configuration=element_under_configuration,
tierno51183952020-04-03 15:48:18 +00001311 element_type=element_type,
tierno588547c2020-07-01 15:30:20 +00001312 other_update=db_nsr_update
quilesj3655ae02019-12-12 16:08:35 +00001313 )
1314
tierno3bedc9b2019-11-27 15:46:57 +00001315 # TODO check if already done
quilesj7e13aeb2019-10-08 13:34:55 +02001316 self.logger.debug(logging_text + step)
David Garcia18a63322020-04-01 16:14:59 +02001317 config = None
tierno588547c2020-07-01 15:30:20 +00001318 if vca_type == "native_charm":
tiernoa278b842020-07-08 15:33:55 +00001319 config_primitive = next((p for p in initial_config_primitive_list if p["name"] == "config"), None)
1320 if config_primitive:
1321 config = self._map_primitive_params(
1322 config_primitive,
1323 {},
1324 deploy_params
1325 )
tierno588547c2020-07-01 15:30:20 +00001326 num_units = 1
1327 if vca_type == "lxc_proxy_charm":
1328 if element_type == "NS":
1329 num_units = db_nsr.get("config-units") or 1
1330 elif element_type == "VNF":
1331 num_units = db_vnfr.get("config-units") or 1
1332 elif element_type == "VDU":
1333 for v in db_vnfr["vdur"]:
1334 if vdu_id == v["vdu-id-ref"]:
1335 num_units = v.get("config-units") or 1
1336 break
David Garciaaae391f2020-11-09 11:12:54 +01001337 if vca_type != "k8s_proxy_charm":
1338 await self.vca_map[vca_type].install_configuration_sw(
1339 ee_id=ee_id,
1340 artifact_path=artifact_path,
1341 db_dict=db_dict,
1342 config=config,
1343 num_units=num_units,
1344 )
quilesj7e13aeb2019-10-08 13:34:55 +02001345
quilesj63f90042020-01-17 09:53:55 +00001346 # write in db flag of configuration_sw already installed
1347 self.update_db_2("nsrs", nsr_id, {db_update_entry + "config_sw_installed": True})
1348
1349 # add relations for this VCA (wait for other peers related with this VCA)
tierno588547c2020-07-01 15:30:20 +00001350 await self._add_vca_relations(logging_text=logging_text, nsr_id=nsr_id,
1351 vca_index=vca_index, vca_type=vca_type)
quilesj63f90042020-01-17 09:53:55 +00001352
quilesj7e13aeb2019-10-08 13:34:55 +02001353 # if SSH access is required, then get execution environment SSH public
David Garciaa27e20a2020-07-10 13:12:44 +02001354 # if native charm we have waited already to VM be UP
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001355 if vca_type in ("k8s_proxy_charm", "lxc_proxy_charm", "helm", "helm-v3"):
tierno3bedc9b2019-11-27 15:46:57 +00001356 pub_key = None
1357 user = None
tierno588547c2020-07-01 15:30:20 +00001358 # self.logger.debug("get ssh key block")
tierno3bedc9b2019-11-27 15:46:57 +00001359 if deep_get(config_descriptor, ("config-access", "ssh-access", "required")):
tierno588547c2020-07-01 15:30:20 +00001360 # self.logger.debug("ssh key needed")
tierno3bedc9b2019-11-27 15:46:57 +00001361 # Needed to inject a ssh key
1362 user = deep_get(config_descriptor, ("config-access", "ssh-access", "default-user"))
1363 step = "Install configuration Software, getting public ssh key"
tierno588547c2020-07-01 15:30:20 +00001364 pub_key = await self.vca_map[vca_type].get_ee_ssh_public__key(ee_id=ee_id, db_dict=db_dict)
quilesj7e13aeb2019-10-08 13:34:55 +02001365
tiernoacc90452019-12-10 11:06:54 +00001366 step = "Insert public key into VM user={} ssh_key={}".format(user, pub_key)
tierno3bedc9b2019-11-27 15:46:57 +00001367 else:
tierno588547c2020-07-01 15:30:20 +00001368 # self.logger.debug("no need to get ssh key")
tierno3bedc9b2019-11-27 15:46:57 +00001369 step = "Waiting to VM being up and getting IP address"
1370 self.logger.debug(logging_text + step)
quilesj7e13aeb2019-10-08 13:34:55 +02001371
tierno3bedc9b2019-11-27 15:46:57 +00001372 # n2vc_redesign STEP 5.1
1373 # wait for RO (ip-address) Insert pub_key into VM
tierno5ee02052019-12-05 19:55:02 +00001374 if vnfr_id:
tierno7ecbc342020-09-21 14:05:39 +00001375 if kdu_name:
1376 rw_mgmt_ip = await self.wait_kdu_up(logging_text, nsr_id, vnfr_id, kdu_name)
1377 else:
1378 rw_mgmt_ip = await self.wait_vm_up_insert_key_ro(logging_text, nsr_id, vnfr_id, vdu_id,
1379 vdu_index, user=user, pub_key=pub_key)
tierno5ee02052019-12-05 19:55:02 +00001380 else:
1381 rw_mgmt_ip = None # This is for a NS configuration
tierno3bedc9b2019-11-27 15:46:57 +00001382
1383 self.logger.debug(logging_text + ' VM_ip_address={}'.format(rw_mgmt_ip))
quilesj7e13aeb2019-10-08 13:34:55 +02001384
tiernoa5088192019-11-26 16:12:53 +00001385 # store rw_mgmt_ip in deploy params for later replacement
quilesj7e13aeb2019-10-08 13:34:55 +02001386 deploy_params["rw_mgmt_ip"] = rw_mgmt_ip
tiernod8323042019-08-09 11:32:23 +00001387
1388 # n2vc_redesign STEP 6 Execute initial config primitive
quilesj7e13aeb2019-10-08 13:34:55 +02001389 step = 'execute initial config primitive'
quilesj3655ae02019-12-12 16:08:35 +00001390
1391 # wait for dependent primitives execution (NS -> VNF -> VDU)
tierno5ee02052019-12-05 19:55:02 +00001392 if initial_config_primitive_list:
1393 await self._wait_dependent_n2vc(nsr_id, vca_deployed_list, vca_index)
quilesj3655ae02019-12-12 16:08:35 +00001394
1395 # stage, in function of element type: vdu, kdu, vnf or ns
1396 my_vca = vca_deployed_list[vca_index]
1397 if my_vca.get("vdu_id") or my_vca.get("kdu_name"):
1398 # VDU or KDU
tiernoe876f672020-02-13 14:34:48 +00001399 stage[0] = 'Stage 3/5: running Day-1 primitives for VDU.'
quilesj3655ae02019-12-12 16:08:35 +00001400 elif my_vca.get("member-vnf-index"):
1401 # VNF
tiernoe876f672020-02-13 14:34:48 +00001402 stage[0] = 'Stage 4/5: running Day-1 primitives for VNF.'
quilesj3655ae02019-12-12 16:08:35 +00001403 else:
1404 # NS
tiernoe876f672020-02-13 14:34:48 +00001405 stage[0] = 'Stage 5/5: running Day-1 primitives for NS.'
quilesj3655ae02019-12-12 16:08:35 +00001406
tiernoc231a872020-01-21 08:49:05 +00001407 self._write_configuration_status(
quilesj3655ae02019-12-12 16:08:35 +00001408 nsr_id=nsr_id,
1409 vca_index=vca_index,
1410 status='EXECUTING PRIMITIVE'
1411 )
1412
1413 self._write_op_status(
1414 op_id=nslcmop_id,
1415 stage=stage
1416 )
1417
tiernoe876f672020-02-13 14:34:48 +00001418 check_if_terminated_needed = True
tiernod8323042019-08-09 11:32:23 +00001419 for initial_config_primitive in initial_config_primitive_list:
tiernoda6fb102019-11-23 00:36:52 +00001420 # adding information on the vca_deployed if it is a NS execution environment
1421 if not vca_deployed["member-vnf-index"]:
David Garciad4816682019-12-09 14:57:43 +01001422 deploy_params["ns_config_info"] = json.dumps(self._get_ns_config_info(nsr_id))
tiernod8323042019-08-09 11:32:23 +00001423 # TODO check if already done
1424 primitive_params_ = self._map_primitive_params(initial_config_primitive, {}, deploy_params)
tierno3bedc9b2019-11-27 15:46:57 +00001425
tiernod8323042019-08-09 11:32:23 +00001426 step = "execute primitive '{}' params '{}'".format(initial_config_primitive["name"], primitive_params_)
1427 self.logger.debug(logging_text + step)
tierno588547c2020-07-01 15:30:20 +00001428 await self.vca_map[vca_type].exec_primitive(
quilesj7e13aeb2019-10-08 13:34:55 +02001429 ee_id=ee_id,
1430 primitive_name=initial_config_primitive["name"],
1431 params_dict=primitive_params_,
1432 db_dict=db_dict
1433 )
tiernoe876f672020-02-13 14:34:48 +00001434 # Once some primitive has been exec, check and write at db if it needs to exec terminated primitives
1435 if check_if_terminated_needed:
1436 if config_descriptor.get('terminate-config-primitive'):
1437 self.update_db_2("nsrs", nsr_id, {db_update_entry + "needed_terminate": True})
1438 check_if_terminated_needed = False
quilesj3655ae02019-12-12 16:08:35 +00001439
tiernod8323042019-08-09 11:32:23 +00001440 # TODO register in database that primitive is done
quilesj7e13aeb2019-10-08 13:34:55 +02001441
tiernob996d942020-07-03 14:52:28 +00001442 # STEP 7 Configure metrics
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001443 if vca_type == "helm" or vca_type == "helm-v3":
tiernob996d942020-07-03 14:52:28 +00001444 prometheus_jobs = await self.add_prometheus_metrics(
1445 ee_id=ee_id,
1446 artifact_path=artifact_path,
1447 ee_config_descriptor=ee_config_descriptor,
1448 vnfr_id=vnfr_id,
1449 nsr_id=nsr_id,
1450 target_ip=rw_mgmt_ip,
1451 )
1452 if prometheus_jobs:
1453 self.update_db_2("nsrs", nsr_id, {db_update_entry + "prometheus_jobs": prometheus_jobs})
1454
quilesj7e13aeb2019-10-08 13:34:55 +02001455 step = "instantiated at VCA"
1456 self.logger.debug(logging_text + step)
1457
tiernoc231a872020-01-21 08:49:05 +00001458 self._write_configuration_status(
quilesj3655ae02019-12-12 16:08:35 +00001459 nsr_id=nsr_id,
1460 vca_index=vca_index,
1461 status='READY'
1462 )
1463
tiernod8323042019-08-09 11:32:23 +00001464 except Exception as e: # TODO not use Exception but N2VC exception
quilesj3655ae02019-12-12 16:08:35 +00001465 # self.update_db_2("nsrs", nsr_id, {db_update_entry + "instantiation": "FAILED"})
tiernoe876f672020-02-13 14:34:48 +00001466 if not isinstance(e, (DbException, N2VCException, LcmException, asyncio.CancelledError)):
1467 self.logger.error("Exception while {} : {}".format(step, e), exc_info=True)
tiernoc231a872020-01-21 08:49:05 +00001468 self._write_configuration_status(
quilesj3655ae02019-12-12 16:08:35 +00001469 nsr_id=nsr_id,
1470 vca_index=vca_index,
1471 status='BROKEN'
1472 )
tiernoe876f672020-02-13 14:34:48 +00001473 raise LcmException("{} {}".format(step, e)) from e
tiernod8323042019-08-09 11:32:23 +00001474
quilesj4cda56b2019-12-05 10:02:20 +00001475 def _write_ns_status(self, nsr_id: str, ns_state: str, current_operation: str, current_operation_id: str,
tiernoa2143262020-03-27 16:20:40 +00001476 error_description: str = None, error_detail: str = None, other_update: dict = None):
tiernoe876f672020-02-13 14:34:48 +00001477 """
1478 Update db_nsr fields.
1479 :param nsr_id:
1480 :param ns_state:
1481 :param current_operation:
1482 :param current_operation_id:
1483 :param error_description:
tiernoa2143262020-03-27 16:20:40 +00001484 :param error_detail:
tiernoe876f672020-02-13 14:34:48 +00001485 :param other_update: Other required changes at database if provided, will be cleared
1486 :return:
1487 """
quilesj4cda56b2019-12-05 10:02:20 +00001488 try:
tiernoe876f672020-02-13 14:34:48 +00001489 db_dict = other_update or {}
1490 db_dict["_admin.nslcmop"] = current_operation_id # for backward compatibility
1491 db_dict["_admin.current-operation"] = current_operation_id
1492 db_dict["_admin.operation-type"] = current_operation if current_operation != "IDLE" else None
quilesj4cda56b2019-12-05 10:02:20 +00001493 db_dict["currentOperation"] = current_operation
1494 db_dict["currentOperationID"] = current_operation_id
1495 db_dict["errorDescription"] = error_description
tiernoa2143262020-03-27 16:20:40 +00001496 db_dict["errorDetail"] = error_detail
tiernoe876f672020-02-13 14:34:48 +00001497
1498 if ns_state:
1499 db_dict["nsState"] = ns_state
quilesj4cda56b2019-12-05 10:02:20 +00001500 self.update_db_2("nsrs", nsr_id, db_dict)
tiernoe876f672020-02-13 14:34:48 +00001501 except DbException as e:
quilesj3655ae02019-12-12 16:08:35 +00001502 self.logger.warn('Error writing NS status, ns={}: {}'.format(nsr_id, e))
1503
tiernoe876f672020-02-13 14:34:48 +00001504 def _write_op_status(self, op_id: str, stage: list = None, error_message: str = None, queuePosition: int = 0,
1505 operation_state: str = None, other_update: dict = None):
quilesj3655ae02019-12-12 16:08:35 +00001506 try:
tiernoe876f672020-02-13 14:34:48 +00001507 db_dict = other_update or {}
quilesj3655ae02019-12-12 16:08:35 +00001508 db_dict['queuePosition'] = queuePosition
tiernoe876f672020-02-13 14:34:48 +00001509 if isinstance(stage, list):
1510 db_dict['stage'] = stage[0]
1511 db_dict['detailed-status'] = " ".join(stage)
1512 elif stage is not None:
1513 db_dict['stage'] = str(stage)
1514
1515 if error_message is not None:
quilesj3655ae02019-12-12 16:08:35 +00001516 db_dict['errorMessage'] = error_message
tiernoe876f672020-02-13 14:34:48 +00001517 if operation_state is not None:
1518 db_dict['operationState'] = operation_state
1519 db_dict["statusEnteredTime"] = time()
quilesj3655ae02019-12-12 16:08:35 +00001520 self.update_db_2("nslcmops", op_id, db_dict)
tiernoe876f672020-02-13 14:34:48 +00001521 except DbException as e:
quilesj3655ae02019-12-12 16:08:35 +00001522 self.logger.warn('Error writing OPERATION status for op_id: {} -> {}'.format(op_id, e))
1523
tierno51183952020-04-03 15:48:18 +00001524 def _write_all_config_status(self, db_nsr: dict, status: str):
quilesj3655ae02019-12-12 16:08:35 +00001525 try:
tierno51183952020-04-03 15:48:18 +00001526 nsr_id = db_nsr["_id"]
quilesj3655ae02019-12-12 16:08:35 +00001527 # configurationStatus
1528 config_status = db_nsr.get('configurationStatus')
1529 if config_status:
tierno51183952020-04-03 15:48:18 +00001530 db_nsr_update = {"configurationStatus.{}.status".format(index): status for index, v in
1531 enumerate(config_status) if v}
quilesj3655ae02019-12-12 16:08:35 +00001532 # update status
tierno51183952020-04-03 15:48:18 +00001533 self.update_db_2("nsrs", nsr_id, db_nsr_update)
quilesj3655ae02019-12-12 16:08:35 +00001534
tiernoe876f672020-02-13 14:34:48 +00001535 except DbException as e:
quilesj3655ae02019-12-12 16:08:35 +00001536 self.logger.warn('Error writing all configuration status, ns={}: {}'.format(nsr_id, e))
1537
quilesj63f90042020-01-17 09:53:55 +00001538 def _write_configuration_status(self, nsr_id: str, vca_index: int, status: str = None,
tierno51183952020-04-03 15:48:18 +00001539 element_under_configuration: str = None, element_type: str = None,
1540 other_update: dict = None):
quilesj3655ae02019-12-12 16:08:35 +00001541
1542 # self.logger.debug('_write_configuration_status(): vca_index={}, status={}'
1543 # .format(vca_index, status))
1544
1545 try:
1546 db_path = 'configurationStatus.{}.'.format(vca_index)
tierno51183952020-04-03 15:48:18 +00001547 db_dict = other_update or {}
quilesj63f90042020-01-17 09:53:55 +00001548 if status:
1549 db_dict[db_path + 'status'] = status
quilesj3655ae02019-12-12 16:08:35 +00001550 if element_under_configuration:
1551 db_dict[db_path + 'elementUnderConfiguration'] = element_under_configuration
1552 if element_type:
1553 db_dict[db_path + 'elementType'] = element_type
1554 self.update_db_2("nsrs", nsr_id, db_dict)
tiernoe876f672020-02-13 14:34:48 +00001555 except DbException as e:
quilesj3655ae02019-12-12 16:08:35 +00001556 self.logger.warn('Error writing configuration status={}, ns={}, vca_index={}: {}'
1557 .format(status, nsr_id, vca_index, e))
quilesj4cda56b2019-12-05 10:02:20 +00001558
tierno38089af2020-04-16 07:56:58 +00001559 async def _do_placement(self, logging_text, db_nslcmop, db_vnfrs):
1560 """
1561 Check and computes the placement, (vim account where to deploy). If it is decided by an external tool, it
1562 sends the request via kafka and wait until the result is wrote at database (nslcmops _admin.plca).
1563 Database is used because the result can be obtained from a different LCM worker in case of HA.
1564 :param logging_text: contains the prefix for logging, with the ns and nslcmop identifiers
1565 :param db_nslcmop: database content of nslcmop
1566 :param db_vnfrs: database content of vnfrs, indexed by member-vnf-index.
tierno8790a3d2020-04-23 22:49:52 +00001567 :return: True if some modification is done. Modifies database vnfrs and parameter db_vnfr with the
1568 computed 'vim-account-id'
tierno38089af2020-04-16 07:56:58 +00001569 """
tierno8790a3d2020-04-23 22:49:52 +00001570 modified = False
tierno38089af2020-04-16 07:56:58 +00001571 nslcmop_id = db_nslcmop['_id']
magnussonle9198bb2020-01-21 13:00:51 +01001572 placement_engine = deep_get(db_nslcmop, ('operationParams', 'placement-engine'))
1573 if placement_engine == "PLA":
tierno38089af2020-04-16 07:56:58 +00001574 self.logger.debug(logging_text + "Invoke and wait for placement optimization")
1575 await self.msg.aiowrite("pla", "get_placement", {'nslcmopId': nslcmop_id}, loop=self.loop)
magnussonle9198bb2020-01-21 13:00:51 +01001576 db_poll_interval = 5
tierno38089af2020-04-16 07:56:58 +00001577 wait = db_poll_interval * 10
magnussonle9198bb2020-01-21 13:00:51 +01001578 pla_result = None
1579 while not pla_result and wait >= 0:
1580 await asyncio.sleep(db_poll_interval)
1581 wait -= db_poll_interval
tierno38089af2020-04-16 07:56:58 +00001582 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
magnussonle9198bb2020-01-21 13:00:51 +01001583 pla_result = deep_get(db_nslcmop, ('_admin', 'pla'))
1584
1585 if not pla_result:
tierno38089af2020-04-16 07:56:58 +00001586 raise LcmException("Placement timeout for nslcmopId={}".format(nslcmop_id))
magnussonle9198bb2020-01-21 13:00:51 +01001587
1588 for pla_vnf in pla_result['vnf']:
1589 vnfr = db_vnfrs.get(pla_vnf['member-vnf-index'])
1590 if not pla_vnf.get('vimAccountId') or not vnfr:
1591 continue
tierno8790a3d2020-04-23 22:49:52 +00001592 modified = True
magnussonle9198bb2020-01-21 13:00:51 +01001593 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, {"vim-account-id": pla_vnf['vimAccountId']})
tierno38089af2020-04-16 07:56:58 +00001594 # Modifies db_vnfrs
1595 vnfr["vim-account-id"] = pla_vnf['vimAccountId']
tierno8790a3d2020-04-23 22:49:52 +00001596 return modified
magnussonle9198bb2020-01-21 13:00:51 +01001597
1598 def update_nsrs_with_pla_result(self, params):
1599 try:
1600 nslcmop_id = deep_get(params, ('placement', 'nslcmopId'))
1601 self.update_db_2("nslcmops", nslcmop_id, {"_admin.pla": params.get('placement')})
1602 except Exception as e:
1603 self.logger.warn('Update failed for nslcmop_id={}:{}'.format(nslcmop_id, e))
1604
tierno59d22d22018-09-25 18:10:19 +02001605 async def instantiate(self, nsr_id, nslcmop_id):
quilesj7e13aeb2019-10-08 13:34:55 +02001606 """
1607
1608 :param nsr_id: ns instance to deploy
1609 :param nslcmop_id: operation to run
1610 :return:
1611 """
kuused124bfe2019-06-18 12:09:24 +02001612
1613 # Try to lock HA task here
1614 task_is_locked_by_me = self.lcm_tasks.lock_HA('ns', 'nslcmops', nslcmop_id)
1615 if not task_is_locked_by_me:
quilesj3655ae02019-12-12 16:08:35 +00001616 self.logger.debug('instantiate() task is not locked by me, ns={}'.format(nsr_id))
kuused124bfe2019-06-18 12:09:24 +02001617 return
1618
tierno59d22d22018-09-25 18:10:19 +02001619 logging_text = "Task ns={} instantiate={} ".format(nsr_id, nslcmop_id)
1620 self.logger.debug(logging_text + "Enter")
quilesj7e13aeb2019-10-08 13:34:55 +02001621
tierno59d22d22018-09-25 18:10:19 +02001622 # get all needed from database
quilesj7e13aeb2019-10-08 13:34:55 +02001623
1624 # database nsrs record
tierno59d22d22018-09-25 18:10:19 +02001625 db_nsr = None
quilesj7e13aeb2019-10-08 13:34:55 +02001626
1627 # database nslcmops record
tierno59d22d22018-09-25 18:10:19 +02001628 db_nslcmop = None
quilesj7e13aeb2019-10-08 13:34:55 +02001629
1630 # update operation on nsrs
tiernoe876f672020-02-13 14:34:48 +00001631 db_nsr_update = {}
quilesj7e13aeb2019-10-08 13:34:55 +02001632 # update operation on nslcmops
tierno59d22d22018-09-25 18:10:19 +02001633 db_nslcmop_update = {}
quilesj7e13aeb2019-10-08 13:34:55 +02001634
tierno59d22d22018-09-25 18:10:19 +02001635 nslcmop_operation_state = None
quilesj7e13aeb2019-10-08 13:34:55 +02001636 db_vnfrs = {} # vnf's info indexed by member-index
1637 # n2vc_info = {}
tiernoe876f672020-02-13 14:34:48 +00001638 tasks_dict_info = {} # from task to info text
tierno59d22d22018-09-25 18:10:19 +02001639 exc = None
tiernoe876f672020-02-13 14:34:48 +00001640 error_list = []
1641 stage = ['Stage 1/5: preparation of the environment.', "Waiting for previous operations to terminate.", ""]
1642 # ^ stage, step, VIM progress
tierno59d22d22018-09-25 18:10:19 +02001643 try:
kuused124bfe2019-06-18 12:09:24 +02001644 # wait for any previous tasks in process
1645 await self.lcm_tasks.waitfor_related_HA('ns', 'nslcmops', nslcmop_id)
1646
tiernob5203912020-08-11 11:20:13 +00001647 stage[1] = "Sync filesystem from database."
tierno21e42212020-07-09 13:51:20 +00001648 self.fs.sync() # TODO, make use of partial sync, only for the needed packages
1649
quilesj7e13aeb2019-10-08 13:34:55 +02001650 # STEP 0: Reading database (nslcmops, nsrs, nsds, vnfrs, vnfds)
tiernob5203912020-08-11 11:20:13 +00001651 stage[1] = "Reading from database."
quilesj4cda56b2019-12-05 10:02:20 +00001652 # nsState="BUILDING", currentOperation="INSTANTIATING", currentOperationID=nslcmop_id
tiernoe876f672020-02-13 14:34:48 +00001653 db_nsr_update["detailed-status"] = "creating"
1654 db_nsr_update["operational-status"] = "init"
quilesj4cda56b2019-12-05 10:02:20 +00001655 self._write_ns_status(
1656 nsr_id=nsr_id,
1657 ns_state="BUILDING",
1658 current_operation="INSTANTIATING",
tiernoe876f672020-02-13 14:34:48 +00001659 current_operation_id=nslcmop_id,
1660 other_update=db_nsr_update
1661 )
1662 self._write_op_status(
1663 op_id=nslcmop_id,
1664 stage=stage,
1665 queuePosition=0
quilesj4cda56b2019-12-05 10:02:20 +00001666 )
1667
quilesj7e13aeb2019-10-08 13:34:55 +02001668 # read from db: operation
tiernob5203912020-08-11 11:20:13 +00001669 stage[1] = "Getting nslcmop={} from db.".format(nslcmop_id)
tierno59d22d22018-09-25 18:10:19 +02001670 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
tierno744303e2020-01-13 16:46:31 +00001671 ns_params = db_nslcmop.get("operationParams")
1672 if ns_params and ns_params.get("timeout_ns_deploy"):
1673 timeout_ns_deploy = ns_params["timeout_ns_deploy"]
1674 else:
1675 timeout_ns_deploy = self.timeout.get("ns_deploy", self.timeout_ns_deploy)
quilesj7e13aeb2019-10-08 13:34:55 +02001676
1677 # read from db: ns
tiernob5203912020-08-11 11:20:13 +00001678 stage[1] = "Getting nsr={} from db.".format(nsr_id)
tierno59d22d22018-09-25 18:10:19 +02001679 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
tiernob5203912020-08-11 11:20:13 +00001680 stage[1] = "Getting nsd={} from db.".format(db_nsr["nsd-id"])
tiernod732fb82020-05-21 13:18:23 +00001681 nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
1682 db_nsr["nsd"] = nsd
tiernod8323042019-08-09 11:32:23 +00001683 # nsr_name = db_nsr["name"] # TODO short-name??
tierno47e86b52018-10-10 14:05:55 +02001684
quilesj7e13aeb2019-10-08 13:34:55 +02001685 # read from db: vnf's of this ns
tiernob5203912020-08-11 11:20:13 +00001686 stage[1] = "Getting vnfrs from db."
tiernoe876f672020-02-13 14:34:48 +00001687 self.logger.debug(logging_text + stage[1])
tierno27246d82018-09-27 15:59:09 +02001688 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
tierno27246d82018-09-27 15:59:09 +02001689
quilesj7e13aeb2019-10-08 13:34:55 +02001690 # read from db: vnfd's for every vnf
bravof922c4172020-11-24 21:21:43 -03001691 db_vnfds = [] # every vnfd data
quilesj7e13aeb2019-10-08 13:34:55 +02001692
1693 # for each vnf in ns, read vnfd
tierno27246d82018-09-27 15:59:09 +02001694 for vnfr in db_vnfrs_list:
bravof922c4172020-11-24 21:21:43 -03001695 db_vnfrs[vnfr["member-vnf-index-ref"]] = vnfr
1696 vnfd_id = vnfr["vnfd-id"]
1697 vnfd_ref = vnfr["vnfd-ref"]
lloretgalleg6d488782020-07-22 10:13:46 +00001698
quilesj7e13aeb2019-10-08 13:34:55 +02001699 # if we haven't this vnfd, read it from db
tierno27246d82018-09-27 15:59:09 +02001700 if vnfd_id not in db_vnfds:
quilesj63f90042020-01-17 09:53:55 +00001701 # read from db
tiernob5203912020-08-11 11:20:13 +00001702 stage[1] = "Getting vnfd={} id='{}' from db.".format(vnfd_id, vnfd_ref)
tiernoe876f672020-02-13 14:34:48 +00001703 self.logger.debug(logging_text + stage[1])
tierno27246d82018-09-27 15:59:09 +02001704 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
tierno27246d82018-09-27 15:59:09 +02001705
quilesj7e13aeb2019-10-08 13:34:55 +02001706 # store vnfd
David Garciad41dbd62020-12-10 12:52:52 +01001707 db_vnfds.append(vnfd)
quilesj7e13aeb2019-10-08 13:34:55 +02001708
1709 # Get or generates the _admin.deployed.VCA list
tiernoe4f7e6c2018-11-27 14:55:30 +00001710 vca_deployed_list = None
1711 if db_nsr["_admin"].get("deployed"):
1712 vca_deployed_list = db_nsr["_admin"]["deployed"].get("VCA")
1713 if vca_deployed_list is None:
1714 vca_deployed_list = []
quilesj3655ae02019-12-12 16:08:35 +00001715 configuration_status_list = []
tiernoe4f7e6c2018-11-27 14:55:30 +00001716 db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
quilesj3655ae02019-12-12 16:08:35 +00001717 db_nsr_update["configurationStatus"] = configuration_status_list
quilesj7e13aeb2019-10-08 13:34:55 +02001718 # add _admin.deployed.VCA to db_nsr dictionary, value=vca_deployed_list
tierno98ad6ea2019-05-30 17:16:28 +00001719 populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
tiernoe4f7e6c2018-11-27 14:55:30 +00001720 elif isinstance(vca_deployed_list, dict):
1721 # maintain backward compatibility. Change a dict to list at database
1722 vca_deployed_list = list(vca_deployed_list.values())
1723 db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
tierno98ad6ea2019-05-30 17:16:28 +00001724 populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
tiernoe4f7e6c2018-11-27 14:55:30 +00001725
tierno6cf25f52019-09-12 09:33:40 +00001726 if not isinstance(deep_get(db_nsr, ("_admin", "deployed", "RO", "vnfd")), list):
tiernoa009e552019-01-30 16:45:44 +00001727 populate_dict(db_nsr, ("_admin", "deployed", "RO", "vnfd"), [])
1728 db_nsr_update["_admin.deployed.RO.vnfd"] = []
tierno59d22d22018-09-25 18:10:19 +02001729
tiernobaa51102018-12-14 13:16:18 +00001730 # set state to INSTANTIATED. When instantiated NBI will not delete directly
1731 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
1732 self.update_db_2("nsrs", nsr_id, db_nsr_update)
lloretgalleg6d488782020-07-22 10:13:46 +00001733 self.db.set_list("vnfrs", {"nsr-id-ref": nsr_id}, {"_admin.nsState": "INSTANTIATED"})
quilesj3655ae02019-12-12 16:08:35 +00001734
1735 # n2vc_redesign STEP 2 Deploy Network Scenario
tiernoe876f672020-02-13 14:34:48 +00001736 stage[0] = 'Stage 2/5: deployment of KDUs, VMs and execution environments.'
quilesj3655ae02019-12-12 16:08:35 +00001737 self._write_op_status(
1738 op_id=nslcmop_id,
tiernoe876f672020-02-13 14:34:48 +00001739 stage=stage
quilesj3655ae02019-12-12 16:08:35 +00001740 )
1741
tiernob5203912020-08-11 11:20:13 +00001742 stage[1] = "Deploying KDUs."
tiernoe876f672020-02-13 14:34:48 +00001743 # self.logger.debug(logging_text + "Before deploy_kdus")
calvinosanch9f9c6f22019-11-04 13:37:39 +01001744 # Call to deploy_kdus in case exists the "vdu:kdu" param
tiernoe876f672020-02-13 14:34:48 +00001745 await self.deploy_kdus(
1746 logging_text=logging_text,
1747 nsr_id=nsr_id,
1748 nslcmop_id=nslcmop_id,
1749 db_vnfrs=db_vnfrs,
1750 db_vnfds=db_vnfds,
1751 task_instantiation_info=tasks_dict_info,
calvinosanch9f9c6f22019-11-04 13:37:39 +01001752 )
tiernoe876f672020-02-13 14:34:48 +00001753
1754 stage[1] = "Getting VCA public key."
tiernod8323042019-08-09 11:32:23 +00001755 # n2vc_redesign STEP 1 Get VCA public ssh-key
1756 # feature 1429. Add n2vc public key to needed VMs
tierno3bedc9b2019-11-27 15:46:57 +00001757 n2vc_key = self.n2vc.get_public_key()
tiernoa5088192019-11-26 16:12:53 +00001758 n2vc_key_list = [n2vc_key]
1759 if self.vca_config.get("public_key"):
1760 n2vc_key_list.append(self.vca_config["public_key"])
tierno98ad6ea2019-05-30 17:16:28 +00001761
tiernoe876f672020-02-13 14:34:48 +00001762 stage[1] = "Deploying NS at VIM."
tiernod8323042019-08-09 11:32:23 +00001763 task_ro = asyncio.ensure_future(
quilesj7e13aeb2019-10-08 13:34:55 +02001764 self.instantiate_RO(
1765 logging_text=logging_text,
1766 nsr_id=nsr_id,
1767 nsd=nsd,
1768 db_nsr=db_nsr,
1769 db_nslcmop=db_nslcmop,
1770 db_vnfrs=db_vnfrs,
bravof922c4172020-11-24 21:21:43 -03001771 db_vnfds=db_vnfds,
tiernoe876f672020-02-13 14:34:48 +00001772 n2vc_key_list=n2vc_key_list,
1773 stage=stage
tierno98ad6ea2019-05-30 17:16:28 +00001774 )
tiernod8323042019-08-09 11:32:23 +00001775 )
1776 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "instantiate_RO", task_ro)
tiernoa2143262020-03-27 16:20:40 +00001777 tasks_dict_info[task_ro] = "Deploying at VIM"
tierno98ad6ea2019-05-30 17:16:28 +00001778
tiernod8323042019-08-09 11:32:23 +00001779 # n2vc_redesign STEP 3 to 6 Deploy N2VC
tiernoe876f672020-02-13 14:34:48 +00001780 stage[1] = "Deploying Execution Environments."
1781 self.logger.debug(logging_text + stage[1])
tierno98ad6ea2019-05-30 17:16:28 +00001782
tiernod8323042019-08-09 11:32:23 +00001783 nsi_id = None # TODO put nsi_id when this nsr belongs to a NSI
bravof922c4172020-11-24 21:21:43 -03001784 for vnf_profile in get_vnf_profiles(nsd):
1785 vnfd_id = vnf_profile["vnfd-id"]
1786 vnfd = find_in_list(db_vnfds, lambda a_vnf: a_vnf["id"] == vnfd_id)
1787 member_vnf_index = str(vnf_profile["id"])
tiernod8323042019-08-09 11:32:23 +00001788 db_vnfr = db_vnfrs[member_vnf_index]
1789 base_folder = vnfd["_admin"]["storage"]
1790 vdu_id = None
1791 vdu_index = 0
tierno98ad6ea2019-05-30 17:16:28 +00001792 vdu_name = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01001793 kdu_name = None
tierno59d22d22018-09-25 18:10:19 +02001794
tierno8a518872018-12-21 13:42:14 +00001795 # Get additional parameters
bravof922c4172020-11-24 21:21:43 -03001796 deploy_params = {"OSM": get_osm_params(db_vnfr)}
tiernod8323042019-08-09 11:32:23 +00001797 if db_vnfr.get("additionalParamsForVnf"):
bravof922c4172020-11-24 21:21:43 -03001798 deploy_params.update(parse_yaml_strings(db_vnfr["additionalParamsForVnf"].copy()))
tierno8a518872018-12-21 13:42:14 +00001799
bravofe5a31bc2021-02-17 19:09:12 -03001800 descriptor_config = get_configuration(vnfd, vnfd["id"])
tierno588547c2020-07-01 15:30:20 +00001801 if descriptor_config:
quilesj7e13aeb2019-10-08 13:34:55 +02001802 self._deploy_n2vc(
tiernoa54150d2019-12-05 17:15:10 +00001803 logging_text=logging_text + "member_vnf_index={} ".format(member_vnf_index),
quilesj7e13aeb2019-10-08 13:34:55 +02001804 db_nsr=db_nsr,
1805 db_vnfr=db_vnfr,
1806 nslcmop_id=nslcmop_id,
1807 nsr_id=nsr_id,
1808 nsi_id=nsi_id,
1809 vnfd_id=vnfd_id,
1810 vdu_id=vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01001811 kdu_name=kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02001812 member_vnf_index=member_vnf_index,
1813 vdu_index=vdu_index,
1814 vdu_name=vdu_name,
1815 deploy_params=deploy_params,
1816 descriptor_config=descriptor_config,
1817 base_folder=base_folder,
tiernoe876f672020-02-13 14:34:48 +00001818 task_instantiation_info=tasks_dict_info,
1819 stage=stage
quilesj7e13aeb2019-10-08 13:34:55 +02001820 )
tierno59d22d22018-09-25 18:10:19 +02001821
1822 # Deploy charms for each VDU that supports one.
bravof922c4172020-11-24 21:21:43 -03001823 for vdud in get_vdu_list(vnfd):
tiernod8323042019-08-09 11:32:23 +00001824 vdu_id = vdud["id"]
bravofe5a31bc2021-02-17 19:09:12 -03001825 descriptor_config = get_configuration(vnfd, vdu_id)
bravof922c4172020-11-24 21:21:43 -03001826 vdur = find_in_list(db_vnfr["vdur"], lambda vdu: vdu["vdu-id-ref"] == vdu_id)
1827
tierno626e0152019-11-29 14:16:16 +00001828 if vdur.get("additionalParams"):
bravof922c4172020-11-24 21:21:43 -03001829 deploy_params_vdu = parse_yaml_strings(vdur["additionalParams"])
tierno626e0152019-11-29 14:16:16 +00001830 else:
1831 deploy_params_vdu = deploy_params
bravof922c4172020-11-24 21:21:43 -03001832 deploy_params_vdu["OSM"] = get_osm_params(db_vnfr, vdu_id, vdu_count_index=0)
1833 vdud_count = get_vdu_profile(vnfd, vdu_id).get("max-number-of-instances", 1)
1834
1835 self.logger.debug("VDUD > {}".format(vdud))
1836 self.logger.debug("Descriptor config > {}".format(descriptor_config))
tierno588547c2020-07-01 15:30:20 +00001837 if descriptor_config:
tiernod8323042019-08-09 11:32:23 +00001838 vdu_name = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01001839 kdu_name = None
bravof922c4172020-11-24 21:21:43 -03001840 for vdu_index in range(vdud_count):
tiernod8323042019-08-09 11:32:23 +00001841 # TODO vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
quilesj7e13aeb2019-10-08 13:34:55 +02001842 self._deploy_n2vc(
tiernoa54150d2019-12-05 17:15:10 +00001843 logging_text=logging_text + "member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
1844 member_vnf_index, vdu_id, vdu_index),
quilesj7e13aeb2019-10-08 13:34:55 +02001845 db_nsr=db_nsr,
1846 db_vnfr=db_vnfr,
1847 nslcmop_id=nslcmop_id,
1848 nsr_id=nsr_id,
1849 nsi_id=nsi_id,
1850 vnfd_id=vnfd_id,
1851 vdu_id=vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01001852 kdu_name=kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02001853 member_vnf_index=member_vnf_index,
1854 vdu_index=vdu_index,
1855 vdu_name=vdu_name,
tierno626e0152019-11-29 14:16:16 +00001856 deploy_params=deploy_params_vdu,
quilesj7e13aeb2019-10-08 13:34:55 +02001857 descriptor_config=descriptor_config,
1858 base_folder=base_folder,
tierno8e2fae72020-04-01 15:21:15 +00001859 task_instantiation_info=tasks_dict_info,
1860 stage=stage
quilesj7e13aeb2019-10-08 13:34:55 +02001861 )
bravof922c4172020-11-24 21:21:43 -03001862 for kdud in get_kdu_list(vnfd):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001863 kdu_name = kdud["name"]
bravofe5a31bc2021-02-17 19:09:12 -03001864 descriptor_config = get_configuration(vnfd, kdu_name)
tierno588547c2020-07-01 15:30:20 +00001865 if descriptor_config:
calvinosanch9f9c6f22019-11-04 13:37:39 +01001866 vdu_id = None
1867 vdu_index = 0
1868 vdu_name = None
tierno72ef84f2020-10-06 08:22:07 +00001869 kdur = next(x for x in db_vnfr["kdur"] if x["kdu-name"] == kdu_name)
bravof922c4172020-11-24 21:21:43 -03001870 deploy_params_kdu = {"OSM": get_osm_params(db_vnfr)}
tierno72ef84f2020-10-06 08:22:07 +00001871 if kdur.get("additionalParams"):
bravof922c4172020-11-24 21:21:43 -03001872 deploy_params_kdu = parse_yaml_strings(kdur["additionalParams"])
tierno59d22d22018-09-25 18:10:19 +02001873
calvinosanch9f9c6f22019-11-04 13:37:39 +01001874 self._deploy_n2vc(
1875 logging_text=logging_text,
1876 db_nsr=db_nsr,
1877 db_vnfr=db_vnfr,
1878 nslcmop_id=nslcmop_id,
1879 nsr_id=nsr_id,
1880 nsi_id=nsi_id,
1881 vnfd_id=vnfd_id,
1882 vdu_id=vdu_id,
1883 kdu_name=kdu_name,
1884 member_vnf_index=member_vnf_index,
1885 vdu_index=vdu_index,
1886 vdu_name=vdu_name,
tierno72ef84f2020-10-06 08:22:07 +00001887 deploy_params=deploy_params_kdu,
calvinosanch9f9c6f22019-11-04 13:37:39 +01001888 descriptor_config=descriptor_config,
1889 base_folder=base_folder,
tierno8e2fae72020-04-01 15:21:15 +00001890 task_instantiation_info=tasks_dict_info,
1891 stage=stage
calvinosanch9f9c6f22019-11-04 13:37:39 +01001892 )
tierno59d22d22018-09-25 18:10:19 +02001893
tierno1b633412019-02-25 16:48:23 +00001894 # Check if this NS has a charm configuration
tiernod8323042019-08-09 11:32:23 +00001895 descriptor_config = nsd.get("ns-configuration")
1896 if descriptor_config and descriptor_config.get("juju"):
1897 vnfd_id = None
1898 db_vnfr = None
1899 member_vnf_index = None
1900 vdu_id = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01001901 kdu_name = None
tiernod8323042019-08-09 11:32:23 +00001902 vdu_index = 0
1903 vdu_name = None
tierno1b633412019-02-25 16:48:23 +00001904
tiernod8323042019-08-09 11:32:23 +00001905 # Get additional parameters
David Garcia40603572020-12-10 20:10:53 +01001906 deploy_params = {"OSM": {"vim_account_id": ns_params["vimAccountId"]}}
tiernod8323042019-08-09 11:32:23 +00001907 if db_nsr.get("additionalParamsForNs"):
bravof922c4172020-11-24 21:21:43 -03001908 deploy_params.update(parse_yaml_strings(db_nsr["additionalParamsForNs"].copy()))
tiernod8323042019-08-09 11:32:23 +00001909 base_folder = nsd["_admin"]["storage"]
quilesj7e13aeb2019-10-08 13:34:55 +02001910 self._deploy_n2vc(
1911 logging_text=logging_text,
1912 db_nsr=db_nsr,
1913 db_vnfr=db_vnfr,
1914 nslcmop_id=nslcmop_id,
1915 nsr_id=nsr_id,
1916 nsi_id=nsi_id,
1917 vnfd_id=vnfd_id,
1918 vdu_id=vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01001919 kdu_name=kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02001920 member_vnf_index=member_vnf_index,
1921 vdu_index=vdu_index,
1922 vdu_name=vdu_name,
1923 deploy_params=deploy_params,
1924 descriptor_config=descriptor_config,
1925 base_folder=base_folder,
tierno8e2fae72020-04-01 15:21:15 +00001926 task_instantiation_info=tasks_dict_info,
1927 stage=stage
quilesj7e13aeb2019-10-08 13:34:55 +02001928 )
tierno1b633412019-02-25 16:48:23 +00001929
tiernoe876f672020-02-13 14:34:48 +00001930 # rest of staff will be done at finally
tierno1b633412019-02-25 16:48:23 +00001931
tiernoe876f672020-02-13 14:34:48 +00001932 except (ROclient.ROClientException, DbException, LcmException, N2VCException) as e:
1933 self.logger.error(logging_text + "Exit Exception while '{}': {}".format(stage[1], e))
tierno59d22d22018-09-25 18:10:19 +02001934 exc = e
1935 except asyncio.CancelledError:
tiernoe876f672020-02-13 14:34:48 +00001936 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(stage[1]))
tierno59d22d22018-09-25 18:10:19 +02001937 exc = "Operation was cancelled"
1938 except Exception as e:
1939 exc = traceback.format_exc()
tiernoe876f672020-02-13 14:34:48 +00001940 self.logger.critical(logging_text + "Exit Exception while '{}': {}".format(stage[1], e), exc_info=True)
tierno59d22d22018-09-25 18:10:19 +02001941 finally:
1942 if exc:
tiernoe876f672020-02-13 14:34:48 +00001943 error_list.append(str(exc))
tiernobaa51102018-12-14 13:16:18 +00001944 try:
tiernoe876f672020-02-13 14:34:48 +00001945 # wait for pending tasks
1946 if tasks_dict_info:
1947 stage[1] = "Waiting for instantiate pending tasks."
1948 self.logger.debug(logging_text + stage[1])
1949 error_list += await self._wait_for_tasks(logging_text, tasks_dict_info, timeout_ns_deploy,
1950 stage, nslcmop_id, nsr_id=nsr_id)
1951 stage[1] = stage[2] = ""
1952 except asyncio.CancelledError:
1953 error_list.append("Cancelled")
1954 # TODO cancel all tasks
1955 except Exception as exc:
1956 error_list.append(str(exc))
quilesj4cda56b2019-12-05 10:02:20 +00001957
tiernoe876f672020-02-13 14:34:48 +00001958 # update operation-status
1959 db_nsr_update["operational-status"] = "running"
1960 # let's begin with VCA 'configured' status (later we can change it)
1961 db_nsr_update["config-status"] = "configured"
1962 for task, task_name in tasks_dict_info.items():
1963 if not task.done() or task.cancelled() or task.exception():
1964 if task_name.startswith(self.task_name_deploy_vca):
1965 # A N2VC task is pending
1966 db_nsr_update["config-status"] = "failed"
quilesj4cda56b2019-12-05 10:02:20 +00001967 else:
tiernoe876f672020-02-13 14:34:48 +00001968 # RO or KDU task is pending
1969 db_nsr_update["operational-status"] = "failed"
quilesj3655ae02019-12-12 16:08:35 +00001970
tiernoe876f672020-02-13 14:34:48 +00001971 # update status at database
1972 if error_list:
tiernoa2143262020-03-27 16:20:40 +00001973 error_detail = ". ".join(error_list)
tiernoe876f672020-02-13 14:34:48 +00001974 self.logger.error(logging_text + error_detail)
tiernob5203912020-08-11 11:20:13 +00001975 error_description_nslcmop = '{} Detail: {}'.format(stage[0], error_detail)
1976 error_description_nsr = 'Operation: INSTANTIATING.{}, {}'.format(nslcmop_id, stage[0])
quilesj3655ae02019-12-12 16:08:35 +00001977
tiernoa2143262020-03-27 16:20:40 +00001978 db_nsr_update["detailed-status"] = error_description_nsr + " Detail: " + error_detail
tiernoe876f672020-02-13 14:34:48 +00001979 db_nslcmop_update["detailed-status"] = error_detail
1980 nslcmop_operation_state = "FAILED"
1981 ns_state = "BROKEN"
1982 else:
tiernoa2143262020-03-27 16:20:40 +00001983 error_detail = None
tiernoe876f672020-02-13 14:34:48 +00001984 error_description_nsr = error_description_nslcmop = None
1985 ns_state = "READY"
1986 db_nsr_update["detailed-status"] = "Done"
1987 db_nslcmop_update["detailed-status"] = "Done"
1988 nslcmop_operation_state = "COMPLETED"
quilesj4cda56b2019-12-05 10:02:20 +00001989
tiernoe876f672020-02-13 14:34:48 +00001990 if db_nsr:
1991 self._write_ns_status(
1992 nsr_id=nsr_id,
1993 ns_state=ns_state,
1994 current_operation="IDLE",
1995 current_operation_id=None,
1996 error_description=error_description_nsr,
tiernoa2143262020-03-27 16:20:40 +00001997 error_detail=error_detail,
tiernoe876f672020-02-13 14:34:48 +00001998 other_update=db_nsr_update
1999 )
tiernoa17d4f42020-04-28 09:59:23 +00002000 self._write_op_status(
2001 op_id=nslcmop_id,
2002 stage="",
2003 error_message=error_description_nslcmop,
2004 operation_state=nslcmop_operation_state,
2005 other_update=db_nslcmop_update,
2006 )
quilesj3655ae02019-12-12 16:08:35 +00002007
tierno59d22d22018-09-25 18:10:19 +02002008 if nslcmop_operation_state:
2009 try:
2010 await self.msg.aiowrite("ns", "instantiated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
tierno8a518872018-12-21 13:42:14 +00002011 "operationState": nslcmop_operation_state},
2012 loop=self.loop)
tierno59d22d22018-09-25 18:10:19 +02002013 except Exception as e:
2014 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
2015
2016 self.logger.debug(logging_text + "Exit")
2017 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_instantiate")
2018
tierno588547c2020-07-01 15:30:20 +00002019 async def _add_vca_relations(self, logging_text, nsr_id, vca_index: int,
2020 timeout: int = 3600, vca_type: str = None) -> bool:
quilesj63f90042020-01-17 09:53:55 +00002021
2022 # steps:
2023 # 1. find all relations for this VCA
2024 # 2. wait for other peers related
2025 # 3. add relations
2026
2027 try:
tierno588547c2020-07-01 15:30:20 +00002028 vca_type = vca_type or "lxc_proxy_charm"
quilesj63f90042020-01-17 09:53:55 +00002029
2030 # STEP 1: find all relations for this VCA
2031
2032 # read nsr record
2033 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
David Garcia171f3542020-05-21 16:41:07 +02002034 nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
quilesj63f90042020-01-17 09:53:55 +00002035
2036 # this VCA data
2037 my_vca = deep_get(db_nsr, ('_admin', 'deployed', 'VCA'))[vca_index]
2038
2039 # read all ns-configuration relations
2040 ns_relations = list()
David Garcia171f3542020-05-21 16:41:07 +02002041 db_ns_relations = deep_get(nsd, ('ns-configuration', 'relation'))
quilesj63f90042020-01-17 09:53:55 +00002042 if db_ns_relations:
2043 for r in db_ns_relations:
2044 # check if this VCA is in the relation
2045 if my_vca.get('member-vnf-index') in\
2046 (r.get('entities')[0].get('id'), r.get('entities')[1].get('id')):
2047 ns_relations.append(r)
2048
2049 # read all vnf-configuration relations
2050 vnf_relations = list()
2051 db_vnfd_list = db_nsr.get('vnfd-id')
2052 if db_vnfd_list:
2053 for vnfd in db_vnfd_list:
2054 db_vnfd = self.db.get_one("vnfds", {"_id": vnfd})
bravofe5a31bc2021-02-17 19:09:12 -03002055 db_vnf_relations = get_configuration(db_vnfd, db_vnfd["id"]).get("relation", [])
quilesj63f90042020-01-17 09:53:55 +00002056 if db_vnf_relations:
2057 for r in db_vnf_relations:
2058 # check if this VCA is in the relation
2059 if my_vca.get('vdu_id') in (r.get('entities')[0].get('id'), r.get('entities')[1].get('id')):
2060 vnf_relations.append(r)
2061
2062 # if no relations, terminate
2063 if not ns_relations and not vnf_relations:
2064 self.logger.debug(logging_text + ' No relations')
2065 return True
2066
2067 self.logger.debug(logging_text + ' adding relations\n {}\n {}'.format(ns_relations, vnf_relations))
2068
2069 # add all relations
2070 start = time()
2071 while True:
2072 # check timeout
2073 now = time()
2074 if now - start >= timeout:
2075 self.logger.error(logging_text + ' : timeout adding relations')
2076 return False
2077
2078 # reload nsr from database (we need to update record: _admin.deloyed.VCA)
2079 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2080
2081 # for each defined NS relation, find the VCA's related
tierno364c4572020-09-14 12:11:32 +00002082 for r in ns_relations.copy():
quilesj63f90042020-01-17 09:53:55 +00002083 from_vca_ee_id = None
2084 to_vca_ee_id = None
2085 from_vca_endpoint = None
2086 to_vca_endpoint = None
2087 vca_list = deep_get(db_nsr, ('_admin', 'deployed', 'VCA'))
2088 for vca in vca_list:
2089 if vca.get('member-vnf-index') == r.get('entities')[0].get('id') \
2090 and vca.get('config_sw_installed'):
2091 from_vca_ee_id = vca.get('ee_id')
2092 from_vca_endpoint = r.get('entities')[0].get('endpoint')
2093 if vca.get('member-vnf-index') == r.get('entities')[1].get('id') \
2094 and vca.get('config_sw_installed'):
2095 to_vca_ee_id = vca.get('ee_id')
2096 to_vca_endpoint = r.get('entities')[1].get('endpoint')
2097 if from_vca_ee_id and to_vca_ee_id:
2098 # add relation
tierno588547c2020-07-01 15:30:20 +00002099 await self.vca_map[vca_type].add_relation(
quilesj63f90042020-01-17 09:53:55 +00002100 ee_id_1=from_vca_ee_id,
2101 ee_id_2=to_vca_ee_id,
2102 endpoint_1=from_vca_endpoint,
2103 endpoint_2=to_vca_endpoint)
2104 # remove entry from relations list
2105 ns_relations.remove(r)
2106 else:
2107 # check failed peers
2108 try:
2109 vca_status_list = db_nsr.get('configurationStatus')
2110 if vca_status_list:
2111 for i in range(len(vca_list)):
2112 vca = vca_list[i]
2113 vca_status = vca_status_list[i]
2114 if vca.get('member-vnf-index') == r.get('entities')[0].get('id'):
2115 if vca_status.get('status') == 'BROKEN':
2116 # peer broken: remove relation from list
2117 ns_relations.remove(r)
2118 if vca.get('member-vnf-index') == r.get('entities')[1].get('id'):
2119 if vca_status.get('status') == 'BROKEN':
2120 # peer broken: remove relation from list
2121 ns_relations.remove(r)
2122 except Exception:
2123 # ignore
2124 pass
2125
2126 # for each defined VNF relation, find the VCA's related
tierno364c4572020-09-14 12:11:32 +00002127 for r in vnf_relations.copy():
quilesj63f90042020-01-17 09:53:55 +00002128 from_vca_ee_id = None
2129 to_vca_ee_id = None
2130 from_vca_endpoint = None
2131 to_vca_endpoint = None
2132 vca_list = deep_get(db_nsr, ('_admin', 'deployed', 'VCA'))
2133 for vca in vca_list:
David Garcia97be6832020-09-09 15:40:44 +02002134 key_to_check = "vdu_id"
2135 if vca.get("vdu_id") is None:
2136 key_to_check = "vnfd_id"
2137 if vca.get(key_to_check) == r.get('entities')[0].get('id') and vca.get('config_sw_installed'):
quilesj63f90042020-01-17 09:53:55 +00002138 from_vca_ee_id = vca.get('ee_id')
2139 from_vca_endpoint = r.get('entities')[0].get('endpoint')
David Garcia97be6832020-09-09 15:40:44 +02002140 if vca.get(key_to_check) == r.get('entities')[1].get('id') and vca.get('config_sw_installed'):
quilesj63f90042020-01-17 09:53:55 +00002141 to_vca_ee_id = vca.get('ee_id')
2142 to_vca_endpoint = r.get('entities')[1].get('endpoint')
2143 if from_vca_ee_id and to_vca_ee_id:
2144 # add relation
tierno588547c2020-07-01 15:30:20 +00002145 await self.vca_map[vca_type].add_relation(
quilesj63f90042020-01-17 09:53:55 +00002146 ee_id_1=from_vca_ee_id,
2147 ee_id_2=to_vca_ee_id,
2148 endpoint_1=from_vca_endpoint,
2149 endpoint_2=to_vca_endpoint)
2150 # remove entry from relations list
2151 vnf_relations.remove(r)
2152 else:
2153 # check failed peers
2154 try:
2155 vca_status_list = db_nsr.get('configurationStatus')
2156 if vca_status_list:
2157 for i in range(len(vca_list)):
2158 vca = vca_list[i]
2159 vca_status = vca_status_list[i]
2160 if vca.get('vdu_id') == r.get('entities')[0].get('id'):
2161 if vca_status.get('status') == 'BROKEN':
2162 # peer broken: remove relation from list
David Garcia092afbd2020-08-25 13:17:25 +02002163 vnf_relations.remove(r)
quilesj63f90042020-01-17 09:53:55 +00002164 if vca.get('vdu_id') == r.get('entities')[1].get('id'):
2165 if vca_status.get('status') == 'BROKEN':
2166 # peer broken: remove relation from list
David Garcia092afbd2020-08-25 13:17:25 +02002167 vnf_relations.remove(r)
quilesj63f90042020-01-17 09:53:55 +00002168 except Exception:
2169 # ignore
2170 pass
2171
2172 # wait for next try
2173 await asyncio.sleep(5.0)
2174
2175 if not ns_relations and not vnf_relations:
2176 self.logger.debug('Relations added')
2177 break
2178
2179 return True
2180
2181 except Exception as e:
2182 self.logger.warn(logging_text + ' ERROR adding relations: {}'.format(e))
2183 return False
2184
tierno7ecbc342020-09-21 14:05:39 +00002185 async def _install_kdu(self, nsr_id: str, nsr_db_path: str, vnfr_data: dict, kdu_index: int, kdud: dict,
lloretgalleg7c121132020-07-08 07:53:22 +00002186 vnfd: dict, k8s_instance_info: dict, k8params: dict = None, timeout: int = 600):
2187
tiernob9018152020-04-16 14:18:24 +00002188 try:
lloretgalleg7c121132020-07-08 07:53:22 +00002189 k8sclustertype = k8s_instance_info["k8scluster-type"]
2190 # Instantiate kdu
2191 db_dict_install = {"collection": "nsrs",
2192 "filter": {"_id": nsr_id},
2193 "path": nsr_db_path}
2194
2195 kdu_instance = await self.k8scluster_map[k8sclustertype].install(
2196 cluster_uuid=k8s_instance_info["k8scluster-uuid"],
2197 kdu_model=k8s_instance_info["kdu-model"],
2198 atomic=True,
2199 params=k8params,
2200 db_dict=db_dict_install,
2201 timeout=timeout,
2202 kdu_name=k8s_instance_info["kdu-name"],
2203 namespace=k8s_instance_info["namespace"])
2204 self.update_db_2("nsrs", nsr_id, {nsr_db_path + ".kdu-instance": kdu_instance})
2205
2206 # Obtain services to obtain management service ip
2207 services = await self.k8scluster_map[k8sclustertype].get_services(
2208 cluster_uuid=k8s_instance_info["k8scluster-uuid"],
2209 kdu_instance=kdu_instance,
2210 namespace=k8s_instance_info["namespace"])
2211
2212 # Obtain management service info (if exists)
tierno7ecbc342020-09-21 14:05:39 +00002213 vnfr_update_dict = {}
lloretgalleg7c121132020-07-08 07:53:22 +00002214 if services:
tierno7ecbc342020-09-21 14:05:39 +00002215 vnfr_update_dict["kdur.{}.services".format(kdu_index)] = services
lloretgalleg7c121132020-07-08 07:53:22 +00002216 mgmt_services = [service for service in kdud.get("service", []) if service.get("mgmt-service")]
2217 for mgmt_service in mgmt_services:
2218 for service in services:
2219 if service["name"].startswith(mgmt_service["name"]):
2220 # Mgmt service found, Obtain service ip
2221 ip = service.get("external_ip", service.get("cluster_ip"))
2222 if isinstance(ip, list) and len(ip) == 1:
2223 ip = ip[0]
2224
2225 vnfr_update_dict["kdur.{}.ip-address".format(kdu_index)] = ip
2226
2227 # Check if must update also mgmt ip at the vnf
2228 service_external_cp = mgmt_service.get("external-connection-point-ref")
2229 if service_external_cp:
2230 if deep_get(vnfd, ("mgmt-interface", "cp")) == service_external_cp:
2231 vnfr_update_dict["ip-address"] = ip
2232
2233 break
2234 else:
2235 self.logger.warn("Mgmt service name: {} not found".format(mgmt_service["name"]))
2236
tierno7ecbc342020-09-21 14:05:39 +00002237 vnfr_update_dict["kdur.{}.status".format(kdu_index)] = "READY"
2238 self.update_db_2("vnfrs", vnfr_data.get("_id"), vnfr_update_dict)
lloretgalleg7c121132020-07-08 07:53:22 +00002239
Dominik Fleischmannc1975dd2020-08-19 12:17:51 +02002240 kdu_config = kdud.get("kdu-configuration")
2241 if kdu_config and kdu_config.get("initial-config-primitive") and kdu_config.get("juju") is None:
2242 initial_config_primitive_list = kdu_config.get("initial-config-primitive")
2243 initial_config_primitive_list.sort(key=lambda val: int(val["seq"]))
2244
2245 for initial_config_primitive in initial_config_primitive_list:
2246 primitive_params_ = self._map_primitive_params(initial_config_primitive, {}, {})
2247
2248 await asyncio.wait_for(
2249 self.k8scluster_map[k8sclustertype].exec_primitive(
2250 cluster_uuid=k8s_instance_info["k8scluster-uuid"],
2251 kdu_instance=kdu_instance,
2252 primitive_name=initial_config_primitive["name"],
2253 params=primitive_params_, db_dict={}),
2254 timeout=timeout)
2255
tiernob9018152020-04-16 14:18:24 +00002256 except Exception as e:
lloretgalleg7c121132020-07-08 07:53:22 +00002257 # Prepare update db with error and raise exception
tiernob9018152020-04-16 14:18:24 +00002258 try:
lloretgalleg7c121132020-07-08 07:53:22 +00002259 self.update_db_2("nsrs", nsr_id, {nsr_db_path + ".detailed-status": str(e)})
tierno7ecbc342020-09-21 14:05:39 +00002260 self.update_db_2("vnfrs", vnfr_data.get("_id"), {"kdur.{}.status".format(kdu_index): "ERROR"})
tiernob9018152020-04-16 14:18:24 +00002261 except Exception:
lloretgalleg7c121132020-07-08 07:53:22 +00002262 # ignore to keep original exception
tiernob9018152020-04-16 14:18:24 +00002263 pass
lloretgalleg7c121132020-07-08 07:53:22 +00002264 # reraise original error
2265 raise
2266
2267 return kdu_instance
tiernob9018152020-04-16 14:18:24 +00002268
tiernoe876f672020-02-13 14:34:48 +00002269 async def deploy_kdus(self, logging_text, nsr_id, nslcmop_id, db_vnfrs, db_vnfds, task_instantiation_info):
calvinosanch9f9c6f22019-11-04 13:37:39 +01002270 # Launch kdus if present in the descriptor
tierno626e0152019-11-29 14:16:16 +00002271
lloretgalleg18ebc3a2020-10-22 09:54:51 +00002272 k8scluster_id_2_uuic = {"helm-chart-v3": {}, "helm-chart": {}, "juju-bundle": {}}
tierno626e0152019-11-29 14:16:16 +00002273
tierno16f4a4e2020-07-20 09:05:51 +00002274 async def _get_cluster_id(cluster_id, cluster_type):
tierno626e0152019-11-29 14:16:16 +00002275 nonlocal k8scluster_id_2_uuic
2276 if cluster_id in k8scluster_id_2_uuic[cluster_type]:
2277 return k8scluster_id_2_uuic[cluster_type][cluster_id]
2278
tierno16f4a4e2020-07-20 09:05:51 +00002279 # check if K8scluster is creating and wait look if previous tasks in process
2280 task_name, task_dependency = self.lcm_tasks.lookfor_related("k8scluster", cluster_id)
2281 if task_dependency:
2282 text = "Waiting for related tasks '{}' on k8scluster {} to be completed".format(task_name, cluster_id)
2283 self.logger.debug(logging_text + text)
2284 await asyncio.wait(task_dependency, timeout=3600)
2285
tierno626e0152019-11-29 14:16:16 +00002286 db_k8scluster = self.db.get_one("k8sclusters", {"_id": cluster_id}, fail_on_empty=False)
2287 if not db_k8scluster:
2288 raise LcmException("K8s cluster {} cannot be found".format(cluster_id))
tierno16f4a4e2020-07-20 09:05:51 +00002289
tierno626e0152019-11-29 14:16:16 +00002290 k8s_id = deep_get(db_k8scluster, ("_admin", cluster_type, "id"))
2291 if not k8s_id:
lloretgalleg18ebc3a2020-10-22 09:54:51 +00002292 if cluster_type == "helm-chart-v3":
2293 try:
2294 # backward compatibility for existing clusters that have not been initialized for helm v3
2295 k8s_credentials = yaml.safe_dump(db_k8scluster.get("credentials"))
2296 k8s_id, uninstall_sw = await self.k8sclusterhelm3.init_env(k8s_credentials,
2297 reuse_cluster_uuid=cluster_id)
2298 db_k8scluster_update = {}
2299 db_k8scluster_update["_admin.helm-chart-v3.error_msg"] = None
2300 db_k8scluster_update["_admin.helm-chart-v3.id"] = k8s_id
2301 db_k8scluster_update["_admin.helm-chart-v3.created"] = uninstall_sw
2302 db_k8scluster_update["_admin.helm-chart-v3.operationalState"] = "ENABLED"
2303 self.update_db_2("k8sclusters", cluster_id, db_k8scluster_update)
2304 except Exception as e:
2305 self.logger.error(logging_text + "error initializing helm-v3 cluster: {}".format(str(e)))
2306 raise LcmException("K8s cluster '{}' has not been initialized for '{}'".format(cluster_id,
2307 cluster_type))
2308 else:
2309 raise LcmException("K8s cluster '{}' has not been initialized for '{}'".
2310 format(cluster_id, cluster_type))
tierno626e0152019-11-29 14:16:16 +00002311 k8scluster_id_2_uuic[cluster_type][cluster_id] = k8s_id
2312 return k8s_id
2313
2314 logging_text += "Deploy kdus: "
tiernoe876f672020-02-13 14:34:48 +00002315 step = ""
calvinosanch9f9c6f22019-11-04 13:37:39 +01002316 try:
tierno626e0152019-11-29 14:16:16 +00002317 db_nsr_update = {"_admin.deployed.K8s": []}
calvinosanch9f9c6f22019-11-04 13:37:39 +01002318 self.update_db_2("nsrs", nsr_id, db_nsr_update)
calvinosanch9f9c6f22019-11-04 13:37:39 +01002319
tierno626e0152019-11-29 14:16:16 +00002320 index = 0
tiernoe876f672020-02-13 14:34:48 +00002321 updated_cluster_list = []
lloretgalleg18ebc3a2020-10-22 09:54:51 +00002322 updated_v3_cluster_list = []
tiernoe876f672020-02-13 14:34:48 +00002323
tierno626e0152019-11-29 14:16:16 +00002324 for vnfr_data in db_vnfrs.values():
lloretgalleg7c121132020-07-08 07:53:22 +00002325 for kdu_index, kdur in enumerate(get_iterable(vnfr_data, "kdur")):
2326 # Step 0: Prepare and set parameters
bravof922c4172020-11-24 21:21:43 -03002327 desc_params = parse_yaml_strings(kdur.get("additionalParams"))
quilesjacde94f2020-01-23 10:07:08 +00002328 vnfd_id = vnfr_data.get('vnfd-id')
David Garciad41dbd62020-12-10 12:52:52 +01002329 vnfd_with_id = find_in_list(db_vnfds, lambda vnfd: vnfd["_id"] == vnfd_id)
2330 kdud = next(kdud for kdud in vnfd_with_id["kdu"] if kdud["name"] == kdur["kdu-name"])
tiernode1584f2020-04-07 09:07:33 +00002331 namespace = kdur.get("k8s-namespace")
tierno626e0152019-11-29 14:16:16 +00002332 if kdur.get("helm-chart"):
lloretgalleg07e53f52020-12-15 10:54:02 +00002333 kdumodel = kdur["helm-chart"]
lloretgalleg18ebc3a2020-10-22 09:54:51 +00002334 # Default version: helm3, if helm-version is v2 assign v2
2335 k8sclustertype = "helm-chart-v3"
2336 self.logger.debug("kdur: {}".format(kdur))
2337 if kdur.get("helm-version") and kdur.get("helm-version") == "v2":
2338 k8sclustertype = "helm-chart"
tierno626e0152019-11-29 14:16:16 +00002339 elif kdur.get("juju-bundle"):
lloretgalleg07e53f52020-12-15 10:54:02 +00002340 kdumodel = kdur["juju-bundle"]
tiernoe876f672020-02-13 14:34:48 +00002341 k8sclustertype = "juju-bundle"
tierno626e0152019-11-29 14:16:16 +00002342 else:
tiernoe876f672020-02-13 14:34:48 +00002343 raise LcmException("kdu type for kdu='{}.{}' is neither helm-chart nor "
2344 "juju-bundle. Maybe an old NBI version is running".
2345 format(vnfr_data["member-vnf-index-ref"], kdur["kdu-name"]))
quilesjacde94f2020-01-23 10:07:08 +00002346 # check if kdumodel is a file and exists
2347 try:
David Garciad41dbd62020-12-10 12:52:52 +01002348 vnfd_with_id = find_in_list(db_vnfds, lambda vnfd: vnfd["_id"] == vnfd_id)
2349 storage = deep_get(vnfd_with_id, ('_admin', 'storage'))
tierno51183952020-04-03 15:48:18 +00002350 if storage and storage.get('pkg-dir'): # may be not present if vnfd has not artifacts
2351 # path format: /vnfdid/pkkdir/helm-charts|juju-bundles/kdumodel
Dominik Fleischmann010c0e72020-05-18 15:19:11 +02002352 filename = '{}/{}/{}s/{}'.format(storage["folder"], storage["pkg-dir"], k8sclustertype,
tierno51183952020-04-03 15:48:18 +00002353 kdumodel)
2354 if self.fs.file_exists(filename, mode='file') or self.fs.file_exists(filename, mode='dir'):
2355 kdumodel = self.fs.path + filename
2356 except (asyncio.TimeoutError, asyncio.CancelledError):
tiernoe876f672020-02-13 14:34:48 +00002357 raise
2358 except Exception: # it is not a file
quilesjacde94f2020-01-23 10:07:08 +00002359 pass
lloretgallegedc5f332020-02-20 11:50:50 +01002360
tiernoe876f672020-02-13 14:34:48 +00002361 k8s_cluster_id = kdur["k8s-cluster"]["id"]
2362 step = "Synchronize repos for k8s cluster '{}'".format(k8s_cluster_id)
tierno16f4a4e2020-07-20 09:05:51 +00002363 cluster_uuid = await _get_cluster_id(k8s_cluster_id, k8sclustertype)
lloretgallegedc5f332020-02-20 11:50:50 +01002364
lloretgalleg7c121132020-07-08 07:53:22 +00002365 # Synchronize repos
lloretgalleg18ebc3a2020-10-22 09:54:51 +00002366 if (k8sclustertype == "helm-chart" and cluster_uuid not in updated_cluster_list)\
2367 or (k8sclustertype == "helm-chart-v3" and cluster_uuid not in updated_v3_cluster_list):
tiernoe876f672020-02-13 14:34:48 +00002368 del_repo_list, added_repo_dict = await asyncio.ensure_future(
lloretgalleg18ebc3a2020-10-22 09:54:51 +00002369 self.k8scluster_map[k8sclustertype].synchronize_repos(cluster_uuid=cluster_uuid))
tiernoe876f672020-02-13 14:34:48 +00002370 if del_repo_list or added_repo_dict:
lloretgalleg18ebc3a2020-10-22 09:54:51 +00002371 if k8sclustertype == "helm-chart":
2372 unset = {'_admin.helm_charts_added.' + item: None for item in del_repo_list}
2373 updated = {'_admin.helm_charts_added.' +
2374 item: name for item, name in added_repo_dict.items()}
2375 updated_cluster_list.append(cluster_uuid)
2376 elif k8sclustertype == "helm-chart-v3":
2377 unset = {'_admin.helm_charts_v3_added.' + item: None for item in del_repo_list}
2378 updated = {'_admin.helm_charts_v3_added.' +
2379 item: name for item, name in added_repo_dict.items()}
2380 updated_v3_cluster_list.append(cluster_uuid)
2381 self.logger.debug(logging_text + "repos synchronized on k8s cluster "
2382 "'{}' to_delete: {}, to_add: {}".
2383 format(k8s_cluster_id, del_repo_list, added_repo_dict))
tiernoe876f672020-02-13 14:34:48 +00002384 self.db.set_one("k8sclusters", {"_id": k8s_cluster_id}, updated, unset=unset)
lloretgallegedc5f332020-02-20 11:50:50 +01002385
lloretgalleg7c121132020-07-08 07:53:22 +00002386 # Instantiate kdu
tiernoe876f672020-02-13 14:34:48 +00002387 step = "Instantiating KDU {}.{} in k8s cluster {}".format(vnfr_data["member-vnf-index-ref"],
2388 kdur["kdu-name"], k8s_cluster_id)
lloretgalleg7c121132020-07-08 07:53:22 +00002389 k8s_instance_info = {"kdu-instance": None,
2390 "k8scluster-uuid": cluster_uuid,
2391 "k8scluster-type": k8sclustertype,
2392 "member-vnf-index": vnfr_data["member-vnf-index-ref"],
2393 "kdu-name": kdur["kdu-name"],
2394 "kdu-model": kdumodel,
2395 "namespace": namespace}
tiernob9018152020-04-16 14:18:24 +00002396 db_path = "_admin.deployed.K8s.{}".format(index)
lloretgalleg7c121132020-07-08 07:53:22 +00002397 db_nsr_update[db_path] = k8s_instance_info
tierno626e0152019-11-29 14:16:16 +00002398 self.update_db_2("nsrs", nsr_id, db_nsr_update)
David Garciad41dbd62020-12-10 12:52:52 +01002399 vnfd_with_id = find_in_list(db_vnfds, lambda vnf: vnf["_id"] == vnfd_id)
tiernoa2143262020-03-27 16:20:40 +00002400 task = asyncio.ensure_future(
David Garciad41dbd62020-12-10 12:52:52 +01002401 self._install_kdu(nsr_id, db_path, vnfr_data, kdu_index, kdud, vnfd_with_id,
lloretgalleg7c121132020-07-08 07:53:22 +00002402 k8s_instance_info, k8params=desc_params, timeout=600))
tiernoe876f672020-02-13 14:34:48 +00002403 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "instantiate_KDU-{}".format(index), task)
tiernoa2143262020-03-27 16:20:40 +00002404 task_instantiation_info[task] = "Deploying KDU {}".format(kdur["kdu-name"])
tiernoe876f672020-02-13 14:34:48 +00002405
tierno626e0152019-11-29 14:16:16 +00002406 index += 1
quilesjdd799ac2020-01-23 16:31:11 +00002407
tiernoe876f672020-02-13 14:34:48 +00002408 except (LcmException, asyncio.CancelledError):
2409 raise
calvinosanch9f9c6f22019-11-04 13:37:39 +01002410 except Exception as e:
tiernoe876f672020-02-13 14:34:48 +00002411 msg = "Exception {} while {}: {}".format(type(e).__name__, step, e)
2412 if isinstance(e, (N2VCException, DbException)):
2413 self.logger.error(logging_text + msg)
2414 else:
2415 self.logger.critical(logging_text + msg, exc_info=True)
quilesjdd799ac2020-01-23 16:31:11 +00002416 raise LcmException(msg)
calvinosanch9f9c6f22019-11-04 13:37:39 +01002417 finally:
calvinosanch9f9c6f22019-11-04 13:37:39 +01002418 if db_nsr_update:
2419 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernoda6fb102019-11-23 00:36:52 +00002420
quilesj7e13aeb2019-10-08 13:34:55 +02002421 def _deploy_n2vc(self, logging_text, db_nsr, db_vnfr, nslcmop_id, nsr_id, nsi_id, vnfd_id, vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002422 kdu_name, member_vnf_index, vdu_index, vdu_name, deploy_params, descriptor_config,
tiernoe876f672020-02-13 14:34:48 +00002423 base_folder, task_instantiation_info, stage):
quilesj7e13aeb2019-10-08 13:34:55 +02002424 # launch instantiate_N2VC in a asyncio task and register task object
2425 # Look where information of this charm is at database <nsrs>._admin.deployed.VCA
2426 # if not found, create one entry and update database
quilesj7e13aeb2019-10-08 13:34:55 +02002427 # fill db_nsr._admin.deployed.VCA.<index>
tierno588547c2020-07-01 15:30:20 +00002428
2429 self.logger.debug(logging_text + "_deploy_n2vc vnfd_id={}, vdu_id={}".format(vnfd_id, vdu_id))
2430 if descriptor_config.get("juju"): # There is one execution envioronment of type juju
2431 ee_list = [descriptor_config]
2432 elif descriptor_config.get("execution-environment-list"):
2433 ee_list = descriptor_config.get("execution-environment-list")
2434 else: # other types as script are not supported
2435 ee_list = []
2436
2437 for ee_item in ee_list:
2438 self.logger.debug(logging_text + "_deploy_n2vc ee_item juju={}, helm={}".format(ee_item.get('juju'),
2439 ee_item.get("helm-chart")))
tiernoa278b842020-07-08 15:33:55 +00002440 ee_descriptor_id = ee_item.get("id")
tierno588547c2020-07-01 15:30:20 +00002441 if ee_item.get("juju"):
2442 vca_name = ee_item['juju'].get('charm')
2443 vca_type = "lxc_proxy_charm" if ee_item['juju'].get('charm') is not None else "native_charm"
2444 if ee_item['juju'].get('cloud') == "k8s":
2445 vca_type = "k8s_proxy_charm"
2446 elif ee_item['juju'].get('proxy') is False:
2447 vca_type = "native_charm"
2448 elif ee_item.get("helm-chart"):
2449 vca_name = ee_item['helm-chart']
lloretgalleg18ebc3a2020-10-22 09:54:51 +00002450 if ee_item.get("helm-version") and ee_item.get("helm-version") == "v2":
2451 vca_type = "helm"
2452 else:
2453 vca_type = "helm-v3"
tierno588547c2020-07-01 15:30:20 +00002454 else:
2455 self.logger.debug(logging_text + "skipping non juju neither charm configuration")
quilesj7e13aeb2019-10-08 13:34:55 +02002456 continue
quilesj3655ae02019-12-12 16:08:35 +00002457
tierno588547c2020-07-01 15:30:20 +00002458 vca_index = -1
2459 for vca_index, vca_deployed in enumerate(db_nsr["_admin"]["deployed"]["VCA"]):
2460 if not vca_deployed:
2461 continue
2462 if vca_deployed.get("member-vnf-index") == member_vnf_index and \
2463 vca_deployed.get("vdu_id") == vdu_id and \
2464 vca_deployed.get("kdu_name") == kdu_name and \
tiernoa278b842020-07-08 15:33:55 +00002465 vca_deployed.get("vdu_count_index", 0) == vdu_index and \
2466 vca_deployed.get("ee_descriptor_id") == ee_descriptor_id:
tierno588547c2020-07-01 15:30:20 +00002467 break
2468 else:
2469 # not found, create one.
tiernoa278b842020-07-08 15:33:55 +00002470 target = "ns" if not member_vnf_index else "vnf/{}".format(member_vnf_index)
2471 if vdu_id:
2472 target += "/vdu/{}/{}".format(vdu_id, vdu_index or 0)
2473 elif kdu_name:
2474 target += "/kdu/{}".format(kdu_name)
tierno588547c2020-07-01 15:30:20 +00002475 vca_deployed = {
tiernoa278b842020-07-08 15:33:55 +00002476 "target_element": target,
2477 # ^ target_element will replace member-vnf-index, kdu_name, vdu_id ... in a single string
tierno588547c2020-07-01 15:30:20 +00002478 "member-vnf-index": member_vnf_index,
2479 "vdu_id": vdu_id,
2480 "kdu_name": kdu_name,
2481 "vdu_count_index": vdu_index,
2482 "operational-status": "init", # TODO revise
2483 "detailed-status": "", # TODO revise
2484 "step": "initial-deploy", # TODO revise
2485 "vnfd_id": vnfd_id,
2486 "vdu_name": vdu_name,
tiernoa278b842020-07-08 15:33:55 +00002487 "type": vca_type,
2488 "ee_descriptor_id": ee_descriptor_id
tierno588547c2020-07-01 15:30:20 +00002489 }
2490 vca_index += 1
quilesj3655ae02019-12-12 16:08:35 +00002491
tierno588547c2020-07-01 15:30:20 +00002492 # create VCA and configurationStatus in db
2493 db_dict = {
2494 "_admin.deployed.VCA.{}".format(vca_index): vca_deployed,
2495 "configurationStatus.{}".format(vca_index): dict()
2496 }
2497 self.update_db_2("nsrs", nsr_id, db_dict)
quilesj7e13aeb2019-10-08 13:34:55 +02002498
tierno588547c2020-07-01 15:30:20 +00002499 db_nsr["_admin"]["deployed"]["VCA"].append(vca_deployed)
2500
bravof922c4172020-11-24 21:21:43 -03002501 self.logger.debug("N2VC > NSR_ID > {}".format(nsr_id))
2502 self.logger.debug("N2VC > DB_NSR > {}".format(db_nsr))
2503 self.logger.debug("N2VC > VCA_DEPLOYED > {}".format(vca_deployed))
2504
tierno588547c2020-07-01 15:30:20 +00002505 # Launch task
2506 task_n2vc = asyncio.ensure_future(
2507 self.instantiate_N2VC(
2508 logging_text=logging_text,
2509 vca_index=vca_index,
2510 nsi_id=nsi_id,
2511 db_nsr=db_nsr,
2512 db_vnfr=db_vnfr,
2513 vdu_id=vdu_id,
2514 kdu_name=kdu_name,
2515 vdu_index=vdu_index,
2516 deploy_params=deploy_params,
2517 config_descriptor=descriptor_config,
2518 base_folder=base_folder,
2519 nslcmop_id=nslcmop_id,
2520 stage=stage,
2521 vca_type=vca_type,
tiernob996d942020-07-03 14:52:28 +00002522 vca_name=vca_name,
2523 ee_config_descriptor=ee_item
tierno588547c2020-07-01 15:30:20 +00002524 )
quilesj7e13aeb2019-10-08 13:34:55 +02002525 )
tierno588547c2020-07-01 15:30:20 +00002526 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "instantiate_N2VC-{}".format(vca_index), task_n2vc)
2527 task_instantiation_info[task_n2vc] = self.task_name_deploy_vca + " {}.{}".format(
2528 member_vnf_index or "", vdu_id or "")
tiernobaa51102018-12-14 13:16:18 +00002529
tiernoc9556972019-07-05 15:25:25 +00002530 @staticmethod
kuuse0ca67472019-05-13 15:59:27 +02002531 def _create_nslcmop(nsr_id, operation, params):
2532 """
2533 Creates a ns-lcm-opp content to be stored at database.
2534 :param nsr_id: internal id of the instance
2535 :param operation: instantiate, terminate, scale, action, ...
2536 :param params: user parameters for the operation
2537 :return: dictionary following SOL005 format
2538 """
2539 # Raise exception if invalid arguments
2540 if not (nsr_id and operation and params):
2541 raise LcmException(
2542 "Parameters 'nsr_id', 'operation' and 'params' needed to create primitive not provided")
2543 now = time()
2544 _id = str(uuid4())
2545 nslcmop = {
2546 "id": _id,
2547 "_id": _id,
2548 # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2549 "operationState": "PROCESSING",
2550 "statusEnteredTime": now,
2551 "nsInstanceId": nsr_id,
2552 "lcmOperationType": operation,
2553 "startTime": now,
2554 "isAutomaticInvocation": False,
2555 "operationParams": params,
2556 "isCancelPending": False,
2557 "links": {
2558 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
2559 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
2560 }
2561 }
2562 return nslcmop
2563
calvinosanch9f9c6f22019-11-04 13:37:39 +01002564 def _format_additional_params(self, params):
tierno626e0152019-11-29 14:16:16 +00002565 params = params or {}
calvinosanch9f9c6f22019-11-04 13:37:39 +01002566 for key, value in params.items():
2567 if str(value).startswith("!!yaml "):
2568 params[key] = yaml.safe_load(value[7:])
calvinosanch9f9c6f22019-11-04 13:37:39 +01002569 return params
2570
kuuse8b998e42019-07-30 15:22:16 +02002571 def _get_terminate_primitive_params(self, seq, vnf_index):
2572 primitive = seq.get('name')
2573 primitive_params = {}
2574 params = {
2575 "member_vnf_index": vnf_index,
2576 "primitive": primitive,
2577 "primitive_params": primitive_params,
2578 }
2579 desc_params = {}
2580 return self._map_primitive_params(seq, params, desc_params)
2581
kuuseac3a8882019-10-03 10:48:06 +02002582 # sub-operations
2583
tierno51183952020-04-03 15:48:18 +00002584 def _retry_or_skip_suboperation(self, db_nslcmop, op_index):
2585 op = deep_get(db_nslcmop, ('_admin', 'operations'), [])[op_index]
2586 if op.get('operationState') == 'COMPLETED':
kuuseac3a8882019-10-03 10:48:06 +02002587 # b. Skip sub-operation
2588 # _ns_execute_primitive() or RO.create_action() will NOT be executed
2589 return self.SUBOPERATION_STATUS_SKIP
2590 else:
tierno7c4e24c2020-05-13 08:41:35 +00002591 # c. retry executing sub-operation
kuuseac3a8882019-10-03 10:48:06 +02002592 # The sub-operation exists, and operationState != 'COMPLETED'
tierno7c4e24c2020-05-13 08:41:35 +00002593 # Update operationState = 'PROCESSING' to indicate a retry.
kuuseac3a8882019-10-03 10:48:06 +02002594 operationState = 'PROCESSING'
2595 detailed_status = 'In progress'
2596 self._update_suboperation_status(
2597 db_nslcmop, op_index, operationState, detailed_status)
2598 # Return the sub-operation index
2599 # _ns_execute_primitive() or RO.create_action() will be called from scale()
2600 # with arguments extracted from the sub-operation
2601 return op_index
2602
2603 # Find a sub-operation where all keys in a matching dictionary must match
2604 # Returns the index of the matching sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if no match
2605 def _find_suboperation(self, db_nslcmop, match):
tierno7c4e24c2020-05-13 08:41:35 +00002606 if db_nslcmop and match:
kuuseac3a8882019-10-03 10:48:06 +02002607 op_list = db_nslcmop.get('_admin', {}).get('operations', [])
2608 for i, op in enumerate(op_list):
2609 if all(op.get(k) == match[k] for k in match):
2610 return i
2611 return self.SUBOPERATION_STATUS_NOT_FOUND
2612
2613 # Update status for a sub-operation given its index
2614 def _update_suboperation_status(self, db_nslcmop, op_index, operationState, detailed_status):
2615 # Update DB for HA tasks
2616 q_filter = {'_id': db_nslcmop['_id']}
2617 update_dict = {'_admin.operations.{}.operationState'.format(op_index): operationState,
2618 '_admin.operations.{}.detailed-status'.format(op_index): detailed_status}
2619 self.db.set_one("nslcmops",
2620 q_filter=q_filter,
2621 update_dict=update_dict,
2622 fail_on_empty=False)
2623
2624 # Add sub-operation, return the index of the added sub-operation
2625 # Optionally, set operationState, detailed-status, and operationType
2626 # Status and type are currently set for 'scale' sub-operations:
2627 # 'operationState' : 'PROCESSING' | 'COMPLETED' | 'FAILED'
2628 # 'detailed-status' : status message
2629 # 'operationType': may be any type, in the case of scaling: 'PRE-SCALE' | 'POST-SCALE'
2630 # Status and operation type are currently only used for 'scale', but NOT for 'terminate' sub-operations.
tierno2357f4e2020-10-19 16:38:59 +00002631 def _add_suboperation(self, db_nslcmop, vnf_index, vdu_id, vdu_count_index, vdu_name, primitive,
quilesj7e13aeb2019-10-08 13:34:55 +02002632 mapped_primitive_params, operationState=None, detailed_status=None, operationType=None,
kuuseac3a8882019-10-03 10:48:06 +02002633 RO_nsr_id=None, RO_scaling_info=None):
tiernoe876f672020-02-13 14:34:48 +00002634 if not db_nslcmop:
kuuseac3a8882019-10-03 10:48:06 +02002635 return self.SUBOPERATION_STATUS_NOT_FOUND
2636 # Get the "_admin.operations" list, if it exists
2637 db_nslcmop_admin = db_nslcmop.get('_admin', {})
2638 op_list = db_nslcmop_admin.get('operations')
2639 # Create or append to the "_admin.operations" list
kuuse8b998e42019-07-30 15:22:16 +02002640 new_op = {'member_vnf_index': vnf_index,
2641 'vdu_id': vdu_id,
2642 'vdu_count_index': vdu_count_index,
2643 'primitive': primitive,
2644 'primitive_params': mapped_primitive_params}
kuuseac3a8882019-10-03 10:48:06 +02002645 if operationState:
2646 new_op['operationState'] = operationState
2647 if detailed_status:
2648 new_op['detailed-status'] = detailed_status
2649 if operationType:
2650 new_op['lcmOperationType'] = operationType
2651 if RO_nsr_id:
2652 new_op['RO_nsr_id'] = RO_nsr_id
2653 if RO_scaling_info:
2654 new_op['RO_scaling_info'] = RO_scaling_info
2655 if not op_list:
2656 # No existing operations, create key 'operations' with current operation as first list element
2657 db_nslcmop_admin.update({'operations': [new_op]})
2658 op_list = db_nslcmop_admin.get('operations')
2659 else:
2660 # Existing operations, append operation to list
2661 op_list.append(new_op)
kuuse8b998e42019-07-30 15:22:16 +02002662
kuuseac3a8882019-10-03 10:48:06 +02002663 db_nslcmop_update = {'_admin.operations': op_list}
2664 self.update_db_2("nslcmops", db_nslcmop['_id'], db_nslcmop_update)
2665 op_index = len(op_list) - 1
2666 return op_index
2667
2668 # Helper methods for scale() sub-operations
2669
2670 # pre-scale/post-scale:
2671 # Check for 3 different cases:
2672 # a. New: First time execution, return SUBOPERATION_STATUS_NEW
2673 # b. Skip: Existing sub-operation exists, operationState == 'COMPLETED', return SUBOPERATION_STATUS_SKIP
tierno7c4e24c2020-05-13 08:41:35 +00002674 # c. retry: Existing sub-operation exists, operationState != 'COMPLETED', return op_index to re-execute
quilesj7e13aeb2019-10-08 13:34:55 +02002675 def _check_or_add_scale_suboperation(self, db_nslcmop, vnf_index, vnf_config_primitive, primitive_params,
2676 operationType, RO_nsr_id=None, RO_scaling_info=None):
kuuseac3a8882019-10-03 10:48:06 +02002677 # Find this sub-operation
tierno7c4e24c2020-05-13 08:41:35 +00002678 if RO_nsr_id and RO_scaling_info:
kuuseac3a8882019-10-03 10:48:06 +02002679 operationType = 'SCALE-RO'
2680 match = {
2681 'member_vnf_index': vnf_index,
2682 'RO_nsr_id': RO_nsr_id,
2683 'RO_scaling_info': RO_scaling_info,
2684 }
2685 else:
2686 match = {
2687 'member_vnf_index': vnf_index,
2688 'primitive': vnf_config_primitive,
2689 'primitive_params': primitive_params,
2690 'lcmOperationType': operationType
2691 }
2692 op_index = self._find_suboperation(db_nslcmop, match)
tierno51183952020-04-03 15:48:18 +00002693 if op_index == self.SUBOPERATION_STATUS_NOT_FOUND:
kuuseac3a8882019-10-03 10:48:06 +02002694 # a. New sub-operation
2695 # The sub-operation does not exist, add it.
2696 # _ns_execute_primitive() will be called from scale() as usual, with non-modified arguments
2697 # The following parameters are set to None for all kind of scaling:
2698 vdu_id = None
2699 vdu_count_index = None
2700 vdu_name = None
tierno51183952020-04-03 15:48:18 +00002701 if RO_nsr_id and RO_scaling_info:
kuuseac3a8882019-10-03 10:48:06 +02002702 vnf_config_primitive = None
2703 primitive_params = None
2704 else:
2705 RO_nsr_id = None
2706 RO_scaling_info = None
2707 # Initial status for sub-operation
2708 operationState = 'PROCESSING'
2709 detailed_status = 'In progress'
2710 # Add sub-operation for pre/post-scaling (zero or more operations)
2711 self._add_suboperation(db_nslcmop,
2712 vnf_index,
2713 vdu_id,
2714 vdu_count_index,
2715 vdu_name,
2716 vnf_config_primitive,
2717 primitive_params,
2718 operationState,
2719 detailed_status,
2720 operationType,
2721 RO_nsr_id,
2722 RO_scaling_info)
2723 return self.SUBOPERATION_STATUS_NEW
2724 else:
2725 # Return either SUBOPERATION_STATUS_SKIP (operationState == 'COMPLETED'),
2726 # or op_index (operationState != 'COMPLETED')
tierno51183952020-04-03 15:48:18 +00002727 return self._retry_or_skip_suboperation(db_nslcmop, op_index)
kuuseac3a8882019-10-03 10:48:06 +02002728
preethika.pdf7d8e02019-12-10 13:10:48 +00002729 # Function to return execution_environment id
2730
2731 def _get_ee_id(self, vnf_index, vdu_id, vca_deployed_list):
tiernoe876f672020-02-13 14:34:48 +00002732 # TODO vdu_index_count
preethika.pdf7d8e02019-12-10 13:10:48 +00002733 for vca in vca_deployed_list:
2734 if vca["member-vnf-index"] == vnf_index and vca["vdu_id"] == vdu_id:
2735 return vca["ee_id"]
2736
tierno588547c2020-07-01 15:30:20 +00002737 async def destroy_N2VC(self, logging_text, db_nslcmop, vca_deployed, config_descriptor,
2738 vca_index, destroy_ee=True, exec_primitives=True):
tiernoe876f672020-02-13 14:34:48 +00002739 """
2740 Execute the terminate primitives and destroy the execution environment (if destroy_ee=False
2741 :param logging_text:
2742 :param db_nslcmop:
2743 :param vca_deployed: Dictionary of deployment info at db_nsr._admin.depoloyed.VCA.<INDEX>
2744 :param config_descriptor: Configuration descriptor of the NSD, VNFD, VNFD.vdu or VNFD.kdu
2745 :param vca_index: index in the database _admin.deployed.VCA
2746 :param destroy_ee: False to do not destroy, because it will be destroyed all of then at once
tierno588547c2020-07-01 15:30:20 +00002747 :param exec_primitives: False to do not execute terminate primitives, because the config is not completed or has
2748 not executed properly
tiernoe876f672020-02-13 14:34:48 +00002749 :return: None or exception
2750 """
tiernoe876f672020-02-13 14:34:48 +00002751
tierno588547c2020-07-01 15:30:20 +00002752 self.logger.debug(
2753 logging_text + " vca_index: {}, vca_deployed: {}, config_descriptor: {}, destroy_ee: {}".format(
2754 vca_index, vca_deployed, config_descriptor, destroy_ee
2755 )
2756 )
2757
2758 vca_type = vca_deployed.get("type", "lxc_proxy_charm")
2759
2760 # execute terminate_primitives
2761 if exec_primitives:
bravof922c4172020-11-24 21:21:43 -03002762 terminate_primitives = get_ee_sorted_terminate_config_primitive_list(
2763 config_descriptor.get("terminate-config-primitive"), vca_deployed.get("ee_descriptor_id"))
tierno588547c2020-07-01 15:30:20 +00002764 vdu_id = vca_deployed.get("vdu_id")
2765 vdu_count_index = vca_deployed.get("vdu_count_index")
2766 vdu_name = vca_deployed.get("vdu_name")
2767 vnf_index = vca_deployed.get("member-vnf-index")
2768 if terminate_primitives and vca_deployed.get("needed_terminate"):
tierno588547c2020-07-01 15:30:20 +00002769 for seq in terminate_primitives:
2770 # For each sequence in list, get primitive and call _ns_execute_primitive()
2771 step = "Calling terminate action for vnf_member_index={} primitive={}".format(
2772 vnf_index, seq.get("name"))
2773 self.logger.debug(logging_text + step)
2774 # Create the primitive for each sequence, i.e. "primitive": "touch"
2775 primitive = seq.get('name')
2776 mapped_primitive_params = self._get_terminate_primitive_params(seq, vnf_index)
tierno588547c2020-07-01 15:30:20 +00002777
2778 # Add sub-operation
2779 self._add_suboperation(db_nslcmop,
2780 vnf_index,
2781 vdu_id,
2782 vdu_count_index,
2783 vdu_name,
2784 primitive,
2785 mapped_primitive_params)
2786 # Sub-operations: Call _ns_execute_primitive() instead of action()
2787 try:
2788 result, result_detail = await self._ns_execute_primitive(vca_deployed["ee_id"], primitive,
2789 mapped_primitive_params,
2790 vca_type=vca_type)
2791 except LcmException:
2792 # this happens when VCA is not deployed. In this case it is not needed to terminate
2793 continue
2794 result_ok = ['COMPLETED', 'PARTIALLY_COMPLETED']
2795 if result not in result_ok:
2796 raise LcmException("terminate_primitive {} for vnf_member_index={} fails with "
2797 "error {}".format(seq.get("name"), vnf_index, result_detail))
2798 # set that this VCA do not need terminated
2799 db_update_entry = "_admin.deployed.VCA.{}.needed_terminate".format(vca_index)
2800 self.update_db_2("nsrs", db_nslcmop["nsInstanceId"], {db_update_entry: False})
tiernoe876f672020-02-13 14:34:48 +00002801
tiernob996d942020-07-03 14:52:28 +00002802 if vca_deployed.get("prometheus_jobs") and self.prometheus:
2803 await self.prometheus.update(remove_jobs=vca_deployed["prometheus_jobs"])
2804
tiernoe876f672020-02-13 14:34:48 +00002805 if destroy_ee:
tierno588547c2020-07-01 15:30:20 +00002806 await self.vca_map[vca_type].delete_execution_environment(vca_deployed["ee_id"])
kuuse0ca67472019-05-13 15:59:27 +02002807
tierno51183952020-04-03 15:48:18 +00002808 async def _delete_all_N2VC(self, db_nsr: dict):
2809 self._write_all_config_status(db_nsr=db_nsr, status='TERMINATING')
2810 namespace = "." + db_nsr["_id"]
tiernof59ad6c2020-04-08 12:50:52 +00002811 try:
2812 await self.n2vc.delete_namespace(namespace=namespace, total_timeout=self.timeout_charm_delete)
2813 except N2VCNotFound: # already deleted. Skip
2814 pass
tierno51183952020-04-03 15:48:18 +00002815 self._write_all_config_status(db_nsr=db_nsr, status='DELETED')
quilesj3655ae02019-12-12 16:08:35 +00002816
tiernoe876f672020-02-13 14:34:48 +00002817 async def _terminate_RO(self, logging_text, nsr_deployed, nsr_id, nslcmop_id, stage):
2818 """
2819 Terminates a deployment from RO
2820 :param logging_text:
2821 :param nsr_deployed: db_nsr._admin.deployed
2822 :param nsr_id:
2823 :param nslcmop_id:
2824 :param stage: list of string with the content to write on db_nslcmop.detailed-status.
2825 this method will update only the index 2, but it will write on database the concatenated content of the list
2826 :return:
2827 """
2828 db_nsr_update = {}
2829 failed_detail = []
2830 ro_nsr_id = ro_delete_action = None
2831 if nsr_deployed and nsr_deployed.get("RO"):
2832 ro_nsr_id = nsr_deployed["RO"].get("nsr_id")
2833 ro_delete_action = nsr_deployed["RO"].get("nsr_delete_action_id")
2834 try:
2835 if ro_nsr_id:
2836 stage[2] = "Deleting ns from VIM."
2837 db_nsr_update["detailed-status"] = " ".join(stage)
2838 self._write_op_status(nslcmop_id, stage)
2839 self.logger.debug(logging_text + stage[2])
2840 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2841 self._write_op_status(nslcmop_id, stage)
2842 desc = await self.RO.delete("ns", ro_nsr_id)
2843 ro_delete_action = desc["action_id"]
2844 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = ro_delete_action
2845 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
2846 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
2847 if ro_delete_action:
2848 # wait until NS is deleted from VIM
2849 stage[2] = "Waiting ns deleted from VIM."
2850 detailed_status_old = None
2851 self.logger.debug(logging_text + stage[2] + " RO_id={} ro_delete_action={}".format(ro_nsr_id,
2852 ro_delete_action))
2853 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2854 self._write_op_status(nslcmop_id, stage)
kuused124bfe2019-06-18 12:09:24 +02002855
tiernoe876f672020-02-13 14:34:48 +00002856 delete_timeout = 20 * 60 # 20 minutes
2857 while delete_timeout > 0:
2858 desc = await self.RO.show(
2859 "ns",
2860 item_id_name=ro_nsr_id,
2861 extra_item="action",
2862 extra_item_id=ro_delete_action)
2863
2864 # deploymentStatus
2865 self._on_update_ro_db(nsrs_id=nsr_id, ro_descriptor=desc)
2866
2867 ns_status, ns_status_info = self.RO.check_action_status(desc)
2868 if ns_status == "ERROR":
2869 raise ROclient.ROClientException(ns_status_info)
2870 elif ns_status == "BUILD":
2871 stage[2] = "Deleting from VIM {}".format(ns_status_info)
2872 elif ns_status == "ACTIVE":
2873 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
2874 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
2875 break
2876 else:
2877 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
2878 if stage[2] != detailed_status_old:
2879 detailed_status_old = stage[2]
2880 db_nsr_update["detailed-status"] = " ".join(stage)
2881 self._write_op_status(nslcmop_id, stage)
2882 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2883 await asyncio.sleep(5, loop=self.loop)
2884 delete_timeout -= 5
2885 else: # delete_timeout <= 0:
2886 raise ROclient.ROClientException("Timeout waiting ns deleted from VIM")
2887
2888 except Exception as e:
2889 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2890 if isinstance(e, ROclient.ROClientException) and e.http_code == 404: # not found
2891 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
2892 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
2893 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
2894 self.logger.debug(logging_text + "RO_ns_id={} already deleted".format(ro_nsr_id))
2895 elif isinstance(e, ROclient.ROClientException) and e.http_code == 409: # conflict
tiernoa2143262020-03-27 16:20:40 +00002896 failed_detail.append("delete conflict: {}".format(e))
2897 self.logger.debug(logging_text + "RO_ns_id={} delete conflict: {}".format(ro_nsr_id, e))
tiernoe876f672020-02-13 14:34:48 +00002898 else:
tiernoa2143262020-03-27 16:20:40 +00002899 failed_detail.append("delete error: {}".format(e))
2900 self.logger.error(logging_text + "RO_ns_id={} delete error: {}".format(ro_nsr_id, e))
tiernoe876f672020-02-13 14:34:48 +00002901
2902 # Delete nsd
2903 if not failed_detail and deep_get(nsr_deployed, ("RO", "nsd_id")):
2904 ro_nsd_id = nsr_deployed["RO"]["nsd_id"]
2905 try:
2906 stage[2] = "Deleting nsd from RO."
2907 db_nsr_update["detailed-status"] = " ".join(stage)
2908 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2909 self._write_op_status(nslcmop_id, stage)
2910 await self.RO.delete("nsd", ro_nsd_id)
2911 self.logger.debug(logging_text + "ro_nsd_id={} deleted".format(ro_nsd_id))
2912 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
2913 except Exception as e:
2914 if isinstance(e, ROclient.ROClientException) and e.http_code == 404: # not found
2915 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
2916 self.logger.debug(logging_text + "ro_nsd_id={} already deleted".format(ro_nsd_id))
2917 elif isinstance(e, ROclient.ROClientException) and e.http_code == 409: # conflict
2918 failed_detail.append("ro_nsd_id={} delete conflict: {}".format(ro_nsd_id, e))
2919 self.logger.debug(logging_text + failed_detail[-1])
2920 else:
2921 failed_detail.append("ro_nsd_id={} delete error: {}".format(ro_nsd_id, e))
2922 self.logger.error(logging_text + failed_detail[-1])
2923
2924 if not failed_detail and deep_get(nsr_deployed, ("RO", "vnfd")):
2925 for index, vnf_deployed in enumerate(nsr_deployed["RO"]["vnfd"]):
2926 if not vnf_deployed or not vnf_deployed["id"]:
2927 continue
2928 try:
2929 ro_vnfd_id = vnf_deployed["id"]
2930 stage[2] = "Deleting member_vnf_index={} ro_vnfd_id={} from RO.".format(
2931 vnf_deployed["member-vnf-index"], ro_vnfd_id)
2932 db_nsr_update["detailed-status"] = " ".join(stage)
2933 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2934 self._write_op_status(nslcmop_id, stage)
2935 await self.RO.delete("vnfd", ro_vnfd_id)
2936 self.logger.debug(logging_text + "ro_vnfd_id={} deleted".format(ro_vnfd_id))
2937 db_nsr_update["_admin.deployed.RO.vnfd.{}.id".format(index)] = None
2938 except Exception as e:
2939 if isinstance(e, ROclient.ROClientException) and e.http_code == 404: # not found
2940 db_nsr_update["_admin.deployed.RO.vnfd.{}.id".format(index)] = None
2941 self.logger.debug(logging_text + "ro_vnfd_id={} already deleted ".format(ro_vnfd_id))
2942 elif isinstance(e, ROclient.ROClientException) and e.http_code == 409: # conflict
2943 failed_detail.append("ro_vnfd_id={} delete conflict: {}".format(ro_vnfd_id, e))
2944 self.logger.debug(logging_text + failed_detail[-1])
2945 else:
2946 failed_detail.append("ro_vnfd_id={} delete error: {}".format(ro_vnfd_id, e))
2947 self.logger.error(logging_text + failed_detail[-1])
2948
tiernoa2143262020-03-27 16:20:40 +00002949 if failed_detail:
2950 stage[2] = "Error deleting from VIM"
2951 else:
2952 stage[2] = "Deleted from VIM"
tiernoe876f672020-02-13 14:34:48 +00002953 db_nsr_update["detailed-status"] = " ".join(stage)
2954 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2955 self._write_op_status(nslcmop_id, stage)
2956
2957 if failed_detail:
tiernoa2143262020-03-27 16:20:40 +00002958 raise LcmException("; ".join(failed_detail))
tiernoe876f672020-02-13 14:34:48 +00002959
2960 async def terminate(self, nsr_id, nslcmop_id):
kuused124bfe2019-06-18 12:09:24 +02002961 # Try to lock HA task here
2962 task_is_locked_by_me = self.lcm_tasks.lock_HA('ns', 'nslcmops', nslcmop_id)
2963 if not task_is_locked_by_me:
2964 return
2965
tierno59d22d22018-09-25 18:10:19 +02002966 logging_text = "Task ns={} terminate={} ".format(nsr_id, nslcmop_id)
2967 self.logger.debug(logging_text + "Enter")
tiernoe876f672020-02-13 14:34:48 +00002968 timeout_ns_terminate = self.timeout_ns_terminate
tierno59d22d22018-09-25 18:10:19 +02002969 db_nsr = None
2970 db_nslcmop = None
tiernoa17d4f42020-04-28 09:59:23 +00002971 operation_params = None
tierno59d22d22018-09-25 18:10:19 +02002972 exc = None
tiernoe876f672020-02-13 14:34:48 +00002973 error_list = [] # annotates all failed error messages
tierno59d22d22018-09-25 18:10:19 +02002974 db_nslcmop_update = {}
tiernoc2564fe2019-01-28 16:18:56 +00002975 autoremove = False # autoremove after terminated
tiernoe876f672020-02-13 14:34:48 +00002976 tasks_dict_info = {}
2977 db_nsr_update = {}
2978 stage = ["Stage 1/3: Preparing task.", "Waiting for previous operations to terminate.", ""]
2979 # ^ contains [stage, step, VIM-status]
tierno59d22d22018-09-25 18:10:19 +02002980 try:
kuused124bfe2019-06-18 12:09:24 +02002981 # wait for any previous tasks in process
2982 await self.lcm_tasks.waitfor_related_HA("ns", 'nslcmops', nslcmop_id)
2983
tiernoe876f672020-02-13 14:34:48 +00002984 stage[1] = "Getting nslcmop={} from db.".format(nslcmop_id)
2985 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
2986 operation_params = db_nslcmop.get("operationParams") or {}
2987 if operation_params.get("timeout_ns_terminate"):
2988 timeout_ns_terminate = operation_params["timeout_ns_terminate"]
2989 stage[1] = "Getting nsr={} from db.".format(nsr_id)
2990 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2991
2992 db_nsr_update["operational-status"] = "terminating"
2993 db_nsr_update["config-status"] = "terminating"
quilesj4cda56b2019-12-05 10:02:20 +00002994 self._write_ns_status(
2995 nsr_id=nsr_id,
2996 ns_state="TERMINATING",
2997 current_operation="TERMINATING",
tiernoe876f672020-02-13 14:34:48 +00002998 current_operation_id=nslcmop_id,
2999 other_update=db_nsr_update
quilesj4cda56b2019-12-05 10:02:20 +00003000 )
quilesj3655ae02019-12-12 16:08:35 +00003001 self._write_op_status(
3002 op_id=nslcmop_id,
tiernoe876f672020-02-13 14:34:48 +00003003 queuePosition=0,
3004 stage=stage
quilesj3655ae02019-12-12 16:08:35 +00003005 )
tiernoe876f672020-02-13 14:34:48 +00003006 nsr_deployed = deepcopy(db_nsr["_admin"].get("deployed")) or {}
tierno59d22d22018-09-25 18:10:19 +02003007 if db_nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
3008 return
tierno59d22d22018-09-25 18:10:19 +02003009
tiernoe876f672020-02-13 14:34:48 +00003010 stage[1] = "Getting vnf descriptors from db."
3011 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
3012 db_vnfds_from_id = {}
3013 db_vnfds_from_member_index = {}
3014 # Loop over VNFRs
3015 for vnfr in db_vnfrs_list:
3016 vnfd_id = vnfr["vnfd-id"]
3017 if vnfd_id not in db_vnfds_from_id:
3018 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
3019 db_vnfds_from_id[vnfd_id] = vnfd
3020 db_vnfds_from_member_index[vnfr["member-vnf-index-ref"]] = db_vnfds_from_id[vnfd_id]
calvinosanch9f9c6f22019-11-04 13:37:39 +01003021
tiernoe876f672020-02-13 14:34:48 +00003022 # Destroy individual execution environments when there are terminating primitives.
3023 # Rest of EE will be deleted at once
tierno588547c2020-07-01 15:30:20 +00003024 # TODO - check before calling _destroy_N2VC
3025 # if not operation_params.get("skip_terminate_primitives"):#
3026 # or not vca.get("needed_terminate"):
3027 stage[0] = "Stage 2/3 execute terminating primitives."
3028 self.logger.debug(logging_text + stage[0])
3029 stage[1] = "Looking execution environment that needs terminate."
3030 self.logger.debug(logging_text + stage[1])
bravof922c4172020-11-24 21:21:43 -03003031
tierno588547c2020-07-01 15:30:20 +00003032 for vca_index, vca in enumerate(get_iterable(nsr_deployed, "VCA")):
tierno588547c2020-07-01 15:30:20 +00003033 config_descriptor = None
3034 if not vca or not vca.get("ee_id"):
3035 continue
3036 if not vca.get("member-vnf-index"):
3037 # ns
3038 config_descriptor = db_nsr.get("ns-configuration")
3039 elif vca.get("vdu_id"):
3040 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
bravofe5a31bc2021-02-17 19:09:12 -03003041 config_descriptor = get_configuration(db_vnfd, vca.get("vdu_id"))
tierno588547c2020-07-01 15:30:20 +00003042 elif vca.get("kdu_name"):
3043 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
bravofe5a31bc2021-02-17 19:09:12 -03003044 config_descriptor = get_configuration(db_vnfd, vca.get("kdu_name"))
tierno588547c2020-07-01 15:30:20 +00003045 else:
bravofe5a31bc2021-02-17 19:09:12 -03003046 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
3047 config_descriptor = get_configuration(db_vnfd, db_vnfd["id"])
tierno588547c2020-07-01 15:30:20 +00003048 vca_type = vca.get("type")
3049 exec_terminate_primitives = (not operation_params.get("skip_terminate_primitives") and
3050 vca.get("needed_terminate"))
tiernoaebd7da2020-08-07 06:36:38 +00003051 # For helm we must destroy_ee. Also for native_charm, as juju_model cannot be deleted if there are
3052 # pending native charms
lloretgalleg18ebc3a2020-10-22 09:54:51 +00003053 destroy_ee = True if vca_type in ("helm", "helm-v3", "native_charm") else False
tierno86e33612020-09-16 14:13:06 +00003054 # self.logger.debug(logging_text + "vca_index: {}, ee_id: {}, vca_type: {} destroy_ee: {}".format(
3055 # vca_index, vca.get("ee_id"), vca_type, destroy_ee))
tiernob996d942020-07-03 14:52:28 +00003056 task = asyncio.ensure_future(
3057 self.destroy_N2VC(logging_text, db_nslcmop, vca, config_descriptor, vca_index,
3058 destroy_ee, exec_terminate_primitives))
tierno588547c2020-07-01 15:30:20 +00003059 tasks_dict_info[task] = "Terminating VCA {}".format(vca.get("ee_id"))
tierno59d22d22018-09-25 18:10:19 +02003060
tierno588547c2020-07-01 15:30:20 +00003061 # wait for pending tasks of terminate primitives
3062 if tasks_dict_info:
tierno86e33612020-09-16 14:13:06 +00003063 self.logger.debug(logging_text + 'Waiting for tasks {}'.format(list(tasks_dict_info.keys())))
tierno588547c2020-07-01 15:30:20 +00003064 error_list = await self._wait_for_tasks(logging_text, tasks_dict_info,
3065 min(self.timeout_charm_delete, timeout_ns_terminate),
3066 stage, nslcmop_id)
tierno86e33612020-09-16 14:13:06 +00003067 tasks_dict_info.clear()
tierno588547c2020-07-01 15:30:20 +00003068 if error_list:
3069 return # raise LcmException("; ".join(error_list))
tierno82974b22018-11-27 21:55:36 +00003070
tiernoe876f672020-02-13 14:34:48 +00003071 # remove All execution environments at once
3072 stage[0] = "Stage 3/3 delete all."
quilesj3655ae02019-12-12 16:08:35 +00003073
tierno49676be2020-04-07 16:34:35 +00003074 if nsr_deployed.get("VCA"):
3075 stage[1] = "Deleting all execution environments."
3076 self.logger.debug(logging_text + stage[1])
3077 task_delete_ee = asyncio.ensure_future(asyncio.wait_for(self._delete_all_N2VC(db_nsr=db_nsr),
3078 timeout=self.timeout_charm_delete))
3079 # task_delete_ee = asyncio.ensure_future(self.n2vc.delete_namespace(namespace="." + nsr_id))
3080 tasks_dict_info[task_delete_ee] = "Terminating all VCA"
tierno59d22d22018-09-25 18:10:19 +02003081
tiernoe876f672020-02-13 14:34:48 +00003082 # Delete from k8scluster
3083 stage[1] = "Deleting KDUs."
3084 self.logger.debug(logging_text + stage[1])
3085 # print(nsr_deployed)
3086 for kdu in get_iterable(nsr_deployed, "K8s"):
3087 if not kdu or not kdu.get("kdu-instance"):
3088 continue
3089 kdu_instance = kdu.get("kdu-instance")
tiernoa2143262020-03-27 16:20:40 +00003090 if kdu.get("k8scluster-type") in self.k8scluster_map:
tiernoe876f672020-02-13 14:34:48 +00003091 task_delete_kdu_instance = asyncio.ensure_future(
tiernoa2143262020-03-27 16:20:40 +00003092 self.k8scluster_map[kdu["k8scluster-type"]].uninstall(
3093 cluster_uuid=kdu.get("k8scluster-uuid"),
3094 kdu_instance=kdu_instance))
tiernoe876f672020-02-13 14:34:48 +00003095 else:
3096 self.logger.error(logging_text + "Unknown k8s deployment type {}".
3097 format(kdu.get("k8scluster-type")))
3098 continue
3099 tasks_dict_info[task_delete_kdu_instance] = "Terminating KDU '{}'".format(kdu.get("kdu-name"))
tierno59d22d22018-09-25 18:10:19 +02003100
3101 # remove from RO
tiernoe876f672020-02-13 14:34:48 +00003102 stage[1] = "Deleting ns from VIM."
tierno69f0d382020-05-07 13:08:09 +00003103 if self.ng_ro:
3104 task_delete_ro = asyncio.ensure_future(
3105 self._terminate_ng_ro(logging_text, nsr_deployed, nsr_id, nslcmop_id, stage))
3106 else:
3107 task_delete_ro = asyncio.ensure_future(
3108 self._terminate_RO(logging_text, nsr_deployed, nsr_id, nslcmop_id, stage))
tiernoe876f672020-02-13 14:34:48 +00003109 tasks_dict_info[task_delete_ro] = "Removing deployment from VIM"
tierno59d22d22018-09-25 18:10:19 +02003110
tiernoe876f672020-02-13 14:34:48 +00003111 # rest of staff will be done at finally
3112
3113 except (ROclient.ROClientException, DbException, LcmException, N2VCException) as e:
3114 self.logger.error(logging_text + "Exit Exception {}".format(e))
3115 exc = e
3116 except asyncio.CancelledError:
3117 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(stage[1]))
3118 exc = "Operation was cancelled"
3119 except Exception as e:
3120 exc = traceback.format_exc()
3121 self.logger.critical(logging_text + "Exit Exception while '{}': {}".format(stage[1], e), exc_info=True)
3122 finally:
3123 if exc:
3124 error_list.append(str(exc))
tierno59d22d22018-09-25 18:10:19 +02003125 try:
tiernoe876f672020-02-13 14:34:48 +00003126 # wait for pending tasks
3127 if tasks_dict_info:
3128 stage[1] = "Waiting for terminate pending tasks."
3129 self.logger.debug(logging_text + stage[1])
3130 error_list += await self._wait_for_tasks(logging_text, tasks_dict_info, timeout_ns_terminate,
3131 stage, nslcmop_id)
3132 stage[1] = stage[2] = ""
3133 except asyncio.CancelledError:
3134 error_list.append("Cancelled")
3135 # TODO cancell all tasks
3136 except Exception as exc:
3137 error_list.append(str(exc))
3138 # update status at database
3139 if error_list:
3140 error_detail = "; ".join(error_list)
3141 # self.logger.error(logging_text + error_detail)
tiernob5203912020-08-11 11:20:13 +00003142 error_description_nslcmop = '{} Detail: {}'.format(stage[0], error_detail)
3143 error_description_nsr = 'Operation: TERMINATING.{}, {}.'.format(nslcmop_id, stage[0])
tierno59d22d22018-09-25 18:10:19 +02003144
tierno59d22d22018-09-25 18:10:19 +02003145 db_nsr_update["operational-status"] = "failed"
tiernoa2143262020-03-27 16:20:40 +00003146 db_nsr_update["detailed-status"] = error_description_nsr + " Detail: " + error_detail
tiernoe876f672020-02-13 14:34:48 +00003147 db_nslcmop_update["detailed-status"] = error_detail
3148 nslcmop_operation_state = "FAILED"
3149 ns_state = "BROKEN"
tierno59d22d22018-09-25 18:10:19 +02003150 else:
tiernoa2143262020-03-27 16:20:40 +00003151 error_detail = None
tiernoe876f672020-02-13 14:34:48 +00003152 error_description_nsr = error_description_nslcmop = None
3153 ns_state = "NOT_INSTANTIATED"
tierno59d22d22018-09-25 18:10:19 +02003154 db_nsr_update["operational-status"] = "terminated"
3155 db_nsr_update["detailed-status"] = "Done"
3156 db_nsr_update["_admin.nsState"] = "NOT_INSTANTIATED"
3157 db_nslcmop_update["detailed-status"] = "Done"
tiernoe876f672020-02-13 14:34:48 +00003158 nslcmop_operation_state = "COMPLETED"
tierno59d22d22018-09-25 18:10:19 +02003159
tiernoe876f672020-02-13 14:34:48 +00003160 if db_nsr:
3161 self._write_ns_status(
3162 nsr_id=nsr_id,
3163 ns_state=ns_state,
3164 current_operation="IDLE",
3165 current_operation_id=None,
3166 error_description=error_description_nsr,
tiernoa2143262020-03-27 16:20:40 +00003167 error_detail=error_detail,
tiernoe876f672020-02-13 14:34:48 +00003168 other_update=db_nsr_update
3169 )
tiernoa17d4f42020-04-28 09:59:23 +00003170 self._write_op_status(
3171 op_id=nslcmop_id,
3172 stage="",
3173 error_message=error_description_nslcmop,
3174 operation_state=nslcmop_operation_state,
3175 other_update=db_nslcmop_update,
3176 )
lloretgalleg6d488782020-07-22 10:13:46 +00003177 if ns_state == "NOT_INSTANTIATED":
3178 try:
3179 self.db.set_list("vnfrs", {"nsr-id-ref": nsr_id}, {"_admin.nsState": "NOT_INSTANTIATED"})
3180 except DbException as e:
3181 self.logger.warn(logging_text + 'Error writing VNFR status for nsr-id-ref: {} -> {}'.
3182 format(nsr_id, e))
tiernoa17d4f42020-04-28 09:59:23 +00003183 if operation_params:
tiernoe876f672020-02-13 14:34:48 +00003184 autoremove = operation_params.get("autoremove", False)
tierno59d22d22018-09-25 18:10:19 +02003185 if nslcmop_operation_state:
3186 try:
3187 await self.msg.aiowrite("ns", "terminated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
tiernoc2564fe2019-01-28 16:18:56 +00003188 "operationState": nslcmop_operation_state,
3189 "autoremove": autoremove},
tierno8a518872018-12-21 13:42:14 +00003190 loop=self.loop)
tierno59d22d22018-09-25 18:10:19 +02003191 except Exception as e:
3192 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
quilesj7e13aeb2019-10-08 13:34:55 +02003193
tierno59d22d22018-09-25 18:10:19 +02003194 self.logger.debug(logging_text + "Exit")
3195 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_terminate")
3196
tiernoe876f672020-02-13 14:34:48 +00003197 async def _wait_for_tasks(self, logging_text, created_tasks_info, timeout, stage, nslcmop_id, nsr_id=None):
3198 time_start = time()
tiernoa2143262020-03-27 16:20:40 +00003199 error_detail_list = []
tiernoe876f672020-02-13 14:34:48 +00003200 error_list = []
3201 pending_tasks = list(created_tasks_info.keys())
3202 num_tasks = len(pending_tasks)
3203 num_done = 0
3204 stage[1] = "{}/{}.".format(num_done, num_tasks)
3205 self._write_op_status(nslcmop_id, stage)
tiernoe876f672020-02-13 14:34:48 +00003206 while pending_tasks:
tiernoa2143262020-03-27 16:20:40 +00003207 new_error = None
tiernoe876f672020-02-13 14:34:48 +00003208 _timeout = timeout + time_start - time()
3209 done, pending_tasks = await asyncio.wait(pending_tasks, timeout=_timeout,
3210 return_when=asyncio.FIRST_COMPLETED)
3211 num_done += len(done)
3212 if not done: # Timeout
3213 for task in pending_tasks:
tiernoa2143262020-03-27 16:20:40 +00003214 new_error = created_tasks_info[task] + ": Timeout"
3215 error_detail_list.append(new_error)
3216 error_list.append(new_error)
tiernoe876f672020-02-13 14:34:48 +00003217 break
3218 for task in done:
3219 if task.cancelled():
tierno067e04a2020-03-31 12:53:13 +00003220 exc = "Cancelled"
tiernoe876f672020-02-13 14:34:48 +00003221 else:
3222 exc = task.exception()
tierno067e04a2020-03-31 12:53:13 +00003223 if exc:
3224 if isinstance(exc, asyncio.TimeoutError):
3225 exc = "Timeout"
3226 new_error = created_tasks_info[task] + ": {}".format(exc)
3227 error_list.append(created_tasks_info[task])
3228 error_detail_list.append(new_error)
tierno28c63da2020-04-20 16:28:56 +00003229 if isinstance(exc, (str, DbException, N2VCException, ROclient.ROClientException, LcmException,
tierno2357f4e2020-10-19 16:38:59 +00003230 K8sException, NgRoException)):
tierno067e04a2020-03-31 12:53:13 +00003231 self.logger.error(logging_text + new_error)
tiernoe876f672020-02-13 14:34:48 +00003232 else:
tierno067e04a2020-03-31 12:53:13 +00003233 exc_traceback = "".join(traceback.format_exception(None, exc, exc.__traceback__))
tierno2357f4e2020-10-19 16:38:59 +00003234 self.logger.error(logging_text + created_tasks_info[task] + " " + exc_traceback)
tierno067e04a2020-03-31 12:53:13 +00003235 else:
3236 self.logger.debug(logging_text + created_tasks_info[task] + ": Done")
tiernoe876f672020-02-13 14:34:48 +00003237 stage[1] = "{}/{}.".format(num_done, num_tasks)
3238 if new_error:
tiernoa2143262020-03-27 16:20:40 +00003239 stage[1] += " Errors: " + ". ".join(error_detail_list) + "."
tiernoe876f672020-02-13 14:34:48 +00003240 if nsr_id: # update also nsr
tiernoa2143262020-03-27 16:20:40 +00003241 self.update_db_2("nsrs", nsr_id, {"errorDescription": "Error at: " + ", ".join(error_list),
3242 "errorDetail": ". ".join(error_detail_list)})
tiernoe876f672020-02-13 14:34:48 +00003243 self._write_op_status(nslcmop_id, stage)
tiernoa2143262020-03-27 16:20:40 +00003244 return error_detail_list
tiernoe876f672020-02-13 14:34:48 +00003245
tiernoda1ff8c2020-10-22 14:12:46 +00003246 @staticmethod
3247 def _map_primitive_params(primitive_desc, params, instantiation_params):
tiernoda964822019-01-14 15:53:47 +00003248 """
3249 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
3250 The default-value is used. If it is between < > it look for a value at instantiation_params
3251 :param primitive_desc: portion of VNFD/NSD that describes primitive
3252 :param params: Params provided by user
3253 :param instantiation_params: Instantiation params provided by user
3254 :return: a dictionary with the calculated params
3255 """
3256 calculated_params = {}
3257 for parameter in primitive_desc.get("parameter", ()):
3258 param_name = parameter["name"]
3259 if param_name in params:
3260 calculated_params[param_name] = params[param_name]
tierno98ad6ea2019-05-30 17:16:28 +00003261 elif "default-value" in parameter or "value" in parameter:
3262 if "value" in parameter:
3263 calculated_params[param_name] = parameter["value"]
3264 else:
3265 calculated_params[param_name] = parameter["default-value"]
3266 if isinstance(calculated_params[param_name], str) and calculated_params[param_name].startswith("<") \
3267 and calculated_params[param_name].endswith(">"):
3268 if calculated_params[param_name][1:-1] in instantiation_params:
3269 calculated_params[param_name] = instantiation_params[calculated_params[param_name][1:-1]]
tiernoda964822019-01-14 15:53:47 +00003270 else:
3271 raise LcmException("Parameter {} needed to execute primitive {} not provided".
tiernod8323042019-08-09 11:32:23 +00003272 format(calculated_params[param_name], primitive_desc["name"]))
tiernoda964822019-01-14 15:53:47 +00003273 else:
3274 raise LcmException("Parameter {} needed to execute primitive {} not provided".
3275 format(param_name, primitive_desc["name"]))
tierno59d22d22018-09-25 18:10:19 +02003276
tiernoda964822019-01-14 15:53:47 +00003277 if isinstance(calculated_params[param_name], (dict, list, tuple)):
bravof922c4172020-11-24 21:21:43 -03003278 calculated_params[param_name] = yaml.safe_dump(calculated_params[param_name],
3279 default_flow_style=True, width=256)
tiernoda964822019-01-14 15:53:47 +00003280 elif isinstance(calculated_params[param_name], str) and calculated_params[param_name].startswith("!!yaml "):
3281 calculated_params[param_name] = calculated_params[param_name][7:]
tiernofa40e692020-10-14 14:59:36 +00003282 if parameter.get("data-type") == "INTEGER":
3283 try:
3284 calculated_params[param_name] = int(calculated_params[param_name])
3285 except ValueError: # error converting string to int
3286 raise LcmException(
3287 "Parameter {} of primitive {} must be integer".format(param_name, primitive_desc["name"]))
3288 elif parameter.get("data-type") == "BOOLEAN":
3289 calculated_params[param_name] = not ((str(calculated_params[param_name])).lower() == 'false')
tiernoc3f2a822019-11-05 13:45:04 +00003290
3291 # add always ns_config_info if primitive name is config
3292 if primitive_desc["name"] == "config":
3293 if "ns_config_info" in instantiation_params:
3294 calculated_params["ns_config_info"] = instantiation_params["ns_config_info"]
tiernoda964822019-01-14 15:53:47 +00003295 return calculated_params
3296
tiernoa278b842020-07-08 15:33:55 +00003297 def _look_for_deployed_vca(self, deployed_vca, member_vnf_index, vdu_id, vdu_count_index, kdu_name=None,
3298 ee_descriptor_id=None):
tiernoe876f672020-02-13 14:34:48 +00003299 # find vca_deployed record for this action. Raise LcmException if not found or there is not any id.
3300 for vca in deployed_vca:
3301 if not vca:
3302 continue
3303 if member_vnf_index != vca["member-vnf-index"] or vdu_id != vca["vdu_id"]:
3304 continue
tiernoe876f672020-02-13 14:34:48 +00003305 if vdu_count_index is not None and vdu_count_index != vca["vdu_count_index"]:
3306 continue
3307 if kdu_name and kdu_name != vca["kdu_name"]:
3308 continue
tiernoa278b842020-07-08 15:33:55 +00003309 if ee_descriptor_id and ee_descriptor_id != vca["ee_descriptor_id"]:
3310 continue
tiernoe876f672020-02-13 14:34:48 +00003311 break
3312 else:
3313 # vca_deployed not found
tiernoa278b842020-07-08 15:33:55 +00003314 raise LcmException("charm for member_vnf_index={} vdu_id={}.{} kdu_name={} execution-environment-list.id={}"
3315 " is not deployed".format(member_vnf_index, vdu_id, vdu_count_index, kdu_name,
3316 ee_descriptor_id))
tiernoe876f672020-02-13 14:34:48 +00003317 # get ee_id
3318 ee_id = vca.get("ee_id")
tierno588547c2020-07-01 15:30:20 +00003319 vca_type = vca.get("type", "lxc_proxy_charm") # default value for backward compatibility - proxy charm
tiernoe876f672020-02-13 14:34:48 +00003320 if not ee_id:
tierno067e04a2020-03-31 12:53:13 +00003321 raise LcmException("charm for member_vnf_index={} vdu_id={} kdu_name={} vdu_count_index={} has not "
tiernoe876f672020-02-13 14:34:48 +00003322 "execution environment"
tierno067e04a2020-03-31 12:53:13 +00003323 .format(member_vnf_index, vdu_id, kdu_name, vdu_count_index))
tierno588547c2020-07-01 15:30:20 +00003324 return ee_id, vca_type
tiernoe876f672020-02-13 14:34:48 +00003325
bravof922c4172020-11-24 21:21:43 -03003326 async def _ns_execute_primitive(self, ee_id, primitive, primitive_params, retries=0, retries_interval=30,
3327 timeout=None, vca_type=None, db_dict=None) -> (str, str):
tiernoda964822019-01-14 15:53:47 +00003328 try:
tierno98ad6ea2019-05-30 17:16:28 +00003329 if primitive == "config":
3330 primitive_params = {"params": primitive_params}
tierno2fc7ce52019-06-11 22:50:01 +00003331
tierno588547c2020-07-01 15:30:20 +00003332 vca_type = vca_type or "lxc_proxy_charm"
3333
quilesj7e13aeb2019-10-08 13:34:55 +02003334 while retries >= 0:
3335 try:
tierno067e04a2020-03-31 12:53:13 +00003336 output = await asyncio.wait_for(
tierno588547c2020-07-01 15:30:20 +00003337 self.vca_map[vca_type].exec_primitive(
tierno067e04a2020-03-31 12:53:13 +00003338 ee_id=ee_id,
3339 primitive_name=primitive,
3340 params_dict=primitive_params,
3341 progress_timeout=self.timeout_progress_primitive,
tierno588547c2020-07-01 15:30:20 +00003342 total_timeout=self.timeout_primitive,
3343 db_dict=db_dict),
tierno067e04a2020-03-31 12:53:13 +00003344 timeout=timeout or self.timeout_primitive)
quilesj7e13aeb2019-10-08 13:34:55 +02003345 # execution was OK
3346 break
tierno067e04a2020-03-31 12:53:13 +00003347 except asyncio.CancelledError:
3348 raise
3349 except Exception as e: # asyncio.TimeoutError
3350 if isinstance(e, asyncio.TimeoutError):
3351 e = "Timeout"
quilesj7e13aeb2019-10-08 13:34:55 +02003352 retries -= 1
3353 if retries >= 0:
tierno73d8bd02019-11-18 17:33:27 +00003354 self.logger.debug('Error executing action {} on {} -> {}'.format(primitive, ee_id, e))
quilesj7e13aeb2019-10-08 13:34:55 +02003355 # wait and retry
3356 await asyncio.sleep(retries_interval, loop=self.loop)
tierno73d8bd02019-11-18 17:33:27 +00003357 else:
tierno067e04a2020-03-31 12:53:13 +00003358 return 'FAILED', str(e)
quilesj7e13aeb2019-10-08 13:34:55 +02003359
tiernoe876f672020-02-13 14:34:48 +00003360 return 'COMPLETED', output
quilesj7e13aeb2019-10-08 13:34:55 +02003361
tierno067e04a2020-03-31 12:53:13 +00003362 except (LcmException, asyncio.CancelledError):
tiernoe876f672020-02-13 14:34:48 +00003363 raise
quilesj7e13aeb2019-10-08 13:34:55 +02003364 except Exception as e:
tiernoe876f672020-02-13 14:34:48 +00003365 return 'FAIL', 'Error executing action {}: {}'.format(primitive, e)
tierno59d22d22018-09-25 18:10:19 +02003366
3367 async def action(self, nsr_id, nslcmop_id):
kuused124bfe2019-06-18 12:09:24 +02003368 # Try to lock HA task here
3369 task_is_locked_by_me = self.lcm_tasks.lock_HA('ns', 'nslcmops', nslcmop_id)
3370 if not task_is_locked_by_me:
3371 return
3372
tierno59d22d22018-09-25 18:10:19 +02003373 logging_text = "Task ns={} action={} ".format(nsr_id, nslcmop_id)
3374 self.logger.debug(logging_text + "Enter")
3375 # get all needed from database
3376 db_nsr = None
3377 db_nslcmop = None
tiernoe876f672020-02-13 14:34:48 +00003378 db_nsr_update = {}
tierno59d22d22018-09-25 18:10:19 +02003379 db_nslcmop_update = {}
3380 nslcmop_operation_state = None
tierno067e04a2020-03-31 12:53:13 +00003381 error_description_nslcmop = None
tierno59d22d22018-09-25 18:10:19 +02003382 exc = None
3383 try:
kuused124bfe2019-06-18 12:09:24 +02003384 # wait for any previous tasks in process
tierno3cf81a32019-11-11 17:07:00 +00003385 step = "Waiting for previous operations to terminate"
kuused124bfe2019-06-18 12:09:24 +02003386 await self.lcm_tasks.waitfor_related_HA('ns', 'nslcmops', nslcmop_id)
3387
quilesj4cda56b2019-12-05 10:02:20 +00003388 self._write_ns_status(
3389 nsr_id=nsr_id,
3390 ns_state=None,
3391 current_operation="RUNNING ACTION",
3392 current_operation_id=nslcmop_id
3393 )
3394
tierno59d22d22018-09-25 18:10:19 +02003395 step = "Getting information from database"
3396 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
3397 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
tiernoda964822019-01-14 15:53:47 +00003398
tiernoe4f7e6c2018-11-27 14:55:30 +00003399 nsr_deployed = db_nsr["_admin"].get("deployed")
tierno1b633412019-02-25 16:48:23 +00003400 vnf_index = db_nslcmop["operationParams"].get("member_vnf_index")
tierno59d22d22018-09-25 18:10:19 +02003401 vdu_id = db_nslcmop["operationParams"].get("vdu_id")
calvinosanch9f9c6f22019-11-04 13:37:39 +01003402 kdu_name = db_nslcmop["operationParams"].get("kdu_name")
tiernoe4f7e6c2018-11-27 14:55:30 +00003403 vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
tierno067e04a2020-03-31 12:53:13 +00003404 primitive = db_nslcmop["operationParams"]["primitive"]
3405 primitive_params = db_nslcmop["operationParams"]["primitive_params"]
3406 timeout_ns_action = db_nslcmop["operationParams"].get("timeout_ns_action", self.timeout_primitive)
tierno59d22d22018-09-25 18:10:19 +02003407
tierno1b633412019-02-25 16:48:23 +00003408 if vnf_index:
3409 step = "Getting vnfr from database"
3410 db_vnfr = self.db.get_one("vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id})
3411 step = "Getting vnfd from database"
3412 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
3413 else:
tierno067e04a2020-03-31 12:53:13 +00003414 step = "Getting nsd from database"
3415 db_nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
tiernoda964822019-01-14 15:53:47 +00003416
tierno82974b22018-11-27 21:55:36 +00003417 # for backward compatibility
3418 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
3419 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
3420 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
3421 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3422
tiernoda964822019-01-14 15:53:47 +00003423 # look for primitive
tiernoa278b842020-07-08 15:33:55 +00003424 config_primitive_desc = descriptor_configuration = None
tiernoda964822019-01-14 15:53:47 +00003425 if vdu_id:
bravofe5a31bc2021-02-17 19:09:12 -03003426 descriptor_configuration = get_configuration(db_vnfd, vdu_id)
calvinosanch9f9c6f22019-11-04 13:37:39 +01003427 elif kdu_name:
bravofe5a31bc2021-02-17 19:09:12 -03003428 descriptor_configuration = get_configuration(db_vnfd, kdu_name)
tierno1b633412019-02-25 16:48:23 +00003429 elif vnf_index:
bravofe5a31bc2021-02-17 19:09:12 -03003430 descriptor_configuration = get_configuration(db_vnfd, db_vnfd["id"])
tierno1b633412019-02-25 16:48:23 +00003431 else:
tiernoa278b842020-07-08 15:33:55 +00003432 descriptor_configuration = db_nsd.get("ns-configuration")
3433
3434 if descriptor_configuration and descriptor_configuration.get("config-primitive"):
3435 for config_primitive in descriptor_configuration["config-primitive"]:
tierno1b633412019-02-25 16:48:23 +00003436 if config_primitive["name"] == primitive:
3437 config_primitive_desc = config_primitive
3438 break
tiernoda964822019-01-14 15:53:47 +00003439
garciadeblas6bed6b32020-07-20 11:05:42 +00003440 if not config_primitive_desc:
3441 if not (kdu_name and primitive in ("upgrade", "rollback", "status")):
3442 raise LcmException("Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".
3443 format(primitive))
3444 primitive_name = primitive
3445 ee_descriptor_id = None
3446 else:
3447 primitive_name = config_primitive_desc.get("execution-environment-primitive", primitive)
3448 ee_descriptor_id = config_primitive_desc.get("execution-environment-ref")
tierno1b633412019-02-25 16:48:23 +00003449
tierno1b633412019-02-25 16:48:23 +00003450 if vnf_index:
tierno626e0152019-11-29 14:16:16 +00003451 if vdu_id:
3452 vdur = next((x for x in db_vnfr["vdur"] if x["vdu-id-ref"] == vdu_id), None)
bravof922c4172020-11-24 21:21:43 -03003453 desc_params = parse_yaml_strings(vdur.get("additionalParams"))
tierno067e04a2020-03-31 12:53:13 +00003454 elif kdu_name:
3455 kdur = next((x for x in db_vnfr["kdur"] if x["kdu-name"] == kdu_name), None)
bravof922c4172020-11-24 21:21:43 -03003456 desc_params = parse_yaml_strings(kdur.get("additionalParams"))
tierno067e04a2020-03-31 12:53:13 +00003457 else:
bravof922c4172020-11-24 21:21:43 -03003458 desc_params = parse_yaml_strings(db_vnfr.get("additionalParamsForVnf"))
tierno1b633412019-02-25 16:48:23 +00003459 else:
bravof922c4172020-11-24 21:21:43 -03003460 desc_params = parse_yaml_strings(db_nsr.get("additionalParamsForNs"))
bravofe5a31bc2021-02-17 19:09:12 -03003461 if kdu_name and get_configuration(db_vnfd, kdu_name):
3462 kdu_configuration = get_configuration(db_vnfd, kdu_name)
David Garciad41dbd62020-12-10 12:52:52 +01003463 actions = set()
David Garciaa1003662021-02-16 21:07:58 +01003464 for primitive in kdu_configuration.get("initial-config-primitive", []):
David Garciad41dbd62020-12-10 12:52:52 +01003465 actions.add(primitive["name"])
David Garciaa1003662021-02-16 21:07:58 +01003466 for primitive in kdu_configuration.get("config-primitive", []):
David Garciad41dbd62020-12-10 12:52:52 +01003467 actions.add(primitive["name"])
3468 kdu_action = True if primitive_name in actions else False
Dominik Fleischmann771c32b2020-04-07 12:39:36 +02003469
tiernoda964822019-01-14 15:53:47 +00003470 # TODO check if ns is in a proper status
tiernoa278b842020-07-08 15:33:55 +00003471 if kdu_name and (primitive_name in ("upgrade", "rollback", "status") or kdu_action):
tierno067e04a2020-03-31 12:53:13 +00003472 # kdur and desc_params already set from before
3473 if primitive_params:
3474 desc_params.update(primitive_params)
3475 # TODO Check if we will need something at vnf level
3476 for index, kdu in enumerate(get_iterable(nsr_deployed, "K8s")):
3477 if kdu_name == kdu["kdu-name"] and kdu["member-vnf-index"] == vnf_index:
3478 break
3479 else:
3480 raise LcmException("KDU '{}' for vnf '{}' not deployed".format(kdu_name, vnf_index))
quilesj7e13aeb2019-10-08 13:34:55 +02003481
tierno067e04a2020-03-31 12:53:13 +00003482 if kdu.get("k8scluster-type") not in self.k8scluster_map:
3483 msg = "unknown k8scluster-type '{}'".format(kdu.get("k8scluster-type"))
3484 raise LcmException(msg)
3485
3486 db_dict = {"collection": "nsrs",
3487 "filter": {"_id": nsr_id},
3488 "path": "_admin.deployed.K8s.{}".format(index)}
tiernoa278b842020-07-08 15:33:55 +00003489 self.logger.debug(logging_text + "Exec k8s {} on {}.{}".format(primitive_name, vnf_index, kdu_name))
3490 step = "Executing kdu {}".format(primitive_name)
3491 if primitive_name == "upgrade":
tierno067e04a2020-03-31 12:53:13 +00003492 if desc_params.get("kdu_model"):
3493 kdu_model = desc_params.get("kdu_model")
3494 del desc_params["kdu_model"]
3495 else:
3496 kdu_model = kdu.get("kdu-model")
3497 parts = kdu_model.split(sep=":")
3498 if len(parts) == 2:
3499 kdu_model = parts[0]
3500
3501 detailed_status = await asyncio.wait_for(
3502 self.k8scluster_map[kdu["k8scluster-type"]].upgrade(
3503 cluster_uuid=kdu.get("k8scluster-uuid"),
3504 kdu_instance=kdu.get("kdu-instance"),
3505 atomic=True, kdu_model=kdu_model,
3506 params=desc_params, db_dict=db_dict,
3507 timeout=timeout_ns_action),
3508 timeout=timeout_ns_action + 10)
3509 self.logger.debug(logging_text + " Upgrade of kdu {} done".format(detailed_status))
tiernoa278b842020-07-08 15:33:55 +00003510 elif primitive_name == "rollback":
tierno067e04a2020-03-31 12:53:13 +00003511 detailed_status = await asyncio.wait_for(
3512 self.k8scluster_map[kdu["k8scluster-type"]].rollback(
3513 cluster_uuid=kdu.get("k8scluster-uuid"),
3514 kdu_instance=kdu.get("kdu-instance"),
3515 db_dict=db_dict),
3516 timeout=timeout_ns_action)
tiernoa278b842020-07-08 15:33:55 +00003517 elif primitive_name == "status":
tierno067e04a2020-03-31 12:53:13 +00003518 detailed_status = await asyncio.wait_for(
3519 self.k8scluster_map[kdu["k8scluster-type"]].status_kdu(
3520 cluster_uuid=kdu.get("k8scluster-uuid"),
3521 kdu_instance=kdu.get("kdu-instance")),
3522 timeout=timeout_ns_action)
Dominik Fleischmann771c32b2020-04-07 12:39:36 +02003523 else:
3524 kdu_instance = kdu.get("kdu-instance") or "{}-{}".format(kdu["kdu-name"], nsr_id)
3525 params = self._map_primitive_params(config_primitive_desc, primitive_params, desc_params)
3526
3527 detailed_status = await asyncio.wait_for(
3528 self.k8scluster_map[kdu["k8scluster-type"]].exec_primitive(
3529 cluster_uuid=kdu.get("k8scluster-uuid"),
3530 kdu_instance=kdu_instance,
tiernoa278b842020-07-08 15:33:55 +00003531 primitive_name=primitive_name,
Dominik Fleischmann771c32b2020-04-07 12:39:36 +02003532 params=params, db_dict=db_dict,
3533 timeout=timeout_ns_action),
3534 timeout=timeout_ns_action)
tierno067e04a2020-03-31 12:53:13 +00003535
3536 if detailed_status:
3537 nslcmop_operation_state = 'COMPLETED'
3538 else:
3539 detailed_status = ''
3540 nslcmop_operation_state = 'FAILED'
tierno067e04a2020-03-31 12:53:13 +00003541 else:
bravof922c4172020-11-24 21:21:43 -03003542 ee_id, vca_type = self._look_for_deployed_vca(nsr_deployed["VCA"], member_vnf_index=vnf_index,
3543 vdu_id=vdu_id, vdu_count_index=vdu_count_index,
tiernoa278b842020-07-08 15:33:55 +00003544 ee_descriptor_id=ee_descriptor_id)
tierno588547c2020-07-01 15:30:20 +00003545 db_nslcmop_notif = {"collection": "nslcmops",
3546 "filter": {"_id": nslcmop_id},
3547 "path": "admin.VCA"}
tierno067e04a2020-03-31 12:53:13 +00003548 nslcmop_operation_state, detailed_status = await self._ns_execute_primitive(
tierno588547c2020-07-01 15:30:20 +00003549 ee_id,
tiernoa278b842020-07-08 15:33:55 +00003550 primitive=primitive_name,
tierno067e04a2020-03-31 12:53:13 +00003551 primitive_params=self._map_primitive_params(config_primitive_desc, primitive_params, desc_params),
tierno588547c2020-07-01 15:30:20 +00003552 timeout=timeout_ns_action,
3553 vca_type=vca_type,
3554 db_dict=db_nslcmop_notif)
tierno067e04a2020-03-31 12:53:13 +00003555
3556 db_nslcmop_update["detailed-status"] = detailed_status
3557 error_description_nslcmop = detailed_status if nslcmop_operation_state == "FAILED" else ""
3558 self.logger.debug(logging_text + " task Done with result {} {}".format(nslcmop_operation_state,
3559 detailed_status))
tierno59d22d22018-09-25 18:10:19 +02003560 return # database update is called inside finally
3561
tiernof59ad6c2020-04-08 12:50:52 +00003562 except (DbException, LcmException, N2VCException, K8sException) as e:
tierno59d22d22018-09-25 18:10:19 +02003563 self.logger.error(logging_text + "Exit Exception {}".format(e))
3564 exc = e
3565 except asyncio.CancelledError:
3566 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
3567 exc = "Operation was cancelled"
tierno067e04a2020-03-31 12:53:13 +00003568 except asyncio.TimeoutError:
3569 self.logger.error(logging_text + "Timeout while '{}'".format(step))
3570 exc = "Timeout"
tierno59d22d22018-09-25 18:10:19 +02003571 except Exception as e:
3572 exc = traceback.format_exc()
3573 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
3574 finally:
tierno067e04a2020-03-31 12:53:13 +00003575 if exc:
3576 db_nslcmop_update["detailed-status"] = detailed_status = error_description_nslcmop = \
kuuse0ca67472019-05-13 15:59:27 +02003577 "FAILED {}: {}".format(step, exc)
tierno067e04a2020-03-31 12:53:13 +00003578 nslcmop_operation_state = "FAILED"
3579 if db_nsr:
3580 self._write_ns_status(
3581 nsr_id=nsr_id,
3582 ns_state=db_nsr["nsState"], # TODO check if degraded. For the moment use previous status
3583 current_operation="IDLE",
3584 current_operation_id=None,
3585 # error_description=error_description_nsr,
3586 # error_detail=error_detail,
3587 other_update=db_nsr_update
3588 )
3589
bravof922c4172020-11-24 21:21:43 -03003590 self._write_op_status(op_id=nslcmop_id, stage="", error_message=error_description_nslcmop,
3591 operation_state=nslcmop_operation_state, other_update=db_nslcmop_update)
tierno067e04a2020-03-31 12:53:13 +00003592
tierno59d22d22018-09-25 18:10:19 +02003593 if nslcmop_operation_state:
3594 try:
3595 await self.msg.aiowrite("ns", "actioned", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
tierno8a518872018-12-21 13:42:14 +00003596 "operationState": nslcmop_operation_state},
3597 loop=self.loop)
tierno59d22d22018-09-25 18:10:19 +02003598 except Exception as e:
3599 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
3600 self.logger.debug(logging_text + "Exit")
3601 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_action")
tierno067e04a2020-03-31 12:53:13 +00003602 return nslcmop_operation_state, detailed_status
tierno59d22d22018-09-25 18:10:19 +02003603
3604 async def scale(self, nsr_id, nslcmop_id):
kuused124bfe2019-06-18 12:09:24 +02003605 # Try to lock HA task here
3606 task_is_locked_by_me = self.lcm_tasks.lock_HA('ns', 'nslcmops', nslcmop_id)
3607 if not task_is_locked_by_me:
3608 return
3609
tierno59d22d22018-09-25 18:10:19 +02003610 logging_text = "Task ns={} scale={} ".format(nsr_id, nslcmop_id)
tierno2357f4e2020-10-19 16:38:59 +00003611 stage = ['', '', '']
3612 # ^ stage, step, VIM progress
tierno59d22d22018-09-25 18:10:19 +02003613 self.logger.debug(logging_text + "Enter")
3614 # get all needed from database
3615 db_nsr = None
tierno59d22d22018-09-25 18:10:19 +02003616 db_nslcmop_update = {}
tiernoe876f672020-02-13 14:34:48 +00003617 db_nsr_update = {}
tierno59d22d22018-09-25 18:10:19 +02003618 exc = None
tierno9ab95942018-10-10 16:44:22 +02003619 # in case of error, indicates what part of scale was failed to put nsr at error status
3620 scale_process = None
tiernod6de1992018-10-11 13:05:52 +02003621 old_operational_status = ""
3622 old_config_status = ""
tierno59d22d22018-09-25 18:10:19 +02003623 try:
kuused124bfe2019-06-18 12:09:24 +02003624 # wait for any previous tasks in process
tierno3cf81a32019-11-11 17:07:00 +00003625 step = "Waiting for previous operations to terminate"
kuused124bfe2019-06-18 12:09:24 +02003626 await self.lcm_tasks.waitfor_related_HA('ns', 'nslcmops', nslcmop_id)
bravof922c4172020-11-24 21:21:43 -03003627 self._write_ns_status(nsr_id=nsr_id, ns_state=None,
3628 current_operation="SCALING", current_operation_id=nslcmop_id)
quilesj4cda56b2019-12-05 10:02:20 +00003629
ikalyvas02d9e7b2019-05-27 18:16:01 +03003630 step = "Getting nslcmop from database"
ikalyvas02d9e7b2019-05-27 18:16:01 +03003631 self.logger.debug(step + " after having waited for previous tasks to be completed")
3632 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
bravof922c4172020-11-24 21:21:43 -03003633
ikalyvas02d9e7b2019-05-27 18:16:01 +03003634 step = "Getting nsr from database"
3635 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
ikalyvas02d9e7b2019-05-27 18:16:01 +03003636 old_operational_status = db_nsr["operational-status"]
3637 old_config_status = db_nsr["config-status"]
bravof922c4172020-11-24 21:21:43 -03003638
tierno59d22d22018-09-25 18:10:19 +02003639 step = "Parsing scaling parameters"
3640 db_nsr_update["operational-status"] = "scaling"
3641 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernoe4f7e6c2018-11-27 14:55:30 +00003642 nsr_deployed = db_nsr["_admin"].get("deployed")
calvinosanch9f9c6f22019-11-04 13:37:39 +01003643
3644 #######
3645 nsr_deployed = db_nsr["_admin"].get("deployed")
3646 vnf_index = db_nslcmop["operationParams"].get("member_vnf_index")
tiernoda6fb102019-11-23 00:36:52 +00003647 # vdu_id = db_nslcmop["operationParams"].get("vdu_id")
3648 # vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
3649 # vdu_name = db_nslcmop["operationParams"].get("vdu_name")
calvinosanch9f9c6f22019-11-04 13:37:39 +01003650 #######
3651
tierno59d22d22018-09-25 18:10:19 +02003652 vnf_index = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
3653 scaling_group = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
3654 scaling_type = db_nslcmop["operationParams"]["scaleVnfData"]["scaleVnfType"]
tierno82974b22018-11-27 21:55:36 +00003655 # for backward compatibility
3656 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
3657 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
3658 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
3659 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3660
tierno59d22d22018-09-25 18:10:19 +02003661 step = "Getting vnfr from database"
3662 db_vnfr = self.db.get_one("vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id})
bravof922c4172020-11-24 21:21:43 -03003663
tierno59d22d22018-09-25 18:10:19 +02003664 step = "Getting vnfd from database"
3665 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
ikalyvas02d9e7b2019-05-27 18:16:01 +03003666
tierno59d22d22018-09-25 18:10:19 +02003667 step = "Getting scaling-group-descriptor"
bravof832f8992020-12-07 12:57:31 -03003668 scaling_descriptor = find_in_list(
3669 get_scaling_aspect(
3670 db_vnfd
3671 ),
3672 lambda scale_desc: scale_desc["name"] == scaling_group
3673 )
3674 if not scaling_descriptor:
tierno59d22d22018-09-25 18:10:19 +02003675 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
3676 "at vnfd:scaling-group-descriptor".format(scaling_group))
ikalyvas02d9e7b2019-05-27 18:16:01 +03003677
tierno15b1cf12019-08-29 13:21:40 +00003678 step = "Sending scale order to VIM"
bravof922c4172020-11-24 21:21:43 -03003679 # TODO check if ns is in a proper status
tierno59d22d22018-09-25 18:10:19 +02003680 nb_scale_op = 0
3681 if not db_nsr["_admin"].get("scaling-group"):
3682 self.update_db_2("nsrs", nsr_id, {"_admin.scaling-group": [{"name": scaling_group, "nb-scale-op": 0}]})
3683 admin_scale_index = 0
3684 else:
3685 for admin_scale_index, admin_scale_info in enumerate(db_nsr["_admin"]["scaling-group"]):
3686 if admin_scale_info["name"] == scaling_group:
3687 nb_scale_op = admin_scale_info.get("nb-scale-op", 0)
3688 break
tierno9ab95942018-10-10 16:44:22 +02003689 else: # not found, set index one plus last element and add new entry with the name
3690 admin_scale_index += 1
3691 db_nsr_update["_admin.scaling-group.{}.name".format(admin_scale_index)] = scaling_group
tierno59d22d22018-09-25 18:10:19 +02003692 RO_scaling_info = []
3693 vdu_scaling_info = {"scaling_group_name": scaling_group, "vdu": []}
3694 if scaling_type == "SCALE_OUT":
bravof832f8992020-12-07 12:57:31 -03003695 if "aspect-delta-details" not in scaling_descriptor:
3696 raise LcmException(
3697 "Aspect delta details not fount in scaling descriptor {}".format(
3698 scaling_descriptor["name"]
3699 )
3700 )
tierno59d22d22018-09-25 18:10:19 +02003701 # count if max-instance-count is reached
bravof832f8992020-12-07 12:57:31 -03003702 deltas = scaling_descriptor.get("aspect-delta-details")["deltas"]
kuuse8b998e42019-07-30 15:22:16 +02003703
tierno59d22d22018-09-25 18:10:19 +02003704 vdu_scaling_info["scaling_direction"] = "OUT"
3705 vdu_scaling_info["vdu-create"] = {}
bravof832f8992020-12-07 12:57:31 -03003706 for delta in deltas:
3707 for vdu_delta in delta["vdu-delta"]:
3708 vdud = get_vdu(db_vnfd, vdu_delta["id"])
3709 vdu_index = get_vdu_index(db_vnfr, vdu_delta["id"])
3710 cloud_init_text = self._get_vdu_cloud_init_content(vdud, db_vnfd)
tierno72ef84f2020-10-06 08:22:07 +00003711 if cloud_init_text:
bravof832f8992020-12-07 12:57:31 -03003712 additional_params = self._get_vdu_additional_params(db_vnfr, vdud["id"]) or {}
3713 cloud_init_list = []
3714
3715 vdu_profile = get_vdu_profile(db_vnfd, vdu_delta["id"])
3716 max_instance_count = 10
3717 if vdu_profile and "max-number-of-instances" in vdu_profile:
3718 max_instance_count = vdu_profile.get("max-number-of-instances", 10)
3719
3720 deafult_instance_num = get_number_of_instances(db_vnfd, vdud["id"])
3721
3722 nb_scale_op += vdu_delta.get("number-of-instances", 1)
3723
3724 if nb_scale_op + deafult_instance_num > max_instance_count:
3725 raise LcmException(
3726 "reached the limit of {} (max-instance-count) "
3727 "scaling-out operations for the "
3728 "scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group)
bravof922c4172020-11-24 21:21:43 -03003729 )
bravof832f8992020-12-07 12:57:31 -03003730 for x in range(vdu_delta.get("number-of-instances", 1)):
3731 if cloud_init_text:
3732 # TODO Information of its own ip is not available because db_vnfr is not updated.
3733 additional_params["OSM"] = get_osm_params(
3734 db_vnfr,
3735 vdu_delta["id"],
3736 vdu_index + x
bravof922c4172020-11-24 21:21:43 -03003737 )
bravof832f8992020-12-07 12:57:31 -03003738 cloud_init_list.append(
3739 self._parse_cloud_init(
3740 cloud_init_text,
3741 additional_params,
3742 db_vnfd["id"],
3743 vdud["id"]
3744 )
3745 )
3746 RO_scaling_info.append(
3747 {
3748 "osm_vdu_id": vdu_delta["id"],
3749 "member-vnf-index": vnf_index,
3750 "type": "create",
3751 "count": vdu_delta.get("number-of-instances", 1)
3752 }
3753 )
3754 if cloud_init_list:
3755 RO_scaling_info[-1]["cloud_init"] = cloud_init_list
3756 vdu_scaling_info["vdu-create"][vdu_delta["id"]] = vdu_delta.get("number-of-instances", 1)
ikalyvas02d9e7b2019-05-27 18:16:01 +03003757
tierno59d22d22018-09-25 18:10:19 +02003758 elif scaling_type == "SCALE_IN":
tierno59d22d22018-09-25 18:10:19 +02003759 if "min-instance-count" in scaling_descriptor and scaling_descriptor["min-instance-count"] is not None:
3760 min_instance_count = int(scaling_descriptor["min-instance-count"])
bravof832f8992020-12-07 12:57:31 -03003761
tierno59d22d22018-09-25 18:10:19 +02003762 vdu_scaling_info["scaling_direction"] = "IN"
3763 vdu_scaling_info["vdu-delete"] = {}
bravof832f8992020-12-07 12:57:31 -03003764 deltas = scaling_descriptor.get("aspect-delta-details")["deltas"]
3765 for delta in deltas:
3766 for vdu_delta in delta["vdu-delta"]:
3767 min_instance_count = 0
3768 vdu_profile = get_vdu_profile(db_vnfd, vdu_delta["id"])
3769 if vdu_profile and "min-number-of-instances" in vdu_profile:
3770 min_instance_count = vdu_profile["min-number-of-instances"]
3771
3772 deafult_instance_num = get_number_of_instances(db_vnfd, vdu_delta["id"])
3773
3774 nb_scale_op -= vdu_delta.get("number-of-instances", 1)
3775 if nb_scale_op + deafult_instance_num < min_instance_count:
3776 raise LcmException(
3777 "reached the limit of {} (min-instance-count) scaling-in operations for the "
3778 "scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group)
3779 )
3780 RO_scaling_info.append({"osm_vdu_id": vdu_delta["id"], "member-vnf-index": vnf_index,
3781 "type": "delete", "count": vdu_delta.get("number-of-instances", 1)})
3782 vdu_scaling_info["vdu-delete"][vdu_delta["id"]] = vdu_delta.get("number-of-instances", 1)
tierno59d22d22018-09-25 18:10:19 +02003783
3784 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
tierno27246d82018-09-27 15:59:09 +02003785 vdu_delete = copy(vdu_scaling_info.get("vdu-delete"))
tierno59d22d22018-09-25 18:10:19 +02003786 if vdu_scaling_info["scaling_direction"] == "IN":
3787 for vdur in reversed(db_vnfr["vdur"]):
tierno27246d82018-09-27 15:59:09 +02003788 if vdu_delete.get(vdur["vdu-id-ref"]):
3789 vdu_delete[vdur["vdu-id-ref"]] -= 1
tierno59d22d22018-09-25 18:10:19 +02003790 vdu_scaling_info["vdu"].append({
tierno2357f4e2020-10-19 16:38:59 +00003791 "name": vdur.get("name") or vdur.get("vdu-name"),
tierno59d22d22018-09-25 18:10:19 +02003792 "vdu_id": vdur["vdu-id-ref"],
3793 "interface": []
3794 })
3795 for interface in vdur["interfaces"]:
3796 vdu_scaling_info["vdu"][-1]["interface"].append({
3797 "name": interface["name"],
3798 "ip_address": interface["ip-address"],
3799 "mac_address": interface.get("mac-address"),
3800 })
tierno2357f4e2020-10-19 16:38:59 +00003801 # vdu_delete = vdu_scaling_info.pop("vdu-delete")
tierno59d22d22018-09-25 18:10:19 +02003802
kuuseac3a8882019-10-03 10:48:06 +02003803 # PRE-SCALE BEGIN
tierno59d22d22018-09-25 18:10:19 +02003804 step = "Executing pre-scale vnf-config-primitive"
3805 if scaling_descriptor.get("scaling-config-action"):
3806 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
kuuseac3a8882019-10-03 10:48:06 +02003807 if (scaling_config_action.get("trigger") == "pre-scale-in" and scaling_type == "SCALE_IN") \
3808 or (scaling_config_action.get("trigger") == "pre-scale-out" and scaling_type == "SCALE_OUT"):
tierno59d22d22018-09-25 18:10:19 +02003809 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
3810 step = db_nslcmop_update["detailed-status"] = \
3811 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive)
tiernoda964822019-01-14 15:53:47 +00003812
tierno59d22d22018-09-25 18:10:19 +02003813 # look for primitive
bravofe5a31bc2021-02-17 19:09:12 -03003814 for config_primitive in (get_configuration(
3815 db_vnfd, db_vnfd["id"]
3816 ) or {}).get("config-primitive", ()):
tierno59d22d22018-09-25 18:10:19 +02003817 if config_primitive["name"] == vnf_config_primitive:
tierno59d22d22018-09-25 18:10:19 +02003818 break
3819 else:
3820 raise LcmException(
3821 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
tiernoda964822019-01-14 15:53:47 +00003822 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
tiernoa278b842020-07-08 15:33:55 +00003823 "primitive".format(scaling_group, vnf_config_primitive))
tiernoda964822019-01-14 15:53:47 +00003824
tierno16fedf52019-05-24 08:38:26 +00003825 vnfr_params = {"VDU_SCALE_INFO": vdu_scaling_info}
tiernoda964822019-01-14 15:53:47 +00003826 if db_vnfr.get("additionalParamsForVnf"):
3827 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
quilesj7e13aeb2019-10-08 13:34:55 +02003828
tierno9ab95942018-10-10 16:44:22 +02003829 scale_process = "VCA"
tiernod6de1992018-10-11 13:05:52 +02003830 db_nsr_update["config-status"] = "configuring pre-scaling"
kuuseac3a8882019-10-03 10:48:06 +02003831 primitive_params = self._map_primitive_params(config_primitive, {}, vnfr_params)
3832
tierno7c4e24c2020-05-13 08:41:35 +00003833 # Pre-scale retry check: Check if this sub-operation has been executed before
kuuseac3a8882019-10-03 10:48:06 +02003834 op_index = self._check_or_add_scale_suboperation(
3835 db_nslcmop, nslcmop_id, vnf_index, vnf_config_primitive, primitive_params, 'PRE-SCALE')
tierno7c4e24c2020-05-13 08:41:35 +00003836 if op_index == self.SUBOPERATION_STATUS_SKIP:
kuuseac3a8882019-10-03 10:48:06 +02003837 # Skip sub-operation
3838 result = 'COMPLETED'
3839 result_detail = 'Done'
3840 self.logger.debug(logging_text +
3841 "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
3842 vnf_config_primitive, result, result_detail))
3843 else:
tierno7c4e24c2020-05-13 08:41:35 +00003844 if op_index == self.SUBOPERATION_STATUS_NEW:
kuuseac3a8882019-10-03 10:48:06 +02003845 # New sub-operation: Get index of this sub-operation
3846 op_index = len(db_nslcmop.get('_admin', {}).get('operations')) - 1
3847 self.logger.debug(logging_text + "vnf_config_primitive={} New sub-operation".
3848 format(vnf_config_primitive))
3849 else:
tierno7c4e24c2020-05-13 08:41:35 +00003850 # retry: Get registered params for this existing sub-operation
kuuseac3a8882019-10-03 10:48:06 +02003851 op = db_nslcmop.get('_admin', {}).get('operations', [])[op_index]
3852 vnf_index = op.get('member_vnf_index')
3853 vnf_config_primitive = op.get('primitive')
3854 primitive_params = op.get('primitive_params')
tierno7c4e24c2020-05-13 08:41:35 +00003855 self.logger.debug(logging_text + "vnf_config_primitive={} Sub-operation retry".
kuuseac3a8882019-10-03 10:48:06 +02003856 format(vnf_config_primitive))
tierno588547c2020-07-01 15:30:20 +00003857 # Execute the primitive, either with new (first-time) or registered (reintent) args
tiernoa278b842020-07-08 15:33:55 +00003858 ee_descriptor_id = config_primitive.get("execution-environment-ref")
3859 primitive_name = config_primitive.get("execution-environment-primitive",
3860 vnf_config_primitive)
tierno588547c2020-07-01 15:30:20 +00003861 ee_id, vca_type = self._look_for_deployed_vca(nsr_deployed["VCA"],
3862 member_vnf_index=vnf_index,
3863 vdu_id=None,
tiernoa278b842020-07-08 15:33:55 +00003864 vdu_count_index=None,
3865 ee_descriptor_id=ee_descriptor_id)
kuuseac3a8882019-10-03 10:48:06 +02003866 result, result_detail = await self._ns_execute_primitive(
tiernoa278b842020-07-08 15:33:55 +00003867 ee_id, primitive_name, primitive_params, vca_type)
kuuseac3a8882019-10-03 10:48:06 +02003868 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
3869 vnf_config_primitive, result, result_detail))
3870 # Update operationState = COMPLETED | FAILED
3871 self._update_suboperation_status(
3872 db_nslcmop, op_index, result, result_detail)
3873
tierno59d22d22018-09-25 18:10:19 +02003874 if result == "FAILED":
3875 raise LcmException(result_detail)
tiernod6de1992018-10-11 13:05:52 +02003876 db_nsr_update["config-status"] = old_config_status
3877 scale_process = None
kuuseac3a8882019-10-03 10:48:06 +02003878 # PRE-SCALE END
tierno59d22d22018-09-25 18:10:19 +02003879
tierno2357f4e2020-10-19 16:38:59 +00003880 db_nsr_update["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index)] = nb_scale_op
3881 db_nsr_update["_admin.scaling-group.{}.time".format(admin_scale_index)] = time()
3882
kuuseac3a8882019-10-03 10:48:06 +02003883 # SCALE RO - BEGIN
tierno59d22d22018-09-25 18:10:19 +02003884 if RO_scaling_info:
tierno9ab95942018-10-10 16:44:22 +02003885 scale_process = "RO"
tierno2357f4e2020-10-19 16:38:59 +00003886 if self.ro_config.get("ng"):
3887 await self._scale_ng_ro(logging_text, db_nsr, db_nslcmop, db_vnfr, vdu_scaling_info, stage)
tierno2357f4e2020-10-19 16:38:59 +00003888 vdu_scaling_info.pop("vdu-create", None)
3889 vdu_scaling_info.pop("vdu-delete", None)
tierno59d22d22018-09-25 18:10:19 +02003890
tierno9ab95942018-10-10 16:44:22 +02003891 scale_process = None
tierno59d22d22018-09-25 18:10:19 +02003892 if db_nsr_update:
3893 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3894
kuuseac3a8882019-10-03 10:48:06 +02003895 # POST-SCALE BEGIN
tierno59d22d22018-09-25 18:10:19 +02003896 # execute primitive service POST-SCALING
3897 step = "Executing post-scale vnf-config-primitive"
3898 if scaling_descriptor.get("scaling-config-action"):
3899 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
kuuseac3a8882019-10-03 10:48:06 +02003900 if (scaling_config_action.get("trigger") == "post-scale-in" and scaling_type == "SCALE_IN") \
3901 or (scaling_config_action.get("trigger") == "post-scale-out" and scaling_type == "SCALE_OUT"):
tierno59d22d22018-09-25 18:10:19 +02003902 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
3903 step = db_nslcmop_update["detailed-status"] = \
3904 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive)
tiernoda964822019-01-14 15:53:47 +00003905
tierno589befb2019-05-29 07:06:23 +00003906 vnfr_params = {"VDU_SCALE_INFO": vdu_scaling_info}
tiernoda964822019-01-14 15:53:47 +00003907 if db_vnfr.get("additionalParamsForVnf"):
3908 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
3909
tierno59d22d22018-09-25 18:10:19 +02003910 # look for primitive
tierno59d22d22018-09-25 18:10:19 +02003911 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
3912 if config_primitive["name"] == vnf_config_primitive:
tierno59d22d22018-09-25 18:10:19 +02003913 break
3914 else:
tiernoa278b842020-07-08 15:33:55 +00003915 raise LcmException(
3916 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-"
3917 "action[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:"
3918 "config-primitive".format(scaling_group, vnf_config_primitive))
tierno9ab95942018-10-10 16:44:22 +02003919 scale_process = "VCA"
tiernod6de1992018-10-11 13:05:52 +02003920 db_nsr_update["config-status"] = "configuring post-scaling"
kuuseac3a8882019-10-03 10:48:06 +02003921 primitive_params = self._map_primitive_params(config_primitive, {}, vnfr_params)
tiernod6de1992018-10-11 13:05:52 +02003922
tierno7c4e24c2020-05-13 08:41:35 +00003923 # Post-scale retry check: Check if this sub-operation has been executed before
kuuseac3a8882019-10-03 10:48:06 +02003924 op_index = self._check_or_add_scale_suboperation(
3925 db_nslcmop, nslcmop_id, vnf_index, vnf_config_primitive, primitive_params, 'POST-SCALE')
quilesj4cda56b2019-12-05 10:02:20 +00003926 if op_index == self.SUBOPERATION_STATUS_SKIP:
kuuseac3a8882019-10-03 10:48:06 +02003927 # Skip sub-operation
3928 result = 'COMPLETED'
3929 result_detail = 'Done'
3930 self.logger.debug(logging_text +
3931 "vnf_config_primitive={} Skipped sub-operation, result {} {}".
3932 format(vnf_config_primitive, result, result_detail))
3933 else:
quilesj4cda56b2019-12-05 10:02:20 +00003934 if op_index == self.SUBOPERATION_STATUS_NEW:
kuuseac3a8882019-10-03 10:48:06 +02003935 # New sub-operation: Get index of this sub-operation
3936 op_index = len(db_nslcmop.get('_admin', {}).get('operations')) - 1
3937 self.logger.debug(logging_text + "vnf_config_primitive={} New sub-operation".
3938 format(vnf_config_primitive))
3939 else:
tierno7c4e24c2020-05-13 08:41:35 +00003940 # retry: Get registered params for this existing sub-operation
kuuseac3a8882019-10-03 10:48:06 +02003941 op = db_nslcmop.get('_admin', {}).get('operations', [])[op_index]
3942 vnf_index = op.get('member_vnf_index')
3943 vnf_config_primitive = op.get('primitive')
3944 primitive_params = op.get('primitive_params')
tierno7c4e24c2020-05-13 08:41:35 +00003945 self.logger.debug(logging_text + "vnf_config_primitive={} Sub-operation retry".
kuuseac3a8882019-10-03 10:48:06 +02003946 format(vnf_config_primitive))
tierno588547c2020-07-01 15:30:20 +00003947 # Execute the primitive, either with new (first-time) or registered (reintent) args
tiernoa278b842020-07-08 15:33:55 +00003948 ee_descriptor_id = config_primitive.get("execution-environment-ref")
3949 primitive_name = config_primitive.get("execution-environment-primitive",
3950 vnf_config_primitive)
tierno588547c2020-07-01 15:30:20 +00003951 ee_id, vca_type = self._look_for_deployed_vca(nsr_deployed["VCA"],
3952 member_vnf_index=vnf_index,
3953 vdu_id=None,
tiernoa278b842020-07-08 15:33:55 +00003954 vdu_count_index=None,
3955 ee_descriptor_id=ee_descriptor_id)
kuuseac3a8882019-10-03 10:48:06 +02003956 result, result_detail = await self._ns_execute_primitive(
tiernoa278b842020-07-08 15:33:55 +00003957 ee_id, primitive_name, primitive_params, vca_type)
kuuseac3a8882019-10-03 10:48:06 +02003958 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
3959 vnf_config_primitive, result, result_detail))
3960 # Update operationState = COMPLETED | FAILED
3961 self._update_suboperation_status(
3962 db_nslcmop, op_index, result, result_detail)
3963
tierno59d22d22018-09-25 18:10:19 +02003964 if result == "FAILED":
3965 raise LcmException(result_detail)
tiernod6de1992018-10-11 13:05:52 +02003966 db_nsr_update["config-status"] = old_config_status
3967 scale_process = None
kuuseac3a8882019-10-03 10:48:06 +02003968 # POST-SCALE END
tierno59d22d22018-09-25 18:10:19 +02003969
tiernod6de1992018-10-11 13:05:52 +02003970 db_nsr_update["detailed-status"] = "" # "scaled {} {}".format(scaling_group, scaling_type)
ikalyvas02d9e7b2019-05-27 18:16:01 +03003971 db_nsr_update["operational-status"] = "running" if old_operational_status == "failed" \
3972 else old_operational_status
tiernod6de1992018-10-11 13:05:52 +02003973 db_nsr_update["config-status"] = old_config_status
tierno59d22d22018-09-25 18:10:19 +02003974 return
tierno2357f4e2020-10-19 16:38:59 +00003975 except (ROclient.ROClientException, DbException, LcmException, NgRoException) as e:
tierno59d22d22018-09-25 18:10:19 +02003976 self.logger.error(logging_text + "Exit Exception {}".format(e))
3977 exc = e
3978 except asyncio.CancelledError:
3979 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
3980 exc = "Operation was cancelled"
3981 except Exception as e:
3982 exc = traceback.format_exc()
3983 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
3984 finally:
bravof922c4172020-11-24 21:21:43 -03003985 self._write_ns_status(nsr_id=nsr_id, ns_state=None, current_operation="IDLE", current_operation_id=None)
tierno59d22d22018-09-25 18:10:19 +02003986 if exc:
tiernoa17d4f42020-04-28 09:59:23 +00003987 db_nslcmop_update["detailed-status"] = error_description_nslcmop = "FAILED {}: {}".format(step, exc)
3988 nslcmop_operation_state = "FAILED"
tierno59d22d22018-09-25 18:10:19 +02003989 if db_nsr:
tiernod6de1992018-10-11 13:05:52 +02003990 db_nsr_update["operational-status"] = old_operational_status
3991 db_nsr_update["config-status"] = old_config_status
3992 db_nsr_update["detailed-status"] = ""
3993 if scale_process:
3994 if "VCA" in scale_process:
3995 db_nsr_update["config-status"] = "failed"
3996 if "RO" in scale_process:
3997 db_nsr_update["operational-status"] = "failed"
3998 db_nsr_update["detailed-status"] = "FAILED scaling nslcmop={} {}: {}".format(nslcmop_id, step,
3999 exc)
tiernoa17d4f42020-04-28 09:59:23 +00004000 else:
4001 error_description_nslcmop = None
4002 nslcmop_operation_state = "COMPLETED"
4003 db_nslcmop_update["detailed-status"] = "Done"
quilesj4cda56b2019-12-05 10:02:20 +00004004
bravof922c4172020-11-24 21:21:43 -03004005 self._write_op_status(op_id=nslcmop_id, stage="", error_message=error_description_nslcmop,
4006 operation_state=nslcmop_operation_state, other_update=db_nslcmop_update)
tiernoa17d4f42020-04-28 09:59:23 +00004007 if db_nsr:
bravof922c4172020-11-24 21:21:43 -03004008 self._write_ns_status(nsr_id=nsr_id, ns_state=None, current_operation="IDLE",
4009 current_operation_id=None, other_update=db_nsr_update)
tiernoa17d4f42020-04-28 09:59:23 +00004010
tierno59d22d22018-09-25 18:10:19 +02004011 if nslcmop_operation_state:
4012 try:
bravof922c4172020-11-24 21:21:43 -03004013 msg = {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id, "operationState": nslcmop_operation_state}
4014 await self.msg.aiowrite("ns", "scaled", msg, loop=self.loop)
tierno59d22d22018-09-25 18:10:19 +02004015 except Exception as e:
4016 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
4017 self.logger.debug(logging_text + "Exit")
4018 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_scale")
tiernob996d942020-07-03 14:52:28 +00004019
tierno2357f4e2020-10-19 16:38:59 +00004020 async def _scale_ng_ro(self, logging_text, db_nsr, db_nslcmop, db_vnfr, vdu_scaling_info, stage):
4021 nsr_id = db_nslcmop["nsInstanceId"]
4022 db_nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
4023 db_vnfrs = {}
4024
4025 # read from db: vnfd's for every vnf
bravof832f8992020-12-07 12:57:31 -03004026 db_vnfds = []
tierno2357f4e2020-10-19 16:38:59 +00004027
4028 # for each vnf in ns, read vnfd
4029 for vnfr in self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id}):
4030 db_vnfrs[vnfr["member-vnf-index-ref"]] = vnfr
4031 vnfd_id = vnfr["vnfd-id"] # vnfd uuid for this vnf
tierno2357f4e2020-10-19 16:38:59 +00004032 # if we haven't this vnfd, read it from db
bravof832f8992020-12-07 12:57:31 -03004033 if not find_in_list(db_vnfds, lambda a_vnfd: a_vnfd["id"] == vnfd_id):
tierno2357f4e2020-10-19 16:38:59 +00004034 # read from db
4035 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
bravof832f8992020-12-07 12:57:31 -03004036 db_vnfds.append(vnfd)
tierno2357f4e2020-10-19 16:38:59 +00004037 n2vc_key = self.n2vc.get_public_key()
4038 n2vc_key_list = [n2vc_key]
4039 self.scale_vnfr(db_vnfr, vdu_scaling_info.get("vdu-create"), vdu_scaling_info.get("vdu-delete"),
4040 mark_delete=True)
4041 # db_vnfr has been updated, update db_vnfrs to use it
4042 db_vnfrs[db_vnfr["member-vnf-index-ref"]] = db_vnfr
4043 await self._instantiate_ng_ro(logging_text, nsr_id, db_nsd, db_nsr, db_nslcmop, db_vnfrs,
bravof922c4172020-11-24 21:21:43 -03004044 db_vnfds, n2vc_key_list, stage=stage, start_deploy=time(),
tierno2357f4e2020-10-19 16:38:59 +00004045 timeout_ns_deploy=self.timeout_ns_deploy)
4046 if vdu_scaling_info.get("vdu-delete"):
4047 self.scale_vnfr(db_vnfr, None, vdu_scaling_info["vdu-delete"], mark_delete=False)
4048
tiernob996d942020-07-03 14:52:28 +00004049 async def add_prometheus_metrics(self, ee_id, artifact_path, ee_config_descriptor, vnfr_id, nsr_id, target_ip):
4050 if not self.prometheus:
4051 return
4052 # look if exist a file called 'prometheus*.j2' and
4053 artifact_content = self.fs.dir_ls(artifact_path)
4054 job_file = next((f for f in artifact_content if f.startswith("prometheus") and f.endswith(".j2")), None)
4055 if not job_file:
4056 return
4057 with self.fs.file_open((artifact_path, job_file), "r") as f:
4058 job_data = f.read()
4059
4060 # TODO get_service
4061 _, _, service = ee_id.partition(".") # remove prefix "namespace."
4062 host_name = "{}-{}".format(service, ee_config_descriptor["metric-service"])
4063 host_port = "80"
4064 vnfr_id = vnfr_id.replace("-", "")
4065 variables = {
4066 "JOB_NAME": vnfr_id,
4067 "TARGET_IP": target_ip,
4068 "EXPORTER_POD_IP": host_name,
4069 "EXPORTER_POD_PORT": host_port,
4070 }
4071 job_list = self.prometheus.parse_job(job_data, variables)
4072 # ensure job_name is using the vnfr_id. Adding the metadata nsr_id
4073 for job in job_list:
4074 if not isinstance(job.get("job_name"), str) or vnfr_id not in job["job_name"]:
4075 job["job_name"] = vnfr_id + "_" + str(randint(1, 10000))
4076 job["nsr_id"] = nsr_id
4077 job_dict = {jl["job_name"]: jl for jl in job_list}
4078 if await self.prometheus.update(job_dict):
4079 return list(job_dict.keys())
David Garciaaae391f2020-11-09 11:12:54 +01004080
4081 def get_vca_cloud_and_credentials(self, vim_account_id: str) -> (str, str):
4082 """
4083 Get VCA Cloud and VCA Cloud Credentials for the VIM account
4084
4085 :param: vim_account_id: VIM Account ID
4086
4087 :return: (cloud_name, cloud_credential)
4088 """
bravof922c4172020-11-24 21:21:43 -03004089 config = VimAccountDB.get_vim_account_with_id(vim_account_id).get("config", {})
David Garciaaae391f2020-11-09 11:12:54 +01004090 return config.get("vca_cloud"), config.get("vca_cloud_credential")
4091
4092 def get_vca_k8s_cloud_and_credentials(self, vim_account_id: str) -> (str, str):
4093 """
4094 Get VCA K8s Cloud and VCA K8s Cloud Credentials for the VIM account
4095
4096 :param: vim_account_id: VIM Account ID
4097
4098 :return: (cloud_name, cloud_credential)
4099 """
bravof922c4172020-11-24 21:21:43 -03004100 config = VimAccountDB.get_vim_account_with_id(vim_account_id).get("config", {})
David Garciaaae391f2020-11-09 11:12:54 +01004101 return config.get("vca_k8s_cloud"), config.get("vca_k8s_cloud_credential")