blob: 714f5db23ef9fc36af0f212c5a491c872458f85d [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
gcalvino35be9152018-12-20 09:33:12 +010025from jinja2 import Environment, Template, meta, TemplateError, TemplateNotFound, TemplateSyntaxError
tierno59d22d22018-09-25 18:10:19 +020026
tierno77677d92019-08-22 13:46:35 +000027from osm_lcm import ROclient
tierno744303e2020-01-13 16:46:31 +000028from osm_lcm.lcm_utils import LcmException, LcmExceptionNoMgmtIP, LcmBase, deep_get, get_iterable, populate_dict
calvinosanch9f9c6f22019-11-04 13:37:39 +010029from n2vc.k8s_helm_conn import K8sHelmConnector
Adam Israelbaacc302019-12-01 12:41:39 -050030from n2vc.k8s_juju_conn import K8sJujuConnector
tierno59d22d22018-09-25 18:10:19 +020031
tierno27246d82018-09-27 15:59:09 +020032from osm_common.dbbase import DbException
tierno59d22d22018-09-25 18:10:19 +020033from osm_common.fsbase import FsException
quilesj7e13aeb2019-10-08 13:34:55 +020034
35from n2vc.n2vc_juju_conn import N2VCJujuConnector
tiernof59ad6c2020-04-08 12:50:52 +000036from n2vc.exceptions import N2VCException, N2VCNotFound, K8sException
tierno59d22d22018-09-25 18:10:19 +020037
tierno27246d82018-09-27 15:59:09 +020038from copy import copy, deepcopy
tierno59d22d22018-09-25 18:10:19 +020039from http import HTTPStatus
40from time import time
tierno27246d82018-09-27 15:59:09 +020041from uuid import uuid4
tiernob9018152020-04-16 14:18:24 +000042from functools import partial
tierno59d22d22018-09-25 18:10:19 +020043
44__author__ = "Alfonso Tierno"
45
46
47class NsLcm(LcmBase):
tierno63de62e2018-10-31 16:38:52 +010048 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 +000049 timeout_ns_deploy = 2 * 3600 # default global timeout for deployment a ns
tiernoe876f672020-02-13 14:34:48 +000050 timeout_ns_terminate = 1800 # default global timeout for un deployment a ns
garciadeblasf9b04952019-04-09 18:53:58 +020051 timeout_charm_delete = 10 * 60
52 timeout_primitive = 10 * 60 # timeout for primitive execution
tierno067e04a2020-03-31 12:53:13 +000053 timeout_progress_primitive = 2 * 60 # timeout for some progress in a primitive execution
tierno59d22d22018-09-25 18:10:19 +020054
kuuseac3a8882019-10-03 10:48:06 +020055 SUBOPERATION_STATUS_NOT_FOUND = -1
56 SUBOPERATION_STATUS_NEW = -2
57 SUBOPERATION_STATUS_SKIP = -3
tiernoa2143262020-03-27 16:20:40 +000058 task_name_deploy_vca = "Deploying VCA"
kuuseac3a8882019-10-03 10:48:06 +020059
tierno744303e2020-01-13 16:46:31 +000060 def __init__(self, db, msg, fs, lcm_tasks, config, loop):
tierno59d22d22018-09-25 18:10:19 +020061 """
62 Init, Connect to database, filesystem storage, and messaging
63 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
64 :return: None
65 """
quilesj7e13aeb2019-10-08 13:34:55 +020066 super().__init__(
67 db=db,
68 msg=msg,
69 fs=fs,
70 logger=logging.getLogger('lcm.ns')
71 )
72
tierno59d22d22018-09-25 18:10:19 +020073 self.loop = loop
74 self.lcm_tasks = lcm_tasks
tierno744303e2020-01-13 16:46:31 +000075 self.timeout = config["timeout"]
76 self.ro_config = config["ro_config"]
77 self.vca_config = config["VCA"].copy()
tierno59d22d22018-09-25 18:10:19 +020078
quilesj7e13aeb2019-10-08 13:34:55 +020079 # create N2VC connector
80 self.n2vc = N2VCJujuConnector(
81 db=self.db,
82 fs=self.fs,
tierno59d22d22018-09-25 18:10:19 +020083 log=self.logger,
quilesj7e13aeb2019-10-08 13:34:55 +020084 loop=self.loop,
85 url='{}:{}'.format(self.vca_config['host'], self.vca_config['port']),
86 username=self.vca_config.get('user', None),
87 vca_config=self.vca_config,
quilesj3655ae02019-12-12 16:08:35 +000088 on_update_db=self._on_update_n2vc_db
tierno59d22d22018-09-25 18:10:19 +020089 )
quilesj7e13aeb2019-10-08 13:34:55 +020090
calvinosanch9f9c6f22019-11-04 13:37:39 +010091 self.k8sclusterhelm = K8sHelmConnector(
92 kubectl_command=self.vca_config.get("kubectlpath"),
93 helm_command=self.vca_config.get("helmpath"),
94 fs=self.fs,
95 log=self.logger,
96 db=self.db,
97 on_update_db=None,
98 )
99
Adam Israelbaacc302019-12-01 12:41:39 -0500100 self.k8sclusterjuju = K8sJujuConnector(
101 kubectl_command=self.vca_config.get("kubectlpath"),
102 juju_command=self.vca_config.get("jujupath"),
103 fs=self.fs,
104 log=self.logger,
105 db=self.db,
106 on_update_db=None,
107 )
108
tiernoa2143262020-03-27 16:20:40 +0000109 self.k8scluster_map = {
110 "helm-chart": self.k8sclusterhelm,
111 "chart": self.k8sclusterhelm,
112 "juju-bundle": self.k8sclusterjuju,
113 "juju": self.k8sclusterjuju,
114 }
quilesj7e13aeb2019-10-08 13:34:55 +0200115 # create RO client
tierno77677d92019-08-22 13:46:35 +0000116 self.RO = ROclient.ROClient(self.loop, **self.ro_config)
tierno59d22d22018-09-25 18:10:19 +0200117
quilesj3655ae02019-12-12 16:08:35 +0000118 def _on_update_ro_db(self, nsrs_id, ro_descriptor):
quilesj7e13aeb2019-10-08 13:34:55 +0200119
quilesj3655ae02019-12-12 16:08:35 +0000120 # self.logger.debug('_on_update_ro_db(nsrs_id={}'.format(nsrs_id))
121
122 try:
123 # TODO filter RO descriptor fields...
124
125 # write to database
126 db_dict = dict()
127 # db_dict['deploymentStatus'] = yaml.dump(ro_descriptor, default_flow_style=False, indent=2)
128 db_dict['deploymentStatus'] = ro_descriptor
129 self.update_db_2("nsrs", nsrs_id, db_dict)
130
131 except Exception as e:
132 self.logger.warn('Cannot write database RO deployment for ns={} -> {}'.format(nsrs_id, e))
133
134 async def _on_update_n2vc_db(self, table, filter, path, updated_data):
135
quilesj69a722c2020-01-09 08:30:17 +0000136 # remove last dot from path (if exists)
137 if path.endswith('.'):
138 path = path[:-1]
139
quilesj3655ae02019-12-12 16:08:35 +0000140 # self.logger.debug('_on_update_n2vc_db(table={}, filter={}, path={}, updated_data={}'
141 # .format(table, filter, path, updated_data))
142
143 try:
144
145 nsr_id = filter.get('_id')
146
147 # read ns record from database
148 nsr = self.db.get_one(table='nsrs', q_filter=filter)
149 current_ns_status = nsr.get('nsState')
150
151 # get vca status for NS
quilesj69a722c2020-01-09 08:30:17 +0000152 status_dict = await self.n2vc.get_status(namespace='.' + nsr_id, yaml_format=False)
quilesj3655ae02019-12-12 16:08:35 +0000153
154 # vcaStatus
155 db_dict = dict()
156 db_dict['vcaStatus'] = status_dict
157
158 # update configurationStatus for this VCA
159 try:
160 vca_index = int(path[path.rfind(".")+1:])
161
162 vca_list = deep_get(target_dict=nsr, key_list=('_admin', 'deployed', 'VCA'))
163 vca_status = vca_list[vca_index].get('status')
164
165 configuration_status_list = nsr.get('configurationStatus')
166 config_status = configuration_status_list[vca_index].get('status')
167
168 if config_status == 'BROKEN' and vca_status != 'failed':
169 db_dict['configurationStatus'][vca_index] = 'READY'
170 elif config_status != 'BROKEN' and vca_status == 'failed':
171 db_dict['configurationStatus'][vca_index] = 'BROKEN'
172 except Exception as e:
173 # not update configurationStatus
174 self.logger.debug('Error updating vca_index (ignore): {}'.format(e))
175
176 # if nsState = 'READY' check if juju is reporting some error => nsState = 'DEGRADED'
177 # if nsState = 'DEGRADED' check if all is OK
178 is_degraded = False
179 if current_ns_status in ('READY', 'DEGRADED'):
180 error_description = ''
181 # check machines
182 if status_dict.get('machines'):
183 for machine_id in status_dict.get('machines'):
184 machine = status_dict.get('machines').get(machine_id)
185 # check machine agent-status
186 if machine.get('agent-status'):
187 s = machine.get('agent-status').get('status')
188 if s != 'started':
189 is_degraded = True
190 error_description += 'machine {} agent-status={} ; '.format(machine_id, s)
191 # check machine instance status
192 if machine.get('instance-status'):
193 s = machine.get('instance-status').get('status')
194 if s != 'running':
195 is_degraded = True
196 error_description += 'machine {} instance-status={} ; '.format(machine_id, s)
197 # check applications
198 if status_dict.get('applications'):
199 for app_id in status_dict.get('applications'):
200 app = status_dict.get('applications').get(app_id)
201 # check application status
202 if app.get('status'):
203 s = app.get('status').get('status')
204 if s != 'active':
205 is_degraded = True
206 error_description += 'application {} status={} ; '.format(app_id, s)
207
208 if error_description:
209 db_dict['errorDescription'] = error_description
210 if current_ns_status == 'READY' and is_degraded:
211 db_dict['nsState'] = 'DEGRADED'
212 if current_ns_status == 'DEGRADED' and not is_degraded:
213 db_dict['nsState'] = 'READY'
214
215 # write to database
216 self.update_db_2("nsrs", nsr_id, db_dict)
217
tierno51183952020-04-03 15:48:18 +0000218 except (asyncio.CancelledError, asyncio.TimeoutError):
219 raise
quilesj3655ae02019-12-12 16:08:35 +0000220 except Exception as e:
221 self.logger.warn('Error updating NS state for ns={}: {}'.format(nsr_id, e))
quilesj7e13aeb2019-10-08 13:34:55 +0200222
gcalvino35be9152018-12-20 09:33:12 +0100223 def vnfd2RO(self, vnfd, new_id=None, additionalParams=None, nsrId=None):
tierno59d22d22018-09-25 18:10:19 +0200224 """
225 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
226 :param vnfd: input vnfd
227 :param new_id: overrides vnf id if provided
tierno8a518872018-12-21 13:42:14 +0000228 :param additionalParams: Instantiation params for VNFs provided
gcalvino35be9152018-12-20 09:33:12 +0100229 :param nsrId: Id of the NSR
tierno59d22d22018-09-25 18:10:19 +0200230 :return: copy of vnfd
231 """
tierno59d22d22018-09-25 18:10:19 +0200232 try:
233 vnfd_RO = deepcopy(vnfd)
tierno8a518872018-12-21 13:42:14 +0000234 # remove unused by RO configuration, monitoring, scaling and internal keys
tierno59d22d22018-09-25 18:10:19 +0200235 vnfd_RO.pop("_id", None)
236 vnfd_RO.pop("_admin", None)
tierno8a518872018-12-21 13:42:14 +0000237 vnfd_RO.pop("vnf-configuration", None)
238 vnfd_RO.pop("monitoring-param", None)
239 vnfd_RO.pop("scaling-group-descriptor", None)
calvinosanch9f9c6f22019-11-04 13:37:39 +0100240 vnfd_RO.pop("kdu", None)
241 vnfd_RO.pop("k8s-cluster", None)
tierno59d22d22018-09-25 18:10:19 +0200242 if new_id:
243 vnfd_RO["id"] = new_id
tierno8a518872018-12-21 13:42:14 +0000244
245 # parse cloud-init or cloud-init-file with the provided variables using Jinja2
246 for vdu in get_iterable(vnfd_RO, "vdu"):
247 cloud_init_file = None
248 if vdu.get("cloud-init-file"):
tierno59d22d22018-09-25 18:10:19 +0200249 base_folder = vnfd["_admin"]["storage"]
gcalvino35be9152018-12-20 09:33:12 +0100250 cloud_init_file = "{}/{}/cloud_init/{}".format(base_folder["folder"], base_folder["pkg-dir"],
251 vdu["cloud-init-file"])
252 with self.fs.file_open(cloud_init_file, "r") as ci_file:
253 cloud_init_content = ci_file.read()
tierno59d22d22018-09-25 18:10:19 +0200254 vdu.pop("cloud-init-file", None)
tierno8a518872018-12-21 13:42:14 +0000255 elif vdu.get("cloud-init"):
gcalvino35be9152018-12-20 09:33:12 +0100256 cloud_init_content = vdu["cloud-init"]
tierno8a518872018-12-21 13:42:14 +0000257 else:
258 continue
259
260 env = Environment()
261 ast = env.parse(cloud_init_content)
262 mandatory_vars = meta.find_undeclared_variables(ast)
263 if mandatory_vars:
264 for var in mandatory_vars:
265 if not additionalParams or var not in additionalParams.keys():
266 raise LcmException("Variable '{}' defined at vnfd[id={}]:vdu[id={}]:cloud-init/cloud-init-"
267 "file, must be provided in the instantiation parameters inside the "
268 "'additionalParamsForVnf' block".format(var, vnfd["id"], vdu["id"]))
269 template = Template(cloud_init_content)
tierno2b611dd2019-01-11 10:30:57 +0000270 cloud_init_content = template.render(additionalParams or {})
gcalvino35be9152018-12-20 09:33:12 +0100271 vdu["cloud-init"] = cloud_init_content
tierno8a518872018-12-21 13:42:14 +0000272
tierno59d22d22018-09-25 18:10:19 +0200273 return vnfd_RO
274 except FsException as e:
tierno8a518872018-12-21 13:42:14 +0000275 raise LcmException("Error reading vnfd[id={}]:vdu[id={}]:cloud-init-file={}: {}".
tiernoda964822019-01-14 15:53:47 +0000276 format(vnfd["id"], vdu["id"], cloud_init_file, e))
tierno8a518872018-12-21 13:42:14 +0000277 except (TemplateError, TemplateNotFound, TemplateSyntaxError) as e:
278 raise LcmException("Error parsing Jinja2 to cloud-init content at vnfd[id={}]:vdu[id={}]: {}".
279 format(vnfd["id"], vdu["id"], e))
tierno59d22d22018-09-25 18:10:19 +0200280
tiernoe95ed362020-04-23 08:24:57 +0000281 def _ns_params_2_RO(self, ns_params, nsd, vnfd_dict, db_vnfrs, n2vc_key_list):
tierno59d22d22018-09-25 18:10:19 +0200282 """
tierno27246d82018-09-27 15:59:09 +0200283 Creates a RO ns descriptor from OSM ns_instantiate params
tierno59d22d22018-09-25 18:10:19 +0200284 :param ns_params: OSM instantiate params
tiernoe95ed362020-04-23 08:24:57 +0000285 :param vnfd_dict: database content of vnfds, indexed by id (not _id). {id: {vnfd_object}, ...}
286 :param db_vnfrs: database content of vnfrs, indexed by member-vnf-index. {member-vnf-index: {vnfr_object}, ...}
tierno59d22d22018-09-25 18:10:19 +0200287 :return: The RO ns descriptor
288 """
289 vim_2_RO = {}
tiernob7f3f0d2019-03-20 17:17:21 +0000290 wim_2_RO = {}
tierno27246d82018-09-27 15:59:09 +0200291 # TODO feature 1417: Check that no instantiation is set over PDU
292 # check if PDU forces a concrete vim-network-id and add it
293 # check if PDU contains a SDN-assist info (dpid, switch, port) and pass it to RO
tierno59d22d22018-09-25 18:10:19 +0200294
295 def vim_account_2_RO(vim_account):
296 if vim_account in vim_2_RO:
297 return vim_2_RO[vim_account]
298
299 db_vim = self.db.get_one("vim_accounts", {"_id": vim_account})
300 if db_vim["_admin"]["operationalState"] != "ENABLED":
301 raise LcmException("VIM={} is not available. operationalState={}".format(
302 vim_account, db_vim["_admin"]["operationalState"]))
303 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
304 vim_2_RO[vim_account] = RO_vim_id
305 return RO_vim_id
306
tiernob7f3f0d2019-03-20 17:17:21 +0000307 def wim_account_2_RO(wim_account):
308 if isinstance(wim_account, str):
309 if wim_account in wim_2_RO:
310 return wim_2_RO[wim_account]
311
312 db_wim = self.db.get_one("wim_accounts", {"_id": wim_account})
313 if db_wim["_admin"]["operationalState"] != "ENABLED":
314 raise LcmException("WIM={} is not available. operationalState={}".format(
315 wim_account, db_wim["_admin"]["operationalState"]))
316 RO_wim_id = db_wim["_admin"]["deployed"]["RO-account"]
317 wim_2_RO[wim_account] = RO_wim_id
318 return RO_wim_id
319 else:
320 return wim_account
321
tierno59d22d22018-09-25 18:10:19 +0200322 def ip_profile_2_RO(ip_profile):
323 RO_ip_profile = deepcopy((ip_profile))
324 if "dns-server" in RO_ip_profile:
325 if isinstance(RO_ip_profile["dns-server"], list):
326 RO_ip_profile["dns-address"] = []
327 for ds in RO_ip_profile.pop("dns-server"):
328 RO_ip_profile["dns-address"].append(ds['address'])
329 else:
330 RO_ip_profile["dns-address"] = RO_ip_profile.pop("dns-server")
331 if RO_ip_profile.get("ip-version") == "ipv4":
332 RO_ip_profile["ip-version"] = "IPv4"
333 if RO_ip_profile.get("ip-version") == "ipv6":
334 RO_ip_profile["ip-version"] = "IPv6"
335 if "dhcp-params" in RO_ip_profile:
336 RO_ip_profile["dhcp"] = RO_ip_profile.pop("dhcp-params")
337 return RO_ip_profile
338
339 if not ns_params:
340 return None
341 RO_ns_params = {
342 # "name": ns_params["nsName"],
343 # "description": ns_params.get("nsDescription"),
344 "datacenter": vim_account_2_RO(ns_params["vimAccountId"]),
tiernob7f3f0d2019-03-20 17:17:21 +0000345 "wim_account": wim_account_2_RO(ns_params.get("wimAccountId")),
tierno59d22d22018-09-25 18:10:19 +0200346 # "scenario": ns_params["nsdId"],
tierno59d22d22018-09-25 18:10:19 +0200347 }
tiernoe95ed362020-04-23 08:24:57 +0000348 # set vim_account of each vnf if different from general vim_account.
349 # Get this information from <vnfr> database content, key vim-account-id
350 # Vim account can be set by placement_engine and it may be different from
351 # the instantiate parameters (vnfs.member-vnf-index.datacenter).
352 for vnf_index, vnfr in db_vnfrs.items():
353 if vnfr.get("vim-account-id") and vnfr["vim-account-id"] != ns_params["vimAccountId"]:
354 populate_dict(RO_ns_params, ("vnfs", vnf_index, "datacenter"), vim_account_2_RO(vnfr["vim-account-id"]))
quilesj7e13aeb2019-10-08 13:34:55 +0200355
tiernoe64f7fb2019-09-11 08:55:52 +0000356 n2vc_key_list = n2vc_key_list or []
357 for vnfd_ref, vnfd in vnfd_dict.items():
358 vdu_needed_access = []
359 mgmt_cp = None
360 if vnfd.get("vnf-configuration"):
tierno6cf25f52019-09-12 09:33:40 +0000361 ssh_required = deep_get(vnfd, ("vnf-configuration", "config-access", "ssh-access", "required"))
tiernoe64f7fb2019-09-11 08:55:52 +0000362 if ssh_required and vnfd.get("mgmt-interface"):
363 if vnfd["mgmt-interface"].get("vdu-id"):
364 vdu_needed_access.append(vnfd["mgmt-interface"]["vdu-id"])
365 elif vnfd["mgmt-interface"].get("cp"):
366 mgmt_cp = vnfd["mgmt-interface"]["cp"]
tierno27246d82018-09-27 15:59:09 +0200367
tiernoe64f7fb2019-09-11 08:55:52 +0000368 for vdu in vnfd.get("vdu", ()):
369 if vdu.get("vdu-configuration"):
tierno6cf25f52019-09-12 09:33:40 +0000370 ssh_required = deep_get(vdu, ("vdu-configuration", "config-access", "ssh-access", "required"))
tiernoe64f7fb2019-09-11 08:55:52 +0000371 if ssh_required:
tierno27246d82018-09-27 15:59:09 +0200372 vdu_needed_access.append(vdu["id"])
tiernoe64f7fb2019-09-11 08:55:52 +0000373 elif mgmt_cp:
374 for vdu_interface in vdu.get("interface"):
375 if vdu_interface.get("external-connection-point-ref") and \
376 vdu_interface["external-connection-point-ref"] == mgmt_cp:
377 vdu_needed_access.append(vdu["id"])
378 mgmt_cp = None
379 break
tierno27246d82018-09-27 15:59:09 +0200380
tiernoe64f7fb2019-09-11 08:55:52 +0000381 if vdu_needed_access:
382 for vnf_member in nsd.get("constituent-vnfd"):
383 if vnf_member["vnfd-id-ref"] != vnfd_ref:
384 continue
385 for vdu in vdu_needed_access:
386 populate_dict(RO_ns_params,
387 ("vnfs", vnf_member["member-vnf-index"], "vdus", vdu, "mgmt_keys"),
388 n2vc_key_list)
tierno27246d82018-09-27 15:59:09 +0200389
tierno25ec7732018-10-24 18:47:11 +0200390 if ns_params.get("vduImage"):
391 RO_ns_params["vduImage"] = ns_params["vduImage"]
392
tiernoc255a822018-10-31 09:41:53 +0100393 if ns_params.get("ssh_keys"):
394 RO_ns_params["cloud-config"] = {"key-pairs": ns_params["ssh_keys"]}
tierno27246d82018-09-27 15:59:09 +0200395 for vnf_params in get_iterable(ns_params, "vnf"):
396 for constituent_vnfd in nsd["constituent-vnfd"]:
397 if constituent_vnfd["member-vnf-index"] == vnf_params["member-vnf-index"]:
398 vnf_descriptor = vnfd_dict[constituent_vnfd["vnfd-id-ref"]]
399 break
400 else:
401 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index={} is not present at nsd:"
402 "constituent-vnfd".format(vnf_params["member-vnf-index"]))
tierno59d22d22018-09-25 18:10:19 +0200403
tierno27246d82018-09-27 15:59:09 +0200404 for vdu_params in get_iterable(vnf_params, "vdu"):
405 # TODO feature 1417: check that this VDU exist and it is not a PDU
406 if vdu_params.get("volume"):
407 for volume_params in vdu_params["volume"]:
408 if volume_params.get("vim-volume-id"):
409 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
410 vdu_params["id"], "devices", volume_params["name"], "vim_id"),
411 volume_params["vim-volume-id"])
412 if vdu_params.get("interface"):
413 for interface_params in vdu_params["interface"]:
414 if interface_params.get("ip-address"):
415 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
416 vdu_params["id"], "interfaces", interface_params["name"],
417 "ip_address"),
418 interface_params["ip-address"])
419 if interface_params.get("mac-address"):
420 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
421 vdu_params["id"], "interfaces", interface_params["name"],
422 "mac_address"),
423 interface_params["mac-address"])
424 if interface_params.get("floating-ip-required"):
425 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
426 vdu_params["id"], "interfaces", interface_params["name"],
427 "floating-ip"),
428 interface_params["floating-ip-required"])
429
430 for internal_vld_params in get_iterable(vnf_params, "internal-vld"):
431 if internal_vld_params.get("vim-network-name"):
432 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "networks",
433 internal_vld_params["name"], "vim-network-name"),
434 internal_vld_params["vim-network-name"])
gcalvino0d7ac8d2018-12-17 16:24:08 +0100435 if internal_vld_params.get("vim-network-id"):
436 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "networks",
437 internal_vld_params["name"], "vim-network-id"),
438 internal_vld_params["vim-network-id"])
tierno27246d82018-09-27 15:59:09 +0200439 if internal_vld_params.get("ip-profile"):
440 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "networks",
441 internal_vld_params["name"], "ip-profile"),
442 ip_profile_2_RO(internal_vld_params["ip-profile"]))
kbsub4d761eb2019-10-17 16:28:48 +0000443 if internal_vld_params.get("provider-network"):
444
445 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "networks",
446 internal_vld_params["name"], "provider-network"),
447 internal_vld_params["provider-network"].copy())
tierno27246d82018-09-27 15:59:09 +0200448
449 for icp_params in get_iterable(internal_vld_params, "internal-connection-point"):
450 # look for interface
451 iface_found = False
452 for vdu_descriptor in vnf_descriptor["vdu"]:
453 for vdu_interface in vdu_descriptor["interface"]:
454 if vdu_interface.get("internal-connection-point-ref") == icp_params["id-ref"]:
455 if icp_params.get("ip-address"):
456 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
457 vdu_descriptor["id"], "interfaces",
458 vdu_interface["name"], "ip_address"),
459 icp_params["ip-address"])
460
461 if icp_params.get("mac-address"):
462 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
463 vdu_descriptor["id"], "interfaces",
464 vdu_interface["name"], "mac_address"),
465 icp_params["mac-address"])
466 iface_found = True
tierno59d22d22018-09-25 18:10:19 +0200467 break
tierno27246d82018-09-27 15:59:09 +0200468 if iface_found:
469 break
470 else:
471 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
472 "internal-vld:id-ref={} is not present at vnfd:internal-"
473 "connection-point".format(vnf_params["member-vnf-index"],
474 icp_params["id-ref"]))
475
476 for vld_params in get_iterable(ns_params, "vld"):
477 if "ip-profile" in vld_params:
478 populate_dict(RO_ns_params, ("networks", vld_params["name"], "ip-profile"),
479 ip_profile_2_RO(vld_params["ip-profile"]))
tiernob7f3f0d2019-03-20 17:17:21 +0000480
kbsub4d761eb2019-10-17 16:28:48 +0000481 if vld_params.get("provider-network"):
482
483 populate_dict(RO_ns_params, ("networks", vld_params["name"], "provider-network"),
484 vld_params["provider-network"].copy())
485
tiernob7f3f0d2019-03-20 17:17:21 +0000486 if "wimAccountId" in vld_params and vld_params["wimAccountId"] is not None:
487 populate_dict(RO_ns_params, ("networks", vld_params["name"], "wim_account"),
488 wim_account_2_RO(vld_params["wimAccountId"])),
tierno27246d82018-09-27 15:59:09 +0200489 if vld_params.get("vim-network-name"):
490 RO_vld_sites = []
491 if isinstance(vld_params["vim-network-name"], dict):
492 for vim_account, vim_net in vld_params["vim-network-name"].items():
493 RO_vld_sites.append({
494 "netmap-use": vim_net,
495 "datacenter": vim_account_2_RO(vim_account)
496 })
497 else: # isinstance str
498 RO_vld_sites.append({"netmap-use": vld_params["vim-network-name"]})
499 if RO_vld_sites:
500 populate_dict(RO_ns_params, ("networks", vld_params["name"], "sites"), RO_vld_sites)
kbsub4d761eb2019-10-17 16:28:48 +0000501
gcalvino0d7ac8d2018-12-17 16:24:08 +0100502 if vld_params.get("vim-network-id"):
503 RO_vld_sites = []
504 if isinstance(vld_params["vim-network-id"], dict):
505 for vim_account, vim_net in vld_params["vim-network-id"].items():
506 RO_vld_sites.append({
507 "netmap-use": vim_net,
508 "datacenter": vim_account_2_RO(vim_account)
509 })
510 else: # isinstance str
511 RO_vld_sites.append({"netmap-use": vld_params["vim-network-id"]})
512 if RO_vld_sites:
513 populate_dict(RO_ns_params, ("networks", vld_params["name"], "sites"), RO_vld_sites)
Felipe Vicens720b07a2019-01-31 02:32:09 +0100514 if vld_params.get("ns-net"):
515 if isinstance(vld_params["ns-net"], dict):
516 for vld_id, instance_scenario_id in vld_params["ns-net"].items():
517 RO_vld_ns_net = {"instance_scenario_id": instance_scenario_id, "osm_id": vld_id}
Felipe Vicensb0e5fe42019-12-05 10:30:38 +0100518 populate_dict(RO_ns_params, ("networks", vld_params["name"], "use-network"), RO_vld_ns_net)
tierno27246d82018-09-27 15:59:09 +0200519 if "vnfd-connection-point-ref" in vld_params:
520 for cp_params in vld_params["vnfd-connection-point-ref"]:
521 # look for interface
522 for constituent_vnfd in nsd["constituent-vnfd"]:
523 if constituent_vnfd["member-vnf-index"] == cp_params["member-vnf-index-ref"]:
524 vnf_descriptor = vnfd_dict[constituent_vnfd["vnfd-id-ref"]]
525 break
526 else:
527 raise LcmException(
528 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={} "
529 "is not present at nsd:constituent-vnfd".format(cp_params["member-vnf-index-ref"]))
530 match_cp = False
531 for vdu_descriptor in vnf_descriptor["vdu"]:
532 for interface_descriptor in vdu_descriptor["interface"]:
533 if interface_descriptor.get("external-connection-point-ref") == \
534 cp_params["vnfd-connection-point-ref"]:
535 match_cp = True
tierno59d22d22018-09-25 18:10:19 +0200536 break
tierno27246d82018-09-27 15:59:09 +0200537 if match_cp:
538 break
539 else:
540 raise LcmException(
541 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={}:"
542 "vnfd-connection-point-ref={} is not present at vnfd={}".format(
543 cp_params["member-vnf-index-ref"],
544 cp_params["vnfd-connection-point-ref"],
545 vnf_descriptor["id"]))
546 if cp_params.get("ip-address"):
547 populate_dict(RO_ns_params, ("vnfs", cp_params["member-vnf-index-ref"], "vdus",
548 vdu_descriptor["id"], "interfaces",
549 interface_descriptor["name"], "ip_address"),
550 cp_params["ip-address"])
551 if cp_params.get("mac-address"):
552 populate_dict(RO_ns_params, ("vnfs", cp_params["member-vnf-index-ref"], "vdus",
553 vdu_descriptor["id"], "interfaces",
554 interface_descriptor["name"], "mac_address"),
555 cp_params["mac-address"])
tierno59d22d22018-09-25 18:10:19 +0200556 return RO_ns_params
557
tierno27246d82018-09-27 15:59:09 +0200558 def scale_vnfr(self, db_vnfr, vdu_create=None, vdu_delete=None):
559 # make a copy to do not change
560 vdu_create = copy(vdu_create)
561 vdu_delete = copy(vdu_delete)
562
563 vdurs = db_vnfr.get("vdur")
564 if vdurs is None:
565 vdurs = []
566 vdu_index = len(vdurs)
567 while vdu_index:
568 vdu_index -= 1
569 vdur = vdurs[vdu_index]
570 if vdur.get("pdu-type"):
571 continue
572 vdu_id_ref = vdur["vdu-id-ref"]
573 if vdu_create and vdu_create.get(vdu_id_ref):
574 for index in range(0, vdu_create[vdu_id_ref]):
575 vdur = deepcopy(vdur)
576 vdur["_id"] = str(uuid4())
577 vdur["count-index"] += 1
578 vdurs.insert(vdu_index+1+index, vdur)
579 del vdu_create[vdu_id_ref]
580 if vdu_delete and vdu_delete.get(vdu_id_ref):
581 del vdurs[vdu_index]
582 vdu_delete[vdu_id_ref] -= 1
583 if not vdu_delete[vdu_id_ref]:
584 del vdu_delete[vdu_id_ref]
585 # check all operations are done
586 if vdu_create or vdu_delete:
587 raise LcmException("Error scaling OUT VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
588 vdu_create))
589 if vdu_delete:
590 raise LcmException("Error scaling IN VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
591 vdu_delete))
592
593 vnfr_update = {"vdur": vdurs}
594 db_vnfr["vdur"] = vdurs
595 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
596
tiernof578e552018-11-08 19:07:20 +0100597 def ns_update_nsr(self, ns_update_nsr, db_nsr, nsr_desc_RO):
598 """
599 Updates database nsr with the RO info for the created vld
600 :param ns_update_nsr: dictionary to be filled with the updated info
601 :param db_nsr: content of db_nsr. This is also modified
602 :param nsr_desc_RO: nsr descriptor from RO
603 :return: Nothing, LcmException is raised on errors
604 """
605
606 for vld_index, vld in enumerate(get_iterable(db_nsr, "vld")):
607 for net_RO in get_iterable(nsr_desc_RO, "nets"):
608 if vld["id"] != net_RO.get("ns_net_osm_id"):
609 continue
610 vld["vim-id"] = net_RO.get("vim_net_id")
611 vld["name"] = net_RO.get("vim_name")
612 vld["status"] = net_RO.get("status")
613 vld["status-detailed"] = net_RO.get("error_msg")
614 ns_update_nsr["vld.{}".format(vld_index)] = vld
615 break
616 else:
617 raise LcmException("ns_update_nsr: Not found vld={} at RO info".format(vld["id"]))
618
tiernoe876f672020-02-13 14:34:48 +0000619 def set_vnfr_at_error(self, db_vnfrs, error_text):
620 try:
621 for db_vnfr in db_vnfrs.values():
622 vnfr_update = {"status": "ERROR"}
623 for vdu_index, vdur in enumerate(get_iterable(db_vnfr, "vdur")):
624 if "status" not in vdur:
625 vdur["status"] = "ERROR"
626 vnfr_update["vdur.{}.status".format(vdu_index)] = "ERROR"
627 if error_text:
628 vdur["status-detailed"] = str(error_text)
629 vnfr_update["vdur.{}.status-detailed".format(vdu_index)] = "ERROR"
630 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
631 except DbException as e:
632 self.logger.error("Cannot update vnf. {}".format(e))
633
tierno59d22d22018-09-25 18:10:19 +0200634 def ns_update_vnfr(self, db_vnfrs, nsr_desc_RO):
635 """
636 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 +0200637 :param db_vnfrs: dictionary with member-vnf-index: vnfr-content
638 :param nsr_desc_RO: nsr descriptor from RO
639 :return: Nothing, LcmException is raised on errors
tierno59d22d22018-09-25 18:10:19 +0200640 """
641 for vnf_index, db_vnfr in db_vnfrs.items():
642 for vnf_RO in nsr_desc_RO["vnfs"]:
tierno27246d82018-09-27 15:59:09 +0200643 if vnf_RO["member_vnf_index"] != vnf_index:
644 continue
645 vnfr_update = {}
tiernof578e552018-11-08 19:07:20 +0100646 if vnf_RO.get("ip_address"):
tierno1674de82019-04-09 13:03:14 +0000647 db_vnfr["ip-address"] = vnfr_update["ip-address"] = vnf_RO["ip_address"].split(";")[0]
tiernof578e552018-11-08 19:07:20 +0100648 elif not db_vnfr.get("ip-address"):
tierno0ec0c272020-02-19 17:43:01 +0000649 if db_vnfr.get("vdur"): # if not VDUs, there is not ip_address
650 raise LcmExceptionNoMgmtIP("ns member_vnf_index '{}' has no IP address".format(vnf_index))
tierno59d22d22018-09-25 18:10:19 +0200651
tierno27246d82018-09-27 15:59:09 +0200652 for vdu_index, vdur in enumerate(get_iterable(db_vnfr, "vdur")):
653 vdur_RO_count_index = 0
654 if vdur.get("pdu-type"):
655 continue
656 for vdur_RO in get_iterable(vnf_RO, "vms"):
657 if vdur["vdu-id-ref"] != vdur_RO["vdu_osm_id"]:
658 continue
659 if vdur["count-index"] != vdur_RO_count_index:
660 vdur_RO_count_index += 1
661 continue
662 vdur["vim-id"] = vdur_RO.get("vim_vm_id")
tierno1674de82019-04-09 13:03:14 +0000663 if vdur_RO.get("ip_address"):
664 vdur["ip-address"] = vdur_RO["ip_address"].split(";")[0]
tierno274ed572019-04-04 13:33:27 +0000665 else:
666 vdur["ip-address"] = None
tierno27246d82018-09-27 15:59:09 +0200667 vdur["vdu-id-ref"] = vdur_RO.get("vdu_osm_id")
668 vdur["name"] = vdur_RO.get("vim_name")
669 vdur["status"] = vdur_RO.get("status")
670 vdur["status-detailed"] = vdur_RO.get("error_msg")
671 for ifacer in get_iterable(vdur, "interfaces"):
672 for interface_RO in get_iterable(vdur_RO, "interfaces"):
673 if ifacer["name"] == interface_RO.get("internal_name"):
674 ifacer["ip-address"] = interface_RO.get("ip_address")
675 ifacer["mac-address"] = interface_RO.get("mac_address")
676 break
677 else:
678 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} interface={} "
quilesj7e13aeb2019-10-08 13:34:55 +0200679 "from VIM info"
680 .format(vnf_index, vdur["vdu-id-ref"], ifacer["name"]))
tierno27246d82018-09-27 15:59:09 +0200681 vnfr_update["vdur.{}".format(vdu_index)] = vdur
682 break
683 else:
tierno15b1cf12019-08-29 13:21:40 +0000684 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} count_index={} from "
685 "VIM info".format(vnf_index, vdur["vdu-id-ref"], vdur["count-index"]))
tiernof578e552018-11-08 19:07:20 +0100686
687 for vld_index, vld in enumerate(get_iterable(db_vnfr, "vld")):
688 for net_RO in get_iterable(nsr_desc_RO, "nets"):
689 if vld["id"] != net_RO.get("vnf_net_osm_id"):
690 continue
691 vld["vim-id"] = net_RO.get("vim_net_id")
692 vld["name"] = net_RO.get("vim_name")
693 vld["status"] = net_RO.get("status")
694 vld["status-detailed"] = net_RO.get("error_msg")
695 vnfr_update["vld.{}".format(vld_index)] = vld
696 break
697 else:
tierno15b1cf12019-08-29 13:21:40 +0000698 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vld={} from VIM info".format(
tiernof578e552018-11-08 19:07:20 +0100699 vnf_index, vld["id"]))
700
tierno27246d82018-09-27 15:59:09 +0200701 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
702 break
tierno59d22d22018-09-25 18:10:19 +0200703
704 else:
tierno15b1cf12019-08-29 13:21:40 +0000705 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} from VIM info".format(vnf_index))
tierno59d22d22018-09-25 18:10:19 +0200706
tierno5ee02052019-12-05 19:55:02 +0000707 def _get_ns_config_info(self, nsr_id):
tiernoc3f2a822019-11-05 13:45:04 +0000708 """
709 Generates a mapping between vnf,vdu elements and the N2VC id
tierno5ee02052019-12-05 19:55:02 +0000710 :param nsr_id: id of nsr to get last database _admin.deployed.VCA that contains this list
tiernoc3f2a822019-11-05 13:45:04 +0000711 :return: a dictionary with {osm-config-mapping: {}} where its element contains:
712 "<member-vnf-index>": <N2VC-id> for a vnf configuration, or
713 "<member-vnf-index>.<vdu.id>.<vdu replica(0, 1,..)>": <N2VC-id> for a vdu configuration
714 """
tierno5ee02052019-12-05 19:55:02 +0000715 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
716 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
tiernoc3f2a822019-11-05 13:45:04 +0000717 mapping = {}
718 ns_config_info = {"osm-config-mapping": mapping}
719 for vca in vca_deployed_list:
720 if not vca["member-vnf-index"]:
721 continue
722 if not vca["vdu_id"]:
723 mapping[vca["member-vnf-index"]] = vca["application"]
724 else:
725 mapping["{}.{}.{}".format(vca["member-vnf-index"], vca["vdu_id"], vca["vdu_count_index"])] =\
726 vca["application"]
727 return ns_config_info
728
729 @staticmethod
730 def _get_initial_config_primitive_list(desc_primitive_list, vca_deployed):
731 """
732 Generates a list of initial-config-primitive based on the list provided by the descriptor. It includes internal
733 primitives as verify-ssh-credentials, or config when needed
734 :param desc_primitive_list: information of the descriptor
735 :param vca_deployed: information of the deployed, needed for known if it is related to an NS, VNF, VDU and if
736 this element contains a ssh public key
737 :return: The modified list. Can ba an empty list, but always a list
738 """
739 if desc_primitive_list:
740 primitive_list = desc_primitive_list.copy()
741 else:
742 primitive_list = []
743 # look for primitive config, and get the position. None if not present
744 config_position = None
745 for index, primitive in enumerate(primitive_list):
746 if primitive["name"] == "config":
747 config_position = index
748 break
749
750 # for NS, add always a config primitive if not present (bug 874)
751 if not vca_deployed["member-vnf-index"] and config_position is None:
752 primitive_list.insert(0, {"name": "config", "parameter": []})
753 config_position = 0
754 # for VNF/VDU add verify-ssh-credentials after config
755 if vca_deployed["member-vnf-index"] and config_position is not None and vca_deployed.get("ssh-public-key"):
756 primitive_list.insert(config_position + 1, {"name": "verify-ssh-credentials", "parameter": []})
757 return primitive_list
758
tiernoe876f672020-02-13 14:34:48 +0000759 async def instantiate_RO(self, logging_text, nsr_id, nsd, db_nsr, db_nslcmop, db_vnfrs, db_vnfds_ref,
760 n2vc_key_list, stage):
tiernoe95ed362020-04-23 08:24:57 +0000761 """
762 Instantiate at RO
763 :param logging_text: preffix text to use at logging
764 :param nsr_id: nsr identity
765 :param nsd: database content of ns descriptor
766 :param db_nsr: database content of ns record
767 :param db_nslcmop: database content of ns operation, in this case, 'instantiate'
768 :param db_vnfrs:
769 :param db_vnfds_ref: database content of vnfds, indexed by id (not _id). {id: {vnfd_object}, ...}
770 :param n2vc_key_list: ssh-public-key list to be inserted to management vdus via cloud-init
771 :param stage: list with 3 items: [general stage, tasks, vim_specific]. This task will write over vim_specific
772 :return: None or exception
773 """
tiernoe876f672020-02-13 14:34:48 +0000774 try:
775 db_nsr_update = {}
776 RO_descriptor_number = 0 # number of descriptors created at RO
777 vnf_index_2_RO_id = {} # map between vnfd/nsd id to the id used at RO
778 nslcmop_id = db_nslcmop["_id"]
779 start_deploy = time()
780 ns_params = db_nslcmop.get("operationParams")
781 if ns_params and ns_params.get("timeout_ns_deploy"):
782 timeout_ns_deploy = ns_params["timeout_ns_deploy"]
783 else:
784 timeout_ns_deploy = self.timeout.get("ns_deploy", self.timeout_ns_deploy)
quilesj7e13aeb2019-10-08 13:34:55 +0200785
tiernoe876f672020-02-13 14:34:48 +0000786 # Check for and optionally request placement optimization. Database will be updated if placement activated
787 stage[2] = "Waiting for Placement."
tierno8790a3d2020-04-23 22:49:52 +0000788 if await self._do_placement(logging_text, db_nslcmop, db_vnfrs):
789 # in case of placement change ns_params[vimAcountId) if not present at any vnfrs
790 for vnfr in db_vnfrs.values():
791 if ns_params["vimAccountId"] == vnfr["vim-account-id"]:
792 break
793 else:
794 ns_params["vimAccountId"] == vnfr["vim-account-id"]
quilesj7e13aeb2019-10-08 13:34:55 +0200795
tiernoe876f672020-02-13 14:34:48 +0000796 # deploy RO
tiernoe876f672020-02-13 14:34:48 +0000797 # get vnfds, instantiate at RO
798 for c_vnf in nsd.get("constituent-vnfd", ()):
799 member_vnf_index = c_vnf["member-vnf-index"]
800 vnfd = db_vnfds_ref[c_vnf['vnfd-id-ref']]
801 vnfd_ref = vnfd["id"]
quilesj7e13aeb2019-10-08 13:34:55 +0200802
tiernoe876f672020-02-13 14:34:48 +0000803 stage[2] = "Creating vnfd='{}' member_vnf_index='{}' at RO".format(vnfd_ref, member_vnf_index)
804 db_nsr_update["detailed-status"] = " ".join(stage)
805 self.update_db_2("nsrs", nsr_id, db_nsr_update)
806 self._write_op_status(nslcmop_id, stage)
calvinosanch9f9c6f22019-11-04 13:37:39 +0100807
tiernoe876f672020-02-13 14:34:48 +0000808 # self.logger.debug(logging_text + stage[2])
809 vnfd_id_RO = "{}.{}.{}".format(nsr_id, RO_descriptor_number, member_vnf_index[:23])
810 vnf_index_2_RO_id[member_vnf_index] = vnfd_id_RO
811 RO_descriptor_number += 1
812
813 # look position at deployed.RO.vnfd if not present it will be appended at the end
814 for index, vnf_deployed in enumerate(db_nsr["_admin"]["deployed"]["RO"]["vnfd"]):
815 if vnf_deployed["member-vnf-index"] == member_vnf_index:
816 break
817 else:
818 index = len(db_nsr["_admin"]["deployed"]["RO"]["vnfd"])
819 db_nsr["_admin"]["deployed"]["RO"]["vnfd"].append(None)
820
821 # look if present
822 RO_update = {"member-vnf-index": member_vnf_index}
823 vnfd_list = await self.RO.get_list("vnfd", filter_by={"osm_id": vnfd_id_RO})
824 if vnfd_list:
825 RO_update["id"] = vnfd_list[0]["uuid"]
826 self.logger.debug(logging_text + "vnfd='{}' member_vnf_index='{}' exists at RO. Using RO_id={}".
827 format(vnfd_ref, member_vnf_index, vnfd_list[0]["uuid"]))
828 else:
829 vnfd_RO = self.vnfd2RO(vnfd, vnfd_id_RO, db_vnfrs[c_vnf["member-vnf-index"]].
830 get("additionalParamsForVnf"), nsr_id)
831 desc = await self.RO.create("vnfd", descriptor=vnfd_RO)
832 RO_update["id"] = desc["uuid"]
833 self.logger.debug(logging_text + "vnfd='{}' member_vnf_index='{}' created at RO. RO_id={}".format(
834 vnfd_ref, member_vnf_index, desc["uuid"]))
835 db_nsr_update["_admin.deployed.RO.vnfd.{}".format(index)] = RO_update
836 db_nsr["_admin"]["deployed"]["RO"]["vnfd"][index] = RO_update
837
838 # create nsd at RO
839 nsd_ref = nsd["id"]
840
841 stage[2] = "Creating nsd={} at RO".format(nsd_ref)
842 db_nsr_update["detailed-status"] = " ".join(stage)
843 self.update_db_2("nsrs", nsr_id, db_nsr_update)
844 self._write_op_status(nslcmop_id, stage)
845
846 # self.logger.debug(logging_text + stage[2])
847 RO_osm_nsd_id = "{}.{}.{}".format(nsr_id, RO_descriptor_number, nsd_ref[:23])
tiernod8323042019-08-09 11:32:23 +0000848 RO_descriptor_number += 1
tiernoe876f672020-02-13 14:34:48 +0000849 nsd_list = await self.RO.get_list("nsd", filter_by={"osm_id": RO_osm_nsd_id})
850 if nsd_list:
851 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = nsd_list[0]["uuid"]
852 self.logger.debug(logging_text + "nsd={} exists at RO. Using RO_id={}".format(
853 nsd_ref, RO_nsd_uuid))
tiernod8323042019-08-09 11:32:23 +0000854 else:
tiernoe876f672020-02-13 14:34:48 +0000855 nsd_RO = deepcopy(nsd)
856 nsd_RO["id"] = RO_osm_nsd_id
857 nsd_RO.pop("_id", None)
858 nsd_RO.pop("_admin", None)
859 for c_vnf in nsd_RO.get("constituent-vnfd", ()):
860 member_vnf_index = c_vnf["member-vnf-index"]
861 c_vnf["vnfd-id-ref"] = vnf_index_2_RO_id[member_vnf_index]
862 for c_vld in nsd_RO.get("vld", ()):
863 for cp in c_vld.get("vnfd-connection-point-ref", ()):
864 member_vnf_index = cp["member-vnf-index-ref"]
865 cp["vnfd-id-ref"] = vnf_index_2_RO_id[member_vnf_index]
tiernod8323042019-08-09 11:32:23 +0000866
tiernoe876f672020-02-13 14:34:48 +0000867 desc = await self.RO.create("nsd", descriptor=nsd_RO)
868 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
869 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = desc["uuid"]
870 self.logger.debug(logging_text + "nsd={} created at RO. RO_id={}".format(nsd_ref, RO_nsd_uuid))
tiernod8323042019-08-09 11:32:23 +0000871 self.update_db_2("nsrs", nsr_id, db_nsr_update)
872
tiernoe876f672020-02-13 14:34:48 +0000873 # Crate ns at RO
874 stage[2] = "Creating nsd={} at RO".format(nsd_ref)
875 db_nsr_update["detailed-status"] = " ".join(stage)
876 self.update_db_2("nsrs", nsr_id, db_nsr_update)
877 self._write_op_status(nslcmop_id, stage)
tiernod8323042019-08-09 11:32:23 +0000878
tiernoe876f672020-02-13 14:34:48 +0000879 # if present use it unless in error status
880 RO_nsr_id = deep_get(db_nsr, ("_admin", "deployed", "RO", "nsr_id"))
881 if RO_nsr_id:
882 try:
883 stage[2] = "Looking for existing ns at RO"
884 db_nsr_update["detailed-status"] = " ".join(stage)
885 self.update_db_2("nsrs", nsr_id, db_nsr_update)
886 self._write_op_status(nslcmop_id, stage)
887 # self.logger.debug(logging_text + stage[2] + " RO_ns_id={}".format(RO_nsr_id))
888 desc = await self.RO.show("ns", RO_nsr_id)
tiernod8323042019-08-09 11:32:23 +0000889
tiernoe876f672020-02-13 14:34:48 +0000890 except ROclient.ROClientException as e:
891 if e.http_code != HTTPStatus.NOT_FOUND:
892 raise
893 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
894 if RO_nsr_id:
895 ns_status, ns_status_info = self.RO.check_ns_status(desc)
896 db_nsr_update["_admin.deployed.RO.nsr_status"] = ns_status
897 if ns_status == "ERROR":
898 stage[2] = "Deleting ns at RO. RO_ns_id={}".format(RO_nsr_id)
899 self.logger.debug(logging_text + stage[2])
900 await self.RO.delete("ns", RO_nsr_id)
901 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
902 if not RO_nsr_id:
903 stage[2] = "Checking dependencies"
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 # self.logger.debug(logging_text + stage[2])
tiernod8323042019-08-09 11:32:23 +0000908
tiernoe876f672020-02-13 14:34:48 +0000909 # check if VIM is creating and wait look if previous tasks in process
910 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account", ns_params["vimAccountId"])
911 if task_dependency:
912 stage[2] = "Waiting for related tasks '{}' to be completed".format(task_name)
913 self.logger.debug(logging_text + stage[2])
914 await asyncio.wait(task_dependency, timeout=3600)
915 if ns_params.get("vnf"):
916 for vnf in ns_params["vnf"]:
917 if "vimAccountId" in vnf:
918 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account",
919 vnf["vimAccountId"])
920 if task_dependency:
921 stage[2] = "Waiting for related tasks '{}' to be completed.".format(task_name)
922 self.logger.debug(logging_text + stage[2])
923 await asyncio.wait(task_dependency, timeout=3600)
924
925 stage[2] = "Checking instantiation parameters."
tiernoe95ed362020-04-23 08:24:57 +0000926 RO_ns_params = self._ns_params_2_RO(ns_params, nsd, db_vnfds_ref, db_vnfrs, n2vc_key_list)
tiernoe876f672020-02-13 14:34:48 +0000927 stage[2] = "Deploying ns at VIM."
928 db_nsr_update["detailed-status"] = " ".join(stage)
929 self.update_db_2("nsrs", nsr_id, db_nsr_update)
930 self._write_op_status(nslcmop_id, stage)
931
932 desc = await self.RO.create("ns", descriptor=RO_ns_params, name=db_nsr["name"], scenario=RO_nsd_uuid)
933 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = desc["uuid"]
934 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
935 db_nsr_update["_admin.deployed.RO.nsr_status"] = "BUILD"
936 self.logger.debug(logging_text + "ns created at RO. RO_id={}".format(desc["uuid"]))
937
938 # wait until NS is ready
939 stage[2] = "Waiting VIM to deploy ns."
940 db_nsr_update["detailed-status"] = " ".join(stage)
941 self.update_db_2("nsrs", nsr_id, db_nsr_update)
942 self._write_op_status(nslcmop_id, stage)
943 detailed_status_old = None
944 self.logger.debug(logging_text + stage[2] + " RO_ns_id={}".format(RO_nsr_id))
945
946 old_desc = None
947 while time() <= start_deploy + timeout_ns_deploy:
tiernod8323042019-08-09 11:32:23 +0000948 desc = await self.RO.show("ns", RO_nsr_id)
quilesj3655ae02019-12-12 16:08:35 +0000949
tiernoe876f672020-02-13 14:34:48 +0000950 # deploymentStatus
951 if desc != old_desc:
952 # desc has changed => update db
953 self._on_update_ro_db(nsrs_id=nsr_id, ro_descriptor=desc)
954 old_desc = desc
tiernod8323042019-08-09 11:32:23 +0000955
tiernoe876f672020-02-13 14:34:48 +0000956 ns_status, ns_status_info = self.RO.check_ns_status(desc)
957 db_nsr_update["_admin.deployed.RO.nsr_status"] = ns_status
958 if ns_status == "ERROR":
959 raise ROclient.ROClientException(ns_status_info)
960 elif ns_status == "BUILD":
961 stage[2] = "VIM: ({})".format(ns_status_info)
962 elif ns_status == "ACTIVE":
963 stage[2] = "Waiting for management IP address reported by the VIM. Updating VNFRs."
964 try:
965 self.ns_update_vnfr(db_vnfrs, desc)
966 break
967 except LcmExceptionNoMgmtIP:
968 pass
969 else:
970 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
971 if stage[2] != detailed_status_old:
972 detailed_status_old = stage[2]
973 db_nsr_update["detailed-status"] = " ".join(stage)
974 self.update_db_2("nsrs", nsr_id, db_nsr_update)
975 self._write_op_status(nslcmop_id, stage)
976 await asyncio.sleep(5, loop=self.loop)
977 else: # timeout_ns_deploy
978 raise ROclient.ROClientException("Timeout waiting ns to be ready")
tiernod8323042019-08-09 11:32:23 +0000979
tiernoe876f672020-02-13 14:34:48 +0000980 # Updating NSR
981 self.ns_update_nsr(db_nsr_update, db_nsr, desc)
tiernod8323042019-08-09 11:32:23 +0000982
tiernoe876f672020-02-13 14:34:48 +0000983 db_nsr_update["_admin.deployed.RO.operational-status"] = "running"
984 # db_nsr["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
985 stage[2] = "Deployed at VIM"
986 db_nsr_update["detailed-status"] = " ".join(stage)
987 self.update_db_2("nsrs", nsr_id, db_nsr_update)
988 self._write_op_status(nslcmop_id, stage)
989 # await self._on_update_n2vc_db("nsrs", {"_id": nsr_id}, "_admin.deployed", db_nsr_update)
990 # self.logger.debug(logging_text + "Deployed at VIM")
991 except (ROclient.ROClientException, LcmException, DbException) as e:
tierno067e04a2020-03-31 12:53:13 +0000992 stage[2] = "ERROR deploying at VIM"
tiernoe876f672020-02-13 14:34:48 +0000993 self.set_vnfr_at_error(db_vnfrs, str(e))
994 raise
quilesj7e13aeb2019-10-08 13:34:55 +0200995
tiernoa5088192019-11-26 16:12:53 +0000996 async def wait_vm_up_insert_key_ro(self, logging_text, nsr_id, vnfr_id, vdu_id, vdu_index, pub_key=None, user=None):
997 """
998 Wait for ip addres at RO, and optionally, insert public key in virtual machine
999 :param logging_text: prefix use for logging
1000 :param nsr_id:
1001 :param vnfr_id:
1002 :param vdu_id:
1003 :param vdu_index:
1004 :param pub_key: public ssh key to inject, None to skip
1005 :param user: user to apply the public ssh key
1006 :return: IP address
1007 """
quilesj7e13aeb2019-10-08 13:34:55 +02001008
tiernoa5088192019-11-26 16:12:53 +00001009 # self.logger.debug(logging_text + "Starting wait_vm_up_insert_key_ro")
tiernod8323042019-08-09 11:32:23 +00001010 ro_nsr_id = None
1011 ip_address = None
1012 nb_tries = 0
1013 target_vdu_id = None
quilesj3149f262019-12-03 10:58:10 +00001014 ro_retries = 0
quilesj7e13aeb2019-10-08 13:34:55 +02001015
tiernod8323042019-08-09 11:32:23 +00001016 while True:
quilesj7e13aeb2019-10-08 13:34:55 +02001017
quilesj3149f262019-12-03 10:58:10 +00001018 ro_retries += 1
1019 if ro_retries >= 360: # 1 hour
1020 raise LcmException("Not found _admin.deployed.RO.nsr_id for nsr_id: {}".format(nsr_id))
1021
tiernod8323042019-08-09 11:32:23 +00001022 await asyncio.sleep(10, loop=self.loop)
quilesj7e13aeb2019-10-08 13:34:55 +02001023
1024 # get ip address
tiernod8323042019-08-09 11:32:23 +00001025 if not target_vdu_id:
1026 db_vnfr = self.db.get_one("vnfrs", {"_id": vnfr_id})
quilesj3149f262019-12-03 10:58:10 +00001027
1028 if not vdu_id: # for the VNF case
tiernoe876f672020-02-13 14:34:48 +00001029 if db_vnfr.get("status") == "ERROR":
1030 raise LcmException("Cannot inject ssh-key because target VNF is in error state")
tiernod8323042019-08-09 11:32:23 +00001031 ip_address = db_vnfr.get("ip-address")
1032 if not ip_address:
1033 continue
quilesj3149f262019-12-03 10:58:10 +00001034 vdur = next((x for x in get_iterable(db_vnfr, "vdur") if x.get("ip-address") == ip_address), None)
1035 else: # VDU case
1036 vdur = next((x for x in get_iterable(db_vnfr, "vdur")
1037 if x.get("vdu-id-ref") == vdu_id and x.get("count-index") == vdu_index), None)
1038
tierno0e8c3f02020-03-12 17:18:21 +00001039 if not vdur and len(db_vnfr.get("vdur", ())) == 1: # If only one, this should be the target vdu
1040 vdur = db_vnfr["vdur"][0]
quilesj3149f262019-12-03 10:58:10 +00001041 if not vdur:
tierno0e8c3f02020-03-12 17:18:21 +00001042 raise LcmException("Not found vnfr_id={}, vdu_id={}, vdu_index={}".format(vnfr_id, vdu_id,
1043 vdu_index))
quilesj7e13aeb2019-10-08 13:34:55 +02001044
tierno0e8c3f02020-03-12 17:18:21 +00001045 if vdur.get("pdu-type") or vdur.get("status") == "ACTIVE":
quilesj3149f262019-12-03 10:58:10 +00001046 ip_address = vdur.get("ip-address")
1047 if not ip_address:
1048 continue
1049 target_vdu_id = vdur["vdu-id-ref"]
1050 elif vdur.get("status") == "ERROR":
1051 raise LcmException("Cannot inject ssh-key because target VM is in error state")
1052
tiernod8323042019-08-09 11:32:23 +00001053 if not target_vdu_id:
1054 continue
tiernod8323042019-08-09 11:32:23 +00001055
quilesj7e13aeb2019-10-08 13:34:55 +02001056 # inject public key into machine
1057 if pub_key and user:
tiernoe876f672020-02-13 14:34:48 +00001058 # wait until NS is deployed at RO
1059 if not ro_nsr_id:
1060 db_nsrs = self.db.get_one("nsrs", {"_id": nsr_id})
1061 ro_nsr_id = deep_get(db_nsrs, ("_admin", "deployed", "RO", "nsr_id"))
1062 if not ro_nsr_id:
1063 continue
1064
tiernoa5088192019-11-26 16:12:53 +00001065 # self.logger.debug(logging_text + "Inserting RO key")
tierno0e8c3f02020-03-12 17:18:21 +00001066 if vdur.get("pdu-type"):
1067 self.logger.error(logging_text + "Cannot inject ssh-ky to a PDU")
1068 return ip_address
quilesj7e13aeb2019-10-08 13:34:55 +02001069 try:
1070 ro_vm_id = "{}-{}".format(db_vnfr["member-vnf-index-ref"], target_vdu_id) # TODO add vdu_index
1071 result_dict = await self.RO.create_action(
1072 item="ns",
1073 item_id_name=ro_nsr_id,
1074 descriptor={"add_public_key": pub_key, "vms": [ro_vm_id], "user": user}
1075 )
1076 # result_dict contains the format {VM-id: {vim_result: 200, description: text}}
1077 if not result_dict or not isinstance(result_dict, dict):
1078 raise LcmException("Unknown response from RO when injecting key")
1079 for result in result_dict.values():
1080 if result.get("vim_result") == 200:
1081 break
1082 else:
1083 raise ROclient.ROClientException("error injecting key: {}".format(
1084 result.get("description")))
1085 break
1086 except ROclient.ROClientException as e:
tiernoa5088192019-11-26 16:12:53 +00001087 if not nb_tries:
1088 self.logger.debug(logging_text + "error injecting key: {}. Retrying until {} seconds".
1089 format(e, 20*10))
quilesj7e13aeb2019-10-08 13:34:55 +02001090 nb_tries += 1
tiernoa5088192019-11-26 16:12:53 +00001091 if nb_tries >= 20:
quilesj7e13aeb2019-10-08 13:34:55 +02001092 raise LcmException("Reaching max tries injecting key. Error: {}".format(e))
quilesj7e13aeb2019-10-08 13:34:55 +02001093 else:
quilesj7e13aeb2019-10-08 13:34:55 +02001094 break
1095
1096 return ip_address
1097
tierno5ee02052019-12-05 19:55:02 +00001098 async def _wait_dependent_n2vc(self, nsr_id, vca_deployed_list, vca_index):
1099 """
1100 Wait until dependent VCA deployments have been finished. NS wait for VNFs and VDUs. VNFs for VDUs
1101 """
1102 my_vca = vca_deployed_list[vca_index]
1103 if my_vca.get("vdu_id") or my_vca.get("kdu_name"):
quilesj3655ae02019-12-12 16:08:35 +00001104 # vdu or kdu: no dependencies
tierno5ee02052019-12-05 19:55:02 +00001105 return
1106 timeout = 300
1107 while timeout >= 0:
quilesj3655ae02019-12-12 16:08:35 +00001108 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1109 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
1110 configuration_status_list = db_nsr["configurationStatus"]
1111 for index, vca_deployed in enumerate(configuration_status_list):
tierno5ee02052019-12-05 19:55:02 +00001112 if index == vca_index:
quilesj3655ae02019-12-12 16:08:35 +00001113 # myself
tierno5ee02052019-12-05 19:55:02 +00001114 continue
1115 if not my_vca.get("member-vnf-index") or \
1116 (vca_deployed.get("member-vnf-index") == my_vca.get("member-vnf-index")):
quilesj3655ae02019-12-12 16:08:35 +00001117 internal_status = configuration_status_list[index].get("status")
1118 if internal_status == 'READY':
1119 continue
1120 elif internal_status == 'BROKEN':
tierno5ee02052019-12-05 19:55:02 +00001121 raise LcmException("Configuration aborted because dependent charm/s has failed")
quilesj3655ae02019-12-12 16:08:35 +00001122 else:
1123 break
tierno5ee02052019-12-05 19:55:02 +00001124 else:
quilesj3655ae02019-12-12 16:08:35 +00001125 # no dependencies, return
tierno5ee02052019-12-05 19:55:02 +00001126 return
1127 await asyncio.sleep(10)
1128 timeout -= 1
tierno5ee02052019-12-05 19:55:02 +00001129
1130 raise LcmException("Configuration aborted because dependent charm/s timeout")
1131
tiernoe876f672020-02-13 14:34:48 +00001132 async def instantiate_N2VC(self, logging_text, vca_index, nsi_id, db_nsr, db_vnfr, vdu_id, kdu_name, vdu_index,
1133 config_descriptor, deploy_params, base_folder, nslcmop_id, stage):
tiernod8323042019-08-09 11:32:23 +00001134 nsr_id = db_nsr["_id"]
1135 db_update_entry = "_admin.deployed.VCA.{}.".format(vca_index)
tiernoda6fb102019-11-23 00:36:52 +00001136 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
tiernod8323042019-08-09 11:32:23 +00001137 vca_deployed = db_nsr["_admin"]["deployed"]["VCA"][vca_index]
quilesj7e13aeb2019-10-08 13:34:55 +02001138 db_dict = {
1139 'collection': 'nsrs',
1140 'filter': {'_id': nsr_id},
1141 'path': db_update_entry
1142 }
tiernod8323042019-08-09 11:32:23 +00001143 step = ""
1144 try:
quilesj3655ae02019-12-12 16:08:35 +00001145
1146 element_type = 'NS'
1147 element_under_configuration = nsr_id
1148
tiernod8323042019-08-09 11:32:23 +00001149 vnfr_id = None
1150 if db_vnfr:
1151 vnfr_id = db_vnfr["_id"]
1152
1153 namespace = "{nsi}.{ns}".format(
1154 nsi=nsi_id if nsi_id else "",
1155 ns=nsr_id)
quilesj3655ae02019-12-12 16:08:35 +00001156
tiernod8323042019-08-09 11:32:23 +00001157 if vnfr_id:
quilesj3655ae02019-12-12 16:08:35 +00001158 element_type = 'VNF'
1159 element_under_configuration = vnfr_id
quilesjb8a35dd2020-01-09 15:10:14 +00001160 namespace += ".{}".format(vnfr_id)
tiernod8323042019-08-09 11:32:23 +00001161 if vdu_id:
1162 namespace += ".{}-{}".format(vdu_id, vdu_index or 0)
quilesj3655ae02019-12-12 16:08:35 +00001163 element_type = 'VDU'
quilesjb8a35dd2020-01-09 15:10:14 +00001164 element_under_configuration = "{}-{}".format(vdu_id, vdu_index or 0)
tierno51183952020-04-03 15:48:18 +00001165 elif kdu_name:
1166 namespace += ".{}".format(kdu_name)
1167 element_type = 'KDU'
1168 element_under_configuration = kdu_name
tiernod8323042019-08-09 11:32:23 +00001169
1170 # Get artifact path
David Garcia56522772020-01-20 13:19:29 +01001171 self.fs.sync() # Sync from FSMongo
David Garcia485b2912019-12-04 14:01:50 +01001172 artifact_path = "{}/{}/charms/{}".format(
tiernod8323042019-08-09 11:32:23 +00001173 base_folder["folder"],
1174 base_folder["pkg-dir"],
1175 config_descriptor["juju"]["charm"]
1176 )
1177
quilesj7e13aeb2019-10-08 13:34:55 +02001178 is_proxy_charm = deep_get(config_descriptor, ('juju', 'charm')) is not None
1179 if deep_get(config_descriptor, ('juju', 'proxy')) is False:
tiernod8323042019-08-09 11:32:23 +00001180 is_proxy_charm = False
1181
1182 # n2vc_redesign STEP 3.1
quilesj7e13aeb2019-10-08 13:34:55 +02001183
1184 # find old ee_id if exists
tiernod8323042019-08-09 11:32:23 +00001185 ee_id = vca_deployed.get("ee_id")
tiernod8323042019-08-09 11:32:23 +00001186
quilesj7e13aeb2019-10-08 13:34:55 +02001187 # create or register execution environment in VCA
1188 if is_proxy_charm:
quilesj3655ae02019-12-12 16:08:35 +00001189
tiernoc231a872020-01-21 08:49:05 +00001190 self._write_configuration_status(
quilesj3655ae02019-12-12 16:08:35 +00001191 nsr_id=nsr_id,
1192 vca_index=vca_index,
1193 status='CREATING',
1194 element_under_configuration=element_under_configuration,
1195 element_type=element_type
1196 )
1197
quilesj7e13aeb2019-10-08 13:34:55 +02001198 step = "create execution environment"
1199 self.logger.debug(logging_text + step)
tierno3bedc9b2019-11-27 15:46:57 +00001200 ee_id, credentials = await self.n2vc.create_execution_environment(namespace=namespace,
1201 reuse_ee_id=ee_id,
1202 db_dict=db_dict)
quilesj3655ae02019-12-12 16:08:35 +00001203
quilesj7e13aeb2019-10-08 13:34:55 +02001204 else:
tierno3bedc9b2019-11-27 15:46:57 +00001205 step = "Waiting to VM being up and getting IP address"
1206 self.logger.debug(logging_text + step)
1207 rw_mgmt_ip = await self.wait_vm_up_insert_key_ro(logging_text, nsr_id, vnfr_id, vdu_id, vdu_index,
1208 user=None, pub_key=None)
1209 credentials = {"hostname": rw_mgmt_ip}
quilesj7e13aeb2019-10-08 13:34:55 +02001210 # get username
tierno3bedc9b2019-11-27 15:46:57 +00001211 username = deep_get(config_descriptor, ("config-access", "ssh-access", "default-user"))
quilesj7e13aeb2019-10-08 13:34:55 +02001212 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1213 # merged. Meanwhile let's get username from initial-config-primitive
tierno3bedc9b2019-11-27 15:46:57 +00001214 if not username and config_descriptor.get("initial-config-primitive"):
1215 for config_primitive in config_descriptor["initial-config-primitive"]:
1216 for param in config_primitive.get("parameter", ()):
1217 if param["name"] == "ssh-username":
1218 username = param["value"]
1219 break
1220 if not username:
1221 raise LcmException("Cannot determine the username neither with 'initial-config-promitive' nor with "
1222 "'config-access.ssh-access.default-user'")
1223 credentials["username"] = username
quilesj7e13aeb2019-10-08 13:34:55 +02001224 # n2vc_redesign STEP 3.2
tierno3bedc9b2019-11-27 15:46:57 +00001225
tiernoc231a872020-01-21 08:49:05 +00001226 self._write_configuration_status(
quilesj3655ae02019-12-12 16:08:35 +00001227 nsr_id=nsr_id,
1228 vca_index=vca_index,
1229 status='REGISTERING',
1230 element_under_configuration=element_under_configuration,
1231 element_type=element_type
1232 )
1233
tierno3bedc9b2019-11-27 15:46:57 +00001234 step = "register execution environment {}".format(credentials)
quilesj7e13aeb2019-10-08 13:34:55 +02001235 self.logger.debug(logging_text + step)
tierno3bedc9b2019-11-27 15:46:57 +00001236 ee_id = await self.n2vc.register_execution_environment(credentials=credentials, namespace=namespace,
1237 db_dict=db_dict)
quilesj7e13aeb2019-10-08 13:34:55 +02001238
1239 # for compatibility with MON/POL modules, the need model and application name at database
1240 # TODO ask to N2VC instead of assuming the format "model_name.application_name"
1241 ee_id_parts = ee_id.split('.')
1242 model_name = ee_id_parts[0]
1243 application_name = ee_id_parts[1]
tierno51183952020-04-03 15:48:18 +00001244 db_nsr_update = {db_update_entry + "model": model_name,
1245 db_update_entry + "application": application_name,
1246 db_update_entry + "ee_id": ee_id}
tiernod8323042019-08-09 11:32:23 +00001247
1248 # n2vc_redesign STEP 3.3
tierno3bedc9b2019-11-27 15:46:57 +00001249
tiernod8323042019-08-09 11:32:23 +00001250 step = "Install configuration Software"
quilesj3655ae02019-12-12 16:08:35 +00001251
tiernoc231a872020-01-21 08:49:05 +00001252 self._write_configuration_status(
quilesj3655ae02019-12-12 16:08:35 +00001253 nsr_id=nsr_id,
1254 vca_index=vca_index,
1255 status='INSTALLING SW',
1256 element_under_configuration=element_under_configuration,
tierno51183952020-04-03 15:48:18 +00001257 element_type=element_type,
1258 other_update=db_nsr_update
quilesj3655ae02019-12-12 16:08:35 +00001259 )
1260
tierno3bedc9b2019-11-27 15:46:57 +00001261 # TODO check if already done
quilesj7e13aeb2019-10-08 13:34:55 +02001262 self.logger.debug(logging_text + step)
David Garcia18a63322020-04-01 16:14:59 +02001263 config = None
1264 if not is_proxy_charm:
1265 initial_config_primitive_list = config_descriptor.get('initial-config-primitive')
1266 if initial_config_primitive_list:
1267 for primitive in initial_config_primitive_list:
1268 if primitive["name"] == "config":
1269 config = self._map_primitive_params(
1270 primitive,
1271 {},
1272 deploy_params
1273 )
1274 break
1275 await self.n2vc.install_configuration_sw(
1276 ee_id=ee_id,
1277 artifact_path=artifact_path,
1278 db_dict=db_dict,
1279 config=config
1280 )
quilesj7e13aeb2019-10-08 13:34:55 +02001281
quilesj63f90042020-01-17 09:53:55 +00001282 # write in db flag of configuration_sw already installed
1283 self.update_db_2("nsrs", nsr_id, {db_update_entry + "config_sw_installed": True})
1284
1285 # add relations for this VCA (wait for other peers related with this VCA)
1286 await self._add_vca_relations(logging_text=logging_text, nsr_id=nsr_id, vca_index=vca_index)
1287
quilesj7e13aeb2019-10-08 13:34:55 +02001288 # if SSH access is required, then get execution environment SSH public
tierno3bedc9b2019-11-27 15:46:57 +00001289 if is_proxy_charm: # if native charm we have waited already to VM be UP
1290 pub_key = None
1291 user = None
1292 if deep_get(config_descriptor, ("config-access", "ssh-access", "required")):
1293 # Needed to inject a ssh key
1294 user = deep_get(config_descriptor, ("config-access", "ssh-access", "default-user"))
1295 step = "Install configuration Software, getting public ssh key"
1296 pub_key = await self.n2vc.get_ee_ssh_public__key(ee_id=ee_id, db_dict=db_dict)
quilesj7e13aeb2019-10-08 13:34:55 +02001297
tiernoacc90452019-12-10 11:06:54 +00001298 step = "Insert public key into VM user={} ssh_key={}".format(user, pub_key)
tierno3bedc9b2019-11-27 15:46:57 +00001299 else:
1300 step = "Waiting to VM being up and getting IP address"
1301 self.logger.debug(logging_text + step)
quilesj7e13aeb2019-10-08 13:34:55 +02001302
tierno3bedc9b2019-11-27 15:46:57 +00001303 # n2vc_redesign STEP 5.1
1304 # wait for RO (ip-address) Insert pub_key into VM
tierno5ee02052019-12-05 19:55:02 +00001305 if vnfr_id:
1306 rw_mgmt_ip = await self.wait_vm_up_insert_key_ro(logging_text, nsr_id, vnfr_id, vdu_id, vdu_index,
1307 user=user, pub_key=pub_key)
1308 else:
1309 rw_mgmt_ip = None # This is for a NS configuration
tierno3bedc9b2019-11-27 15:46:57 +00001310
1311 self.logger.debug(logging_text + ' VM_ip_address={}'.format(rw_mgmt_ip))
quilesj7e13aeb2019-10-08 13:34:55 +02001312
tiernoa5088192019-11-26 16:12:53 +00001313 # store rw_mgmt_ip in deploy params for later replacement
quilesj7e13aeb2019-10-08 13:34:55 +02001314 deploy_params["rw_mgmt_ip"] = rw_mgmt_ip
tiernod8323042019-08-09 11:32:23 +00001315
1316 # n2vc_redesign STEP 6 Execute initial config primitive
quilesj7e13aeb2019-10-08 13:34:55 +02001317 step = 'execute initial config primitive'
tiernoa5088192019-11-26 16:12:53 +00001318 initial_config_primitive_list = config_descriptor.get('initial-config-primitive')
quilesj7e13aeb2019-10-08 13:34:55 +02001319
1320 # sort initial config primitives by 'seq'
quilesj63f90042020-01-17 09:53:55 +00001321 if initial_config_primitive_list:
1322 try:
1323 initial_config_primitive_list.sort(key=lambda val: int(val['seq']))
1324 except Exception as e:
1325 self.logger.error(logging_text + step + ": " + str(e))
1326 else:
1327 self.logger.debug(logging_text + step + ": No initial-config-primitive")
quilesj7e13aeb2019-10-08 13:34:55 +02001328
tiernoda6fb102019-11-23 00:36:52 +00001329 # add config if not present for NS charm
1330 initial_config_primitive_list = self._get_initial_config_primitive_list(initial_config_primitive_list,
1331 vca_deployed)
quilesj3655ae02019-12-12 16:08:35 +00001332
1333 # wait for dependent primitives execution (NS -> VNF -> VDU)
tierno5ee02052019-12-05 19:55:02 +00001334 if initial_config_primitive_list:
1335 await self._wait_dependent_n2vc(nsr_id, vca_deployed_list, vca_index)
quilesj3655ae02019-12-12 16:08:35 +00001336
1337 # stage, in function of element type: vdu, kdu, vnf or ns
1338 my_vca = vca_deployed_list[vca_index]
1339 if my_vca.get("vdu_id") or my_vca.get("kdu_name"):
1340 # VDU or KDU
tiernoe876f672020-02-13 14:34:48 +00001341 stage[0] = 'Stage 3/5: running Day-1 primitives for VDU.'
quilesj3655ae02019-12-12 16:08:35 +00001342 elif my_vca.get("member-vnf-index"):
1343 # VNF
tiernoe876f672020-02-13 14:34:48 +00001344 stage[0] = 'Stage 4/5: running Day-1 primitives for VNF.'
quilesj3655ae02019-12-12 16:08:35 +00001345 else:
1346 # NS
tiernoe876f672020-02-13 14:34:48 +00001347 stage[0] = 'Stage 5/5: running Day-1 primitives for NS.'
quilesj3655ae02019-12-12 16:08:35 +00001348
tiernoc231a872020-01-21 08:49:05 +00001349 self._write_configuration_status(
quilesj3655ae02019-12-12 16:08:35 +00001350 nsr_id=nsr_id,
1351 vca_index=vca_index,
1352 status='EXECUTING PRIMITIVE'
1353 )
1354
1355 self._write_op_status(
1356 op_id=nslcmop_id,
1357 stage=stage
1358 )
1359
tiernoe876f672020-02-13 14:34:48 +00001360 check_if_terminated_needed = True
tiernod8323042019-08-09 11:32:23 +00001361 for initial_config_primitive in initial_config_primitive_list:
tiernoda6fb102019-11-23 00:36:52 +00001362 # adding information on the vca_deployed if it is a NS execution environment
1363 if not vca_deployed["member-vnf-index"]:
David Garciad4816682019-12-09 14:57:43 +01001364 deploy_params["ns_config_info"] = json.dumps(self._get_ns_config_info(nsr_id))
tiernod8323042019-08-09 11:32:23 +00001365 # TODO check if already done
1366 primitive_params_ = self._map_primitive_params(initial_config_primitive, {}, deploy_params)
tierno3bedc9b2019-11-27 15:46:57 +00001367
tiernod8323042019-08-09 11:32:23 +00001368 step = "execute primitive '{}' params '{}'".format(initial_config_primitive["name"], primitive_params_)
1369 self.logger.debug(logging_text + step)
quilesj7e13aeb2019-10-08 13:34:55 +02001370 await self.n2vc.exec_primitive(
1371 ee_id=ee_id,
1372 primitive_name=initial_config_primitive["name"],
1373 params_dict=primitive_params_,
1374 db_dict=db_dict
1375 )
tiernoe876f672020-02-13 14:34:48 +00001376 # Once some primitive has been exec, check and write at db if it needs to exec terminated primitives
1377 if check_if_terminated_needed:
1378 if config_descriptor.get('terminate-config-primitive'):
1379 self.update_db_2("nsrs", nsr_id, {db_update_entry + "needed_terminate": True})
1380 check_if_terminated_needed = False
quilesj3655ae02019-12-12 16:08:35 +00001381
tiernod8323042019-08-09 11:32:23 +00001382 # TODO register in database that primitive is done
quilesj7e13aeb2019-10-08 13:34:55 +02001383
1384 step = "instantiated at VCA"
1385 self.logger.debug(logging_text + step)
1386
tiernoc231a872020-01-21 08:49:05 +00001387 self._write_configuration_status(
quilesj3655ae02019-12-12 16:08:35 +00001388 nsr_id=nsr_id,
1389 vca_index=vca_index,
1390 status='READY'
1391 )
1392
tiernod8323042019-08-09 11:32:23 +00001393 except Exception as e: # TODO not use Exception but N2VC exception
quilesj3655ae02019-12-12 16:08:35 +00001394 # self.update_db_2("nsrs", nsr_id, {db_update_entry + "instantiation": "FAILED"})
tiernoe876f672020-02-13 14:34:48 +00001395 if not isinstance(e, (DbException, N2VCException, LcmException, asyncio.CancelledError)):
1396 self.logger.error("Exception while {} : {}".format(step, e), exc_info=True)
tiernoc231a872020-01-21 08:49:05 +00001397 self._write_configuration_status(
quilesj3655ae02019-12-12 16:08:35 +00001398 nsr_id=nsr_id,
1399 vca_index=vca_index,
1400 status='BROKEN'
1401 )
tiernoe876f672020-02-13 14:34:48 +00001402 raise LcmException("{} {}".format(step, e)) from e
tiernod8323042019-08-09 11:32:23 +00001403
quilesj4cda56b2019-12-05 10:02:20 +00001404 def _write_ns_status(self, nsr_id: str, ns_state: str, current_operation: str, current_operation_id: str,
tiernoa2143262020-03-27 16:20:40 +00001405 error_description: str = None, error_detail: str = None, other_update: dict = None):
tiernoe876f672020-02-13 14:34:48 +00001406 """
1407 Update db_nsr fields.
1408 :param nsr_id:
1409 :param ns_state:
1410 :param current_operation:
1411 :param current_operation_id:
1412 :param error_description:
tiernoa2143262020-03-27 16:20:40 +00001413 :param error_detail:
tiernoe876f672020-02-13 14:34:48 +00001414 :param other_update: Other required changes at database if provided, will be cleared
1415 :return:
1416 """
quilesj4cda56b2019-12-05 10:02:20 +00001417 try:
tiernoe876f672020-02-13 14:34:48 +00001418 db_dict = other_update or {}
1419 db_dict["_admin.nslcmop"] = current_operation_id # for backward compatibility
1420 db_dict["_admin.current-operation"] = current_operation_id
1421 db_dict["_admin.operation-type"] = current_operation if current_operation != "IDLE" else None
quilesj4cda56b2019-12-05 10:02:20 +00001422 db_dict["currentOperation"] = current_operation
1423 db_dict["currentOperationID"] = current_operation_id
1424 db_dict["errorDescription"] = error_description
tiernoa2143262020-03-27 16:20:40 +00001425 db_dict["errorDetail"] = error_detail
tiernoe876f672020-02-13 14:34:48 +00001426
1427 if ns_state:
1428 db_dict["nsState"] = ns_state
quilesj4cda56b2019-12-05 10:02:20 +00001429 self.update_db_2("nsrs", nsr_id, db_dict)
tiernoe876f672020-02-13 14:34:48 +00001430 except DbException as e:
quilesj3655ae02019-12-12 16:08:35 +00001431 self.logger.warn('Error writing NS status, ns={}: {}'.format(nsr_id, e))
1432
tiernoe876f672020-02-13 14:34:48 +00001433 def _write_op_status(self, op_id: str, stage: list = None, error_message: str = None, queuePosition: int = 0,
1434 operation_state: str = None, other_update: dict = None):
quilesj3655ae02019-12-12 16:08:35 +00001435 try:
tiernoe876f672020-02-13 14:34:48 +00001436 db_dict = other_update or {}
quilesj3655ae02019-12-12 16:08:35 +00001437 db_dict['queuePosition'] = queuePosition
tiernoe876f672020-02-13 14:34:48 +00001438 if isinstance(stage, list):
1439 db_dict['stage'] = stage[0]
1440 db_dict['detailed-status'] = " ".join(stage)
1441 elif stage is not None:
1442 db_dict['stage'] = str(stage)
1443
1444 if error_message is not None:
quilesj3655ae02019-12-12 16:08:35 +00001445 db_dict['errorMessage'] = error_message
tiernoe876f672020-02-13 14:34:48 +00001446 if operation_state is not None:
1447 db_dict['operationState'] = operation_state
1448 db_dict["statusEnteredTime"] = time()
quilesj3655ae02019-12-12 16:08:35 +00001449 self.update_db_2("nslcmops", op_id, db_dict)
tiernoe876f672020-02-13 14:34:48 +00001450 except DbException as e:
quilesj3655ae02019-12-12 16:08:35 +00001451 self.logger.warn('Error writing OPERATION status for op_id: {} -> {}'.format(op_id, e))
1452
tierno51183952020-04-03 15:48:18 +00001453 def _write_all_config_status(self, db_nsr: dict, status: str):
quilesj3655ae02019-12-12 16:08:35 +00001454 try:
tierno51183952020-04-03 15:48:18 +00001455 nsr_id = db_nsr["_id"]
quilesj3655ae02019-12-12 16:08:35 +00001456 # configurationStatus
1457 config_status = db_nsr.get('configurationStatus')
1458 if config_status:
tierno51183952020-04-03 15:48:18 +00001459 db_nsr_update = {"configurationStatus.{}.status".format(index): status for index, v in
1460 enumerate(config_status) if v}
quilesj3655ae02019-12-12 16:08:35 +00001461 # update status
tierno51183952020-04-03 15:48:18 +00001462 self.update_db_2("nsrs", nsr_id, db_nsr_update)
quilesj3655ae02019-12-12 16:08:35 +00001463
tiernoe876f672020-02-13 14:34:48 +00001464 except DbException as e:
quilesj3655ae02019-12-12 16:08:35 +00001465 self.logger.warn('Error writing all configuration status, ns={}: {}'.format(nsr_id, e))
1466
quilesj63f90042020-01-17 09:53:55 +00001467 def _write_configuration_status(self, nsr_id: str, vca_index: int, status: str = None,
tierno51183952020-04-03 15:48:18 +00001468 element_under_configuration: str = None, element_type: str = None,
1469 other_update: dict = None):
quilesj3655ae02019-12-12 16:08:35 +00001470
1471 # self.logger.debug('_write_configuration_status(): vca_index={}, status={}'
1472 # .format(vca_index, status))
1473
1474 try:
1475 db_path = 'configurationStatus.{}.'.format(vca_index)
tierno51183952020-04-03 15:48:18 +00001476 db_dict = other_update or {}
quilesj63f90042020-01-17 09:53:55 +00001477 if status:
1478 db_dict[db_path + 'status'] = status
quilesj3655ae02019-12-12 16:08:35 +00001479 if element_under_configuration:
1480 db_dict[db_path + 'elementUnderConfiguration'] = element_under_configuration
1481 if element_type:
1482 db_dict[db_path + 'elementType'] = element_type
1483 self.update_db_2("nsrs", nsr_id, db_dict)
tiernoe876f672020-02-13 14:34:48 +00001484 except DbException as e:
quilesj3655ae02019-12-12 16:08:35 +00001485 self.logger.warn('Error writing configuration status={}, ns={}, vca_index={}: {}'
1486 .format(status, nsr_id, vca_index, e))
quilesj4cda56b2019-12-05 10:02:20 +00001487
tierno38089af2020-04-16 07:56:58 +00001488 async def _do_placement(self, logging_text, db_nslcmop, db_vnfrs):
1489 """
1490 Check and computes the placement, (vim account where to deploy). If it is decided by an external tool, it
1491 sends the request via kafka and wait until the result is wrote at database (nslcmops _admin.plca).
1492 Database is used because the result can be obtained from a different LCM worker in case of HA.
1493 :param logging_text: contains the prefix for logging, with the ns and nslcmop identifiers
1494 :param db_nslcmop: database content of nslcmop
1495 :param db_vnfrs: database content of vnfrs, indexed by member-vnf-index.
tierno8790a3d2020-04-23 22:49:52 +00001496 :return: True if some modification is done. Modifies database vnfrs and parameter db_vnfr with the
1497 computed 'vim-account-id'
tierno38089af2020-04-16 07:56:58 +00001498 """
tierno8790a3d2020-04-23 22:49:52 +00001499 modified = False
tierno38089af2020-04-16 07:56:58 +00001500 nslcmop_id = db_nslcmop['_id']
magnussonle9198bb2020-01-21 13:00:51 +01001501 placement_engine = deep_get(db_nslcmop, ('operationParams', 'placement-engine'))
1502 if placement_engine == "PLA":
tierno38089af2020-04-16 07:56:58 +00001503 self.logger.debug(logging_text + "Invoke and wait for placement optimization")
1504 await self.msg.aiowrite("pla", "get_placement", {'nslcmopId': nslcmop_id}, loop=self.loop)
magnussonle9198bb2020-01-21 13:00:51 +01001505 db_poll_interval = 5
tierno38089af2020-04-16 07:56:58 +00001506 wait = db_poll_interval * 10
magnussonle9198bb2020-01-21 13:00:51 +01001507 pla_result = None
1508 while not pla_result and wait >= 0:
1509 await asyncio.sleep(db_poll_interval)
1510 wait -= db_poll_interval
tierno38089af2020-04-16 07:56:58 +00001511 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
magnussonle9198bb2020-01-21 13:00:51 +01001512 pla_result = deep_get(db_nslcmop, ('_admin', 'pla'))
1513
1514 if not pla_result:
tierno38089af2020-04-16 07:56:58 +00001515 raise LcmException("Placement timeout for nslcmopId={}".format(nslcmop_id))
magnussonle9198bb2020-01-21 13:00:51 +01001516
1517 for pla_vnf in pla_result['vnf']:
1518 vnfr = db_vnfrs.get(pla_vnf['member-vnf-index'])
1519 if not pla_vnf.get('vimAccountId') or not vnfr:
1520 continue
tierno8790a3d2020-04-23 22:49:52 +00001521 modified = True
magnussonle9198bb2020-01-21 13:00:51 +01001522 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, {"vim-account-id": pla_vnf['vimAccountId']})
tierno38089af2020-04-16 07:56:58 +00001523 # Modifies db_vnfrs
1524 vnfr["vim-account-id"] = pla_vnf['vimAccountId']
tierno8790a3d2020-04-23 22:49:52 +00001525 return modified
magnussonle9198bb2020-01-21 13:00:51 +01001526
1527 def update_nsrs_with_pla_result(self, params):
1528 try:
1529 nslcmop_id = deep_get(params, ('placement', 'nslcmopId'))
1530 self.update_db_2("nslcmops", nslcmop_id, {"_admin.pla": params.get('placement')})
1531 except Exception as e:
1532 self.logger.warn('Update failed for nslcmop_id={}:{}'.format(nslcmop_id, e))
1533
tierno59d22d22018-09-25 18:10:19 +02001534 async def instantiate(self, nsr_id, nslcmop_id):
quilesj7e13aeb2019-10-08 13:34:55 +02001535 """
1536
1537 :param nsr_id: ns instance to deploy
1538 :param nslcmop_id: operation to run
1539 :return:
1540 """
kuused124bfe2019-06-18 12:09:24 +02001541
1542 # Try to lock HA task here
1543 task_is_locked_by_me = self.lcm_tasks.lock_HA('ns', 'nslcmops', nslcmop_id)
1544 if not task_is_locked_by_me:
quilesj3655ae02019-12-12 16:08:35 +00001545 self.logger.debug('instantiate() task is not locked by me, ns={}'.format(nsr_id))
kuused124bfe2019-06-18 12:09:24 +02001546 return
1547
tierno59d22d22018-09-25 18:10:19 +02001548 logging_text = "Task ns={} instantiate={} ".format(nsr_id, nslcmop_id)
1549 self.logger.debug(logging_text + "Enter")
quilesj7e13aeb2019-10-08 13:34:55 +02001550
tierno59d22d22018-09-25 18:10:19 +02001551 # get all needed from database
quilesj7e13aeb2019-10-08 13:34:55 +02001552
1553 # database nsrs record
tierno59d22d22018-09-25 18:10:19 +02001554 db_nsr = None
quilesj7e13aeb2019-10-08 13:34:55 +02001555
1556 # database nslcmops record
tierno59d22d22018-09-25 18:10:19 +02001557 db_nslcmop = None
quilesj7e13aeb2019-10-08 13:34:55 +02001558
1559 # update operation on nsrs
tiernoe876f672020-02-13 14:34:48 +00001560 db_nsr_update = {}
quilesj7e13aeb2019-10-08 13:34:55 +02001561 # update operation on nslcmops
tierno59d22d22018-09-25 18:10:19 +02001562 db_nslcmop_update = {}
quilesj7e13aeb2019-10-08 13:34:55 +02001563
tierno59d22d22018-09-25 18:10:19 +02001564 nslcmop_operation_state = None
quilesj7e13aeb2019-10-08 13:34:55 +02001565 db_vnfrs = {} # vnf's info indexed by member-index
1566 # n2vc_info = {}
tiernoe876f672020-02-13 14:34:48 +00001567 tasks_dict_info = {} # from task to info text
tierno59d22d22018-09-25 18:10:19 +02001568 exc = None
tiernoe876f672020-02-13 14:34:48 +00001569 error_list = []
1570 stage = ['Stage 1/5: preparation of the environment.', "Waiting for previous operations to terminate.", ""]
1571 # ^ stage, step, VIM progress
tierno59d22d22018-09-25 18:10:19 +02001572 try:
kuused124bfe2019-06-18 12:09:24 +02001573 # wait for any previous tasks in process
1574 await self.lcm_tasks.waitfor_related_HA('ns', 'nslcmops', nslcmop_id)
1575
quilesj7e13aeb2019-10-08 13:34:55 +02001576 # STEP 0: Reading database (nslcmops, nsrs, nsds, vnfrs, vnfds)
tiernoe876f672020-02-13 14:34:48 +00001577 stage[1] = "Reading from database,"
quilesj4cda56b2019-12-05 10:02:20 +00001578 # nsState="BUILDING", currentOperation="INSTANTIATING", currentOperationID=nslcmop_id
tiernoe876f672020-02-13 14:34:48 +00001579 db_nsr_update["detailed-status"] = "creating"
1580 db_nsr_update["operational-status"] = "init"
quilesj4cda56b2019-12-05 10:02:20 +00001581 self._write_ns_status(
1582 nsr_id=nsr_id,
1583 ns_state="BUILDING",
1584 current_operation="INSTANTIATING",
tiernoe876f672020-02-13 14:34:48 +00001585 current_operation_id=nslcmop_id,
1586 other_update=db_nsr_update
1587 )
1588 self._write_op_status(
1589 op_id=nslcmop_id,
1590 stage=stage,
1591 queuePosition=0
quilesj4cda56b2019-12-05 10:02:20 +00001592 )
1593
quilesj7e13aeb2019-10-08 13:34:55 +02001594 # read from db: operation
tiernoe876f672020-02-13 14:34:48 +00001595 stage[1] = "Getting nslcmop={} from db".format(nslcmop_id)
tierno59d22d22018-09-25 18:10:19 +02001596 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
tierno744303e2020-01-13 16:46:31 +00001597 ns_params = db_nslcmop.get("operationParams")
1598 if ns_params and ns_params.get("timeout_ns_deploy"):
1599 timeout_ns_deploy = ns_params["timeout_ns_deploy"]
1600 else:
1601 timeout_ns_deploy = self.timeout.get("ns_deploy", self.timeout_ns_deploy)
quilesj7e13aeb2019-10-08 13:34:55 +02001602
1603 # read from db: ns
tiernoe876f672020-02-13 14:34:48 +00001604 stage[1] = "Getting nsr={} from db".format(nsr_id)
tierno59d22d22018-09-25 18:10:19 +02001605 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
quilesj7e13aeb2019-10-08 13:34:55 +02001606 # nsd is replicated into ns (no db read)
tierno59d22d22018-09-25 18:10:19 +02001607 nsd = db_nsr["nsd"]
tiernod8323042019-08-09 11:32:23 +00001608 # nsr_name = db_nsr["name"] # TODO short-name??
tierno47e86b52018-10-10 14:05:55 +02001609
quilesj7e13aeb2019-10-08 13:34:55 +02001610 # read from db: vnf's of this ns
tiernoe876f672020-02-13 14:34:48 +00001611 stage[1] = "Getting vnfrs from db"
1612 self.logger.debug(logging_text + stage[1])
tierno27246d82018-09-27 15:59:09 +02001613 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
tierno27246d82018-09-27 15:59:09 +02001614
quilesj7e13aeb2019-10-08 13:34:55 +02001615 # read from db: vnfd's for every vnf
1616 db_vnfds_ref = {} # every vnfd data indexed by vnf name
1617 db_vnfds = {} # every vnfd data indexed by vnf id
1618 db_vnfds_index = {} # every vnfd data indexed by vnf member-index
1619
1620 # for each vnf in ns, read vnfd
tierno27246d82018-09-27 15:59:09 +02001621 for vnfr in db_vnfrs_list:
quilesj7e13aeb2019-10-08 13:34:55 +02001622 db_vnfrs[vnfr["member-vnf-index-ref"]] = vnfr # vnf's dict indexed by member-index: '1', '2', etc
1623 vnfd_id = vnfr["vnfd-id"] # vnfd uuid for this vnf
1624 vnfd_ref = vnfr["vnfd-ref"] # vnfd name for this vnf
1625 # if we haven't this vnfd, read it from db
tierno27246d82018-09-27 15:59:09 +02001626 if vnfd_id not in db_vnfds:
quilesj63f90042020-01-17 09:53:55 +00001627 # read from db
tiernoe876f672020-02-13 14:34:48 +00001628 stage[1] = "Getting vnfd={} id='{}' from db".format(vnfd_id, vnfd_ref)
1629 self.logger.debug(logging_text + stage[1])
tierno27246d82018-09-27 15:59:09 +02001630 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
tierno27246d82018-09-27 15:59:09 +02001631
quilesj7e13aeb2019-10-08 13:34:55 +02001632 # store vnfd
1633 db_vnfds_ref[vnfd_ref] = vnfd # vnfd's indexed by name
1634 db_vnfds[vnfd_id] = vnfd # vnfd's indexed by id
1635 db_vnfds_index[vnfr["member-vnf-index-ref"]] = db_vnfds[vnfd_id] # vnfd's indexed by member-index
1636
1637 # Get or generates the _admin.deployed.VCA list
tiernoe4f7e6c2018-11-27 14:55:30 +00001638 vca_deployed_list = None
1639 if db_nsr["_admin"].get("deployed"):
1640 vca_deployed_list = db_nsr["_admin"]["deployed"].get("VCA")
1641 if vca_deployed_list is None:
1642 vca_deployed_list = []
quilesj3655ae02019-12-12 16:08:35 +00001643 configuration_status_list = []
tiernoe4f7e6c2018-11-27 14:55:30 +00001644 db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
quilesj3655ae02019-12-12 16:08:35 +00001645 db_nsr_update["configurationStatus"] = configuration_status_list
quilesj7e13aeb2019-10-08 13:34:55 +02001646 # add _admin.deployed.VCA to db_nsr dictionary, value=vca_deployed_list
tierno98ad6ea2019-05-30 17:16:28 +00001647 populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
tiernoe4f7e6c2018-11-27 14:55:30 +00001648 elif isinstance(vca_deployed_list, dict):
1649 # maintain backward compatibility. Change a dict to list at database
1650 vca_deployed_list = list(vca_deployed_list.values())
1651 db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
tierno98ad6ea2019-05-30 17:16:28 +00001652 populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
tiernoe4f7e6c2018-11-27 14:55:30 +00001653
tierno6cf25f52019-09-12 09:33:40 +00001654 if not isinstance(deep_get(db_nsr, ("_admin", "deployed", "RO", "vnfd")), list):
tiernoa009e552019-01-30 16:45:44 +00001655 populate_dict(db_nsr, ("_admin", "deployed", "RO", "vnfd"), [])
1656 db_nsr_update["_admin.deployed.RO.vnfd"] = []
tierno59d22d22018-09-25 18:10:19 +02001657
tiernobaa51102018-12-14 13:16:18 +00001658 # set state to INSTANTIATED. When instantiated NBI will not delete directly
1659 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
1660 self.update_db_2("nsrs", nsr_id, db_nsr_update)
quilesj3655ae02019-12-12 16:08:35 +00001661
1662 # n2vc_redesign STEP 2 Deploy Network Scenario
tiernoe876f672020-02-13 14:34:48 +00001663 stage[0] = 'Stage 2/5: deployment of KDUs, VMs and execution environments.'
quilesj3655ae02019-12-12 16:08:35 +00001664 self._write_op_status(
1665 op_id=nslcmop_id,
tiernoe876f672020-02-13 14:34:48 +00001666 stage=stage
quilesj3655ae02019-12-12 16:08:35 +00001667 )
1668
tiernoe876f672020-02-13 14:34:48 +00001669 stage[1] = "Deploying KDUs,"
1670 # self.logger.debug(logging_text + "Before deploy_kdus")
calvinosanch9f9c6f22019-11-04 13:37:39 +01001671 # Call to deploy_kdus in case exists the "vdu:kdu" param
tiernoe876f672020-02-13 14:34:48 +00001672 await self.deploy_kdus(
1673 logging_text=logging_text,
1674 nsr_id=nsr_id,
1675 nslcmop_id=nslcmop_id,
1676 db_vnfrs=db_vnfrs,
1677 db_vnfds=db_vnfds,
1678 task_instantiation_info=tasks_dict_info,
calvinosanch9f9c6f22019-11-04 13:37:39 +01001679 )
tiernoe876f672020-02-13 14:34:48 +00001680
1681 stage[1] = "Getting VCA public key."
tiernod8323042019-08-09 11:32:23 +00001682 # n2vc_redesign STEP 1 Get VCA public ssh-key
1683 # feature 1429. Add n2vc public key to needed VMs
tierno3bedc9b2019-11-27 15:46:57 +00001684 n2vc_key = self.n2vc.get_public_key()
tiernoa5088192019-11-26 16:12:53 +00001685 n2vc_key_list = [n2vc_key]
1686 if self.vca_config.get("public_key"):
1687 n2vc_key_list.append(self.vca_config["public_key"])
tierno98ad6ea2019-05-30 17:16:28 +00001688
tiernoe876f672020-02-13 14:34:48 +00001689 stage[1] = "Deploying NS at VIM."
tiernod8323042019-08-09 11:32:23 +00001690 task_ro = asyncio.ensure_future(
quilesj7e13aeb2019-10-08 13:34:55 +02001691 self.instantiate_RO(
1692 logging_text=logging_text,
1693 nsr_id=nsr_id,
1694 nsd=nsd,
1695 db_nsr=db_nsr,
1696 db_nslcmop=db_nslcmop,
1697 db_vnfrs=db_vnfrs,
1698 db_vnfds_ref=db_vnfds_ref,
tiernoe876f672020-02-13 14:34:48 +00001699 n2vc_key_list=n2vc_key_list,
1700 stage=stage
tierno98ad6ea2019-05-30 17:16:28 +00001701 )
tiernod8323042019-08-09 11:32:23 +00001702 )
1703 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "instantiate_RO", task_ro)
tiernoa2143262020-03-27 16:20:40 +00001704 tasks_dict_info[task_ro] = "Deploying at VIM"
tierno98ad6ea2019-05-30 17:16:28 +00001705
tiernod8323042019-08-09 11:32:23 +00001706 # n2vc_redesign STEP 3 to 6 Deploy N2VC
tiernoe876f672020-02-13 14:34:48 +00001707 stage[1] = "Deploying Execution Environments."
1708 self.logger.debug(logging_text + stage[1])
tierno98ad6ea2019-05-30 17:16:28 +00001709
tiernod8323042019-08-09 11:32:23 +00001710 nsi_id = None # TODO put nsi_id when this nsr belongs to a NSI
quilesj7e13aeb2019-10-08 13:34:55 +02001711 # get_iterable() returns a value from a dict or empty tuple if key does not exist
tierno98ad6ea2019-05-30 17:16:28 +00001712 for c_vnf in get_iterable(nsd, "constituent-vnfd"):
1713 vnfd_id = c_vnf["vnfd-id-ref"]
tierno98ad6ea2019-05-30 17:16:28 +00001714 vnfd = db_vnfds_ref[vnfd_id]
tiernod8323042019-08-09 11:32:23 +00001715 member_vnf_index = str(c_vnf["member-vnf-index"])
1716 db_vnfr = db_vnfrs[member_vnf_index]
1717 base_folder = vnfd["_admin"]["storage"]
1718 vdu_id = None
1719 vdu_index = 0
tierno98ad6ea2019-05-30 17:16:28 +00001720 vdu_name = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01001721 kdu_name = None
tierno59d22d22018-09-25 18:10:19 +02001722
tierno8a518872018-12-21 13:42:14 +00001723 # Get additional parameters
tiernod8323042019-08-09 11:32:23 +00001724 deploy_params = {}
1725 if db_vnfr.get("additionalParamsForVnf"):
tierno626e0152019-11-29 14:16:16 +00001726 deploy_params = self._format_additional_params(db_vnfr["additionalParamsForVnf"].copy())
tierno8a518872018-12-21 13:42:14 +00001727
tiernod8323042019-08-09 11:32:23 +00001728 descriptor_config = vnfd.get("vnf-configuration")
1729 if descriptor_config and descriptor_config.get("juju"):
quilesj7e13aeb2019-10-08 13:34:55 +02001730 self._deploy_n2vc(
tiernoa54150d2019-12-05 17:15:10 +00001731 logging_text=logging_text + "member_vnf_index={} ".format(member_vnf_index),
quilesj7e13aeb2019-10-08 13:34:55 +02001732 db_nsr=db_nsr,
1733 db_vnfr=db_vnfr,
1734 nslcmop_id=nslcmop_id,
1735 nsr_id=nsr_id,
1736 nsi_id=nsi_id,
1737 vnfd_id=vnfd_id,
1738 vdu_id=vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01001739 kdu_name=kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02001740 member_vnf_index=member_vnf_index,
1741 vdu_index=vdu_index,
1742 vdu_name=vdu_name,
1743 deploy_params=deploy_params,
1744 descriptor_config=descriptor_config,
1745 base_folder=base_folder,
tiernoe876f672020-02-13 14:34:48 +00001746 task_instantiation_info=tasks_dict_info,
1747 stage=stage
quilesj7e13aeb2019-10-08 13:34:55 +02001748 )
tierno59d22d22018-09-25 18:10:19 +02001749
1750 # Deploy charms for each VDU that supports one.
tiernod8323042019-08-09 11:32:23 +00001751 for vdud in get_iterable(vnfd, 'vdu'):
1752 vdu_id = vdud["id"]
1753 descriptor_config = vdud.get('vdu-configuration')
tierno626e0152019-11-29 14:16:16 +00001754 vdur = next((x for x in db_vnfr["vdur"] if x["vdu-id-ref"] == vdu_id), None)
1755 if vdur.get("additionalParams"):
1756 deploy_params_vdu = self._format_additional_params(vdur["additionalParams"])
1757 else:
1758 deploy_params_vdu = deploy_params
tiernod8323042019-08-09 11:32:23 +00001759 if descriptor_config and descriptor_config.get("juju"):
1760 # look for vdu index in the db_vnfr["vdu"] section
1761 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
1762 # if vdur["vdu-id-ref"] == vdu_id:
1763 # break
1764 # else:
1765 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
1766 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
1767 # vdu_name = vdur.get("name")
1768 vdu_name = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01001769 kdu_name = None
tiernod8323042019-08-09 11:32:23 +00001770 for vdu_index in range(int(vdud.get("count", 1))):
1771 # TODO vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
quilesj7e13aeb2019-10-08 13:34:55 +02001772 self._deploy_n2vc(
tiernoa54150d2019-12-05 17:15:10 +00001773 logging_text=logging_text + "member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
1774 member_vnf_index, vdu_id, vdu_index),
quilesj7e13aeb2019-10-08 13:34:55 +02001775 db_nsr=db_nsr,
1776 db_vnfr=db_vnfr,
1777 nslcmop_id=nslcmop_id,
1778 nsr_id=nsr_id,
1779 nsi_id=nsi_id,
1780 vnfd_id=vnfd_id,
1781 vdu_id=vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01001782 kdu_name=kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02001783 member_vnf_index=member_vnf_index,
1784 vdu_index=vdu_index,
1785 vdu_name=vdu_name,
tierno626e0152019-11-29 14:16:16 +00001786 deploy_params=deploy_params_vdu,
quilesj7e13aeb2019-10-08 13:34:55 +02001787 descriptor_config=descriptor_config,
1788 base_folder=base_folder,
tierno8e2fae72020-04-01 15:21:15 +00001789 task_instantiation_info=tasks_dict_info,
1790 stage=stage
quilesj7e13aeb2019-10-08 13:34:55 +02001791 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001792 for kdud in get_iterable(vnfd, 'kdu'):
1793 kdu_name = kdud["name"]
1794 descriptor_config = kdud.get('kdu-configuration')
1795 if descriptor_config and descriptor_config.get("juju"):
1796 vdu_id = None
1797 vdu_index = 0
1798 vdu_name = None
1799 # look for vdu index in the db_vnfr["vdu"] section
1800 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
1801 # if vdur["vdu-id-ref"] == vdu_id:
1802 # break
1803 # else:
1804 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
1805 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
1806 # vdu_name = vdur.get("name")
1807 # vdu_name = None
tierno59d22d22018-09-25 18:10:19 +02001808
calvinosanch9f9c6f22019-11-04 13:37:39 +01001809 self._deploy_n2vc(
1810 logging_text=logging_text,
1811 db_nsr=db_nsr,
1812 db_vnfr=db_vnfr,
1813 nslcmop_id=nslcmop_id,
1814 nsr_id=nsr_id,
1815 nsi_id=nsi_id,
1816 vnfd_id=vnfd_id,
1817 vdu_id=vdu_id,
1818 kdu_name=kdu_name,
1819 member_vnf_index=member_vnf_index,
1820 vdu_index=vdu_index,
1821 vdu_name=vdu_name,
1822 deploy_params=deploy_params,
1823 descriptor_config=descriptor_config,
1824 base_folder=base_folder,
tierno8e2fae72020-04-01 15:21:15 +00001825 task_instantiation_info=tasks_dict_info,
1826 stage=stage
calvinosanch9f9c6f22019-11-04 13:37:39 +01001827 )
tierno59d22d22018-09-25 18:10:19 +02001828
tierno1b633412019-02-25 16:48:23 +00001829 # Check if this NS has a charm configuration
tiernod8323042019-08-09 11:32:23 +00001830 descriptor_config = nsd.get("ns-configuration")
1831 if descriptor_config and descriptor_config.get("juju"):
1832 vnfd_id = None
1833 db_vnfr = None
1834 member_vnf_index = None
1835 vdu_id = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01001836 kdu_name = None
tiernod8323042019-08-09 11:32:23 +00001837 vdu_index = 0
1838 vdu_name = None
tierno1b633412019-02-25 16:48:23 +00001839
tiernod8323042019-08-09 11:32:23 +00001840 # Get additional parameters
1841 deploy_params = {}
1842 if db_nsr.get("additionalParamsForNs"):
tierno626e0152019-11-29 14:16:16 +00001843 deploy_params = self._format_additional_params(db_nsr["additionalParamsForNs"].copy())
tiernod8323042019-08-09 11:32:23 +00001844 base_folder = nsd["_admin"]["storage"]
quilesj7e13aeb2019-10-08 13:34:55 +02001845 self._deploy_n2vc(
1846 logging_text=logging_text,
1847 db_nsr=db_nsr,
1848 db_vnfr=db_vnfr,
1849 nslcmop_id=nslcmop_id,
1850 nsr_id=nsr_id,
1851 nsi_id=nsi_id,
1852 vnfd_id=vnfd_id,
1853 vdu_id=vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01001854 kdu_name=kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02001855 member_vnf_index=member_vnf_index,
1856 vdu_index=vdu_index,
1857 vdu_name=vdu_name,
1858 deploy_params=deploy_params,
1859 descriptor_config=descriptor_config,
1860 base_folder=base_folder,
tierno8e2fae72020-04-01 15:21:15 +00001861 task_instantiation_info=tasks_dict_info,
1862 stage=stage
quilesj7e13aeb2019-10-08 13:34:55 +02001863 )
tierno1b633412019-02-25 16:48:23 +00001864
tiernoe876f672020-02-13 14:34:48 +00001865 # rest of staff will be done at finally
tierno1b633412019-02-25 16:48:23 +00001866
tiernoe876f672020-02-13 14:34:48 +00001867 except (ROclient.ROClientException, DbException, LcmException, N2VCException) as e:
1868 self.logger.error(logging_text + "Exit Exception while '{}': {}".format(stage[1], e))
tierno59d22d22018-09-25 18:10:19 +02001869 exc = e
1870 except asyncio.CancelledError:
tiernoe876f672020-02-13 14:34:48 +00001871 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(stage[1]))
tierno59d22d22018-09-25 18:10:19 +02001872 exc = "Operation was cancelled"
1873 except Exception as e:
1874 exc = traceback.format_exc()
tiernoe876f672020-02-13 14:34:48 +00001875 self.logger.critical(logging_text + "Exit Exception while '{}': {}".format(stage[1], e), exc_info=True)
tierno59d22d22018-09-25 18:10:19 +02001876 finally:
1877 if exc:
tiernoe876f672020-02-13 14:34:48 +00001878 error_list.append(str(exc))
tiernobaa51102018-12-14 13:16:18 +00001879 try:
tiernoe876f672020-02-13 14:34:48 +00001880 # wait for pending tasks
1881 if tasks_dict_info:
1882 stage[1] = "Waiting for instantiate pending tasks."
1883 self.logger.debug(logging_text + stage[1])
1884 error_list += await self._wait_for_tasks(logging_text, tasks_dict_info, timeout_ns_deploy,
1885 stage, nslcmop_id, nsr_id=nsr_id)
1886 stage[1] = stage[2] = ""
1887 except asyncio.CancelledError:
1888 error_list.append("Cancelled")
1889 # TODO cancel all tasks
1890 except Exception as exc:
1891 error_list.append(str(exc))
quilesj4cda56b2019-12-05 10:02:20 +00001892
tiernoe876f672020-02-13 14:34:48 +00001893 # update operation-status
1894 db_nsr_update["operational-status"] = "running"
1895 # let's begin with VCA 'configured' status (later we can change it)
1896 db_nsr_update["config-status"] = "configured"
1897 for task, task_name in tasks_dict_info.items():
1898 if not task.done() or task.cancelled() or task.exception():
1899 if task_name.startswith(self.task_name_deploy_vca):
1900 # A N2VC task is pending
1901 db_nsr_update["config-status"] = "failed"
quilesj4cda56b2019-12-05 10:02:20 +00001902 else:
tiernoe876f672020-02-13 14:34:48 +00001903 # RO or KDU task is pending
1904 db_nsr_update["operational-status"] = "failed"
quilesj3655ae02019-12-12 16:08:35 +00001905
tiernoe876f672020-02-13 14:34:48 +00001906 # update status at database
1907 if error_list:
tiernoa2143262020-03-27 16:20:40 +00001908 error_detail = ". ".join(error_list)
tiernoe876f672020-02-13 14:34:48 +00001909 self.logger.error(logging_text + error_detail)
tiernoa2143262020-03-27 16:20:40 +00001910 error_description_nslcmop = 'Stage: {}. Detail: {}'.format(stage[0], error_detail)
1911 error_description_nsr = 'Operation: INSTANTIATING.{}, Stage {}'.format(nslcmop_id, stage[0])
quilesj3655ae02019-12-12 16:08:35 +00001912
tiernoa2143262020-03-27 16:20:40 +00001913 db_nsr_update["detailed-status"] = error_description_nsr + " Detail: " + error_detail
tiernoe876f672020-02-13 14:34:48 +00001914 db_nslcmop_update["detailed-status"] = error_detail
1915 nslcmop_operation_state = "FAILED"
1916 ns_state = "BROKEN"
1917 else:
tiernoa2143262020-03-27 16:20:40 +00001918 error_detail = None
tiernoe876f672020-02-13 14:34:48 +00001919 error_description_nsr = error_description_nslcmop = None
1920 ns_state = "READY"
1921 db_nsr_update["detailed-status"] = "Done"
1922 db_nslcmop_update["detailed-status"] = "Done"
1923 nslcmop_operation_state = "COMPLETED"
quilesj4cda56b2019-12-05 10:02:20 +00001924
tiernoe876f672020-02-13 14:34:48 +00001925 if db_nsr:
1926 self._write_ns_status(
1927 nsr_id=nsr_id,
1928 ns_state=ns_state,
1929 current_operation="IDLE",
1930 current_operation_id=None,
1931 error_description=error_description_nsr,
tiernoa2143262020-03-27 16:20:40 +00001932 error_detail=error_detail,
tiernoe876f672020-02-13 14:34:48 +00001933 other_update=db_nsr_update
1934 )
1935 if db_nslcmop:
1936 self._write_op_status(
1937 op_id=nslcmop_id,
1938 stage="",
1939 error_message=error_description_nslcmop,
1940 operation_state=nslcmop_operation_state,
1941 other_update=db_nslcmop_update,
1942 )
quilesj3655ae02019-12-12 16:08:35 +00001943
tierno59d22d22018-09-25 18:10:19 +02001944 if nslcmop_operation_state:
1945 try:
1946 await self.msg.aiowrite("ns", "instantiated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
tierno8a518872018-12-21 13:42:14 +00001947 "operationState": nslcmop_operation_state},
1948 loop=self.loop)
tierno59d22d22018-09-25 18:10:19 +02001949 except Exception as e:
1950 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1951
1952 self.logger.debug(logging_text + "Exit")
1953 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_instantiate")
1954
quilesj63f90042020-01-17 09:53:55 +00001955 async def _add_vca_relations(self, logging_text, nsr_id, vca_index: int, timeout: int = 3600) -> bool:
1956
1957 # steps:
1958 # 1. find all relations for this VCA
1959 # 2. wait for other peers related
1960 # 3. add relations
1961
1962 try:
1963
1964 # STEP 1: find all relations for this VCA
1965
1966 # read nsr record
1967 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1968
1969 # this VCA data
1970 my_vca = deep_get(db_nsr, ('_admin', 'deployed', 'VCA'))[vca_index]
1971
1972 # read all ns-configuration relations
1973 ns_relations = list()
1974 db_ns_relations = deep_get(db_nsr, ('nsd', 'ns-configuration', 'relation'))
1975 if db_ns_relations:
1976 for r in db_ns_relations:
1977 # check if this VCA is in the relation
1978 if my_vca.get('member-vnf-index') in\
1979 (r.get('entities')[0].get('id'), r.get('entities')[1].get('id')):
1980 ns_relations.append(r)
1981
1982 # read all vnf-configuration relations
1983 vnf_relations = list()
1984 db_vnfd_list = db_nsr.get('vnfd-id')
1985 if db_vnfd_list:
1986 for vnfd in db_vnfd_list:
1987 db_vnfd = self.db.get_one("vnfds", {"_id": vnfd})
1988 db_vnf_relations = deep_get(db_vnfd, ('vnf-configuration', 'relation'))
1989 if db_vnf_relations:
1990 for r in db_vnf_relations:
1991 # check if this VCA is in the relation
1992 if my_vca.get('vdu_id') in (r.get('entities')[0].get('id'), r.get('entities')[1].get('id')):
1993 vnf_relations.append(r)
1994
1995 # if no relations, terminate
1996 if not ns_relations and not vnf_relations:
1997 self.logger.debug(logging_text + ' No relations')
1998 return True
1999
2000 self.logger.debug(logging_text + ' adding relations\n {}\n {}'.format(ns_relations, vnf_relations))
2001
2002 # add all relations
2003 start = time()
2004 while True:
2005 # check timeout
2006 now = time()
2007 if now - start >= timeout:
2008 self.logger.error(logging_text + ' : timeout adding relations')
2009 return False
2010
2011 # reload nsr from database (we need to update record: _admin.deloyed.VCA)
2012 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2013
2014 # for each defined NS relation, find the VCA's related
2015 for r in ns_relations:
2016 from_vca_ee_id = None
2017 to_vca_ee_id = None
2018 from_vca_endpoint = None
2019 to_vca_endpoint = None
2020 vca_list = deep_get(db_nsr, ('_admin', 'deployed', 'VCA'))
2021 for vca in vca_list:
2022 if vca.get('member-vnf-index') == r.get('entities')[0].get('id') \
2023 and vca.get('config_sw_installed'):
2024 from_vca_ee_id = vca.get('ee_id')
2025 from_vca_endpoint = r.get('entities')[0].get('endpoint')
2026 if vca.get('member-vnf-index') == r.get('entities')[1].get('id') \
2027 and vca.get('config_sw_installed'):
2028 to_vca_ee_id = vca.get('ee_id')
2029 to_vca_endpoint = r.get('entities')[1].get('endpoint')
2030 if from_vca_ee_id and to_vca_ee_id:
2031 # add relation
2032 await self.n2vc.add_relation(
2033 ee_id_1=from_vca_ee_id,
2034 ee_id_2=to_vca_ee_id,
2035 endpoint_1=from_vca_endpoint,
2036 endpoint_2=to_vca_endpoint)
2037 # remove entry from relations list
2038 ns_relations.remove(r)
2039 else:
2040 # check failed peers
2041 try:
2042 vca_status_list = db_nsr.get('configurationStatus')
2043 if vca_status_list:
2044 for i in range(len(vca_list)):
2045 vca = vca_list[i]
2046 vca_status = vca_status_list[i]
2047 if vca.get('member-vnf-index') == r.get('entities')[0].get('id'):
2048 if vca_status.get('status') == 'BROKEN':
2049 # peer broken: remove relation from list
2050 ns_relations.remove(r)
2051 if vca.get('member-vnf-index') == r.get('entities')[1].get('id'):
2052 if vca_status.get('status') == 'BROKEN':
2053 # peer broken: remove relation from list
2054 ns_relations.remove(r)
2055 except Exception:
2056 # ignore
2057 pass
2058
2059 # for each defined VNF relation, find the VCA's related
2060 for r in vnf_relations:
2061 from_vca_ee_id = None
2062 to_vca_ee_id = None
2063 from_vca_endpoint = None
2064 to_vca_endpoint = None
2065 vca_list = deep_get(db_nsr, ('_admin', 'deployed', 'VCA'))
2066 for vca in vca_list:
2067 if vca.get('vdu_id') == r.get('entities')[0].get('id') and vca.get('config_sw_installed'):
2068 from_vca_ee_id = vca.get('ee_id')
2069 from_vca_endpoint = r.get('entities')[0].get('endpoint')
2070 if vca.get('vdu_id') == r.get('entities')[1].get('id') and vca.get('config_sw_installed'):
2071 to_vca_ee_id = vca.get('ee_id')
2072 to_vca_endpoint = r.get('entities')[1].get('endpoint')
2073 if from_vca_ee_id and to_vca_ee_id:
2074 # add relation
2075 await self.n2vc.add_relation(
2076 ee_id_1=from_vca_ee_id,
2077 ee_id_2=to_vca_ee_id,
2078 endpoint_1=from_vca_endpoint,
2079 endpoint_2=to_vca_endpoint)
2080 # remove entry from relations list
2081 vnf_relations.remove(r)
2082 else:
2083 # check failed peers
2084 try:
2085 vca_status_list = db_nsr.get('configurationStatus')
2086 if vca_status_list:
2087 for i in range(len(vca_list)):
2088 vca = vca_list[i]
2089 vca_status = vca_status_list[i]
2090 if vca.get('vdu_id') == r.get('entities')[0].get('id'):
2091 if vca_status.get('status') == 'BROKEN':
2092 # peer broken: remove relation from list
2093 ns_relations.remove(r)
2094 if vca.get('vdu_id') == r.get('entities')[1].get('id'):
2095 if vca_status.get('status') == 'BROKEN':
2096 # peer broken: remove relation from list
2097 ns_relations.remove(r)
2098 except Exception:
2099 # ignore
2100 pass
2101
2102 # wait for next try
2103 await asyncio.sleep(5.0)
2104
2105 if not ns_relations and not vnf_relations:
2106 self.logger.debug('Relations added')
2107 break
2108
2109 return True
2110
2111 except Exception as e:
2112 self.logger.warn(logging_text + ' ERROR adding relations: {}'.format(e))
2113 return False
2114
tiernob9018152020-04-16 14:18:24 +00002115 def _write_db_callback(self, task, item, _id, on_done=None, on_exc=None):
2116 """
2117 callback for kdu install intended to store the returned kdu_instance at database
2118 :return: None
2119 """
2120 db_update = {}
2121 try:
2122 result = task.result()
2123 if on_done:
2124 db_update[on_done] = str(result)
2125 except Exception as e:
2126 if on_exc:
2127 db_update[on_exc] = str(e)
2128 if db_update:
2129 try:
2130 self.update_db_2(item, _id, db_update)
2131 except Exception:
2132 pass
2133
tiernoe876f672020-02-13 14:34:48 +00002134 async def deploy_kdus(self, logging_text, nsr_id, nslcmop_id, db_vnfrs, db_vnfds, task_instantiation_info):
calvinosanch9f9c6f22019-11-04 13:37:39 +01002135 # Launch kdus if present in the descriptor
tierno626e0152019-11-29 14:16:16 +00002136
2137 k8scluster_id_2_uuic = {"helm-chart": {}, "juju-bundle": {}}
2138
2139 def _get_cluster_id(cluster_id, cluster_type):
2140 nonlocal k8scluster_id_2_uuic
2141 if cluster_id in k8scluster_id_2_uuic[cluster_type]:
2142 return k8scluster_id_2_uuic[cluster_type][cluster_id]
2143
2144 db_k8scluster = self.db.get_one("k8sclusters", {"_id": cluster_id}, fail_on_empty=False)
2145 if not db_k8scluster:
2146 raise LcmException("K8s cluster {} cannot be found".format(cluster_id))
2147 k8s_id = deep_get(db_k8scluster, ("_admin", cluster_type, "id"))
2148 if not k8s_id:
2149 raise LcmException("K8s cluster '{}' has not been initilized for '{}'".format(cluster_id, cluster_type))
2150 k8scluster_id_2_uuic[cluster_type][cluster_id] = k8s_id
2151 return k8s_id
2152
2153 logging_text += "Deploy kdus: "
tiernoe876f672020-02-13 14:34:48 +00002154 step = ""
calvinosanch9f9c6f22019-11-04 13:37:39 +01002155 try:
tierno626e0152019-11-29 14:16:16 +00002156 db_nsr_update = {"_admin.deployed.K8s": []}
calvinosanch9f9c6f22019-11-04 13:37:39 +01002157 self.update_db_2("nsrs", nsr_id, db_nsr_update)
calvinosanch9f9c6f22019-11-04 13:37:39 +01002158
tierno626e0152019-11-29 14:16:16 +00002159 index = 0
tiernoe876f672020-02-13 14:34:48 +00002160 updated_cluster_list = []
2161
tierno626e0152019-11-29 14:16:16 +00002162 for vnfr_data in db_vnfrs.values():
2163 for kdur in get_iterable(vnfr_data, "kdur"):
2164 desc_params = self._format_additional_params(kdur.get("additionalParams"))
quilesjacde94f2020-01-23 10:07:08 +00002165 vnfd_id = vnfr_data.get('vnfd-id')
tiernode1584f2020-04-07 09:07:33 +00002166 namespace = kdur.get("k8s-namespace")
tierno626e0152019-11-29 14:16:16 +00002167 if kdur.get("helm-chart"):
2168 kdumodel = kdur["helm-chart"]
tiernoe876f672020-02-13 14:34:48 +00002169 k8sclustertype = "helm-chart"
tierno626e0152019-11-29 14:16:16 +00002170 elif kdur.get("juju-bundle"):
2171 kdumodel = kdur["juju-bundle"]
tiernoe876f672020-02-13 14:34:48 +00002172 k8sclustertype = "juju-bundle"
tierno626e0152019-11-29 14:16:16 +00002173 else:
tiernoe876f672020-02-13 14:34:48 +00002174 raise LcmException("kdu type for kdu='{}.{}' is neither helm-chart nor "
2175 "juju-bundle. Maybe an old NBI version is running".
2176 format(vnfr_data["member-vnf-index-ref"], kdur["kdu-name"]))
quilesjacde94f2020-01-23 10:07:08 +00002177 # check if kdumodel is a file and exists
2178 try:
tierno51183952020-04-03 15:48:18 +00002179 storage = deep_get(db_vnfds.get(vnfd_id), ('_admin', 'storage'))
2180 if storage and storage.get('pkg-dir'): # may be not present if vnfd has not artifacts
2181 # path format: /vnfdid/pkkdir/helm-charts|juju-bundles/kdumodel
2182 filename = '{}/{}/{}s/{}'.format(storage["folder"], storage["'pkg-dir"], k8sclustertype,
2183 kdumodel)
2184 if self.fs.file_exists(filename, mode='file') or self.fs.file_exists(filename, mode='dir'):
2185 kdumodel = self.fs.path + filename
2186 except (asyncio.TimeoutError, asyncio.CancelledError):
tiernoe876f672020-02-13 14:34:48 +00002187 raise
2188 except Exception: # it is not a file
quilesjacde94f2020-01-23 10:07:08 +00002189 pass
lloretgallegedc5f332020-02-20 11:50:50 +01002190
tiernoe876f672020-02-13 14:34:48 +00002191 k8s_cluster_id = kdur["k8s-cluster"]["id"]
2192 step = "Synchronize repos for k8s cluster '{}'".format(k8s_cluster_id)
2193 cluster_uuid = _get_cluster_id(k8s_cluster_id, k8sclustertype)
lloretgallegedc5f332020-02-20 11:50:50 +01002194
tiernoe876f672020-02-13 14:34:48 +00002195 if k8sclustertype == "helm-chart" and cluster_uuid not in updated_cluster_list:
2196 del_repo_list, added_repo_dict = await asyncio.ensure_future(
2197 self.k8sclusterhelm.synchronize_repos(cluster_uuid=cluster_uuid))
2198 if del_repo_list or added_repo_dict:
2199 unset = {'_admin.helm_charts_added.' + item: None for item in del_repo_list}
2200 updated = {'_admin.helm_charts_added.' +
2201 item: name for item, name in added_repo_dict.items()}
2202 self.logger.debug(logging_text + "repos synchronized on k8s cluster '{}' to_delete: {}, "
2203 "to_add: {}".format(k8s_cluster_id, del_repo_list,
2204 added_repo_dict))
2205 self.db.set_one("k8sclusters", {"_id": k8s_cluster_id}, updated, unset=unset)
2206 updated_cluster_list.append(cluster_uuid)
lloretgallegedc5f332020-02-20 11:50:50 +01002207
tiernoe876f672020-02-13 14:34:48 +00002208 step = "Instantiating KDU {}.{} in k8s cluster {}".format(vnfr_data["member-vnf-index-ref"],
2209 kdur["kdu-name"], k8s_cluster_id)
tierno626e0152019-11-29 14:16:16 +00002210
tierno067e04a2020-03-31 12:53:13 +00002211 k8s_instace_info = {"kdu-instance": None,
2212 "k8scluster-uuid": cluster_uuid,
tierno626e0152019-11-29 14:16:16 +00002213 "k8scluster-type": k8sclustertype,
tierno067e04a2020-03-31 12:53:13 +00002214 "member-vnf-index": vnfr_data["member-vnf-index-ref"],
2215 "kdu-name": kdur["kdu-name"],
tiernode1584f2020-04-07 09:07:33 +00002216 "kdu-model": kdumodel,
2217 "namespace": namespace}
tiernob9018152020-04-16 14:18:24 +00002218 db_path = "_admin.deployed.K8s.{}".format(index)
2219 db_nsr_update[db_path] = k8s_instace_info
tierno626e0152019-11-29 14:16:16 +00002220 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tierno626e0152019-11-29 14:16:16 +00002221
tiernoe876f672020-02-13 14:34:48 +00002222 db_dict = {"collection": "nsrs",
2223 "filter": {"_id": nsr_id},
tiernob9018152020-04-16 14:18:24 +00002224 "path": db_path}
lloretgallegedc5f332020-02-20 11:50:50 +01002225
tiernoa2143262020-03-27 16:20:40 +00002226 task = asyncio.ensure_future(
2227 self.k8scluster_map[k8sclustertype].install(cluster_uuid=cluster_uuid, kdu_model=kdumodel,
2228 atomic=True, params=desc_params,
2229 db_dict=db_dict, timeout=600,
tiernode1584f2020-04-07 09:07:33 +00002230 kdu_name=kdur["kdu-name"], namespace=namespace))
Adam Israelbaacc302019-12-01 12:41:39 -05002231
tiernob9018152020-04-16 14:18:24 +00002232 task.add_done_callback(partial(self._write_db_callback, item="nsrs", _id=nsr_id,
2233 on_done=db_path + ".kdu-instance",
2234 on_exc=db_path + ".detailed-status"))
tiernoe876f672020-02-13 14:34:48 +00002235 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "instantiate_KDU-{}".format(index), task)
tiernoa2143262020-03-27 16:20:40 +00002236 task_instantiation_info[task] = "Deploying KDU {}".format(kdur["kdu-name"])
tiernoe876f672020-02-13 14:34:48 +00002237
tierno626e0152019-11-29 14:16:16 +00002238 index += 1
quilesjdd799ac2020-01-23 16:31:11 +00002239
tiernoe876f672020-02-13 14:34:48 +00002240 except (LcmException, asyncio.CancelledError):
2241 raise
calvinosanch9f9c6f22019-11-04 13:37:39 +01002242 except Exception as e:
tiernoe876f672020-02-13 14:34:48 +00002243 msg = "Exception {} while {}: {}".format(type(e).__name__, step, e)
2244 if isinstance(e, (N2VCException, DbException)):
2245 self.logger.error(logging_text + msg)
2246 else:
2247 self.logger.critical(logging_text + msg, exc_info=True)
quilesjdd799ac2020-01-23 16:31:11 +00002248 raise LcmException(msg)
calvinosanch9f9c6f22019-11-04 13:37:39 +01002249 finally:
calvinosanch9f9c6f22019-11-04 13:37:39 +01002250 if db_nsr_update:
2251 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernoda6fb102019-11-23 00:36:52 +00002252
quilesj7e13aeb2019-10-08 13:34:55 +02002253 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 +01002254 kdu_name, member_vnf_index, vdu_index, vdu_name, deploy_params, descriptor_config,
tiernoe876f672020-02-13 14:34:48 +00002255 base_folder, task_instantiation_info, stage):
quilesj7e13aeb2019-10-08 13:34:55 +02002256 # launch instantiate_N2VC in a asyncio task and register task object
2257 # Look where information of this charm is at database <nsrs>._admin.deployed.VCA
2258 # if not found, create one entry and update database
tiernobaa51102018-12-14 13:16:18 +00002259
quilesj7e13aeb2019-10-08 13:34:55 +02002260 # fill db_nsr._admin.deployed.VCA.<index>
2261 vca_index = -1
2262 for vca_index, vca_deployed in enumerate(db_nsr["_admin"]["deployed"]["VCA"]):
2263 if not vca_deployed:
2264 continue
2265 if vca_deployed.get("member-vnf-index") == member_vnf_index and \
2266 vca_deployed.get("vdu_id") == vdu_id and \
calvinosanch9f9c6f22019-11-04 13:37:39 +01002267 vca_deployed.get("kdu_name") == kdu_name and \
quilesj7e13aeb2019-10-08 13:34:55 +02002268 vca_deployed.get("vdu_count_index", 0) == vdu_index:
2269 break
2270 else:
2271 # not found, create one.
2272 vca_deployed = {
2273 "member-vnf-index": member_vnf_index,
2274 "vdu_id": vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002275 "kdu_name": kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02002276 "vdu_count_index": vdu_index,
2277 "operational-status": "init", # TODO revise
2278 "detailed-status": "", # TODO revise
2279 "step": "initial-deploy", # TODO revise
2280 "vnfd_id": vnfd_id,
2281 "vdu_name": vdu_name,
2282 }
2283 vca_index += 1
quilesj3655ae02019-12-12 16:08:35 +00002284
2285 # create VCA and configurationStatus in db
2286 db_dict = {
2287 "_admin.deployed.VCA.{}".format(vca_index): vca_deployed,
2288 "configurationStatus.{}".format(vca_index): dict()
2289 }
2290 self.update_db_2("nsrs", nsr_id, db_dict)
2291
quilesj7e13aeb2019-10-08 13:34:55 +02002292 db_nsr["_admin"]["deployed"]["VCA"].append(vca_deployed)
2293
2294 # Launch task
2295 task_n2vc = asyncio.ensure_future(
2296 self.instantiate_N2VC(
2297 logging_text=logging_text,
2298 vca_index=vca_index,
2299 nsi_id=nsi_id,
2300 db_nsr=db_nsr,
2301 db_vnfr=db_vnfr,
2302 vdu_id=vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01002303 kdu_name=kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02002304 vdu_index=vdu_index,
2305 deploy_params=deploy_params,
2306 config_descriptor=descriptor_config,
2307 base_folder=base_folder,
tiernoe876f672020-02-13 14:34:48 +00002308 nslcmop_id=nslcmop_id,
2309 stage=stage
quilesj7e13aeb2019-10-08 13:34:55 +02002310 )
2311 )
2312 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "instantiate_N2VC-{}".format(vca_index), task_n2vc)
tiernoe876f672020-02-13 14:34:48 +00002313 task_instantiation_info[task_n2vc] = self.task_name_deploy_vca + " {}.{}".format(
2314 member_vnf_index or "", vdu_id or "")
tiernobaa51102018-12-14 13:16:18 +00002315
kuuse0ca67472019-05-13 15:59:27 +02002316 # Check if this VNFD has a configured terminate action
2317 def _has_terminate_config_primitive(self, vnfd):
2318 vnf_config = vnfd.get("vnf-configuration")
2319 if vnf_config and vnf_config.get("terminate-config-primitive"):
2320 return True
2321 else:
2322 return False
2323
tiernoc9556972019-07-05 15:25:25 +00002324 @staticmethod
2325 def _get_terminate_config_primitive_seq_list(vnfd):
2326 """ Get a numerically sorted list of the sequences for this VNFD's terminate action """
kuuse0ca67472019-05-13 15:59:27 +02002327 # No need to check for existing primitive twice, already done before
2328 vnf_config = vnfd.get("vnf-configuration")
2329 seq_list = vnf_config.get("terminate-config-primitive")
2330 # Get all 'seq' tags in seq_list, order sequences numerically, ascending.
2331 seq_list_sorted = sorted(seq_list, key=lambda x: int(x['seq']))
2332 return seq_list_sorted
2333
2334 @staticmethod
2335 def _create_nslcmop(nsr_id, operation, params):
2336 """
2337 Creates a ns-lcm-opp content to be stored at database.
2338 :param nsr_id: internal id of the instance
2339 :param operation: instantiate, terminate, scale, action, ...
2340 :param params: user parameters for the operation
2341 :return: dictionary following SOL005 format
2342 """
2343 # Raise exception if invalid arguments
2344 if not (nsr_id and operation and params):
2345 raise LcmException(
2346 "Parameters 'nsr_id', 'operation' and 'params' needed to create primitive not provided")
2347 now = time()
2348 _id = str(uuid4())
2349 nslcmop = {
2350 "id": _id,
2351 "_id": _id,
2352 # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2353 "operationState": "PROCESSING",
2354 "statusEnteredTime": now,
2355 "nsInstanceId": nsr_id,
2356 "lcmOperationType": operation,
2357 "startTime": now,
2358 "isAutomaticInvocation": False,
2359 "operationParams": params,
2360 "isCancelPending": False,
2361 "links": {
2362 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
2363 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
2364 }
2365 }
2366 return nslcmop
2367
calvinosanch9f9c6f22019-11-04 13:37:39 +01002368 def _format_additional_params(self, params):
tierno626e0152019-11-29 14:16:16 +00002369 params = params or {}
calvinosanch9f9c6f22019-11-04 13:37:39 +01002370 for key, value in params.items():
2371 if str(value).startswith("!!yaml "):
2372 params[key] = yaml.safe_load(value[7:])
calvinosanch9f9c6f22019-11-04 13:37:39 +01002373 return params
2374
kuuse8b998e42019-07-30 15:22:16 +02002375 def _get_terminate_primitive_params(self, seq, vnf_index):
2376 primitive = seq.get('name')
2377 primitive_params = {}
2378 params = {
2379 "member_vnf_index": vnf_index,
2380 "primitive": primitive,
2381 "primitive_params": primitive_params,
2382 }
2383 desc_params = {}
2384 return self._map_primitive_params(seq, params, desc_params)
2385
kuuseac3a8882019-10-03 10:48:06 +02002386 # sub-operations
2387
tierno51183952020-04-03 15:48:18 +00002388 def _retry_or_skip_suboperation(self, db_nslcmop, op_index):
2389 op = deep_get(db_nslcmop, ('_admin', 'operations'), [])[op_index]
2390 if op.get('operationState') == 'COMPLETED':
kuuseac3a8882019-10-03 10:48:06 +02002391 # b. Skip sub-operation
2392 # _ns_execute_primitive() or RO.create_action() will NOT be executed
2393 return self.SUBOPERATION_STATUS_SKIP
2394 else:
2395 # c. Reintent executing sub-operation
2396 # The sub-operation exists, and operationState != 'COMPLETED'
2397 # Update operationState = 'PROCESSING' to indicate a reintent.
2398 operationState = 'PROCESSING'
2399 detailed_status = 'In progress'
2400 self._update_suboperation_status(
2401 db_nslcmop, op_index, operationState, detailed_status)
2402 # Return the sub-operation index
2403 # _ns_execute_primitive() or RO.create_action() will be called from scale()
2404 # with arguments extracted from the sub-operation
2405 return op_index
2406
2407 # Find a sub-operation where all keys in a matching dictionary must match
2408 # Returns the index of the matching sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if no match
2409 def _find_suboperation(self, db_nslcmop, match):
2410 if (db_nslcmop and match):
2411 op_list = db_nslcmop.get('_admin', {}).get('operations', [])
2412 for i, op in enumerate(op_list):
2413 if all(op.get(k) == match[k] for k in match):
2414 return i
2415 return self.SUBOPERATION_STATUS_NOT_FOUND
2416
2417 # Update status for a sub-operation given its index
2418 def _update_suboperation_status(self, db_nslcmop, op_index, operationState, detailed_status):
2419 # Update DB for HA tasks
2420 q_filter = {'_id': db_nslcmop['_id']}
2421 update_dict = {'_admin.operations.{}.operationState'.format(op_index): operationState,
2422 '_admin.operations.{}.detailed-status'.format(op_index): detailed_status}
2423 self.db.set_one("nslcmops",
2424 q_filter=q_filter,
2425 update_dict=update_dict,
2426 fail_on_empty=False)
2427
2428 # Add sub-operation, return the index of the added sub-operation
2429 # Optionally, set operationState, detailed-status, and operationType
2430 # Status and type are currently set for 'scale' sub-operations:
2431 # 'operationState' : 'PROCESSING' | 'COMPLETED' | 'FAILED'
2432 # 'detailed-status' : status message
2433 # 'operationType': may be any type, in the case of scaling: 'PRE-SCALE' | 'POST-SCALE'
2434 # Status and operation type are currently only used for 'scale', but NOT for 'terminate' sub-operations.
quilesj7e13aeb2019-10-08 13:34:55 +02002435 def _add_suboperation(self, db_nslcmop, vnf_index, vdu_id, vdu_count_index, vdu_name, primitive,
2436 mapped_primitive_params, operationState=None, detailed_status=None, operationType=None,
kuuseac3a8882019-10-03 10:48:06 +02002437 RO_nsr_id=None, RO_scaling_info=None):
tiernoe876f672020-02-13 14:34:48 +00002438 if not db_nslcmop:
kuuseac3a8882019-10-03 10:48:06 +02002439 return self.SUBOPERATION_STATUS_NOT_FOUND
2440 # Get the "_admin.operations" list, if it exists
2441 db_nslcmop_admin = db_nslcmop.get('_admin', {})
2442 op_list = db_nslcmop_admin.get('operations')
2443 # Create or append to the "_admin.operations" list
kuuse8b998e42019-07-30 15:22:16 +02002444 new_op = {'member_vnf_index': vnf_index,
2445 'vdu_id': vdu_id,
2446 'vdu_count_index': vdu_count_index,
2447 'primitive': primitive,
2448 'primitive_params': mapped_primitive_params}
kuuseac3a8882019-10-03 10:48:06 +02002449 if operationState:
2450 new_op['operationState'] = operationState
2451 if detailed_status:
2452 new_op['detailed-status'] = detailed_status
2453 if operationType:
2454 new_op['lcmOperationType'] = operationType
2455 if RO_nsr_id:
2456 new_op['RO_nsr_id'] = RO_nsr_id
2457 if RO_scaling_info:
2458 new_op['RO_scaling_info'] = RO_scaling_info
2459 if not op_list:
2460 # No existing operations, create key 'operations' with current operation as first list element
2461 db_nslcmop_admin.update({'operations': [new_op]})
2462 op_list = db_nslcmop_admin.get('operations')
2463 else:
2464 # Existing operations, append operation to list
2465 op_list.append(new_op)
kuuse8b998e42019-07-30 15:22:16 +02002466
kuuseac3a8882019-10-03 10:48:06 +02002467 db_nslcmop_update = {'_admin.operations': op_list}
2468 self.update_db_2("nslcmops", db_nslcmop['_id'], db_nslcmop_update)
2469 op_index = len(op_list) - 1
2470 return op_index
2471
2472 # Helper methods for scale() sub-operations
2473
2474 # pre-scale/post-scale:
2475 # Check for 3 different cases:
2476 # a. New: First time execution, return SUBOPERATION_STATUS_NEW
2477 # b. Skip: Existing sub-operation exists, operationState == 'COMPLETED', return SUBOPERATION_STATUS_SKIP
2478 # c. Reintent: Existing sub-operation exists, operationState != 'COMPLETED', return op_index to re-execute
quilesj7e13aeb2019-10-08 13:34:55 +02002479 def _check_or_add_scale_suboperation(self, db_nslcmop, vnf_index, vnf_config_primitive, primitive_params,
2480 operationType, RO_nsr_id=None, RO_scaling_info=None):
kuuseac3a8882019-10-03 10:48:06 +02002481 # Find this sub-operation
2482 if (RO_nsr_id and RO_scaling_info):
2483 operationType = 'SCALE-RO'
2484 match = {
2485 'member_vnf_index': vnf_index,
2486 'RO_nsr_id': RO_nsr_id,
2487 'RO_scaling_info': RO_scaling_info,
2488 }
2489 else:
2490 match = {
2491 'member_vnf_index': vnf_index,
2492 'primitive': vnf_config_primitive,
2493 'primitive_params': primitive_params,
2494 'lcmOperationType': operationType
2495 }
2496 op_index = self._find_suboperation(db_nslcmop, match)
tierno51183952020-04-03 15:48:18 +00002497 if op_index == self.SUBOPERATION_STATUS_NOT_FOUND:
kuuseac3a8882019-10-03 10:48:06 +02002498 # a. New sub-operation
2499 # The sub-operation does not exist, add it.
2500 # _ns_execute_primitive() will be called from scale() as usual, with non-modified arguments
2501 # The following parameters are set to None for all kind of scaling:
2502 vdu_id = None
2503 vdu_count_index = None
2504 vdu_name = None
tierno51183952020-04-03 15:48:18 +00002505 if RO_nsr_id and RO_scaling_info:
kuuseac3a8882019-10-03 10:48:06 +02002506 vnf_config_primitive = None
2507 primitive_params = None
2508 else:
2509 RO_nsr_id = None
2510 RO_scaling_info = None
2511 # Initial status for sub-operation
2512 operationState = 'PROCESSING'
2513 detailed_status = 'In progress'
2514 # Add sub-operation for pre/post-scaling (zero or more operations)
2515 self._add_suboperation(db_nslcmop,
2516 vnf_index,
2517 vdu_id,
2518 vdu_count_index,
2519 vdu_name,
2520 vnf_config_primitive,
2521 primitive_params,
2522 operationState,
2523 detailed_status,
2524 operationType,
2525 RO_nsr_id,
2526 RO_scaling_info)
2527 return self.SUBOPERATION_STATUS_NEW
2528 else:
2529 # Return either SUBOPERATION_STATUS_SKIP (operationState == 'COMPLETED'),
2530 # or op_index (operationState != 'COMPLETED')
tierno51183952020-04-03 15:48:18 +00002531 return self._retry_or_skip_suboperation(db_nslcmop, op_index)
kuuseac3a8882019-10-03 10:48:06 +02002532
preethika.pdf7d8e02019-12-10 13:10:48 +00002533 # Function to return execution_environment id
2534
2535 def _get_ee_id(self, vnf_index, vdu_id, vca_deployed_list):
tiernoe876f672020-02-13 14:34:48 +00002536 # TODO vdu_index_count
preethika.pdf7d8e02019-12-10 13:10:48 +00002537 for vca in vca_deployed_list:
2538 if vca["member-vnf-index"] == vnf_index and vca["vdu_id"] == vdu_id:
2539 return vca["ee_id"]
2540
tiernoe876f672020-02-13 14:34:48 +00002541 async def destroy_N2VC(self, logging_text, db_nslcmop, vca_deployed, config_descriptor, vca_index, destroy_ee=True):
2542 """
2543 Execute the terminate primitives and destroy the execution environment (if destroy_ee=False
2544 :param logging_text:
2545 :param db_nslcmop:
2546 :param vca_deployed: Dictionary of deployment info at db_nsr._admin.depoloyed.VCA.<INDEX>
2547 :param config_descriptor: Configuration descriptor of the NSD, VNFD, VNFD.vdu or VNFD.kdu
2548 :param vca_index: index in the database _admin.deployed.VCA
2549 :param destroy_ee: False to do not destroy, because it will be destroyed all of then at once
2550 :return: None or exception
2551 """
2552 # execute terminate_primitives
2553 terminate_primitives = config_descriptor.get("terminate-config-primitive")
2554 vdu_id = vca_deployed.get("vdu_id")
2555 vdu_count_index = vca_deployed.get("vdu_count_index")
2556 vdu_name = vca_deployed.get("vdu_name")
2557 vnf_index = vca_deployed.get("member-vnf-index")
2558 if terminate_primitives and vca_deployed.get("needed_terminate"):
2559 # Get all 'seq' tags in seq_list, order sequences numerically, ascending.
2560 terminate_primitives = sorted(terminate_primitives, key=lambda x: int(x['seq']))
2561 for seq in terminate_primitives:
kuuse8b998e42019-07-30 15:22:16 +02002562 # For each sequence in list, get primitive and call _ns_execute_primitive()
kuuse0ca67472019-05-13 15:59:27 +02002563 step = "Calling terminate action for vnf_member_index={} primitive={}".format(
2564 vnf_index, seq.get("name"))
2565 self.logger.debug(logging_text + step)
kuuse8b998e42019-07-30 15:22:16 +02002566 # Create the primitive for each sequence, i.e. "primitive": "touch"
kuuse0ca67472019-05-13 15:59:27 +02002567 primitive = seq.get('name')
kuuse8b998e42019-07-30 15:22:16 +02002568 mapped_primitive_params = self._get_terminate_primitive_params(seq, vnf_index)
2569 # The following 3 parameters are currently set to None for 'terminate':
2570 # vdu_id, vdu_count_index, vdu_name
tiernoe876f672020-02-13 14:34:48 +00002571
kuuseac3a8882019-10-03 10:48:06 +02002572 # Add sub-operation
kuuse8b998e42019-07-30 15:22:16 +02002573 self._add_suboperation(db_nslcmop,
kuuse8b998e42019-07-30 15:22:16 +02002574 vnf_index,
2575 vdu_id,
2576 vdu_count_index,
2577 vdu_name,
2578 primitive,
2579 mapped_primitive_params)
kuuseac3a8882019-10-03 10:48:06 +02002580 # Sub-operations: Call _ns_execute_primitive() instead of action()
quilesj7e13aeb2019-10-08 13:34:55 +02002581 try:
tiernoe876f672020-02-13 14:34:48 +00002582 result, result_detail = await self._ns_execute_primitive(vca_deployed["ee_id"], primitive,
2583 mapped_primitive_params)
2584 except LcmException:
2585 # this happens when VCA is not deployed. In this case it is not needed to terminate
2586 continue
2587 result_ok = ['COMPLETED', 'PARTIALLY_COMPLETED']
2588 if result not in result_ok:
2589 raise LcmException("terminate_primitive {} for vnf_member_index={} fails with "
2590 "error {}".format(seq.get("name"), vnf_index, result_detail))
2591 # set that this VCA do not need terminated
2592 db_update_entry = "_admin.deployed.VCA.{}.needed_terminate".format(vca_index)
2593 self.update_db_2("nsrs", db_nslcmop["nsInstanceId"], {db_update_entry: False})
2594
2595 if destroy_ee:
2596 await self.n2vc.delete_execution_environment(vca_deployed["ee_id"])
kuuse0ca67472019-05-13 15:59:27 +02002597
tierno51183952020-04-03 15:48:18 +00002598 async def _delete_all_N2VC(self, db_nsr: dict):
2599 self._write_all_config_status(db_nsr=db_nsr, status='TERMINATING')
2600 namespace = "." + db_nsr["_id"]
tiernof59ad6c2020-04-08 12:50:52 +00002601 try:
2602 await self.n2vc.delete_namespace(namespace=namespace, total_timeout=self.timeout_charm_delete)
2603 except N2VCNotFound: # already deleted. Skip
2604 pass
tierno51183952020-04-03 15:48:18 +00002605 self._write_all_config_status(db_nsr=db_nsr, status='DELETED')
quilesj3655ae02019-12-12 16:08:35 +00002606
tiernoe876f672020-02-13 14:34:48 +00002607 async def _terminate_RO(self, logging_text, nsr_deployed, nsr_id, nslcmop_id, stage):
2608 """
2609 Terminates a deployment from RO
2610 :param logging_text:
2611 :param nsr_deployed: db_nsr._admin.deployed
2612 :param nsr_id:
2613 :param nslcmop_id:
2614 :param stage: list of string with the content to write on db_nslcmop.detailed-status.
2615 this method will update only the index 2, but it will write on database the concatenated content of the list
2616 :return:
2617 """
2618 db_nsr_update = {}
2619 failed_detail = []
2620 ro_nsr_id = ro_delete_action = None
2621 if nsr_deployed and nsr_deployed.get("RO"):
2622 ro_nsr_id = nsr_deployed["RO"].get("nsr_id")
2623 ro_delete_action = nsr_deployed["RO"].get("nsr_delete_action_id")
2624 try:
2625 if ro_nsr_id:
2626 stage[2] = "Deleting ns from VIM."
2627 db_nsr_update["detailed-status"] = " ".join(stage)
2628 self._write_op_status(nslcmop_id, stage)
2629 self.logger.debug(logging_text + stage[2])
2630 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2631 self._write_op_status(nslcmop_id, stage)
2632 desc = await self.RO.delete("ns", ro_nsr_id)
2633 ro_delete_action = desc["action_id"]
2634 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = ro_delete_action
2635 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
2636 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
2637 if ro_delete_action:
2638 # wait until NS is deleted from VIM
2639 stage[2] = "Waiting ns deleted from VIM."
2640 detailed_status_old = None
2641 self.logger.debug(logging_text + stage[2] + " RO_id={} ro_delete_action={}".format(ro_nsr_id,
2642 ro_delete_action))
2643 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2644 self._write_op_status(nslcmop_id, stage)
kuused124bfe2019-06-18 12:09:24 +02002645
tiernoe876f672020-02-13 14:34:48 +00002646 delete_timeout = 20 * 60 # 20 minutes
2647 while delete_timeout > 0:
2648 desc = await self.RO.show(
2649 "ns",
2650 item_id_name=ro_nsr_id,
2651 extra_item="action",
2652 extra_item_id=ro_delete_action)
2653
2654 # deploymentStatus
2655 self._on_update_ro_db(nsrs_id=nsr_id, ro_descriptor=desc)
2656
2657 ns_status, ns_status_info = self.RO.check_action_status(desc)
2658 if ns_status == "ERROR":
2659 raise ROclient.ROClientException(ns_status_info)
2660 elif ns_status == "BUILD":
2661 stage[2] = "Deleting from VIM {}".format(ns_status_info)
2662 elif ns_status == "ACTIVE":
2663 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
2664 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
2665 break
2666 else:
2667 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
2668 if stage[2] != detailed_status_old:
2669 detailed_status_old = stage[2]
2670 db_nsr_update["detailed-status"] = " ".join(stage)
2671 self._write_op_status(nslcmop_id, stage)
2672 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2673 await asyncio.sleep(5, loop=self.loop)
2674 delete_timeout -= 5
2675 else: # delete_timeout <= 0:
2676 raise ROclient.ROClientException("Timeout waiting ns deleted from VIM")
2677
2678 except Exception as e:
2679 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2680 if isinstance(e, ROclient.ROClientException) and e.http_code == 404: # not found
2681 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
2682 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
2683 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
2684 self.logger.debug(logging_text + "RO_ns_id={} already deleted".format(ro_nsr_id))
2685 elif isinstance(e, ROclient.ROClientException) and e.http_code == 409: # conflict
tiernoa2143262020-03-27 16:20:40 +00002686 failed_detail.append("delete conflict: {}".format(e))
2687 self.logger.debug(logging_text + "RO_ns_id={} delete conflict: {}".format(ro_nsr_id, e))
tiernoe876f672020-02-13 14:34:48 +00002688 else:
tiernoa2143262020-03-27 16:20:40 +00002689 failed_detail.append("delete error: {}".format(e))
2690 self.logger.error(logging_text + "RO_ns_id={} delete error: {}".format(ro_nsr_id, e))
tiernoe876f672020-02-13 14:34:48 +00002691
2692 # Delete nsd
2693 if not failed_detail and deep_get(nsr_deployed, ("RO", "nsd_id")):
2694 ro_nsd_id = nsr_deployed["RO"]["nsd_id"]
2695 try:
2696 stage[2] = "Deleting nsd from RO."
2697 db_nsr_update["detailed-status"] = " ".join(stage)
2698 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2699 self._write_op_status(nslcmop_id, stage)
2700 await self.RO.delete("nsd", ro_nsd_id)
2701 self.logger.debug(logging_text + "ro_nsd_id={} deleted".format(ro_nsd_id))
2702 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
2703 except Exception as e:
2704 if isinstance(e, ROclient.ROClientException) and e.http_code == 404: # not found
2705 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
2706 self.logger.debug(logging_text + "ro_nsd_id={} already deleted".format(ro_nsd_id))
2707 elif isinstance(e, ROclient.ROClientException) and e.http_code == 409: # conflict
2708 failed_detail.append("ro_nsd_id={} delete conflict: {}".format(ro_nsd_id, e))
2709 self.logger.debug(logging_text + failed_detail[-1])
2710 else:
2711 failed_detail.append("ro_nsd_id={} delete error: {}".format(ro_nsd_id, e))
2712 self.logger.error(logging_text + failed_detail[-1])
2713
2714 if not failed_detail and deep_get(nsr_deployed, ("RO", "vnfd")):
2715 for index, vnf_deployed in enumerate(nsr_deployed["RO"]["vnfd"]):
2716 if not vnf_deployed or not vnf_deployed["id"]:
2717 continue
2718 try:
2719 ro_vnfd_id = vnf_deployed["id"]
2720 stage[2] = "Deleting member_vnf_index={} ro_vnfd_id={} from RO.".format(
2721 vnf_deployed["member-vnf-index"], ro_vnfd_id)
2722 db_nsr_update["detailed-status"] = " ".join(stage)
2723 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2724 self._write_op_status(nslcmop_id, stage)
2725 await self.RO.delete("vnfd", ro_vnfd_id)
2726 self.logger.debug(logging_text + "ro_vnfd_id={} deleted".format(ro_vnfd_id))
2727 db_nsr_update["_admin.deployed.RO.vnfd.{}.id".format(index)] = None
2728 except Exception as e:
2729 if isinstance(e, ROclient.ROClientException) and e.http_code == 404: # not found
2730 db_nsr_update["_admin.deployed.RO.vnfd.{}.id".format(index)] = None
2731 self.logger.debug(logging_text + "ro_vnfd_id={} already deleted ".format(ro_vnfd_id))
2732 elif isinstance(e, ROclient.ROClientException) and e.http_code == 409: # conflict
2733 failed_detail.append("ro_vnfd_id={} delete conflict: {}".format(ro_vnfd_id, e))
2734 self.logger.debug(logging_text + failed_detail[-1])
2735 else:
2736 failed_detail.append("ro_vnfd_id={} delete error: {}".format(ro_vnfd_id, e))
2737 self.logger.error(logging_text + failed_detail[-1])
2738
tiernoa2143262020-03-27 16:20:40 +00002739 if failed_detail:
2740 stage[2] = "Error deleting from VIM"
2741 else:
2742 stage[2] = "Deleted from VIM"
tiernoe876f672020-02-13 14:34:48 +00002743 db_nsr_update["detailed-status"] = " ".join(stage)
2744 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2745 self._write_op_status(nslcmop_id, stage)
2746
2747 if failed_detail:
tiernoa2143262020-03-27 16:20:40 +00002748 raise LcmException("; ".join(failed_detail))
tiernoe876f672020-02-13 14:34:48 +00002749
2750 async def terminate(self, nsr_id, nslcmop_id):
kuused124bfe2019-06-18 12:09:24 +02002751 # Try to lock HA task here
2752 task_is_locked_by_me = self.lcm_tasks.lock_HA('ns', 'nslcmops', nslcmop_id)
2753 if not task_is_locked_by_me:
2754 return
2755
tierno59d22d22018-09-25 18:10:19 +02002756 logging_text = "Task ns={} terminate={} ".format(nsr_id, nslcmop_id)
2757 self.logger.debug(logging_text + "Enter")
tiernoe876f672020-02-13 14:34:48 +00002758 timeout_ns_terminate = self.timeout_ns_terminate
tierno59d22d22018-09-25 18:10:19 +02002759 db_nsr = None
2760 db_nslcmop = None
2761 exc = None
tiernoe876f672020-02-13 14:34:48 +00002762 error_list = [] # annotates all failed error messages
tierno59d22d22018-09-25 18:10:19 +02002763 db_nslcmop_update = {}
tiernoc2564fe2019-01-28 16:18:56 +00002764 autoremove = False # autoremove after terminated
tiernoe876f672020-02-13 14:34:48 +00002765 tasks_dict_info = {}
2766 db_nsr_update = {}
2767 stage = ["Stage 1/3: Preparing task.", "Waiting for previous operations to terminate.", ""]
2768 # ^ contains [stage, step, VIM-status]
tierno59d22d22018-09-25 18:10:19 +02002769 try:
kuused124bfe2019-06-18 12:09:24 +02002770 # wait for any previous tasks in process
2771 await self.lcm_tasks.waitfor_related_HA("ns", 'nslcmops', nslcmop_id)
2772
tiernoe876f672020-02-13 14:34:48 +00002773 stage[1] = "Getting nslcmop={} from db.".format(nslcmop_id)
2774 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
2775 operation_params = db_nslcmop.get("operationParams") or {}
2776 if operation_params.get("timeout_ns_terminate"):
2777 timeout_ns_terminate = operation_params["timeout_ns_terminate"]
2778 stage[1] = "Getting nsr={} from db.".format(nsr_id)
2779 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2780
2781 db_nsr_update["operational-status"] = "terminating"
2782 db_nsr_update["config-status"] = "terminating"
quilesj4cda56b2019-12-05 10:02:20 +00002783 self._write_ns_status(
2784 nsr_id=nsr_id,
2785 ns_state="TERMINATING",
2786 current_operation="TERMINATING",
tiernoe876f672020-02-13 14:34:48 +00002787 current_operation_id=nslcmop_id,
2788 other_update=db_nsr_update
quilesj4cda56b2019-12-05 10:02:20 +00002789 )
quilesj3655ae02019-12-12 16:08:35 +00002790 self._write_op_status(
2791 op_id=nslcmop_id,
tiernoe876f672020-02-13 14:34:48 +00002792 queuePosition=0,
2793 stage=stage
quilesj3655ae02019-12-12 16:08:35 +00002794 )
tiernoe876f672020-02-13 14:34:48 +00002795 nsr_deployed = deepcopy(db_nsr["_admin"].get("deployed")) or {}
tierno59d22d22018-09-25 18:10:19 +02002796 if db_nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
2797 return
tierno59d22d22018-09-25 18:10:19 +02002798
tiernoe876f672020-02-13 14:34:48 +00002799 stage[1] = "Getting vnf descriptors from db."
2800 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
2801 db_vnfds_from_id = {}
2802 db_vnfds_from_member_index = {}
2803 # Loop over VNFRs
2804 for vnfr in db_vnfrs_list:
2805 vnfd_id = vnfr["vnfd-id"]
2806 if vnfd_id not in db_vnfds_from_id:
2807 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
2808 db_vnfds_from_id[vnfd_id] = vnfd
2809 db_vnfds_from_member_index[vnfr["member-vnf-index-ref"]] = db_vnfds_from_id[vnfd_id]
calvinosanch9f9c6f22019-11-04 13:37:39 +01002810
tiernoe876f672020-02-13 14:34:48 +00002811 # Destroy individual execution environments when there are terminating primitives.
2812 # Rest of EE will be deleted at once
2813 if not operation_params.get("skip_terminate_primitives"):
2814 stage[0] = "Stage 2/3 execute terminating primitives."
2815 stage[1] = "Looking execution environment that needs terminate."
2816 self.logger.debug(logging_text + stage[1])
2817 for vca_index, vca in enumerate(get_iterable(nsr_deployed, "VCA")):
2818 config_descriptor = None
2819 if not vca or not vca.get("ee_id") or not vca.get("needed_terminate"):
2820 continue
2821 if not vca.get("member-vnf-index"):
2822 # ns
2823 config_descriptor = db_nsr.get("ns-configuration")
2824 elif vca.get("vdu_id"):
2825 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
2826 vdud = next((vdu for vdu in db_vnfd.get("vdu", ()) if vdu["id"] == vca.get("vdu_id")), None)
2827 if vdud:
2828 config_descriptor = vdud.get("vdu-configuration")
2829 elif vca.get("kdu_name"):
2830 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
2831 kdud = next((kdu for kdu in db_vnfd.get("kdu", ()) if kdu["name"] == vca.get("kdu_name")), None)
2832 if kdud:
2833 config_descriptor = kdud.get("kdu-configuration")
2834 else:
2835 config_descriptor = db_vnfds_from_member_index[vca["member-vnf-index"]].get("vnf-configuration")
2836 task = asyncio.ensure_future(self.destroy_N2VC(logging_text, db_nslcmop, vca, config_descriptor,
2837 vca_index, False))
2838 tasks_dict_info[task] = "Terminating VCA {}".format(vca.get("ee_id"))
tierno59d22d22018-09-25 18:10:19 +02002839
tiernoe876f672020-02-13 14:34:48 +00002840 # wait for pending tasks of terminate primitives
2841 if tasks_dict_info:
2842 self.logger.debug(logging_text + 'Waiting for terminate primitive pending tasks...')
2843 error_list = await self._wait_for_tasks(logging_text, tasks_dict_info,
2844 min(self.timeout_charm_delete, timeout_ns_terminate),
2845 stage, nslcmop_id)
2846 if error_list:
2847 return # raise LcmException("; ".join(error_list))
2848 tasks_dict_info.clear()
tierno82974b22018-11-27 21:55:36 +00002849
tiernoe876f672020-02-13 14:34:48 +00002850 # remove All execution environments at once
2851 stage[0] = "Stage 3/3 delete all."
quilesj3655ae02019-12-12 16:08:35 +00002852
tierno49676be2020-04-07 16:34:35 +00002853 if nsr_deployed.get("VCA"):
2854 stage[1] = "Deleting all execution environments."
2855 self.logger.debug(logging_text + stage[1])
2856 task_delete_ee = asyncio.ensure_future(asyncio.wait_for(self._delete_all_N2VC(db_nsr=db_nsr),
2857 timeout=self.timeout_charm_delete))
2858 # task_delete_ee = asyncio.ensure_future(self.n2vc.delete_namespace(namespace="." + nsr_id))
2859 tasks_dict_info[task_delete_ee] = "Terminating all VCA"
tierno59d22d22018-09-25 18:10:19 +02002860
tiernoe876f672020-02-13 14:34:48 +00002861 # Delete from k8scluster
2862 stage[1] = "Deleting KDUs."
2863 self.logger.debug(logging_text + stage[1])
2864 # print(nsr_deployed)
2865 for kdu in get_iterable(nsr_deployed, "K8s"):
2866 if not kdu or not kdu.get("kdu-instance"):
2867 continue
2868 kdu_instance = kdu.get("kdu-instance")
tiernoa2143262020-03-27 16:20:40 +00002869 if kdu.get("k8scluster-type") in self.k8scluster_map:
tiernoe876f672020-02-13 14:34:48 +00002870 task_delete_kdu_instance = asyncio.ensure_future(
tiernoa2143262020-03-27 16:20:40 +00002871 self.k8scluster_map[kdu["k8scluster-type"]].uninstall(
2872 cluster_uuid=kdu.get("k8scluster-uuid"),
2873 kdu_instance=kdu_instance))
tiernoe876f672020-02-13 14:34:48 +00002874 else:
2875 self.logger.error(logging_text + "Unknown k8s deployment type {}".
2876 format(kdu.get("k8scluster-type")))
2877 continue
2878 tasks_dict_info[task_delete_kdu_instance] = "Terminating KDU '{}'".format(kdu.get("kdu-name"))
tierno59d22d22018-09-25 18:10:19 +02002879
2880 # remove from RO
tiernoe876f672020-02-13 14:34:48 +00002881 stage[1] = "Deleting ns from VIM."
2882 task_delete_ro = asyncio.ensure_future(
2883 self._terminate_RO(logging_text, nsr_deployed, nsr_id, nslcmop_id, stage))
2884 tasks_dict_info[task_delete_ro] = "Removing deployment from VIM"
tierno59d22d22018-09-25 18:10:19 +02002885
tiernoe876f672020-02-13 14:34:48 +00002886 # rest of staff will be done at finally
2887
2888 except (ROclient.ROClientException, DbException, LcmException, N2VCException) as e:
2889 self.logger.error(logging_text + "Exit Exception {}".format(e))
2890 exc = e
2891 except asyncio.CancelledError:
2892 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(stage[1]))
2893 exc = "Operation was cancelled"
2894 except Exception as e:
2895 exc = traceback.format_exc()
2896 self.logger.critical(logging_text + "Exit Exception while '{}': {}".format(stage[1], e), exc_info=True)
2897 finally:
2898 if exc:
2899 error_list.append(str(exc))
tierno59d22d22018-09-25 18:10:19 +02002900 try:
tiernoe876f672020-02-13 14:34:48 +00002901 # wait for pending tasks
2902 if tasks_dict_info:
2903 stage[1] = "Waiting for terminate pending tasks."
2904 self.logger.debug(logging_text + stage[1])
2905 error_list += await self._wait_for_tasks(logging_text, tasks_dict_info, timeout_ns_terminate,
2906 stage, nslcmop_id)
2907 stage[1] = stage[2] = ""
2908 except asyncio.CancelledError:
2909 error_list.append("Cancelled")
2910 # TODO cancell all tasks
2911 except Exception as exc:
2912 error_list.append(str(exc))
2913 # update status at database
2914 if error_list:
2915 error_detail = "; ".join(error_list)
2916 # self.logger.error(logging_text + error_detail)
tiernoa2143262020-03-27 16:20:40 +00002917 error_description_nslcmop = 'Stage: {}. Detail: {}'.format(stage[0], error_detail)
2918 error_description_nsr = 'Operation: TERMINATING.{}, Stage {}.'.format(nslcmop_id, stage[0])
tierno59d22d22018-09-25 18:10:19 +02002919
tierno59d22d22018-09-25 18:10:19 +02002920 db_nsr_update["operational-status"] = "failed"
tiernoa2143262020-03-27 16:20:40 +00002921 db_nsr_update["detailed-status"] = error_description_nsr + " Detail: " + error_detail
tiernoe876f672020-02-13 14:34:48 +00002922 db_nslcmop_update["detailed-status"] = error_detail
2923 nslcmop_operation_state = "FAILED"
2924 ns_state = "BROKEN"
tierno59d22d22018-09-25 18:10:19 +02002925 else:
tiernoa2143262020-03-27 16:20:40 +00002926 error_detail = None
tiernoe876f672020-02-13 14:34:48 +00002927 error_description_nsr = error_description_nslcmop = None
2928 ns_state = "NOT_INSTANTIATED"
tierno59d22d22018-09-25 18:10:19 +02002929 db_nsr_update["operational-status"] = "terminated"
2930 db_nsr_update["detailed-status"] = "Done"
2931 db_nsr_update["_admin.nsState"] = "NOT_INSTANTIATED"
2932 db_nslcmop_update["detailed-status"] = "Done"
tiernoe876f672020-02-13 14:34:48 +00002933 nslcmop_operation_state = "COMPLETED"
tierno59d22d22018-09-25 18:10:19 +02002934
tiernoe876f672020-02-13 14:34:48 +00002935 if db_nsr:
2936 self._write_ns_status(
2937 nsr_id=nsr_id,
2938 ns_state=ns_state,
2939 current_operation="IDLE",
2940 current_operation_id=None,
2941 error_description=error_description_nsr,
tiernoa2143262020-03-27 16:20:40 +00002942 error_detail=error_detail,
tiernoe876f672020-02-13 14:34:48 +00002943 other_update=db_nsr_update
2944 )
2945 if db_nslcmop:
2946 self._write_op_status(
2947 op_id=nslcmop_id,
2948 stage="",
2949 error_message=error_description_nslcmop,
2950 operation_state=nslcmop_operation_state,
2951 other_update=db_nslcmop_update,
2952 )
2953 autoremove = operation_params.get("autoremove", False)
tierno59d22d22018-09-25 18:10:19 +02002954 if nslcmop_operation_state:
2955 try:
2956 await self.msg.aiowrite("ns", "terminated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
tiernoc2564fe2019-01-28 16:18:56 +00002957 "operationState": nslcmop_operation_state,
2958 "autoremove": autoremove},
tierno8a518872018-12-21 13:42:14 +00002959 loop=self.loop)
tierno59d22d22018-09-25 18:10:19 +02002960 except Exception as e:
2961 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
quilesj7e13aeb2019-10-08 13:34:55 +02002962
tierno59d22d22018-09-25 18:10:19 +02002963 self.logger.debug(logging_text + "Exit")
2964 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_terminate")
2965
tiernoe876f672020-02-13 14:34:48 +00002966 async def _wait_for_tasks(self, logging_text, created_tasks_info, timeout, stage, nslcmop_id, nsr_id=None):
2967 time_start = time()
tiernoa2143262020-03-27 16:20:40 +00002968 error_detail_list = []
tiernoe876f672020-02-13 14:34:48 +00002969 error_list = []
2970 pending_tasks = list(created_tasks_info.keys())
2971 num_tasks = len(pending_tasks)
2972 num_done = 0
2973 stage[1] = "{}/{}.".format(num_done, num_tasks)
2974 self._write_op_status(nslcmop_id, stage)
tiernoe876f672020-02-13 14:34:48 +00002975 while pending_tasks:
tiernoa2143262020-03-27 16:20:40 +00002976 new_error = None
tiernoe876f672020-02-13 14:34:48 +00002977 _timeout = timeout + time_start - time()
2978 done, pending_tasks = await asyncio.wait(pending_tasks, timeout=_timeout,
2979 return_when=asyncio.FIRST_COMPLETED)
2980 num_done += len(done)
2981 if not done: # Timeout
2982 for task in pending_tasks:
tiernoa2143262020-03-27 16:20:40 +00002983 new_error = created_tasks_info[task] + ": Timeout"
2984 error_detail_list.append(new_error)
2985 error_list.append(new_error)
tiernoe876f672020-02-13 14:34:48 +00002986 break
2987 for task in done:
2988 if task.cancelled():
tierno067e04a2020-03-31 12:53:13 +00002989 exc = "Cancelled"
tiernoe876f672020-02-13 14:34:48 +00002990 else:
2991 exc = task.exception()
tierno067e04a2020-03-31 12:53:13 +00002992 if exc:
2993 if isinstance(exc, asyncio.TimeoutError):
2994 exc = "Timeout"
2995 new_error = created_tasks_info[task] + ": {}".format(exc)
2996 error_list.append(created_tasks_info[task])
2997 error_detail_list.append(new_error)
tierno28c63da2020-04-20 16:28:56 +00002998 if isinstance(exc, (str, DbException, N2VCException, ROclient.ROClientException, LcmException,
2999 K8sException)):
tierno067e04a2020-03-31 12:53:13 +00003000 self.logger.error(logging_text + new_error)
tiernoe876f672020-02-13 14:34:48 +00003001 else:
tierno067e04a2020-03-31 12:53:13 +00003002 exc_traceback = "".join(traceback.format_exception(None, exc, exc.__traceback__))
3003 self.logger.error(logging_text + created_tasks_info[task] + exc_traceback)
3004 else:
3005 self.logger.debug(logging_text + created_tasks_info[task] + ": Done")
tiernoe876f672020-02-13 14:34:48 +00003006 stage[1] = "{}/{}.".format(num_done, num_tasks)
3007 if new_error:
tiernoa2143262020-03-27 16:20:40 +00003008 stage[1] += " Errors: " + ". ".join(error_detail_list) + "."
tiernoe876f672020-02-13 14:34:48 +00003009 if nsr_id: # update also nsr
tiernoa2143262020-03-27 16:20:40 +00003010 self.update_db_2("nsrs", nsr_id, {"errorDescription": "Error at: " + ", ".join(error_list),
3011 "errorDetail": ". ".join(error_detail_list)})
tiernoe876f672020-02-13 14:34:48 +00003012 self._write_op_status(nslcmop_id, stage)
tiernoa2143262020-03-27 16:20:40 +00003013 return error_detail_list
tiernoe876f672020-02-13 14:34:48 +00003014
tiernoda964822019-01-14 15:53:47 +00003015 @staticmethod
3016 def _map_primitive_params(primitive_desc, params, instantiation_params):
3017 """
3018 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
3019 The default-value is used. If it is between < > it look for a value at instantiation_params
3020 :param primitive_desc: portion of VNFD/NSD that describes primitive
3021 :param params: Params provided by user
3022 :param instantiation_params: Instantiation params provided by user
3023 :return: a dictionary with the calculated params
3024 """
3025 calculated_params = {}
3026 for parameter in primitive_desc.get("parameter", ()):
3027 param_name = parameter["name"]
3028 if param_name in params:
3029 calculated_params[param_name] = params[param_name]
tierno98ad6ea2019-05-30 17:16:28 +00003030 elif "default-value" in parameter or "value" in parameter:
3031 if "value" in parameter:
3032 calculated_params[param_name] = parameter["value"]
3033 else:
3034 calculated_params[param_name] = parameter["default-value"]
3035 if isinstance(calculated_params[param_name], str) and calculated_params[param_name].startswith("<") \
3036 and calculated_params[param_name].endswith(">"):
3037 if calculated_params[param_name][1:-1] in instantiation_params:
3038 calculated_params[param_name] = instantiation_params[calculated_params[param_name][1:-1]]
tiernoda964822019-01-14 15:53:47 +00003039 else:
3040 raise LcmException("Parameter {} needed to execute primitive {} not provided".
tiernod8323042019-08-09 11:32:23 +00003041 format(calculated_params[param_name], primitive_desc["name"]))
tiernoda964822019-01-14 15:53:47 +00003042 else:
3043 raise LcmException("Parameter {} needed to execute primitive {} not provided".
3044 format(param_name, primitive_desc["name"]))
tierno59d22d22018-09-25 18:10:19 +02003045
tiernoda964822019-01-14 15:53:47 +00003046 if isinstance(calculated_params[param_name], (dict, list, tuple)):
3047 calculated_params[param_name] = yaml.safe_dump(calculated_params[param_name], default_flow_style=True,
3048 width=256)
3049 elif isinstance(calculated_params[param_name], str) and calculated_params[param_name].startswith("!!yaml "):
3050 calculated_params[param_name] = calculated_params[param_name][7:]
tiernoc3f2a822019-11-05 13:45:04 +00003051
3052 # add always ns_config_info if primitive name is config
3053 if primitive_desc["name"] == "config":
3054 if "ns_config_info" in instantiation_params:
3055 calculated_params["ns_config_info"] = instantiation_params["ns_config_info"]
tiernoda964822019-01-14 15:53:47 +00003056 return calculated_params
3057
tierno067e04a2020-03-31 12:53:13 +00003058 def _look_for_deployed_vca(self, deployed_vca, member_vnf_index, vdu_id, vdu_count_index, kdu_name=None):
tiernoe876f672020-02-13 14:34:48 +00003059 # find vca_deployed record for this action. Raise LcmException if not found or there is not any id.
3060 for vca in deployed_vca:
3061 if not vca:
3062 continue
3063 if member_vnf_index != vca["member-vnf-index"] or vdu_id != vca["vdu_id"]:
3064 continue
tiernoe876f672020-02-13 14:34:48 +00003065 if vdu_count_index is not None and vdu_count_index != vca["vdu_count_index"]:
3066 continue
3067 if kdu_name and kdu_name != vca["kdu_name"]:
3068 continue
3069 break
3070 else:
3071 # vca_deployed not found
tierno067e04a2020-03-31 12:53:13 +00003072 raise LcmException("charm for member_vnf_index={} vdu_id={} kdu_name={} vdu_count_index={} is not "
3073 "deployed".format(member_vnf_index, vdu_id, kdu_name, vdu_count_index))
quilesj7e13aeb2019-10-08 13:34:55 +02003074
tiernoe876f672020-02-13 14:34:48 +00003075 # get ee_id
3076 ee_id = vca.get("ee_id")
3077 if not ee_id:
tierno067e04a2020-03-31 12:53:13 +00003078 raise LcmException("charm for member_vnf_index={} vdu_id={} kdu_name={} vdu_count_index={} has not "
tiernoe876f672020-02-13 14:34:48 +00003079 "execution environment"
tierno067e04a2020-03-31 12:53:13 +00003080 .format(member_vnf_index, vdu_id, kdu_name, vdu_count_index))
tiernoe876f672020-02-13 14:34:48 +00003081 return ee_id
3082
3083 async def _ns_execute_primitive(self, ee_id, primitive, primitive_params, retries=0,
tierno067e04a2020-03-31 12:53:13 +00003084 retries_interval=30, timeout=None) -> (str, str):
tiernoda964822019-01-14 15:53:47 +00003085 try:
tierno98ad6ea2019-05-30 17:16:28 +00003086 if primitive == "config":
3087 primitive_params = {"params": primitive_params}
tierno2fc7ce52019-06-11 22:50:01 +00003088
quilesj7e13aeb2019-10-08 13:34:55 +02003089 while retries >= 0:
3090 try:
tierno067e04a2020-03-31 12:53:13 +00003091 output = await asyncio.wait_for(
3092 self.n2vc.exec_primitive(
3093 ee_id=ee_id,
3094 primitive_name=primitive,
3095 params_dict=primitive_params,
3096 progress_timeout=self.timeout_progress_primitive,
3097 total_timeout=self.timeout_primitive),
3098 timeout=timeout or self.timeout_primitive)
quilesj7e13aeb2019-10-08 13:34:55 +02003099 # execution was OK
3100 break
tierno067e04a2020-03-31 12:53:13 +00003101 except asyncio.CancelledError:
3102 raise
3103 except Exception as e: # asyncio.TimeoutError
3104 if isinstance(e, asyncio.TimeoutError):
3105 e = "Timeout"
quilesj7e13aeb2019-10-08 13:34:55 +02003106 retries -= 1
3107 if retries >= 0:
tierno73d8bd02019-11-18 17:33:27 +00003108 self.logger.debug('Error executing action {} on {} -> {}'.format(primitive, ee_id, e))
quilesj7e13aeb2019-10-08 13:34:55 +02003109 # wait and retry
3110 await asyncio.sleep(retries_interval, loop=self.loop)
tierno73d8bd02019-11-18 17:33:27 +00003111 else:
tierno067e04a2020-03-31 12:53:13 +00003112 return 'FAILED', str(e)
quilesj7e13aeb2019-10-08 13:34:55 +02003113
tiernoe876f672020-02-13 14:34:48 +00003114 return 'COMPLETED', output
quilesj7e13aeb2019-10-08 13:34:55 +02003115
tierno067e04a2020-03-31 12:53:13 +00003116 except (LcmException, asyncio.CancelledError):
tiernoe876f672020-02-13 14:34:48 +00003117 raise
quilesj7e13aeb2019-10-08 13:34:55 +02003118 except Exception as e:
tiernoe876f672020-02-13 14:34:48 +00003119 return 'FAIL', 'Error executing action {}: {}'.format(primitive, e)
tierno59d22d22018-09-25 18:10:19 +02003120
3121 async def action(self, nsr_id, nslcmop_id):
kuused124bfe2019-06-18 12:09:24 +02003122
3123 # Try to lock HA task here
3124 task_is_locked_by_me = self.lcm_tasks.lock_HA('ns', 'nslcmops', nslcmop_id)
3125 if not task_is_locked_by_me:
3126 return
3127
tierno59d22d22018-09-25 18:10:19 +02003128 logging_text = "Task ns={} action={} ".format(nsr_id, nslcmop_id)
3129 self.logger.debug(logging_text + "Enter")
3130 # get all needed from database
3131 db_nsr = None
3132 db_nslcmop = None
tiernoe876f672020-02-13 14:34:48 +00003133 db_nsr_update = {}
tierno59d22d22018-09-25 18:10:19 +02003134 db_nslcmop_update = {}
3135 nslcmop_operation_state = None
tierno067e04a2020-03-31 12:53:13 +00003136 error_description_nslcmop = None
tierno59d22d22018-09-25 18:10:19 +02003137 exc = None
3138 try:
kuused124bfe2019-06-18 12:09:24 +02003139 # wait for any previous tasks in process
tierno3cf81a32019-11-11 17:07:00 +00003140 step = "Waiting for previous operations to terminate"
kuused124bfe2019-06-18 12:09:24 +02003141 await self.lcm_tasks.waitfor_related_HA('ns', 'nslcmops', nslcmop_id)
3142
quilesj4cda56b2019-12-05 10:02:20 +00003143 self._write_ns_status(
3144 nsr_id=nsr_id,
3145 ns_state=None,
3146 current_operation="RUNNING ACTION",
3147 current_operation_id=nslcmop_id
3148 )
3149
tierno59d22d22018-09-25 18:10:19 +02003150 step = "Getting information from database"
3151 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
3152 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
tiernoda964822019-01-14 15:53:47 +00003153
tiernoe4f7e6c2018-11-27 14:55:30 +00003154 nsr_deployed = db_nsr["_admin"].get("deployed")
tierno1b633412019-02-25 16:48:23 +00003155 vnf_index = db_nslcmop["operationParams"].get("member_vnf_index")
tierno59d22d22018-09-25 18:10:19 +02003156 vdu_id = db_nslcmop["operationParams"].get("vdu_id")
calvinosanch9f9c6f22019-11-04 13:37:39 +01003157 kdu_name = db_nslcmop["operationParams"].get("kdu_name")
tiernoe4f7e6c2018-11-27 14:55:30 +00003158 vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
tierno067e04a2020-03-31 12:53:13 +00003159 primitive = db_nslcmop["operationParams"]["primitive"]
3160 primitive_params = db_nslcmop["operationParams"]["primitive_params"]
3161 timeout_ns_action = db_nslcmop["operationParams"].get("timeout_ns_action", self.timeout_primitive)
tierno59d22d22018-09-25 18:10:19 +02003162
tierno1b633412019-02-25 16:48:23 +00003163 if vnf_index:
3164 step = "Getting vnfr from database"
3165 db_vnfr = self.db.get_one("vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id})
3166 step = "Getting vnfd from database"
3167 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
3168 else:
tierno067e04a2020-03-31 12:53:13 +00003169 step = "Getting nsd from database"
3170 db_nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
tiernoda964822019-01-14 15:53:47 +00003171
tierno82974b22018-11-27 21:55:36 +00003172 # for backward compatibility
3173 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
3174 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
3175 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
3176 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3177
tiernoda964822019-01-14 15:53:47 +00003178 # look for primitive
3179 config_primitive_desc = None
3180 if vdu_id:
3181 for vdu in get_iterable(db_vnfd, "vdu"):
3182 if vdu_id == vdu["id"]:
tierno067e04a2020-03-31 12:53:13 +00003183 for config_primitive in deep_get(vdu, ("vdu-configuration", "config-primitive"), ()):
tiernoda964822019-01-14 15:53:47 +00003184 if config_primitive["name"] == primitive:
3185 config_primitive_desc = config_primitive
3186 break
tierno067e04a2020-03-31 12:53:13 +00003187 break
calvinosanch9f9c6f22019-11-04 13:37:39 +01003188 elif kdu_name:
tierno067e04a2020-03-31 12:53:13 +00003189 for kdu in get_iterable(db_vnfd, "kdu"):
3190 if kdu_name == kdu["name"]:
3191 for config_primitive in deep_get(kdu, ("kdu-configuration", "config-primitive"), ()):
3192 if config_primitive["name"] == primitive:
3193 config_primitive_desc = config_primitive
3194 break
3195 break
tierno1b633412019-02-25 16:48:23 +00003196 elif vnf_index:
tierno067e04a2020-03-31 12:53:13 +00003197 for config_primitive in deep_get(db_vnfd, ("vnf-configuration", "config-primitive"), ()):
tierno1b633412019-02-25 16:48:23 +00003198 if config_primitive["name"] == primitive:
3199 config_primitive_desc = config_primitive
3200 break
3201 else:
tierno067e04a2020-03-31 12:53:13 +00003202 for config_primitive in deep_get(db_nsd, ("ns-configuration", "config-primitive"), ()):
tierno1b633412019-02-25 16:48:23 +00003203 if config_primitive["name"] == primitive:
3204 config_primitive_desc = config_primitive
3205 break
tiernoda964822019-01-14 15:53:47 +00003206
tierno067e04a2020-03-31 12:53:13 +00003207 if not config_primitive_desc and not (kdu_name and primitive in ("upgrade", "rollback", "status")):
tierno1b633412019-02-25 16:48:23 +00003208 raise LcmException("Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".
3209 format(primitive))
3210
tierno1b633412019-02-25 16:48:23 +00003211 if vnf_index:
tierno626e0152019-11-29 14:16:16 +00003212 if vdu_id:
3213 vdur = next((x for x in db_vnfr["vdur"] if x["vdu-id-ref"] == vdu_id), None)
tierno067e04a2020-03-31 12:53:13 +00003214 desc_params = self._format_additional_params(vdur.get("additionalParams"))
3215 elif kdu_name:
3216 kdur = next((x for x in db_vnfr["kdur"] if x["kdu-name"] == kdu_name), None)
3217 desc_params = self._format_additional_params(kdur.get("additionalParams"))
3218 else:
3219 desc_params = self._format_additional_params(db_vnfr.get("additionalParamsForVnf"))
tierno1b633412019-02-25 16:48:23 +00003220 else:
tierno067e04a2020-03-31 12:53:13 +00003221 desc_params = self._format_additional_params(db_nsr.get("additionalParamsForNs"))
tiernoda964822019-01-14 15:53:47 +00003222
Dominik Fleischmann771c32b2020-04-07 12:39:36 +02003223 if kdu_name:
3224 kdu_action = True if not deep_get(kdu, ("kdu-configuration", "juju")) else False
3225
tiernoda964822019-01-14 15:53:47 +00003226 # TODO check if ns is in a proper status
Dominik Fleischmann771c32b2020-04-07 12:39:36 +02003227 if kdu_name and (primitive in ("upgrade", "rollback", "status") or kdu_action):
tierno067e04a2020-03-31 12:53:13 +00003228 # kdur and desc_params already set from before
3229 if primitive_params:
3230 desc_params.update(primitive_params)
3231 # TODO Check if we will need something at vnf level
3232 for index, kdu in enumerate(get_iterable(nsr_deployed, "K8s")):
3233 if kdu_name == kdu["kdu-name"] and kdu["member-vnf-index"] == vnf_index:
3234 break
3235 else:
3236 raise LcmException("KDU '{}' for vnf '{}' not deployed".format(kdu_name, vnf_index))
quilesj7e13aeb2019-10-08 13:34:55 +02003237
tierno067e04a2020-03-31 12:53:13 +00003238 if kdu.get("k8scluster-type") not in self.k8scluster_map:
3239 msg = "unknown k8scluster-type '{}'".format(kdu.get("k8scluster-type"))
3240 raise LcmException(msg)
3241
3242 db_dict = {"collection": "nsrs",
3243 "filter": {"_id": nsr_id},
3244 "path": "_admin.deployed.K8s.{}".format(index)}
3245 self.logger.debug(logging_text + "Exec k8s {} on {}.{}".format(primitive, vnf_index, kdu_name))
3246 step = "Executing kdu {}".format(primitive)
3247 if primitive == "upgrade":
3248 if desc_params.get("kdu_model"):
3249 kdu_model = desc_params.get("kdu_model")
3250 del desc_params["kdu_model"]
3251 else:
3252 kdu_model = kdu.get("kdu-model")
3253 parts = kdu_model.split(sep=":")
3254 if len(parts) == 2:
3255 kdu_model = parts[0]
3256
3257 detailed_status = await asyncio.wait_for(
3258 self.k8scluster_map[kdu["k8scluster-type"]].upgrade(
3259 cluster_uuid=kdu.get("k8scluster-uuid"),
3260 kdu_instance=kdu.get("kdu-instance"),
3261 atomic=True, kdu_model=kdu_model,
3262 params=desc_params, db_dict=db_dict,
3263 timeout=timeout_ns_action),
3264 timeout=timeout_ns_action + 10)
3265 self.logger.debug(logging_text + " Upgrade of kdu {} done".format(detailed_status))
3266 elif primitive == "rollback":
3267 detailed_status = await asyncio.wait_for(
3268 self.k8scluster_map[kdu["k8scluster-type"]].rollback(
3269 cluster_uuid=kdu.get("k8scluster-uuid"),
3270 kdu_instance=kdu.get("kdu-instance"),
3271 db_dict=db_dict),
3272 timeout=timeout_ns_action)
3273 elif primitive == "status":
3274 detailed_status = await asyncio.wait_for(
3275 self.k8scluster_map[kdu["k8scluster-type"]].status_kdu(
3276 cluster_uuid=kdu.get("k8scluster-uuid"),
3277 kdu_instance=kdu.get("kdu-instance")),
3278 timeout=timeout_ns_action)
Dominik Fleischmann771c32b2020-04-07 12:39:36 +02003279 else:
3280 kdu_instance = kdu.get("kdu-instance") or "{}-{}".format(kdu["kdu-name"], nsr_id)
3281 params = self._map_primitive_params(config_primitive_desc, primitive_params, desc_params)
3282
3283 detailed_status = await asyncio.wait_for(
3284 self.k8scluster_map[kdu["k8scluster-type"]].exec_primitive(
3285 cluster_uuid=kdu.get("k8scluster-uuid"),
3286 kdu_instance=kdu_instance,
3287 primitive_name=primitive,
3288 params=params, db_dict=db_dict,
3289 timeout=timeout_ns_action),
3290 timeout=timeout_ns_action)
tierno067e04a2020-03-31 12:53:13 +00003291
3292 if detailed_status:
3293 nslcmop_operation_state = 'COMPLETED'
3294 else:
3295 detailed_status = ''
3296 nslcmop_operation_state = 'FAILED'
tierno067e04a2020-03-31 12:53:13 +00003297 else:
3298 nslcmop_operation_state, detailed_status = await self._ns_execute_primitive(
3299 self._look_for_deployed_vca(nsr_deployed["VCA"],
3300 member_vnf_index=vnf_index,
3301 vdu_id=vdu_id,
3302 vdu_count_index=vdu_count_index),
3303 primitive=primitive,
3304 primitive_params=self._map_primitive_params(config_primitive_desc, primitive_params, desc_params),
3305 timeout=timeout_ns_action)
3306
3307 db_nslcmop_update["detailed-status"] = detailed_status
3308 error_description_nslcmop = detailed_status if nslcmop_operation_state == "FAILED" else ""
3309 self.logger.debug(logging_text + " task Done with result {} {}".format(nslcmop_operation_state,
3310 detailed_status))
tierno59d22d22018-09-25 18:10:19 +02003311 return # database update is called inside finally
3312
tiernof59ad6c2020-04-08 12:50:52 +00003313 except (DbException, LcmException, N2VCException, K8sException) as e:
tierno59d22d22018-09-25 18:10:19 +02003314 self.logger.error(logging_text + "Exit Exception {}".format(e))
3315 exc = e
3316 except asyncio.CancelledError:
3317 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
3318 exc = "Operation was cancelled"
tierno067e04a2020-03-31 12:53:13 +00003319 except asyncio.TimeoutError:
3320 self.logger.error(logging_text + "Timeout while '{}'".format(step))
3321 exc = "Timeout"
tierno59d22d22018-09-25 18:10:19 +02003322 except Exception as e:
3323 exc = traceback.format_exc()
3324 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
3325 finally:
tierno067e04a2020-03-31 12:53:13 +00003326 if exc:
3327 db_nslcmop_update["detailed-status"] = detailed_status = error_description_nslcmop = \
kuuse0ca67472019-05-13 15:59:27 +02003328 "FAILED {}: {}".format(step, exc)
tierno067e04a2020-03-31 12:53:13 +00003329 nslcmop_operation_state = "FAILED"
3330 if db_nsr:
3331 self._write_ns_status(
3332 nsr_id=nsr_id,
3333 ns_state=db_nsr["nsState"], # TODO check if degraded. For the moment use previous status
3334 current_operation="IDLE",
3335 current_operation_id=None,
3336 # error_description=error_description_nsr,
3337 # error_detail=error_detail,
3338 other_update=db_nsr_update
3339 )
3340
3341 if db_nslcmop:
3342 self._write_op_status(
3343 op_id=nslcmop_id,
3344 stage="",
3345 error_message=error_description_nslcmop,
3346 operation_state=nslcmop_operation_state,
3347 other_update=db_nslcmop_update,
3348 )
3349
tierno59d22d22018-09-25 18:10:19 +02003350 if nslcmop_operation_state:
3351 try:
3352 await self.msg.aiowrite("ns", "actioned", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
tierno8a518872018-12-21 13:42:14 +00003353 "operationState": nslcmop_operation_state},
3354 loop=self.loop)
tierno59d22d22018-09-25 18:10:19 +02003355 except Exception as e:
3356 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
3357 self.logger.debug(logging_text + "Exit")
3358 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_action")
tierno067e04a2020-03-31 12:53:13 +00003359 return nslcmop_operation_state, detailed_status
tierno59d22d22018-09-25 18:10:19 +02003360
3361 async def scale(self, nsr_id, nslcmop_id):
kuused124bfe2019-06-18 12:09:24 +02003362
3363 # Try to lock HA task here
3364 task_is_locked_by_me = self.lcm_tasks.lock_HA('ns', 'nslcmops', nslcmop_id)
3365 if not task_is_locked_by_me:
3366 return
3367
tierno59d22d22018-09-25 18:10:19 +02003368 logging_text = "Task ns={} scale={} ".format(nsr_id, nslcmop_id)
3369 self.logger.debug(logging_text + "Enter")
3370 # get all needed from database
3371 db_nsr = None
3372 db_nslcmop = None
3373 db_nslcmop_update = {}
3374 nslcmop_operation_state = None
tiernoe876f672020-02-13 14:34:48 +00003375 db_nsr_update = {}
tierno59d22d22018-09-25 18:10:19 +02003376 exc = None
tierno9ab95942018-10-10 16:44:22 +02003377 # in case of error, indicates what part of scale was failed to put nsr at error status
3378 scale_process = None
tiernod6de1992018-10-11 13:05:52 +02003379 old_operational_status = ""
3380 old_config_status = ""
tiernof578e552018-11-08 19:07:20 +01003381 vnfr_scaled = False
tierno59d22d22018-09-25 18:10:19 +02003382 try:
kuused124bfe2019-06-18 12:09:24 +02003383 # wait for any previous tasks in process
tierno3cf81a32019-11-11 17:07:00 +00003384 step = "Waiting for previous operations to terminate"
kuused124bfe2019-06-18 12:09:24 +02003385 await self.lcm_tasks.waitfor_related_HA('ns', 'nslcmops', nslcmop_id)
tierno47e86b52018-10-10 14:05:55 +02003386
quilesj4cda56b2019-12-05 10:02:20 +00003387 self._write_ns_status(
3388 nsr_id=nsr_id,
3389 ns_state=None,
3390 current_operation="SCALING",
3391 current_operation_id=nslcmop_id
3392 )
3393
ikalyvas02d9e7b2019-05-27 18:16:01 +03003394 step = "Getting nslcmop from database"
ikalyvas02d9e7b2019-05-27 18:16:01 +03003395 self.logger.debug(step + " after having waited for previous tasks to be completed")
3396 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
3397 step = "Getting nsr from database"
3398 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
3399
3400 old_operational_status = db_nsr["operational-status"]
3401 old_config_status = db_nsr["config-status"]
tierno59d22d22018-09-25 18:10:19 +02003402 step = "Parsing scaling parameters"
tierno9babfda2019-06-07 12:36:50 +00003403 # self.logger.debug(step)
tierno59d22d22018-09-25 18:10:19 +02003404 db_nsr_update["operational-status"] = "scaling"
3405 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernoe4f7e6c2018-11-27 14:55:30 +00003406 nsr_deployed = db_nsr["_admin"].get("deployed")
calvinosanch9f9c6f22019-11-04 13:37:39 +01003407
3408 #######
3409 nsr_deployed = db_nsr["_admin"].get("deployed")
3410 vnf_index = db_nslcmop["operationParams"].get("member_vnf_index")
tiernoda6fb102019-11-23 00:36:52 +00003411 # vdu_id = db_nslcmop["operationParams"].get("vdu_id")
3412 # vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
3413 # vdu_name = db_nslcmop["operationParams"].get("vdu_name")
calvinosanch9f9c6f22019-11-04 13:37:39 +01003414 #######
3415
tiernoe4f7e6c2018-11-27 14:55:30 +00003416 RO_nsr_id = nsr_deployed["RO"]["nsr_id"]
tierno59d22d22018-09-25 18:10:19 +02003417 vnf_index = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
3418 scaling_group = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
3419 scaling_type = db_nslcmop["operationParams"]["scaleVnfData"]["scaleVnfType"]
3420 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
3421
tierno82974b22018-11-27 21:55:36 +00003422 # for backward compatibility
3423 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
3424 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
3425 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
3426 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3427
tierno59d22d22018-09-25 18:10:19 +02003428 step = "Getting vnfr from database"
3429 db_vnfr = self.db.get_one("vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id})
3430 step = "Getting vnfd from database"
3431 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
ikalyvas02d9e7b2019-05-27 18:16:01 +03003432
tierno59d22d22018-09-25 18:10:19 +02003433 step = "Getting scaling-group-descriptor"
3434 for scaling_descriptor in db_vnfd["scaling-group-descriptor"]:
3435 if scaling_descriptor["name"] == scaling_group:
3436 break
3437 else:
3438 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
3439 "at vnfd:scaling-group-descriptor".format(scaling_group))
ikalyvas02d9e7b2019-05-27 18:16:01 +03003440
tierno59d22d22018-09-25 18:10:19 +02003441 # cooldown_time = 0
3442 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
3443 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
3444 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
3445 # break
3446
3447 # TODO check if ns is in a proper status
tierno15b1cf12019-08-29 13:21:40 +00003448 step = "Sending scale order to VIM"
tierno59d22d22018-09-25 18:10:19 +02003449 nb_scale_op = 0
3450 if not db_nsr["_admin"].get("scaling-group"):
3451 self.update_db_2("nsrs", nsr_id, {"_admin.scaling-group": [{"name": scaling_group, "nb-scale-op": 0}]})
3452 admin_scale_index = 0
3453 else:
3454 for admin_scale_index, admin_scale_info in enumerate(db_nsr["_admin"]["scaling-group"]):
3455 if admin_scale_info["name"] == scaling_group:
3456 nb_scale_op = admin_scale_info.get("nb-scale-op", 0)
3457 break
tierno9ab95942018-10-10 16:44:22 +02003458 else: # not found, set index one plus last element and add new entry with the name
3459 admin_scale_index += 1
3460 db_nsr_update["_admin.scaling-group.{}.name".format(admin_scale_index)] = scaling_group
tierno59d22d22018-09-25 18:10:19 +02003461 RO_scaling_info = []
3462 vdu_scaling_info = {"scaling_group_name": scaling_group, "vdu": []}
3463 if scaling_type == "SCALE_OUT":
3464 # count if max-instance-count is reached
kuuse818d70c2019-08-07 14:43:44 +02003465 max_instance_count = scaling_descriptor.get("max-instance-count", 10)
3466 # self.logger.debug("MAX_INSTANCE_COUNT is {}".format(max_instance_count))
3467 if nb_scale_op >= max_instance_count:
3468 raise LcmException("reached the limit of {} (max-instance-count) "
3469 "scaling-out operations for the "
3470 "scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group))
kuuse8b998e42019-07-30 15:22:16 +02003471
ikalyvas02d9e7b2019-05-27 18:16:01 +03003472 nb_scale_op += 1
tierno59d22d22018-09-25 18:10:19 +02003473 vdu_scaling_info["scaling_direction"] = "OUT"
3474 vdu_scaling_info["vdu-create"] = {}
3475 for vdu_scale_info in scaling_descriptor["vdu"]:
3476 RO_scaling_info.append({"osm_vdu_id": vdu_scale_info["vdu-id-ref"], "member-vnf-index": vnf_index,
3477 "type": "create", "count": vdu_scale_info.get("count", 1)})
3478 vdu_scaling_info["vdu-create"][vdu_scale_info["vdu-id-ref"]] = vdu_scale_info.get("count", 1)
ikalyvas02d9e7b2019-05-27 18:16:01 +03003479
tierno59d22d22018-09-25 18:10:19 +02003480 elif scaling_type == "SCALE_IN":
3481 # count if min-instance-count is reached
tierno27246d82018-09-27 15:59:09 +02003482 min_instance_count = 0
tierno59d22d22018-09-25 18:10:19 +02003483 if "min-instance-count" in scaling_descriptor and scaling_descriptor["min-instance-count"] is not None:
3484 min_instance_count = int(scaling_descriptor["min-instance-count"])
tierno9babfda2019-06-07 12:36:50 +00003485 if nb_scale_op <= min_instance_count:
3486 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
3487 "scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group))
ikalyvas02d9e7b2019-05-27 18:16:01 +03003488 nb_scale_op -= 1
tierno59d22d22018-09-25 18:10:19 +02003489 vdu_scaling_info["scaling_direction"] = "IN"
3490 vdu_scaling_info["vdu-delete"] = {}
3491 for vdu_scale_info in scaling_descriptor["vdu"]:
3492 RO_scaling_info.append({"osm_vdu_id": vdu_scale_info["vdu-id-ref"], "member-vnf-index": vnf_index,
3493 "type": "delete", "count": vdu_scale_info.get("count", 1)})
3494 vdu_scaling_info["vdu-delete"][vdu_scale_info["vdu-id-ref"]] = vdu_scale_info.get("count", 1)
3495
3496 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
tierno27246d82018-09-27 15:59:09 +02003497 vdu_create = vdu_scaling_info.get("vdu-create")
3498 vdu_delete = copy(vdu_scaling_info.get("vdu-delete"))
tierno59d22d22018-09-25 18:10:19 +02003499 if vdu_scaling_info["scaling_direction"] == "IN":
3500 for vdur in reversed(db_vnfr["vdur"]):
tierno27246d82018-09-27 15:59:09 +02003501 if vdu_delete.get(vdur["vdu-id-ref"]):
3502 vdu_delete[vdur["vdu-id-ref"]] -= 1
tierno59d22d22018-09-25 18:10:19 +02003503 vdu_scaling_info["vdu"].append({
3504 "name": vdur["name"],
3505 "vdu_id": vdur["vdu-id-ref"],
3506 "interface": []
3507 })
3508 for interface in vdur["interfaces"]:
3509 vdu_scaling_info["vdu"][-1]["interface"].append({
3510 "name": interface["name"],
3511 "ip_address": interface["ip-address"],
3512 "mac_address": interface.get("mac-address"),
3513 })
tierno27246d82018-09-27 15:59:09 +02003514 vdu_delete = vdu_scaling_info.pop("vdu-delete")
tierno59d22d22018-09-25 18:10:19 +02003515
kuuseac3a8882019-10-03 10:48:06 +02003516 # PRE-SCALE BEGIN
tierno59d22d22018-09-25 18:10:19 +02003517 step = "Executing pre-scale vnf-config-primitive"
3518 if scaling_descriptor.get("scaling-config-action"):
3519 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
kuuseac3a8882019-10-03 10:48:06 +02003520 if (scaling_config_action.get("trigger") == "pre-scale-in" and scaling_type == "SCALE_IN") \
3521 or (scaling_config_action.get("trigger") == "pre-scale-out" and scaling_type == "SCALE_OUT"):
tierno59d22d22018-09-25 18:10:19 +02003522 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
3523 step = db_nslcmop_update["detailed-status"] = \
3524 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive)
tiernoda964822019-01-14 15:53:47 +00003525
tierno59d22d22018-09-25 18:10:19 +02003526 # look for primitive
tierno59d22d22018-09-25 18:10:19 +02003527 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
3528 if config_primitive["name"] == vnf_config_primitive:
tierno59d22d22018-09-25 18:10:19 +02003529 break
3530 else:
3531 raise LcmException(
3532 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
tiernoda964822019-01-14 15:53:47 +00003533 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
tierno59d22d22018-09-25 18:10:19 +02003534 "primitive".format(scaling_group, config_primitive))
tiernoda964822019-01-14 15:53:47 +00003535
tierno16fedf52019-05-24 08:38:26 +00003536 vnfr_params = {"VDU_SCALE_INFO": vdu_scaling_info}
tiernoda964822019-01-14 15:53:47 +00003537 if db_vnfr.get("additionalParamsForVnf"):
3538 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
quilesj7e13aeb2019-10-08 13:34:55 +02003539
tierno9ab95942018-10-10 16:44:22 +02003540 scale_process = "VCA"
tiernod6de1992018-10-11 13:05:52 +02003541 db_nsr_update["config-status"] = "configuring pre-scaling"
kuuseac3a8882019-10-03 10:48:06 +02003542 primitive_params = self._map_primitive_params(config_primitive, {}, vnfr_params)
3543
3544 # Pre-scale reintent check: Check if this sub-operation has been executed before
3545 op_index = self._check_or_add_scale_suboperation(
3546 db_nslcmop, nslcmop_id, vnf_index, vnf_config_primitive, primitive_params, 'PRE-SCALE')
3547 if (op_index == self.SUBOPERATION_STATUS_SKIP):
3548 # Skip sub-operation
3549 result = 'COMPLETED'
3550 result_detail = 'Done'
3551 self.logger.debug(logging_text +
3552 "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
3553 vnf_config_primitive, result, result_detail))
3554 else:
3555 if (op_index == self.SUBOPERATION_STATUS_NEW):
3556 # New sub-operation: Get index of this sub-operation
3557 op_index = len(db_nslcmop.get('_admin', {}).get('operations')) - 1
3558 self.logger.debug(logging_text + "vnf_config_primitive={} New sub-operation".
3559 format(vnf_config_primitive))
3560 else:
3561 # Reintent: Get registered params for this existing sub-operation
3562 op = db_nslcmop.get('_admin', {}).get('operations', [])[op_index]
3563 vnf_index = op.get('member_vnf_index')
3564 vnf_config_primitive = op.get('primitive')
3565 primitive_params = op.get('primitive_params')
3566 self.logger.debug(logging_text + "vnf_config_primitive={} Sub-operation reintent".
3567 format(vnf_config_primitive))
3568 # Execute the primitive, either with new (first-time) or registered (reintent) args
3569 result, result_detail = await self._ns_execute_primitive(
tiernoe876f672020-02-13 14:34:48 +00003570 self._look_for_deployed_vca(nsr_deployed["VCA"],
3571 member_vnf_index=vnf_index,
3572 vdu_id=None,
tiernoe876f672020-02-13 14:34:48 +00003573 vdu_count_index=None),
3574 vnf_config_primitive, primitive_params)
kuuseac3a8882019-10-03 10:48:06 +02003575 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
3576 vnf_config_primitive, result, result_detail))
3577 # Update operationState = COMPLETED | FAILED
3578 self._update_suboperation_status(
3579 db_nslcmop, op_index, result, result_detail)
3580
tierno59d22d22018-09-25 18:10:19 +02003581 if result == "FAILED":
3582 raise LcmException(result_detail)
tiernod6de1992018-10-11 13:05:52 +02003583 db_nsr_update["config-status"] = old_config_status
3584 scale_process = None
kuuseac3a8882019-10-03 10:48:06 +02003585 # PRE-SCALE END
tierno59d22d22018-09-25 18:10:19 +02003586
kuuseac3a8882019-10-03 10:48:06 +02003587 # SCALE RO - BEGIN
3588 # Should this block be skipped if 'RO_nsr_id' == None ?
3589 # if (RO_nsr_id and RO_scaling_info):
tierno59d22d22018-09-25 18:10:19 +02003590 if RO_scaling_info:
tierno9ab95942018-10-10 16:44:22 +02003591 scale_process = "RO"
kuuseac3a8882019-10-03 10:48:06 +02003592 # Scale RO reintent check: Check if this sub-operation has been executed before
3593 op_index = self._check_or_add_scale_suboperation(
3594 db_nslcmop, vnf_index, None, None, 'SCALE-RO', RO_nsr_id, RO_scaling_info)
3595 if (op_index == self.SUBOPERATION_STATUS_SKIP):
3596 # Skip sub-operation
3597 result = 'COMPLETED'
3598 result_detail = 'Done'
3599 self.logger.debug(logging_text + "Skipped sub-operation RO, result {} {}".format(
3600 result, result_detail))
3601 else:
3602 if (op_index == self.SUBOPERATION_STATUS_NEW):
3603 # New sub-operation: Get index of this sub-operation
3604 op_index = len(db_nslcmop.get('_admin', {}).get('operations')) - 1
3605 self.logger.debug(logging_text + "New sub-operation RO")
tierno59d22d22018-09-25 18:10:19 +02003606 else:
kuuseac3a8882019-10-03 10:48:06 +02003607 # Reintent: Get registered params for this existing sub-operation
3608 op = db_nslcmop.get('_admin', {}).get('operations', [])[op_index]
3609 RO_nsr_id = op.get('RO_nsr_id')
3610 RO_scaling_info = op.get('RO_scaling_info')
3611 self.logger.debug(logging_text + "Sub-operation RO reintent".format(
3612 vnf_config_primitive))
3613
3614 RO_desc = await self.RO.create_action("ns", RO_nsr_id, {"vdu-scaling": RO_scaling_info})
3615 db_nsr_update["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index)] = nb_scale_op
3616 db_nsr_update["_admin.scaling-group.{}.time".format(admin_scale_index)] = time()
3617 # wait until ready
3618 RO_nslcmop_id = RO_desc["instance_action_id"]
3619 db_nslcmop_update["_admin.deploy.RO"] = RO_nslcmop_id
3620
3621 RO_task_done = False
3622 step = detailed_status = "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id)
3623 detailed_status_old = None
3624 self.logger.debug(logging_text + step)
3625
3626 deployment_timeout = 1 * 3600 # One hour
3627 while deployment_timeout > 0:
3628 if not RO_task_done:
3629 desc = await self.RO.show("ns", item_id_name=RO_nsr_id, extra_item="action",
3630 extra_item_id=RO_nslcmop_id)
quilesj3655ae02019-12-12 16:08:35 +00003631
3632 # deploymentStatus
3633 self._on_update_ro_db(nsrs_id=nsr_id, ro_descriptor=desc)
3634
kuuseac3a8882019-10-03 10:48:06 +02003635 ns_status, ns_status_info = self.RO.check_action_status(desc)
3636 if ns_status == "ERROR":
3637 raise ROclient.ROClientException(ns_status_info)
3638 elif ns_status == "BUILD":
3639 detailed_status = step + "; {}".format(ns_status_info)
3640 elif ns_status == "ACTIVE":
3641 RO_task_done = True
3642 step = detailed_status = "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id)
3643 self.logger.debug(logging_text + step)
3644 else:
3645 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
tierno59d22d22018-09-25 18:10:19 +02003646 else:
quilesj7e13aeb2019-10-08 13:34:55 +02003647
kuuseac3a8882019-10-03 10:48:06 +02003648 if ns_status == "ERROR":
3649 raise ROclient.ROClientException(ns_status_info)
3650 elif ns_status == "BUILD":
3651 detailed_status = step + "; {}".format(ns_status_info)
3652 elif ns_status == "ACTIVE":
3653 step = detailed_status = \
3654 "Waiting for management IP address reported by the VIM. Updating VNFRs"
3655 if not vnfr_scaled:
3656 self.scale_vnfr(db_vnfr, vdu_create=vdu_create, vdu_delete=vdu_delete)
3657 vnfr_scaled = True
3658 try:
3659 desc = await self.RO.show("ns", RO_nsr_id)
quilesj3655ae02019-12-12 16:08:35 +00003660
3661 # deploymentStatus
3662 self._on_update_ro_db(nsrs_id=nsr_id, ro_descriptor=desc)
3663
kuuseac3a8882019-10-03 10:48:06 +02003664 # nsr_deployed["nsr_ip"] = RO.get_ns_vnf_info(desc)
3665 self.ns_update_vnfr({db_vnfr["member-vnf-index-ref"]: db_vnfr}, desc)
3666 break
3667 except LcmExceptionNoMgmtIP:
3668 pass
3669 else:
3670 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
3671 if detailed_status != detailed_status_old:
3672 self._update_suboperation_status(
3673 db_nslcmop, op_index, 'COMPLETED', detailed_status)
3674 detailed_status_old = db_nslcmop_update["detailed-status"] = detailed_status
3675 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
tierno59d22d22018-09-25 18:10:19 +02003676
kuuseac3a8882019-10-03 10:48:06 +02003677 await asyncio.sleep(5, loop=self.loop)
3678 deployment_timeout -= 5
3679 if deployment_timeout <= 0:
3680 self._update_suboperation_status(
3681 db_nslcmop, nslcmop_id, op_index, 'FAILED', "Timeout when waiting for ns to get ready")
3682 raise ROclient.ROClientException("Timeout waiting ns to be ready")
tierno59d22d22018-09-25 18:10:19 +02003683
kuuseac3a8882019-10-03 10:48:06 +02003684 # update VDU_SCALING_INFO with the obtained ip_addresses
3685 if vdu_scaling_info["scaling_direction"] == "OUT":
3686 for vdur in reversed(db_vnfr["vdur"]):
3687 if vdu_scaling_info["vdu-create"].get(vdur["vdu-id-ref"]):
3688 vdu_scaling_info["vdu-create"][vdur["vdu-id-ref"]] -= 1
3689 vdu_scaling_info["vdu"].append({
3690 "name": vdur["name"],
3691 "vdu_id": vdur["vdu-id-ref"],
3692 "interface": []
tierno59d22d22018-09-25 18:10:19 +02003693 })
kuuseac3a8882019-10-03 10:48:06 +02003694 for interface in vdur["interfaces"]:
3695 vdu_scaling_info["vdu"][-1]["interface"].append({
3696 "name": interface["name"],
3697 "ip_address": interface["ip-address"],
3698 "mac_address": interface.get("mac-address"),
3699 })
3700 del vdu_scaling_info["vdu-create"]
3701
3702 self._update_suboperation_status(db_nslcmop, op_index, 'COMPLETED', 'Done')
3703 # SCALE RO - END
tierno59d22d22018-09-25 18:10:19 +02003704
tierno9ab95942018-10-10 16:44:22 +02003705 scale_process = None
tierno59d22d22018-09-25 18:10:19 +02003706 if db_nsr_update:
3707 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3708
kuuseac3a8882019-10-03 10:48:06 +02003709 # POST-SCALE BEGIN
tierno59d22d22018-09-25 18:10:19 +02003710 # execute primitive service POST-SCALING
3711 step = "Executing post-scale vnf-config-primitive"
3712 if scaling_descriptor.get("scaling-config-action"):
3713 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
kuuseac3a8882019-10-03 10:48:06 +02003714 if (scaling_config_action.get("trigger") == "post-scale-in" and scaling_type == "SCALE_IN") \
3715 or (scaling_config_action.get("trigger") == "post-scale-out" and scaling_type == "SCALE_OUT"):
tierno59d22d22018-09-25 18:10:19 +02003716 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
3717 step = db_nslcmop_update["detailed-status"] = \
3718 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive)
tiernoda964822019-01-14 15:53:47 +00003719
tierno589befb2019-05-29 07:06:23 +00003720 vnfr_params = {"VDU_SCALE_INFO": vdu_scaling_info}
tiernoda964822019-01-14 15:53:47 +00003721 if db_vnfr.get("additionalParamsForVnf"):
3722 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
3723
tierno59d22d22018-09-25 18:10:19 +02003724 # look for primitive
tierno59d22d22018-09-25 18:10:19 +02003725 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
3726 if config_primitive["name"] == vnf_config_primitive:
tierno59d22d22018-09-25 18:10:19 +02003727 break
3728 else:
3729 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
3730 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
tierno47e86b52018-10-10 14:05:55 +02003731 "match any vnf-configuration:config-primitive".format(scaling_group,
3732 config_primitive))
tierno9ab95942018-10-10 16:44:22 +02003733 scale_process = "VCA"
tiernod6de1992018-10-11 13:05:52 +02003734 db_nsr_update["config-status"] = "configuring post-scaling"
kuuseac3a8882019-10-03 10:48:06 +02003735 primitive_params = self._map_primitive_params(config_primitive, {}, vnfr_params)
tiernod6de1992018-10-11 13:05:52 +02003736
kuuseac3a8882019-10-03 10:48:06 +02003737 # Post-scale reintent check: Check if this sub-operation has been executed before
3738 op_index = self._check_or_add_scale_suboperation(
3739 db_nslcmop, nslcmop_id, vnf_index, vnf_config_primitive, primitive_params, 'POST-SCALE')
quilesj4cda56b2019-12-05 10:02:20 +00003740 if op_index == self.SUBOPERATION_STATUS_SKIP:
kuuseac3a8882019-10-03 10:48:06 +02003741 # Skip sub-operation
3742 result = 'COMPLETED'
3743 result_detail = 'Done'
3744 self.logger.debug(logging_text +
3745 "vnf_config_primitive={} Skipped sub-operation, result {} {}".
3746 format(vnf_config_primitive, result, result_detail))
3747 else:
quilesj4cda56b2019-12-05 10:02:20 +00003748 if op_index == self.SUBOPERATION_STATUS_NEW:
kuuseac3a8882019-10-03 10:48:06 +02003749 # New sub-operation: Get index of this sub-operation
3750 op_index = len(db_nslcmop.get('_admin', {}).get('operations')) - 1
3751 self.logger.debug(logging_text + "vnf_config_primitive={} New sub-operation".
3752 format(vnf_config_primitive))
3753 else:
3754 # Reintent: Get registered params for this existing sub-operation
3755 op = db_nslcmop.get('_admin', {}).get('operations', [])[op_index]
3756 vnf_index = op.get('member_vnf_index')
3757 vnf_config_primitive = op.get('primitive')
3758 primitive_params = op.get('primitive_params')
3759 self.logger.debug(logging_text + "vnf_config_primitive={} Sub-operation reintent".
3760 format(vnf_config_primitive))
3761 # Execute the primitive, either with new (first-time) or registered (reintent) args
3762 result, result_detail = await self._ns_execute_primitive(
tiernoe876f672020-02-13 14:34:48 +00003763 self._look_for_deployed_vca(nsr_deployed["VCA"],
3764 member_vnf_index=vnf_index,
3765 vdu_id=None,
tiernoe876f672020-02-13 14:34:48 +00003766 vdu_count_index=None),
3767 vnf_config_primitive, primitive_params)
kuuseac3a8882019-10-03 10:48:06 +02003768 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
3769 vnf_config_primitive, result, result_detail))
3770 # Update operationState = COMPLETED | FAILED
3771 self._update_suboperation_status(
3772 db_nslcmop, op_index, result, result_detail)
3773
tierno59d22d22018-09-25 18:10:19 +02003774 if result == "FAILED":
3775 raise LcmException(result_detail)
tiernod6de1992018-10-11 13:05:52 +02003776 db_nsr_update["config-status"] = old_config_status
3777 scale_process = None
kuuseac3a8882019-10-03 10:48:06 +02003778 # POST-SCALE END
tierno59d22d22018-09-25 18:10:19 +02003779
3780 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
3781 db_nslcmop_update["statusEnteredTime"] = time()
3782 db_nslcmop_update["detailed-status"] = "done"
tiernod6de1992018-10-11 13:05:52 +02003783 db_nsr_update["detailed-status"] = "" # "scaled {} {}".format(scaling_group, scaling_type)
ikalyvas02d9e7b2019-05-27 18:16:01 +03003784 db_nsr_update["operational-status"] = "running" if old_operational_status == "failed" \
3785 else old_operational_status
tiernod6de1992018-10-11 13:05:52 +02003786 db_nsr_update["config-status"] = old_config_status
tierno59d22d22018-09-25 18:10:19 +02003787 return
3788 except (ROclient.ROClientException, DbException, LcmException) as e:
3789 self.logger.error(logging_text + "Exit Exception {}".format(e))
3790 exc = e
3791 except asyncio.CancelledError:
3792 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
3793 exc = "Operation was cancelled"
3794 except Exception as e:
3795 exc = traceback.format_exc()
3796 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
3797 finally:
quilesj3655ae02019-12-12 16:08:35 +00003798 self._write_ns_status(
3799 nsr_id=nsr_id,
3800 ns_state=None,
3801 current_operation="IDLE",
3802 current_operation_id=None
3803 )
tierno59d22d22018-09-25 18:10:19 +02003804 if exc:
3805 if db_nslcmop:
3806 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
3807 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
3808 db_nslcmop_update["statusEnteredTime"] = time()
3809 if db_nsr:
tiernod6de1992018-10-11 13:05:52 +02003810 db_nsr_update["operational-status"] = old_operational_status
3811 db_nsr_update["config-status"] = old_config_status
3812 db_nsr_update["detailed-status"] = ""
3813 if scale_process:
3814 if "VCA" in scale_process:
3815 db_nsr_update["config-status"] = "failed"
3816 if "RO" in scale_process:
3817 db_nsr_update["operational-status"] = "failed"
3818 db_nsr_update["detailed-status"] = "FAILED scaling nslcmop={} {}: {}".format(nslcmop_id, step,
3819 exc)
tiernobaa51102018-12-14 13:16:18 +00003820 try:
3821 if db_nslcmop and db_nslcmop_update:
3822 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
3823 if db_nsr:
quilesj4cda56b2019-12-05 10:02:20 +00003824 self._write_ns_status(
3825 nsr_id=nsr_id,
3826 ns_state=None,
3827 current_operation="IDLE",
tiernoe876f672020-02-13 14:34:48 +00003828 current_operation_id=None,
3829 other_update=db_nsr_update
quilesj4cda56b2019-12-05 10:02:20 +00003830 )
3831
tiernobaa51102018-12-14 13:16:18 +00003832 except DbException as e:
3833 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno59d22d22018-09-25 18:10:19 +02003834 if nslcmop_operation_state:
3835 try:
3836 await self.msg.aiowrite("ns", "scaled", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
tierno8a518872018-12-21 13:42:14 +00003837 "operationState": nslcmop_operation_state},
3838 loop=self.loop)
tierno59d22d22018-09-25 18:10:19 +02003839 # if cooldown_time:
tiernod8323042019-08-09 11:32:23 +00003840 # await asyncio.sleep(cooldown_time, loop=self.loop)
tierno59d22d22018-09-25 18:10:19 +02003841 # await self.msg.aiowrite("ns","scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
3842 except Exception as e:
3843 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
3844 self.logger.debug(logging_text + "Exit")
3845 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_scale")