ab1ee3b1bf1e7940c683bc553fa8acb02236b386
[osm/LCM.git] / osm_lcm / ns.py
1 # -*- coding: utf-8 -*-
2
3 ##
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
19 import asyncio
20 import yaml
21 import logging
22 import logging.handlers
23 import traceback
24 import json
25 from jinja2 import (
26 Environment,
27 TemplateError,
28 TemplateNotFound,
29 StrictUndefined,
30 UndefinedError,
31 )
32
33 from osm_lcm import ROclient
34 from osm_lcm.data_utils.nsr import get_deployed_kdu
35 from osm_lcm.ng_ro import NgRoClient, NgRoException
36 from osm_lcm.lcm_utils import (
37 LcmException,
38 LcmExceptionNoMgmtIP,
39 LcmBase,
40 deep_get,
41 get_iterable,
42 populate_dict,
43 )
44 from osm_lcm.data_utils.nsd import get_vnf_profiles
45 from osm_lcm.data_utils.vnfd import (
46 get_vdu_list,
47 get_vdu_profile,
48 get_ee_sorted_initial_config_primitive_list,
49 get_ee_sorted_terminate_config_primitive_list,
50 get_kdu_list,
51 get_virtual_link_profiles,
52 get_vdu,
53 get_configuration,
54 get_vdu_index,
55 get_scaling_aspect,
56 get_number_of_instances,
57 get_juju_ee_ref,
58 get_kdu_profile,
59 )
60 from osm_lcm.data_utils.list_utils import find_in_list
61 from osm_lcm.data_utils.vnfr import get_osm_params, get_vdur_index, get_kdur
62 from osm_lcm.data_utils.dict_utils import parse_yaml_strings
63 from osm_lcm.data_utils.database.vim_account import VimAccountDB
64 from n2vc.k8s_helm_conn import K8sHelmConnector
65 from n2vc.k8s_helm3_conn import K8sHelm3Connector
66 from n2vc.k8s_juju_conn import K8sJujuConnector
67
68 from osm_common.dbbase import DbException
69 from osm_common.fsbase import FsException
70
71 from osm_lcm.data_utils.database.database import Database
72 from osm_lcm.data_utils.filesystem.filesystem import Filesystem
73
74 from n2vc.n2vc_juju_conn import N2VCJujuConnector
75 from n2vc.exceptions import N2VCException, N2VCNotFound, K8sException
76
77 from osm_lcm.lcm_helm_conn import LCMHelmConn
78
79 from copy import copy, deepcopy
80 from time import time
81 from uuid import uuid4
82
83 from random import randint
84
85 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
86
87
88 class NsLcm(LcmBase):
89 timeout_vca_on_error = (
90 5 * 60
91 ) # Time for charm from first time at blocked,error status to mark as failed
92 timeout_ns_deploy = 2 * 3600 # default global timeout for deployment a ns
93 timeout_ns_terminate = 1800 # default global timeout for un deployment a ns
94 timeout_charm_delete = 10 * 60
95 timeout_primitive = 30 * 60 # timeout for primitive execution
96 timeout_progress_primitive = (
97 10 * 60
98 ) # timeout for some progress in a primitive execution
99
100 SUBOPERATION_STATUS_NOT_FOUND = -1
101 SUBOPERATION_STATUS_NEW = -2
102 SUBOPERATION_STATUS_SKIP = -3
103 task_name_deploy_vca = "Deploying VCA"
104
105 def __init__(self, msg, lcm_tasks, config, loop, prometheus=None):
106 """
107 Init, Connect to database, filesystem storage, and messaging
108 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
109 :return: None
110 """
111 super().__init__(msg=msg, logger=logging.getLogger("lcm.ns"))
112
113 self.db = Database().instance.db
114 self.fs = Filesystem().instance.fs
115 self.loop = loop
116 self.lcm_tasks = lcm_tasks
117 self.timeout = config["timeout"]
118 self.ro_config = config["ro_config"]
119 self.ng_ro = config["ro_config"].get("ng")
120 self.vca_config = config["VCA"].copy()
121
122 # create N2VC connector
123 self.n2vc = N2VCJujuConnector(
124 log=self.logger,
125 loop=self.loop,
126 on_update_db=self._on_update_n2vc_db,
127 fs=self.fs,
128 db=self.db,
129 )
130
131 self.conn_helm_ee = LCMHelmConn(
132 log=self.logger,
133 loop=self.loop,
134 vca_config=self.vca_config,
135 on_update_db=self._on_update_n2vc_db,
136 )
137
138 self.k8sclusterhelm2 = K8sHelmConnector(
139 kubectl_command=self.vca_config.get("kubectlpath"),
140 helm_command=self.vca_config.get("helmpath"),
141 log=self.logger,
142 on_update_db=None,
143 fs=self.fs,
144 db=self.db,
145 )
146
147 self.k8sclusterhelm3 = K8sHelm3Connector(
148 kubectl_command=self.vca_config.get("kubectlpath"),
149 helm_command=self.vca_config.get("helm3path"),
150 fs=self.fs,
151 log=self.logger,
152 db=self.db,
153 on_update_db=None,
154 )
155
156 self.k8sclusterjuju = K8sJujuConnector(
157 kubectl_command=self.vca_config.get("kubectlpath"),
158 juju_command=self.vca_config.get("jujupath"),
159 log=self.logger,
160 loop=self.loop,
161 on_update_db=self._on_update_k8s_db,
162 fs=self.fs,
163 db=self.db,
164 )
165
166 self.k8scluster_map = {
167 "helm-chart": self.k8sclusterhelm2,
168 "helm-chart-v3": self.k8sclusterhelm3,
169 "chart": self.k8sclusterhelm3,
170 "juju-bundle": self.k8sclusterjuju,
171 "juju": self.k8sclusterjuju,
172 }
173
174 self.vca_map = {
175 "lxc_proxy_charm": self.n2vc,
176 "native_charm": self.n2vc,
177 "k8s_proxy_charm": self.n2vc,
178 "helm": self.conn_helm_ee,
179 "helm-v3": self.conn_helm_ee,
180 }
181
182 self.prometheus = prometheus
183
184 # create RO client
185 self.RO = NgRoClient(self.loop, **self.ro_config)
186
187 @staticmethod
188 def increment_ip_mac(ip_mac, vm_index=1):
189 if not isinstance(ip_mac, str):
190 return ip_mac
191 try:
192 # try with ipv4 look for last dot
193 i = ip_mac.rfind(".")
194 if i > 0:
195 i += 1
196 return "{}{}".format(ip_mac[:i], int(ip_mac[i:]) + vm_index)
197 # try with ipv6 or mac look for last colon. Operate in hex
198 i = ip_mac.rfind(":")
199 if i > 0:
200 i += 1
201 # format in hex, len can be 2 for mac or 4 for ipv6
202 return ("{}{:0" + str(len(ip_mac) - i) + "x}").format(
203 ip_mac[:i], int(ip_mac[i:], 16) + vm_index
204 )
205 except Exception:
206 pass
207 return None
208
209 def _on_update_ro_db(self, nsrs_id, ro_descriptor):
210
211 # self.logger.debug('_on_update_ro_db(nsrs_id={}'.format(nsrs_id))
212
213 try:
214 # TODO filter RO descriptor fields...
215
216 # write to database
217 db_dict = dict()
218 # db_dict['deploymentStatus'] = yaml.dump(ro_descriptor, default_flow_style=False, indent=2)
219 db_dict["deploymentStatus"] = ro_descriptor
220 self.update_db_2("nsrs", nsrs_id, db_dict)
221
222 except Exception as e:
223 self.logger.warn(
224 "Cannot write database RO deployment for ns={} -> {}".format(nsrs_id, e)
225 )
226
227 async def _on_update_n2vc_db(self, table, filter, path, updated_data, vca_id=None):
228
229 # remove last dot from path (if exists)
230 if path.endswith("."):
231 path = path[:-1]
232
233 # self.logger.debug('_on_update_n2vc_db(table={}, filter={}, path={}, updated_data={}'
234 # .format(table, filter, path, updated_data))
235 try:
236
237 nsr_id = filter.get("_id")
238
239 # read ns record from database
240 nsr = self.db.get_one(table="nsrs", q_filter=filter)
241 current_ns_status = nsr.get("nsState")
242
243 # get vca status for NS
244 status_dict = await self.n2vc.get_status(
245 namespace="." + nsr_id, yaml_format=False, vca_id=vca_id
246 )
247
248 # vcaStatus
249 db_dict = dict()
250 db_dict["vcaStatus"] = status_dict
251 await self.n2vc.update_vca_status(db_dict["vcaStatus"], vca_id=vca_id)
252
253 # update configurationStatus for this VCA
254 try:
255 vca_index = int(path[path.rfind(".") + 1 :])
256
257 vca_list = deep_get(
258 target_dict=nsr, key_list=("_admin", "deployed", "VCA")
259 )
260 vca_status = vca_list[vca_index].get("status")
261
262 configuration_status_list = nsr.get("configurationStatus")
263 config_status = configuration_status_list[vca_index].get("status")
264
265 if config_status == "BROKEN" and vca_status != "failed":
266 db_dict["configurationStatus"][vca_index] = "READY"
267 elif config_status != "BROKEN" and vca_status == "failed":
268 db_dict["configurationStatus"][vca_index] = "BROKEN"
269 except Exception as e:
270 # not update configurationStatus
271 self.logger.debug("Error updating vca_index (ignore): {}".format(e))
272
273 # if nsState = 'READY' check if juju is reporting some error => nsState = 'DEGRADED'
274 # if nsState = 'DEGRADED' check if all is OK
275 is_degraded = False
276 if current_ns_status in ("READY", "DEGRADED"):
277 error_description = ""
278 # check machines
279 if status_dict.get("machines"):
280 for machine_id in status_dict.get("machines"):
281 machine = status_dict.get("machines").get(machine_id)
282 # check machine agent-status
283 if machine.get("agent-status"):
284 s = machine.get("agent-status").get("status")
285 if s != "started":
286 is_degraded = True
287 error_description += (
288 "machine {} agent-status={} ; ".format(
289 machine_id, s
290 )
291 )
292 # check machine instance status
293 if machine.get("instance-status"):
294 s = machine.get("instance-status").get("status")
295 if s != "running":
296 is_degraded = True
297 error_description += (
298 "machine {} instance-status={} ; ".format(
299 machine_id, s
300 )
301 )
302 # check applications
303 if status_dict.get("applications"):
304 for app_id in status_dict.get("applications"):
305 app = status_dict.get("applications").get(app_id)
306 # check application status
307 if app.get("status"):
308 s = app.get("status").get("status")
309 if s != "active":
310 is_degraded = True
311 error_description += (
312 "application {} status={} ; ".format(app_id, s)
313 )
314
315 if error_description:
316 db_dict["errorDescription"] = error_description
317 if current_ns_status == "READY" and is_degraded:
318 db_dict["nsState"] = "DEGRADED"
319 if current_ns_status == "DEGRADED" and not is_degraded:
320 db_dict["nsState"] = "READY"
321
322 # write to database
323 self.update_db_2("nsrs", nsr_id, db_dict)
324
325 except (asyncio.CancelledError, asyncio.TimeoutError):
326 raise
327 except Exception as e:
328 self.logger.warn("Error updating NS state for ns={}: {}".format(nsr_id, e))
329
330 async def _on_update_k8s_db(
331 self, cluster_uuid, kdu_instance, filter=None, vca_id=None
332 ):
333 """
334 Updating vca status in NSR record
335 :param cluster_uuid: UUID of a k8s cluster
336 :param kdu_instance: The unique name of the KDU instance
337 :param filter: To get nsr_id
338 :return: none
339 """
340
341 # self.logger.debug("_on_update_k8s_db(cluster_uuid={}, kdu_instance={}, filter={}"
342 # .format(cluster_uuid, kdu_instance, filter))
343
344 try:
345 nsr_id = filter.get("_id")
346
347 # get vca status for NS
348 vca_status = await self.k8sclusterjuju.status_kdu(
349 cluster_uuid,
350 kdu_instance,
351 complete_status=True,
352 yaml_format=False,
353 vca_id=vca_id,
354 )
355 # vcaStatus
356 db_dict = dict()
357 db_dict["vcaStatus"] = {nsr_id: vca_status}
358
359 await self.k8sclusterjuju.update_vca_status(
360 db_dict["vcaStatus"],
361 kdu_instance,
362 vca_id=vca_id,
363 )
364
365 # write to database
366 self.update_db_2("nsrs", nsr_id, db_dict)
367
368 except (asyncio.CancelledError, asyncio.TimeoutError):
369 raise
370 except Exception as e:
371 self.logger.warn("Error updating NS state for ns={}: {}".format(nsr_id, e))
372
373 @staticmethod
374 def _parse_cloud_init(cloud_init_text, additional_params, vnfd_id, vdu_id):
375 try:
376 env = Environment(undefined=StrictUndefined)
377 template = env.from_string(cloud_init_text)
378 return template.render(additional_params or {})
379 except UndefinedError as e:
380 raise LcmException(
381 "Variable {} at vnfd[id={}]:vdu[id={}]:cloud-init/cloud-init-"
382 "file, must be provided in the instantiation parameters inside the "
383 "'additionalParamsForVnf/Vdu' block".format(e, vnfd_id, vdu_id)
384 )
385 except (TemplateError, TemplateNotFound) as e:
386 raise LcmException(
387 "Error parsing Jinja2 to cloud-init content at vnfd[id={}]:vdu[id={}]: {}".format(
388 vnfd_id, vdu_id, e
389 )
390 )
391
392 def _get_vdu_cloud_init_content(self, vdu, vnfd):
393 cloud_init_content = cloud_init_file = None
394 try:
395 if vdu.get("cloud-init-file"):
396 base_folder = vnfd["_admin"]["storage"]
397 cloud_init_file = "{}/{}/cloud_init/{}".format(
398 base_folder["folder"],
399 base_folder["pkg-dir"],
400 vdu["cloud-init-file"],
401 )
402 with self.fs.file_open(cloud_init_file, "r") as ci_file:
403 cloud_init_content = ci_file.read()
404 elif vdu.get("cloud-init"):
405 cloud_init_content = vdu["cloud-init"]
406
407 return cloud_init_content
408 except FsException as e:
409 raise LcmException(
410 "Error reading vnfd[id={}]:vdu[id={}]:cloud-init-file={}: {}".format(
411 vnfd["id"], vdu["id"], cloud_init_file, e
412 )
413 )
414
415 def _get_vdu_additional_params(self, db_vnfr, vdu_id):
416 vdur = next(
417 vdur for vdur in db_vnfr.get("vdur") if vdu_id == vdur["vdu-id-ref"]
418 )
419 additional_params = vdur.get("additionalParams")
420 return parse_yaml_strings(additional_params)
421
422 def vnfd2RO(self, vnfd, new_id=None, additionalParams=None, nsrId=None):
423 """
424 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
425 :param vnfd: input vnfd
426 :param new_id: overrides vnf id if provided
427 :param additionalParams: Instantiation params for VNFs provided
428 :param nsrId: Id of the NSR
429 :return: copy of vnfd
430 """
431 vnfd_RO = deepcopy(vnfd)
432 # remove unused by RO configuration, monitoring, scaling and internal keys
433 vnfd_RO.pop("_id", None)
434 vnfd_RO.pop("_admin", None)
435 vnfd_RO.pop("monitoring-param", None)
436 vnfd_RO.pop("scaling-group-descriptor", None)
437 vnfd_RO.pop("kdu", None)
438 vnfd_RO.pop("k8s-cluster", None)
439 if new_id:
440 vnfd_RO["id"] = new_id
441
442 # parse cloud-init or cloud-init-file with the provided variables using Jinja2
443 for vdu in get_iterable(vnfd_RO, "vdu"):
444 vdu.pop("cloud-init-file", None)
445 vdu.pop("cloud-init", None)
446 return vnfd_RO
447
448 @staticmethod
449 def ip_profile_2_RO(ip_profile):
450 RO_ip_profile = deepcopy(ip_profile)
451 if "dns-server" in RO_ip_profile:
452 if isinstance(RO_ip_profile["dns-server"], list):
453 RO_ip_profile["dns-address"] = []
454 for ds in RO_ip_profile.pop("dns-server"):
455 RO_ip_profile["dns-address"].append(ds["address"])
456 else:
457 RO_ip_profile["dns-address"] = RO_ip_profile.pop("dns-server")
458 if RO_ip_profile.get("ip-version") == "ipv4":
459 RO_ip_profile["ip-version"] = "IPv4"
460 if RO_ip_profile.get("ip-version") == "ipv6":
461 RO_ip_profile["ip-version"] = "IPv6"
462 if "dhcp-params" in RO_ip_profile:
463 RO_ip_profile["dhcp"] = RO_ip_profile.pop("dhcp-params")
464 return RO_ip_profile
465
466 def _get_ro_vim_id_for_vim_account(self, vim_account):
467 db_vim = self.db.get_one("vim_accounts", {"_id": vim_account})
468 if db_vim["_admin"]["operationalState"] != "ENABLED":
469 raise LcmException(
470 "VIM={} is not available. operationalState={}".format(
471 vim_account, db_vim["_admin"]["operationalState"]
472 )
473 )
474 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
475 return RO_vim_id
476
477 def get_ro_wim_id_for_wim_account(self, wim_account):
478 if isinstance(wim_account, str):
479 db_wim = self.db.get_one("wim_accounts", {"_id": wim_account})
480 if db_wim["_admin"]["operationalState"] != "ENABLED":
481 raise LcmException(
482 "WIM={} is not available. operationalState={}".format(
483 wim_account, db_wim["_admin"]["operationalState"]
484 )
485 )
486 RO_wim_id = db_wim["_admin"]["deployed"]["RO-account"]
487 return RO_wim_id
488 else:
489 return wim_account
490
491 def scale_vnfr(self, db_vnfr, vdu_create=None, vdu_delete=None, mark_delete=False):
492
493 db_vdu_push_list = []
494 db_update = {"_admin.modified": time()}
495 if vdu_create:
496 for vdu_id, vdu_count in vdu_create.items():
497 vdur = next(
498 (
499 vdur
500 for vdur in reversed(db_vnfr["vdur"])
501 if vdur["vdu-id-ref"] == vdu_id
502 ),
503 None,
504 )
505 if not vdur:
506 raise LcmException(
507 "Error scaling OUT VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
508 vdu_id
509 )
510 )
511
512 for count in range(vdu_count):
513 vdur_copy = deepcopy(vdur)
514 vdur_copy["status"] = "BUILD"
515 vdur_copy["status-detailed"] = None
516 vdur_copy["ip-address"] = None
517 vdur_copy["_id"] = str(uuid4())
518 vdur_copy["count-index"] += count + 1
519 vdur_copy["id"] = "{}-{}".format(
520 vdur_copy["vdu-id-ref"], vdur_copy["count-index"]
521 )
522 vdur_copy.pop("vim_info", None)
523 for iface in vdur_copy["interfaces"]:
524 if iface.get("fixed-ip"):
525 iface["ip-address"] = self.increment_ip_mac(
526 iface["ip-address"], count + 1
527 )
528 else:
529 iface.pop("ip-address", None)
530 if iface.get("fixed-mac"):
531 iface["mac-address"] = self.increment_ip_mac(
532 iface["mac-address"], count + 1
533 )
534 else:
535 iface.pop("mac-address", None)
536 iface.pop(
537 "mgmt_vnf", None
538 ) # only first vdu can be managment of vnf
539 db_vdu_push_list.append(vdur_copy)
540 # self.logger.debug("scale out, adding vdu={}".format(vdur_copy))
541 if vdu_delete:
542 for vdu_id, vdu_count in vdu_delete.items():
543 if mark_delete:
544 indexes_to_delete = [
545 iv[0]
546 for iv in enumerate(db_vnfr["vdur"])
547 if iv[1]["vdu-id-ref"] == vdu_id
548 ]
549 db_update.update(
550 {
551 "vdur.{}.status".format(i): "DELETING"
552 for i in indexes_to_delete[-vdu_count:]
553 }
554 )
555 else:
556 # it must be deleted one by one because common.db does not allow otherwise
557 vdus_to_delete = [
558 v
559 for v in reversed(db_vnfr["vdur"])
560 if v["vdu-id-ref"] == vdu_id
561 ]
562 for vdu in vdus_to_delete[:vdu_count]:
563 self.db.set_one(
564 "vnfrs",
565 {"_id": db_vnfr["_id"]},
566 None,
567 pull={"vdur": {"_id": vdu["_id"]}},
568 )
569 db_push = {"vdur": db_vdu_push_list} if db_vdu_push_list else None
570 self.db.set_one("vnfrs", {"_id": db_vnfr["_id"]}, db_update, push_list=db_push)
571 # modify passed dictionary db_vnfr
572 db_vnfr_ = self.db.get_one("vnfrs", {"_id": db_vnfr["_id"]})
573 db_vnfr["vdur"] = db_vnfr_["vdur"]
574
575 def ns_update_nsr(self, ns_update_nsr, db_nsr, nsr_desc_RO):
576 """
577 Updates database nsr with the RO info for the created vld
578 :param ns_update_nsr: dictionary to be filled with the updated info
579 :param db_nsr: content of db_nsr. This is also modified
580 :param nsr_desc_RO: nsr descriptor from RO
581 :return: Nothing, LcmException is raised on errors
582 """
583
584 for vld_index, vld in enumerate(get_iterable(db_nsr, "vld")):
585 for net_RO in get_iterable(nsr_desc_RO, "nets"):
586 if vld["id"] != net_RO.get("ns_net_osm_id"):
587 continue
588 vld["vim-id"] = net_RO.get("vim_net_id")
589 vld["name"] = net_RO.get("vim_name")
590 vld["status"] = net_RO.get("status")
591 vld["status-detailed"] = net_RO.get("error_msg")
592 ns_update_nsr["vld.{}".format(vld_index)] = vld
593 break
594 else:
595 raise LcmException(
596 "ns_update_nsr: Not found vld={} at RO info".format(vld["id"])
597 )
598
599 def set_vnfr_at_error(self, db_vnfrs, error_text):
600 try:
601 for db_vnfr in db_vnfrs.values():
602 vnfr_update = {"status": "ERROR"}
603 for vdu_index, vdur in enumerate(get_iterable(db_vnfr, "vdur")):
604 if "status" not in vdur:
605 vdur["status"] = "ERROR"
606 vnfr_update["vdur.{}.status".format(vdu_index)] = "ERROR"
607 if error_text:
608 vdur["status-detailed"] = str(error_text)
609 vnfr_update[
610 "vdur.{}.status-detailed".format(vdu_index)
611 ] = "ERROR"
612 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
613 except DbException as e:
614 self.logger.error("Cannot update vnf. {}".format(e))
615
616 def ns_update_vnfr(self, db_vnfrs, nsr_desc_RO):
617 """
618 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
619 :param db_vnfrs: dictionary with member-vnf-index: vnfr-content
620 :param nsr_desc_RO: nsr descriptor from RO
621 :return: Nothing, LcmException is raised on errors
622 """
623 for vnf_index, db_vnfr in db_vnfrs.items():
624 for vnf_RO in nsr_desc_RO["vnfs"]:
625 if vnf_RO["member_vnf_index"] != vnf_index:
626 continue
627 vnfr_update = {}
628 if vnf_RO.get("ip_address"):
629 db_vnfr["ip-address"] = vnfr_update["ip-address"] = vnf_RO[
630 "ip_address"
631 ].split(";")[0]
632 elif not db_vnfr.get("ip-address"):
633 if db_vnfr.get("vdur"): # if not VDUs, there is not ip_address
634 raise LcmExceptionNoMgmtIP(
635 "ns member_vnf_index '{}' has no IP address".format(
636 vnf_index
637 )
638 )
639
640 for vdu_index, vdur in enumerate(get_iterable(db_vnfr, "vdur")):
641 vdur_RO_count_index = 0
642 if vdur.get("pdu-type"):
643 continue
644 for vdur_RO in get_iterable(vnf_RO, "vms"):
645 if vdur["vdu-id-ref"] != vdur_RO["vdu_osm_id"]:
646 continue
647 if vdur["count-index"] != vdur_RO_count_index:
648 vdur_RO_count_index += 1
649 continue
650 vdur["vim-id"] = vdur_RO.get("vim_vm_id")
651 if vdur_RO.get("ip_address"):
652 vdur["ip-address"] = vdur_RO["ip_address"].split(";")[0]
653 else:
654 vdur["ip-address"] = None
655 vdur["vdu-id-ref"] = vdur_RO.get("vdu_osm_id")
656 vdur["name"] = vdur_RO.get("vim_name")
657 vdur["status"] = vdur_RO.get("status")
658 vdur["status-detailed"] = vdur_RO.get("error_msg")
659 for ifacer in get_iterable(vdur, "interfaces"):
660 for interface_RO in get_iterable(vdur_RO, "interfaces"):
661 if ifacer["name"] == interface_RO.get("internal_name"):
662 ifacer["ip-address"] = interface_RO.get(
663 "ip_address"
664 )
665 ifacer["mac-address"] = interface_RO.get(
666 "mac_address"
667 )
668 break
669 else:
670 raise LcmException(
671 "ns_update_vnfr: Not found member_vnf_index={} vdur={} interface={} "
672 "from VIM info".format(
673 vnf_index, vdur["vdu-id-ref"], ifacer["name"]
674 )
675 )
676 vnfr_update["vdur.{}".format(vdu_index)] = vdur
677 break
678 else:
679 raise LcmException(
680 "ns_update_vnfr: Not found member_vnf_index={} vdur={} count_index={} from "
681 "VIM info".format(
682 vnf_index, vdur["vdu-id-ref"], vdur["count-index"]
683 )
684 )
685
686 for vld_index, vld in enumerate(get_iterable(db_vnfr, "vld")):
687 for net_RO in get_iterable(nsr_desc_RO, "nets"):
688 if vld["id"] != net_RO.get("vnf_net_osm_id"):
689 continue
690 vld["vim-id"] = net_RO.get("vim_net_id")
691 vld["name"] = net_RO.get("vim_name")
692 vld["status"] = net_RO.get("status")
693 vld["status-detailed"] = net_RO.get("error_msg")
694 vnfr_update["vld.{}".format(vld_index)] = vld
695 break
696 else:
697 raise LcmException(
698 "ns_update_vnfr: Not found member_vnf_index={} vld={} from VIM info".format(
699 vnf_index, vld["id"]
700 )
701 )
702
703 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
704 break
705
706 else:
707 raise LcmException(
708 "ns_update_vnfr: Not found member_vnf_index={} from VIM info".format(
709 vnf_index
710 )
711 )
712
713 def _get_ns_config_info(self, nsr_id):
714 """
715 Generates a mapping between vnf,vdu elements and the N2VC id
716 :param nsr_id: id of nsr to get last database _admin.deployed.VCA that contains this list
717 :return: a dictionary with {osm-config-mapping: {}} where its element contains:
718 "<member-vnf-index>": <N2VC-id> for a vnf configuration, or
719 "<member-vnf-index>.<vdu.id>.<vdu replica(0, 1,..)>": <N2VC-id> for a vdu configuration
720 """
721 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
722 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
723 mapping = {}
724 ns_config_info = {"osm-config-mapping": mapping}
725 for vca in vca_deployed_list:
726 if not vca["member-vnf-index"]:
727 continue
728 if not vca["vdu_id"]:
729 mapping[vca["member-vnf-index"]] = vca["application"]
730 else:
731 mapping[
732 "{}.{}.{}".format(
733 vca["member-vnf-index"], vca["vdu_id"], vca["vdu_count_index"]
734 )
735 ] = vca["application"]
736 return ns_config_info
737
738 async def _instantiate_ng_ro(
739 self,
740 logging_text,
741 nsr_id,
742 nsd,
743 db_nsr,
744 db_nslcmop,
745 db_vnfrs,
746 db_vnfds,
747 n2vc_key_list,
748 stage,
749 start_deploy,
750 timeout_ns_deploy,
751 ):
752
753 db_vims = {}
754
755 def get_vim_account(vim_account_id):
756 nonlocal db_vims
757 if vim_account_id in db_vims:
758 return db_vims[vim_account_id]
759 db_vim = self.db.get_one("vim_accounts", {"_id": vim_account_id})
760 db_vims[vim_account_id] = db_vim
761 return db_vim
762
763 # modify target_vld info with instantiation parameters
764 def parse_vld_instantiation_params(
765 target_vim, target_vld, vld_params, target_sdn
766 ):
767 if vld_params.get("ip-profile"):
768 target_vld["vim_info"][target_vim]["ip_profile"] = vld_params[
769 "ip-profile"
770 ]
771 if vld_params.get("provider-network"):
772 target_vld["vim_info"][target_vim]["provider_network"] = vld_params[
773 "provider-network"
774 ]
775 if "sdn-ports" in vld_params["provider-network"] and target_sdn:
776 target_vld["vim_info"][target_sdn]["sdn-ports"] = vld_params[
777 "provider-network"
778 ]["sdn-ports"]
779 if vld_params.get("wimAccountId"):
780 target_wim = "wim:{}".format(vld_params["wimAccountId"])
781 target_vld["vim_info"][target_wim] = {}
782 for param in ("vim-network-name", "vim-network-id"):
783 if vld_params.get(param):
784 if isinstance(vld_params[param], dict):
785 for vim, vim_net in vld_params[param].items():
786 other_target_vim = "vim:" + vim
787 populate_dict(
788 target_vld["vim_info"],
789 (other_target_vim, param.replace("-", "_")),
790 vim_net,
791 )
792 else: # isinstance str
793 target_vld["vim_info"][target_vim][
794 param.replace("-", "_")
795 ] = vld_params[param]
796 if vld_params.get("common_id"):
797 target_vld["common_id"] = vld_params.get("common_id")
798
799 # modify target["ns"]["vld"] with instantiation parameters to override vnf vim-account
800 def update_ns_vld_target(target, ns_params):
801 for vnf_params in ns_params.get("vnf", ()):
802 if vnf_params.get("vimAccountId"):
803 target_vnf = next(
804 (
805 vnfr
806 for vnfr in db_vnfrs.values()
807 if vnf_params["member-vnf-index"]
808 == vnfr["member-vnf-index-ref"]
809 ),
810 None,
811 )
812 vdur = next((vdur for vdur in target_vnf.get("vdur", ())), None)
813 for a_index, a_vld in enumerate(target["ns"]["vld"]):
814 target_vld = find_in_list(
815 get_iterable(vdur, "interfaces"),
816 lambda iface: iface.get("ns-vld-id") == a_vld["name"],
817 )
818 if target_vld:
819 if vnf_params.get("vimAccountId") not in a_vld.get(
820 "vim_info", {}
821 ):
822 target["ns"]["vld"][a_index].get("vim_info").update(
823 {
824 "vim:{}".format(vnf_params["vimAccountId"]): {
825 "vim_network_name": ""
826 }
827 }
828 )
829
830 nslcmop_id = db_nslcmop["_id"]
831 target = {
832 "name": db_nsr["name"],
833 "ns": {"vld": []},
834 "vnf": [],
835 "image": deepcopy(db_nsr["image"]),
836 "flavor": deepcopy(db_nsr["flavor"]),
837 "action_id": nslcmop_id,
838 "cloud_init_content": {},
839 }
840 for image in target["image"]:
841 image["vim_info"] = {}
842 for flavor in target["flavor"]:
843 flavor["vim_info"] = {}
844
845 if db_nslcmop.get("lcmOperationType") != "instantiate":
846 # get parameters of instantiation:
847 db_nslcmop_instantiate = self.db.get_list(
848 "nslcmops",
849 {
850 "nsInstanceId": db_nslcmop["nsInstanceId"],
851 "lcmOperationType": "instantiate",
852 },
853 )[-1]
854 ns_params = db_nslcmop_instantiate.get("operationParams")
855 else:
856 ns_params = db_nslcmop.get("operationParams")
857 ssh_keys_instantiation = ns_params.get("ssh_keys") or []
858 ssh_keys_all = ssh_keys_instantiation + (n2vc_key_list or [])
859
860 cp2target = {}
861 for vld_index, vld in enumerate(db_nsr.get("vld")):
862 target_vim = "vim:{}".format(ns_params["vimAccountId"])
863 target_vld = {
864 "id": vld["id"],
865 "name": vld["name"],
866 "mgmt-network": vld.get("mgmt-network", False),
867 "type": vld.get("type"),
868 "vim_info": {
869 target_vim: {
870 "vim_network_name": vld.get("vim-network-name"),
871 "vim_account_id": ns_params["vimAccountId"],
872 }
873 },
874 }
875 # check if this network needs SDN assist
876 if vld.get("pci-interfaces"):
877 db_vim = get_vim_account(ns_params["vimAccountId"])
878 sdnc_id = db_vim["config"].get("sdn-controller")
879 if sdnc_id:
880 sdn_vld = "nsrs:{}:vld.{}".format(nsr_id, vld["id"])
881 target_sdn = "sdn:{}".format(sdnc_id)
882 target_vld["vim_info"][target_sdn] = {
883 "sdn": True,
884 "target_vim": target_vim,
885 "vlds": [sdn_vld],
886 "type": vld.get("type"),
887 }
888
889 nsd_vnf_profiles = get_vnf_profiles(nsd)
890 for nsd_vnf_profile in nsd_vnf_profiles:
891 for cp in nsd_vnf_profile["virtual-link-connectivity"]:
892 if cp["virtual-link-profile-id"] == vld["id"]:
893 cp2target[
894 "member_vnf:{}.{}".format(
895 cp["constituent-cpd-id"][0][
896 "constituent-base-element-id"
897 ],
898 cp["constituent-cpd-id"][0]["constituent-cpd-id"],
899 )
900 ] = "nsrs:{}:vld.{}".format(nsr_id, vld_index)
901
902 # check at nsd descriptor, if there is an ip-profile
903 vld_params = {}
904 nsd_vlp = find_in_list(
905 get_virtual_link_profiles(nsd),
906 lambda a_link_profile: a_link_profile["virtual-link-desc-id"]
907 == vld["id"],
908 )
909 if (
910 nsd_vlp
911 and nsd_vlp.get("virtual-link-protocol-data")
912 and nsd_vlp["virtual-link-protocol-data"].get("l3-protocol-data")
913 ):
914 ip_profile_source_data = nsd_vlp["virtual-link-protocol-data"][
915 "l3-protocol-data"
916 ]
917 ip_profile_dest_data = {}
918 if "ip-version" in ip_profile_source_data:
919 ip_profile_dest_data["ip-version"] = ip_profile_source_data[
920 "ip-version"
921 ]
922 if "cidr" in ip_profile_source_data:
923 ip_profile_dest_data["subnet-address"] = ip_profile_source_data[
924 "cidr"
925 ]
926 if "gateway-ip" in ip_profile_source_data:
927 ip_profile_dest_data["gateway-address"] = ip_profile_source_data[
928 "gateway-ip"
929 ]
930 if "dhcp-enabled" in ip_profile_source_data:
931 ip_profile_dest_data["dhcp-params"] = {
932 "enabled": ip_profile_source_data["dhcp-enabled"]
933 }
934 vld_params["ip-profile"] = ip_profile_dest_data
935
936 # update vld_params with instantiation params
937 vld_instantiation_params = find_in_list(
938 get_iterable(ns_params, "vld"),
939 lambda a_vld: a_vld["name"] in (vld["name"], vld["id"]),
940 )
941 if vld_instantiation_params:
942 vld_params.update(vld_instantiation_params)
943 parse_vld_instantiation_params(target_vim, target_vld, vld_params, None)
944 target["ns"]["vld"].append(target_vld)
945 # Update the target ns_vld if vnf vim_account is overriden by instantiation params
946 update_ns_vld_target(target, ns_params)
947
948 for vnfr in db_vnfrs.values():
949 vnfd = find_in_list(
950 db_vnfds, lambda db_vnf: db_vnf["id"] == vnfr["vnfd-ref"]
951 )
952 vnf_params = find_in_list(
953 get_iterable(ns_params, "vnf"),
954 lambda a_vnf: a_vnf["member-vnf-index"] == vnfr["member-vnf-index-ref"],
955 )
956 target_vnf = deepcopy(vnfr)
957 target_vim = "vim:{}".format(vnfr["vim-account-id"])
958 for vld in target_vnf.get("vld", ()):
959 # check if connected to a ns.vld, to fill target'
960 vnf_cp = find_in_list(
961 vnfd.get("int-virtual-link-desc", ()),
962 lambda cpd: cpd.get("id") == vld["id"],
963 )
964 if vnf_cp:
965 ns_cp = "member_vnf:{}.{}".format(
966 vnfr["member-vnf-index-ref"], vnf_cp["id"]
967 )
968 if cp2target.get(ns_cp):
969 vld["target"] = cp2target[ns_cp]
970
971 vld["vim_info"] = {
972 target_vim: {"vim_network_name": vld.get("vim-network-name")}
973 }
974 # check if this network needs SDN assist
975 target_sdn = None
976 if vld.get("pci-interfaces"):
977 db_vim = get_vim_account(vnfr["vim-account-id"])
978 sdnc_id = db_vim["config"].get("sdn-controller")
979 if sdnc_id:
980 sdn_vld = "vnfrs:{}:vld.{}".format(target_vnf["_id"], vld["id"])
981 target_sdn = "sdn:{}".format(sdnc_id)
982 vld["vim_info"][target_sdn] = {
983 "sdn": True,
984 "target_vim": target_vim,
985 "vlds": [sdn_vld],
986 "type": vld.get("type"),
987 }
988
989 # check at vnfd descriptor, if there is an ip-profile
990 vld_params = {}
991 vnfd_vlp = find_in_list(
992 get_virtual_link_profiles(vnfd),
993 lambda a_link_profile: a_link_profile["id"] == vld["id"],
994 )
995 if (
996 vnfd_vlp
997 and vnfd_vlp.get("virtual-link-protocol-data")
998 and vnfd_vlp["virtual-link-protocol-data"].get("l3-protocol-data")
999 ):
1000 ip_profile_source_data = vnfd_vlp["virtual-link-protocol-data"][
1001 "l3-protocol-data"
1002 ]
1003 ip_profile_dest_data = {}
1004 if "ip-version" in ip_profile_source_data:
1005 ip_profile_dest_data["ip-version"] = ip_profile_source_data[
1006 "ip-version"
1007 ]
1008 if "cidr" in ip_profile_source_data:
1009 ip_profile_dest_data["subnet-address"] = ip_profile_source_data[
1010 "cidr"
1011 ]
1012 if "gateway-ip" in ip_profile_source_data:
1013 ip_profile_dest_data[
1014 "gateway-address"
1015 ] = ip_profile_source_data["gateway-ip"]
1016 if "dhcp-enabled" in ip_profile_source_data:
1017 ip_profile_dest_data["dhcp-params"] = {
1018 "enabled": ip_profile_source_data["dhcp-enabled"]
1019 }
1020
1021 vld_params["ip-profile"] = ip_profile_dest_data
1022 # update vld_params with instantiation params
1023 if vnf_params:
1024 vld_instantiation_params = find_in_list(
1025 get_iterable(vnf_params, "internal-vld"),
1026 lambda i_vld: i_vld["name"] == vld["id"],
1027 )
1028 if vld_instantiation_params:
1029 vld_params.update(vld_instantiation_params)
1030 parse_vld_instantiation_params(target_vim, vld, vld_params, target_sdn)
1031
1032 vdur_list = []
1033 for vdur in target_vnf.get("vdur", ()):
1034 if vdur.get("status") == "DELETING" or vdur.get("pdu-type"):
1035 continue # This vdu must not be created
1036 vdur["vim_info"] = {"vim_account_id": vnfr["vim-account-id"]}
1037
1038 self.logger.debug("NS > ssh_keys > {}".format(ssh_keys_all))
1039
1040 if ssh_keys_all:
1041 vdu_configuration = get_configuration(vnfd, vdur["vdu-id-ref"])
1042 vnf_configuration = get_configuration(vnfd, vnfd["id"])
1043 if (
1044 vdu_configuration
1045 and vdu_configuration.get("config-access")
1046 and vdu_configuration.get("config-access").get("ssh-access")
1047 ):
1048 vdur["ssh-keys"] = ssh_keys_all
1049 vdur["ssh-access-required"] = vdu_configuration[
1050 "config-access"
1051 ]["ssh-access"]["required"]
1052 elif (
1053 vnf_configuration
1054 and vnf_configuration.get("config-access")
1055 and vnf_configuration.get("config-access").get("ssh-access")
1056 and any(iface.get("mgmt-vnf") for iface in vdur["interfaces"])
1057 ):
1058 vdur["ssh-keys"] = ssh_keys_all
1059 vdur["ssh-access-required"] = vnf_configuration[
1060 "config-access"
1061 ]["ssh-access"]["required"]
1062 elif ssh_keys_instantiation and find_in_list(
1063 vdur["interfaces"], lambda iface: iface.get("mgmt-vnf")
1064 ):
1065 vdur["ssh-keys"] = ssh_keys_instantiation
1066
1067 self.logger.debug("NS > vdur > {}".format(vdur))
1068
1069 vdud = get_vdu(vnfd, vdur["vdu-id-ref"])
1070 # cloud-init
1071 if vdud.get("cloud-init-file"):
1072 vdur["cloud-init"] = "{}:file:{}".format(
1073 vnfd["_id"], vdud.get("cloud-init-file")
1074 )
1075 # read file and put content at target.cloul_init_content. Avoid ng_ro to use shared package system
1076 if vdur["cloud-init"] not in target["cloud_init_content"]:
1077 base_folder = vnfd["_admin"]["storage"]
1078 cloud_init_file = "{}/{}/cloud_init/{}".format(
1079 base_folder["folder"],
1080 base_folder["pkg-dir"],
1081 vdud.get("cloud-init-file"),
1082 )
1083 with self.fs.file_open(cloud_init_file, "r") as ci_file:
1084 target["cloud_init_content"][
1085 vdur["cloud-init"]
1086 ] = ci_file.read()
1087 elif vdud.get("cloud-init"):
1088 vdur["cloud-init"] = "{}:vdu:{}".format(
1089 vnfd["_id"], get_vdu_index(vnfd, vdur["vdu-id-ref"])
1090 )
1091 # put content at target.cloul_init_content. Avoid ng_ro read vnfd descriptor
1092 target["cloud_init_content"][vdur["cloud-init"]] = vdud[
1093 "cloud-init"
1094 ]
1095 vdur["additionalParams"] = vdur.get("additionalParams") or {}
1096 deploy_params_vdu = self._format_additional_params(
1097 vdur.get("additionalParams") or {}
1098 )
1099 deploy_params_vdu["OSM"] = get_osm_params(
1100 vnfr, vdur["vdu-id-ref"], vdur["count-index"]
1101 )
1102 vdur["additionalParams"] = deploy_params_vdu
1103
1104 # flavor
1105 ns_flavor = target["flavor"][int(vdur["ns-flavor-id"])]
1106 if target_vim not in ns_flavor["vim_info"]:
1107 ns_flavor["vim_info"][target_vim] = {}
1108
1109 # deal with images
1110 # in case alternative images are provided we must check if they should be applied
1111 # for the vim_type, modify the vim_type taking into account
1112 ns_image_id = int(vdur["ns-image-id"])
1113 if vdur.get("alt-image-ids"):
1114 db_vim = get_vim_account(vnfr["vim-account-id"])
1115 vim_type = db_vim["vim_type"]
1116 for alt_image_id in vdur.get("alt-image-ids"):
1117 ns_alt_image = target["image"][int(alt_image_id)]
1118 if vim_type == ns_alt_image.get("vim-type"):
1119 # must use alternative image
1120 self.logger.debug(
1121 "use alternative image id: {}".format(alt_image_id)
1122 )
1123 ns_image_id = alt_image_id
1124 vdur["ns-image-id"] = ns_image_id
1125 break
1126 ns_image = target["image"][int(ns_image_id)]
1127 if target_vim not in ns_image["vim_info"]:
1128 ns_image["vim_info"][target_vim] = {}
1129
1130 vdur["vim_info"] = {target_vim: {}}
1131 # instantiation parameters
1132 # if vnf_params:
1133 # vdu_instantiation_params = next((v for v in get_iterable(vnf_params, "vdu") if v["id"] ==
1134 # vdud["id"]), None)
1135 vdur_list.append(vdur)
1136 target_vnf["vdur"] = vdur_list
1137 target["vnf"].append(target_vnf)
1138
1139 desc = await self.RO.deploy(nsr_id, target)
1140 self.logger.debug("RO return > {}".format(desc))
1141 action_id = desc["action_id"]
1142 await self._wait_ng_ro(
1143 nsr_id, action_id, nslcmop_id, start_deploy, timeout_ns_deploy, stage
1144 )
1145
1146 # Updating NSR
1147 db_nsr_update = {
1148 "_admin.deployed.RO.operational-status": "running",
1149 "detailed-status": " ".join(stage),
1150 }
1151 # db_nsr["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
1152 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1153 self._write_op_status(nslcmop_id, stage)
1154 self.logger.debug(
1155 logging_text + "ns deployed at RO. RO_id={}".format(action_id)
1156 )
1157 return
1158
1159 async def _wait_ng_ro(
1160 self,
1161 nsr_id,
1162 action_id,
1163 nslcmop_id=None,
1164 start_time=None,
1165 timeout=600,
1166 stage=None,
1167 ):
1168 detailed_status_old = None
1169 db_nsr_update = {}
1170 start_time = start_time or time()
1171 while time() <= start_time + timeout:
1172 desc_status = await self.RO.status(nsr_id, action_id)
1173 self.logger.debug("Wait NG RO > {}".format(desc_status))
1174 if desc_status["status"] == "FAILED":
1175 raise NgRoException(desc_status["details"])
1176 elif desc_status["status"] == "BUILD":
1177 if stage:
1178 stage[2] = "VIM: ({})".format(desc_status["details"])
1179 elif desc_status["status"] == "DONE":
1180 if stage:
1181 stage[2] = "Deployed at VIM"
1182 break
1183 else:
1184 assert False, "ROclient.check_ns_status returns unknown {}".format(
1185 desc_status["status"]
1186 )
1187 if stage and nslcmop_id and stage[2] != detailed_status_old:
1188 detailed_status_old = stage[2]
1189 db_nsr_update["detailed-status"] = " ".join(stage)
1190 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1191 self._write_op_status(nslcmop_id, stage)
1192 await asyncio.sleep(15, loop=self.loop)
1193 else: # timeout_ns_deploy
1194 raise NgRoException("Timeout waiting ns to deploy")
1195
1196 async def _terminate_ng_ro(
1197 self, logging_text, nsr_deployed, nsr_id, nslcmop_id, stage
1198 ):
1199 db_nsr_update = {}
1200 failed_detail = []
1201 action_id = None
1202 start_deploy = time()
1203 try:
1204 target = {
1205 "ns": {"vld": []},
1206 "vnf": [],
1207 "image": [],
1208 "flavor": [],
1209 "action_id": nslcmop_id,
1210 }
1211 desc = await self.RO.deploy(nsr_id, target)
1212 action_id = desc["action_id"]
1213 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = action_id
1214 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETING"
1215 self.logger.debug(
1216 logging_text
1217 + "ns terminate action at RO. action_id={}".format(action_id)
1218 )
1219
1220 # wait until done
1221 delete_timeout = 20 * 60 # 20 minutes
1222 await self._wait_ng_ro(
1223 nsr_id, action_id, nslcmop_id, start_deploy, delete_timeout, stage
1224 )
1225
1226 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
1227 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
1228 # delete all nsr
1229 await self.RO.delete(nsr_id)
1230 except Exception as e:
1231 if isinstance(e, NgRoException) and e.http_code == 404: # not found
1232 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
1233 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
1234 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
1235 self.logger.debug(
1236 logging_text + "RO_action_id={} already deleted".format(action_id)
1237 )
1238 elif isinstance(e, NgRoException) and e.http_code == 409: # conflict
1239 failed_detail.append("delete conflict: {}".format(e))
1240 self.logger.debug(
1241 logging_text
1242 + "RO_action_id={} delete conflict: {}".format(action_id, e)
1243 )
1244 else:
1245 failed_detail.append("delete error: {}".format(e))
1246 self.logger.error(
1247 logging_text
1248 + "RO_action_id={} delete error: {}".format(action_id, e)
1249 )
1250
1251 if failed_detail:
1252 stage[2] = "Error deleting from VIM"
1253 else:
1254 stage[2] = "Deleted from VIM"
1255 db_nsr_update["detailed-status"] = " ".join(stage)
1256 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1257 self._write_op_status(nslcmop_id, stage)
1258
1259 if failed_detail:
1260 raise LcmException("; ".join(failed_detail))
1261 return
1262
1263 async def instantiate_RO(
1264 self,
1265 logging_text,
1266 nsr_id,
1267 nsd,
1268 db_nsr,
1269 db_nslcmop,
1270 db_vnfrs,
1271 db_vnfds,
1272 n2vc_key_list,
1273 stage,
1274 ):
1275 """
1276 Instantiate at RO
1277 :param logging_text: preffix text to use at logging
1278 :param nsr_id: nsr identity
1279 :param nsd: database content of ns descriptor
1280 :param db_nsr: database content of ns record
1281 :param db_nslcmop: database content of ns operation, in this case, 'instantiate'
1282 :param db_vnfrs:
1283 :param db_vnfds: database content of vnfds, indexed by id (not _id). {id: {vnfd_object}, ...}
1284 :param n2vc_key_list: ssh-public-key list to be inserted to management vdus via cloud-init
1285 :param stage: list with 3 items: [general stage, tasks, vim_specific]. This task will write over vim_specific
1286 :return: None or exception
1287 """
1288 try:
1289 start_deploy = time()
1290 ns_params = db_nslcmop.get("operationParams")
1291 if ns_params and ns_params.get("timeout_ns_deploy"):
1292 timeout_ns_deploy = ns_params["timeout_ns_deploy"]
1293 else:
1294 timeout_ns_deploy = self.timeout.get(
1295 "ns_deploy", self.timeout_ns_deploy
1296 )
1297
1298 # Check for and optionally request placement optimization. Database will be updated if placement activated
1299 stage[2] = "Waiting for Placement."
1300 if await self._do_placement(logging_text, db_nslcmop, db_vnfrs):
1301 # in case of placement change ns_params[vimAcountId) if not present at any vnfrs
1302 for vnfr in db_vnfrs.values():
1303 if ns_params["vimAccountId"] == vnfr["vim-account-id"]:
1304 break
1305 else:
1306 ns_params["vimAccountId"] == vnfr["vim-account-id"]
1307
1308 return await self._instantiate_ng_ro(
1309 logging_text,
1310 nsr_id,
1311 nsd,
1312 db_nsr,
1313 db_nslcmop,
1314 db_vnfrs,
1315 db_vnfds,
1316 n2vc_key_list,
1317 stage,
1318 start_deploy,
1319 timeout_ns_deploy,
1320 )
1321 except Exception as e:
1322 stage[2] = "ERROR deploying at VIM"
1323 self.set_vnfr_at_error(db_vnfrs, str(e))
1324 self.logger.error(
1325 "Error deploying at VIM {}".format(e),
1326 exc_info=not isinstance(
1327 e,
1328 (
1329 ROclient.ROClientException,
1330 LcmException,
1331 DbException,
1332 NgRoException,
1333 ),
1334 ),
1335 )
1336 raise
1337
1338 async def wait_kdu_up(self, logging_text, nsr_id, vnfr_id, kdu_name):
1339 """
1340 Wait for kdu to be up, get ip address
1341 :param logging_text: prefix use for logging
1342 :param nsr_id:
1343 :param vnfr_id:
1344 :param kdu_name:
1345 :return: IP address
1346 """
1347
1348 # self.logger.debug(logging_text + "Starting wait_kdu_up")
1349 nb_tries = 0
1350
1351 while nb_tries < 360:
1352 db_vnfr = self.db.get_one("vnfrs", {"_id": vnfr_id})
1353 kdur = next(
1354 (
1355 x
1356 for x in get_iterable(db_vnfr, "kdur")
1357 if x.get("kdu-name") == kdu_name
1358 ),
1359 None,
1360 )
1361 if not kdur:
1362 raise LcmException(
1363 "Not found vnfr_id={}, kdu_name={}".format(vnfr_id, kdu_name)
1364 )
1365 if kdur.get("status"):
1366 if kdur["status"] in ("READY", "ENABLED"):
1367 return kdur.get("ip-address")
1368 else:
1369 raise LcmException(
1370 "target KDU={} is in error state".format(kdu_name)
1371 )
1372
1373 await asyncio.sleep(10, loop=self.loop)
1374 nb_tries += 1
1375 raise LcmException("Timeout waiting KDU={} instantiated".format(kdu_name))
1376
1377 async def wait_vm_up_insert_key_ro(
1378 self, logging_text, nsr_id, vnfr_id, vdu_id, vdu_index, pub_key=None, user=None
1379 ):
1380 """
1381 Wait for ip addres at RO, and optionally, insert public key in virtual machine
1382 :param logging_text: prefix use for logging
1383 :param nsr_id:
1384 :param vnfr_id:
1385 :param vdu_id:
1386 :param vdu_index:
1387 :param pub_key: public ssh key to inject, None to skip
1388 :param user: user to apply the public ssh key
1389 :return: IP address
1390 """
1391
1392 self.logger.debug(logging_text + "Starting wait_vm_up_insert_key_ro")
1393 ro_nsr_id = None
1394 ip_address = None
1395 nb_tries = 0
1396 target_vdu_id = None
1397 ro_retries = 0
1398
1399 while True:
1400
1401 ro_retries += 1
1402 if ro_retries >= 360: # 1 hour
1403 raise LcmException(
1404 "Not found _admin.deployed.RO.nsr_id for nsr_id: {}".format(nsr_id)
1405 )
1406
1407 await asyncio.sleep(10, loop=self.loop)
1408
1409 # get ip address
1410 if not target_vdu_id:
1411 db_vnfr = self.db.get_one("vnfrs", {"_id": vnfr_id})
1412
1413 if not vdu_id: # for the VNF case
1414 if db_vnfr.get("status") == "ERROR":
1415 raise LcmException(
1416 "Cannot inject ssh-key because target VNF is in error state"
1417 )
1418 ip_address = db_vnfr.get("ip-address")
1419 if not ip_address:
1420 continue
1421 vdur = next(
1422 (
1423 x
1424 for x in get_iterable(db_vnfr, "vdur")
1425 if x.get("ip-address") == ip_address
1426 ),
1427 None,
1428 )
1429 else: # VDU case
1430 vdur = next(
1431 (
1432 x
1433 for x in get_iterable(db_vnfr, "vdur")
1434 if x.get("vdu-id-ref") == vdu_id
1435 and x.get("count-index") == vdu_index
1436 ),
1437 None,
1438 )
1439
1440 if (
1441 not vdur and len(db_vnfr.get("vdur", ())) == 1
1442 ): # If only one, this should be the target vdu
1443 vdur = db_vnfr["vdur"][0]
1444 if not vdur:
1445 raise LcmException(
1446 "Not found vnfr_id={}, vdu_id={}, vdu_index={}".format(
1447 vnfr_id, vdu_id, vdu_index
1448 )
1449 )
1450 # New generation RO stores information at "vim_info"
1451 ng_ro_status = None
1452 target_vim = None
1453 if vdur.get("vim_info"):
1454 target_vim = next(
1455 t for t in vdur["vim_info"]
1456 ) # there should be only one key
1457 ng_ro_status = vdur["vim_info"][target_vim].get("vim_status")
1458 if (
1459 vdur.get("pdu-type")
1460 or vdur.get("status") == "ACTIVE"
1461 or ng_ro_status == "ACTIVE"
1462 ):
1463 ip_address = vdur.get("ip-address")
1464 if not ip_address:
1465 continue
1466 target_vdu_id = vdur["vdu-id-ref"]
1467 elif vdur.get("status") == "ERROR" or ng_ro_status == "ERROR":
1468 raise LcmException(
1469 "Cannot inject ssh-key because target VM is in error state"
1470 )
1471
1472 if not target_vdu_id:
1473 continue
1474
1475 # inject public key into machine
1476 if pub_key and user:
1477 self.logger.debug(logging_text + "Inserting RO key")
1478 self.logger.debug("SSH > PubKey > {}".format(pub_key))
1479 if vdur.get("pdu-type"):
1480 self.logger.error(logging_text + "Cannot inject ssh-ky to a PDU")
1481 return ip_address
1482 try:
1483 ro_vm_id = "{}-{}".format(
1484 db_vnfr["member-vnf-index-ref"], target_vdu_id
1485 ) # TODO add vdu_index
1486 if self.ng_ro:
1487 target = {
1488 "action": {
1489 "action": "inject_ssh_key",
1490 "key": pub_key,
1491 "user": user,
1492 },
1493 "vnf": [{"_id": vnfr_id, "vdur": [{"id": vdur["id"]}]}],
1494 }
1495 desc = await self.RO.deploy(nsr_id, target)
1496 action_id = desc["action_id"]
1497 await self._wait_ng_ro(nsr_id, action_id, timeout=600)
1498 break
1499 else:
1500 # wait until NS is deployed at RO
1501 if not ro_nsr_id:
1502 db_nsrs = self.db.get_one("nsrs", {"_id": nsr_id})
1503 ro_nsr_id = deep_get(
1504 db_nsrs, ("_admin", "deployed", "RO", "nsr_id")
1505 )
1506 if not ro_nsr_id:
1507 continue
1508 result_dict = await self.RO.create_action(
1509 item="ns",
1510 item_id_name=ro_nsr_id,
1511 descriptor={
1512 "add_public_key": pub_key,
1513 "vms": [ro_vm_id],
1514 "user": user,
1515 },
1516 )
1517 # result_dict contains the format {VM-id: {vim_result: 200, description: text}}
1518 if not result_dict or not isinstance(result_dict, dict):
1519 raise LcmException(
1520 "Unknown response from RO when injecting key"
1521 )
1522 for result in result_dict.values():
1523 if result.get("vim_result") == 200:
1524 break
1525 else:
1526 raise ROclient.ROClientException(
1527 "error injecting key: {}".format(
1528 result.get("description")
1529 )
1530 )
1531 break
1532 except NgRoException as e:
1533 raise LcmException(
1534 "Reaching max tries injecting key. Error: {}".format(e)
1535 )
1536 except ROclient.ROClientException as e:
1537 if not nb_tries:
1538 self.logger.debug(
1539 logging_text
1540 + "error injecting key: {}. Retrying until {} seconds".format(
1541 e, 20 * 10
1542 )
1543 )
1544 nb_tries += 1
1545 if nb_tries >= 20:
1546 raise LcmException(
1547 "Reaching max tries injecting key. Error: {}".format(e)
1548 )
1549 else:
1550 break
1551
1552 return ip_address
1553
1554 async def _wait_dependent_n2vc(self, nsr_id, vca_deployed_list, vca_index):
1555 """
1556 Wait until dependent VCA deployments have been finished. NS wait for VNFs and VDUs. VNFs for VDUs
1557 """
1558 my_vca = vca_deployed_list[vca_index]
1559 if my_vca.get("vdu_id") or my_vca.get("kdu_name"):
1560 # vdu or kdu: no dependencies
1561 return
1562 timeout = 300
1563 while timeout >= 0:
1564 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1565 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
1566 configuration_status_list = db_nsr["configurationStatus"]
1567 for index, vca_deployed in enumerate(configuration_status_list):
1568 if index == vca_index:
1569 # myself
1570 continue
1571 if not my_vca.get("member-vnf-index") or (
1572 vca_deployed.get("member-vnf-index")
1573 == my_vca.get("member-vnf-index")
1574 ):
1575 internal_status = configuration_status_list[index].get("status")
1576 if internal_status == "READY":
1577 continue
1578 elif internal_status == "BROKEN":
1579 raise LcmException(
1580 "Configuration aborted because dependent charm/s has failed"
1581 )
1582 else:
1583 break
1584 else:
1585 # no dependencies, return
1586 return
1587 await asyncio.sleep(10)
1588 timeout -= 1
1589
1590 raise LcmException("Configuration aborted because dependent charm/s timeout")
1591
1592 def get_vca_id(self, db_vnfr: dict, db_nsr: dict):
1593 vca_id = None
1594 if db_vnfr:
1595 vca_id = deep_get(db_vnfr, ("vca-id",))
1596 elif db_nsr:
1597 vim_account_id = deep_get(db_nsr, ("instantiate_params", "vimAccountId"))
1598 vca_id = VimAccountDB.get_vim_account_with_id(vim_account_id).get("vca")
1599 return vca_id
1600
1601 async def instantiate_N2VC(
1602 self,
1603 logging_text,
1604 vca_index,
1605 nsi_id,
1606 db_nsr,
1607 db_vnfr,
1608 vdu_id,
1609 kdu_name,
1610 vdu_index,
1611 config_descriptor,
1612 deploy_params,
1613 base_folder,
1614 nslcmop_id,
1615 stage,
1616 vca_type,
1617 vca_name,
1618 ee_config_descriptor,
1619 ):
1620 nsr_id = db_nsr["_id"]
1621 db_update_entry = "_admin.deployed.VCA.{}.".format(vca_index)
1622 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
1623 vca_deployed = db_nsr["_admin"]["deployed"]["VCA"][vca_index]
1624 osm_config = {"osm": {"ns_id": db_nsr["_id"]}}
1625 db_dict = {
1626 "collection": "nsrs",
1627 "filter": {"_id": nsr_id},
1628 "path": db_update_entry,
1629 }
1630 step = ""
1631 try:
1632
1633 element_type = "NS"
1634 element_under_configuration = nsr_id
1635
1636 vnfr_id = None
1637 if db_vnfr:
1638 vnfr_id = db_vnfr["_id"]
1639 osm_config["osm"]["vnf_id"] = vnfr_id
1640
1641 namespace = "{nsi}.{ns}".format(nsi=nsi_id if nsi_id else "", ns=nsr_id)
1642
1643 if vca_type == "native_charm":
1644 index_number = 0
1645 else:
1646 index_number = vdu_index or 0
1647
1648 if vnfr_id:
1649 element_type = "VNF"
1650 element_under_configuration = vnfr_id
1651 namespace += ".{}-{}".format(vnfr_id, index_number)
1652 if vdu_id:
1653 namespace += ".{}-{}".format(vdu_id, index_number)
1654 element_type = "VDU"
1655 element_under_configuration = "{}-{}".format(vdu_id, index_number)
1656 osm_config["osm"]["vdu_id"] = vdu_id
1657 elif kdu_name:
1658 namespace += ".{}".format(kdu_name)
1659 element_type = "KDU"
1660 element_under_configuration = kdu_name
1661 osm_config["osm"]["kdu_name"] = kdu_name
1662
1663 # Get artifact path
1664 artifact_path = "{}/{}/{}/{}".format(
1665 base_folder["folder"],
1666 base_folder["pkg-dir"],
1667 "charms"
1668 if vca_type in ("native_charm", "lxc_proxy_charm", "k8s_proxy_charm")
1669 else "helm-charts",
1670 vca_name,
1671 )
1672
1673 self.logger.debug("Artifact path > {}".format(artifact_path))
1674
1675 # get initial_config_primitive_list that applies to this element
1676 initial_config_primitive_list = config_descriptor.get(
1677 "initial-config-primitive"
1678 )
1679
1680 self.logger.debug(
1681 "Initial config primitive list > {}".format(
1682 initial_config_primitive_list
1683 )
1684 )
1685
1686 # add config if not present for NS charm
1687 ee_descriptor_id = ee_config_descriptor.get("id")
1688 self.logger.debug("EE Descriptor > {}".format(ee_descriptor_id))
1689 initial_config_primitive_list = get_ee_sorted_initial_config_primitive_list(
1690 initial_config_primitive_list, vca_deployed, ee_descriptor_id
1691 )
1692
1693 self.logger.debug(
1694 "Initial config primitive list #2 > {}".format(
1695 initial_config_primitive_list
1696 )
1697 )
1698 # n2vc_redesign STEP 3.1
1699 # find old ee_id if exists
1700 ee_id = vca_deployed.get("ee_id")
1701
1702 vca_id = self.get_vca_id(db_vnfr, db_nsr)
1703 # create or register execution environment in VCA
1704 if vca_type in ("lxc_proxy_charm", "k8s_proxy_charm", "helm", "helm-v3"):
1705
1706 self._write_configuration_status(
1707 nsr_id=nsr_id,
1708 vca_index=vca_index,
1709 status="CREATING",
1710 element_under_configuration=element_under_configuration,
1711 element_type=element_type,
1712 )
1713
1714 step = "create execution environment"
1715 self.logger.debug(logging_text + step)
1716
1717 ee_id = None
1718 credentials = None
1719 if vca_type == "k8s_proxy_charm":
1720 ee_id = await self.vca_map[vca_type].install_k8s_proxy_charm(
1721 charm_name=artifact_path[artifact_path.rfind("/") + 1 :],
1722 namespace=namespace,
1723 artifact_path=artifact_path,
1724 db_dict=db_dict,
1725 vca_id=vca_id,
1726 )
1727 elif vca_type == "helm" or vca_type == "helm-v3":
1728 ee_id, credentials = await self.vca_map[
1729 vca_type
1730 ].create_execution_environment(
1731 namespace=namespace,
1732 reuse_ee_id=ee_id,
1733 db_dict=db_dict,
1734 config=osm_config,
1735 artifact_path=artifact_path,
1736 vca_type=vca_type,
1737 )
1738 else:
1739 ee_id, credentials = await self.vca_map[
1740 vca_type
1741 ].create_execution_environment(
1742 namespace=namespace,
1743 reuse_ee_id=ee_id,
1744 db_dict=db_dict,
1745 vca_id=vca_id,
1746 )
1747
1748 elif vca_type == "native_charm":
1749 step = "Waiting to VM being up and getting IP address"
1750 self.logger.debug(logging_text + step)
1751 rw_mgmt_ip = await self.wait_vm_up_insert_key_ro(
1752 logging_text,
1753 nsr_id,
1754 vnfr_id,
1755 vdu_id,
1756 vdu_index,
1757 user=None,
1758 pub_key=None,
1759 )
1760 credentials = {"hostname": rw_mgmt_ip}
1761 # get username
1762 username = deep_get(
1763 config_descriptor, ("config-access", "ssh-access", "default-user")
1764 )
1765 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1766 # merged. Meanwhile let's get username from initial-config-primitive
1767 if not username and initial_config_primitive_list:
1768 for config_primitive in initial_config_primitive_list:
1769 for param in config_primitive.get("parameter", ()):
1770 if param["name"] == "ssh-username":
1771 username = param["value"]
1772 break
1773 if not username:
1774 raise LcmException(
1775 "Cannot determine the username neither with 'initial-config-primitive' nor with "
1776 "'config-access.ssh-access.default-user'"
1777 )
1778 credentials["username"] = username
1779 # n2vc_redesign STEP 3.2
1780
1781 self._write_configuration_status(
1782 nsr_id=nsr_id,
1783 vca_index=vca_index,
1784 status="REGISTERING",
1785 element_under_configuration=element_under_configuration,
1786 element_type=element_type,
1787 )
1788
1789 step = "register execution environment {}".format(credentials)
1790 self.logger.debug(logging_text + step)
1791 ee_id = await self.vca_map[vca_type].register_execution_environment(
1792 credentials=credentials,
1793 namespace=namespace,
1794 db_dict=db_dict,
1795 vca_id=vca_id,
1796 )
1797
1798 # for compatibility with MON/POL modules, the need model and application name at database
1799 # TODO ask MON/POL if needed to not assuming anymore the format "model_name.application_name"
1800 ee_id_parts = ee_id.split(".")
1801 db_nsr_update = {db_update_entry + "ee_id": ee_id}
1802 if len(ee_id_parts) >= 2:
1803 model_name = ee_id_parts[0]
1804 application_name = ee_id_parts[1]
1805 db_nsr_update[db_update_entry + "model"] = model_name
1806 db_nsr_update[db_update_entry + "application"] = application_name
1807
1808 # n2vc_redesign STEP 3.3
1809 step = "Install configuration Software"
1810
1811 self._write_configuration_status(
1812 nsr_id=nsr_id,
1813 vca_index=vca_index,
1814 status="INSTALLING SW",
1815 element_under_configuration=element_under_configuration,
1816 element_type=element_type,
1817 other_update=db_nsr_update,
1818 )
1819
1820 # TODO check if already done
1821 self.logger.debug(logging_text + step)
1822 config = None
1823 if vca_type == "native_charm":
1824 config_primitive = next(
1825 (p for p in initial_config_primitive_list if p["name"] == "config"),
1826 None,
1827 )
1828 if config_primitive:
1829 config = self._map_primitive_params(
1830 config_primitive, {}, deploy_params
1831 )
1832 num_units = 1
1833 if vca_type == "lxc_proxy_charm":
1834 if element_type == "NS":
1835 num_units = db_nsr.get("config-units") or 1
1836 elif element_type == "VNF":
1837 num_units = db_vnfr.get("config-units") or 1
1838 elif element_type == "VDU":
1839 for v in db_vnfr["vdur"]:
1840 if vdu_id == v["vdu-id-ref"]:
1841 num_units = v.get("config-units") or 1
1842 break
1843 if vca_type != "k8s_proxy_charm":
1844 await self.vca_map[vca_type].install_configuration_sw(
1845 ee_id=ee_id,
1846 artifact_path=artifact_path,
1847 db_dict=db_dict,
1848 config=config,
1849 num_units=num_units,
1850 vca_id=vca_id,
1851 vca_type=vca_type,
1852 )
1853
1854 # write in db flag of configuration_sw already installed
1855 self.update_db_2(
1856 "nsrs", nsr_id, {db_update_entry + "config_sw_installed": True}
1857 )
1858
1859 # add relations for this VCA (wait for other peers related with this VCA)
1860 await self._add_vca_relations(
1861 logging_text=logging_text,
1862 nsr_id=nsr_id,
1863 vca_index=vca_index,
1864 vca_id=vca_id,
1865 vca_type=vca_type,
1866 )
1867
1868 # if SSH access is required, then get execution environment SSH public
1869 # if native charm we have waited already to VM be UP
1870 if vca_type in ("k8s_proxy_charm", "lxc_proxy_charm", "helm", "helm-v3"):
1871 pub_key = None
1872 user = None
1873 # self.logger.debug("get ssh key block")
1874 if deep_get(
1875 config_descriptor, ("config-access", "ssh-access", "required")
1876 ):
1877 # self.logger.debug("ssh key needed")
1878 # Needed to inject a ssh key
1879 user = deep_get(
1880 config_descriptor,
1881 ("config-access", "ssh-access", "default-user"),
1882 )
1883 step = "Install configuration Software, getting public ssh key"
1884 pub_key = await self.vca_map[vca_type].get_ee_ssh_public__key(
1885 ee_id=ee_id, db_dict=db_dict, vca_id=vca_id
1886 )
1887
1888 step = "Insert public key into VM user={} ssh_key={}".format(
1889 user, pub_key
1890 )
1891 else:
1892 # self.logger.debug("no need to get ssh key")
1893 step = "Waiting to VM being up and getting IP address"
1894 self.logger.debug(logging_text + step)
1895
1896 # n2vc_redesign STEP 5.1
1897 # wait for RO (ip-address) Insert pub_key into VM
1898 if vnfr_id:
1899 if kdu_name:
1900 rw_mgmt_ip = await self.wait_kdu_up(
1901 logging_text, nsr_id, vnfr_id, kdu_name
1902 )
1903 else:
1904 rw_mgmt_ip = await self.wait_vm_up_insert_key_ro(
1905 logging_text,
1906 nsr_id,
1907 vnfr_id,
1908 vdu_id,
1909 vdu_index,
1910 user=user,
1911 pub_key=pub_key,
1912 )
1913 else:
1914 rw_mgmt_ip = None # This is for a NS configuration
1915
1916 self.logger.debug(logging_text + " VM_ip_address={}".format(rw_mgmt_ip))
1917
1918 # store rw_mgmt_ip in deploy params for later replacement
1919 deploy_params["rw_mgmt_ip"] = rw_mgmt_ip
1920
1921 # n2vc_redesign STEP 6 Execute initial config primitive
1922 step = "execute initial config primitive"
1923
1924 # wait for dependent primitives execution (NS -> VNF -> VDU)
1925 if initial_config_primitive_list:
1926 await self._wait_dependent_n2vc(nsr_id, vca_deployed_list, vca_index)
1927
1928 # stage, in function of element type: vdu, kdu, vnf or ns
1929 my_vca = vca_deployed_list[vca_index]
1930 if my_vca.get("vdu_id") or my_vca.get("kdu_name"):
1931 # VDU or KDU
1932 stage[0] = "Stage 3/5: running Day-1 primitives for VDU."
1933 elif my_vca.get("member-vnf-index"):
1934 # VNF
1935 stage[0] = "Stage 4/5: running Day-1 primitives for VNF."
1936 else:
1937 # NS
1938 stage[0] = "Stage 5/5: running Day-1 primitives for NS."
1939
1940 self._write_configuration_status(
1941 nsr_id=nsr_id, vca_index=vca_index, status="EXECUTING PRIMITIVE"
1942 )
1943
1944 self._write_op_status(op_id=nslcmop_id, stage=stage)
1945
1946 check_if_terminated_needed = True
1947 for initial_config_primitive in initial_config_primitive_list:
1948 # adding information on the vca_deployed if it is a NS execution environment
1949 if not vca_deployed["member-vnf-index"]:
1950 deploy_params["ns_config_info"] = json.dumps(
1951 self._get_ns_config_info(nsr_id)
1952 )
1953 # TODO check if already done
1954 primitive_params_ = self._map_primitive_params(
1955 initial_config_primitive, {}, deploy_params
1956 )
1957
1958 step = "execute primitive '{}' params '{}'".format(
1959 initial_config_primitive["name"], primitive_params_
1960 )
1961 self.logger.debug(logging_text + step)
1962 await self.vca_map[vca_type].exec_primitive(
1963 ee_id=ee_id,
1964 primitive_name=initial_config_primitive["name"],
1965 params_dict=primitive_params_,
1966 db_dict=db_dict,
1967 vca_id=vca_id,
1968 vca_type=vca_type,
1969 )
1970 # Once some primitive has been exec, check and write at db if it needs to exec terminated primitives
1971 if check_if_terminated_needed:
1972 if config_descriptor.get("terminate-config-primitive"):
1973 self.update_db_2(
1974 "nsrs", nsr_id, {db_update_entry + "needed_terminate": True}
1975 )
1976 check_if_terminated_needed = False
1977
1978 # TODO register in database that primitive is done
1979
1980 # STEP 7 Configure metrics
1981 if vca_type == "helm" or vca_type == "helm-v3":
1982 prometheus_jobs = await self.add_prometheus_metrics(
1983 ee_id=ee_id,
1984 artifact_path=artifact_path,
1985 ee_config_descriptor=ee_config_descriptor,
1986 vnfr_id=vnfr_id,
1987 nsr_id=nsr_id,
1988 target_ip=rw_mgmt_ip,
1989 )
1990 if prometheus_jobs:
1991 self.update_db_2(
1992 "nsrs",
1993 nsr_id,
1994 {db_update_entry + "prometheus_jobs": prometheus_jobs},
1995 )
1996
1997 step = "instantiated at VCA"
1998 self.logger.debug(logging_text + step)
1999
2000 self._write_configuration_status(
2001 nsr_id=nsr_id, vca_index=vca_index, status="READY"
2002 )
2003
2004 except Exception as e: # TODO not use Exception but N2VC exception
2005 # self.update_db_2("nsrs", nsr_id, {db_update_entry + "instantiation": "FAILED"})
2006 if not isinstance(
2007 e, (DbException, N2VCException, LcmException, asyncio.CancelledError)
2008 ):
2009 self.logger.error(
2010 "Exception while {} : {}".format(step, e), exc_info=True
2011 )
2012 self._write_configuration_status(
2013 nsr_id=nsr_id, vca_index=vca_index, status="BROKEN"
2014 )
2015 raise LcmException("{} {}".format(step, e)) from e
2016
2017 def _write_ns_status(
2018 self,
2019 nsr_id: str,
2020 ns_state: str,
2021 current_operation: str,
2022 current_operation_id: str,
2023 error_description: str = None,
2024 error_detail: str = None,
2025 other_update: dict = None,
2026 ):
2027 """
2028 Update db_nsr fields.
2029 :param nsr_id:
2030 :param ns_state:
2031 :param current_operation:
2032 :param current_operation_id:
2033 :param error_description:
2034 :param error_detail:
2035 :param other_update: Other required changes at database if provided, will be cleared
2036 :return:
2037 """
2038 try:
2039 db_dict = other_update or {}
2040 db_dict[
2041 "_admin.nslcmop"
2042 ] = current_operation_id # for backward compatibility
2043 db_dict["_admin.current-operation"] = current_operation_id
2044 db_dict["_admin.operation-type"] = (
2045 current_operation if current_operation != "IDLE" else None
2046 )
2047 db_dict["currentOperation"] = current_operation
2048 db_dict["currentOperationID"] = current_operation_id
2049 db_dict["errorDescription"] = error_description
2050 db_dict["errorDetail"] = error_detail
2051
2052 if ns_state:
2053 db_dict["nsState"] = ns_state
2054 self.update_db_2("nsrs", nsr_id, db_dict)
2055 except DbException as e:
2056 self.logger.warn("Error writing NS status, ns={}: {}".format(nsr_id, e))
2057
2058 def _write_op_status(
2059 self,
2060 op_id: str,
2061 stage: list = None,
2062 error_message: str = None,
2063 queuePosition: int = 0,
2064 operation_state: str = None,
2065 other_update: dict = None,
2066 ):
2067 try:
2068 db_dict = other_update or {}
2069 db_dict["queuePosition"] = queuePosition
2070 if isinstance(stage, list):
2071 db_dict["stage"] = stage[0]
2072 db_dict["detailed-status"] = " ".join(stage)
2073 elif stage is not None:
2074 db_dict["stage"] = str(stage)
2075
2076 if error_message is not None:
2077 db_dict["errorMessage"] = error_message
2078 if operation_state is not None:
2079 db_dict["operationState"] = operation_state
2080 db_dict["statusEnteredTime"] = time()
2081 self.update_db_2("nslcmops", op_id, db_dict)
2082 except DbException as e:
2083 self.logger.warn(
2084 "Error writing OPERATION status for op_id: {} -> {}".format(op_id, e)
2085 )
2086
2087 def _write_all_config_status(self, db_nsr: dict, status: str):
2088 try:
2089 nsr_id = db_nsr["_id"]
2090 # configurationStatus
2091 config_status = db_nsr.get("configurationStatus")
2092 if config_status:
2093 db_nsr_update = {
2094 "configurationStatus.{}.status".format(index): status
2095 for index, v in enumerate(config_status)
2096 if v
2097 }
2098 # update status
2099 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2100
2101 except DbException as e:
2102 self.logger.warn(
2103 "Error writing all configuration status, ns={}: {}".format(nsr_id, e)
2104 )
2105
2106 def _write_configuration_status(
2107 self,
2108 nsr_id: str,
2109 vca_index: int,
2110 status: str = None,
2111 element_under_configuration: str = None,
2112 element_type: str = None,
2113 other_update: dict = None,
2114 ):
2115
2116 # self.logger.debug('_write_configuration_status(): vca_index={}, status={}'
2117 # .format(vca_index, status))
2118
2119 try:
2120 db_path = "configurationStatus.{}.".format(vca_index)
2121 db_dict = other_update or {}
2122 if status:
2123 db_dict[db_path + "status"] = status
2124 if element_under_configuration:
2125 db_dict[
2126 db_path + "elementUnderConfiguration"
2127 ] = element_under_configuration
2128 if element_type:
2129 db_dict[db_path + "elementType"] = element_type
2130 self.update_db_2("nsrs", nsr_id, db_dict)
2131 except DbException as e:
2132 self.logger.warn(
2133 "Error writing configuration status={}, ns={}, vca_index={}: {}".format(
2134 status, nsr_id, vca_index, e
2135 )
2136 )
2137
2138 async def _do_placement(self, logging_text, db_nslcmop, db_vnfrs):
2139 """
2140 Check and computes the placement, (vim account where to deploy). If it is decided by an external tool, it
2141 sends the request via kafka and wait until the result is wrote at database (nslcmops _admin.plca).
2142 Database is used because the result can be obtained from a different LCM worker in case of HA.
2143 :param logging_text: contains the prefix for logging, with the ns and nslcmop identifiers
2144 :param db_nslcmop: database content of nslcmop
2145 :param db_vnfrs: database content of vnfrs, indexed by member-vnf-index.
2146 :return: True if some modification is done. Modifies database vnfrs and parameter db_vnfr with the
2147 computed 'vim-account-id'
2148 """
2149 modified = False
2150 nslcmop_id = db_nslcmop["_id"]
2151 placement_engine = deep_get(db_nslcmop, ("operationParams", "placement-engine"))
2152 if placement_engine == "PLA":
2153 self.logger.debug(
2154 logging_text + "Invoke and wait for placement optimization"
2155 )
2156 await self.msg.aiowrite(
2157 "pla", "get_placement", {"nslcmopId": nslcmop_id}, loop=self.loop
2158 )
2159 db_poll_interval = 5
2160 wait = db_poll_interval * 10
2161 pla_result = None
2162 while not pla_result and wait >= 0:
2163 await asyncio.sleep(db_poll_interval)
2164 wait -= db_poll_interval
2165 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
2166 pla_result = deep_get(db_nslcmop, ("_admin", "pla"))
2167
2168 if not pla_result:
2169 raise LcmException(
2170 "Placement timeout for nslcmopId={}".format(nslcmop_id)
2171 )
2172
2173 for pla_vnf in pla_result["vnf"]:
2174 vnfr = db_vnfrs.get(pla_vnf["member-vnf-index"])
2175 if not pla_vnf.get("vimAccountId") or not vnfr:
2176 continue
2177 modified = True
2178 self.db.set_one(
2179 "vnfrs",
2180 {"_id": vnfr["_id"]},
2181 {"vim-account-id": pla_vnf["vimAccountId"]},
2182 )
2183 # Modifies db_vnfrs
2184 vnfr["vim-account-id"] = pla_vnf["vimAccountId"]
2185 return modified
2186
2187 def update_nsrs_with_pla_result(self, params):
2188 try:
2189 nslcmop_id = deep_get(params, ("placement", "nslcmopId"))
2190 self.update_db_2(
2191 "nslcmops", nslcmop_id, {"_admin.pla": params.get("placement")}
2192 )
2193 except Exception as e:
2194 self.logger.warn("Update failed for nslcmop_id={}:{}".format(nslcmop_id, e))
2195
2196 async def instantiate(self, nsr_id, nslcmop_id):
2197 """
2198
2199 :param nsr_id: ns instance to deploy
2200 :param nslcmop_id: operation to run
2201 :return:
2202 """
2203
2204 # Try to lock HA task here
2205 task_is_locked_by_me = self.lcm_tasks.lock_HA("ns", "nslcmops", nslcmop_id)
2206 if not task_is_locked_by_me:
2207 self.logger.debug(
2208 "instantiate() task is not locked by me, ns={}".format(nsr_id)
2209 )
2210 return
2211
2212 logging_text = "Task ns={} instantiate={} ".format(nsr_id, nslcmop_id)
2213 self.logger.debug(logging_text + "Enter")
2214
2215 # get all needed from database
2216
2217 # database nsrs record
2218 db_nsr = None
2219
2220 # database nslcmops record
2221 db_nslcmop = None
2222
2223 # update operation on nsrs
2224 db_nsr_update = {}
2225 # update operation on nslcmops
2226 db_nslcmop_update = {}
2227
2228 nslcmop_operation_state = None
2229 db_vnfrs = {} # vnf's info indexed by member-index
2230 # n2vc_info = {}
2231 tasks_dict_info = {} # from task to info text
2232 exc = None
2233 error_list = []
2234 stage = [
2235 "Stage 1/5: preparation of the environment.",
2236 "Waiting for previous operations to terminate.",
2237 "",
2238 ]
2239 # ^ stage, step, VIM progress
2240 try:
2241 # wait for any previous tasks in process
2242 await self.lcm_tasks.waitfor_related_HA("ns", "nslcmops", nslcmop_id)
2243
2244 # STEP 0: Reading database (nslcmops, nsrs, nsds, vnfrs, vnfds)
2245 stage[1] = "Reading from database."
2246 # nsState="BUILDING", currentOperation="INSTANTIATING", currentOperationID=nslcmop_id
2247 db_nsr_update["detailed-status"] = "creating"
2248 db_nsr_update["operational-status"] = "init"
2249 self._write_ns_status(
2250 nsr_id=nsr_id,
2251 ns_state="BUILDING",
2252 current_operation="INSTANTIATING",
2253 current_operation_id=nslcmop_id,
2254 other_update=db_nsr_update,
2255 )
2256 self._write_op_status(op_id=nslcmop_id, stage=stage, queuePosition=0)
2257
2258 # read from db: operation
2259 stage[1] = "Getting nslcmop={} from db.".format(nslcmop_id)
2260 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
2261 if db_nslcmop["operationParams"].get("additionalParamsForVnf"):
2262 db_nslcmop["operationParams"]["additionalParamsForVnf"] = json.loads(
2263 db_nslcmop["operationParams"]["additionalParamsForVnf"]
2264 )
2265 ns_params = db_nslcmop.get("operationParams")
2266 if ns_params and ns_params.get("timeout_ns_deploy"):
2267 timeout_ns_deploy = ns_params["timeout_ns_deploy"]
2268 else:
2269 timeout_ns_deploy = self.timeout.get(
2270 "ns_deploy", self.timeout_ns_deploy
2271 )
2272
2273 # read from db: ns
2274 stage[1] = "Getting nsr={} from db.".format(nsr_id)
2275 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2276 stage[1] = "Getting nsd={} from db.".format(db_nsr["nsd-id"])
2277 nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
2278 self.fs.sync(db_nsr["nsd-id"])
2279 db_nsr["nsd"] = nsd
2280 # nsr_name = db_nsr["name"] # TODO short-name??
2281
2282 # read from db: vnf's of this ns
2283 stage[1] = "Getting vnfrs from db."
2284 self.logger.debug(logging_text + stage[1])
2285 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
2286
2287 # read from db: vnfd's for every vnf
2288 db_vnfds = [] # every vnfd data
2289
2290 # for each vnf in ns, read vnfd
2291 for vnfr in db_vnfrs_list:
2292 if vnfr.get("kdur"):
2293 kdur_list = []
2294 for kdur in vnfr["kdur"]:
2295 if kdur.get("additionalParams"):
2296 kdur["additionalParams"] = json.loads(kdur["additionalParams"])
2297 kdur_list.append(kdur)
2298 vnfr["kdur"] = kdur_list
2299
2300 db_vnfrs[vnfr["member-vnf-index-ref"]] = vnfr
2301 vnfd_id = vnfr["vnfd-id"]
2302 vnfd_ref = vnfr["vnfd-ref"]
2303 self.fs.sync(vnfd_id)
2304
2305 # if we haven't this vnfd, read it from db
2306 if vnfd_id not in db_vnfds:
2307 # read from db
2308 stage[1] = "Getting vnfd={} id='{}' from db.".format(
2309 vnfd_id, vnfd_ref
2310 )
2311 self.logger.debug(logging_text + stage[1])
2312 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
2313
2314 # store vnfd
2315 db_vnfds.append(vnfd)
2316
2317 # Get or generates the _admin.deployed.VCA list
2318 vca_deployed_list = None
2319 if db_nsr["_admin"].get("deployed"):
2320 vca_deployed_list = db_nsr["_admin"]["deployed"].get("VCA")
2321 if vca_deployed_list is None:
2322 vca_deployed_list = []
2323 configuration_status_list = []
2324 db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
2325 db_nsr_update["configurationStatus"] = configuration_status_list
2326 # add _admin.deployed.VCA to db_nsr dictionary, value=vca_deployed_list
2327 populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
2328 elif isinstance(vca_deployed_list, dict):
2329 # maintain backward compatibility. Change a dict to list at database
2330 vca_deployed_list = list(vca_deployed_list.values())
2331 db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
2332 populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
2333
2334 if not isinstance(
2335 deep_get(db_nsr, ("_admin", "deployed", "RO", "vnfd")), list
2336 ):
2337 populate_dict(db_nsr, ("_admin", "deployed", "RO", "vnfd"), [])
2338 db_nsr_update["_admin.deployed.RO.vnfd"] = []
2339
2340 # set state to INSTANTIATED. When instantiated NBI will not delete directly
2341 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
2342 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2343 self.db.set_list(
2344 "vnfrs", {"nsr-id-ref": nsr_id}, {"_admin.nsState": "INSTANTIATED"}
2345 )
2346
2347 # n2vc_redesign STEP 2 Deploy Network Scenario
2348 stage[0] = "Stage 2/5: deployment of KDUs, VMs and execution environments."
2349 self._write_op_status(op_id=nslcmop_id, stage=stage)
2350
2351 stage[1] = "Deploying KDUs."
2352 # self.logger.debug(logging_text + "Before deploy_kdus")
2353 # Call to deploy_kdus in case exists the "vdu:kdu" param
2354 await self.deploy_kdus(
2355 logging_text=logging_text,
2356 nsr_id=nsr_id,
2357 nslcmop_id=nslcmop_id,
2358 db_vnfrs=db_vnfrs,
2359 db_vnfds=db_vnfds,
2360 task_instantiation_info=tasks_dict_info,
2361 )
2362
2363 stage[1] = "Getting VCA public key."
2364 # n2vc_redesign STEP 1 Get VCA public ssh-key
2365 # feature 1429. Add n2vc public key to needed VMs
2366 n2vc_key = self.n2vc.get_public_key()
2367 n2vc_key_list = [n2vc_key]
2368 if self.vca_config.get("public_key"):
2369 n2vc_key_list.append(self.vca_config["public_key"])
2370
2371 stage[1] = "Deploying NS at VIM."
2372 task_ro = asyncio.ensure_future(
2373 self.instantiate_RO(
2374 logging_text=logging_text,
2375 nsr_id=nsr_id,
2376 nsd=nsd,
2377 db_nsr=db_nsr,
2378 db_nslcmop=db_nslcmop,
2379 db_vnfrs=db_vnfrs,
2380 db_vnfds=db_vnfds,
2381 n2vc_key_list=n2vc_key_list,
2382 stage=stage,
2383 )
2384 )
2385 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "instantiate_RO", task_ro)
2386 tasks_dict_info[task_ro] = "Deploying at VIM"
2387
2388 # n2vc_redesign STEP 3 to 6 Deploy N2VC
2389 stage[1] = "Deploying Execution Environments."
2390 self.logger.debug(logging_text + stage[1])
2391
2392 nsi_id = None # TODO put nsi_id when this nsr belongs to a NSI
2393 for vnf_profile in get_vnf_profiles(nsd):
2394 vnfd_id = vnf_profile["vnfd-id"]
2395 vnfd = find_in_list(db_vnfds, lambda a_vnf: a_vnf["id"] == vnfd_id)
2396 member_vnf_index = str(vnf_profile["id"])
2397 db_vnfr = db_vnfrs[member_vnf_index]
2398 base_folder = vnfd["_admin"]["storage"]
2399 vdu_id = None
2400 vdu_index = 0
2401 vdu_name = None
2402 kdu_name = None
2403
2404 # Get additional parameters
2405 deploy_params = {"OSM": get_osm_params(db_vnfr)}
2406 if db_vnfr.get("additionalParamsForVnf"):
2407 deploy_params.update(
2408 parse_yaml_strings(db_vnfr["additionalParamsForVnf"].copy())
2409 )
2410
2411 descriptor_config = get_configuration(vnfd, vnfd["id"])
2412 if descriptor_config:
2413 self._deploy_n2vc(
2414 logging_text=logging_text
2415 + "member_vnf_index={} ".format(member_vnf_index),
2416 db_nsr=db_nsr,
2417 db_vnfr=db_vnfr,
2418 nslcmop_id=nslcmop_id,
2419 nsr_id=nsr_id,
2420 nsi_id=nsi_id,
2421 vnfd_id=vnfd_id,
2422 vdu_id=vdu_id,
2423 kdu_name=kdu_name,
2424 member_vnf_index=member_vnf_index,
2425 vdu_index=vdu_index,
2426 vdu_name=vdu_name,
2427 deploy_params=deploy_params,
2428 descriptor_config=descriptor_config,
2429 base_folder=base_folder,
2430 task_instantiation_info=tasks_dict_info,
2431 stage=stage,
2432 )
2433
2434 # Deploy charms for each VDU that supports one.
2435 for vdud in get_vdu_list(vnfd):
2436 vdu_id = vdud["id"]
2437 descriptor_config = get_configuration(vnfd, vdu_id)
2438 vdur = find_in_list(
2439 db_vnfr["vdur"], lambda vdu: vdu["vdu-id-ref"] == vdu_id
2440 )
2441
2442 if vdur.get("additionalParams"):
2443 deploy_params_vdu = parse_yaml_strings(vdur["additionalParams"])
2444 else:
2445 deploy_params_vdu = deploy_params
2446 deploy_params_vdu["OSM"] = get_osm_params(
2447 db_vnfr, vdu_id, vdu_count_index=0
2448 )
2449 vdud_count = get_number_of_instances(vnfd, vdu_id)
2450
2451 self.logger.debug("VDUD > {}".format(vdud))
2452 self.logger.debug(
2453 "Descriptor config > {}".format(descriptor_config)
2454 )
2455 if descriptor_config:
2456 vdu_name = None
2457 kdu_name = None
2458 for vdu_index in range(vdud_count):
2459 # TODO vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
2460 self._deploy_n2vc(
2461 logging_text=logging_text
2462 + "member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
2463 member_vnf_index, vdu_id, vdu_index
2464 ),
2465 db_nsr=db_nsr,
2466 db_vnfr=db_vnfr,
2467 nslcmop_id=nslcmop_id,
2468 nsr_id=nsr_id,
2469 nsi_id=nsi_id,
2470 vnfd_id=vnfd_id,
2471 vdu_id=vdu_id,
2472 kdu_name=kdu_name,
2473 member_vnf_index=member_vnf_index,
2474 vdu_index=vdu_index,
2475 vdu_name=vdu_name,
2476 deploy_params=deploy_params_vdu,
2477 descriptor_config=descriptor_config,
2478 base_folder=base_folder,
2479 task_instantiation_info=tasks_dict_info,
2480 stage=stage,
2481 )
2482 for kdud in get_kdu_list(vnfd):
2483 kdu_name = kdud["name"]
2484 descriptor_config = get_configuration(vnfd, kdu_name)
2485 if descriptor_config:
2486 vdu_id = None
2487 vdu_index = 0
2488 vdu_name = None
2489 kdur = next(
2490 x for x in db_vnfr["kdur"] if x["kdu-name"] == kdu_name
2491 )
2492 deploy_params_kdu = {"OSM": get_osm_params(db_vnfr)}
2493 if kdur.get("additionalParams"):
2494 deploy_params_kdu = parse_yaml_strings(
2495 kdur["additionalParams"]
2496 )
2497
2498 self._deploy_n2vc(
2499 logging_text=logging_text,
2500 db_nsr=db_nsr,
2501 db_vnfr=db_vnfr,
2502 nslcmop_id=nslcmop_id,
2503 nsr_id=nsr_id,
2504 nsi_id=nsi_id,
2505 vnfd_id=vnfd_id,
2506 vdu_id=vdu_id,
2507 kdu_name=kdu_name,
2508 member_vnf_index=member_vnf_index,
2509 vdu_index=vdu_index,
2510 vdu_name=vdu_name,
2511 deploy_params=deploy_params_kdu,
2512 descriptor_config=descriptor_config,
2513 base_folder=base_folder,
2514 task_instantiation_info=tasks_dict_info,
2515 stage=stage,
2516 )
2517
2518 # Check if this NS has a charm configuration
2519 descriptor_config = nsd.get("ns-configuration")
2520 if descriptor_config and descriptor_config.get("juju"):
2521 vnfd_id = None
2522 db_vnfr = None
2523 member_vnf_index = None
2524 vdu_id = None
2525 kdu_name = None
2526 vdu_index = 0
2527 vdu_name = None
2528
2529 # Get additional parameters
2530 deploy_params = {"OSM": {"vim_account_id": ns_params["vimAccountId"]}}
2531 if db_nsr.get("additionalParamsForNs"):
2532 deploy_params.update(
2533 parse_yaml_strings(db_nsr["additionalParamsForNs"].copy())
2534 )
2535 base_folder = nsd["_admin"]["storage"]
2536 self._deploy_n2vc(
2537 logging_text=logging_text,
2538 db_nsr=db_nsr,
2539 db_vnfr=db_vnfr,
2540 nslcmop_id=nslcmop_id,
2541 nsr_id=nsr_id,
2542 nsi_id=nsi_id,
2543 vnfd_id=vnfd_id,
2544 vdu_id=vdu_id,
2545 kdu_name=kdu_name,
2546 member_vnf_index=member_vnf_index,
2547 vdu_index=vdu_index,
2548 vdu_name=vdu_name,
2549 deploy_params=deploy_params,
2550 descriptor_config=descriptor_config,
2551 base_folder=base_folder,
2552 task_instantiation_info=tasks_dict_info,
2553 stage=stage,
2554 )
2555
2556 # rest of staff will be done at finally
2557
2558 except (
2559 ROclient.ROClientException,
2560 DbException,
2561 LcmException,
2562 N2VCException,
2563 ) as e:
2564 self.logger.error(
2565 logging_text + "Exit Exception while '{}': {}".format(stage[1], e)
2566 )
2567 exc = e
2568 except asyncio.CancelledError:
2569 self.logger.error(
2570 logging_text + "Cancelled Exception while '{}'".format(stage[1])
2571 )
2572 exc = "Operation was cancelled"
2573 except Exception as e:
2574 exc = traceback.format_exc()
2575 self.logger.critical(
2576 logging_text + "Exit Exception while '{}': {}".format(stage[1], e),
2577 exc_info=True,
2578 )
2579 finally:
2580 if exc:
2581 error_list.append(str(exc))
2582 try:
2583 # wait for pending tasks
2584 if tasks_dict_info:
2585 stage[1] = "Waiting for instantiate pending tasks."
2586 self.logger.debug(logging_text + stage[1])
2587 error_list += await self._wait_for_tasks(
2588 logging_text,
2589 tasks_dict_info,
2590 timeout_ns_deploy,
2591 stage,
2592 nslcmop_id,
2593 nsr_id=nsr_id,
2594 )
2595 stage[1] = stage[2] = ""
2596 except asyncio.CancelledError:
2597 error_list.append("Cancelled")
2598 # TODO cancel all tasks
2599 except Exception as exc:
2600 error_list.append(str(exc))
2601
2602 # update operation-status
2603 db_nsr_update["operational-status"] = "running"
2604 # let's begin with VCA 'configured' status (later we can change it)
2605 db_nsr_update["config-status"] = "configured"
2606 for task, task_name in tasks_dict_info.items():
2607 if not task.done() or task.cancelled() or task.exception():
2608 if task_name.startswith(self.task_name_deploy_vca):
2609 # A N2VC task is pending
2610 db_nsr_update["config-status"] = "failed"
2611 else:
2612 # RO or KDU task is pending
2613 db_nsr_update["operational-status"] = "failed"
2614
2615 # update status at database
2616 if error_list:
2617 error_detail = ". ".join(error_list)
2618 self.logger.error(logging_text + error_detail)
2619 error_description_nslcmop = "{} Detail: {}".format(
2620 stage[0], error_detail
2621 )
2622 error_description_nsr = "Operation: INSTANTIATING.{}, {}".format(
2623 nslcmop_id, stage[0]
2624 )
2625
2626 db_nsr_update["detailed-status"] = (
2627 error_description_nsr + " Detail: " + error_detail
2628 )
2629 db_nslcmop_update["detailed-status"] = error_detail
2630 nslcmop_operation_state = "FAILED"
2631 ns_state = "BROKEN"
2632 else:
2633 error_detail = None
2634 error_description_nsr = error_description_nslcmop = None
2635 ns_state = "READY"
2636 db_nsr_update["detailed-status"] = "Done"
2637 db_nslcmop_update["detailed-status"] = "Done"
2638 nslcmop_operation_state = "COMPLETED"
2639
2640 if db_nsr:
2641 self._write_ns_status(
2642 nsr_id=nsr_id,
2643 ns_state=ns_state,
2644 current_operation="IDLE",
2645 current_operation_id=None,
2646 error_description=error_description_nsr,
2647 error_detail=error_detail,
2648 other_update=db_nsr_update,
2649 )
2650 self._write_op_status(
2651 op_id=nslcmop_id,
2652 stage="",
2653 error_message=error_description_nslcmop,
2654 operation_state=nslcmop_operation_state,
2655 other_update=db_nslcmop_update,
2656 )
2657
2658 if nslcmop_operation_state:
2659 try:
2660 await self.msg.aiowrite(
2661 "ns",
2662 "instantiated",
2663 {
2664 "nsr_id": nsr_id,
2665 "nslcmop_id": nslcmop_id,
2666 "operationState": nslcmop_operation_state,
2667 },
2668 loop=self.loop,
2669 )
2670 except Exception as e:
2671 self.logger.error(
2672 logging_text + "kafka_write notification Exception {}".format(e)
2673 )
2674
2675 self.logger.debug(logging_text + "Exit")
2676 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_instantiate")
2677
2678 async def _add_vca_relations(
2679 self,
2680 logging_text,
2681 nsr_id,
2682 vca_index: int,
2683 timeout: int = 3600,
2684 vca_type: str = None,
2685 vca_id: str = None,
2686 ) -> bool:
2687
2688 # steps:
2689 # 1. find all relations for this VCA
2690 # 2. wait for other peers related
2691 # 3. add relations
2692
2693 try:
2694 vca_type = vca_type or "lxc_proxy_charm"
2695
2696 # STEP 1: find all relations for this VCA
2697
2698 # read nsr record
2699 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2700 nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
2701
2702 # this VCA data
2703 my_vca = deep_get(db_nsr, ("_admin", "deployed", "VCA"))[vca_index]
2704
2705 # read all ns-configuration relations
2706 ns_relations = list()
2707 db_ns_relations = deep_get(nsd, ("ns-configuration", "relation"))
2708 if db_ns_relations:
2709 for r in db_ns_relations:
2710 # check if this VCA is in the relation
2711 if my_vca.get("member-vnf-index") in (
2712 r.get("entities")[0].get("id"),
2713 r.get("entities")[1].get("id"),
2714 ):
2715 ns_relations.append(r)
2716
2717 # read all vnf-configuration relations
2718 vnf_relations = list()
2719 db_vnfd_list = db_nsr.get("vnfd-id")
2720 if db_vnfd_list:
2721 for vnfd in db_vnfd_list:
2722 db_vnf_relations = None
2723 db_vnfd = self.db.get_one("vnfds", {"_id": vnfd})
2724 db_vnf_configuration = get_configuration(db_vnfd, db_vnfd["id"])
2725 if db_vnf_configuration:
2726 db_vnf_relations = db_vnf_configuration.get("relation", [])
2727 if db_vnf_relations:
2728 for r in db_vnf_relations:
2729 # check if this VCA is in the relation
2730 if my_vca.get("vdu_id") in (
2731 r.get("entities")[0].get("id"),
2732 r.get("entities")[1].get("id"),
2733 ):
2734 vnf_relations.append(r)
2735
2736 # if no relations, terminate
2737 if not ns_relations and not vnf_relations:
2738 self.logger.debug(logging_text + " No relations")
2739 return True
2740
2741 self.logger.debug(
2742 logging_text
2743 + " adding relations\n {}\n {}".format(
2744 ns_relations, vnf_relations
2745 )
2746 )
2747
2748 # add all relations
2749 start = time()
2750 while True:
2751 # check timeout
2752 now = time()
2753 if now - start >= timeout:
2754 self.logger.error(logging_text + " : timeout adding relations")
2755 return False
2756
2757 # reload nsr from database (we need to update record: _admin.deloyed.VCA)
2758 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2759
2760 # for each defined NS relation, find the VCA's related
2761 for r in ns_relations.copy():
2762 from_vca_ee_id = None
2763 to_vca_ee_id = None
2764 from_vca_endpoint = None
2765 to_vca_endpoint = None
2766 vca_list = deep_get(db_nsr, ("_admin", "deployed", "VCA"))
2767 for vca in vca_list:
2768 if vca.get("member-vnf-index") == r.get("entities")[0].get(
2769 "id"
2770 ) and vca.get("config_sw_installed"):
2771 from_vca_ee_id = vca.get("ee_id")
2772 from_vca_endpoint = r.get("entities")[0].get("endpoint")
2773 if vca.get("member-vnf-index") == r.get("entities")[1].get(
2774 "id"
2775 ) and vca.get("config_sw_installed"):
2776 to_vca_ee_id = vca.get("ee_id")
2777 to_vca_endpoint = r.get("entities")[1].get("endpoint")
2778 if from_vca_ee_id and to_vca_ee_id:
2779 # add relation
2780 await self.vca_map[vca_type].add_relation(
2781 ee_id_1=from_vca_ee_id,
2782 ee_id_2=to_vca_ee_id,
2783 endpoint_1=from_vca_endpoint,
2784 endpoint_2=to_vca_endpoint,
2785 vca_id=vca_id,
2786 )
2787 # remove entry from relations list
2788 ns_relations.remove(r)
2789 else:
2790 # check failed peers
2791 try:
2792 vca_status_list = db_nsr.get("configurationStatus")
2793 if vca_status_list:
2794 for i in range(len(vca_list)):
2795 vca = vca_list[i]
2796 vca_status = vca_status_list[i]
2797 if vca.get("member-vnf-index") == r.get("entities")[
2798 0
2799 ].get("id"):
2800 if vca_status.get("status") == "BROKEN":
2801 # peer broken: remove relation from list
2802 ns_relations.remove(r)
2803 if vca.get("member-vnf-index") == r.get("entities")[
2804 1
2805 ].get("id"):
2806 if vca_status.get("status") == "BROKEN":
2807 # peer broken: remove relation from list
2808 ns_relations.remove(r)
2809 except Exception:
2810 # ignore
2811 pass
2812
2813 # for each defined VNF relation, find the VCA's related
2814 for r in vnf_relations.copy():
2815 from_vca_ee_id = None
2816 to_vca_ee_id = None
2817 from_vca_endpoint = None
2818 to_vca_endpoint = None
2819 vca_list = deep_get(db_nsr, ("_admin", "deployed", "VCA"))
2820 for vca in vca_list:
2821 key_to_check = "vdu_id"
2822 if vca.get("vdu_id") is None:
2823 key_to_check = "vnfd_id"
2824 if vca.get(key_to_check) == r.get("entities")[0].get(
2825 "id"
2826 ) and vca.get("config_sw_installed"):
2827 from_vca_ee_id = vca.get("ee_id")
2828 from_vca_endpoint = r.get("entities")[0].get("endpoint")
2829 if vca.get(key_to_check) == r.get("entities")[1].get(
2830 "id"
2831 ) and vca.get("config_sw_installed"):
2832 to_vca_ee_id = vca.get("ee_id")
2833 to_vca_endpoint = r.get("entities")[1].get("endpoint")
2834 if from_vca_ee_id and to_vca_ee_id:
2835 # add relation
2836 await self.vca_map[vca_type].add_relation(
2837 ee_id_1=from_vca_ee_id,
2838 ee_id_2=to_vca_ee_id,
2839 endpoint_1=from_vca_endpoint,
2840 endpoint_2=to_vca_endpoint,
2841 vca_id=vca_id,
2842 )
2843 # remove entry from relations list
2844 vnf_relations.remove(r)
2845 else:
2846 # check failed peers
2847 try:
2848 vca_status_list = db_nsr.get("configurationStatus")
2849 if vca_status_list:
2850 for i in range(len(vca_list)):
2851 vca = vca_list[i]
2852 vca_status = vca_status_list[i]
2853 if vca.get("vdu_id") == r.get("entities")[0].get(
2854 "id"
2855 ):
2856 if vca_status.get("status") == "BROKEN":
2857 # peer broken: remove relation from list
2858 vnf_relations.remove(r)
2859 if vca.get("vdu_id") == r.get("entities")[1].get(
2860 "id"
2861 ):
2862 if vca_status.get("status") == "BROKEN":
2863 # peer broken: remove relation from list
2864 vnf_relations.remove(r)
2865 except Exception:
2866 # ignore
2867 pass
2868
2869 # wait for next try
2870 await asyncio.sleep(5.0)
2871
2872 if not ns_relations and not vnf_relations:
2873 self.logger.debug("Relations added")
2874 break
2875
2876 return True
2877
2878 except Exception as e:
2879 self.logger.warn(logging_text + " ERROR adding relations: {}".format(e))
2880 return False
2881
2882 async def _install_kdu(
2883 self,
2884 nsr_id: str,
2885 nsr_db_path: str,
2886 vnfr_data: dict,
2887 kdu_index: int,
2888 kdud: dict,
2889 vnfd: dict,
2890 k8s_instance_info: dict,
2891 k8params: dict = None,
2892 timeout: int = 600,
2893 vca_id: str = None,
2894 ):
2895
2896 try:
2897 k8sclustertype = k8s_instance_info["k8scluster-type"]
2898 # Instantiate kdu
2899 db_dict_install = {
2900 "collection": "nsrs",
2901 "filter": {"_id": nsr_id},
2902 "path": nsr_db_path,
2903 }
2904
2905 if k8s_instance_info.get("kdu-deployment-name"):
2906 kdu_instance = k8s_instance_info.get("kdu-deployment-name")
2907 else:
2908 kdu_instance = self.k8scluster_map[
2909 k8sclustertype
2910 ].generate_kdu_instance_name(
2911 db_dict=db_dict_install,
2912 kdu_model=k8s_instance_info["kdu-model"],
2913 kdu_name=k8s_instance_info["kdu-name"],
2914 )
2915 self.update_db_2(
2916 "nsrs", nsr_id, {nsr_db_path + ".kdu-instance": kdu_instance}
2917 )
2918 await self.k8scluster_map[k8sclustertype].install(
2919 cluster_uuid=k8s_instance_info["k8scluster-uuid"],
2920 kdu_model=k8s_instance_info["kdu-model"],
2921 atomic=True,
2922 params=k8params,
2923 db_dict=db_dict_install,
2924 timeout=timeout,
2925 kdu_name=k8s_instance_info["kdu-name"],
2926 namespace=k8s_instance_info["namespace"],
2927 kdu_instance=kdu_instance,
2928 vca_id=vca_id,
2929 )
2930 self.update_db_2(
2931 "nsrs", nsr_id, {nsr_db_path + ".kdu-instance": kdu_instance}
2932 )
2933
2934 # Obtain services to obtain management service ip
2935 services = await self.k8scluster_map[k8sclustertype].get_services(
2936 cluster_uuid=k8s_instance_info["k8scluster-uuid"],
2937 kdu_instance=kdu_instance,
2938 namespace=k8s_instance_info["namespace"],
2939 )
2940
2941 # Obtain management service info (if exists)
2942 vnfr_update_dict = {}
2943 kdu_config = get_configuration(vnfd, kdud["name"])
2944 if kdu_config:
2945 target_ee_list = kdu_config.get("execution-environment-list", [])
2946 else:
2947 target_ee_list = []
2948
2949 if services:
2950 vnfr_update_dict["kdur.{}.services".format(kdu_index)] = services
2951 mgmt_services = [
2952 service
2953 for service in kdud.get("service", [])
2954 if service.get("mgmt-service")
2955 ]
2956 for mgmt_service in mgmt_services:
2957 for service in services:
2958 if service["name"].startswith(mgmt_service["name"]):
2959 # Mgmt service found, Obtain service ip
2960 ip = service.get("external_ip", service.get("cluster_ip"))
2961 if isinstance(ip, list) and len(ip) == 1:
2962 ip = ip[0]
2963
2964 vnfr_update_dict[
2965 "kdur.{}.ip-address".format(kdu_index)
2966 ] = ip
2967
2968 # Check if must update also mgmt ip at the vnf
2969 service_external_cp = mgmt_service.get(
2970 "external-connection-point-ref"
2971 )
2972 if service_external_cp:
2973 if (
2974 deep_get(vnfd, ("mgmt-interface", "cp"))
2975 == service_external_cp
2976 ):
2977 vnfr_update_dict["ip-address"] = ip
2978
2979 if find_in_list(
2980 target_ee_list,
2981 lambda ee: ee.get(
2982 "external-connection-point-ref", ""
2983 )
2984 == service_external_cp,
2985 ):
2986 vnfr_update_dict[
2987 "kdur.{}.ip-address".format(kdu_index)
2988 ] = ip
2989 break
2990 else:
2991 self.logger.warn(
2992 "Mgmt service name: {} not found".format(
2993 mgmt_service["name"]
2994 )
2995 )
2996
2997 vnfr_update_dict["kdur.{}.status".format(kdu_index)] = "READY"
2998 self.update_db_2("vnfrs", vnfr_data.get("_id"), vnfr_update_dict)
2999
3000 kdu_config = get_configuration(vnfd, k8s_instance_info["kdu-name"])
3001 if (
3002 kdu_config
3003 and kdu_config.get("initial-config-primitive")
3004 and get_juju_ee_ref(vnfd, k8s_instance_info["kdu-name"]) is None
3005 ):
3006 initial_config_primitive_list = kdu_config.get(
3007 "initial-config-primitive"
3008 )
3009 initial_config_primitive_list.sort(key=lambda val: int(val["seq"]))
3010
3011 for initial_config_primitive in initial_config_primitive_list:
3012 primitive_params_ = self._map_primitive_params(
3013 initial_config_primitive, {}, {}
3014 )
3015
3016 await asyncio.wait_for(
3017 self.k8scluster_map[k8sclustertype].exec_primitive(
3018 cluster_uuid=k8s_instance_info["k8scluster-uuid"],
3019 kdu_instance=kdu_instance,
3020 primitive_name=initial_config_primitive["name"],
3021 params=primitive_params_,
3022 db_dict=db_dict_install,
3023 vca_id=vca_id,
3024 ),
3025 timeout=timeout,
3026 )
3027
3028 except Exception as e:
3029 # Prepare update db with error and raise exception
3030 try:
3031 self.update_db_2(
3032 "nsrs", nsr_id, {nsr_db_path + ".detailed-status": str(e)}
3033 )
3034 self.update_db_2(
3035 "vnfrs",
3036 vnfr_data.get("_id"),
3037 {"kdur.{}.status".format(kdu_index): "ERROR"},
3038 )
3039 except Exception:
3040 # ignore to keep original exception
3041 pass
3042 # reraise original error
3043 raise
3044
3045 return kdu_instance
3046
3047 async def deploy_kdus(
3048 self,
3049 logging_text,
3050 nsr_id,
3051 nslcmop_id,
3052 db_vnfrs,
3053 db_vnfds,
3054 task_instantiation_info,
3055 ):
3056 # Launch kdus if present in the descriptor
3057
3058 k8scluster_id_2_uuic = {
3059 "helm-chart-v3": {},
3060 "helm-chart": {},
3061 "juju-bundle": {},
3062 }
3063
3064 async def _get_cluster_id(cluster_id, cluster_type):
3065 nonlocal k8scluster_id_2_uuic
3066 if cluster_id in k8scluster_id_2_uuic[cluster_type]:
3067 return k8scluster_id_2_uuic[cluster_type][cluster_id]
3068
3069 # check if K8scluster is creating and wait look if previous tasks in process
3070 task_name, task_dependency = self.lcm_tasks.lookfor_related(
3071 "k8scluster", cluster_id
3072 )
3073 if task_dependency:
3074 text = "Waiting for related tasks '{}' on k8scluster {} to be completed".format(
3075 task_name, cluster_id
3076 )
3077 self.logger.debug(logging_text + text)
3078 await asyncio.wait(task_dependency, timeout=3600)
3079
3080 db_k8scluster = self.db.get_one(
3081 "k8sclusters", {"_id": cluster_id}, fail_on_empty=False
3082 )
3083 if not db_k8scluster:
3084 raise LcmException("K8s cluster {} cannot be found".format(cluster_id))
3085
3086 k8s_id = deep_get(db_k8scluster, ("_admin", cluster_type, "id"))
3087 if not k8s_id:
3088 if cluster_type == "helm-chart-v3":
3089 try:
3090 # backward compatibility for existing clusters that have not been initialized for helm v3
3091 k8s_credentials = yaml.safe_dump(
3092 db_k8scluster.get("credentials")
3093 )
3094 k8s_id, uninstall_sw = await self.k8sclusterhelm3.init_env(
3095 k8s_credentials, reuse_cluster_uuid=cluster_id
3096 )
3097 db_k8scluster_update = {}
3098 db_k8scluster_update["_admin.helm-chart-v3.error_msg"] = None
3099 db_k8scluster_update["_admin.helm-chart-v3.id"] = k8s_id
3100 db_k8scluster_update[
3101 "_admin.helm-chart-v3.created"
3102 ] = uninstall_sw
3103 db_k8scluster_update[
3104 "_admin.helm-chart-v3.operationalState"
3105 ] = "ENABLED"
3106 self.update_db_2(
3107 "k8sclusters", cluster_id, db_k8scluster_update
3108 )
3109 except Exception as e:
3110 self.logger.error(
3111 logging_text
3112 + "error initializing helm-v3 cluster: {}".format(str(e))
3113 )
3114 raise LcmException(
3115 "K8s cluster '{}' has not been initialized for '{}'".format(
3116 cluster_id, cluster_type
3117 )
3118 )
3119 else:
3120 raise LcmException(
3121 "K8s cluster '{}' has not been initialized for '{}'".format(
3122 cluster_id, cluster_type
3123 )
3124 )
3125 k8scluster_id_2_uuic[cluster_type][cluster_id] = k8s_id
3126 return k8s_id
3127
3128 logging_text += "Deploy kdus: "
3129 step = ""
3130 try:
3131 db_nsr_update = {"_admin.deployed.K8s": []}
3132 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3133
3134 index = 0
3135 updated_cluster_list = []
3136 updated_v3_cluster_list = []
3137
3138 for vnfr_data in db_vnfrs.values():
3139 vca_id = self.get_vca_id(vnfr_data, {})
3140 for kdu_index, kdur in enumerate(get_iterable(vnfr_data, "kdur")):
3141 # Step 0: Prepare and set parameters
3142 desc_params = parse_yaml_strings(kdur.get("additionalParams"))
3143 vnfd_id = vnfr_data.get("vnfd-id")
3144 vnfd_with_id = find_in_list(
3145 db_vnfds, lambda vnfd: vnfd["_id"] == vnfd_id
3146 )
3147 kdud = next(
3148 kdud
3149 for kdud in vnfd_with_id["kdu"]
3150 if kdud["name"] == kdur["kdu-name"]
3151 )
3152 namespace = kdur.get("k8s-namespace")
3153 kdu_deployment_name = kdur.get("kdu-deployment-name")
3154 if kdur.get("helm-chart"):
3155 kdumodel = kdur["helm-chart"]
3156 # Default version: helm3, if helm-version is v2 assign v2
3157 k8sclustertype = "helm-chart-v3"
3158 self.logger.debug("kdur: {}".format(kdur))
3159 if (
3160 kdur.get("helm-version")
3161 and kdur.get("helm-version") == "v2"
3162 ):
3163 k8sclustertype = "helm-chart"
3164 elif kdur.get("juju-bundle"):
3165 kdumodel = kdur["juju-bundle"]
3166 k8sclustertype = "juju-bundle"
3167 else:
3168 raise LcmException(
3169 "kdu type for kdu='{}.{}' is neither helm-chart nor "
3170 "juju-bundle. Maybe an old NBI version is running".format(
3171 vnfr_data["member-vnf-index-ref"], kdur["kdu-name"]
3172 )
3173 )
3174 # check if kdumodel is a file and exists
3175 try:
3176 vnfd_with_id = find_in_list(
3177 db_vnfds, lambda vnfd: vnfd["_id"] == vnfd_id
3178 )
3179 storage = deep_get(vnfd_with_id, ("_admin", "storage"))
3180 if storage and storage.get(
3181 "pkg-dir"
3182 ): # may be not present if vnfd has not artifacts
3183 # path format: /vnfdid/pkkdir/helm-charts|juju-bundles/kdumodel
3184 filename = "{}/{}/{}s/{}".format(
3185 storage["folder"],
3186 storage["pkg-dir"],
3187 k8sclustertype,
3188 kdumodel,
3189 )
3190 if self.fs.file_exists(
3191 filename, mode="file"
3192 ) or self.fs.file_exists(filename, mode="dir"):
3193 kdumodel = self.fs.path + filename
3194 except (asyncio.TimeoutError, asyncio.CancelledError):
3195 raise
3196 except Exception: # it is not a file
3197 pass
3198
3199 k8s_cluster_id = kdur["k8s-cluster"]["id"]
3200 step = "Synchronize repos for k8s cluster '{}'".format(
3201 k8s_cluster_id
3202 )
3203 cluster_uuid = await _get_cluster_id(k8s_cluster_id, k8sclustertype)
3204
3205 # Synchronize repos
3206 if (
3207 k8sclustertype == "helm-chart"
3208 and cluster_uuid not in updated_cluster_list
3209 ) or (
3210 k8sclustertype == "helm-chart-v3"
3211 and cluster_uuid not in updated_v3_cluster_list
3212 ):
3213 del_repo_list, added_repo_dict = await asyncio.ensure_future(
3214 self.k8scluster_map[k8sclustertype].synchronize_repos(
3215 cluster_uuid=cluster_uuid
3216 )
3217 )
3218 if del_repo_list or added_repo_dict:
3219 if k8sclustertype == "helm-chart":
3220 unset = {
3221 "_admin.helm_charts_added." + item: None
3222 for item in del_repo_list
3223 }
3224 updated = {
3225 "_admin.helm_charts_added." + item: name
3226 for item, name in added_repo_dict.items()
3227 }
3228 updated_cluster_list.append(cluster_uuid)
3229 elif k8sclustertype == "helm-chart-v3":
3230 unset = {
3231 "_admin.helm_charts_v3_added." + item: None
3232 for item in del_repo_list
3233 }
3234 updated = {
3235 "_admin.helm_charts_v3_added." + item: name
3236 for item, name in added_repo_dict.items()
3237 }
3238 updated_v3_cluster_list.append(cluster_uuid)
3239 self.logger.debug(
3240 logging_text + "repos synchronized on k8s cluster "
3241 "'{}' to_delete: {}, to_add: {}".format(
3242 k8s_cluster_id, del_repo_list, added_repo_dict
3243 )
3244 )
3245 self.db.set_one(
3246 "k8sclusters",
3247 {"_id": k8s_cluster_id},
3248 updated,
3249 unset=unset,
3250 )
3251
3252 # Instantiate kdu
3253 step = "Instantiating KDU {}.{} in k8s cluster {}".format(
3254 vnfr_data["member-vnf-index-ref"],
3255 kdur["kdu-name"],
3256 k8s_cluster_id,
3257 )
3258 k8s_instance_info = {
3259 "kdu-instance": None,
3260 "k8scluster-uuid": cluster_uuid,
3261 "k8scluster-type": k8sclustertype,
3262 "member-vnf-index": vnfr_data["member-vnf-index-ref"],
3263 "kdu-name": kdur["kdu-name"],
3264 "kdu-model": kdumodel,
3265 "namespace": namespace,
3266 "kdu-deployment-name": kdu_deployment_name,
3267 }
3268 db_path = "_admin.deployed.K8s.{}".format(index)
3269 db_nsr_update[db_path] = k8s_instance_info
3270 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3271 vnfd_with_id = find_in_list(
3272 db_vnfds, lambda vnf: vnf["_id"] == vnfd_id
3273 )
3274 task = asyncio.ensure_future(
3275 self._install_kdu(
3276 nsr_id,
3277 db_path,
3278 vnfr_data,
3279 kdu_index,
3280 kdud,
3281 vnfd_with_id,
3282 k8s_instance_info,
3283 k8params=desc_params,
3284 timeout=600,
3285 vca_id=vca_id,
3286 )
3287 )
3288 self.lcm_tasks.register(
3289 "ns",
3290 nsr_id,
3291 nslcmop_id,
3292 "instantiate_KDU-{}".format(index),
3293 task,
3294 )
3295 task_instantiation_info[task] = "Deploying KDU {}".format(
3296 kdur["kdu-name"]
3297 )
3298
3299 index += 1
3300
3301 except (LcmException, asyncio.CancelledError):
3302 raise
3303 except Exception as e:
3304 msg = "Exception {} while {}: {}".format(type(e).__name__, step, e)
3305 if isinstance(e, (N2VCException, DbException)):
3306 self.logger.error(logging_text + msg)
3307 else:
3308 self.logger.critical(logging_text + msg, exc_info=True)
3309 raise LcmException(msg)
3310 finally:
3311 if db_nsr_update:
3312 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3313
3314 def _deploy_n2vc(
3315 self,
3316 logging_text,
3317 db_nsr,
3318 db_vnfr,
3319 nslcmop_id,
3320 nsr_id,
3321 nsi_id,
3322 vnfd_id,
3323 vdu_id,
3324 kdu_name,
3325 member_vnf_index,
3326 vdu_index,
3327 vdu_name,
3328 deploy_params,
3329 descriptor_config,
3330 base_folder,
3331 task_instantiation_info,
3332 stage,
3333 ):
3334 # launch instantiate_N2VC in a asyncio task and register task object
3335 # Look where information of this charm is at database <nsrs>._admin.deployed.VCA
3336 # if not found, create one entry and update database
3337 # fill db_nsr._admin.deployed.VCA.<index>
3338
3339 self.logger.debug(
3340 logging_text + "_deploy_n2vc vnfd_id={}, vdu_id={}".format(vnfd_id, vdu_id)
3341 )
3342 if "execution-environment-list" in descriptor_config:
3343 ee_list = descriptor_config.get("execution-environment-list", [])
3344 elif "juju" in descriptor_config:
3345 ee_list = [descriptor_config] # ns charms
3346 else: # other types as script are not supported
3347 ee_list = []
3348
3349 for ee_item in ee_list:
3350 self.logger.debug(
3351 logging_text
3352 + "_deploy_n2vc ee_item juju={}, helm={}".format(
3353 ee_item.get("juju"), ee_item.get("helm-chart")
3354 )
3355 )
3356 ee_descriptor_id = ee_item.get("id")
3357 if ee_item.get("juju"):
3358 vca_name = ee_item["juju"].get("charm")
3359 vca_type = (
3360 "lxc_proxy_charm"
3361 if ee_item["juju"].get("charm") is not None
3362 else "native_charm"
3363 )
3364 if ee_item["juju"].get("cloud") == "k8s":
3365 vca_type = "k8s_proxy_charm"
3366 elif ee_item["juju"].get("proxy") is False:
3367 vca_type = "native_charm"
3368 elif ee_item.get("helm-chart"):
3369 vca_name = ee_item["helm-chart"]
3370 if ee_item.get("helm-version") and ee_item.get("helm-version") == "v2":
3371 vca_type = "helm"
3372 else:
3373 vca_type = "helm-v3"
3374 else:
3375 self.logger.debug(
3376 logging_text + "skipping non juju neither charm configuration"
3377 )
3378 continue
3379
3380 vca_index = -1
3381 for vca_index, vca_deployed in enumerate(
3382 db_nsr["_admin"]["deployed"]["VCA"]
3383 ):
3384 if not vca_deployed:
3385 continue
3386 if (
3387 vca_deployed.get("member-vnf-index") == member_vnf_index
3388 and vca_deployed.get("vdu_id") == vdu_id
3389 and vca_deployed.get("kdu_name") == kdu_name
3390 and vca_deployed.get("vdu_count_index", 0) == vdu_index
3391 and vca_deployed.get("ee_descriptor_id") == ee_descriptor_id
3392 ):
3393 break
3394 else:
3395 # not found, create one.
3396 target = (
3397 "ns" if not member_vnf_index else "vnf/{}".format(member_vnf_index)
3398 )
3399 if vdu_id:
3400 target += "/vdu/{}/{}".format(vdu_id, vdu_index or 0)
3401 elif kdu_name:
3402 target += "/kdu/{}".format(kdu_name)
3403 vca_deployed = {
3404 "target_element": target,
3405 # ^ target_element will replace member-vnf-index, kdu_name, vdu_id ... in a single string
3406 "member-vnf-index": member_vnf_index,
3407 "vdu_id": vdu_id,
3408 "kdu_name": kdu_name,
3409 "vdu_count_index": vdu_index,
3410 "operational-status": "init", # TODO revise
3411 "detailed-status": "", # TODO revise
3412 "step": "initial-deploy", # TODO revise
3413 "vnfd_id": vnfd_id,
3414 "vdu_name": vdu_name,
3415 "type": vca_type,
3416 "ee_descriptor_id": ee_descriptor_id,
3417 }
3418 vca_index += 1
3419
3420 # create VCA and configurationStatus in db
3421 db_dict = {
3422 "_admin.deployed.VCA.{}".format(vca_index): vca_deployed,
3423 "configurationStatus.{}".format(vca_index): dict(),
3424 }
3425 self.update_db_2("nsrs", nsr_id, db_dict)
3426
3427 db_nsr["_admin"]["deployed"]["VCA"].append(vca_deployed)
3428
3429 self.logger.debug("N2VC > NSR_ID > {}".format(nsr_id))
3430 self.logger.debug("N2VC > DB_NSR > {}".format(db_nsr))
3431 self.logger.debug("N2VC > VCA_DEPLOYED > {}".format(vca_deployed))
3432
3433 # Launch task
3434 task_n2vc = asyncio.ensure_future(
3435 self.instantiate_N2VC(
3436 logging_text=logging_text,
3437 vca_index=vca_index,
3438 nsi_id=nsi_id,
3439 db_nsr=db_nsr,
3440 db_vnfr=db_vnfr,
3441 vdu_id=vdu_id,
3442 kdu_name=kdu_name,
3443 vdu_index=vdu_index,
3444 deploy_params=deploy_params,
3445 config_descriptor=descriptor_config,
3446 base_folder=base_folder,
3447 nslcmop_id=nslcmop_id,
3448 stage=stage,
3449 vca_type=vca_type,
3450 vca_name=vca_name,
3451 ee_config_descriptor=ee_item,
3452 )
3453 )
3454 self.lcm_tasks.register(
3455 "ns",
3456 nsr_id,
3457 nslcmop_id,
3458 "instantiate_N2VC-{}".format(vca_index),
3459 task_n2vc,
3460 )
3461 task_instantiation_info[
3462 task_n2vc
3463 ] = self.task_name_deploy_vca + " {}.{}".format(
3464 member_vnf_index or "", vdu_id or ""
3465 )
3466
3467 @staticmethod
3468 def _create_nslcmop(nsr_id, operation, params):
3469 """
3470 Creates a ns-lcm-opp content to be stored at database.
3471 :param nsr_id: internal id of the instance
3472 :param operation: instantiate, terminate, scale, action, ...
3473 :param params: user parameters for the operation
3474 :return: dictionary following SOL005 format
3475 """
3476 # Raise exception if invalid arguments
3477 if not (nsr_id and operation and params):
3478 raise LcmException(
3479 "Parameters 'nsr_id', 'operation' and 'params' needed to create primitive not provided"
3480 )
3481 now = time()
3482 _id = str(uuid4())
3483 nslcmop = {
3484 "id": _id,
3485 "_id": _id,
3486 # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
3487 "operationState": "PROCESSING",
3488 "statusEnteredTime": now,
3489 "nsInstanceId": nsr_id,
3490 "lcmOperationType": operation,
3491 "startTime": now,
3492 "isAutomaticInvocation": False,
3493 "operationParams": params,
3494 "isCancelPending": False,
3495 "links": {
3496 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
3497 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
3498 },
3499 }
3500 return nslcmop
3501
3502 def _format_additional_params(self, params):
3503 params = params or {}
3504 for key, value in params.items():
3505 if str(value).startswith("!!yaml "):
3506 params[key] = yaml.safe_load(value[7:])
3507 return params
3508
3509 def _get_terminate_primitive_params(self, seq, vnf_index):
3510 primitive = seq.get("name")
3511 primitive_params = {}
3512 params = {
3513 "member_vnf_index": vnf_index,
3514 "primitive": primitive,
3515 "primitive_params": primitive_params,
3516 }
3517 desc_params = {}
3518 return self._map_primitive_params(seq, params, desc_params)
3519
3520 # sub-operations
3521
3522 def _retry_or_skip_suboperation(self, db_nslcmop, op_index):
3523 op = deep_get(db_nslcmop, ("_admin", "operations"), [])[op_index]
3524 if op.get("operationState") == "COMPLETED":
3525 # b. Skip sub-operation
3526 # _ns_execute_primitive() or RO.create_action() will NOT be executed
3527 return self.SUBOPERATION_STATUS_SKIP
3528 else:
3529 # c. retry executing sub-operation
3530 # The sub-operation exists, and operationState != 'COMPLETED'
3531 # Update operationState = 'PROCESSING' to indicate a retry.
3532 operationState = "PROCESSING"
3533 detailed_status = "In progress"
3534 self._update_suboperation_status(
3535 db_nslcmop, op_index, operationState, detailed_status
3536 )
3537 # Return the sub-operation index
3538 # _ns_execute_primitive() or RO.create_action() will be called from scale()
3539 # with arguments extracted from the sub-operation
3540 return op_index
3541
3542 # Find a sub-operation where all keys in a matching dictionary must match
3543 # Returns the index of the matching sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if no match
3544 def _find_suboperation(self, db_nslcmop, match):
3545 if db_nslcmop and match:
3546 op_list = db_nslcmop.get("_admin", {}).get("operations", [])
3547 for i, op in enumerate(op_list):
3548 if all(op.get(k) == match[k] for k in match):
3549 return i
3550 return self.SUBOPERATION_STATUS_NOT_FOUND
3551
3552 # Update status for a sub-operation given its index
3553 def _update_suboperation_status(
3554 self, db_nslcmop, op_index, operationState, detailed_status
3555 ):
3556 # Update DB for HA tasks
3557 q_filter = {"_id": db_nslcmop["_id"]}
3558 update_dict = {
3559 "_admin.operations.{}.operationState".format(op_index): operationState,
3560 "_admin.operations.{}.detailed-status".format(op_index): detailed_status,
3561 }
3562 self.db.set_one(
3563 "nslcmops", q_filter=q_filter, update_dict=update_dict, fail_on_empty=False
3564 )
3565
3566 # Add sub-operation, return the index of the added sub-operation
3567 # Optionally, set operationState, detailed-status, and operationType
3568 # Status and type are currently set for 'scale' sub-operations:
3569 # 'operationState' : 'PROCESSING' | 'COMPLETED' | 'FAILED'
3570 # 'detailed-status' : status message
3571 # 'operationType': may be any type, in the case of scaling: 'PRE-SCALE' | 'POST-SCALE'
3572 # Status and operation type are currently only used for 'scale', but NOT for 'terminate' sub-operations.
3573 def _add_suboperation(
3574 self,
3575 db_nslcmop,
3576 vnf_index,
3577 vdu_id,
3578 vdu_count_index,
3579 vdu_name,
3580 primitive,
3581 mapped_primitive_params,
3582 operationState=None,
3583 detailed_status=None,
3584 operationType=None,
3585 RO_nsr_id=None,
3586 RO_scaling_info=None,
3587 ):
3588 if not db_nslcmop:
3589 return self.SUBOPERATION_STATUS_NOT_FOUND
3590 # Get the "_admin.operations" list, if it exists
3591 db_nslcmop_admin = db_nslcmop.get("_admin", {})
3592 op_list = db_nslcmop_admin.get("operations")
3593 # Create or append to the "_admin.operations" list
3594 new_op = {
3595 "member_vnf_index": vnf_index,
3596 "vdu_id": vdu_id,
3597 "vdu_count_index": vdu_count_index,
3598 "primitive": primitive,
3599 "primitive_params": mapped_primitive_params,
3600 }
3601 if operationState:
3602 new_op["operationState"] = operationState
3603 if detailed_status:
3604 new_op["detailed-status"] = detailed_status
3605 if operationType:
3606 new_op["lcmOperationType"] = operationType
3607 if RO_nsr_id:
3608 new_op["RO_nsr_id"] = RO_nsr_id
3609 if RO_scaling_info:
3610 new_op["RO_scaling_info"] = RO_scaling_info
3611 if not op_list:
3612 # No existing operations, create key 'operations' with current operation as first list element
3613 db_nslcmop_admin.update({"operations": [new_op]})
3614 op_list = db_nslcmop_admin.get("operations")
3615 else:
3616 # Existing operations, append operation to list
3617 op_list.append(new_op)
3618
3619 db_nslcmop_update = {"_admin.operations": op_list}
3620 self.update_db_2("nslcmops", db_nslcmop["_id"], db_nslcmop_update)
3621 op_index = len(op_list) - 1
3622 return op_index
3623
3624 # Helper methods for scale() sub-operations
3625
3626 # pre-scale/post-scale:
3627 # Check for 3 different cases:
3628 # a. New: First time execution, return SUBOPERATION_STATUS_NEW
3629 # b. Skip: Existing sub-operation exists, operationState == 'COMPLETED', return SUBOPERATION_STATUS_SKIP
3630 # c. retry: Existing sub-operation exists, operationState != 'COMPLETED', return op_index to re-execute
3631 def _check_or_add_scale_suboperation(
3632 self,
3633 db_nslcmop,
3634 vnf_index,
3635 vnf_config_primitive,
3636 primitive_params,
3637 operationType,
3638 RO_nsr_id=None,
3639 RO_scaling_info=None,
3640 ):
3641 # Find this sub-operation
3642 if RO_nsr_id and RO_scaling_info:
3643 operationType = "SCALE-RO"
3644 match = {
3645 "member_vnf_index": vnf_index,
3646 "RO_nsr_id": RO_nsr_id,
3647 "RO_scaling_info": RO_scaling_info,
3648 }
3649 else:
3650 match = {
3651 "member_vnf_index": vnf_index,
3652 "primitive": vnf_config_primitive,
3653 "primitive_params": primitive_params,
3654 "lcmOperationType": operationType,
3655 }
3656 op_index = self._find_suboperation(db_nslcmop, match)
3657 if op_index == self.SUBOPERATION_STATUS_NOT_FOUND:
3658 # a. New sub-operation
3659 # The sub-operation does not exist, add it.
3660 # _ns_execute_primitive() will be called from scale() as usual, with non-modified arguments
3661 # The following parameters are set to None for all kind of scaling:
3662 vdu_id = None
3663 vdu_count_index = None
3664 vdu_name = None
3665 if RO_nsr_id and RO_scaling_info:
3666 vnf_config_primitive = None
3667 primitive_params = None
3668 else:
3669 RO_nsr_id = None
3670 RO_scaling_info = None
3671 # Initial status for sub-operation
3672 operationState = "PROCESSING"
3673 detailed_status = "In progress"
3674 # Add sub-operation for pre/post-scaling (zero or more operations)
3675 self._add_suboperation(
3676 db_nslcmop,
3677 vnf_index,
3678 vdu_id,
3679 vdu_count_index,
3680 vdu_name,
3681 vnf_config_primitive,
3682 primitive_params,
3683 operationState,
3684 detailed_status,
3685 operationType,
3686 RO_nsr_id,
3687 RO_scaling_info,
3688 )
3689 return self.SUBOPERATION_STATUS_NEW
3690 else:
3691 # Return either SUBOPERATION_STATUS_SKIP (operationState == 'COMPLETED'),
3692 # or op_index (operationState != 'COMPLETED')
3693 return self._retry_or_skip_suboperation(db_nslcmop, op_index)
3694
3695 # Function to return execution_environment id
3696
3697 def _get_ee_id(self, vnf_index, vdu_id, vca_deployed_list):
3698 # TODO vdu_index_count
3699 for vca in vca_deployed_list:
3700 if vca["member-vnf-index"] == vnf_index and vca["vdu_id"] == vdu_id:
3701 return vca["ee_id"]
3702
3703 async def destroy_N2VC(
3704 self,
3705 logging_text,
3706 db_nslcmop,
3707 vca_deployed,
3708 config_descriptor,
3709 vca_index,
3710 destroy_ee=True,
3711 exec_primitives=True,
3712 scaling_in=False,
3713 vca_id: str = None,
3714 ):
3715 """
3716 Execute the terminate primitives and destroy the execution environment (if destroy_ee=False
3717 :param logging_text:
3718 :param db_nslcmop:
3719 :param vca_deployed: Dictionary of deployment info at db_nsr._admin.depoloyed.VCA.<INDEX>
3720 :param config_descriptor: Configuration descriptor of the NSD, VNFD, VNFD.vdu or VNFD.kdu
3721 :param vca_index: index in the database _admin.deployed.VCA
3722 :param destroy_ee: False to do not destroy, because it will be destroyed all of then at once
3723 :param exec_primitives: False to do not execute terminate primitives, because the config is not completed or has
3724 not executed properly
3725 :param scaling_in: True destroys the application, False destroys the model
3726 :return: None or exception
3727 """
3728
3729 self.logger.debug(
3730 logging_text
3731 + " vca_index: {}, vca_deployed: {}, config_descriptor: {}, destroy_ee: {}".format(
3732 vca_index, vca_deployed, config_descriptor, destroy_ee
3733 )
3734 )
3735
3736 vca_type = vca_deployed.get("type", "lxc_proxy_charm")
3737
3738 # execute terminate_primitives
3739 if exec_primitives:
3740 terminate_primitives = get_ee_sorted_terminate_config_primitive_list(
3741 config_descriptor.get("terminate-config-primitive"),
3742 vca_deployed.get("ee_descriptor_id"),
3743 )
3744 vdu_id = vca_deployed.get("vdu_id")
3745 vdu_count_index = vca_deployed.get("vdu_count_index")
3746 vdu_name = vca_deployed.get("vdu_name")
3747 vnf_index = vca_deployed.get("member-vnf-index")
3748 if terminate_primitives and vca_deployed.get("needed_terminate"):
3749 for seq in terminate_primitives:
3750 # For each sequence in list, get primitive and call _ns_execute_primitive()
3751 step = "Calling terminate action for vnf_member_index={} primitive={}".format(
3752 vnf_index, seq.get("name")
3753 )
3754 self.logger.debug(logging_text + step)
3755 # Create the primitive for each sequence, i.e. "primitive": "touch"
3756 primitive = seq.get("name")
3757 mapped_primitive_params = self._get_terminate_primitive_params(
3758 seq, vnf_index
3759 )
3760
3761 # Add sub-operation
3762 self._add_suboperation(
3763 db_nslcmop,
3764 vnf_index,
3765 vdu_id,
3766 vdu_count_index,
3767 vdu_name,
3768 primitive,
3769 mapped_primitive_params,
3770 )
3771 # Sub-operations: Call _ns_execute_primitive() instead of action()
3772 try:
3773 result, result_detail = await self._ns_execute_primitive(
3774 vca_deployed["ee_id"],
3775 primitive,
3776 mapped_primitive_params,
3777 vca_type=vca_type,
3778 vca_id=vca_id,
3779 )
3780 except LcmException:
3781 # this happens when VCA is not deployed. In this case it is not needed to terminate
3782 continue
3783 result_ok = ["COMPLETED", "PARTIALLY_COMPLETED"]
3784 if result not in result_ok:
3785 raise LcmException(
3786 "terminate_primitive {} for vnf_member_index={} fails with "
3787 "error {}".format(seq.get("name"), vnf_index, result_detail)
3788 )
3789 # set that this VCA do not need terminated
3790 db_update_entry = "_admin.deployed.VCA.{}.needed_terminate".format(
3791 vca_index
3792 )
3793 self.update_db_2(
3794 "nsrs", db_nslcmop["nsInstanceId"], {db_update_entry: False}
3795 )
3796
3797 if vca_deployed.get("prometheus_jobs") and self.prometheus:
3798 await self.prometheus.update(remove_jobs=vca_deployed["prometheus_jobs"])
3799
3800 if destroy_ee:
3801 await self.vca_map[vca_type].delete_execution_environment(
3802 vca_deployed["ee_id"],
3803 scaling_in=scaling_in,
3804 vca_type=vca_type,
3805 vca_id=vca_id,
3806 )
3807
3808 async def _delete_all_N2VC(self, db_nsr: dict, vca_id: str = None):
3809 self._write_all_config_status(db_nsr=db_nsr, status="TERMINATING")
3810 namespace = "." + db_nsr["_id"]
3811 try:
3812 await self.n2vc.delete_namespace(
3813 namespace=namespace,
3814 total_timeout=self.timeout_charm_delete,
3815 vca_id=vca_id,
3816 )
3817 except N2VCNotFound: # already deleted. Skip
3818 pass
3819 self._write_all_config_status(db_nsr=db_nsr, status="DELETED")
3820
3821 async def _terminate_RO(
3822 self, logging_text, nsr_deployed, nsr_id, nslcmop_id, stage
3823 ):
3824 """
3825 Terminates a deployment from RO
3826 :param logging_text:
3827 :param nsr_deployed: db_nsr._admin.deployed
3828 :param nsr_id:
3829 :param nslcmop_id:
3830 :param stage: list of string with the content to write on db_nslcmop.detailed-status.
3831 this method will update only the index 2, but it will write on database the concatenated content of the list
3832 :return:
3833 """
3834 db_nsr_update = {}
3835 failed_detail = []
3836 ro_nsr_id = ro_delete_action = None
3837 if nsr_deployed and nsr_deployed.get("RO"):
3838 ro_nsr_id = nsr_deployed["RO"].get("nsr_id")
3839 ro_delete_action = nsr_deployed["RO"].get("nsr_delete_action_id")
3840 try:
3841 if ro_nsr_id:
3842 stage[2] = "Deleting ns from VIM."
3843 db_nsr_update["detailed-status"] = " ".join(stage)
3844 self._write_op_status(nslcmop_id, stage)
3845 self.logger.debug(logging_text + stage[2])
3846 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3847 self._write_op_status(nslcmop_id, stage)
3848 desc = await self.RO.delete("ns", ro_nsr_id)
3849 ro_delete_action = desc["action_id"]
3850 db_nsr_update[
3851 "_admin.deployed.RO.nsr_delete_action_id"
3852 ] = ro_delete_action
3853 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
3854 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
3855 if ro_delete_action:
3856 # wait until NS is deleted from VIM
3857 stage[2] = "Waiting ns deleted from VIM."
3858 detailed_status_old = None
3859 self.logger.debug(
3860 logging_text
3861 + stage[2]
3862 + " RO_id={} ro_delete_action={}".format(
3863 ro_nsr_id, ro_delete_action
3864 )
3865 )
3866 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3867 self._write_op_status(nslcmop_id, stage)
3868
3869 delete_timeout = 20 * 60 # 20 minutes
3870 while delete_timeout > 0:
3871 desc = await self.RO.show(
3872 "ns",
3873 item_id_name=ro_nsr_id,
3874 extra_item="action",
3875 extra_item_id=ro_delete_action,
3876 )
3877
3878 # deploymentStatus
3879 self._on_update_ro_db(nsrs_id=nsr_id, ro_descriptor=desc)
3880
3881 ns_status, ns_status_info = self.RO.check_action_status(desc)
3882 if ns_status == "ERROR":
3883 raise ROclient.ROClientException(ns_status_info)
3884 elif ns_status == "BUILD":
3885 stage[2] = "Deleting from VIM {}".format(ns_status_info)
3886 elif ns_status == "ACTIVE":
3887 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
3888 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
3889 break
3890 else:
3891 assert (
3892 False
3893 ), "ROclient.check_action_status returns unknown {}".format(
3894 ns_status
3895 )
3896 if stage[2] != detailed_status_old:
3897 detailed_status_old = stage[2]
3898 db_nsr_update["detailed-status"] = " ".join(stage)
3899 self._write_op_status(nslcmop_id, stage)
3900 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3901 await asyncio.sleep(5, loop=self.loop)
3902 delete_timeout -= 5
3903 else: # delete_timeout <= 0:
3904 raise ROclient.ROClientException(
3905 "Timeout waiting ns deleted from VIM"
3906 )
3907
3908 except Exception as e:
3909 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3910 if (
3911 isinstance(e, ROclient.ROClientException) and e.http_code == 404
3912 ): # not found
3913 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
3914 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
3915 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
3916 self.logger.debug(
3917 logging_text + "RO_ns_id={} already deleted".format(ro_nsr_id)
3918 )
3919 elif (
3920 isinstance(e, ROclient.ROClientException) and e.http_code == 409
3921 ): # conflict
3922 failed_detail.append("delete conflict: {}".format(e))
3923 self.logger.debug(
3924 logging_text
3925 + "RO_ns_id={} delete conflict: {}".format(ro_nsr_id, e)
3926 )
3927 else:
3928 failed_detail.append("delete error: {}".format(e))
3929 self.logger.error(
3930 logging_text + "RO_ns_id={} delete error: {}".format(ro_nsr_id, e)
3931 )
3932
3933 # Delete nsd
3934 if not failed_detail and deep_get(nsr_deployed, ("RO", "nsd_id")):
3935 ro_nsd_id = nsr_deployed["RO"]["nsd_id"]
3936 try:
3937 stage[2] = "Deleting nsd from RO."
3938 db_nsr_update["detailed-status"] = " ".join(stage)
3939 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3940 self._write_op_status(nslcmop_id, stage)
3941 await self.RO.delete("nsd", ro_nsd_id)
3942 self.logger.debug(
3943 logging_text + "ro_nsd_id={} deleted".format(ro_nsd_id)
3944 )
3945 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
3946 except Exception as e:
3947 if (
3948 isinstance(e, ROclient.ROClientException) and e.http_code == 404
3949 ): # not found
3950 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
3951 self.logger.debug(
3952 logging_text + "ro_nsd_id={} already deleted".format(ro_nsd_id)
3953 )
3954 elif (
3955 isinstance(e, ROclient.ROClientException) and e.http_code == 409
3956 ): # conflict
3957 failed_detail.append(
3958 "ro_nsd_id={} delete conflict: {}".format(ro_nsd_id, e)
3959 )
3960 self.logger.debug(logging_text + failed_detail[-1])
3961 else:
3962 failed_detail.append(
3963 "ro_nsd_id={} delete error: {}".format(ro_nsd_id, e)
3964 )
3965 self.logger.error(logging_text + failed_detail[-1])
3966
3967 if not failed_detail and deep_get(nsr_deployed, ("RO", "vnfd")):
3968 for index, vnf_deployed in enumerate(nsr_deployed["RO"]["vnfd"]):
3969 if not vnf_deployed or not vnf_deployed["id"]:
3970 continue
3971 try:
3972 ro_vnfd_id = vnf_deployed["id"]
3973 stage[
3974 2
3975 ] = "Deleting member_vnf_index={} ro_vnfd_id={} from RO.".format(
3976 vnf_deployed["member-vnf-index"], ro_vnfd_id
3977 )
3978 db_nsr_update["detailed-status"] = " ".join(stage)
3979 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3980 self._write_op_status(nslcmop_id, stage)
3981 await self.RO.delete("vnfd", ro_vnfd_id)
3982 self.logger.debug(
3983 logging_text + "ro_vnfd_id={} deleted".format(ro_vnfd_id)
3984 )
3985 db_nsr_update["_admin.deployed.RO.vnfd.{}.id".format(index)] = None
3986 except Exception as e:
3987 if (
3988 isinstance(e, ROclient.ROClientException) and e.http_code == 404
3989 ): # not found
3990 db_nsr_update[
3991 "_admin.deployed.RO.vnfd.{}.id".format(index)
3992 ] = None
3993 self.logger.debug(
3994 logging_text
3995 + "ro_vnfd_id={} already deleted ".format(ro_vnfd_id)
3996 )
3997 elif (
3998 isinstance(e, ROclient.ROClientException) and e.http_code == 409
3999 ): # conflict
4000 failed_detail.append(
4001 "ro_vnfd_id={} delete conflict: {}".format(ro_vnfd_id, e)
4002 )
4003 self.logger.debug(logging_text + failed_detail[-1])
4004 else:
4005 failed_detail.append(
4006 "ro_vnfd_id={} delete error: {}".format(ro_vnfd_id, e)
4007 )
4008 self.logger.error(logging_text + failed_detail[-1])
4009
4010 if failed_detail:
4011 stage[2] = "Error deleting from VIM"
4012 else:
4013 stage[2] = "Deleted from VIM"
4014 db_nsr_update["detailed-status"] = " ".join(stage)
4015 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4016 self._write_op_status(nslcmop_id, stage)
4017
4018 if failed_detail:
4019 raise LcmException("; ".join(failed_detail))
4020
4021 async def terminate(self, nsr_id, nslcmop_id):
4022 # Try to lock HA task here
4023 task_is_locked_by_me = self.lcm_tasks.lock_HA("ns", "nslcmops", nslcmop_id)
4024 if not task_is_locked_by_me:
4025 return
4026
4027 logging_text = "Task ns={} terminate={} ".format(nsr_id, nslcmop_id)
4028 self.logger.debug(logging_text + "Enter")
4029 timeout_ns_terminate = self.timeout_ns_terminate
4030 db_nsr = None
4031 db_nslcmop = None
4032 operation_params = None
4033 exc = None
4034 error_list = [] # annotates all failed error messages
4035 db_nslcmop_update = {}
4036 autoremove = False # autoremove after terminated
4037 tasks_dict_info = {}
4038 db_nsr_update = {}
4039 stage = [
4040 "Stage 1/3: Preparing task.",
4041 "Waiting for previous operations to terminate.",
4042 "",
4043 ]
4044 # ^ contains [stage, step, VIM-status]
4045 try:
4046 # wait for any previous tasks in process
4047 await self.lcm_tasks.waitfor_related_HA("ns", "nslcmops", nslcmop_id)
4048
4049 stage[1] = "Getting nslcmop={} from db.".format(nslcmop_id)
4050 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
4051 operation_params = db_nslcmop.get("operationParams") or {}
4052 if operation_params.get("timeout_ns_terminate"):
4053 timeout_ns_terminate = operation_params["timeout_ns_terminate"]
4054 stage[1] = "Getting nsr={} from db.".format(nsr_id)
4055 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
4056
4057 db_nsr_update["operational-status"] = "terminating"
4058 db_nsr_update["config-status"] = "terminating"
4059 self._write_ns_status(
4060 nsr_id=nsr_id,
4061 ns_state="TERMINATING",
4062 current_operation="TERMINATING",
4063 current_operation_id=nslcmop_id,
4064 other_update=db_nsr_update,
4065 )
4066 self._write_op_status(op_id=nslcmop_id, queuePosition=0, stage=stage)
4067 nsr_deployed = deepcopy(db_nsr["_admin"].get("deployed")) or {}
4068 if db_nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
4069 return
4070
4071 stage[1] = "Getting vnf descriptors from db."
4072 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
4073 db_vnfrs_dict = {
4074 db_vnfr["member-vnf-index-ref"]: db_vnfr for db_vnfr in db_vnfrs_list
4075 }
4076 db_vnfds_from_id = {}
4077 db_vnfds_from_member_index = {}
4078 # Loop over VNFRs
4079 for vnfr in db_vnfrs_list:
4080 vnfd_id = vnfr["vnfd-id"]
4081 if vnfd_id not in db_vnfds_from_id:
4082 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
4083 db_vnfds_from_id[vnfd_id] = vnfd
4084 db_vnfds_from_member_index[
4085 vnfr["member-vnf-index-ref"]
4086 ] = db_vnfds_from_id[vnfd_id]
4087
4088 # Destroy individual execution environments when there are terminating primitives.
4089 # Rest of EE will be deleted at once
4090 # TODO - check before calling _destroy_N2VC
4091 # if not operation_params.get("skip_terminate_primitives"):#
4092 # or not vca.get("needed_terminate"):
4093 stage[0] = "Stage 2/3 execute terminating primitives."
4094 self.logger.debug(logging_text + stage[0])
4095 stage[1] = "Looking execution environment that needs terminate."
4096 self.logger.debug(logging_text + stage[1])
4097
4098 for vca_index, vca in enumerate(get_iterable(nsr_deployed, "VCA")):
4099 config_descriptor = None
4100 vca_member_vnf_index = vca.get("member-vnf-index")
4101 vca_id = self.get_vca_id(
4102 db_vnfrs_dict.get(vca_member_vnf_index)
4103 if vca_member_vnf_index
4104 else None,
4105 db_nsr,
4106 )
4107 if not vca or not vca.get("ee_id"):
4108 continue
4109 if not vca.get("member-vnf-index"):
4110 # ns
4111 config_descriptor = db_nsr.get("ns-configuration")
4112 elif vca.get("vdu_id"):
4113 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
4114 config_descriptor = get_configuration(db_vnfd, vca.get("vdu_id"))
4115 elif vca.get("kdu_name"):
4116 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
4117 config_descriptor = get_configuration(db_vnfd, vca.get("kdu_name"))
4118 else:
4119 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
4120 config_descriptor = get_configuration(db_vnfd, db_vnfd["id"])
4121 vca_type = vca.get("type")
4122 exec_terminate_primitives = not operation_params.get(
4123 "skip_terminate_primitives"
4124 ) and vca.get("needed_terminate")
4125 # For helm we must destroy_ee. Also for native_charm, as juju_model cannot be deleted if there are
4126 # pending native charms
4127 destroy_ee = (
4128 True if vca_type in ("helm", "helm-v3", "native_charm") else False
4129 )
4130 # self.logger.debug(logging_text + "vca_index: {}, ee_id: {}, vca_type: {} destroy_ee: {}".format(
4131 # vca_index, vca.get("ee_id"), vca_type, destroy_ee))
4132 task = asyncio.ensure_future(
4133 self.destroy_N2VC(
4134 logging_text,
4135 db_nslcmop,
4136 vca,
4137 config_descriptor,
4138 vca_index,
4139 destroy_ee,
4140 exec_terminate_primitives,
4141 vca_id=vca_id,
4142 )
4143 )
4144 tasks_dict_info[task] = "Terminating VCA {}".format(vca.get("ee_id"))
4145
4146 # wait for pending tasks of terminate primitives
4147 if tasks_dict_info:
4148 self.logger.debug(
4149 logging_text
4150 + "Waiting for tasks {}".format(list(tasks_dict_info.keys()))
4151 )
4152 error_list = await self._wait_for_tasks(
4153 logging_text,
4154 tasks_dict_info,
4155 min(self.timeout_charm_delete, timeout_ns_terminate),
4156 stage,
4157 nslcmop_id,
4158 )
4159 tasks_dict_info.clear()
4160 if error_list:
4161 return # raise LcmException("; ".join(error_list))
4162
4163 # remove All execution environments at once
4164 stage[0] = "Stage 3/3 delete all."
4165
4166 if nsr_deployed.get("VCA"):
4167 stage[1] = "Deleting all execution environments."
4168 self.logger.debug(logging_text + stage[1])
4169 vca_id = self.get_vca_id({}, db_nsr)
4170 task_delete_ee = asyncio.ensure_future(
4171 asyncio.wait_for(
4172 self._delete_all_N2VC(db_nsr=db_nsr, vca_id=vca_id),
4173 timeout=self.timeout_charm_delete,
4174 )
4175 )
4176 # task_delete_ee = asyncio.ensure_future(self.n2vc.delete_namespace(namespace="." + nsr_id))
4177 tasks_dict_info[task_delete_ee] = "Terminating all VCA"
4178
4179 # Delete from k8scluster
4180 stage[1] = "Deleting KDUs."
4181 self.logger.debug(logging_text + stage[1])
4182 # print(nsr_deployed)
4183 for kdu in get_iterable(nsr_deployed, "K8s"):
4184 if not kdu or not kdu.get("kdu-instance"):
4185 continue
4186 kdu_instance = kdu.get("kdu-instance")
4187 if kdu.get("k8scluster-type") in self.k8scluster_map:
4188 # TODO: Uninstall kdu instances taking into account they could be deployed in different VIMs
4189 vca_id = self.get_vca_id({}, db_nsr)
4190 task_delete_kdu_instance = asyncio.ensure_future(
4191 self.k8scluster_map[kdu["k8scluster-type"]].uninstall(
4192 cluster_uuid=kdu.get("k8scluster-uuid"),
4193 kdu_instance=kdu_instance,
4194 vca_id=vca_id,
4195 )
4196 )
4197 else:
4198 self.logger.error(
4199 logging_text
4200 + "Unknown k8s deployment type {}".format(
4201 kdu.get("k8scluster-type")
4202 )
4203 )
4204 continue
4205 tasks_dict_info[
4206 task_delete_kdu_instance
4207 ] = "Terminating KDU '{}'".format(kdu.get("kdu-name"))
4208
4209 # remove from RO
4210 stage[1] = "Deleting ns from VIM."
4211 if self.ng_ro:
4212 task_delete_ro = asyncio.ensure_future(
4213 self._terminate_ng_ro(
4214 logging_text, nsr_deployed, nsr_id, nslcmop_id, stage
4215 )
4216 )
4217 else:
4218 task_delete_ro = asyncio.ensure_future(
4219 self._terminate_RO(
4220 logging_text, nsr_deployed, nsr_id, nslcmop_id, stage
4221 )
4222 )
4223 tasks_dict_info[task_delete_ro] = "Removing deployment from VIM"
4224
4225 # rest of staff will be done at finally
4226
4227 except (
4228 ROclient.ROClientException,
4229 DbException,
4230 LcmException,
4231 N2VCException,
4232 ) as e:
4233 self.logger.error(logging_text + "Exit Exception {}".format(e))
4234 exc = e
4235 except asyncio.CancelledError:
4236 self.logger.error(
4237 logging_text + "Cancelled Exception while '{}'".format(stage[1])
4238 )
4239 exc = "Operation was cancelled"
4240 except Exception as e:
4241 exc = traceback.format_exc()
4242 self.logger.critical(
4243 logging_text + "Exit Exception while '{}': {}".format(stage[1], e),
4244 exc_info=True,
4245 )
4246 finally:
4247 if exc:
4248 error_list.append(str(exc))
4249 try:
4250 # wait for pending tasks
4251 if tasks_dict_info:
4252 stage[1] = "Waiting for terminate pending tasks."
4253 self.logger.debug(logging_text + stage[1])
4254 error_list += await self._wait_for_tasks(
4255 logging_text,
4256 tasks_dict_info,
4257 timeout_ns_terminate,
4258 stage,
4259 nslcmop_id,
4260 )
4261 stage[1] = stage[2] = ""
4262 except asyncio.CancelledError:
4263 error_list.append("Cancelled")
4264 # TODO cancell all tasks
4265 except Exception as exc:
4266 error_list.append(str(exc))
4267 # update status at database
4268 if error_list:
4269 error_detail = "; ".join(error_list)
4270 # self.logger.error(logging_text + error_detail)
4271 error_description_nslcmop = "{} Detail: {}".format(
4272 stage[0], error_detail
4273 )
4274 error_description_nsr = "Operation: TERMINATING.{}, {}.".format(
4275 nslcmop_id, stage[0]
4276 )
4277
4278 db_nsr_update["operational-status"] = "failed"
4279 db_nsr_update["detailed-status"] = (
4280 error_description_nsr + " Detail: " + error_detail
4281 )
4282 db_nslcmop_update["detailed-status"] = error_detail
4283 nslcmop_operation_state = "FAILED"
4284 ns_state = "BROKEN"
4285 else:
4286 error_detail = None
4287 error_description_nsr = error_description_nslcmop = None
4288 ns_state = "NOT_INSTANTIATED"
4289 db_nsr_update["operational-status"] = "terminated"
4290 db_nsr_update["detailed-status"] = "Done"
4291 db_nsr_update["_admin.nsState"] = "NOT_INSTANTIATED"
4292 db_nslcmop_update["detailed-status"] = "Done"
4293 nslcmop_operation_state = "COMPLETED"
4294
4295 if db_nsr:
4296 self._write_ns_status(
4297 nsr_id=nsr_id,
4298 ns_state=ns_state,
4299 current_operation="IDLE",
4300 current_operation_id=None,
4301 error_description=error_description_nsr,
4302 error_detail=error_detail,
4303 other_update=db_nsr_update,
4304 )
4305 self._write_op_status(
4306 op_id=nslcmop_id,
4307 stage="",
4308 error_message=error_description_nslcmop,
4309 operation_state=nslcmop_operation_state,
4310 other_update=db_nslcmop_update,
4311 )
4312 if ns_state == "NOT_INSTANTIATED":
4313 try:
4314 self.db.set_list(
4315 "vnfrs",
4316 {"nsr-id-ref": nsr_id},
4317 {"_admin.nsState": "NOT_INSTANTIATED"},
4318 )
4319 except DbException as e:
4320 self.logger.warn(
4321 logging_text
4322 + "Error writing VNFR status for nsr-id-ref: {} -> {}".format(
4323 nsr_id, e
4324 )
4325 )
4326 if operation_params:
4327 autoremove = operation_params.get("autoremove", False)
4328 if nslcmop_operation_state:
4329 try:
4330 await self.msg.aiowrite(
4331 "ns",
4332 "terminated",
4333 {
4334 "nsr_id": nsr_id,
4335 "nslcmop_id": nslcmop_id,
4336 "operationState": nslcmop_operation_state,
4337 "autoremove": autoremove,
4338 },
4339 loop=self.loop,
4340 )
4341 except Exception as e:
4342 self.logger.error(
4343 logging_text + "kafka_write notification Exception {}".format(e)
4344 )
4345
4346 self.logger.debug(logging_text + "Exit")
4347 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_terminate")
4348
4349 async def _wait_for_tasks(
4350 self, logging_text, created_tasks_info, timeout, stage, nslcmop_id, nsr_id=None
4351 ):
4352 time_start = time()
4353 error_detail_list = []
4354 error_list = []
4355 pending_tasks = list(created_tasks_info.keys())
4356 num_tasks = len(pending_tasks)
4357 num_done = 0
4358 stage[1] = "{}/{}.".format(num_done, num_tasks)
4359 self._write_op_status(nslcmop_id, stage)
4360 while pending_tasks:
4361 new_error = None
4362 _timeout = timeout + time_start - time()
4363 done, pending_tasks = await asyncio.wait(
4364 pending_tasks, timeout=_timeout, return_when=asyncio.FIRST_COMPLETED
4365 )
4366 num_done += len(done)
4367 if not done: # Timeout
4368 for task in pending_tasks:
4369 new_error = created_tasks_info[task] + ": Timeout"
4370 error_detail_list.append(new_error)
4371 error_list.append(new_error)
4372 break
4373 for task in done:
4374 if task.cancelled():
4375 exc = "Cancelled"
4376 else:
4377 exc = task.exception()
4378 if exc:
4379 if isinstance(exc, asyncio.TimeoutError):
4380 exc = "Timeout"
4381 new_error = created_tasks_info[task] + ": {}".format(exc)
4382 error_list.append(created_tasks_info[task])
4383 error_detail_list.append(new_error)
4384 if isinstance(
4385 exc,
4386 (
4387 str,
4388 DbException,
4389 N2VCException,
4390 ROclient.ROClientException,
4391 LcmException,
4392 K8sException,
4393 NgRoException,
4394 ),
4395 ):
4396 self.logger.error(logging_text + new_error)
4397 else:
4398 exc_traceback = "".join(
4399 traceback.format_exception(None, exc, exc.__traceback__)
4400 )
4401 self.logger.error(
4402 logging_text
4403 + created_tasks_info[task]
4404 + " "
4405 + exc_traceback
4406 )
4407 else:
4408 self.logger.debug(
4409 logging_text + created_tasks_info[task] + ": Done"
4410 )
4411 stage[1] = "{}/{}.".format(num_done, num_tasks)
4412 if new_error:
4413 stage[1] += " Errors: " + ". ".join(error_detail_list) + "."
4414 if nsr_id: # update also nsr
4415 self.update_db_2(
4416 "nsrs",
4417 nsr_id,
4418 {
4419 "errorDescription": "Error at: " + ", ".join(error_list),
4420 "errorDetail": ". ".join(error_detail_list),
4421 },
4422 )
4423 self._write_op_status(nslcmop_id, stage)
4424 return error_detail_list
4425
4426 @staticmethod
4427 def _map_primitive_params(primitive_desc, params, instantiation_params):
4428 """
4429 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
4430 The default-value is used. If it is between < > it look for a value at instantiation_params
4431 :param primitive_desc: portion of VNFD/NSD that describes primitive
4432 :param params: Params provided by user
4433 :param instantiation_params: Instantiation params provided by user
4434 :return: a dictionary with the calculated params
4435 """
4436 calculated_params = {}
4437 for parameter in primitive_desc.get("parameter", ()):
4438 param_name = parameter["name"]
4439 if param_name in params:
4440 calculated_params[param_name] = params[param_name]
4441 elif "default-value" in parameter or "value" in parameter:
4442 if "value" in parameter:
4443 calculated_params[param_name] = parameter["value"]
4444 else:
4445 calculated_params[param_name] = parameter["default-value"]
4446 if (
4447 isinstance(calculated_params[param_name], str)
4448 and calculated_params[param_name].startswith("<")
4449 and calculated_params[param_name].endswith(">")
4450 ):
4451 if calculated_params[param_name][1:-1] in instantiation_params:
4452 calculated_params[param_name] = instantiation_params[
4453 calculated_params[param_name][1:-1]
4454 ]
4455 else:
4456 raise LcmException(
4457 "Parameter {} needed to execute primitive {} not provided".format(
4458 calculated_params[param_name], primitive_desc["name"]
4459 )
4460 )
4461 else:
4462 raise LcmException(
4463 "Parameter {} needed to execute primitive {} not provided".format(
4464 param_name, primitive_desc["name"]
4465 )
4466 )
4467
4468 if isinstance(calculated_params[param_name], (dict, list, tuple)):
4469 calculated_params[param_name] = yaml.safe_dump(
4470 calculated_params[param_name], default_flow_style=True, width=256
4471 )
4472 elif isinstance(calculated_params[param_name], str) and calculated_params[
4473 param_name
4474 ].startswith("!!yaml "):
4475 calculated_params[param_name] = calculated_params[param_name][7:]
4476 if parameter.get("data-type") == "INTEGER":
4477 try:
4478 calculated_params[param_name] = int(calculated_params[param_name])
4479 except ValueError: # error converting string to int
4480 raise LcmException(
4481 "Parameter {} of primitive {} must be integer".format(
4482 param_name, primitive_desc["name"]
4483 )
4484 )
4485 elif parameter.get("data-type") == "BOOLEAN":
4486 calculated_params[param_name] = not (
4487 (str(calculated_params[param_name])).lower() == "false"
4488 )
4489
4490 # add always ns_config_info if primitive name is config
4491 if primitive_desc["name"] == "config":
4492 if "ns_config_info" in instantiation_params:
4493 calculated_params["ns_config_info"] = instantiation_params[
4494 "ns_config_info"
4495 ]
4496 return calculated_params
4497
4498 def _look_for_deployed_vca(
4499 self,
4500 deployed_vca,
4501 member_vnf_index,
4502 vdu_id,
4503 vdu_count_index,
4504 kdu_name=None,
4505 ee_descriptor_id=None,
4506 ):
4507 # find vca_deployed record for this action. Raise LcmException if not found or there is not any id.
4508 for vca in deployed_vca:
4509 if not vca:
4510 continue
4511 if member_vnf_index != vca["member-vnf-index"] or vdu_id != vca["vdu_id"]:
4512 continue
4513 if (
4514 vdu_count_index is not None
4515 and vdu_count_index != vca["vdu_count_index"]
4516 ):
4517 continue
4518 if kdu_name and kdu_name != vca["kdu_name"]:
4519 continue
4520 if ee_descriptor_id and ee_descriptor_id != vca["ee_descriptor_id"]:
4521 continue
4522 break
4523 else:
4524 # vca_deployed not found
4525 raise LcmException(
4526 "charm for member_vnf_index={} vdu_id={}.{} kdu_name={} execution-environment-list.id={}"
4527 " is not deployed".format(
4528 member_vnf_index,
4529 vdu_id,
4530 vdu_count_index,
4531 kdu_name,
4532 ee_descriptor_id,
4533 )
4534 )
4535 # get ee_id
4536 ee_id = vca.get("ee_id")
4537 vca_type = vca.get(
4538 "type", "lxc_proxy_charm"
4539 ) # default value for backward compatibility - proxy charm
4540 if not ee_id:
4541 raise LcmException(
4542 "charm for member_vnf_index={} vdu_id={} kdu_name={} vdu_count_index={} has not "
4543 "execution environment".format(
4544 member_vnf_index, vdu_id, kdu_name, vdu_count_index
4545 )
4546 )
4547 return ee_id, vca_type
4548
4549 async def _ns_execute_primitive(
4550 self,
4551 ee_id,
4552 primitive,
4553 primitive_params,
4554 retries=0,
4555 retries_interval=30,
4556 timeout=None,
4557 vca_type=None,
4558 db_dict=None,
4559 vca_id: str = None,
4560 ) -> (str, str):
4561 try:
4562 if primitive == "config":
4563 primitive_params = {"params": primitive_params}
4564
4565 vca_type = vca_type or "lxc_proxy_charm"
4566
4567 while retries >= 0:
4568 try:
4569 output = await asyncio.wait_for(
4570 self.vca_map[vca_type].exec_primitive(
4571 ee_id=ee_id,
4572 primitive_name=primitive,
4573 params_dict=primitive_params,
4574 progress_timeout=self.timeout_progress_primitive,
4575 total_timeout=self.timeout_primitive,
4576 db_dict=db_dict,
4577 vca_id=vca_id,
4578 vca_type=vca_type,
4579 ),
4580 timeout=timeout or self.timeout_primitive,
4581 )
4582 # execution was OK
4583 break
4584 except asyncio.CancelledError:
4585 raise
4586 except Exception as e: # asyncio.TimeoutError
4587 if isinstance(e, asyncio.TimeoutError):
4588 e = "Timeout"
4589 retries -= 1
4590 if retries >= 0:
4591 self.logger.debug(
4592 "Error executing action {} on {} -> {}".format(
4593 primitive, ee_id, e
4594 )
4595 )
4596 # wait and retry
4597 await asyncio.sleep(retries_interval, loop=self.loop)
4598 else:
4599 return "FAILED", str(e)
4600
4601 return "COMPLETED", output
4602
4603 except (LcmException, asyncio.CancelledError):
4604 raise
4605 except Exception as e:
4606 return "FAIL", "Error executing action {}: {}".format(primitive, e)
4607
4608 async def vca_status_refresh(self, nsr_id, nslcmop_id):
4609 """
4610 Updating the vca_status with latest juju information in nsrs record
4611 :param: nsr_id: Id of the nsr
4612 :param: nslcmop_id: Id of the nslcmop
4613 :return: None
4614 """
4615
4616 self.logger.debug("Task ns={} action={} Enter".format(nsr_id, nslcmop_id))
4617 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
4618 vca_id = self.get_vca_id({}, db_nsr)
4619 if db_nsr["_admin"]["deployed"]["K8s"]:
4620 for k8s_index, k8s in enumerate(db_nsr["_admin"]["deployed"]["K8s"]):
4621 cluster_uuid, kdu_instance = k8s["k8scluster-uuid"], k8s["kdu-instance"]
4622 await self._on_update_k8s_db(
4623 cluster_uuid, kdu_instance, filter={"_id": nsr_id}, vca_id=vca_id
4624 )
4625 else:
4626 for vca_index, _ in enumerate(db_nsr["_admin"]["deployed"]["VCA"]):
4627 table, filter = "nsrs", {"_id": nsr_id}
4628 path = "_admin.deployed.VCA.{}.".format(vca_index)
4629 await self._on_update_n2vc_db(table, filter, path, {})
4630
4631 self.logger.debug("Task ns={} action={} Exit".format(nsr_id, nslcmop_id))
4632 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_vca_status_refresh")
4633
4634 async def action(self, nsr_id, nslcmop_id):
4635 # Try to lock HA task here
4636 task_is_locked_by_me = self.lcm_tasks.lock_HA("ns", "nslcmops", nslcmop_id)
4637 if not task_is_locked_by_me:
4638 return
4639
4640 logging_text = "Task ns={} action={} ".format(nsr_id, nslcmop_id)
4641 self.logger.debug(logging_text + "Enter")
4642 # get all needed from database
4643 db_nsr = None
4644 db_nslcmop = None
4645 db_nsr_update = {}
4646 db_nslcmop_update = {}
4647 nslcmop_operation_state = None
4648 error_description_nslcmop = None
4649 exc = None
4650 try:
4651 # wait for any previous tasks in process
4652 step = "Waiting for previous operations to terminate"
4653 await self.lcm_tasks.waitfor_related_HA("ns", "nslcmops", nslcmop_id)
4654
4655 self._write_ns_status(
4656 nsr_id=nsr_id,
4657 ns_state=None,
4658 current_operation="RUNNING ACTION",
4659 current_operation_id=nslcmop_id,
4660 )
4661
4662 step = "Getting information from database"
4663 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
4664 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
4665 if db_nslcmop["operationParams"].get("primitive_params"):
4666 db_nslcmop["operationParams"]["primitive_params"] = json.loads(
4667 db_nslcmop["operationParams"]["primitive_params"]
4668 )
4669
4670 nsr_deployed = db_nsr["_admin"].get("deployed")
4671 vnf_index = db_nslcmop["operationParams"].get("member_vnf_index")
4672 vdu_id = db_nslcmop["operationParams"].get("vdu_id")
4673 kdu_name = db_nslcmop["operationParams"].get("kdu_name")
4674 vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
4675 primitive = db_nslcmop["operationParams"]["primitive"]
4676 primitive_params = db_nslcmop["operationParams"]["primitive_params"]
4677 timeout_ns_action = db_nslcmop["operationParams"].get(
4678 "timeout_ns_action", self.timeout_primitive
4679 )
4680
4681 if vnf_index:
4682 step = "Getting vnfr from database"
4683 db_vnfr = self.db.get_one(
4684 "vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id}
4685 )
4686 if db_vnfr.get("kdur"):
4687 kdur_list = []
4688 for kdur in db_vnfr["kdur"]:
4689 if kdur.get("additionalParams"):
4690 kdur["additionalParams"] = json.loads(kdur["additionalParams"])
4691 kdur_list.append(kdur)
4692 db_vnfr["kdur"] = kdur_list
4693 step = "Getting vnfd from database"
4694 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
4695 else:
4696 step = "Getting nsd from database"
4697 db_nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
4698
4699 vca_id = self.get_vca_id(db_vnfr, db_nsr)
4700 # for backward compatibility
4701 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
4702 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
4703 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
4704 self.update_db_2("nsrs", nsr_id, db_nsr_update)
4705
4706 # look for primitive
4707 config_primitive_desc = descriptor_configuration = None
4708 if vdu_id:
4709 descriptor_configuration = get_configuration(db_vnfd, vdu_id)
4710 elif kdu_name:
4711 descriptor_configuration = get_configuration(db_vnfd, kdu_name)
4712 elif vnf_index:
4713 descriptor_configuration = get_configuration(db_vnfd, db_vnfd["id"])
4714 else:
4715 descriptor_configuration = db_nsd.get("ns-configuration")
4716
4717 if descriptor_configuration and descriptor_configuration.get(
4718 "config-primitive"
4719 ):
4720 for config_primitive in descriptor_configuration["config-primitive"]:
4721 if config_primitive["name"] == primitive:
4722 config_primitive_desc = config_primitive
4723 break
4724
4725 if not config_primitive_desc:
4726 if not (kdu_name and primitive in ("upgrade", "rollback", "status")):
4727 raise LcmException(
4728 "Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".format(
4729 primitive
4730 )
4731 )
4732 primitive_name = primitive
4733 ee_descriptor_id = None
4734 else:
4735 primitive_name = config_primitive_desc.get(
4736 "execution-environment-primitive", primitive
4737 )
4738 ee_descriptor_id = config_primitive_desc.get(
4739 "execution-environment-ref"
4740 )
4741
4742 if vnf_index:
4743 if vdu_id:
4744 vdur = next(
4745 (x for x in db_vnfr["vdur"] if x["vdu-id-ref"] == vdu_id), None
4746 )
4747 desc_params = parse_yaml_strings(vdur.get("additionalParams"))
4748 elif kdu_name:
4749 kdur = next(
4750 (x for x in db_vnfr["kdur"] if x["kdu-name"] == kdu_name), None
4751 )
4752 desc_params = parse_yaml_strings(kdur.get("additionalParams"))
4753 else:
4754 desc_params = parse_yaml_strings(
4755 db_vnfr.get("additionalParamsForVnf")
4756 )
4757 else:
4758 desc_params = parse_yaml_strings(db_nsr.get("additionalParamsForNs"))
4759 if kdu_name and get_configuration(db_vnfd, kdu_name):
4760 kdu_configuration = get_configuration(db_vnfd, kdu_name)
4761 actions = set()
4762 for primitive in kdu_configuration.get("initial-config-primitive", []):
4763 actions.add(primitive["name"])
4764 for primitive in kdu_configuration.get("config-primitive", []):
4765 actions.add(primitive["name"])
4766 kdu_action = True if primitive_name in actions else False
4767
4768 # TODO check if ns is in a proper status
4769 if kdu_name and (
4770 primitive_name in ("upgrade", "rollback", "status") or kdu_action
4771 ):
4772 # kdur and desc_params already set from before
4773 if primitive_params:
4774 desc_params.update(primitive_params)
4775 # TODO Check if we will need something at vnf level
4776 for index, kdu in enumerate(get_iterable(nsr_deployed, "K8s")):
4777 if (
4778 kdu_name == kdu["kdu-name"]
4779 and kdu["member-vnf-index"] == vnf_index
4780 ):
4781 break
4782 else:
4783 raise LcmException(
4784 "KDU '{}' for vnf '{}' not deployed".format(kdu_name, vnf_index)
4785 )
4786
4787 if kdu.get("k8scluster-type") not in self.k8scluster_map:
4788 msg = "unknown k8scluster-type '{}'".format(
4789 kdu.get("k8scluster-type")
4790 )
4791 raise LcmException(msg)
4792
4793 db_dict = {
4794 "collection": "nsrs",
4795 "filter": {"_id": nsr_id},
4796 "path": "_admin.deployed.K8s.{}".format(index),
4797 }
4798 self.logger.debug(
4799 logging_text
4800 + "Exec k8s {} on {}.{}".format(primitive_name, vnf_index, kdu_name)
4801 )
4802 step = "Executing kdu {}".format(primitive_name)
4803 if primitive_name == "upgrade":
4804 if desc_params.get("kdu_model"):
4805 kdu_model = desc_params.get("kdu_model")
4806 del desc_params["kdu_model"]
4807 else:
4808 kdu_model = kdu.get("kdu-model")
4809 parts = kdu_model.split(sep=":")
4810 if len(parts) == 2:
4811 kdu_model = parts[0]
4812
4813 detailed_status = await asyncio.wait_for(
4814 self.k8scluster_map[kdu["k8scluster-type"]].upgrade(
4815 cluster_uuid=kdu.get("k8scluster-uuid"),
4816 kdu_instance=kdu.get("kdu-instance"),
4817 atomic=True,
4818 kdu_model=kdu_model,
4819 params=desc_params,
4820 db_dict=db_dict,
4821 timeout=timeout_ns_action,
4822 ),
4823 timeout=timeout_ns_action + 10,
4824 )
4825 self.logger.debug(
4826 logging_text + " Upgrade of kdu {} done".format(detailed_status)
4827 )
4828 elif primitive_name == "rollback":
4829 detailed_status = await asyncio.wait_for(
4830 self.k8scluster_map[kdu["k8scluster-type"]].rollback(
4831 cluster_uuid=kdu.get("k8scluster-uuid"),
4832 kdu_instance=kdu.get("kdu-instance"),
4833 db_dict=db_dict,
4834 ),
4835 timeout=timeout_ns_action,
4836 )
4837 elif primitive_name == "status":
4838 detailed_status = await asyncio.wait_for(
4839 self.k8scluster_map[kdu["k8scluster-type"]].status_kdu(
4840 cluster_uuid=kdu.get("k8scluster-uuid"),
4841 kdu_instance=kdu.get("kdu-instance"),
4842 vca_id=vca_id,
4843 ),
4844 timeout=timeout_ns_action,
4845 )
4846 else:
4847 kdu_instance = kdu.get("kdu-instance") or "{}-{}".format(
4848 kdu["kdu-name"], nsr_id
4849 )
4850 params = self._map_primitive_params(
4851 config_primitive_desc, primitive_params, desc_params
4852 )
4853
4854 detailed_status = await asyncio.wait_for(
4855 self.k8scluster_map[kdu["k8scluster-type"]].exec_primitive(
4856 cluster_uuid=kdu.get("k8scluster-uuid"),
4857 kdu_instance=kdu_instance,
4858 primitive_name=primitive_name,
4859 params=params,
4860 db_dict=db_dict,
4861 timeout=timeout_ns_action,
4862 vca_id=vca_id,
4863 ),
4864 timeout=timeout_ns_action,
4865 )
4866
4867 if detailed_status:
4868 nslcmop_operation_state = "COMPLETED"
4869 else:
4870 detailed_status = ""
4871 nslcmop_operation_state = "FAILED"
4872 else:
4873 ee_id, vca_type = self._look_for_deployed_vca(
4874 nsr_deployed["VCA"],
4875 member_vnf_index=vnf_index,
4876 vdu_id=vdu_id,
4877 vdu_count_index=vdu_count_index,
4878 ee_descriptor_id=ee_descriptor_id,
4879 )
4880 for vca_index, vca_deployed in enumerate(
4881 db_nsr["_admin"]["deployed"]["VCA"]
4882 ):
4883 if vca_deployed.get("member-vnf-index") == vnf_index:
4884 db_dict = {
4885 "collection": "nsrs",
4886 "filter": {"_id": nsr_id},
4887 "path": "_admin.deployed.VCA.{}.".format(vca_index),
4888 }
4889 break
4890 (
4891 nslcmop_operation_state,
4892 detailed_status,
4893 ) = await self._ns_execute_primitive(
4894 ee_id,
4895 primitive=primitive_name,
4896 primitive_params=self._map_primitive_params(
4897 config_primitive_desc, primitive_params, desc_params
4898 ),
4899 timeout=timeout_ns_action,
4900 vca_type=vca_type,
4901 db_dict=db_dict,
4902 vca_id=vca_id,
4903 )
4904
4905 db_nslcmop_update["detailed-status"] = detailed_status
4906 error_description_nslcmop = (
4907 detailed_status if nslcmop_operation_state == "FAILED" else ""
4908 )
4909 self.logger.debug(
4910 logging_text
4911 + " task Done with result {} {}".format(
4912 nslcmop_operation_state, detailed_status
4913 )
4914 )
4915 return # database update is called inside finally
4916
4917 except (DbException, LcmException, N2VCException, K8sException) as e:
4918 self.logger.error(logging_text + "Exit Exception {}".format(e))
4919 exc = e
4920 except asyncio.CancelledError:
4921 self.logger.error(
4922 logging_text + "Cancelled Exception while '{}'".format(step)
4923 )
4924 exc = "Operation was cancelled"
4925 except asyncio.TimeoutError:
4926 self.logger.error(logging_text + "Timeout while '{}'".format(step))
4927 exc = "Timeout"
4928 except Exception as e:
4929 exc = traceback.format_exc()
4930 self.logger.critical(
4931 logging_text + "Exit Exception {} {}".format(type(e).__name__, e),
4932 exc_info=True,
4933 )
4934 finally:
4935 if exc:
4936 db_nslcmop_update[
4937 "detailed-status"
4938 ] = (
4939 detailed_status
4940 ) = error_description_nslcmop = "FAILED {}: {}".format(step, exc)
4941 nslcmop_operation_state = "FAILED"
4942 if db_nsr:
4943 self._write_ns_status(
4944 nsr_id=nsr_id,
4945 ns_state=db_nsr[
4946 "nsState"
4947 ], # TODO check if degraded. For the moment use previous status
4948 current_operation="IDLE",
4949 current_operation_id=None,
4950 # error_description=error_description_nsr,
4951 # error_detail=error_detail,
4952 other_update=db_nsr_update,
4953 )
4954
4955 self._write_op_status(
4956 op_id=nslcmop_id,
4957 stage="",
4958 error_message=error_description_nslcmop,
4959 operation_state=nslcmop_operation_state,
4960 other_update=db_nslcmop_update,
4961 )
4962
4963 if nslcmop_operation_state:
4964 try:
4965 await self.msg.aiowrite(
4966 "ns",
4967 "actioned",
4968 {
4969 "nsr_id": nsr_id,
4970 "nslcmop_id": nslcmop_id,
4971 "operationState": nslcmop_operation_state,
4972 },
4973 loop=self.loop,
4974 )
4975 except Exception as e:
4976 self.logger.error(
4977 logging_text + "kafka_write notification Exception {}".format(e)
4978 )
4979 self.logger.debug(logging_text + "Exit")
4980 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_action")
4981 return nslcmop_operation_state, detailed_status
4982
4983 async def scale(self, nsr_id, nslcmop_id):
4984 # Try to lock HA task here
4985 task_is_locked_by_me = self.lcm_tasks.lock_HA("ns", "nslcmops", nslcmop_id)
4986 if not task_is_locked_by_me:
4987 return
4988
4989 logging_text = "Task ns={} scale={} ".format(nsr_id, nslcmop_id)
4990 stage = ["", "", ""]
4991 tasks_dict_info = {}
4992 # ^ stage, step, VIM progress
4993 self.logger.debug(logging_text + "Enter")
4994 # get all needed from database
4995 db_nsr = None
4996 db_nslcmop_update = {}
4997 db_nsr_update = {}
4998 exc = None
4999 # in case of error, indicates what part of scale was failed to put nsr at error status
5000 scale_process = None
5001 old_operational_status = ""
5002 old_config_status = ""
5003 nsi_id = None
5004 try:
5005 # wait for any previous tasks in process
5006 step = "Waiting for previous operations to terminate"
5007 await self.lcm_tasks.waitfor_related_HA("ns", "nslcmops", nslcmop_id)
5008 self._write_ns_status(
5009 nsr_id=nsr_id,
5010 ns_state=None,
5011 current_operation="SCALING",
5012 current_operation_id=nslcmop_id,
5013 )
5014
5015 step = "Getting nslcmop from database"
5016 self.logger.debug(
5017 step + " after having waited for previous tasks to be completed"
5018 )
5019 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
5020
5021 step = "Getting nsr from database"
5022 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
5023 old_operational_status = db_nsr["operational-status"]
5024 old_config_status = db_nsr["config-status"]
5025
5026 step = "Parsing scaling parameters"
5027 db_nsr_update["operational-status"] = "scaling"
5028 self.update_db_2("nsrs", nsr_id, db_nsr_update)
5029 nsr_deployed = db_nsr["_admin"].get("deployed")
5030
5031 vnf_index = db_nslcmop["operationParams"]["scaleVnfData"][
5032 "scaleByStepData"
5033 ]["member-vnf-index"]
5034 scaling_group = db_nslcmop["operationParams"]["scaleVnfData"][
5035 "scaleByStepData"
5036 ]["scaling-group-descriptor"]
5037 scaling_type = db_nslcmop["operationParams"]["scaleVnfData"]["scaleVnfType"]
5038 # for backward compatibility
5039 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
5040 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
5041 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
5042 self.update_db_2("nsrs", nsr_id, db_nsr_update)
5043
5044 step = "Getting vnfr from database"
5045 db_vnfr = self.db.get_one(
5046 "vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id}
5047 )
5048
5049 vca_id = self.get_vca_id(db_vnfr, db_nsr)
5050
5051 step = "Getting vnfd from database"
5052 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
5053
5054 base_folder = db_vnfd["_admin"]["storage"]
5055
5056 step = "Getting scaling-group-descriptor"
5057 scaling_descriptor = find_in_list(
5058 get_scaling_aspect(db_vnfd),
5059 lambda scale_desc: scale_desc["name"] == scaling_group,
5060 )
5061 if not scaling_descriptor:
5062 raise LcmException(
5063 "input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
5064 "at vnfd:scaling-group-descriptor".format(scaling_group)
5065 )
5066
5067 step = "Sending scale order to VIM"
5068 # TODO check if ns is in a proper status
5069 nb_scale_op = 0
5070 if not db_nsr["_admin"].get("scaling-group"):
5071 self.update_db_2(
5072 "nsrs",
5073 nsr_id,
5074 {
5075 "_admin.scaling-group": [
5076 {"name": scaling_group, "nb-scale-op": 0}
5077 ]
5078 },
5079 )
5080 admin_scale_index = 0
5081 else:
5082 for admin_scale_index, admin_scale_info in enumerate(
5083 db_nsr["_admin"]["scaling-group"]
5084 ):
5085 if admin_scale_info["name"] == scaling_group:
5086 nb_scale_op = admin_scale_info.get("nb-scale-op", 0)
5087 break
5088 else: # not found, set index one plus last element and add new entry with the name
5089 admin_scale_index += 1
5090 db_nsr_update[
5091 "_admin.scaling-group.{}.name".format(admin_scale_index)
5092 ] = scaling_group
5093
5094 vca_scaling_info = []
5095 scaling_info = {"scaling_group_name": scaling_group, "vdu": [], "kdu": []}
5096 if scaling_type == "SCALE_OUT":
5097 if "aspect-delta-details" not in scaling_descriptor:
5098 raise LcmException(
5099 "Aspect delta details not fount in scaling descriptor {}".format(
5100 scaling_descriptor["name"]
5101 )
5102 )
5103 # count if max-instance-count is reached
5104 deltas = scaling_descriptor.get("aspect-delta-details")["deltas"]
5105
5106 scaling_info["scaling_direction"] = "OUT"
5107 scaling_info["vdu-create"] = {}
5108 scaling_info["kdu-create"] = {}
5109 for delta in deltas:
5110 for vdu_delta in delta.get("vdu-delta", {}):
5111 vdud = get_vdu(db_vnfd, vdu_delta["id"])
5112 # vdu_index also provides the number of instance of the targeted vdu
5113 vdu_count = vdu_index = get_vdur_index(db_vnfr, vdu_delta)
5114 cloud_init_text = self._get_vdu_cloud_init_content(
5115 vdud, db_vnfd
5116 )
5117 if cloud_init_text:
5118 additional_params = (
5119 self._get_vdu_additional_params(db_vnfr, vdud["id"])
5120 or {}
5121 )
5122 cloud_init_list = []
5123
5124 vdu_profile = get_vdu_profile(db_vnfd, vdu_delta["id"])
5125 max_instance_count = 10
5126 if vdu_profile and "max-number-of-instances" in vdu_profile:
5127 max_instance_count = vdu_profile.get(
5128 "max-number-of-instances", 10
5129 )
5130
5131 default_instance_num = get_number_of_instances(
5132 db_vnfd, vdud["id"]
5133 )
5134 instances_number = vdu_delta.get("number-of-instances", 1)
5135 nb_scale_op += instances_number
5136
5137 new_instance_count = nb_scale_op + default_instance_num
5138 # Control if new count is over max and vdu count is less than max.
5139 # Then assign new instance count
5140 if new_instance_count > max_instance_count > vdu_count:
5141 instances_number = new_instance_count - max_instance_count
5142 else:
5143 instances_number = instances_number
5144
5145 if new_instance_count > max_instance_count:
5146 raise LcmException(
5147 "reached the limit of {} (max-instance-count) "
5148 "scaling-out operations for the "
5149 "scaling-group-descriptor '{}'".format(
5150 nb_scale_op, scaling_group
5151 )
5152 )
5153 for x in range(vdu_delta.get("number-of-instances", 1)):
5154 if cloud_init_text:
5155 # TODO Information of its own ip is not available because db_vnfr is not updated.
5156 additional_params["OSM"] = get_osm_params(
5157 db_vnfr, vdu_delta["id"], vdu_index + x
5158 )
5159 cloud_init_list.append(
5160 self._parse_cloud_init(
5161 cloud_init_text,
5162 additional_params,
5163 db_vnfd["id"],
5164 vdud["id"],
5165 )
5166 )
5167 vca_scaling_info.append(
5168 {
5169 "osm_vdu_id": vdu_delta["id"],
5170 "member-vnf-index": vnf_index,
5171 "type": "create",
5172 "vdu_index": vdu_index + x,
5173 }
5174 )
5175 scaling_info["vdu-create"][vdu_delta["id"]] = instances_number
5176 for kdu_delta in delta.get("kdu-resource-delta", {}):
5177 kdu_profile = get_kdu_profile(db_vnfd, kdu_delta["id"])
5178 kdu_name = kdu_profile["kdu-name"]
5179 resource_name = kdu_profile["resource-name"]
5180
5181 # Might have different kdus in the same delta
5182 # Should have list for each kdu
5183 if not scaling_info["kdu-create"].get(kdu_name, None):
5184 scaling_info["kdu-create"][kdu_name] = []
5185
5186 kdur = get_kdur(db_vnfr, kdu_name)
5187 if kdur.get("helm-chart"):
5188 k8s_cluster_type = "helm-chart-v3"
5189 self.logger.debug("kdur: {}".format(kdur))
5190 if (
5191 kdur.get("helm-version")
5192 and kdur.get("helm-version") == "v2"
5193 ):
5194 k8s_cluster_type = "helm-chart"
5195 raise NotImplementedError
5196 elif kdur.get("juju-bundle"):
5197 k8s_cluster_type = "juju-bundle"
5198 else:
5199 raise LcmException(
5200 "kdu type for kdu='{}.{}' is neither helm-chart nor "
5201 "juju-bundle. Maybe an old NBI version is running".format(
5202 db_vnfr["member-vnf-index-ref"], kdu_name
5203 )
5204 )
5205
5206 max_instance_count = 10
5207 if kdu_profile and "max-number-of-instances" in kdu_profile:
5208 max_instance_count = kdu_profile.get(
5209 "max-number-of-instances", 10
5210 )
5211
5212 nb_scale_op += kdu_delta.get("number-of-instances", 1)
5213 deployed_kdu, _ = get_deployed_kdu(
5214 nsr_deployed, kdu_name, vnf_index
5215 )
5216 if deployed_kdu is None:
5217 raise LcmException(
5218 "KDU '{}' for vnf '{}' not deployed".format(
5219 kdu_name, vnf_index
5220 )
5221 )
5222 kdu_instance = deployed_kdu.get("kdu-instance")
5223 instance_num = await self.k8scluster_map[
5224 k8s_cluster_type
5225 ].get_scale_count(resource_name, kdu_instance, vca_id=vca_id)
5226 kdu_replica_count = instance_num + kdu_delta.get(
5227 "number-of-instances", 1
5228 )
5229
5230 # Control if new count is over max and instance_num is less than max.
5231 # Then assign max instance number to kdu replica count
5232 if kdu_replica_count > max_instance_count > instance_num:
5233 kdu_replica_count = max_instance_count
5234 if kdu_replica_count > max_instance_count:
5235 raise LcmException(
5236 "reached the limit of {} (max-instance-count) "
5237 "scaling-out operations for the "
5238 "scaling-group-descriptor '{}'".format(
5239 instance_num, scaling_group
5240 )
5241 )
5242
5243 for x in range(kdu_delta.get("number-of-instances", 1)):
5244 vca_scaling_info.append(
5245 {
5246 "osm_kdu_id": kdu_name,
5247 "member-vnf-index": vnf_index,
5248 "type": "create",
5249 "kdu_index": instance_num + x - 1,
5250 }
5251 )
5252 scaling_info["kdu-create"][kdu_name].append(
5253 {
5254 "member-vnf-index": vnf_index,
5255 "type": "create",
5256 "k8s-cluster-type": k8s_cluster_type,
5257 "resource-name": resource_name,
5258 "scale": kdu_replica_count,
5259 }
5260 )
5261 elif scaling_type == "SCALE_IN":
5262 deltas = scaling_descriptor.get("aspect-delta-details")["deltas"]
5263
5264 scaling_info["scaling_direction"] = "IN"
5265 scaling_info["vdu-delete"] = {}
5266 scaling_info["kdu-delete"] = {}
5267
5268 for delta in deltas:
5269 for vdu_delta in delta.get("vdu-delta", {}):
5270 vdu_count = vdu_index = get_vdur_index(db_vnfr, vdu_delta)
5271 min_instance_count = 0
5272 vdu_profile = get_vdu_profile(db_vnfd, vdu_delta["id"])
5273 if vdu_profile and "min-number-of-instances" in vdu_profile:
5274 min_instance_count = vdu_profile["min-number-of-instances"]
5275
5276 default_instance_num = get_number_of_instances(
5277 db_vnfd, vdu_delta["id"]
5278 )
5279 instance_num = vdu_delta.get("number-of-instances", 1)
5280 nb_scale_op -= instance_num
5281
5282 new_instance_count = nb_scale_op + default_instance_num
5283
5284 if new_instance_count < min_instance_count < vdu_count:
5285 instances_number = min_instance_count - new_instance_count
5286 else:
5287 instances_number = instance_num
5288
5289 if new_instance_count < min_instance_count:
5290 raise LcmException(
5291 "reached the limit of {} (min-instance-count) scaling-in operations for the "
5292 "scaling-group-descriptor '{}'".format(
5293 nb_scale_op, scaling_group
5294 )
5295 )
5296 for x in range(vdu_delta.get("number-of-instances", 1)):
5297 vca_scaling_info.append(
5298 {
5299 "osm_vdu_id": vdu_delta["id"],
5300 "member-vnf-index": vnf_index,
5301 "type": "delete",
5302 "vdu_index": vdu_index - 1 - x,
5303 }
5304 )
5305 scaling_info["vdu-delete"][vdu_delta["id"]] = instances_number
5306 for kdu_delta in delta.get("kdu-resource-delta", {}):
5307 kdu_profile = get_kdu_profile(db_vnfd, kdu_delta["id"])
5308 kdu_name = kdu_profile["kdu-name"]
5309 resource_name = kdu_profile["resource-name"]
5310
5311 if not scaling_info["kdu-delete"].get(kdu_name, None):
5312 scaling_info["kdu-delete"][kdu_name] = []
5313
5314 kdur = get_kdur(db_vnfr, kdu_name)
5315 if kdur.get("helm-chart"):
5316 k8s_cluster_type = "helm-chart-v3"
5317 self.logger.debug("kdur: {}".format(kdur))
5318 if (
5319 kdur.get("helm-version")
5320 and kdur.get("helm-version") == "v2"
5321 ):
5322 k8s_cluster_type = "helm-chart"
5323 raise NotImplementedError
5324 elif kdur.get("juju-bundle"):
5325 k8s_cluster_type = "juju-bundle"
5326 else:
5327 raise LcmException(
5328 "kdu type for kdu='{}.{}' is neither helm-chart nor "
5329 "juju-bundle. Maybe an old NBI version is running".format(
5330 db_vnfr["member-vnf-index-ref"], kdur["kdu-name"]
5331 )
5332 )
5333
5334 min_instance_count = 0
5335 if kdu_profile and "min-number-of-instances" in kdu_profile:
5336 min_instance_count = kdu_profile["min-number-of-instances"]
5337
5338 nb_scale_op -= kdu_delta.get("number-of-instances", 1)
5339 deployed_kdu, _ = get_deployed_kdu(
5340 nsr_deployed, kdu_name, vnf_index
5341 )
5342 if deployed_kdu is None:
5343 raise LcmException(
5344 "KDU '{}' for vnf '{}' not deployed".format(
5345 kdu_name, vnf_index
5346 )
5347 )
5348 kdu_instance = deployed_kdu.get("kdu-instance")
5349 instance_num = await self.k8scluster_map[
5350 k8s_cluster_type
5351 ].get_scale_count(resource_name, kdu_instance, vca_id=vca_id)
5352 kdu_replica_count = instance_num - kdu_delta.get(
5353 "number-of-instances", 1
5354 )
5355
5356 if kdu_replica_count < min_instance_count < instance_num:
5357 kdu_replica_count = min_instance_count
5358 if kdu_replica_count < min_instance_count:
5359 raise LcmException(
5360 "reached the limit of {} (min-instance-count) scaling-in operations for the "
5361 "scaling-group-descriptor '{}'".format(
5362 instance_num, scaling_group
5363 )
5364 )
5365
5366 for x in range(kdu_delta.get("number-of-instances", 1)):
5367 vca_scaling_info.append(
5368 {
5369 "osm_kdu_id": kdu_name,
5370 "member-vnf-index": vnf_index,
5371 "type": "delete",
5372 "kdu_index": instance_num - x - 1,
5373 }
5374 )
5375 scaling_info["kdu-delete"][kdu_name].append(
5376 {
5377 "member-vnf-index": vnf_index,
5378 "type": "delete",
5379 "k8s-cluster-type": k8s_cluster_type,
5380 "resource-name": resource_name,
5381 "scale": kdu_replica_count,
5382 }
5383 )
5384
5385 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
5386 vdu_delete = copy(scaling_info.get("vdu-delete"))
5387 if scaling_info["scaling_direction"] == "IN":
5388 for vdur in reversed(db_vnfr["vdur"]):
5389 if vdu_delete.get(vdur["vdu-id-ref"]):
5390 vdu_delete[vdur["vdu-id-ref"]] -= 1
5391 scaling_info["vdu"].append(
5392 {
5393 "name": vdur.get("name") or vdur.get("vdu-name"),
5394 "vdu_id": vdur["vdu-id-ref"],
5395 "interface": [],
5396 }
5397 )
5398 for interface in vdur["interfaces"]:
5399 scaling_info["vdu"][-1]["interface"].append(
5400 {
5401 "name": interface["name"],
5402 "ip_address": interface["ip-address"],
5403 "mac_address": interface.get("mac-address"),
5404 }
5405 )
5406 # vdu_delete = vdu_scaling_info.pop("vdu-delete")
5407
5408 # PRE-SCALE BEGIN
5409 step = "Executing pre-scale vnf-config-primitive"
5410 if scaling_descriptor.get("scaling-config-action"):
5411 for scaling_config_action in scaling_descriptor[
5412 "scaling-config-action"
5413 ]:
5414 if (
5415 scaling_config_action.get("trigger") == "pre-scale-in"
5416 and scaling_type == "SCALE_IN"
5417 ) or (
5418 scaling_config_action.get("trigger") == "pre-scale-out"
5419 and scaling_type == "SCALE_OUT"
5420 ):
5421 vnf_config_primitive = scaling_config_action[
5422 "vnf-config-primitive-name-ref"
5423 ]
5424 step = db_nslcmop_update[
5425 "detailed-status"
5426 ] = "executing pre-scale scaling-config-action '{}'".format(
5427 vnf_config_primitive
5428 )
5429
5430 # look for primitive
5431 for config_primitive in (
5432 get_configuration(db_vnfd, db_vnfd["id"]) or {}
5433 ).get("config-primitive", ()):
5434 if config_primitive["name"] == vnf_config_primitive:
5435 break
5436 else:
5437 raise LcmException(
5438 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
5439 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
5440 "primitive".format(scaling_group, vnf_config_primitive)
5441 )
5442
5443 vnfr_params = {"VDU_SCALE_INFO": scaling_info}
5444 if db_vnfr.get("additionalParamsForVnf"):
5445 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
5446
5447 scale_process = "VCA"
5448 db_nsr_update["config-status"] = "configuring pre-scaling"
5449 primitive_params = self._map_primitive_params(
5450 config_primitive, {}, vnfr_params
5451 )
5452
5453 # Pre-scale retry check: Check if this sub-operation has been executed before
5454 op_index = self._check_or_add_scale_suboperation(
5455 db_nslcmop,
5456 vnf_index,
5457 vnf_config_primitive,
5458 primitive_params,
5459 "PRE-SCALE",
5460 )
5461 if op_index == self.SUBOPERATION_STATUS_SKIP:
5462 # Skip sub-operation
5463 result = "COMPLETED"
5464 result_detail = "Done"
5465 self.logger.debug(
5466 logging_text
5467 + "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
5468 vnf_config_primitive, result, result_detail
5469 )
5470 )
5471 else:
5472 if op_index == self.SUBOPERATION_STATUS_NEW:
5473 # New sub-operation: Get index of this sub-operation
5474 op_index = (
5475 len(db_nslcmop.get("_admin", {}).get("operations"))
5476 - 1
5477 )
5478 self.logger.debug(
5479 logging_text
5480 + "vnf_config_primitive={} New sub-operation".format(
5481 vnf_config_primitive
5482 )
5483 )
5484 else:
5485 # retry: Get registered params for this existing sub-operation
5486 op = db_nslcmop.get("_admin", {}).get("operations", [])[
5487 op_index
5488 ]
5489 vnf_index = op.get("member_vnf_index")
5490 vnf_config_primitive = op.get("primitive")
5491 primitive_params = op.get("primitive_params")
5492 self.logger.debug(
5493 logging_text
5494 + "vnf_config_primitive={} Sub-operation retry".format(
5495 vnf_config_primitive
5496 )
5497 )
5498 # Execute the primitive, either with new (first-time) or registered (reintent) args
5499 ee_descriptor_id = config_primitive.get(
5500 "execution-environment-ref"
5501 )
5502 primitive_name = config_primitive.get(
5503 "execution-environment-primitive", vnf_config_primitive
5504 )
5505 ee_id, vca_type = self._look_for_deployed_vca(
5506 nsr_deployed["VCA"],
5507 member_vnf_index=vnf_index,
5508 vdu_id=None,
5509 vdu_count_index=None,
5510 ee_descriptor_id=ee_descriptor_id,
5511 )
5512 result, result_detail = await self._ns_execute_primitive(
5513 ee_id,
5514 primitive_name,
5515 primitive_params,
5516 vca_type=vca_type,
5517 vca_id=vca_id,
5518 )
5519 self.logger.debug(
5520 logging_text
5521 + "vnf_config_primitive={} Done with result {} {}".format(
5522 vnf_config_primitive, result, result_detail
5523 )
5524 )
5525 # Update operationState = COMPLETED | FAILED
5526 self._update_suboperation_status(
5527 db_nslcmop, op_index, result, result_detail
5528 )
5529
5530 if result == "FAILED":
5531 raise LcmException(result_detail)
5532 db_nsr_update["config-status"] = old_config_status
5533 scale_process = None
5534 # PRE-SCALE END
5535
5536 db_nsr_update[
5537 "_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index)
5538 ] = nb_scale_op
5539 db_nsr_update[
5540 "_admin.scaling-group.{}.time".format(admin_scale_index)
5541 ] = time()
5542
5543 # SCALE-IN VCA - BEGIN
5544 if vca_scaling_info:
5545 step = db_nslcmop_update[
5546 "detailed-status"
5547 ] = "Deleting the execution environments"
5548 scale_process = "VCA"
5549 for vca_info in vca_scaling_info:
5550 if vca_info["type"] == "delete":
5551 member_vnf_index = str(vca_info["member-vnf-index"])
5552 self.logger.debug(
5553 logging_text + "vdu info: {}".format(vca_info)
5554 )
5555 if vca_info.get("osm_vdu_id"):
5556 vdu_id = vca_info["osm_vdu_id"]
5557 vdu_index = int(vca_info["vdu_index"])
5558 stage[
5559 1
5560 ] = "Scaling member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
5561 member_vnf_index, vdu_id, vdu_index
5562 )
5563 else:
5564 vdu_index = 0
5565 kdu_id = vca_info["osm_kdu_id"]
5566 stage[
5567 1
5568 ] = "Scaling member_vnf_index={}, kdu_id={}, vdu_index={} ".format(
5569 member_vnf_index, kdu_id, vdu_index
5570 )
5571 stage[2] = step = "Scaling in VCA"
5572 self._write_op_status(op_id=nslcmop_id, stage=stage)
5573 vca_update = db_nsr["_admin"]["deployed"]["VCA"]
5574 config_update = db_nsr["configurationStatus"]
5575 for vca_index, vca in enumerate(vca_update):
5576 if (
5577 (vca or vca.get("ee_id"))
5578 and vca["member-vnf-index"] == member_vnf_index
5579 and vca["vdu_count_index"] == vdu_index
5580 ):
5581 if vca.get("vdu_id"):
5582 config_descriptor = get_configuration(
5583 db_vnfd, vca.get("vdu_id")
5584 )
5585 elif vca.get("kdu_name"):
5586 config_descriptor = get_configuration(
5587 db_vnfd, vca.get("kdu_name")
5588 )
5589 else:
5590 config_descriptor = get_configuration(
5591 db_vnfd, db_vnfd["id"]
5592 )
5593 operation_params = (
5594 db_nslcmop.get("operationParams") or {}
5595 )
5596 exec_terminate_primitives = not operation_params.get(
5597 "skip_terminate_primitives"
5598 ) and vca.get("needed_terminate")
5599 task = asyncio.ensure_future(
5600 asyncio.wait_for(
5601 self.destroy_N2VC(
5602 logging_text,
5603 db_nslcmop,
5604 vca,
5605 config_descriptor,
5606 vca_index,
5607 destroy_ee=True,
5608 exec_primitives=exec_terminate_primitives,
5609 scaling_in=True,
5610 vca_id=vca_id,
5611 ),
5612 timeout=self.timeout_charm_delete,
5613 )
5614 )
5615 tasks_dict_info[task] = "Terminating VCA {}".format(
5616 vca.get("ee_id")
5617 )
5618 del vca_update[vca_index]
5619 del config_update[vca_index]
5620 # wait for pending tasks of terminate primitives
5621 if tasks_dict_info:
5622 self.logger.debug(
5623 logging_text
5624 + "Waiting for tasks {}".format(
5625 list(tasks_dict_info.keys())
5626 )
5627 )
5628 error_list = await self._wait_for_tasks(
5629 logging_text,
5630 tasks_dict_info,
5631 min(
5632 self.timeout_charm_delete, self.timeout_ns_terminate
5633 ),
5634 stage,
5635 nslcmop_id,
5636 )
5637 tasks_dict_info.clear()
5638 if error_list:
5639 raise LcmException("; ".join(error_list))
5640
5641 db_vca_and_config_update = {
5642 "_admin.deployed.VCA": vca_update,
5643 "configurationStatus": config_update,
5644 }
5645 self.update_db_2(
5646 "nsrs", db_nsr["_id"], db_vca_and_config_update
5647 )
5648 scale_process = None
5649 # SCALE-IN VCA - END
5650
5651 # SCALE RO - BEGIN
5652 if scaling_info.get("vdu-create") or scaling_info.get("vdu-delete"):
5653 scale_process = "RO"
5654 if self.ro_config.get("ng"):
5655 await self._scale_ng_ro(
5656 logging_text, db_nsr, db_nslcmop, db_vnfr, scaling_info, stage
5657 )
5658 scaling_info.pop("vdu-create", None)
5659 scaling_info.pop("vdu-delete", None)
5660
5661 scale_process = None
5662 # SCALE RO - END
5663
5664 # SCALE KDU - BEGIN
5665 if scaling_info.get("kdu-create") or scaling_info.get("kdu-delete"):
5666 scale_process = "KDU"
5667 await self._scale_kdu(
5668 logging_text, nsr_id, nsr_deployed, db_vnfd, vca_id, scaling_info
5669 )
5670 scaling_info.pop("kdu-create", None)
5671 scaling_info.pop("kdu-delete", None)
5672
5673 scale_process = None
5674 # SCALE KDU - END
5675
5676 if db_nsr_update:
5677 self.update_db_2("nsrs", nsr_id, db_nsr_update)
5678
5679 # SCALE-UP VCA - BEGIN
5680 if vca_scaling_info:
5681 step = db_nslcmop_update[
5682 "detailed-status"
5683 ] = "Creating new execution environments"
5684 scale_process = "VCA"
5685 for vca_info in vca_scaling_info:
5686 if vca_info["type"] == "create":
5687 member_vnf_index = str(vca_info["member-vnf-index"])
5688 self.logger.debug(
5689 logging_text + "vdu info: {}".format(vca_info)
5690 )
5691 vnfd_id = db_vnfr["vnfd-ref"]
5692 if vca_info.get("osm_vdu_id"):
5693 vdu_index = int(vca_info["vdu_index"])
5694 deploy_params = {"OSM": get_osm_params(db_vnfr)}
5695 if db_vnfr.get("additionalParamsForVnf"):
5696 deploy_params.update(
5697 parse_yaml_strings(
5698 db_vnfr["additionalParamsForVnf"].copy()
5699 )
5700 )
5701 descriptor_config = get_configuration(
5702 db_vnfd, db_vnfd["id"]
5703 )
5704 if descriptor_config:
5705 vdu_id = None
5706 vdu_name = None
5707 kdu_name = None
5708 self._deploy_n2vc(
5709 logging_text=logging_text
5710 + "member_vnf_index={} ".format(member_vnf_index),
5711 db_nsr=db_nsr,
5712 db_vnfr=db_vnfr,
5713 nslcmop_id=nslcmop_id,
5714 nsr_id=nsr_id,
5715 nsi_id=nsi_id,
5716 vnfd_id=vnfd_id,
5717 vdu_id=vdu_id,
5718 kdu_name=kdu_name,
5719 member_vnf_index=member_vnf_index,
5720 vdu_index=vdu_index,
5721 vdu_name=vdu_name,
5722 deploy_params=deploy_params,
5723 descriptor_config=descriptor_config,
5724 base_folder=base_folder,
5725 task_instantiation_info=tasks_dict_info,
5726 stage=stage,
5727 )
5728 vdu_id = vca_info["osm_vdu_id"]
5729 vdur = find_in_list(
5730 db_vnfr["vdur"], lambda vdu: vdu["vdu-id-ref"] == vdu_id
5731 )
5732 descriptor_config = get_configuration(db_vnfd, vdu_id)
5733 if vdur.get("additionalParams"):
5734 deploy_params_vdu = parse_yaml_strings(
5735 vdur["additionalParams"]
5736 )
5737 else:
5738 deploy_params_vdu = deploy_params
5739 deploy_params_vdu["OSM"] = get_osm_params(
5740 db_vnfr, vdu_id, vdu_count_index=vdu_index
5741 )
5742 if descriptor_config:
5743 vdu_name = None
5744 kdu_name = None
5745 stage[
5746 1
5747 ] = "Scaling member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
5748 member_vnf_index, vdu_id, vdu_index
5749 )
5750 stage[2] = step = "Scaling out VCA"
5751 self._write_op_status(op_id=nslcmop_id, stage=stage)
5752 self._deploy_n2vc(
5753 logging_text=logging_text
5754 + "member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
5755 member_vnf_index, vdu_id, vdu_index
5756 ),
5757 db_nsr=db_nsr,
5758 db_vnfr=db_vnfr,
5759 nslcmop_id=nslcmop_id,
5760 nsr_id=nsr_id,
5761 nsi_id=nsi_id,
5762 vnfd_id=vnfd_id,
5763 vdu_id=vdu_id,
5764 kdu_name=kdu_name,
5765 member_vnf_index=member_vnf_index,
5766 vdu_index=vdu_index,
5767 vdu_name=vdu_name,
5768 deploy_params=deploy_params_vdu,
5769 descriptor_config=descriptor_config,
5770 base_folder=base_folder,
5771 task_instantiation_info=tasks_dict_info,
5772 stage=stage,
5773 )
5774 else:
5775 kdu_name = vca_info["osm_kdu_id"]
5776 descriptor_config = get_configuration(db_vnfd, kdu_name)
5777 if descriptor_config:
5778 vdu_id = None
5779 kdu_index = int(vca_info["kdu_index"])
5780 vdu_name = None
5781 kdur = next(
5782 x
5783 for x in db_vnfr["kdur"]
5784 if x["kdu-name"] == kdu_name
5785 )
5786 deploy_params_kdu = {"OSM": get_osm_params(db_vnfr)}
5787 if kdur.get("additionalParams"):
5788 deploy_params_kdu = parse_yaml_strings(
5789 kdur["additionalParams"]
5790 )
5791
5792 self._deploy_n2vc(
5793 logging_text=logging_text,
5794 db_nsr=db_nsr,
5795 db_vnfr=db_vnfr,
5796 nslcmop_id=nslcmop_id,
5797 nsr_id=nsr_id,
5798 nsi_id=nsi_id,
5799 vnfd_id=vnfd_id,
5800 vdu_id=vdu_id,
5801 kdu_name=kdu_name,
5802 member_vnf_index=member_vnf_index,
5803 vdu_index=kdu_index,
5804 vdu_name=vdu_name,
5805 deploy_params=deploy_params_kdu,
5806 descriptor_config=descriptor_config,
5807 base_folder=base_folder,
5808 task_instantiation_info=tasks_dict_info,
5809 stage=stage,
5810 )
5811 # SCALE-UP VCA - END
5812 scale_process = None
5813
5814 # POST-SCALE BEGIN
5815 # execute primitive service POST-SCALING
5816 step = "Executing post-scale vnf-config-primitive"
5817 if scaling_descriptor.get("scaling-config-action"):
5818 for scaling_config_action in scaling_descriptor[
5819 "scaling-config-action"
5820 ]:
5821 if (
5822 scaling_config_action.get("trigger") == "post-scale-in"
5823 and scaling_type == "SCALE_IN"
5824 ) or (
5825 scaling_config_action.get("trigger") == "post-scale-out"
5826 and scaling_type == "SCALE_OUT"
5827 ):
5828 vnf_config_primitive = scaling_config_action[
5829 "vnf-config-primitive-name-ref"
5830 ]
5831 step = db_nslcmop_update[
5832 "detailed-status"
5833 ] = "executing post-scale scaling-config-action '{}'".format(
5834 vnf_config_primitive
5835 )
5836
5837 vnfr_params = {"VDU_SCALE_INFO": scaling_info}
5838 if db_vnfr.get("additionalParamsForVnf"):
5839 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
5840
5841 # look for primitive
5842 for config_primitive in (
5843 get_configuration(db_vnfd, db_vnfd["id"]) or {}
5844 ).get("config-primitive", ()):
5845 if config_primitive["name"] == vnf_config_primitive:
5846 break
5847 else:
5848 raise LcmException(
5849 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-"
5850 "action[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:"
5851 "config-primitive".format(
5852 scaling_group, vnf_config_primitive
5853 )
5854 )
5855 scale_process = "VCA"
5856 db_nsr_update["config-status"] = "configuring post-scaling"
5857 primitive_params = self._map_primitive_params(
5858 config_primitive, {}, vnfr_params
5859 )
5860
5861 # Post-scale retry check: Check if this sub-operation has been executed before
5862 op_index = self._check_or_add_scale_suboperation(
5863 db_nslcmop,
5864 vnf_index,
5865 vnf_config_primitive,
5866 primitive_params,
5867 "POST-SCALE",
5868 )
5869 if op_index == self.SUBOPERATION_STATUS_SKIP:
5870 # Skip sub-operation
5871 result = "COMPLETED"
5872 result_detail = "Done"
5873 self.logger.debug(
5874 logging_text
5875 + "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
5876 vnf_config_primitive, result, result_detail
5877 )
5878 )
5879 else:
5880 if op_index == self.SUBOPERATION_STATUS_NEW:
5881 # New sub-operation: Get index of this sub-operation
5882 op_index = (
5883 len(db_nslcmop.get("_admin", {}).get("operations"))
5884 - 1
5885 )
5886 self.logger.debug(
5887 logging_text
5888 + "vnf_config_primitive={} New sub-operation".format(
5889 vnf_config_primitive
5890 )
5891 )
5892 else:
5893 # retry: Get registered params for this existing sub-operation
5894 op = db_nslcmop.get("_admin", {}).get("operations", [])[
5895 op_index
5896 ]
5897 vnf_index = op.get("member_vnf_index")
5898 vnf_config_primitive = op.get("primitive")
5899 primitive_params = op.get("primitive_params")
5900 self.logger.debug(
5901 logging_text
5902 + "vnf_config_primitive={} Sub-operation retry".format(
5903 vnf_config_primitive
5904 )
5905 )
5906 # Execute the primitive, either with new (first-time) or registered (reintent) args
5907 ee_descriptor_id = config_primitive.get(
5908 "execution-environment-ref"
5909 )
5910 primitive_name = config_primitive.get(
5911 "execution-environment-primitive", vnf_config_primitive
5912 )
5913 ee_id, vca_type = self._look_for_deployed_vca(
5914 nsr_deployed["VCA"],
5915 member_vnf_index=vnf_index,
5916 vdu_id=None,
5917 vdu_count_index=None,
5918 ee_descriptor_id=ee_descriptor_id,
5919 )
5920 result, result_detail = await self._ns_execute_primitive(
5921 ee_id,
5922 primitive_name,
5923 primitive_params,
5924 vca_type=vca_type,
5925 vca_id=vca_id,
5926 )
5927 self.logger.debug(
5928 logging_text
5929 + "vnf_config_primitive={} Done with result {} {}".format(
5930 vnf_config_primitive, result, result_detail
5931 )
5932 )
5933 # Update operationState = COMPLETED | FAILED
5934 self._update_suboperation_status(
5935 db_nslcmop, op_index, result, result_detail
5936 )
5937
5938 if result == "FAILED":
5939 raise LcmException(result_detail)
5940 db_nsr_update["config-status"] = old_config_status
5941 scale_process = None
5942 # POST-SCALE END
5943
5944 db_nsr_update[
5945 "detailed-status"
5946 ] = "" # "scaled {} {}".format(scaling_group, scaling_type)
5947 db_nsr_update["operational-status"] = (
5948 "running"
5949 if old_operational_status == "failed"
5950 else old_operational_status
5951 )
5952 db_nsr_update["config-status"] = old_config_status
5953 return
5954 except (
5955 ROclient.ROClientException,
5956 DbException,
5957 LcmException,
5958 NgRoException,
5959 ) as e:
5960 self.logger.error(logging_text + "Exit Exception {}".format(e))
5961 exc = e
5962 except asyncio.CancelledError:
5963 self.logger.error(
5964 logging_text + "Cancelled Exception while '{}'".format(step)
5965 )
5966 exc = "Operation was cancelled"
5967 except Exception as e:
5968 exc = traceback.format_exc()
5969 self.logger.critical(
5970 logging_text + "Exit Exception {} {}".format(type(e).__name__, e),
5971 exc_info=True,
5972 )
5973 finally:
5974 self._write_ns_status(
5975 nsr_id=nsr_id,
5976 ns_state=None,
5977 current_operation="IDLE",
5978 current_operation_id=None,
5979 )
5980 if tasks_dict_info:
5981 stage[1] = "Waiting for instantiate pending tasks."
5982 self.logger.debug(logging_text + stage[1])
5983 exc = await self._wait_for_tasks(
5984 logging_text,
5985 tasks_dict_info,
5986 self.timeout_ns_deploy,
5987 stage,
5988 nslcmop_id,
5989 nsr_id=nsr_id,
5990 )
5991 if exc:
5992 db_nslcmop_update[
5993 "detailed-status"
5994 ] = error_description_nslcmop = "FAILED {}: {}".format(step, exc)
5995 nslcmop_operation_state = "FAILED"
5996 if db_nsr:
5997 db_nsr_update["operational-status"] = old_operational_status
5998 db_nsr_update["config-status"] = old_config_status
5999 db_nsr_update["detailed-status"] = ""
6000 if scale_process:
6001 if "VCA" in scale_process:
6002 db_nsr_update["config-status"] = "failed"
6003 if "RO" in scale_process:
6004 db_nsr_update["operational-status"] = "failed"
6005 db_nsr_update[
6006 "detailed-status"
6007 ] = "FAILED scaling nslcmop={} {}: {}".format(
6008 nslcmop_id, step, exc
6009 )
6010 else:
6011 error_description_nslcmop = None
6012 nslcmop_operation_state = "COMPLETED"
6013 db_nslcmop_update["detailed-status"] = "Done"
6014
6015 self._write_op_status(
6016 op_id=nslcmop_id,
6017 stage="",
6018 error_message=error_description_nslcmop,
6019 operation_state=nslcmop_operation_state,
6020 other_update=db_nslcmop_update,
6021 )
6022 if db_nsr:
6023 self._write_ns_status(
6024 nsr_id=nsr_id,
6025 ns_state=None,
6026 current_operation="IDLE",
6027 current_operation_id=None,
6028 other_update=db_nsr_update,
6029 )
6030
6031 if nslcmop_operation_state:
6032 try:
6033 msg = {
6034 "nsr_id": nsr_id,
6035 "nslcmop_id": nslcmop_id,
6036 "operationState": nslcmop_operation_state,
6037 }
6038 await self.msg.aiowrite("ns", "scaled", msg, loop=self.loop)
6039 except Exception as e:
6040 self.logger.error(
6041 logging_text + "kafka_write notification Exception {}".format(e)
6042 )
6043 self.logger.debug(logging_text + "Exit")
6044 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_scale")
6045
6046 async def _scale_kdu(
6047 self, logging_text, nsr_id, nsr_deployed, db_vnfd, vca_id, scaling_info
6048 ):
6049 _scaling_info = scaling_info.get("kdu-create") or scaling_info.get("kdu-delete")
6050 for kdu_name in _scaling_info:
6051 for kdu_scaling_info in _scaling_info[kdu_name]:
6052 deployed_kdu, index = get_deployed_kdu(
6053 nsr_deployed, kdu_name, kdu_scaling_info["member-vnf-index"]
6054 )
6055 cluster_uuid = deployed_kdu["k8scluster-uuid"]
6056 kdu_instance = deployed_kdu["kdu-instance"]
6057 scale = int(kdu_scaling_info["scale"])
6058 k8s_cluster_type = kdu_scaling_info["k8s-cluster-type"]
6059
6060 db_dict = {
6061 "collection": "nsrs",
6062 "filter": {"_id": nsr_id},
6063 "path": "_admin.deployed.K8s.{}".format(index),
6064 }
6065
6066 step = "scaling application {}".format(
6067 kdu_scaling_info["resource-name"]
6068 )
6069 self.logger.debug(logging_text + step)
6070
6071 if kdu_scaling_info["type"] == "delete":
6072 kdu_config = get_configuration(db_vnfd, kdu_name)
6073 if (
6074 kdu_config
6075 and kdu_config.get("terminate-config-primitive")
6076 and get_juju_ee_ref(db_vnfd, kdu_name) is None
6077 ):
6078 terminate_config_primitive_list = kdu_config.get(
6079 "terminate-config-primitive"
6080 )
6081 terminate_config_primitive_list.sort(
6082 key=lambda val: int(val["seq"])
6083 )
6084
6085 for (
6086 terminate_config_primitive
6087 ) in terminate_config_primitive_list:
6088 primitive_params_ = self._map_primitive_params(
6089 terminate_config_primitive, {}, {}
6090 )
6091 step = "execute terminate config primitive"
6092 self.logger.debug(logging_text + step)
6093 await asyncio.wait_for(
6094 self.k8scluster_map[k8s_cluster_type].exec_primitive(
6095 cluster_uuid=cluster_uuid,
6096 kdu_instance=kdu_instance,
6097 primitive_name=terminate_config_primitive["name"],
6098 params=primitive_params_,
6099 db_dict=db_dict,
6100 vca_id=vca_id,
6101 ),
6102 timeout=600,
6103 )
6104
6105 await asyncio.wait_for(
6106 self.k8scluster_map[k8s_cluster_type].scale(
6107 kdu_instance,
6108 scale,
6109 kdu_scaling_info["resource-name"],
6110 vca_id=vca_id,
6111 ),
6112 timeout=self.timeout_vca_on_error,
6113 )
6114
6115 if kdu_scaling_info["type"] == "create":
6116 kdu_config = get_configuration(db_vnfd, kdu_name)
6117 if (
6118 kdu_config
6119 and kdu_config.get("initial-config-primitive")
6120 and get_juju_ee_ref(db_vnfd, kdu_name) is None
6121 ):
6122 initial_config_primitive_list = kdu_config.get(
6123 "initial-config-primitive"
6124 )
6125 initial_config_primitive_list.sort(
6126 key=lambda val: int(val["seq"])
6127 )
6128
6129 for initial_config_primitive in initial_config_primitive_list:
6130 primitive_params_ = self._map_primitive_params(
6131 initial_config_primitive, {}, {}
6132 )
6133 step = "execute initial config primitive"
6134 self.logger.debug(logging_text + step)
6135 await asyncio.wait_for(
6136 self.k8scluster_map[k8s_cluster_type].exec_primitive(
6137 cluster_uuid=cluster_uuid,
6138 kdu_instance=kdu_instance,
6139 primitive_name=initial_config_primitive["name"],
6140 params=primitive_params_,
6141 db_dict=db_dict,
6142 vca_id=vca_id,
6143 ),
6144 timeout=600,
6145 )
6146
6147 async def _scale_ng_ro(
6148 self, logging_text, db_nsr, db_nslcmop, db_vnfr, vdu_scaling_info, stage
6149 ):
6150 nsr_id = db_nslcmop["nsInstanceId"]
6151 db_nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
6152 db_vnfrs = {}
6153
6154 # read from db: vnfd's for every vnf
6155 db_vnfds = []
6156
6157 # for each vnf in ns, read vnfd
6158 for vnfr in self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id}):
6159 db_vnfrs[vnfr["member-vnf-index-ref"]] = vnfr
6160 vnfd_id = vnfr["vnfd-id"] # vnfd uuid for this vnf
6161 # if we haven't this vnfd, read it from db
6162 if not find_in_list(db_vnfds, lambda a_vnfd: a_vnfd["id"] == vnfd_id):
6163 # read from db
6164 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
6165 db_vnfds.append(vnfd)
6166 n2vc_key = self.n2vc.get_public_key()
6167 n2vc_key_list = [n2vc_key]
6168 self.scale_vnfr(
6169 db_vnfr,
6170 vdu_scaling_info.get("vdu-create"),
6171 vdu_scaling_info.get("vdu-delete"),
6172 mark_delete=True,
6173 )
6174 # db_vnfr has been updated, update db_vnfrs to use it
6175 db_vnfrs[db_vnfr["member-vnf-index-ref"]] = db_vnfr
6176 await self._instantiate_ng_ro(
6177 logging_text,
6178 nsr_id,
6179 db_nsd,
6180 db_nsr,
6181 db_nslcmop,
6182 db_vnfrs,
6183 db_vnfds,
6184 n2vc_key_list,
6185 stage=stage,
6186 start_deploy=time(),
6187 timeout_ns_deploy=self.timeout_ns_deploy,
6188 )
6189 if vdu_scaling_info.get("vdu-delete"):
6190 self.scale_vnfr(
6191 db_vnfr, None, vdu_scaling_info["vdu-delete"], mark_delete=False
6192 )
6193
6194 async def add_prometheus_metrics(
6195 self, ee_id, artifact_path, ee_config_descriptor, vnfr_id, nsr_id, target_ip
6196 ):
6197 if not self.prometheus:
6198 return
6199 # look if exist a file called 'prometheus*.j2' and
6200 artifact_content = self.fs.dir_ls(artifact_path)
6201 job_file = next(
6202 (
6203 f
6204 for f in artifact_content
6205 if f.startswith("prometheus") and f.endswith(".j2")
6206 ),
6207 None,
6208 )
6209 if not job_file:
6210 return
6211 with self.fs.file_open((artifact_path, job_file), "r") as f:
6212 job_data = f.read()
6213
6214 # TODO get_service
6215 _, _, service = ee_id.partition(".") # remove prefix "namespace."
6216 host_name = "{}-{}".format(service, ee_config_descriptor["metric-service"])
6217 host_port = "80"
6218 vnfr_id = vnfr_id.replace("-", "")
6219 variables = {
6220 "JOB_NAME": vnfr_id,
6221 "TARGET_IP": target_ip,
6222 "EXPORTER_POD_IP": host_name,
6223 "EXPORTER_POD_PORT": host_port,
6224 }
6225 job_list = self.prometheus.parse_job(job_data, variables)
6226 # ensure job_name is using the vnfr_id. Adding the metadata nsr_id
6227 for job in job_list:
6228 if (
6229 not isinstance(job.get("job_name"), str)
6230 or vnfr_id not in job["job_name"]
6231 ):
6232 job["job_name"] = vnfr_id + "_" + str(randint(1, 10000))
6233 job["nsr_id"] = nsr_id
6234 job_dict = {jl["job_name"]: jl for jl in job_list}
6235 if await self.prometheus.update(job_dict):
6236 return list(job_dict.keys())
6237
6238 def get_vca_cloud_and_credentials(self, vim_account_id: str) -> (str, str):
6239 """
6240 Get VCA Cloud and VCA Cloud Credentials for the VIM account
6241
6242 :param: vim_account_id: VIM Account ID
6243
6244 :return: (cloud_name, cloud_credential)
6245 """
6246 config = VimAccountDB.get_vim_account_with_id(vim_account_id).get("config", {})
6247 return config.get("vca_cloud"), config.get("vca_cloud_credential")
6248
6249 def get_vca_k8s_cloud_and_credentials(self, vim_account_id: str) -> (str, str):
6250 """
6251 Get VCA K8s Cloud and VCA K8s Cloud Credentials for the VIM account
6252
6253 :param: vim_account_id: VIM Account ID
6254
6255 :return: (cloud_name, cloud_credential)
6256 """
6257 config = VimAccountDB.get_vim_account_with_id(vim_account_id).get("config", {})
6258 return config.get("vca_k8s_cloud"), config.get("vca_k8s_cloud_credential")