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