1 # -*- coding: utf-8 -*-
4 # Copyright 2018 Telefonica S.A.
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
10 # http://www.apache.org/licenses/LICENSE-2.0
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
21 from typing
import Any
, Dict
, List
24 import logging
.handlers
36 from osm_lcm
import ROclient
37 from osm_lcm
.data_utils
.lcm_config
import LcmCfg
38 from osm_lcm
.data_utils
.nsr
import (
41 get_deployed_vca_list
,
44 from osm_lcm
.data_utils
.vca
import (
53 from osm_lcm
.ng_ro
import NgRoClient
, NgRoException
54 from osm_lcm
.lcm_utils
import (
60 check_juju_bundle_existence
,
61 get_charm_artifact_path
,
65 from osm_lcm
.data_utils
.nsd
import (
66 get_ns_configuration_relation_list
,
70 from osm_lcm
.data_utils
.vnfd
import (
76 get_ee_sorted_initial_config_primitive_list
,
77 get_ee_sorted_terminate_config_primitive_list
,
79 get_virtual_link_profiles
,
84 get_number_of_instances
,
86 get_kdu_resource_profile
,
87 find_software_version
,
90 from osm_lcm
.data_utils
.list_utils
import find_in_list
91 from osm_lcm
.data_utils
.vnfr
import (
95 get_volumes_from_instantiation_params
,
97 from osm_lcm
.data_utils
.dict_utils
import parse_yaml_strings
98 from osm_lcm
.data_utils
.database
.vim_account
import VimAccountDB
99 from n2vc
.definitions
import RelationEndpoint
100 from n2vc
.k8s_helm_conn
import K8sHelmConnector
101 from n2vc
.k8s_helm3_conn
import K8sHelm3Connector
102 from n2vc
.k8s_juju_conn
import K8sJujuConnector
104 from osm_common
.dbbase
import DbException
105 from osm_common
.fsbase
import FsException
107 from osm_lcm
.data_utils
.database
.database
import Database
108 from osm_lcm
.data_utils
.filesystem
.filesystem
import Filesystem
109 from osm_lcm
.data_utils
.wim
import (
111 get_target_wim_attrs
,
112 select_feasible_wim_account
,
115 from n2vc
.n2vc_juju_conn
import N2VCJujuConnector
116 from n2vc
.exceptions
import N2VCException
, N2VCNotFound
, K8sException
118 from osm_lcm
.lcm_helm_conn
import LCMHelmConn
119 from osm_lcm
.osm_config
import OsmConfigBuilder
120 from osm_lcm
.prometheus
import parse_job
122 from copy
import copy
, deepcopy
123 from time
import time
124 from uuid
import uuid4
126 from random
import SystemRandom
128 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
131 class NsLcm(LcmBase
):
132 SUBOPERATION_STATUS_NOT_FOUND
= -1
133 SUBOPERATION_STATUS_NEW
= -2
134 SUBOPERATION_STATUS_SKIP
= -3
135 EE_TLS_NAME
= "ee-tls"
136 task_name_deploy_vca
= "Deploying VCA"
137 rel_operation_types
= {
146 def __init__(self
, msg
, lcm_tasks
, config
: LcmCfg
):
148 Init, Connect to database, filesystem storage, and messaging
149 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
152 super().__init
__(msg
=msg
, logger
=logging
.getLogger("lcm.ns"))
154 self
.db
= Database().instance
.db
155 self
.fs
= Filesystem().instance
.fs
156 self
.lcm_tasks
= lcm_tasks
157 self
.timeout
= config
.timeout
158 self
.ro_config
= config
.RO
159 self
.vca_config
= config
.VCA
161 # create N2VC connector
162 self
.n2vc
= N2VCJujuConnector(
164 on_update_db
=self
._on
_update
_n
2vc
_db
,
169 self
.conn_helm_ee
= LCMHelmConn(
171 vca_config
=self
.vca_config
,
172 on_update_db
=self
._on
_update
_n
2vc
_db
,
175 self
.k8sclusterhelm2
= K8sHelmConnector(
176 kubectl_command
=self
.vca_config
.kubectlpath
,
177 helm_command
=self
.vca_config
.helmpath
,
184 self
.k8sclusterhelm3
= K8sHelm3Connector(
185 kubectl_command
=self
.vca_config
.kubectlpath
,
186 helm_command
=self
.vca_config
.helm3path
,
193 self
.k8sclusterjuju
= K8sJujuConnector(
194 kubectl_command
=self
.vca_config
.kubectlpath
,
195 juju_command
=self
.vca_config
.jujupath
,
197 on_update_db
=self
._on
_update
_k
8s
_db
,
202 self
.k8scluster_map
= {
203 "helm-chart": self
.k8sclusterhelm2
,
204 "helm-chart-v3": self
.k8sclusterhelm3
,
205 "chart": self
.k8sclusterhelm3
,
206 "juju-bundle": self
.k8sclusterjuju
,
207 "juju": self
.k8sclusterjuju
,
211 "lxc_proxy_charm": self
.n2vc
,
212 "native_charm": self
.n2vc
,
213 "k8s_proxy_charm": self
.n2vc
,
214 "helm": self
.conn_helm_ee
,
215 "helm-v3": self
.conn_helm_ee
,
219 self
.RO
= NgRoClient(**self
.ro_config
.to_dict())
221 self
.op_status_map
= {
222 "instantiation": self
.RO
.status
,
223 "termination": self
.RO
.status
,
224 "migrate": self
.RO
.status
,
225 "healing": self
.RO
.recreate_status
,
226 "verticalscale": self
.RO
.status
,
227 "start_stop_rebuild": self
.RO
.status
,
231 def increment_ip_mac(ip_mac
, vm_index
=1):
232 if not isinstance(ip_mac
, str):
235 # try with ipv4 look for last dot
236 i
= ip_mac
.rfind(".")
239 return "{}{}".format(ip_mac
[:i
], int(ip_mac
[i
:]) + vm_index
)
240 # try with ipv6 or mac look for last colon. Operate in hex
241 i
= ip_mac
.rfind(":")
244 # format in hex, len can be 2 for mac or 4 for ipv6
245 return ("{}{:0" + str(len(ip_mac
) - i
) + "x}").format(
246 ip_mac
[:i
], int(ip_mac
[i
:], 16) + vm_index
252 async def _on_update_n2vc_db(self
, table
, filter, path
, updated_data
, vca_id
=None):
253 # remove last dot from path (if exists)
254 if path
.endswith("."):
257 # self.logger.debug('_on_update_n2vc_db(table={}, filter={}, path={}, updated_data={}'
258 # .format(table, filter, path, updated_data))
260 nsr_id
= filter.get("_id")
262 # read ns record from database
263 nsr
= self
.db
.get_one(table
="nsrs", q_filter
=filter)
264 current_ns_status
= nsr
.get("nsState")
266 # get vca status for NS
267 status_dict
= await self
.n2vc
.get_status(
268 namespace
="." + nsr_id
, yaml_format
=False, vca_id
=vca_id
273 db_dict
["vcaStatus"] = status_dict
275 # update configurationStatus for this VCA
277 vca_index
= int(path
[path
.rfind(".") + 1 :])
280 target_dict
=nsr
, key_list
=("_admin", "deployed", "VCA")
282 vca_status
= vca_list
[vca_index
].get("status")
284 configuration_status_list
= nsr
.get("configurationStatus")
285 config_status
= configuration_status_list
[vca_index
].get("status")
287 if config_status
== "BROKEN" and vca_status
!= "failed":
288 db_dict
["configurationStatus"][vca_index
] = "READY"
289 elif config_status
!= "BROKEN" and vca_status
== "failed":
290 db_dict
["configurationStatus"][vca_index
] = "BROKEN"
291 except Exception as e
:
292 # not update configurationStatus
293 self
.logger
.debug("Error updating vca_index (ignore): {}".format(e
))
295 # if nsState = 'READY' check if juju is reporting some error => nsState = 'DEGRADED'
296 # if nsState = 'DEGRADED' check if all is OK
298 if current_ns_status
in ("READY", "DEGRADED"):
299 error_description
= ""
301 if status_dict
.get("machines"):
302 for machine_id
in status_dict
.get("machines"):
303 machine
= status_dict
.get("machines").get(machine_id
)
304 # check machine agent-status
305 if machine
.get("agent-status"):
306 s
= machine
.get("agent-status").get("status")
309 error_description
+= (
310 "machine {} agent-status={} ; ".format(
314 # check machine instance status
315 if machine
.get("instance-status"):
316 s
= machine
.get("instance-status").get("status")
319 error_description
+= (
320 "machine {} instance-status={} ; ".format(
325 if status_dict
.get("applications"):
326 for app_id
in status_dict
.get("applications"):
327 app
= status_dict
.get("applications").get(app_id
)
328 # check application status
329 if app
.get("status"):
330 s
= app
.get("status").get("status")
333 error_description
+= (
334 "application {} status={} ; ".format(app_id
, s
)
337 if error_description
:
338 db_dict
["errorDescription"] = error_description
339 if current_ns_status
== "READY" and is_degraded
:
340 db_dict
["nsState"] = "DEGRADED"
341 if current_ns_status
== "DEGRADED" and not is_degraded
:
342 db_dict
["nsState"] = "READY"
345 self
.update_db_2("nsrs", nsr_id
, db_dict
)
347 except (asyncio
.CancelledError
, asyncio
.TimeoutError
):
349 except Exception as e
:
350 self
.logger
.warn("Error updating NS state for ns={}: {}".format(nsr_id
, e
))
352 async def _on_update_k8s_db(
353 self
, cluster_uuid
, kdu_instance
, filter=None, vca_id
=None, cluster_type
="juju"
356 Updating vca status in NSR record
357 :param cluster_uuid: UUID of a k8s cluster
358 :param kdu_instance: The unique name of the KDU instance
359 :param filter: To get nsr_id
360 :cluster_type: The cluster type (juju, k8s)
364 # self.logger.debug("_on_update_k8s_db(cluster_uuid={}, kdu_instance={}, filter={}"
365 # .format(cluster_uuid, kdu_instance, filter))
367 nsr_id
= filter.get("_id")
369 vca_status
= await self
.k8scluster_map
[cluster_type
].status_kdu(
370 cluster_uuid
=cluster_uuid
,
371 kdu_instance
=kdu_instance
,
373 complete_status
=True,
379 db_dict
["vcaStatus"] = {nsr_id
: vca_status
}
382 f
"Obtained VCA status for cluster type '{cluster_type}': {vca_status}"
386 self
.update_db_2("nsrs", nsr_id
, db_dict
)
387 except (asyncio
.CancelledError
, asyncio
.TimeoutError
):
389 except Exception as e
:
390 self
.logger
.warn("Error updating NS state for ns={}: {}".format(nsr_id
, e
))
393 def _parse_cloud_init(cloud_init_text
, additional_params
, vnfd_id
, vdu_id
):
396 undefined
=StrictUndefined
,
397 autoescape
=select_autoescape(default_for_string
=True, default
=True),
399 template
= env
.from_string(cloud_init_text
)
400 return template
.render(additional_params
or {})
401 except UndefinedError
as e
:
403 "Variable {} at vnfd[id={}]:vdu[id={}]:cloud-init/cloud-init-"
404 "file, must be provided in the instantiation parameters inside the "
405 "'additionalParamsForVnf/Vdu' block".format(e
, vnfd_id
, vdu_id
)
407 except (TemplateError
, TemplateNotFound
) as e
:
409 "Error parsing Jinja2 to cloud-init content at vnfd[id={}]:vdu[id={}]: {}".format(
414 def _get_vdu_cloud_init_content(self
, vdu
, vnfd
):
415 cloud_init_content
= cloud_init_file
= None
417 if vdu
.get("cloud-init-file"):
418 base_folder
= vnfd
["_admin"]["storage"]
419 if base_folder
["pkg-dir"]:
420 cloud_init_file
= "{}/{}/cloud_init/{}".format(
421 base_folder
["folder"],
422 base_folder
["pkg-dir"],
423 vdu
["cloud-init-file"],
426 cloud_init_file
= "{}/Scripts/cloud_init/{}".format(
427 base_folder
["folder"],
428 vdu
["cloud-init-file"],
430 with self
.fs
.file_open(cloud_init_file
, "r") as ci_file
:
431 cloud_init_content
= ci_file
.read()
432 elif vdu
.get("cloud-init"):
433 cloud_init_content
= vdu
["cloud-init"]
435 return cloud_init_content
436 except FsException
as e
:
438 "Error reading vnfd[id={}]:vdu[id={}]:cloud-init-file={}: {}".format(
439 vnfd
["id"], vdu
["id"], cloud_init_file
, e
443 def _get_vdu_additional_params(self
, db_vnfr
, vdu_id
):
445 (vdur
for vdur
in db_vnfr
.get("vdur") if vdu_id
== vdur
["vdu-id-ref"]), {}
447 additional_params
= vdur
.get("additionalParams")
448 return parse_yaml_strings(additional_params
)
451 def ip_profile_2_RO(ip_profile
):
452 RO_ip_profile
= deepcopy(ip_profile
)
453 if "dns-server" in RO_ip_profile
:
454 if isinstance(RO_ip_profile
["dns-server"], list):
455 RO_ip_profile
["dns-address"] = []
456 for ds
in RO_ip_profile
.pop("dns-server"):
457 RO_ip_profile
["dns-address"].append(ds
["address"])
459 RO_ip_profile
["dns-address"] = RO_ip_profile
.pop("dns-server")
460 if RO_ip_profile
.get("ip-version") == "ipv4":
461 RO_ip_profile
["ip-version"] = "IPv4"
462 if RO_ip_profile
.get("ip-version") == "ipv6":
463 RO_ip_profile
["ip-version"] = "IPv6"
464 if "dhcp-params" in RO_ip_profile
:
465 RO_ip_profile
["dhcp"] = RO_ip_profile
.pop("dhcp-params")
468 def scale_vnfr(self
, db_vnfr
, vdu_create
=None, vdu_delete
=None, mark_delete
=False):
469 db_vdu_push_list
= []
471 db_update
= {"_admin.modified": time()}
473 for vdu_id
, vdu_count
in vdu_create
.items():
477 for vdur
in reversed(db_vnfr
["vdur"])
478 if vdur
["vdu-id-ref"] == vdu_id
483 # Read the template saved in the db:
485 "No vdur in the database. Using the vdur-template to scale"
487 vdur_template
= db_vnfr
.get("vdur-template")
488 if not vdur_template
:
490 "Error scaling OUT VNFR for {}. No vnfr or template exists".format(
494 vdur
= vdur_template
[0]
495 # Delete a template from the database after using it
498 {"_id": db_vnfr
["_id"]},
500 pull
={"vdur-template": {"_id": vdur
["_id"]}},
502 for count
in range(vdu_count
):
503 vdur_copy
= deepcopy(vdur
)
504 vdur_copy
["status"] = "BUILD"
505 vdur_copy
["status-detailed"] = None
506 vdur_copy
["ip-address"] = None
507 vdur_copy
["_id"] = str(uuid4())
508 vdur_copy
["count-index"] += count
+ 1
509 vdur_copy
["id"] = "{}-{}".format(
510 vdur_copy
["vdu-id-ref"], vdur_copy
["count-index"]
512 vdur_copy
.pop("vim_info", None)
513 for iface
in vdur_copy
["interfaces"]:
514 if iface
.get("fixed-ip"):
515 iface
["ip-address"] = self
.increment_ip_mac(
516 iface
["ip-address"], count
+ 1
519 iface
.pop("ip-address", None)
520 if iface
.get("fixed-mac"):
521 iface
["mac-address"] = self
.increment_ip_mac(
522 iface
["mac-address"], count
+ 1
525 iface
.pop("mac-address", None)
529 ) # only first vdu can be managment of vnf
530 db_vdu_push_list
.append(vdur_copy
)
531 # self.logger.debug("scale out, adding vdu={}".format(vdur_copy))
533 if len(db_vnfr
["vdur"]) == 1:
534 # The scale will move to 0 instances
536 "Scaling to 0 !, creating the template with the last vdur"
538 template_vdur
= [db_vnfr
["vdur"][0]]
539 for vdu_id
, vdu_count
in vdu_delete
.items():
541 indexes_to_delete
= [
543 for iv
in enumerate(db_vnfr
["vdur"])
544 if iv
[1]["vdu-id-ref"] == vdu_id
548 "vdur.{}.status".format(i
): "DELETING"
549 for i
in indexes_to_delete
[-vdu_count
:]
553 # it must be deleted one by one because common.db does not allow otherwise
556 for v
in reversed(db_vnfr
["vdur"])
557 if v
["vdu-id-ref"] == vdu_id
559 for vdu
in vdus_to_delete
[:vdu_count
]:
562 {"_id": db_vnfr
["_id"]},
564 pull
={"vdur": {"_id": vdu
["_id"]}},
568 db_push
["vdur"] = db_vdu_push_list
570 db_push
["vdur-template"] = template_vdur
573 db_vnfr
["vdur-template"] = template_vdur
574 self
.db
.set_one("vnfrs", {"_id": db_vnfr
["_id"]}, db_update
, push_list
=db_push
)
575 # modify passed dictionary db_vnfr
576 db_vnfr_
= self
.db
.get_one("vnfrs", {"_id": db_vnfr
["_id"]})
577 db_vnfr
["vdur"] = db_vnfr_
["vdur"]
579 def ns_update_nsr(self
, ns_update_nsr
, db_nsr
, nsr_desc_RO
):
581 Updates database nsr with the RO info for the created vld
582 :param ns_update_nsr: dictionary to be filled with the updated info
583 :param db_nsr: content of db_nsr. This is also modified
584 :param nsr_desc_RO: nsr descriptor from RO
585 :return: Nothing, LcmException is raised on errors
588 for vld_index
, vld
in enumerate(get_iterable(db_nsr
, "vld")):
589 for net_RO
in get_iterable(nsr_desc_RO
, "nets"):
590 if vld
["id"] != net_RO
.get("ns_net_osm_id"):
592 vld
["vim-id"] = net_RO
.get("vim_net_id")
593 vld
["name"] = net_RO
.get("vim_name")
594 vld
["status"] = net_RO
.get("status")
595 vld
["status-detailed"] = net_RO
.get("error_msg")
596 ns_update_nsr
["vld.{}".format(vld_index
)] = vld
600 "ns_update_nsr: Not found vld={} at RO info".format(vld
["id"])
603 def set_vnfr_at_error(self
, db_vnfrs
, error_text
):
605 for db_vnfr
in db_vnfrs
.values():
606 vnfr_update
= {"status": "ERROR"}
607 for vdu_index
, vdur
in enumerate(get_iterable(db_vnfr
, "vdur")):
608 if "status" not in vdur
:
609 vdur
["status"] = "ERROR"
610 vnfr_update
["vdur.{}.status".format(vdu_index
)] = "ERROR"
612 vdur
["status-detailed"] = str(error_text
)
614 "vdur.{}.status-detailed".format(vdu_index
)
616 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
617 except DbException
as e
:
618 self
.logger
.error("Cannot update vnf. {}".format(e
))
620 def _get_ns_config_info(self
, nsr_id
):
622 Generates a mapping between vnf,vdu elements and the N2VC id
623 :param nsr_id: id of nsr to get last database _admin.deployed.VCA that contains this list
624 :return: a dictionary with {osm-config-mapping: {}} where its element contains:
625 "<member-vnf-index>": <N2VC-id> for a vnf configuration, or
626 "<member-vnf-index>.<vdu.id>.<vdu replica(0, 1,..)>": <N2VC-id> for a vdu configuration
628 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
629 vca_deployed_list
= db_nsr
["_admin"]["deployed"]["VCA"]
631 ns_config_info
= {"osm-config-mapping": mapping
}
632 for vca
in vca_deployed_list
:
633 if not vca
["member-vnf-index"]:
635 if not vca
["vdu_id"]:
636 mapping
[vca
["member-vnf-index"]] = vca
["application"]
640 vca
["member-vnf-index"], vca
["vdu_id"], vca
["vdu_count_index"]
642 ] = vca
["application"]
643 return ns_config_info
645 async def _instantiate_ng_ro(
661 def get_vim_account(vim_account_id
):
663 if vim_account_id
in db_vims
:
664 return db_vims
[vim_account_id
]
665 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_account_id
})
666 db_vims
[vim_account_id
] = db_vim
669 # modify target_vld info with instantiation parameters
670 def parse_vld_instantiation_params(
671 target_vim
, target_vld
, vld_params
, target_sdn
673 if vld_params
.get("ip-profile"):
674 target_vld
["vim_info"][target_vim
]["ip_profile"] = vld_to_ro_ip_profile(
675 vld_params
["ip-profile"]
677 if vld_params
.get("provider-network"):
678 target_vld
["vim_info"][target_vim
]["provider_network"] = vld_params
[
681 if "sdn-ports" in vld_params
["provider-network"] and target_sdn
:
682 target_vld
["vim_info"][target_sdn
]["sdn-ports"] = vld_params
[
686 # check if WIM is needed; if needed, choose a feasible WIM able to connect VIMs
687 # if wim_account_id is specified in vld_params, validate if it is feasible.
688 wim_account_id
, db_wim
= select_feasible_wim_account(
689 db_nsr
, db_vnfrs
, target_vld
, vld_params
, self
.logger
693 # WIM is needed and a feasible one was found, populate WIM target and SDN ports
694 self
.logger
.info("WIM selected: {:s}".format(str(wim_account_id
)))
695 # update vld_params with correct WIM account Id
696 vld_params
["wimAccountId"] = wim_account_id
698 target_wim
= "wim:{}".format(wim_account_id
)
699 target_wim_attrs
= get_target_wim_attrs(nsr_id
, target_vld
, vld_params
)
700 sdn_ports
= get_sdn_ports(vld_params
, db_wim
)
701 if len(sdn_ports
) > 0:
702 target_vld
["vim_info"][target_wim
] = target_wim_attrs
703 target_vld
["vim_info"][target_wim
]["sdn-ports"] = sdn_ports
706 "Target VLD with WIM data: {:s}".format(str(target_vld
))
709 for param
in ("vim-network-name", "vim-network-id"):
710 if vld_params
.get(param
):
711 if isinstance(vld_params
[param
], dict):
712 for vim
, vim_net
in vld_params
[param
].items():
713 other_target_vim
= "vim:" + vim
715 target_vld
["vim_info"],
716 (other_target_vim
, param
.replace("-", "_")),
719 else: # isinstance str
720 target_vld
["vim_info"][target_vim
][
721 param
.replace("-", "_")
722 ] = vld_params
[param
]
723 if vld_params
.get("common_id"):
724 target_vld
["common_id"] = vld_params
.get("common_id")
726 # modify target["ns"]["vld"] with instantiation parameters to override vnf vim-account
727 def update_ns_vld_target(target
, ns_params
):
728 for vnf_params
in ns_params
.get("vnf", ()):
729 if vnf_params
.get("vimAccountId"):
733 for vnfr
in db_vnfrs
.values()
734 if vnf_params
["member-vnf-index"]
735 == vnfr
["member-vnf-index-ref"]
739 vdur
= next((vdur
for vdur
in target_vnf
.get("vdur", ())), None)
742 for a_index
, a_vld
in enumerate(target
["ns"]["vld"]):
743 target_vld
= find_in_list(
744 get_iterable(vdur
, "interfaces"),
745 lambda iface
: iface
.get("ns-vld-id") == a_vld
["name"],
748 vld_params
= find_in_list(
749 get_iterable(ns_params
, "vld"),
750 lambda v_vld
: v_vld
["name"] in (a_vld
["name"], a_vld
["id"]),
753 if vnf_params
.get("vimAccountId") not in a_vld
.get(
756 target_vim_network_list
= [
757 v
for _
, v
in a_vld
.get("vim_info").items()
759 target_vim_network_name
= next(
761 item
.get("vim_network_name", "")
762 for item
in target_vim_network_list
767 target
["ns"]["vld"][a_index
].get("vim_info").update(
769 "vim:{}".format(vnf_params
["vimAccountId"]): {
770 "vim_network_name": target_vim_network_name
,
776 for param
in ("vim-network-name", "vim-network-id"):
777 if vld_params
.get(param
) and isinstance(
778 vld_params
[param
], dict
780 for vim
, vim_net
in vld_params
[
783 other_target_vim
= "vim:" + vim
785 target
["ns"]["vld"][a_index
].get(
790 param
.replace("-", "_"),
795 nslcmop_id
= db_nslcmop
["_id"]
797 "name": db_nsr
["name"],
800 "image": deepcopy(db_nsr
["image"]),
801 "flavor": deepcopy(db_nsr
["flavor"]),
802 "action_id": nslcmop_id
,
803 "cloud_init_content": {},
805 for image
in target
["image"]:
806 image
["vim_info"] = {}
807 for flavor
in target
["flavor"]:
808 flavor
["vim_info"] = {}
809 if db_nsr
.get("shared-volumes"):
810 target
["shared-volumes"] = deepcopy(db_nsr
["shared-volumes"])
811 for shared_volumes
in target
["shared-volumes"]:
812 shared_volumes
["vim_info"] = {}
813 if db_nsr
.get("affinity-or-anti-affinity-group"):
814 target
["affinity-or-anti-affinity-group"] = deepcopy(
815 db_nsr
["affinity-or-anti-affinity-group"]
817 for affinity_or_anti_affinity_group
in target
[
818 "affinity-or-anti-affinity-group"
820 affinity_or_anti_affinity_group
["vim_info"] = {}
822 if db_nslcmop
.get("lcmOperationType") != "instantiate":
823 # get parameters of instantiation:
824 db_nslcmop_instantiate
= self
.db
.get_list(
827 "nsInstanceId": db_nslcmop
["nsInstanceId"],
828 "lcmOperationType": "instantiate",
831 ns_params
= db_nslcmop_instantiate
.get("operationParams")
833 ns_params
= db_nslcmop
.get("operationParams")
834 ssh_keys_instantiation
= ns_params
.get("ssh_keys") or []
835 ssh_keys_all
= ssh_keys_instantiation
+ (n2vc_key_list
or [])
838 for vld_index
, vld
in enumerate(db_nsr
.get("vld")):
839 target_vim
= "vim:{}".format(ns_params
["vimAccountId"])
843 "mgmt-network": vld
.get("mgmt-network", False),
844 "type": vld
.get("type"),
847 "vim_network_name": vld
.get("vim-network-name"),
848 "vim_account_id": ns_params
["vimAccountId"],
852 # check if this network needs SDN assist
853 if vld
.get("pci-interfaces"):
854 db_vim
= get_vim_account(ns_params
["vimAccountId"])
855 if vim_config
:= db_vim
.get("config"):
856 if sdnc_id
:= vim_config
.get("sdn-controller"):
857 sdn_vld
= "nsrs:{}:vld.{}".format(nsr_id
, vld
["id"])
858 target_sdn
= "sdn:{}".format(sdnc_id
)
859 target_vld
["vim_info"][target_sdn
] = {
861 "target_vim": target_vim
,
863 "type": vld
.get("type"),
866 nsd_vnf_profiles
= get_vnf_profiles(nsd
)
867 for nsd_vnf_profile
in nsd_vnf_profiles
:
868 for cp
in nsd_vnf_profile
["virtual-link-connectivity"]:
869 if cp
["virtual-link-profile-id"] == vld
["id"]:
871 "member_vnf:{}.{}".format(
872 cp
["constituent-cpd-id"][0][
873 "constituent-base-element-id"
875 cp
["constituent-cpd-id"][0]["constituent-cpd-id"],
877 ] = "nsrs:{}:vld.{}".format(nsr_id
, vld_index
)
879 # check at nsd descriptor, if there is an ip-profile
881 nsd_vlp
= find_in_list(
882 get_virtual_link_profiles(nsd
),
883 lambda a_link_profile
: a_link_profile
["virtual-link-desc-id"]
888 and nsd_vlp
.get("virtual-link-protocol-data")
889 and nsd_vlp
["virtual-link-protocol-data"].get("l3-protocol-data")
891 vld_params
["ip-profile"] = nsd_vlp
["virtual-link-protocol-data"][
895 # update vld_params with instantiation params
896 vld_instantiation_params
= find_in_list(
897 get_iterable(ns_params
, "vld"),
898 lambda a_vld
: a_vld
["name"] in (vld
["name"], vld
["id"]),
900 if vld_instantiation_params
:
901 vld_params
.update(vld_instantiation_params
)
902 parse_vld_instantiation_params(target_vim
, target_vld
, vld_params
, None)
903 target
["ns"]["vld"].append(target_vld
)
904 # Update the target ns_vld if vnf vim_account is overriden by instantiation params
905 update_ns_vld_target(target
, ns_params
)
907 for vnfr
in db_vnfrs
.values():
909 db_vnfds
, lambda db_vnf
: db_vnf
["id"] == vnfr
["vnfd-ref"]
911 vnf_params
= find_in_list(
912 get_iterable(ns_params
, "vnf"),
913 lambda a_vnf
: a_vnf
["member-vnf-index"] == vnfr
["member-vnf-index-ref"],
915 target_vnf
= deepcopy(vnfr
)
916 target_vim
= "vim:{}".format(vnfr
["vim-account-id"])
917 for vld
in target_vnf
.get("vld", ()):
918 # check if connected to a ns.vld, to fill target'
919 vnf_cp
= find_in_list(
920 vnfd
.get("int-virtual-link-desc", ()),
921 lambda cpd
: cpd
.get("id") == vld
["id"],
924 ns_cp
= "member_vnf:{}.{}".format(
925 vnfr
["member-vnf-index-ref"], vnf_cp
["id"]
927 if cp2target
.get(ns_cp
):
928 vld
["target"] = cp2target
[ns_cp
]
931 target_vim
: {"vim_network_name": vld
.get("vim-network-name")}
933 # check if this network needs SDN assist
935 if vld
.get("pci-interfaces"):
936 db_vim
= get_vim_account(vnfr
["vim-account-id"])
937 sdnc_id
= db_vim
["config"].get("sdn-controller")
939 sdn_vld
= "vnfrs:{}:vld.{}".format(target_vnf
["_id"], vld
["id"])
940 target_sdn
= "sdn:{}".format(sdnc_id
)
941 vld
["vim_info"][target_sdn
] = {
943 "target_vim": target_vim
,
945 "type": vld
.get("type"),
948 # check at vnfd descriptor, if there is an ip-profile
950 vnfd_vlp
= find_in_list(
951 get_virtual_link_profiles(vnfd
),
952 lambda a_link_profile
: a_link_profile
["id"] == vld
["id"],
956 and vnfd_vlp
.get("virtual-link-protocol-data")
957 and vnfd_vlp
["virtual-link-protocol-data"].get("l3-protocol-data")
959 vld_params
["ip-profile"] = vnfd_vlp
["virtual-link-protocol-data"][
962 # update vld_params with instantiation params
964 vld_instantiation_params
= find_in_list(
965 get_iterable(vnf_params
, "internal-vld"),
966 lambda i_vld
: i_vld
["name"] == vld
["id"],
968 if vld_instantiation_params
:
969 vld_params
.update(vld_instantiation_params
)
970 parse_vld_instantiation_params(target_vim
, vld
, vld_params
, target_sdn
)
973 for vdur
in target_vnf
.get("vdur", ()):
974 if vdur
.get("status") == "DELETING" or vdur
.get("pdu-type"):
975 continue # This vdu must not be created
976 vdur
["vim_info"] = {"vim_account_id": vnfr
["vim-account-id"]}
978 self
.logger
.debug("NS > ssh_keys > {}".format(ssh_keys_all
))
981 vdu_configuration
= get_configuration(vnfd
, vdur
["vdu-id-ref"])
982 vnf_configuration
= get_configuration(vnfd
, vnfd
["id"])
985 and vdu_configuration
.get("config-access")
986 and vdu_configuration
.get("config-access").get("ssh-access")
988 vdur
["ssh-keys"] = ssh_keys_all
989 vdur
["ssh-access-required"] = vdu_configuration
[
991 ]["ssh-access"]["required"]
994 and vnf_configuration
.get("config-access")
995 and vnf_configuration
.get("config-access").get("ssh-access")
996 and any(iface
.get("mgmt-vnf") for iface
in vdur
["interfaces"])
998 vdur
["ssh-keys"] = ssh_keys_all
999 vdur
["ssh-access-required"] = vnf_configuration
[
1001 ]["ssh-access"]["required"]
1002 elif ssh_keys_instantiation
and find_in_list(
1003 vdur
["interfaces"], lambda iface
: iface
.get("mgmt-vnf")
1005 vdur
["ssh-keys"] = ssh_keys_instantiation
1007 self
.logger
.debug("NS > vdur > {}".format(vdur
))
1009 vdud
= get_vdu(vnfd
, vdur
["vdu-id-ref"])
1011 if vdud
.get("cloud-init-file"):
1012 vdur
["cloud-init"] = "{}:file:{}".format(
1013 vnfd
["_id"], vdud
.get("cloud-init-file")
1015 # read file and put content at target.cloul_init_content. Avoid ng_ro to use shared package system
1016 if vdur
["cloud-init"] not in target
["cloud_init_content"]:
1017 base_folder
= vnfd
["_admin"]["storage"]
1018 if base_folder
["pkg-dir"]:
1019 cloud_init_file
= "{}/{}/cloud_init/{}".format(
1020 base_folder
["folder"],
1021 base_folder
["pkg-dir"],
1022 vdud
.get("cloud-init-file"),
1025 cloud_init_file
= "{}/Scripts/cloud_init/{}".format(
1026 base_folder
["folder"],
1027 vdud
.get("cloud-init-file"),
1029 with self
.fs
.file_open(cloud_init_file
, "r") as ci_file
:
1030 target
["cloud_init_content"][
1033 elif vdud
.get("cloud-init"):
1034 vdur
["cloud-init"] = "{}:vdu:{}".format(
1035 vnfd
["_id"], get_vdu_index(vnfd
, vdur
["vdu-id-ref"])
1037 # put content at target.cloul_init_content. Avoid ng_ro read vnfd descriptor
1038 target
["cloud_init_content"][vdur
["cloud-init"]] = vdud
[
1041 vdur
["additionalParams"] = vdur
.get("additionalParams") or {}
1042 deploy_params_vdu
= self
._format
_additional
_params
(
1043 vdur
.get("additionalParams") or {}
1045 deploy_params_vdu
["OSM"] = get_osm_params(
1046 vnfr
, vdur
["vdu-id-ref"], vdur
["count-index"]
1048 vdur
["additionalParams"] = deploy_params_vdu
1051 ns_flavor
= target
["flavor"][int(vdur
["ns-flavor-id"])]
1052 if target_vim
not in ns_flavor
["vim_info"]:
1053 ns_flavor
["vim_info"][target_vim
] = {}
1056 # in case alternative images are provided we must check if they should be applied
1057 # for the vim_type, modify the vim_type taking into account
1058 ns_image_id
= int(vdur
["ns-image-id"])
1059 if vdur
.get("alt-image-ids"):
1060 db_vim
= get_vim_account(vnfr
["vim-account-id"])
1061 vim_type
= db_vim
["vim_type"]
1062 for alt_image_id
in vdur
.get("alt-image-ids"):
1063 ns_alt_image
= target
["image"][int(alt_image_id
)]
1064 if vim_type
== ns_alt_image
.get("vim-type"):
1065 # must use alternative image
1067 "use alternative image id: {}".format(alt_image_id
)
1069 ns_image_id
= alt_image_id
1070 vdur
["ns-image-id"] = ns_image_id
1072 ns_image
= target
["image"][int(ns_image_id
)]
1073 if target_vim
not in ns_image
["vim_info"]:
1074 ns_image
["vim_info"][target_vim
] = {}
1077 if vdur
.get("affinity-or-anti-affinity-group-id"):
1078 for ags_id
in vdur
["affinity-or-anti-affinity-group-id"]:
1079 ns_ags
= target
["affinity-or-anti-affinity-group"][int(ags_id
)]
1080 if target_vim
not in ns_ags
["vim_info"]:
1081 ns_ags
["vim_info"][target_vim
] = {}
1084 if vdur
.get("shared-volumes-id"):
1085 for sv_id
in vdur
["shared-volumes-id"]:
1086 ns_sv
= find_in_list(
1087 target
["shared-volumes"], lambda sv
: sv_id
in sv
["id"]
1090 ns_sv
["vim_info"][target_vim
] = {}
1092 vdur
["vim_info"] = {target_vim
: {}}
1093 # instantiation parameters
1095 vdu_instantiation_params
= find_in_list(
1096 get_iterable(vnf_params
, "vdu"),
1097 lambda i_vdu
: i_vdu
["id"] == vdud
["id"],
1099 if vdu_instantiation_params
:
1100 # Parse the vdu_volumes from the instantiation params
1101 vdu_volumes
= get_volumes_from_instantiation_params(
1102 vdu_instantiation_params
, vdud
1104 vdur
["additionalParams"]["OSM"]["vdu_volumes"] = vdu_volumes
1105 vdur
["additionalParams"]["OSM"][
1107 ] = vdu_instantiation_params
.get("vim-flavor-id")
1108 vdur_list
.append(vdur
)
1109 target_vnf
["vdur"] = vdur_list
1110 target
["vnf"].append(target_vnf
)
1112 self
.logger
.debug("Send to RO > nsr_id={} target={}".format(nsr_id
, target
))
1113 desc
= await self
.RO
.deploy(nsr_id
, target
)
1114 self
.logger
.debug("RO return > {}".format(desc
))
1115 action_id
= desc
["action_id"]
1116 await self
._wait
_ng
_ro
(
1123 operation
="instantiation",
1128 "_admin.deployed.RO.operational-status": "running",
1129 "detailed-status": " ".join(stage
),
1131 # db_nsr["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
1132 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1133 self
._write
_op
_status
(nslcmop_id
, stage
)
1135 logging_text
+ "ns deployed at RO. RO_id={}".format(action_id
)
1139 async def _wait_ng_ro(
1149 detailed_status_old
= None
1151 start_time
= start_time
or time()
1152 while time() <= start_time
+ timeout
:
1153 desc_status
= await self
.op_status_map
[operation
](nsr_id
, action_id
)
1154 self
.logger
.debug("Wait NG RO > {}".format(desc_status
))
1155 if desc_status
["status"] == "FAILED":
1156 raise NgRoException(desc_status
["details"])
1157 elif desc_status
["status"] == "BUILD":
1159 stage
[2] = "VIM: ({})".format(desc_status
["details"])
1160 elif desc_status
["status"] == "DONE":
1162 stage
[2] = "Deployed at VIM"
1165 assert False, "ROclient.check_ns_status returns unknown {}".format(
1166 desc_status
["status"]
1168 if stage
and nslcmop_id
and stage
[2] != detailed_status_old
:
1169 detailed_status_old
= stage
[2]
1170 db_nsr_update
["detailed-status"] = " ".join(stage
)
1171 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1172 self
._write
_op
_status
(nslcmop_id
, stage
)
1173 await asyncio
.sleep(15)
1174 else: # timeout_ns_deploy
1175 raise NgRoException("Timeout waiting ns to deploy")
1177 async def _terminate_ng_ro(
1178 self
, logging_text
, nsr_deployed
, nsr_id
, nslcmop_id
, stage
1183 start_deploy
= time()
1190 "action_id": nslcmop_id
,
1192 desc
= await self
.RO
.deploy(nsr_id
, target
)
1193 action_id
= desc
["action_id"]
1194 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETING"
1197 + "ns terminate action at RO. action_id={}".format(action_id
)
1201 delete_timeout
= 20 * 60 # 20 minutes
1202 await self
._wait
_ng
_ro
(
1209 operation
="termination",
1211 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
1213 await self
.RO
.delete(nsr_id
)
1214 except NgRoException
as e
:
1215 if e
.http_code
== 404: # not found
1216 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1217 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
1219 logging_text
+ "RO_action_id={} already deleted".format(action_id
)
1221 elif e
.http_code
== 409: # conflict
1222 failed_detail
.append("delete conflict: {}".format(e
))
1225 + "RO_action_id={} delete conflict: {}".format(action_id
, e
)
1228 failed_detail
.append("delete error: {}".format(e
))
1231 + "RO_action_id={} delete error: {}".format(action_id
, e
)
1233 except Exception as e
:
1234 failed_detail
.append("delete error: {}".format(e
))
1236 logging_text
+ "RO_action_id={} delete error: {}".format(action_id
, e
)
1240 stage
[2] = "Error deleting from VIM"
1242 stage
[2] = "Deleted from VIM"
1243 db_nsr_update
["detailed-status"] = " ".join(stage
)
1244 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1245 self
._write
_op
_status
(nslcmop_id
, stage
)
1248 raise LcmException("; ".join(failed_detail
))
1251 async def instantiate_RO(
1265 :param logging_text: preffix text to use at logging
1266 :param nsr_id: nsr identity
1267 :param nsd: database content of ns descriptor
1268 :param db_nsr: database content of ns record
1269 :param db_nslcmop: database content of ns operation, in this case, 'instantiate'
1271 :param db_vnfds: database content of vnfds, indexed by id (not _id). {id: {vnfd_object}, ...}
1272 :param n2vc_key_list: ssh-public-key list to be inserted to management vdus via cloud-init
1273 :param stage: list with 3 items: [general stage, tasks, vim_specific]. This task will write over vim_specific
1274 :return: None or exception
1277 start_deploy
= time()
1278 ns_params
= db_nslcmop
.get("operationParams")
1279 if ns_params
and ns_params
.get("timeout_ns_deploy"):
1280 timeout_ns_deploy
= ns_params
["timeout_ns_deploy"]
1282 timeout_ns_deploy
= self
.timeout
.ns_deploy
1284 # Check for and optionally request placement optimization. Database will be updated if placement activated
1285 stage
[2] = "Waiting for Placement."
1286 if await self
._do
_placement
(logging_text
, db_nslcmop
, db_vnfrs
):
1287 # in case of placement change ns_params[vimAcountId) if not present at any vnfrs
1288 for vnfr
in db_vnfrs
.values():
1289 if ns_params
["vimAccountId"] == vnfr
["vim-account-id"]:
1292 ns_params
["vimAccountId"] == vnfr
["vim-account-id"]
1294 return await self
._instantiate
_ng
_ro
(
1307 except Exception as e
:
1308 stage
[2] = "ERROR deploying at VIM"
1309 self
.set_vnfr_at_error(db_vnfrs
, str(e
))
1311 "Error deploying at VIM {}".format(e
),
1312 exc_info
=not isinstance(
1315 ROclient
.ROClientException
,
1324 async def wait_kdu_up(self
, logging_text
, nsr_id
, vnfr_id
, kdu_name
):
1326 Wait for kdu to be up, get ip address
1327 :param logging_text: prefix use for logging
1331 :return: IP address, K8s services
1334 # self.logger.debug(logging_text + "Starting wait_kdu_up")
1337 while nb_tries
< 360:
1338 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnfr_id
})
1342 for x
in get_iterable(db_vnfr
, "kdur")
1343 if x
.get("kdu-name") == kdu_name
1349 "Not found vnfr_id={}, kdu_name={}".format(vnfr_id
, kdu_name
)
1351 if kdur
.get("status"):
1352 if kdur
["status"] in ("READY", "ENABLED"):
1353 return kdur
.get("ip-address"), kdur
.get("services")
1356 "target KDU={} is in error state".format(kdu_name
)
1359 await asyncio
.sleep(10)
1361 raise LcmException("Timeout waiting KDU={} instantiated".format(kdu_name
))
1363 async def wait_vm_up_insert_key_ro(
1364 self
, logging_text
, nsr_id
, vnfr_id
, vdu_id
, vdu_index
, pub_key
=None, user
=None
1367 Wait for ip addres at RO, and optionally, insert public key in virtual machine
1368 :param logging_text: prefix use for logging
1373 :param pub_key: public ssh key to inject, None to skip
1374 :param user: user to apply the public ssh key
1378 self
.logger
.debug(logging_text
+ "Starting wait_vm_up_insert_key_ro")
1380 target_vdu_id
= None
1385 if ro_retries
>= 360: # 1 hour
1387 "Not found _admin.deployed.RO.nsr_id for nsr_id: {}".format(nsr_id
)
1390 await asyncio
.sleep(10)
1393 if not target_vdu_id
:
1394 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnfr_id
})
1396 if not vdu_id
: # for the VNF case
1397 if db_vnfr
.get("status") == "ERROR":
1399 "Cannot inject ssh-key because target VNF is in error state"
1401 ip_address
= db_vnfr
.get("ip-address")
1407 for x
in get_iterable(db_vnfr
, "vdur")
1408 if x
.get("ip-address") == ip_address
1416 for x
in get_iterable(db_vnfr
, "vdur")
1417 if x
.get("vdu-id-ref") == vdu_id
1418 and x
.get("count-index") == vdu_index
1424 not vdur
and len(db_vnfr
.get("vdur", ())) == 1
1425 ): # If only one, this should be the target vdu
1426 vdur
= db_vnfr
["vdur"][0]
1429 "Not found vnfr_id={}, vdu_id={}, vdu_index={}".format(
1430 vnfr_id
, vdu_id
, vdu_index
1433 # New generation RO stores information at "vim_info"
1436 if vdur
.get("vim_info"):
1438 t
for t
in vdur
["vim_info"]
1439 ) # there should be only one key
1440 ng_ro_status
= vdur
["vim_info"][target_vim
].get("vim_status")
1442 vdur
.get("pdu-type")
1443 or vdur
.get("status") == "ACTIVE"
1444 or ng_ro_status
== "ACTIVE"
1446 ip_address
= vdur
.get("ip-address")
1449 target_vdu_id
= vdur
["vdu-id-ref"]
1450 elif vdur
.get("status") == "ERROR" or ng_ro_status
== "ERROR":
1452 "Cannot inject ssh-key because target VM is in error state"
1455 if not target_vdu_id
:
1458 # inject public key into machine
1459 if pub_key
and user
:
1460 self
.logger
.debug(logging_text
+ "Inserting RO key")
1461 self
.logger
.debug("SSH > PubKey > {}".format(pub_key
))
1462 if vdur
.get("pdu-type"):
1463 self
.logger
.error(logging_text
+ "Cannot inject ssh-ky to a PDU")
1468 "action": "inject_ssh_key",
1472 "vnf": [{"_id": vnfr_id
, "vdur": [{"id": vdur
["id"]}]}],
1474 desc
= await self
.RO
.deploy(nsr_id
, target
)
1475 action_id
= desc
["action_id"]
1476 await self
._wait
_ng
_ro
(
1477 nsr_id
, action_id
, timeout
=600, operation
="instantiation"
1480 except NgRoException
as e
:
1482 "Reaching max tries injecting key. Error: {}".format(e
)
1489 async def _wait_dependent_n2vc(self
, nsr_id
, vca_deployed_list
, vca_index
):
1491 Wait until dependent VCA deployments have been finished. NS wait for VNFs and VDUs. VNFs for VDUs
1493 my_vca
= vca_deployed_list
[vca_index
]
1494 if my_vca
.get("vdu_id") or my_vca
.get("kdu_name"):
1495 # vdu or kdu: no dependencies
1499 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1500 vca_deployed_list
= db_nsr
["_admin"]["deployed"]["VCA"]
1501 configuration_status_list
= db_nsr
["configurationStatus"]
1502 for index
, vca_deployed
in enumerate(configuration_status_list
):
1503 if index
== vca_index
:
1506 if not my_vca
.get("member-vnf-index") or (
1507 vca_deployed
.get("member-vnf-index")
1508 == my_vca
.get("member-vnf-index")
1510 internal_status
= configuration_status_list
[index
].get("status")
1511 if internal_status
== "READY":
1513 elif internal_status
== "BROKEN":
1515 "Configuration aborted because dependent charm/s has failed"
1520 # no dependencies, return
1522 await asyncio
.sleep(10)
1525 raise LcmException("Configuration aborted because dependent charm/s timeout")
1527 def get_vca_id(self
, db_vnfr
: dict, db_nsr
: dict):
1530 vca_id
= deep_get(db_vnfr
, ("vca-id",))
1532 vim_account_id
= deep_get(db_nsr
, ("instantiate_params", "vimAccountId"))
1533 vca_id
= VimAccountDB
.get_vim_account_with_id(vim_account_id
).get("vca")
1536 async def instantiate_N2VC(
1554 ee_config_descriptor
,
1556 nsr_id
= db_nsr
["_id"]
1557 db_update_entry
= "_admin.deployed.VCA.{}.".format(vca_index
)
1558 vca_deployed_list
= db_nsr
["_admin"]["deployed"]["VCA"]
1559 vca_deployed
= db_nsr
["_admin"]["deployed"]["VCA"][vca_index
]
1560 osm_config
= {"osm": {"ns_id": db_nsr
["_id"]}}
1562 "collection": "nsrs",
1563 "filter": {"_id": nsr_id
},
1564 "path": db_update_entry
,
1569 element_under_configuration
= nsr_id
1573 vnfr_id
= db_vnfr
["_id"]
1574 osm_config
["osm"]["vnf_id"] = vnfr_id
1576 namespace
= "{nsi}.{ns}".format(nsi
=nsi_id
if nsi_id
else "", ns
=nsr_id
)
1578 if vca_type
== "native_charm":
1581 index_number
= vdu_index
or 0
1584 element_type
= "VNF"
1585 element_under_configuration
= vnfr_id
1586 namespace
+= ".{}-{}".format(vnfr_id
, index_number
)
1588 namespace
+= ".{}-{}".format(vdu_id
, index_number
)
1589 element_type
= "VDU"
1590 element_under_configuration
= "{}-{}".format(vdu_id
, index_number
)
1591 osm_config
["osm"]["vdu_id"] = vdu_id
1593 namespace
+= ".{}".format(kdu_name
)
1594 element_type
= "KDU"
1595 element_under_configuration
= kdu_name
1596 osm_config
["osm"]["kdu_name"] = kdu_name
1599 if base_folder
["pkg-dir"]:
1600 artifact_path
= "{}/{}/{}/{}".format(
1601 base_folder
["folder"],
1602 base_folder
["pkg-dir"],
1605 in ("native_charm", "lxc_proxy_charm", "k8s_proxy_charm")
1610 artifact_path
= "{}/Scripts/{}/{}/".format(
1611 base_folder
["folder"],
1614 in ("native_charm", "lxc_proxy_charm", "k8s_proxy_charm")
1619 self
.logger
.debug("Artifact path > {}".format(artifact_path
))
1621 # get initial_config_primitive_list that applies to this element
1622 initial_config_primitive_list
= config_descriptor
.get(
1623 "initial-config-primitive"
1627 "Initial config primitive list > {}".format(
1628 initial_config_primitive_list
1632 # add config if not present for NS charm
1633 ee_descriptor_id
= ee_config_descriptor
.get("id")
1634 self
.logger
.debug("EE Descriptor > {}".format(ee_descriptor_id
))
1635 initial_config_primitive_list
= get_ee_sorted_initial_config_primitive_list(
1636 initial_config_primitive_list
, vca_deployed
, ee_descriptor_id
1640 "Initial config primitive list #2 > {}".format(
1641 initial_config_primitive_list
1644 # n2vc_redesign STEP 3.1
1645 # find old ee_id if exists
1646 ee_id
= vca_deployed
.get("ee_id")
1648 vca_id
= self
.get_vca_id(db_vnfr
, db_nsr
)
1649 # create or register execution environment in VCA
1650 if vca_type
in ("lxc_proxy_charm", "k8s_proxy_charm", "helm", "helm-v3"):
1651 self
._write
_configuration
_status
(
1653 vca_index
=vca_index
,
1655 element_under_configuration
=element_under_configuration
,
1656 element_type
=element_type
,
1659 step
= "create execution environment"
1660 self
.logger
.debug(logging_text
+ step
)
1664 if vca_type
== "k8s_proxy_charm":
1665 ee_id
= await self
.vca_map
[vca_type
].install_k8s_proxy_charm(
1666 charm_name
=artifact_path
[artifact_path
.rfind("/") + 1 :],
1667 namespace
=namespace
,
1668 artifact_path
=artifact_path
,
1672 elif vca_type
== "helm" or vca_type
== "helm-v3":
1673 ee_id
, credentials
= await self
.vca_map
[
1675 ].create_execution_environment(
1680 artifact_path
=artifact_path
,
1681 chart_model
=vca_name
,
1685 ee_id
, credentials
= await self
.vca_map
[
1687 ].create_execution_environment(
1688 namespace
=namespace
,
1694 elif vca_type
== "native_charm":
1695 step
= "Waiting to VM being up and getting IP address"
1696 self
.logger
.debug(logging_text
+ step
)
1697 rw_mgmt_ip
= await self
.wait_vm_up_insert_key_ro(
1706 credentials
= {"hostname": rw_mgmt_ip
}
1708 username
= deep_get(
1709 config_descriptor
, ("config-access", "ssh-access", "default-user")
1711 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1712 # merged. Meanwhile let's get username from initial-config-primitive
1713 if not username
and initial_config_primitive_list
:
1714 for config_primitive
in initial_config_primitive_list
:
1715 for param
in config_primitive
.get("parameter", ()):
1716 if param
["name"] == "ssh-username":
1717 username
= param
["value"]
1721 "Cannot determine the username neither with 'initial-config-primitive' nor with "
1722 "'config-access.ssh-access.default-user'"
1724 credentials
["username"] = username
1725 # n2vc_redesign STEP 3.2
1727 self
._write
_configuration
_status
(
1729 vca_index
=vca_index
,
1730 status
="REGISTERING",
1731 element_under_configuration
=element_under_configuration
,
1732 element_type
=element_type
,
1735 step
= "register execution environment {}".format(credentials
)
1736 self
.logger
.debug(logging_text
+ step
)
1737 ee_id
= await self
.vca_map
[vca_type
].register_execution_environment(
1738 credentials
=credentials
,
1739 namespace
=namespace
,
1744 # for compatibility with MON/POL modules, the need model and application name at database
1745 # TODO ask MON/POL if needed to not assuming anymore the format "model_name.application_name"
1746 ee_id_parts
= ee_id
.split(".")
1747 db_nsr_update
= {db_update_entry
+ "ee_id": ee_id
}
1748 if len(ee_id_parts
) >= 2:
1749 model_name
= ee_id_parts
[0]
1750 application_name
= ee_id_parts
[1]
1751 db_nsr_update
[db_update_entry
+ "model"] = model_name
1752 db_nsr_update
[db_update_entry
+ "application"] = application_name
1754 # n2vc_redesign STEP 3.3
1755 step
= "Install configuration Software"
1757 self
._write
_configuration
_status
(
1759 vca_index
=vca_index
,
1760 status
="INSTALLING SW",
1761 element_under_configuration
=element_under_configuration
,
1762 element_type
=element_type
,
1763 other_update
=db_nsr_update
,
1766 # TODO check if already done
1767 self
.logger
.debug(logging_text
+ step
)
1769 if vca_type
== "native_charm":
1770 config_primitive
= next(
1771 (p
for p
in initial_config_primitive_list
if p
["name"] == "config"),
1774 if config_primitive
:
1775 config
= self
._map
_primitive
_params
(
1776 config_primitive
, {}, deploy_params
1779 if vca_type
== "lxc_proxy_charm":
1780 if element_type
== "NS":
1781 num_units
= db_nsr
.get("config-units") or 1
1782 elif element_type
== "VNF":
1783 num_units
= db_vnfr
.get("config-units") or 1
1784 elif element_type
== "VDU":
1785 for v
in db_vnfr
["vdur"]:
1786 if vdu_id
== v
["vdu-id-ref"]:
1787 num_units
= v
.get("config-units") or 1
1789 if vca_type
!= "k8s_proxy_charm":
1790 await self
.vca_map
[vca_type
].install_configuration_sw(
1792 artifact_path
=artifact_path
,
1795 num_units
=num_units
,
1800 # write in db flag of configuration_sw already installed
1802 "nsrs", nsr_id
, {db_update_entry
+ "config_sw_installed": True}
1805 # add relations for this VCA (wait for other peers related with this VCA)
1806 is_relation_added
= await self
._add
_vca
_relations
(
1807 logging_text
=logging_text
,
1810 vca_index
=vca_index
,
1813 if not is_relation_added
:
1814 raise LcmException("Relations could not be added to VCA.")
1816 # if SSH access is required, then get execution environment SSH public
1817 # if native charm we have waited already to VM be UP
1818 if vca_type
in ("k8s_proxy_charm", "lxc_proxy_charm", "helm", "helm-v3"):
1821 # self.logger.debug("get ssh key block")
1823 config_descriptor
, ("config-access", "ssh-access", "required")
1825 # self.logger.debug("ssh key needed")
1826 # Needed to inject a ssh key
1829 ("config-access", "ssh-access", "default-user"),
1831 step
= "Install configuration Software, getting public ssh key"
1832 pub_key
= await self
.vca_map
[vca_type
].get_ee_ssh_public__key(
1833 ee_id
=ee_id
, db_dict
=db_dict
, vca_id
=vca_id
1836 step
= "Insert public key into VM user={} ssh_key={}".format(
1840 # self.logger.debug("no need to get ssh key")
1841 step
= "Waiting to VM being up and getting IP address"
1842 self
.logger
.debug(logging_text
+ step
)
1844 # default rw_mgmt_ip to None, avoiding the non definition of the variable
1847 # n2vc_redesign STEP 5.1
1848 # wait for RO (ip-address) Insert pub_key into VM
1851 rw_mgmt_ip
, services
= await self
.wait_kdu_up(
1852 logging_text
, nsr_id
, vnfr_id
, kdu_name
1854 vnfd
= self
.db
.get_one(
1856 {"_id": f
'{db_vnfr["vnfd-id"]}:{db_vnfr["revision"]}'},
1858 kdu
= get_kdu(vnfd
, kdu_name
)
1860 service
["name"] for service
in get_kdu_services(kdu
)
1862 exposed_services
= []
1863 for service
in services
:
1864 if any(s
in service
["name"] for s
in kdu_services
):
1865 exposed_services
.append(service
)
1866 await self
.vca_map
[vca_type
].exec_primitive(
1868 primitive_name
="config",
1870 "osm-config": json
.dumps(
1872 k8s
={"services": exposed_services
}
1879 # This verification is needed in order to avoid trying to add a public key
1880 # to a VM, when the VNF is a KNF (in the edge case where the user creates a VCA
1881 # for a KNF and not for its KDUs, the previous verification gives False, and the code
1882 # jumps to this block, meaning that there is the need to verify if the VNF is actually a VNF
1884 elif db_vnfr
.get("vdur"):
1885 rw_mgmt_ip
= await self
.wait_vm_up_insert_key_ro(
1895 self
.logger
.debug(logging_text
+ " VM_ip_address={}".format(rw_mgmt_ip
))
1897 # store rw_mgmt_ip in deploy params for later replacement
1898 deploy_params
["rw_mgmt_ip"] = rw_mgmt_ip
1900 # n2vc_redesign STEP 6 Execute initial config primitive
1901 step
= "execute initial config primitive"
1903 # wait for dependent primitives execution (NS -> VNF -> VDU)
1904 if initial_config_primitive_list
:
1905 await self
._wait
_dependent
_n
2vc
(nsr_id
, vca_deployed_list
, vca_index
)
1907 # stage, in function of element type: vdu, kdu, vnf or ns
1908 my_vca
= vca_deployed_list
[vca_index
]
1909 if my_vca
.get("vdu_id") or my_vca
.get("kdu_name"):
1911 stage
[0] = "Stage 3/5: running Day-1 primitives for VDU."
1912 elif my_vca
.get("member-vnf-index"):
1914 stage
[0] = "Stage 4/5: running Day-1 primitives for VNF."
1917 stage
[0] = "Stage 5/5: running Day-1 primitives for NS."
1919 self
._write
_configuration
_status
(
1920 nsr_id
=nsr_id
, vca_index
=vca_index
, status
="EXECUTING PRIMITIVE"
1923 self
._write
_op
_status
(op_id
=nslcmop_id
, stage
=stage
)
1925 check_if_terminated_needed
= True
1926 for initial_config_primitive
in initial_config_primitive_list
:
1927 # adding information on the vca_deployed if it is a NS execution environment
1928 if not vca_deployed
["member-vnf-index"]:
1929 deploy_params
["ns_config_info"] = json
.dumps(
1930 self
._get
_ns
_config
_info
(nsr_id
)
1932 # TODO check if already done
1933 primitive_params_
= self
._map
_primitive
_params
(
1934 initial_config_primitive
, {}, deploy_params
1937 step
= "execute primitive '{}' params '{}'".format(
1938 initial_config_primitive
["name"], primitive_params_
1940 self
.logger
.debug(logging_text
+ step
)
1941 await self
.vca_map
[vca_type
].exec_primitive(
1943 primitive_name
=initial_config_primitive
["name"],
1944 params_dict
=primitive_params_
,
1949 # Once some primitive has been exec, check and write at db if it needs to exec terminated primitives
1950 if check_if_terminated_needed
:
1951 if config_descriptor
.get("terminate-config-primitive"):
1953 "nsrs", nsr_id
, {db_update_entry
+ "needed_terminate": True}
1955 check_if_terminated_needed
= False
1957 # TODO register in database that primitive is done
1959 # STEP 7 Configure metrics
1960 if vca_type
== "helm" or vca_type
== "helm-v3":
1961 # TODO: review for those cases where the helm chart is a reference and
1962 # is not part of the NF package
1963 prometheus_jobs
= await self
.extract_prometheus_scrape_jobs(
1965 artifact_path
=artifact_path
,
1966 ee_config_descriptor
=ee_config_descriptor
,
1969 target_ip
=rw_mgmt_ip
,
1970 element_type
=element_type
,
1971 vnf_member_index
=db_vnfr
.get("member-vnf-index-ref", ""),
1973 vdu_index
=vdu_index
,
1975 kdu_index
=kdu_index
,
1981 {db_update_entry
+ "prometheus_jobs": prometheus_jobs
},
1984 for job
in prometheus_jobs
:
1987 {"job_name": job
["job_name"]},
1990 fail_on_empty
=False,
1993 step
= "instantiated at VCA"
1994 self
.logger
.debug(logging_text
+ step
)
1996 self
._write
_configuration
_status
(
1997 nsr_id
=nsr_id
, vca_index
=vca_index
, status
="READY"
2000 except Exception as e
: # TODO not use Exception but N2VC exception
2001 # self.update_db_2("nsrs", nsr_id, {db_update_entry + "instantiation": "FAILED"})
2003 e
, (DbException
, N2VCException
, LcmException
, asyncio
.CancelledError
)
2006 "Exception while {} : {}".format(step
, e
), exc_info
=True
2008 self
._write
_configuration
_status
(
2009 nsr_id
=nsr_id
, vca_index
=vca_index
, status
="BROKEN"
2011 raise LcmException("{}. {}".format(step
, e
)) from e
2013 def _write_ns_status(
2017 current_operation
: str,
2018 current_operation_id
: str,
2019 error_description
: str = None,
2020 error_detail
: str = None,
2021 other_update
: dict = None,
2024 Update db_nsr fields.
2027 :param current_operation:
2028 :param current_operation_id:
2029 :param error_description:
2030 :param error_detail:
2031 :param other_update: Other required changes at database if provided, will be cleared
2035 db_dict
= other_update
or {}
2038 ] = current_operation_id
# for backward compatibility
2039 db_dict
["_admin.current-operation"] = current_operation_id
2040 db_dict
["_admin.operation-type"] = (
2041 current_operation
if current_operation
!= "IDLE" else None
2043 db_dict
["currentOperation"] = current_operation
2044 db_dict
["currentOperationID"] = current_operation_id
2045 db_dict
["errorDescription"] = error_description
2046 db_dict
["errorDetail"] = error_detail
2049 db_dict
["nsState"] = ns_state
2050 self
.update_db_2("nsrs", nsr_id
, db_dict
)
2051 except DbException
as e
:
2052 self
.logger
.warn("Error writing NS status, ns={}: {}".format(nsr_id
, e
))
2054 def _write_op_status(
2058 error_message
: str = None,
2059 queuePosition
: int = 0,
2060 operation_state
: str = None,
2061 other_update
: dict = None,
2064 db_dict
= other_update
or {}
2065 db_dict
["queuePosition"] = queuePosition
2066 if isinstance(stage
, list):
2067 db_dict
["stage"] = stage
[0]
2068 db_dict
["detailed-status"] = " ".join(stage
)
2069 elif stage
is not None:
2070 db_dict
["stage"] = str(stage
)
2072 if error_message
is not None:
2073 db_dict
["errorMessage"] = error_message
2074 if operation_state
is not None:
2075 db_dict
["operationState"] = operation_state
2076 db_dict
["statusEnteredTime"] = time()
2077 self
.update_db_2("nslcmops", op_id
, db_dict
)
2078 except DbException
as e
:
2080 "Error writing OPERATION status for op_id: {} -> {}".format(op_id
, e
)
2083 def _write_all_config_status(self
, db_nsr
: dict, status
: str):
2085 nsr_id
= db_nsr
["_id"]
2086 # configurationStatus
2087 config_status
= db_nsr
.get("configurationStatus")
2090 "configurationStatus.{}.status".format(index
): status
2091 for index
, v
in enumerate(config_status
)
2095 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2097 except DbException
as e
:
2099 "Error writing all configuration status, ns={}: {}".format(nsr_id
, e
)
2102 def _write_configuration_status(
2107 element_under_configuration
: str = None,
2108 element_type
: str = None,
2109 other_update
: dict = None,
2111 # self.logger.debug('_write_configuration_status(): vca_index={}, status={}'
2112 # .format(vca_index, status))
2115 db_path
= "configurationStatus.{}.".format(vca_index
)
2116 db_dict
= other_update
or {}
2118 db_dict
[db_path
+ "status"] = status
2119 if element_under_configuration
:
2121 db_path
+ "elementUnderConfiguration"
2122 ] = element_under_configuration
2124 db_dict
[db_path
+ "elementType"] = element_type
2125 self
.update_db_2("nsrs", nsr_id
, db_dict
)
2126 except DbException
as e
:
2128 "Error writing configuration status={}, ns={}, vca_index={}: {}".format(
2129 status
, nsr_id
, vca_index
, e
2133 async def _do_placement(self
, logging_text
, db_nslcmop
, db_vnfrs
):
2135 Check and computes the placement, (vim account where to deploy). If it is decided by an external tool, it
2136 sends the request via kafka and wait until the result is wrote at database (nslcmops _admin.plca).
2137 Database is used because the result can be obtained from a different LCM worker in case of HA.
2138 :param logging_text: contains the prefix for logging, with the ns and nslcmop identifiers
2139 :param db_nslcmop: database content of nslcmop
2140 :param db_vnfrs: database content of vnfrs, indexed by member-vnf-index.
2141 :return: True if some modification is done. Modifies database vnfrs and parameter db_vnfr with the
2142 computed 'vim-account-id'
2145 nslcmop_id
= db_nslcmop
["_id"]
2146 placement_engine
= deep_get(db_nslcmop
, ("operationParams", "placement-engine"))
2147 if placement_engine
== "PLA":
2149 logging_text
+ "Invoke and wait for placement optimization"
2151 await self
.msg
.aiowrite("pla", "get_placement", {"nslcmopId": nslcmop_id
})
2152 db_poll_interval
= 5
2153 wait
= db_poll_interval
* 10
2155 while not pla_result
and wait
>= 0:
2156 await asyncio
.sleep(db_poll_interval
)
2157 wait
-= db_poll_interval
2158 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
2159 pla_result
= deep_get(db_nslcmop
, ("_admin", "pla"))
2163 "Placement timeout for nslcmopId={}".format(nslcmop_id
)
2166 for pla_vnf
in pla_result
["vnf"]:
2167 vnfr
= db_vnfrs
.get(pla_vnf
["member-vnf-index"])
2168 if not pla_vnf
.get("vimAccountId") or not vnfr
:
2173 {"_id": vnfr
["_id"]},
2174 {"vim-account-id": pla_vnf
["vimAccountId"]},
2177 vnfr
["vim-account-id"] = pla_vnf
["vimAccountId"]
2180 def _gather_vnfr_healing_alerts(self
, vnfr
, vnfd
):
2182 nsr_id
= vnfr
["nsr-id-ref"]
2183 df
= vnfd
.get("df", [{}])[0]
2184 # Checking for auto-healing configuration
2185 if "healing-aspect" in df
:
2186 healing_aspects
= df
["healing-aspect"]
2187 for healing
in healing_aspects
:
2188 for healing_policy
in healing
.get("healing-policy", ()):
2189 vdu_id
= healing_policy
["vdu-id"]
2191 (vdur
for vdur
in vnfr
["vdur"] if vdu_id
== vdur
["vdu-id-ref"]),
2196 metric_name
= "vm_status"
2197 vdu_name
= vdur
.get("name")
2198 vnf_member_index
= vnfr
["member-vnf-index-ref"]
2200 name
= f
"healing_{uuid}"
2201 action
= healing_policy
2202 # action_on_recovery = healing.get("action-on-recovery")
2203 # cooldown_time = healing.get("cooldown-time")
2204 # day1 = healing.get("day1")
2208 "metric": metric_name
,
2211 "vnf_member_index": vnf_member_index
,
2212 "vdu_name": vdu_name
,
2214 "alarm_status": "ok",
2215 "action_type": "healing",
2218 alerts
.append(alert
)
2221 def _gather_vnfr_scaling_alerts(self
, vnfr
, vnfd
):
2223 nsr_id
= vnfr
["nsr-id-ref"]
2224 df
= vnfd
.get("df", [{}])[0]
2225 # Checking for auto-scaling configuration
2226 if "scaling-aspect" in df
:
2227 scaling_aspects
= df
["scaling-aspect"]
2228 all_vnfd_monitoring_params
= {}
2229 for ivld
in vnfd
.get("int-virtual-link-desc", ()):
2230 for mp
in ivld
.get("monitoring-parameters", ()):
2231 all_vnfd_monitoring_params
[mp
.get("id")] = mp
2232 for vdu
in vnfd
.get("vdu", ()):
2233 for mp
in vdu
.get("monitoring-parameter", ()):
2234 all_vnfd_monitoring_params
[mp
.get("id")] = mp
2235 for df
in vnfd
.get("df", ()):
2236 for mp
in df
.get("monitoring-parameter", ()):
2237 all_vnfd_monitoring_params
[mp
.get("id")] = mp
2238 for scaling_aspect
in scaling_aspects
:
2239 scaling_group_name
= scaling_aspect
.get("name", "")
2240 # Get monitored VDUs
2241 all_monitored_vdus
= set()
2242 for delta
in scaling_aspect
.get("aspect-delta-details", {}).get(
2245 for vdu_delta
in delta
.get("vdu-delta", ()):
2246 all_monitored_vdus
.add(vdu_delta
.get("id"))
2247 monitored_vdurs
= list(
2249 lambda vdur
: vdur
["vdu-id-ref"] in all_monitored_vdus
,
2253 if not monitored_vdurs
:
2255 "Scaling criteria is referring to a vnf-monitoring-param that does not contain a reference to a vdu or vnf metric"
2258 for scaling_policy
in scaling_aspect
.get("scaling-policy", ()):
2259 if scaling_policy
["scaling-type"] != "automatic":
2261 threshold_time
= scaling_policy
.get("threshold-time", "1")
2262 cooldown_time
= scaling_policy
.get("cooldown-time", "0")
2263 for scaling_criteria
in scaling_policy
["scaling-criteria"]:
2264 monitoring_param_ref
= scaling_criteria
.get(
2265 "vnf-monitoring-param-ref"
2267 vnf_monitoring_param
= all_vnfd_monitoring_params
[
2268 monitoring_param_ref
2270 for vdur
in monitored_vdurs
:
2271 vdu_id
= vdur
["vdu-id-ref"]
2272 metric_name
= vnf_monitoring_param
.get("performance-metric")
2273 metric_name
= f
"osm_{metric_name}"
2274 vnf_member_index
= vnfr
["member-vnf-index-ref"]
2275 scalein_threshold
= scaling_criteria
.get(
2276 "scale-in-threshold"
2278 scaleout_threshold
= scaling_criteria
.get(
2279 "scale-out-threshold"
2281 # Looking for min/max-number-of-instances
2282 instances_min_number
= 1
2283 instances_max_number
= 1
2284 vdu_profile
= df
["vdu-profile"]
2287 item
for item
in vdu_profile
if item
["id"] == vdu_id
2289 instances_min_number
= profile
.get(
2290 "min-number-of-instances", 1
2292 instances_max_number
= profile
.get(
2293 "max-number-of-instances", 1
2296 if scalein_threshold
:
2298 name
= f
"scalein_{uuid}"
2299 operation
= scaling_criteria
[
2300 "scale-in-relational-operation"
2302 rel_operator
= self
.rel_operation_types
.get(
2305 metric_selector
= f
'{metric_name}{{ns_id="{nsr_id}", vnf_member_index="{vnf_member_index}", vdu_id="{vdu_id}"}}'
2306 expression
= f
"(count ({metric_selector}) > {instances_min_number}) and (avg({metric_selector}) {rel_operator} {scalein_threshold})"
2309 "vnf_member_index": vnf_member_index
,
2315 "for": str(threshold_time
) + "m",
2318 action
= scaling_policy
2320 "scaling-group": scaling_group_name
,
2321 "cooldown-time": cooldown_time
,
2326 "metric": metric_name
,
2329 "vnf_member_index": vnf_member_index
,
2332 "alarm_status": "ok",
2333 "action_type": "scale_in",
2335 "prometheus_config": prom_cfg
,
2337 alerts
.append(alert
)
2339 if scaleout_threshold
:
2341 name
= f
"scaleout_{uuid}"
2342 operation
= scaling_criteria
[
2343 "scale-out-relational-operation"
2345 rel_operator
= self
.rel_operation_types
.get(
2348 metric_selector
= f
'{metric_name}{{ns_id="{nsr_id}", vnf_member_index="{vnf_member_index}", vdu_id="{vdu_id}"}}'
2349 expression
= f
"(count ({metric_selector}) < {instances_max_number}) and (avg({metric_selector}) {rel_operator} {scaleout_threshold})"
2352 "vnf_member_index": vnf_member_index
,
2358 "for": str(threshold_time
) + "m",
2361 action
= scaling_policy
2363 "scaling-group": scaling_group_name
,
2364 "cooldown-time": cooldown_time
,
2369 "metric": metric_name
,
2372 "vnf_member_index": vnf_member_index
,
2375 "alarm_status": "ok",
2376 "action_type": "scale_out",
2378 "prometheus_config": prom_cfg
,
2380 alerts
.append(alert
)
2383 def _gather_vnfr_alarm_alerts(self
, vnfr
, vnfd
):
2385 nsr_id
= vnfr
["nsr-id-ref"]
2386 vnf_member_index
= vnfr
["member-vnf-index-ref"]
2388 # Checking for VNF alarm configuration
2389 for vdur
in vnfr
["vdur"]:
2390 vdu_id
= vdur
["vdu-id-ref"]
2391 vdu
= next(filter(lambda vdu
: vdu
["id"] == vdu_id
, vnfd
["vdu"]))
2393 # Get VDU monitoring params, since alerts are based on them
2394 vdu_monitoring_params
= {}
2395 for mp
in vdu
.get("monitoring-parameter", []):
2396 vdu_monitoring_params
[mp
.get("id")] = mp
2397 if not vdu_monitoring_params
:
2399 "VDU alarm refers to a VDU monitoring param, but there are no VDU monitoring params in the VDU"
2402 # Get alarms in the VDU
2403 alarm_descriptors
= vdu
["alarm"]
2404 # Create VDU alarms for each alarm in the VDU
2405 for alarm_descriptor
in alarm_descriptors
:
2406 # Check that the VDU alarm refers to a proper monitoring param
2407 alarm_monitoring_param
= alarm_descriptor
.get(
2408 "vnf-monitoring-param-ref", ""
2410 vdu_specific_monitoring_param
= vdu_monitoring_params
.get(
2411 alarm_monitoring_param
, {}
2413 if not vdu_specific_monitoring_param
:
2415 "VDU alarm refers to a VDU monitoring param not present in the VDU"
2418 metric_name
= vdu_specific_monitoring_param
.get(
2419 "performance-metric"
2423 "VDU alarm refers to a VDU monitoring param that has no associated performance-metric"
2426 # Set params of the alarm to be created in Prometheus
2427 metric_name
= f
"osm_{metric_name}"
2428 metric_threshold
= alarm_descriptor
.get("value")
2430 alert_name
= f
"vdu_alarm_{uuid}"
2431 operation
= alarm_descriptor
["operation"]
2432 rel_operator
= self
.rel_operation_types
.get(operation
, "<=")
2433 metric_selector
= f
'{metric_name}{{ns_id="{nsr_id}", vnf_member_index="{vnf_member_index}", vdu_id="{vdu_id}"}}'
2434 expression
= f
"{metric_selector} {rel_operator} {metric_threshold}"
2437 "vnf_member_index": vnf_member_index
,
2439 "vdu_name": "{{ $labels.vdu_name }}",
2442 "alert": alert_name
,
2444 "for": "1m", # default value. Ideally, this should be related to an IM param, but there is not such param
2447 alarm_action
= dict()
2448 for action_type
in ["ok", "insufficient-data", "alarm"]:
2450 "actions" in alarm_descriptor
2451 and action_type
in alarm_descriptor
["actions"]
2453 alarm_action
[action_type
] = alarm_descriptor
["actions"][
2459 "metric": metric_name
,
2462 "vnf_member_index": vnf_member_index
,
2465 "alarm_status": "ok",
2466 "action_type": "vdu_alarm",
2467 "action": alarm_action
,
2468 "prometheus_config": prom_cfg
,
2470 alerts
.append(alert
)
2473 def update_nsrs_with_pla_result(self
, params
):
2475 nslcmop_id
= deep_get(params
, ("placement", "nslcmopId"))
2477 "nslcmops", nslcmop_id
, {"_admin.pla": params
.get("placement")}
2479 except Exception as e
:
2480 self
.logger
.warn("Update failed for nslcmop_id={}:{}".format(nslcmop_id
, e
))
2482 async def instantiate(self
, nsr_id
, nslcmop_id
):
2485 :param nsr_id: ns instance to deploy
2486 :param nslcmop_id: operation to run
2490 # Try to lock HA task here
2491 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA("ns", "nslcmops", nslcmop_id
)
2492 if not task_is_locked_by_me
:
2494 "instantiate() task is not locked by me, ns={}".format(nsr_id
)
2498 logging_text
= "Task ns={} instantiate={} ".format(nsr_id
, nslcmop_id
)
2499 self
.logger
.debug(logging_text
+ "Enter")
2501 # get all needed from database
2503 # database nsrs record
2506 # database nslcmops record
2509 # update operation on nsrs
2511 # update operation on nslcmops
2512 db_nslcmop_update
= {}
2514 timeout_ns_deploy
= self
.timeout
.ns_deploy
2516 nslcmop_operation_state
= None
2517 db_vnfrs
= {} # vnf's info indexed by member-index
2519 tasks_dict_info
= {} # from task to info text
2523 "Stage 1/5: preparation of the environment.",
2524 "Waiting for previous operations to terminate.",
2527 # ^ stage, step, VIM progress
2529 # wait for any previous tasks in process
2530 await self
.lcm_tasks
.waitfor_related_HA("ns", "nslcmops", nslcmop_id
)
2532 # STEP 0: Reading database (nslcmops, nsrs, nsds, vnfrs, vnfds)
2533 stage
[1] = "Reading from database."
2534 # nsState="BUILDING", currentOperation="INSTANTIATING", currentOperationID=nslcmop_id
2535 db_nsr_update
["detailed-status"] = "creating"
2536 db_nsr_update
["operational-status"] = "init"
2537 self
._write
_ns
_status
(
2539 ns_state
="BUILDING",
2540 current_operation
="INSTANTIATING",
2541 current_operation_id
=nslcmop_id
,
2542 other_update
=db_nsr_update
,
2544 self
._write
_op
_status
(op_id
=nslcmop_id
, stage
=stage
, queuePosition
=0)
2546 # read from db: operation
2547 stage
[1] = "Getting nslcmop={} from db.".format(nslcmop_id
)
2548 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
2549 if db_nslcmop
["operationParams"].get("additionalParamsForVnf"):
2550 db_nslcmop
["operationParams"]["additionalParamsForVnf"] = json
.loads(
2551 db_nslcmop
["operationParams"]["additionalParamsForVnf"]
2553 ns_params
= db_nslcmop
.get("operationParams")
2554 if ns_params
and ns_params
.get("timeout_ns_deploy"):
2555 timeout_ns_deploy
= ns_params
["timeout_ns_deploy"]
2558 stage
[1] = "Getting nsr={} from db.".format(nsr_id
)
2559 self
.logger
.debug(logging_text
+ stage
[1])
2560 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2561 stage
[1] = "Getting nsd={} from db.".format(db_nsr
["nsd-id"])
2562 self
.logger
.debug(logging_text
+ stage
[1])
2563 nsd
= self
.db
.get_one("nsds", {"_id": db_nsr
["nsd-id"]})
2564 self
.fs
.sync(db_nsr
["nsd-id"])
2566 # nsr_name = db_nsr["name"] # TODO short-name??
2568 # read from db: vnf's of this ns
2569 stage
[1] = "Getting vnfrs from db."
2570 self
.logger
.debug(logging_text
+ stage
[1])
2571 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2573 # read from db: vnfd's for every vnf
2574 db_vnfds
= [] # every vnfd data
2576 # for each vnf in ns, read vnfd
2577 for vnfr
in db_vnfrs_list
:
2578 if vnfr
.get("kdur"):
2580 for kdur
in vnfr
["kdur"]:
2581 if kdur
.get("additionalParams"):
2582 kdur
["additionalParams"] = json
.loads(
2583 kdur
["additionalParams"]
2585 kdur_list
.append(kdur
)
2586 vnfr
["kdur"] = kdur_list
2588 db_vnfrs
[vnfr
["member-vnf-index-ref"]] = vnfr
2589 vnfd_id
= vnfr
["vnfd-id"]
2590 vnfd_ref
= vnfr
["vnfd-ref"]
2591 self
.fs
.sync(vnfd_id
)
2593 # if we haven't this vnfd, read it from db
2594 if vnfd_id
not in db_vnfds
:
2596 stage
[1] = "Getting vnfd={} id='{}' from db.".format(
2599 self
.logger
.debug(logging_text
+ stage
[1])
2600 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
2603 db_vnfds
.append(vnfd
)
2605 # Get or generates the _admin.deployed.VCA list
2606 vca_deployed_list
= None
2607 if db_nsr
["_admin"].get("deployed"):
2608 vca_deployed_list
= db_nsr
["_admin"]["deployed"].get("VCA")
2609 if vca_deployed_list
is None:
2610 vca_deployed_list
= []
2611 configuration_status_list
= []
2612 db_nsr_update
["_admin.deployed.VCA"] = vca_deployed_list
2613 db_nsr_update
["configurationStatus"] = configuration_status_list
2614 # add _admin.deployed.VCA to db_nsr dictionary, value=vca_deployed_list
2615 populate_dict(db_nsr
, ("_admin", "deployed", "VCA"), vca_deployed_list
)
2616 elif isinstance(vca_deployed_list
, dict):
2617 # maintain backward compatibility. Change a dict to list at database
2618 vca_deployed_list
= list(vca_deployed_list
.values())
2619 db_nsr_update
["_admin.deployed.VCA"] = vca_deployed_list
2620 populate_dict(db_nsr
, ("_admin", "deployed", "VCA"), vca_deployed_list
)
2623 deep_get(db_nsr
, ("_admin", "deployed", "RO", "vnfd")), list
2625 populate_dict(db_nsr
, ("_admin", "deployed", "RO", "vnfd"), [])
2626 db_nsr_update
["_admin.deployed.RO.vnfd"] = []
2628 # set state to INSTANTIATED. When instantiated NBI will not delete directly
2629 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
2630 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2632 "vnfrs", {"nsr-id-ref": nsr_id
}, {"_admin.nsState": "INSTANTIATED"}
2635 # n2vc_redesign STEP 2 Deploy Network Scenario
2636 stage
[0] = "Stage 2/5: deployment of KDUs, VMs and execution environments."
2637 self
._write
_op
_status
(op_id
=nslcmop_id
, stage
=stage
)
2639 stage
[1] = "Deploying KDUs."
2640 # self.logger.debug(logging_text + "Before deploy_kdus")
2641 # Call to deploy_kdus in case exists the "vdu:kdu" param
2642 await self
.deploy_kdus(
2643 logging_text
=logging_text
,
2645 nslcmop_id
=nslcmop_id
,
2648 task_instantiation_info
=tasks_dict_info
,
2651 stage
[1] = "Getting VCA public key."
2652 # n2vc_redesign STEP 1 Get VCA public ssh-key
2653 # feature 1429. Add n2vc public key to needed VMs
2654 n2vc_key
= self
.n2vc
.get_public_key()
2655 n2vc_key_list
= [n2vc_key
]
2656 if self
.vca_config
.public_key
:
2657 n2vc_key_list
.append(self
.vca_config
.public_key
)
2659 stage
[1] = "Deploying NS at VIM."
2660 task_ro
= asyncio
.ensure_future(
2661 self
.instantiate_RO(
2662 logging_text
=logging_text
,
2666 db_nslcmop
=db_nslcmop
,
2669 n2vc_key_list
=n2vc_key_list
,
2673 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_RO", task_ro
)
2674 tasks_dict_info
[task_ro
] = "Deploying at VIM"
2676 # n2vc_redesign STEP 3 to 6 Deploy N2VC
2677 stage
[1] = "Deploying Execution Environments."
2678 self
.logger
.debug(logging_text
+ stage
[1])
2680 # create namespace and certificate if any helm based EE is present in the NS
2681 if check_helm_ee_in_ns(db_vnfds
):
2682 await self
.vca_map
["helm-v3"].setup_ns_namespace(
2685 # create TLS certificates
2686 await self
.vca_map
["helm-v3"].create_tls_certificate(
2687 secret_name
=self
.EE_TLS_NAME
,
2690 usage
="server auth",
2694 nsi_id
= None # TODO put nsi_id when this nsr belongs to a NSI
2695 for vnf_profile
in get_vnf_profiles(nsd
):
2696 vnfd_id
= vnf_profile
["vnfd-id"]
2697 vnfd
= find_in_list(db_vnfds
, lambda a_vnf
: a_vnf
["id"] == vnfd_id
)
2698 member_vnf_index
= str(vnf_profile
["id"])
2699 db_vnfr
= db_vnfrs
[member_vnf_index
]
2700 base_folder
= vnfd
["_admin"]["storage"]
2707 # Get additional parameters
2708 deploy_params
= {"OSM": get_osm_params(db_vnfr
)}
2709 if db_vnfr
.get("additionalParamsForVnf"):
2710 deploy_params
.update(
2711 parse_yaml_strings(db_vnfr
["additionalParamsForVnf"].copy())
2714 descriptor_config
= get_configuration(vnfd
, vnfd
["id"])
2715 if descriptor_config
:
2717 logging_text
=logging_text
2718 + "member_vnf_index={} ".format(member_vnf_index
),
2721 nslcmop_id
=nslcmop_id
,
2727 member_vnf_index
=member_vnf_index
,
2728 vdu_index
=vdu_index
,
2729 kdu_index
=kdu_index
,
2731 deploy_params
=deploy_params
,
2732 descriptor_config
=descriptor_config
,
2733 base_folder
=base_folder
,
2734 task_instantiation_info
=tasks_dict_info
,
2738 # Deploy charms for each VDU that supports one.
2739 for vdud
in get_vdu_list(vnfd
):
2741 descriptor_config
= get_configuration(vnfd
, vdu_id
)
2742 vdur
= find_in_list(
2743 db_vnfr
["vdur"], lambda vdu
: vdu
["vdu-id-ref"] == vdu_id
2746 if vdur
.get("additionalParams"):
2747 deploy_params_vdu
= parse_yaml_strings(vdur
["additionalParams"])
2749 deploy_params_vdu
= deploy_params
2750 deploy_params_vdu
["OSM"] = get_osm_params(
2751 db_vnfr
, vdu_id
, vdu_count_index
=0
2753 vdud_count
= get_number_of_instances(vnfd
, vdu_id
)
2755 self
.logger
.debug("VDUD > {}".format(vdud
))
2757 "Descriptor config > {}".format(descriptor_config
)
2759 if descriptor_config
:
2763 for vdu_index
in range(vdud_count
):
2764 # TODO vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
2766 logging_text
=logging_text
2767 + "member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
2768 member_vnf_index
, vdu_id
, vdu_index
2772 nslcmop_id
=nslcmop_id
,
2778 kdu_index
=kdu_index
,
2779 member_vnf_index
=member_vnf_index
,
2780 vdu_index
=vdu_index
,
2782 deploy_params
=deploy_params_vdu
,
2783 descriptor_config
=descriptor_config
,
2784 base_folder
=base_folder
,
2785 task_instantiation_info
=tasks_dict_info
,
2788 for kdud
in get_kdu_list(vnfd
):
2789 kdu_name
= kdud
["name"]
2790 descriptor_config
= get_configuration(vnfd
, kdu_name
)
2791 if descriptor_config
:
2795 kdu_index
, kdur
= next(
2797 for x
in enumerate(db_vnfr
["kdur"])
2798 if x
[1]["kdu-name"] == kdu_name
2800 deploy_params_kdu
= {"OSM": get_osm_params(db_vnfr
)}
2801 if kdur
.get("additionalParams"):
2802 deploy_params_kdu
.update(
2803 parse_yaml_strings(kdur
["additionalParams"].copy())
2807 logging_text
=logging_text
,
2810 nslcmop_id
=nslcmop_id
,
2816 member_vnf_index
=member_vnf_index
,
2817 vdu_index
=vdu_index
,
2818 kdu_index
=kdu_index
,
2820 deploy_params
=deploy_params_kdu
,
2821 descriptor_config
=descriptor_config
,
2822 base_folder
=base_folder
,
2823 task_instantiation_info
=tasks_dict_info
,
2827 # Check if each vnf has exporter for metric collection if so update prometheus job records
2828 if "exporters-endpoints" in vnfd
.get("df")[0]:
2829 exporter_config
= vnfd
.get("df")[0].get("exporters-endpoints")
2830 self
.logger
.debug("exporter config :{}".format(exporter_config
))
2831 artifact_path
= "{}/{}/{}".format(
2832 base_folder
["folder"],
2833 base_folder
["pkg-dir"],
2834 "exporter-endpoint",
2837 ee_config_descriptor
= exporter_config
2838 vnfr_id
= db_vnfr
["id"]
2839 rw_mgmt_ip
= await self
.wait_vm_up_insert_key_ro(
2848 self
.logger
.debug("rw_mgmt_ip:{}".format(rw_mgmt_ip
))
2849 self
.logger
.debug("Artifact_path:{}".format(artifact_path
))
2850 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnfr_id
})
2851 vdu_id_for_prom
= None
2852 vdu_index_for_prom
= None
2853 for x
in get_iterable(db_vnfr
, "vdur"):
2854 vdu_id_for_prom
= x
.get("vdu-id-ref")
2855 vdu_index_for_prom
= x
.get("count-index")
2856 prometheus_jobs
= await self
.extract_prometheus_scrape_jobs(
2858 artifact_path
=artifact_path
,
2859 ee_config_descriptor
=ee_config_descriptor
,
2862 target_ip
=rw_mgmt_ip
,
2864 vdu_id
=vdu_id_for_prom
,
2865 vdu_index
=vdu_index_for_prom
,
2868 self
.logger
.debug("Prometheus job:{}".format(prometheus_jobs
))
2870 db_nsr_update
["_admin.deployed.prometheus_jobs"] = prometheus_jobs
2877 for job
in prometheus_jobs
:
2880 {"job_name": job
["job_name"]},
2883 fail_on_empty
=False,
2886 # Check if this NS has a charm configuration
2887 descriptor_config
= nsd
.get("ns-configuration")
2888 if descriptor_config
and descriptor_config
.get("juju"):
2891 member_vnf_index
= None
2898 # Get additional parameters
2899 deploy_params
= {"OSM": {"vim_account_id": ns_params
["vimAccountId"]}}
2900 if db_nsr
.get("additionalParamsForNs"):
2901 deploy_params
.update(
2902 parse_yaml_strings(db_nsr
["additionalParamsForNs"].copy())
2904 base_folder
= nsd
["_admin"]["storage"]
2906 logging_text
=logging_text
,
2909 nslcmop_id
=nslcmop_id
,
2915 member_vnf_index
=member_vnf_index
,
2916 vdu_index
=vdu_index
,
2917 kdu_index
=kdu_index
,
2919 deploy_params
=deploy_params
,
2920 descriptor_config
=descriptor_config
,
2921 base_folder
=base_folder
,
2922 task_instantiation_info
=tasks_dict_info
,
2926 # rest of staff will be done at finally
2929 ROclient
.ROClientException
,
2935 logging_text
+ "Exit Exception while '{}': {}".format(stage
[1], e
)
2938 except asyncio
.CancelledError
:
2940 logging_text
+ "Cancelled Exception while '{}'".format(stage
[1])
2942 exc
= "Operation was cancelled"
2943 except Exception as e
:
2944 exc
= traceback
.format_exc()
2945 self
.logger
.critical(
2946 logging_text
+ "Exit Exception while '{}': {}".format(stage
[1], e
),
2951 error_list
.append(str(exc
))
2953 # wait for pending tasks
2955 stage
[1] = "Waiting for instantiate pending tasks."
2956 self
.logger
.debug(logging_text
+ stage
[1])
2957 error_list
+= await self
._wait
_for
_tasks
(
2965 stage
[1] = stage
[2] = ""
2966 except asyncio
.CancelledError
:
2967 error_list
.append("Cancelled")
2968 # TODO cancel all tasks
2969 except Exception as exc
:
2970 error_list
.append(str(exc
))
2972 # update operation-status
2973 db_nsr_update
["operational-status"] = "running"
2974 # let's begin with VCA 'configured' status (later we can change it)
2975 db_nsr_update
["config-status"] = "configured"
2976 for task
, task_name
in tasks_dict_info
.items():
2977 if not task
.done() or task
.cancelled() or task
.exception():
2978 if task_name
.startswith(self
.task_name_deploy_vca
):
2979 # A N2VC task is pending
2980 db_nsr_update
["config-status"] = "failed"
2982 # RO or KDU task is pending
2983 db_nsr_update
["operational-status"] = "failed"
2985 # update status at database
2987 error_detail
= ". ".join(error_list
)
2988 self
.logger
.error(logging_text
+ error_detail
)
2989 error_description_nslcmop
= "{} Detail: {}".format(
2990 stage
[0], error_detail
2992 error_description_nsr
= "Operation: INSTANTIATING.{}, {}".format(
2993 nslcmop_id
, stage
[0]
2996 db_nsr_update
["detailed-status"] = (
2997 error_description_nsr
+ " Detail: " + error_detail
2999 db_nslcmop_update
["detailed-status"] = error_detail
3000 nslcmop_operation_state
= "FAILED"
3004 error_description_nsr
= error_description_nslcmop
= None
3006 db_nsr_update
["detailed-status"] = "Done"
3007 db_nslcmop_update
["detailed-status"] = "Done"
3008 nslcmop_operation_state
= "COMPLETED"
3009 # Gather auto-healing and auto-scaling alerts for each vnfr
3012 for vnfr
in self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
}):
3014 (sub
for sub
in db_vnfds
if sub
["_id"] == vnfr
["vnfd-id"]), None
3016 healing_alerts
= self
._gather
_vnfr
_healing
_alerts
(vnfr
, vnfd
)
3017 for alert
in healing_alerts
:
3018 self
.logger
.info(f
"Storing healing alert in MongoDB: {alert}")
3019 self
.db
.create("alerts", alert
)
3021 scaling_alerts
= self
._gather
_vnfr
_scaling
_alerts
(vnfr
, vnfd
)
3022 for alert
in scaling_alerts
:
3023 self
.logger
.info(f
"Storing scaling alert in MongoDB: {alert}")
3024 self
.db
.create("alerts", alert
)
3026 alarm_alerts
= self
._gather
_vnfr
_alarm
_alerts
(vnfr
, vnfd
)
3027 for alert
in alarm_alerts
:
3028 self
.logger
.info(f
"Storing VNF alarm alert in MongoDB: {alert}")
3029 self
.db
.create("alerts", alert
)
3031 self
._write
_ns
_status
(
3034 current_operation
="IDLE",
3035 current_operation_id
=None,
3036 error_description
=error_description_nsr
,
3037 error_detail
=error_detail
,
3038 other_update
=db_nsr_update
,
3040 self
._write
_op
_status
(
3043 error_message
=error_description_nslcmop
,
3044 operation_state
=nslcmop_operation_state
,
3045 other_update
=db_nslcmop_update
,
3048 if nslcmop_operation_state
:
3050 await self
.msg
.aiowrite(
3055 "nslcmop_id": nslcmop_id
,
3056 "operationState": nslcmop_operation_state
,
3057 "startTime": db_nslcmop
["startTime"],
3058 "links": db_nslcmop
["links"],
3059 "operationParams": {
3060 "nsInstanceId": nsr_id
,
3061 "nsdId": db_nsr
["nsd-id"],
3065 except Exception as e
:
3067 logging_text
+ "kafka_write notification Exception {}".format(e
)
3070 self
.logger
.debug(logging_text
+ "Exit")
3071 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_instantiate")
3073 def _get_vnfd(self
, vnfd_id
: str, projects_read
: str, cached_vnfds
: Dict
[str, Any
]):
3074 if vnfd_id
not in cached_vnfds
:
3075 cached_vnfds
[vnfd_id
] = self
.db
.get_one(
3076 "vnfds", {"id": vnfd_id
, "_admin.projects_read": projects_read
}
3078 return cached_vnfds
[vnfd_id
]
3080 def _get_vnfr(self
, nsr_id
: str, vnf_profile_id
: str, cached_vnfrs
: Dict
[str, Any
]):
3081 if vnf_profile_id
not in cached_vnfrs
:
3082 cached_vnfrs
[vnf_profile_id
] = self
.db
.get_one(
3085 "member-vnf-index-ref": vnf_profile_id
,
3086 "nsr-id-ref": nsr_id
,
3089 return cached_vnfrs
[vnf_profile_id
]
3091 def _is_deployed_vca_in_relation(
3092 self
, vca
: DeployedVCA
, relation
: Relation
3095 for endpoint
in (relation
.provider
, relation
.requirer
):
3096 if endpoint
["kdu-resource-profile-id"]:
3099 vca
.vnf_profile_id
== endpoint
.vnf_profile_id
3100 and vca
.vdu_profile_id
== endpoint
.vdu_profile_id
3101 and vca
.execution_environment_ref
== endpoint
.execution_environment_ref
3107 def _update_ee_relation_data_with_implicit_data(
3108 self
, nsr_id
, nsd
, ee_relation_data
, cached_vnfds
, vnf_profile_id
: str = None
3110 ee_relation_data
= safe_get_ee_relation(
3111 nsr_id
, ee_relation_data
, vnf_profile_id
=vnf_profile_id
3113 ee_relation_level
= EELevel
.get_level(ee_relation_data
)
3114 if (ee_relation_level
in (EELevel
.VNF
, EELevel
.VDU
)) and not ee_relation_data
[
3115 "execution-environment-ref"
3117 vnf_profile
= get_vnf_profile(nsd
, ee_relation_data
["vnf-profile-id"])
3118 vnfd_id
= vnf_profile
["vnfd-id"]
3119 project
= nsd
["_admin"]["projects_read"][0]
3120 db_vnfd
= self
._get
_vnfd
(vnfd_id
, project
, cached_vnfds
)
3123 if ee_relation_level
== EELevel
.VNF
3124 else ee_relation_data
["vdu-profile-id"]
3126 ee
= get_juju_ee_ref(db_vnfd
, entity_id
)
3129 f
"not execution environments found for ee_relation {ee_relation_data}"
3131 ee_relation_data
["execution-environment-ref"] = ee
["id"]
3132 return ee_relation_data
3134 def _get_ns_relations(
3137 nsd
: Dict
[str, Any
],
3139 cached_vnfds
: Dict
[str, Any
],
3140 ) -> List
[Relation
]:
3142 db_ns_relations
= get_ns_configuration_relation_list(nsd
)
3143 for r
in db_ns_relations
:
3144 provider_dict
= None
3145 requirer_dict
= None
3146 if all(key
in r
for key
in ("provider", "requirer")):
3147 provider_dict
= r
["provider"]
3148 requirer_dict
= r
["requirer"]
3149 elif "entities" in r
:
3150 provider_id
= r
["entities"][0]["id"]
3153 "endpoint": r
["entities"][0]["endpoint"],
3155 if provider_id
!= nsd
["id"]:
3156 provider_dict
["vnf-profile-id"] = provider_id
3157 requirer_id
= r
["entities"][1]["id"]
3160 "endpoint": r
["entities"][1]["endpoint"],
3162 if requirer_id
!= nsd
["id"]:
3163 requirer_dict
["vnf-profile-id"] = requirer_id
3166 "provider/requirer or entities must be included in the relation."
3168 relation_provider
= self
._update
_ee
_relation
_data
_with
_implicit
_data
(
3169 nsr_id
, nsd
, provider_dict
, cached_vnfds
3171 relation_requirer
= self
._update
_ee
_relation
_data
_with
_implicit
_data
(
3172 nsr_id
, nsd
, requirer_dict
, cached_vnfds
3174 provider
= EERelation(relation_provider
)
3175 requirer
= EERelation(relation_requirer
)
3176 relation
= Relation(r
["name"], provider
, requirer
)
3177 vca_in_relation
= self
._is
_deployed
_vca
_in
_relation
(vca
, relation
)
3179 relations
.append(relation
)
3182 def _get_vnf_relations(
3185 nsd
: Dict
[str, Any
],
3187 cached_vnfds
: Dict
[str, Any
],
3188 ) -> List
[Relation
]:
3190 if vca
.target_element
== "ns":
3191 self
.logger
.debug("VCA is a NS charm, not a VNF.")
3193 vnf_profile
= get_vnf_profile(nsd
, vca
.vnf_profile_id
)
3194 vnf_profile_id
= vnf_profile
["id"]
3195 vnfd_id
= vnf_profile
["vnfd-id"]
3196 project
= nsd
["_admin"]["projects_read"][0]
3197 db_vnfd
= self
._get
_vnfd
(vnfd_id
, project
, cached_vnfds
)
3198 db_vnf_relations
= get_relation_list(db_vnfd
, vnfd_id
)
3199 for r
in db_vnf_relations
:
3200 provider_dict
= None
3201 requirer_dict
= None
3202 if all(key
in r
for key
in ("provider", "requirer")):
3203 provider_dict
= r
["provider"]
3204 requirer_dict
= r
["requirer"]
3205 elif "entities" in r
:
3206 provider_id
= r
["entities"][0]["id"]
3209 "vnf-profile-id": vnf_profile_id
,
3210 "endpoint": r
["entities"][0]["endpoint"],
3212 if provider_id
!= vnfd_id
:
3213 provider_dict
["vdu-profile-id"] = provider_id
3214 requirer_id
= r
["entities"][1]["id"]
3217 "vnf-profile-id": vnf_profile_id
,
3218 "endpoint": r
["entities"][1]["endpoint"],
3220 if requirer_id
!= vnfd_id
:
3221 requirer_dict
["vdu-profile-id"] = requirer_id
3224 "provider/requirer or entities must be included in the relation."
3226 relation_provider
= self
._update
_ee
_relation
_data
_with
_implicit
_data
(
3227 nsr_id
, nsd
, provider_dict
, cached_vnfds
, vnf_profile_id
=vnf_profile_id
3229 relation_requirer
= self
._update
_ee
_relation
_data
_with
_implicit
_data
(
3230 nsr_id
, nsd
, requirer_dict
, cached_vnfds
, vnf_profile_id
=vnf_profile_id
3232 provider
= EERelation(relation_provider
)
3233 requirer
= EERelation(relation_requirer
)
3234 relation
= Relation(r
["name"], provider
, requirer
)
3235 vca_in_relation
= self
._is
_deployed
_vca
_in
_relation
(vca
, relation
)
3237 relations
.append(relation
)
3240 def _get_kdu_resource_data(
3242 ee_relation
: EERelation
,
3243 db_nsr
: Dict
[str, Any
],
3244 cached_vnfds
: Dict
[str, Any
],
3245 ) -> DeployedK8sResource
:
3246 nsd
= get_nsd(db_nsr
)
3247 vnf_profiles
= get_vnf_profiles(nsd
)
3248 vnfd_id
= find_in_list(
3250 lambda vnf_profile
: vnf_profile
["id"] == ee_relation
.vnf_profile_id
,
3252 project
= nsd
["_admin"]["projects_read"][0]
3253 db_vnfd
= self
._get
_vnfd
(vnfd_id
, project
, cached_vnfds
)
3254 kdu_resource_profile
= get_kdu_resource_profile(
3255 db_vnfd
, ee_relation
.kdu_resource_profile_id
3257 kdu_name
= kdu_resource_profile
["kdu-name"]
3258 deployed_kdu
, _
= get_deployed_kdu(
3259 db_nsr
.get("_admin", ()).get("deployed", ()),
3261 ee_relation
.vnf_profile_id
,
3263 deployed_kdu
.update({"resource-name": kdu_resource_profile
["resource-name"]})
3266 def _get_deployed_component(
3268 ee_relation
: EERelation
,
3269 db_nsr
: Dict
[str, Any
],
3270 cached_vnfds
: Dict
[str, Any
],
3271 ) -> DeployedComponent
:
3272 nsr_id
= db_nsr
["_id"]
3273 deployed_component
= None
3274 ee_level
= EELevel
.get_level(ee_relation
)
3275 if ee_level
== EELevel
.NS
:
3276 vca
= get_deployed_vca(db_nsr
, {"vdu_id": None, "member-vnf-index": None})
3278 deployed_component
= DeployedVCA(nsr_id
, vca
)
3279 elif ee_level
== EELevel
.VNF
:
3280 vca
= get_deployed_vca(
3284 "member-vnf-index": ee_relation
.vnf_profile_id
,
3285 "ee_descriptor_id": ee_relation
.execution_environment_ref
,
3289 deployed_component
= DeployedVCA(nsr_id
, vca
)
3290 elif ee_level
== EELevel
.VDU
:
3291 vca
= get_deployed_vca(
3294 "vdu_id": ee_relation
.vdu_profile_id
,
3295 "member-vnf-index": ee_relation
.vnf_profile_id
,
3296 "ee_descriptor_id": ee_relation
.execution_environment_ref
,
3300 deployed_component
= DeployedVCA(nsr_id
, vca
)
3301 elif ee_level
== EELevel
.KDU
:
3302 kdu_resource_data
= self
._get
_kdu
_resource
_data
(
3303 ee_relation
, db_nsr
, cached_vnfds
3305 if kdu_resource_data
:
3306 deployed_component
= DeployedK8sResource(kdu_resource_data
)
3307 return deployed_component
3309 async def _add_relation(
3313 db_nsr
: Dict
[str, Any
],
3314 cached_vnfds
: Dict
[str, Any
],
3315 cached_vnfrs
: Dict
[str, Any
],
3317 deployed_provider
= self
._get
_deployed
_component
(
3318 relation
.provider
, db_nsr
, cached_vnfds
3320 deployed_requirer
= self
._get
_deployed
_component
(
3321 relation
.requirer
, db_nsr
, cached_vnfds
3325 and deployed_requirer
3326 and deployed_provider
.config_sw_installed
3327 and deployed_requirer
.config_sw_installed
3329 provider_db_vnfr
= (
3331 relation
.provider
.nsr_id
,
3332 relation
.provider
.vnf_profile_id
,
3335 if relation
.provider
.vnf_profile_id
3338 requirer_db_vnfr
= (
3340 relation
.requirer
.nsr_id
,
3341 relation
.requirer
.vnf_profile_id
,
3344 if relation
.requirer
.vnf_profile_id
3347 provider_vca_id
= self
.get_vca_id(provider_db_vnfr
, db_nsr
)
3348 requirer_vca_id
= self
.get_vca_id(requirer_db_vnfr
, db_nsr
)
3349 provider_relation_endpoint
= RelationEndpoint(
3350 deployed_provider
.ee_id
,
3352 relation
.provider
.endpoint
,
3354 requirer_relation_endpoint
= RelationEndpoint(
3355 deployed_requirer
.ee_id
,
3357 relation
.requirer
.endpoint
,
3360 await self
.vca_map
[vca_type
].add_relation(
3361 provider
=provider_relation_endpoint
,
3362 requirer
=requirer_relation_endpoint
,
3364 except N2VCException
as exception
:
3365 self
.logger
.error(exception
)
3366 raise LcmException(exception
)
3370 async def _add_vca_relations(
3376 timeout
: int = 3600,
3379 # 1. find all relations for this VCA
3380 # 2. wait for other peers related
3384 # STEP 1: find all relations for this VCA
3387 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
3388 nsd
= get_nsd(db_nsr
)
3391 deployed_vca_dict
= get_deployed_vca_list(db_nsr
)[vca_index
]
3392 my_vca
= DeployedVCA(nsr_id
, deployed_vca_dict
)
3397 relations
.extend(self
._get
_ns
_relations
(nsr_id
, nsd
, my_vca
, cached_vnfds
))
3398 relations
.extend(self
._get
_vnf
_relations
(nsr_id
, nsd
, my_vca
, cached_vnfds
))
3400 # if no relations, terminate
3402 self
.logger
.debug(logging_text
+ " No relations")
3405 self
.logger
.debug(logging_text
+ " adding relations {}".format(relations
))
3412 if now
- start
>= timeout
:
3413 self
.logger
.error(logging_text
+ " : timeout adding relations")
3416 # reload nsr from database (we need to update record: _admin.deployed.VCA)
3417 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
3419 # for each relation, find the VCA's related
3420 for relation
in relations
.copy():
3421 added
= await self
._add
_relation
(
3429 relations
.remove(relation
)
3432 self
.logger
.debug("Relations added")
3434 await asyncio
.sleep(5.0)
3438 except Exception as e
:
3439 self
.logger
.warn(logging_text
+ " ERROR adding relations: {}".format(e
))
3442 async def _install_kdu(
3450 k8s_instance_info
: dict,
3451 k8params
: dict = None,
3456 k8sclustertype
= k8s_instance_info
["k8scluster-type"]
3459 "collection": "nsrs",
3460 "filter": {"_id": nsr_id
},
3461 "path": nsr_db_path
,
3464 if k8s_instance_info
.get("kdu-deployment-name"):
3465 kdu_instance
= k8s_instance_info
.get("kdu-deployment-name")
3467 kdu_instance
= self
.k8scluster_map
[
3469 ].generate_kdu_instance_name(
3470 db_dict
=db_dict_install
,
3471 kdu_model
=k8s_instance_info
["kdu-model"],
3472 kdu_name
=k8s_instance_info
["kdu-name"],
3475 # Update the nsrs table with the kdu-instance value
3479 _desc
={nsr_db_path
+ ".kdu-instance": kdu_instance
},
3482 # Update the nsrs table with the actual namespace being used, if the k8scluster-type is `juju` or
3483 # `juju-bundle`. This verification is needed because there is not a standard/homogeneous namespace
3484 # between the Helm Charts and Juju Bundles-based KNFs. If we found a way of having an homogeneous
3485 # namespace, this first verification could be removed, and the next step would be done for any kind
3487 # TODO -> find a way to have an homogeneous namespace between the Helm Charts and Juju Bundles-based
3488 # KNFs (Bug 2027: https://osm.etsi.org/bugzilla/show_bug.cgi?id=2027)
3489 if k8sclustertype
in ("juju", "juju-bundle"):
3490 # First, verify if the current namespace is present in the `_admin.projects_read` (if not, it means
3491 # that the user passed a namespace which he wants its KDU to be deployed in)
3497 "_admin.projects_write": k8s_instance_info
["namespace"],
3498 "_admin.projects_read": k8s_instance_info
["namespace"],
3504 f
"Updating namespace/model for Juju Bundle from {k8s_instance_info['namespace']} to {kdu_instance}"
3509 _desc
={f
"{nsr_db_path}.namespace": kdu_instance
},
3511 k8s_instance_info
["namespace"] = kdu_instance
3513 await self
.k8scluster_map
[k8sclustertype
].install(
3514 cluster_uuid
=k8s_instance_info
["k8scluster-uuid"],
3515 kdu_model
=k8s_instance_info
["kdu-model"],
3518 db_dict
=db_dict_install
,
3520 kdu_name
=k8s_instance_info
["kdu-name"],
3521 namespace
=k8s_instance_info
["namespace"],
3522 kdu_instance
=kdu_instance
,
3526 # Obtain services to obtain management service ip
3527 services
= await self
.k8scluster_map
[k8sclustertype
].get_services(
3528 cluster_uuid
=k8s_instance_info
["k8scluster-uuid"],
3529 kdu_instance
=kdu_instance
,
3530 namespace
=k8s_instance_info
["namespace"],
3533 # Obtain management service info (if exists)
3534 vnfr_update_dict
= {}
3535 kdu_config
= get_configuration(vnfd
, kdud
["name"])
3537 target_ee_list
= kdu_config
.get("execution-environment-list", [])
3542 vnfr_update_dict
["kdur.{}.services".format(kdu_index
)] = services
3545 for service
in kdud
.get("service", [])
3546 if service
.get("mgmt-service")
3548 for mgmt_service
in mgmt_services
:
3549 for service
in services
:
3550 if service
["name"].startswith(mgmt_service
["name"]):
3551 # Mgmt service found, Obtain service ip
3552 ip
= service
.get("external_ip", service
.get("cluster_ip"))
3553 if isinstance(ip
, list) and len(ip
) == 1:
3557 "kdur.{}.ip-address".format(kdu_index
)
3560 # Check if must update also mgmt ip at the vnf
3561 service_external_cp
= mgmt_service
.get(
3562 "external-connection-point-ref"
3564 if service_external_cp
:
3566 deep_get(vnfd
, ("mgmt-interface", "cp"))
3567 == service_external_cp
3569 vnfr_update_dict
["ip-address"] = ip
3574 "external-connection-point-ref", ""
3576 == service_external_cp
,
3579 "kdur.{}.ip-address".format(kdu_index
)
3584 "Mgmt service name: {} not found".format(
3585 mgmt_service
["name"]
3589 vnfr_update_dict
["kdur.{}.status".format(kdu_index
)] = "READY"
3590 self
.update_db_2("vnfrs", vnfr_data
.get("_id"), vnfr_update_dict
)
3592 kdu_config
= get_configuration(vnfd
, k8s_instance_info
["kdu-name"])
3595 and kdu_config
.get("initial-config-primitive")
3596 and get_juju_ee_ref(vnfd
, k8s_instance_info
["kdu-name"]) is None
3598 initial_config_primitive_list
= kdu_config
.get(
3599 "initial-config-primitive"
3601 initial_config_primitive_list
.sort(key
=lambda val
: int(val
["seq"]))
3603 for initial_config_primitive
in initial_config_primitive_list
:
3604 primitive_params_
= self
._map
_primitive
_params
(
3605 initial_config_primitive
, {}, {}
3608 await asyncio
.wait_for(
3609 self
.k8scluster_map
[k8sclustertype
].exec_primitive(
3610 cluster_uuid
=k8s_instance_info
["k8scluster-uuid"],
3611 kdu_instance
=kdu_instance
,
3612 primitive_name
=initial_config_primitive
["name"],
3613 params
=primitive_params_
,
3614 db_dict
=db_dict_install
,
3620 except Exception as e
:
3621 # Prepare update db with error and raise exception
3624 "nsrs", nsr_id
, {nsr_db_path
+ ".detailed-status": str(e
)}
3628 vnfr_data
.get("_id"),
3629 {"kdur.{}.status".format(kdu_index
): "ERROR"},
3632 # ignore to keep original exception
3634 # reraise original error
3639 async def deploy_kdus(
3646 task_instantiation_info
,
3648 # Launch kdus if present in the descriptor
3650 k8scluster_id_2_uuic
= {
3651 "helm-chart-v3": {},
3656 async def _get_cluster_id(cluster_id
, cluster_type
):
3657 nonlocal k8scluster_id_2_uuic
3658 if cluster_id
in k8scluster_id_2_uuic
[cluster_type
]:
3659 return k8scluster_id_2_uuic
[cluster_type
][cluster_id
]
3661 # check if K8scluster is creating and wait look if previous tasks in process
3662 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related(
3663 "k8scluster", cluster_id
3666 text
= "Waiting for related tasks '{}' on k8scluster {} to be completed".format(
3667 task_name
, cluster_id
3669 self
.logger
.debug(logging_text
+ text
)
3670 await asyncio
.wait(task_dependency
, timeout
=3600)
3672 db_k8scluster
= self
.db
.get_one(
3673 "k8sclusters", {"_id": cluster_id
}, fail_on_empty
=False
3675 if not db_k8scluster
:
3676 raise LcmException("K8s cluster {} cannot be found".format(cluster_id
))
3678 k8s_id
= deep_get(db_k8scluster
, ("_admin", cluster_type
, "id"))
3680 if cluster_type
== "helm-chart-v3":
3682 # backward compatibility for existing clusters that have not been initialized for helm v3
3683 k8s_credentials
= yaml
.safe_dump(
3684 db_k8scluster
.get("credentials")
3686 k8s_id
, uninstall_sw
= await self
.k8sclusterhelm3
.init_env(
3687 k8s_credentials
, reuse_cluster_uuid
=cluster_id
3689 db_k8scluster_update
= {}
3690 db_k8scluster_update
["_admin.helm-chart-v3.error_msg"] = None
3691 db_k8scluster_update
["_admin.helm-chart-v3.id"] = k8s_id
3692 db_k8scluster_update
[
3693 "_admin.helm-chart-v3.created"
3695 db_k8scluster_update
[
3696 "_admin.helm-chart-v3.operationalState"
3699 "k8sclusters", cluster_id
, db_k8scluster_update
3701 except Exception as e
:
3704 + "error initializing helm-v3 cluster: {}".format(str(e
))
3707 "K8s cluster '{}' has not been initialized for '{}'".format(
3708 cluster_id
, cluster_type
3713 "K8s cluster '{}' has not been initialized for '{}'".format(
3714 cluster_id
, cluster_type
3717 k8scluster_id_2_uuic
[cluster_type
][cluster_id
] = k8s_id
3720 logging_text
+= "Deploy kdus: "
3723 db_nsr_update
= {"_admin.deployed.K8s": []}
3724 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
3727 updated_cluster_list
= []
3728 updated_v3_cluster_list
= []
3730 for vnfr_data
in db_vnfrs
.values():
3731 vca_id
= self
.get_vca_id(vnfr_data
, {})
3732 for kdu_index
, kdur
in enumerate(get_iterable(vnfr_data
, "kdur")):
3733 # Step 0: Prepare and set parameters
3734 desc_params
= parse_yaml_strings(kdur
.get("additionalParams"))
3735 vnfd_id
= vnfr_data
.get("vnfd-id")
3736 vnfd_with_id
= find_in_list(
3737 db_vnfds
, lambda vnfd
: vnfd
["_id"] == vnfd_id
3741 for kdud
in vnfd_with_id
["kdu"]
3742 if kdud
["name"] == kdur
["kdu-name"]
3744 namespace
= kdur
.get("k8s-namespace")
3745 kdu_deployment_name
= kdur
.get("kdu-deployment-name")
3746 if kdur
.get("helm-chart"):
3747 kdumodel
= kdur
["helm-chart"]
3748 # Default version: helm3, if helm-version is v2 assign v2
3749 k8sclustertype
= "helm-chart-v3"
3750 self
.logger
.debug("kdur: {}".format(kdur
))
3752 kdur
.get("helm-version")
3753 and kdur
.get("helm-version") == "v2"
3755 k8sclustertype
= "helm-chart"
3756 elif kdur
.get("juju-bundle"):
3757 kdumodel
= kdur
["juju-bundle"]
3758 k8sclustertype
= "juju-bundle"
3761 "kdu type for kdu='{}.{}' is neither helm-chart nor "
3762 "juju-bundle. Maybe an old NBI version is running".format(
3763 vnfr_data
["member-vnf-index-ref"], kdur
["kdu-name"]
3766 # check if kdumodel is a file and exists
3768 vnfd_with_id
= find_in_list(
3769 db_vnfds
, lambda vnfd
: vnfd
["_id"] == vnfd_id
3771 storage
= deep_get(vnfd_with_id
, ("_admin", "storage"))
3772 if storage
: # may be not present if vnfd has not artifacts
3773 # path format: /vnfdid/pkkdir/helm-charts|juju-bundles/kdumodel
3774 if storage
["pkg-dir"]:
3775 filename
= "{}/{}/{}s/{}".format(
3782 filename
= "{}/Scripts/{}s/{}".format(
3787 if self
.fs
.file_exists(
3788 filename
, mode
="file"
3789 ) or self
.fs
.file_exists(filename
, mode
="dir"):
3790 kdumodel
= self
.fs
.path
+ filename
3791 except (asyncio
.TimeoutError
, asyncio
.CancelledError
):
3793 except Exception: # it is not a file
3796 k8s_cluster_id
= kdur
["k8s-cluster"]["id"]
3797 step
= "Synchronize repos for k8s cluster '{}'".format(
3800 cluster_uuid
= await _get_cluster_id(k8s_cluster_id
, k8sclustertype
)
3804 k8sclustertype
== "helm-chart"
3805 and cluster_uuid
not in updated_cluster_list
3807 k8sclustertype
== "helm-chart-v3"
3808 and cluster_uuid
not in updated_v3_cluster_list
3810 del_repo_list
, added_repo_dict
= await asyncio
.ensure_future(
3811 self
.k8scluster_map
[k8sclustertype
].synchronize_repos(
3812 cluster_uuid
=cluster_uuid
3815 if del_repo_list
or added_repo_dict
:
3816 if k8sclustertype
== "helm-chart":
3818 "_admin.helm_charts_added." + item
: None
3819 for item
in del_repo_list
3822 "_admin.helm_charts_added." + item
: name
3823 for item
, name
in added_repo_dict
.items()
3825 updated_cluster_list
.append(cluster_uuid
)
3826 elif k8sclustertype
== "helm-chart-v3":
3828 "_admin.helm_charts_v3_added." + item
: None
3829 for item
in del_repo_list
3832 "_admin.helm_charts_v3_added." + item
: name
3833 for item
, name
in added_repo_dict
.items()
3835 updated_v3_cluster_list
.append(cluster_uuid
)
3837 logging_text
+ "repos synchronized on k8s cluster "
3838 "'{}' to_delete: {}, to_add: {}".format(
3839 k8s_cluster_id
, del_repo_list
, added_repo_dict
3844 {"_id": k8s_cluster_id
},
3850 step
= "Instantiating KDU {}.{} in k8s cluster {}".format(
3851 vnfr_data
["member-vnf-index-ref"],
3855 k8s_instance_info
= {
3856 "kdu-instance": None,
3857 "k8scluster-uuid": cluster_uuid
,
3858 "k8scluster-type": k8sclustertype
,
3859 "member-vnf-index": vnfr_data
["member-vnf-index-ref"],
3860 "kdu-name": kdur
["kdu-name"],
3861 "kdu-model": kdumodel
,
3862 "namespace": namespace
,
3863 "kdu-deployment-name": kdu_deployment_name
,
3865 db_path
= "_admin.deployed.K8s.{}".format(index
)
3866 db_nsr_update
[db_path
] = k8s_instance_info
3867 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
3868 vnfd_with_id
= find_in_list(
3869 db_vnfds
, lambda vnf
: vnf
["_id"] == vnfd_id
3871 task
= asyncio
.ensure_future(
3880 k8params
=desc_params
,
3885 self
.lcm_tasks
.register(
3889 "instantiate_KDU-{}".format(index
),
3892 task_instantiation_info
[task
] = "Deploying KDU {}".format(
3898 except (LcmException
, asyncio
.CancelledError
):
3900 except Exception as e
:
3901 msg
= "Exception {} while {}: {}".format(type(e
).__name
__, step
, e
)
3902 if isinstance(e
, (N2VCException
, DbException
)):
3903 self
.logger
.error(logging_text
+ msg
)
3905 self
.logger
.critical(logging_text
+ msg
, exc_info
=True)
3906 raise LcmException(msg
)
3909 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
3929 task_instantiation_info
,
3932 # launch instantiate_N2VC in a asyncio task and register task object
3933 # Look where information of this charm is at database <nsrs>._admin.deployed.VCA
3934 # if not found, create one entry and update database
3935 # fill db_nsr._admin.deployed.VCA.<index>
3938 logging_text
+ "_deploy_n2vc vnfd_id={}, vdu_id={}".format(vnfd_id
, vdu_id
)
3942 get_charm_name
= False
3943 if "execution-environment-list" in descriptor_config
:
3944 ee_list
= descriptor_config
.get("execution-environment-list", [])
3945 elif "juju" in descriptor_config
:
3946 ee_list
= [descriptor_config
] # ns charms
3947 if "execution-environment-list" not in descriptor_config
:
3948 # charm name is only required for ns charms
3949 get_charm_name
= True
3950 else: # other types as script are not supported
3953 for ee_item
in ee_list
:
3956 + "_deploy_n2vc ee_item juju={}, helm={}".format(
3957 ee_item
.get("juju"), ee_item
.get("helm-chart")
3960 ee_descriptor_id
= ee_item
.get("id")
3961 if ee_item
.get("juju"):
3962 vca_name
= ee_item
["juju"].get("charm")
3964 charm_name
= self
.find_charm_name(db_nsr
, str(vca_name
))
3967 if ee_item
["juju"].get("charm") is not None
3970 if ee_item
["juju"].get("cloud") == "k8s":
3971 vca_type
= "k8s_proxy_charm"
3972 elif ee_item
["juju"].get("proxy") is False:
3973 vca_type
= "native_charm"
3974 elif ee_item
.get("helm-chart"):
3975 vca_name
= ee_item
["helm-chart"]
3976 if ee_item
.get("helm-version") and ee_item
.get("helm-version") == "v2":
3979 vca_type
= "helm-v3"
3982 logging_text
+ "skipping non juju neither charm configuration"
3987 for vca_index
, vca_deployed
in enumerate(
3988 db_nsr
["_admin"]["deployed"]["VCA"]
3990 if not vca_deployed
:
3993 vca_deployed
.get("member-vnf-index") == member_vnf_index
3994 and vca_deployed
.get("vdu_id") == vdu_id
3995 and vca_deployed
.get("kdu_name") == kdu_name
3996 and vca_deployed
.get("vdu_count_index", 0) == vdu_index
3997 and vca_deployed
.get("ee_descriptor_id") == ee_descriptor_id
4001 # not found, create one.
4003 "ns" if not member_vnf_index
else "vnf/{}".format(member_vnf_index
)
4006 target
+= "/vdu/{}/{}".format(vdu_id
, vdu_index
or 0)
4008 target
+= "/kdu/{}".format(kdu_name
)
4010 "target_element": target
,
4011 # ^ target_element will replace member-vnf-index, kdu_name, vdu_id ... in a single string
4012 "member-vnf-index": member_vnf_index
,
4014 "kdu_name": kdu_name
,
4015 "vdu_count_index": vdu_index
,
4016 "operational-status": "init", # TODO revise
4017 "detailed-status": "", # TODO revise
4018 "step": "initial-deploy", # TODO revise
4020 "vdu_name": vdu_name
,
4022 "ee_descriptor_id": ee_descriptor_id
,
4023 "charm_name": charm_name
,
4027 # create VCA and configurationStatus in db
4029 "_admin.deployed.VCA.{}".format(vca_index
): vca_deployed
,
4030 "configurationStatus.{}".format(vca_index
): dict(),
4032 self
.update_db_2("nsrs", nsr_id
, db_dict
)
4034 db_nsr
["_admin"]["deployed"]["VCA"].append(vca_deployed
)
4036 self
.logger
.debug("N2VC > NSR_ID > {}".format(nsr_id
))
4037 self
.logger
.debug("N2VC > DB_NSR > {}".format(db_nsr
))
4038 self
.logger
.debug("N2VC > VCA_DEPLOYED > {}".format(vca_deployed
))
4041 task_n2vc
= asyncio
.ensure_future(
4042 self
.instantiate_N2VC(
4043 logging_text
=logging_text
,
4044 vca_index
=vca_index
,
4050 vdu_index
=vdu_index
,
4051 kdu_index
=kdu_index
,
4052 deploy_params
=deploy_params
,
4053 config_descriptor
=descriptor_config
,
4054 base_folder
=base_folder
,
4055 nslcmop_id
=nslcmop_id
,
4059 ee_config_descriptor
=ee_item
,
4062 self
.lcm_tasks
.register(
4066 "instantiate_N2VC-{}".format(vca_index
),
4069 task_instantiation_info
[
4071 ] = self
.task_name_deploy_vca
+ " {}.{}".format(
4072 member_vnf_index
or "", vdu_id
or ""
4075 def _format_additional_params(self
, params
):
4076 params
= params
or {}
4077 for key
, value
in params
.items():
4078 if str(value
).startswith("!!yaml "):
4079 params
[key
] = yaml
.safe_load(value
[7:])
4082 def _get_terminate_primitive_params(self
, seq
, vnf_index
):
4083 primitive
= seq
.get("name")
4084 primitive_params
= {}
4086 "member_vnf_index": vnf_index
,
4087 "primitive": primitive
,
4088 "primitive_params": primitive_params
,
4091 return self
._map
_primitive
_params
(seq
, params
, desc_params
)
4095 def _retry_or_skip_suboperation(self
, db_nslcmop
, op_index
):
4096 op
= deep_get(db_nslcmop
, ("_admin", "operations"), [])[op_index
]
4097 if op
.get("operationState") == "COMPLETED":
4098 # b. Skip sub-operation
4099 # _ns_execute_primitive() or RO.create_action() will NOT be executed
4100 return self
.SUBOPERATION_STATUS_SKIP
4102 # c. retry executing sub-operation
4103 # The sub-operation exists, and operationState != 'COMPLETED'
4104 # Update operationState = 'PROCESSING' to indicate a retry.
4105 operationState
= "PROCESSING"
4106 detailed_status
= "In progress"
4107 self
._update
_suboperation
_status
(
4108 db_nslcmop
, op_index
, operationState
, detailed_status
4110 # Return the sub-operation index
4111 # _ns_execute_primitive() or RO.create_action() will be called from scale()
4112 # with arguments extracted from the sub-operation
4115 # Find a sub-operation where all keys in a matching dictionary must match
4116 # Returns the index of the matching sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if no match
4117 def _find_suboperation(self
, db_nslcmop
, match
):
4118 if db_nslcmop
and match
:
4119 op_list
= db_nslcmop
.get("_admin", {}).get("operations", [])
4120 for i
, op
in enumerate(op_list
):
4121 if all(op
.get(k
) == match
[k
] for k
in match
):
4123 return self
.SUBOPERATION_STATUS_NOT_FOUND
4125 # Update status for a sub-operation given its index
4126 def _update_suboperation_status(
4127 self
, db_nslcmop
, op_index
, operationState
, detailed_status
4129 # Update DB for HA tasks
4130 q_filter
= {"_id": db_nslcmop
["_id"]}
4132 "_admin.operations.{}.operationState".format(op_index
): operationState
,
4133 "_admin.operations.{}.detailed-status".format(op_index
): detailed_status
,
4136 "nslcmops", q_filter
=q_filter
, update_dict
=update_dict
, fail_on_empty
=False
4139 # Add sub-operation, return the index of the added sub-operation
4140 # Optionally, set operationState, detailed-status, and operationType
4141 # Status and type are currently set for 'scale' sub-operations:
4142 # 'operationState' : 'PROCESSING' | 'COMPLETED' | 'FAILED'
4143 # 'detailed-status' : status message
4144 # 'operationType': may be any type, in the case of scaling: 'PRE-SCALE' | 'POST-SCALE'
4145 # Status and operation type are currently only used for 'scale', but NOT for 'terminate' sub-operations.
4146 def _add_suboperation(
4154 mapped_primitive_params
,
4155 operationState
=None,
4156 detailed_status
=None,
4159 RO_scaling_info
=None,
4162 return self
.SUBOPERATION_STATUS_NOT_FOUND
4163 # Get the "_admin.operations" list, if it exists
4164 db_nslcmop_admin
= db_nslcmop
.get("_admin", {})
4165 op_list
= db_nslcmop_admin
.get("operations")
4166 # Create or append to the "_admin.operations" list
4168 "member_vnf_index": vnf_index
,
4170 "vdu_count_index": vdu_count_index
,
4171 "primitive": primitive
,
4172 "primitive_params": mapped_primitive_params
,
4175 new_op
["operationState"] = operationState
4177 new_op
["detailed-status"] = detailed_status
4179 new_op
["lcmOperationType"] = operationType
4181 new_op
["RO_nsr_id"] = RO_nsr_id
4183 new_op
["RO_scaling_info"] = RO_scaling_info
4185 # No existing operations, create key 'operations' with current operation as first list element
4186 db_nslcmop_admin
.update({"operations": [new_op
]})
4187 op_list
= db_nslcmop_admin
.get("operations")
4189 # Existing operations, append operation to list
4190 op_list
.append(new_op
)
4192 db_nslcmop_update
= {"_admin.operations": op_list
}
4193 self
.update_db_2("nslcmops", db_nslcmop
["_id"], db_nslcmop_update
)
4194 op_index
= len(op_list
) - 1
4197 # Helper methods for scale() sub-operations
4199 # pre-scale/post-scale:
4200 # Check for 3 different cases:
4201 # a. New: First time execution, return SUBOPERATION_STATUS_NEW
4202 # b. Skip: Existing sub-operation exists, operationState == 'COMPLETED', return SUBOPERATION_STATUS_SKIP
4203 # c. retry: Existing sub-operation exists, operationState != 'COMPLETED', return op_index to re-execute
4204 def _check_or_add_scale_suboperation(
4208 vnf_config_primitive
,
4212 RO_scaling_info
=None,
4214 # Find this sub-operation
4215 if RO_nsr_id
and RO_scaling_info
:
4216 operationType
= "SCALE-RO"
4218 "member_vnf_index": vnf_index
,
4219 "RO_nsr_id": RO_nsr_id
,
4220 "RO_scaling_info": RO_scaling_info
,
4224 "member_vnf_index": vnf_index
,
4225 "primitive": vnf_config_primitive
,
4226 "primitive_params": primitive_params
,
4227 "lcmOperationType": operationType
,
4229 op_index
= self
._find
_suboperation
(db_nslcmop
, match
)
4230 if op_index
== self
.SUBOPERATION_STATUS_NOT_FOUND
:
4231 # a. New sub-operation
4232 # The sub-operation does not exist, add it.
4233 # _ns_execute_primitive() will be called from scale() as usual, with non-modified arguments
4234 # The following parameters are set to None for all kind of scaling:
4236 vdu_count_index
= None
4238 if RO_nsr_id
and RO_scaling_info
:
4239 vnf_config_primitive
= None
4240 primitive_params
= None
4243 RO_scaling_info
= None
4244 # Initial status for sub-operation
4245 operationState
= "PROCESSING"
4246 detailed_status
= "In progress"
4247 # Add sub-operation for pre/post-scaling (zero or more operations)
4248 self
._add
_suboperation
(
4254 vnf_config_primitive
,
4262 return self
.SUBOPERATION_STATUS_NEW
4264 # Return either SUBOPERATION_STATUS_SKIP (operationState == 'COMPLETED'),
4265 # or op_index (operationState != 'COMPLETED')
4266 return self
._retry
_or
_skip
_suboperation
(db_nslcmop
, op_index
)
4268 # Function to return execution_environment id
4270 async def destroy_N2VC(
4278 exec_primitives
=True,
4283 Execute the terminate primitives and destroy the execution environment (if destroy_ee=False
4284 :param logging_text:
4286 :param vca_deployed: Dictionary of deployment info at db_nsr._admin.depoloyed.VCA.<INDEX>
4287 :param config_descriptor: Configuration descriptor of the NSD, VNFD, VNFD.vdu or VNFD.kdu
4288 :param vca_index: index in the database _admin.deployed.VCA
4289 :param destroy_ee: False to do not destroy, because it will be destroyed all of then at once
4290 :param exec_primitives: False to do not execute terminate primitives, because the config is not completed or has
4291 not executed properly
4292 :param scaling_in: True destroys the application, False destroys the model
4293 :return: None or exception
4298 + " vca_index: {}, vca_deployed: {}, config_descriptor: {}, destroy_ee: {}".format(
4299 vca_index
, vca_deployed
, config_descriptor
, destroy_ee
4303 vca_type
= vca_deployed
.get("type", "lxc_proxy_charm")
4305 # execute terminate_primitives
4307 terminate_primitives
= get_ee_sorted_terminate_config_primitive_list(
4308 config_descriptor
.get("terminate-config-primitive"),
4309 vca_deployed
.get("ee_descriptor_id"),
4311 vdu_id
= vca_deployed
.get("vdu_id")
4312 vdu_count_index
= vca_deployed
.get("vdu_count_index")
4313 vdu_name
= vca_deployed
.get("vdu_name")
4314 vnf_index
= vca_deployed
.get("member-vnf-index")
4315 if terminate_primitives
and vca_deployed
.get("needed_terminate"):
4316 for seq
in terminate_primitives
:
4317 # For each sequence in list, get primitive and call _ns_execute_primitive()
4318 step
= "Calling terminate action for vnf_member_index={} primitive={}".format(
4319 vnf_index
, seq
.get("name")
4321 self
.logger
.debug(logging_text
+ step
)
4322 # Create the primitive for each sequence, i.e. "primitive": "touch"
4323 primitive
= seq
.get("name")
4324 mapped_primitive_params
= self
._get
_terminate
_primitive
_params
(
4329 self
._add
_suboperation
(
4336 mapped_primitive_params
,
4338 # Sub-operations: Call _ns_execute_primitive() instead of action()
4340 result
, result_detail
= await self
._ns
_execute
_primitive
(
4341 vca_deployed
["ee_id"],
4343 mapped_primitive_params
,
4347 except LcmException
:
4348 # this happens when VCA is not deployed. In this case it is not needed to terminate
4350 result_ok
= ["COMPLETED", "PARTIALLY_COMPLETED"]
4351 if result
not in result_ok
:
4353 "terminate_primitive {} for vnf_member_index={} fails with "
4354 "error {}".format(seq
.get("name"), vnf_index
, result_detail
)
4356 # set that this VCA do not need terminated
4357 db_update_entry
= "_admin.deployed.VCA.{}.needed_terminate".format(
4361 "nsrs", db_nslcmop
["nsInstanceId"], {db_update_entry
: False}
4364 # Delete Prometheus Jobs if any
4365 # This uses NSR_ID, so it will destroy any jobs under this index
4366 self
.db
.del_list("prometheus_jobs", {"nsr_id": db_nslcmop
["nsInstanceId"]})
4369 await self
.vca_map
[vca_type
].delete_execution_environment(
4370 vca_deployed
["ee_id"],
4371 scaling_in
=scaling_in
,
4376 async def _delete_all_N2VC(self
, db_nsr
: dict, vca_id
: str = None):
4377 self
._write
_all
_config
_status
(db_nsr
=db_nsr
, status
="TERMINATING")
4378 namespace
= "." + db_nsr
["_id"]
4380 await self
.n2vc
.delete_namespace(
4381 namespace
=namespace
,
4382 total_timeout
=self
.timeout
.charm_delete
,
4385 except N2VCNotFound
: # already deleted. Skip
4387 self
._write
_all
_config
_status
(db_nsr
=db_nsr
, status
="DELETED")
4389 async def terminate(self
, nsr_id
, nslcmop_id
):
4390 # Try to lock HA task here
4391 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA("ns", "nslcmops", nslcmop_id
)
4392 if not task_is_locked_by_me
:
4395 logging_text
= "Task ns={} terminate={} ".format(nsr_id
, nslcmop_id
)
4396 self
.logger
.debug(logging_text
+ "Enter")
4397 timeout_ns_terminate
= self
.timeout
.ns_terminate
4400 operation_params
= None
4402 error_list
= [] # annotates all failed error messages
4403 db_nslcmop_update
= {}
4404 autoremove
= False # autoremove after terminated
4405 tasks_dict_info
= {}
4408 "Stage 1/3: Preparing task.",
4409 "Waiting for previous operations to terminate.",
4412 # ^ contains [stage, step, VIM-status]
4414 # wait for any previous tasks in process
4415 await self
.lcm_tasks
.waitfor_related_HA("ns", "nslcmops", nslcmop_id
)
4417 stage
[1] = "Getting nslcmop={} from db.".format(nslcmop_id
)
4418 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
4419 operation_params
= db_nslcmop
.get("operationParams") or {}
4420 if operation_params
.get("timeout_ns_terminate"):
4421 timeout_ns_terminate
= operation_params
["timeout_ns_terminate"]
4422 stage
[1] = "Getting nsr={} from db.".format(nsr_id
)
4423 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
4425 db_nsr_update
["operational-status"] = "terminating"
4426 db_nsr_update
["config-status"] = "terminating"
4427 self
._write
_ns
_status
(
4429 ns_state
="TERMINATING",
4430 current_operation
="TERMINATING",
4431 current_operation_id
=nslcmop_id
,
4432 other_update
=db_nsr_update
,
4434 self
._write
_op
_status
(op_id
=nslcmop_id
, queuePosition
=0, stage
=stage
)
4435 nsr_deployed
= deepcopy(db_nsr
["_admin"].get("deployed")) or {}
4436 if db_nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
4439 stage
[1] = "Getting vnf descriptors from db."
4440 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
4442 db_vnfr
["member-vnf-index-ref"]: db_vnfr
for db_vnfr
in db_vnfrs_list
4444 db_vnfds_from_id
= {}
4445 db_vnfds_from_member_index
= {}
4447 for vnfr
in db_vnfrs_list
:
4448 vnfd_id
= vnfr
["vnfd-id"]
4449 if vnfd_id
not in db_vnfds_from_id
:
4450 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
4451 db_vnfds_from_id
[vnfd_id
] = vnfd
4452 db_vnfds_from_member_index
[
4453 vnfr
["member-vnf-index-ref"]
4454 ] = db_vnfds_from_id
[vnfd_id
]
4456 # Destroy individual execution environments when there are terminating primitives.
4457 # Rest of EE will be deleted at once
4458 # TODO - check before calling _destroy_N2VC
4459 # if not operation_params.get("skip_terminate_primitives"):#
4460 # or not vca.get("needed_terminate"):
4461 stage
[0] = "Stage 2/3 execute terminating primitives."
4462 self
.logger
.debug(logging_text
+ stage
[0])
4463 stage
[1] = "Looking execution environment that needs terminate."
4464 self
.logger
.debug(logging_text
+ stage
[1])
4466 for vca_index
, vca
in enumerate(get_iterable(nsr_deployed
, "VCA")):
4467 config_descriptor
= None
4468 vca_member_vnf_index
= vca
.get("member-vnf-index")
4469 vca_id
= self
.get_vca_id(
4470 db_vnfrs_dict
.get(vca_member_vnf_index
)
4471 if vca_member_vnf_index
4475 if not vca
or not vca
.get("ee_id"):
4477 if not vca
.get("member-vnf-index"):
4479 config_descriptor
= db_nsr
.get("ns-configuration")
4480 elif vca
.get("vdu_id"):
4481 db_vnfd
= db_vnfds_from_member_index
[vca
["member-vnf-index"]]
4482 config_descriptor
= get_configuration(db_vnfd
, vca
.get("vdu_id"))
4483 elif vca
.get("kdu_name"):
4484 db_vnfd
= db_vnfds_from_member_index
[vca
["member-vnf-index"]]
4485 config_descriptor
= get_configuration(db_vnfd
, vca
.get("kdu_name"))
4487 db_vnfd
= db_vnfds_from_member_index
[vca
["member-vnf-index"]]
4488 config_descriptor
= get_configuration(db_vnfd
, db_vnfd
["id"])
4489 vca_type
= vca
.get("type")
4490 exec_terminate_primitives
= not operation_params
.get(
4491 "skip_terminate_primitives"
4492 ) and vca
.get("needed_terminate")
4493 # For helm we must destroy_ee. Also for native_charm, as juju_model cannot be deleted if there are
4494 # pending native charms
4496 True if vca_type
in ("helm", "helm-v3", "native_charm") else False
4498 # self.logger.debug(logging_text + "vca_index: {}, ee_id: {}, vca_type: {} destroy_ee: {}".format(
4499 # vca_index, vca.get("ee_id"), vca_type, destroy_ee))
4500 task
= asyncio
.ensure_future(
4508 exec_terminate_primitives
,
4512 tasks_dict_info
[task
] = "Terminating VCA {}".format(vca
.get("ee_id"))
4514 # wait for pending tasks of terminate primitives
4518 + "Waiting for tasks {}".format(list(tasks_dict_info
.keys()))
4520 error_list
= await self
._wait
_for
_tasks
(
4523 min(self
.timeout
.charm_delete
, timeout_ns_terminate
),
4527 tasks_dict_info
.clear()
4529 return # raise LcmException("; ".join(error_list))
4531 # remove All execution environments at once
4532 stage
[0] = "Stage 3/3 delete all."
4534 if nsr_deployed
.get("VCA"):
4535 stage
[1] = "Deleting all execution environments."
4536 self
.logger
.debug(logging_text
+ stage
[1])
4537 vca_id
= self
.get_vca_id({}, db_nsr
)
4538 task_delete_ee
= asyncio
.ensure_future(
4540 self
._delete
_all
_N
2VC
(db_nsr
=db_nsr
, vca_id
=vca_id
),
4541 timeout
=self
.timeout
.charm_delete
,
4544 # task_delete_ee = asyncio.ensure_future(self.n2vc.delete_namespace(namespace="." + nsr_id))
4545 tasks_dict_info
[task_delete_ee
] = "Terminating all VCA"
4547 # Delete Namespace and Certificates if necessary
4548 if check_helm_ee_in_ns(list(db_vnfds_from_member_index
.values())):
4549 await self
.vca_map
["helm-v3"].delete_tls_certificate(
4550 namespace
=db_nslcmop
["nsInstanceId"],
4551 certificate_name
=self
.EE_TLS_NAME
,
4553 await self
.vca_map
["helm-v3"].delete_namespace(
4554 namespace
=db_nslcmop
["nsInstanceId"],
4557 # Delete from k8scluster
4558 stage
[1] = "Deleting KDUs."
4559 self
.logger
.debug(logging_text
+ stage
[1])
4560 # print(nsr_deployed)
4561 for kdu
in get_iterable(nsr_deployed
, "K8s"):
4562 if not kdu
or not kdu
.get("kdu-instance"):
4564 kdu_instance
= kdu
.get("kdu-instance")
4565 if kdu
.get("k8scluster-type") in self
.k8scluster_map
:
4566 # TODO: Uninstall kdu instances taking into account they could be deployed in different VIMs
4567 vca_id
= self
.get_vca_id({}, db_nsr
)
4568 task_delete_kdu_instance
= asyncio
.ensure_future(
4569 self
.k8scluster_map
[kdu
["k8scluster-type"]].uninstall(
4570 cluster_uuid
=kdu
.get("k8scluster-uuid"),
4571 kdu_instance
=kdu_instance
,
4573 namespace
=kdu
.get("namespace"),
4579 + "Unknown k8s deployment type {}".format(
4580 kdu
.get("k8scluster-type")
4585 task_delete_kdu_instance
4586 ] = "Terminating KDU '{}'".format(kdu
.get("kdu-name"))
4589 stage
[1] = "Deleting ns from VIM."
4590 if self
.ro_config
.ng
:
4591 task_delete_ro
= asyncio
.ensure_future(
4592 self
._terminate
_ng
_ro
(
4593 logging_text
, nsr_deployed
, nsr_id
, nslcmop_id
, stage
4596 tasks_dict_info
[task_delete_ro
] = "Removing deployment from VIM"
4598 # rest of staff will be done at finally
4601 ROclient
.ROClientException
,
4606 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
4608 except asyncio
.CancelledError
:
4610 logging_text
+ "Cancelled Exception while '{}'".format(stage
[1])
4612 exc
= "Operation was cancelled"
4613 except Exception as e
:
4614 exc
= traceback
.format_exc()
4615 self
.logger
.critical(
4616 logging_text
+ "Exit Exception while '{}': {}".format(stage
[1], e
),
4621 error_list
.append(str(exc
))
4623 # wait for pending tasks
4625 stage
[1] = "Waiting for terminate pending tasks."
4626 self
.logger
.debug(logging_text
+ stage
[1])
4627 error_list
+= await self
._wait
_for
_tasks
(
4630 timeout_ns_terminate
,
4634 stage
[1] = stage
[2] = ""
4635 except asyncio
.CancelledError
:
4636 error_list
.append("Cancelled")
4637 # TODO cancell all tasks
4638 except Exception as exc
:
4639 error_list
.append(str(exc
))
4640 # update status at database
4642 error_detail
= "; ".join(error_list
)
4643 # self.logger.error(logging_text + error_detail)
4644 error_description_nslcmop
= "{} Detail: {}".format(
4645 stage
[0], error_detail
4647 error_description_nsr
= "Operation: TERMINATING.{}, {}.".format(
4648 nslcmop_id
, stage
[0]
4651 db_nsr_update
["operational-status"] = "failed"
4652 db_nsr_update
["detailed-status"] = (
4653 error_description_nsr
+ " Detail: " + error_detail
4655 db_nslcmop_update
["detailed-status"] = error_detail
4656 nslcmop_operation_state
= "FAILED"
4660 error_description_nsr
= error_description_nslcmop
= None
4661 ns_state
= "NOT_INSTANTIATED"
4662 db_nsr_update
["operational-status"] = "terminated"
4663 db_nsr_update
["detailed-status"] = "Done"
4664 db_nsr_update
["_admin.nsState"] = "NOT_INSTANTIATED"
4665 db_nslcmop_update
["detailed-status"] = "Done"
4666 nslcmop_operation_state
= "COMPLETED"
4669 self
._write
_ns
_status
(
4672 current_operation
="IDLE",
4673 current_operation_id
=None,
4674 error_description
=error_description_nsr
,
4675 error_detail
=error_detail
,
4676 other_update
=db_nsr_update
,
4678 self
._write
_op
_status
(
4681 error_message
=error_description_nslcmop
,
4682 operation_state
=nslcmop_operation_state
,
4683 other_update
=db_nslcmop_update
,
4685 if ns_state
== "NOT_INSTANTIATED":
4689 {"nsr-id-ref": nsr_id
},
4690 {"_admin.nsState": "NOT_INSTANTIATED"},
4692 except DbException
as e
:
4695 + "Error writing VNFR status for nsr-id-ref: {} -> {}".format(
4699 if operation_params
:
4700 autoremove
= operation_params
.get("autoremove", False)
4701 if nslcmop_operation_state
:
4703 await self
.msg
.aiowrite(
4708 "nslcmop_id": nslcmop_id
,
4709 "operationState": nslcmop_operation_state
,
4710 "autoremove": autoremove
,
4713 except Exception as e
:
4715 logging_text
+ "kafka_write notification Exception {}".format(e
)
4717 self
.logger
.debug(f
"Deleting alerts: ns_id={nsr_id}")
4718 self
.db
.del_list("alerts", {"tags.ns_id": nsr_id
})
4720 self
.logger
.debug(logging_text
+ "Exit")
4721 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_terminate")
4723 async def _wait_for_tasks(
4724 self
, logging_text
, created_tasks_info
, timeout
, stage
, nslcmop_id
, nsr_id
=None
4727 error_detail_list
= []
4729 pending_tasks
= list(created_tasks_info
.keys())
4730 num_tasks
= len(pending_tasks
)
4732 stage
[1] = "{}/{}.".format(num_done
, num_tasks
)
4733 self
._write
_op
_status
(nslcmop_id
, stage
)
4734 while pending_tasks
:
4736 _timeout
= timeout
+ time_start
- time()
4737 done
, pending_tasks
= await asyncio
.wait(
4738 pending_tasks
, timeout
=_timeout
, return_when
=asyncio
.FIRST_COMPLETED
4740 num_done
+= len(done
)
4741 if not done
: # Timeout
4742 for task
in pending_tasks
:
4743 new_error
= created_tasks_info
[task
] + ": Timeout"
4744 error_detail_list
.append(new_error
)
4745 error_list
.append(new_error
)
4748 if task
.cancelled():
4751 exc
= task
.exception()
4753 if isinstance(exc
, asyncio
.TimeoutError
):
4755 new_error
= created_tasks_info
[task
] + ": {}".format(exc
)
4756 error_list
.append(created_tasks_info
[task
])
4757 error_detail_list
.append(new_error
)
4764 ROclient
.ROClientException
,
4770 self
.logger
.error(logging_text
+ new_error
)
4772 exc_traceback
= "".join(
4773 traceback
.format_exception(None, exc
, exc
.__traceback
__)
4777 + created_tasks_info
[task
]
4783 logging_text
+ created_tasks_info
[task
] + ": Done"
4785 stage
[1] = "{}/{}.".format(num_done
, num_tasks
)
4787 stage
[1] += " Errors: " + ". ".join(error_detail_list
) + "."
4788 if nsr_id
: # update also nsr
4793 "errorDescription": "Error at: " + ", ".join(error_list
),
4794 "errorDetail": ". ".join(error_detail_list
),
4797 self
._write
_op
_status
(nslcmop_id
, stage
)
4798 return error_detail_list
4801 def _map_primitive_params(primitive_desc
, params
, instantiation_params
):
4803 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
4804 The default-value is used. If it is between < > it look for a value at instantiation_params
4805 :param primitive_desc: portion of VNFD/NSD that describes primitive
4806 :param params: Params provided by user
4807 :param instantiation_params: Instantiation params provided by user
4808 :return: a dictionary with the calculated params
4810 calculated_params
= {}
4811 for parameter
in primitive_desc
.get("parameter", ()):
4812 param_name
= parameter
["name"]
4813 if param_name
in params
:
4814 calculated_params
[param_name
] = params
[param_name
]
4815 elif "default-value" in parameter
or "value" in parameter
:
4816 if "value" in parameter
:
4817 calculated_params
[param_name
] = parameter
["value"]
4819 calculated_params
[param_name
] = parameter
["default-value"]
4821 isinstance(calculated_params
[param_name
], str)
4822 and calculated_params
[param_name
].startswith("<")
4823 and calculated_params
[param_name
].endswith(">")
4825 if calculated_params
[param_name
][1:-1] in instantiation_params
:
4826 calculated_params
[param_name
] = instantiation_params
[
4827 calculated_params
[param_name
][1:-1]
4831 "Parameter {} needed to execute primitive {} not provided".format(
4832 calculated_params
[param_name
], primitive_desc
["name"]
4837 "Parameter {} needed to execute primitive {} not provided".format(
4838 param_name
, primitive_desc
["name"]
4842 if isinstance(calculated_params
[param_name
], (dict, list, tuple)):
4843 calculated_params
[param_name
] = yaml
.safe_dump(
4844 calculated_params
[param_name
], default_flow_style
=True, width
=256
4846 elif isinstance(calculated_params
[param_name
], str) and calculated_params
[
4848 ].startswith("!!yaml "):
4849 calculated_params
[param_name
] = calculated_params
[param_name
][7:]
4850 if parameter
.get("data-type") == "INTEGER":
4852 calculated_params
[param_name
] = int(calculated_params
[param_name
])
4853 except ValueError: # error converting string to int
4855 "Parameter {} of primitive {} must be integer".format(
4856 param_name
, primitive_desc
["name"]
4859 elif parameter
.get("data-type") == "BOOLEAN":
4860 calculated_params
[param_name
] = not (
4861 (str(calculated_params
[param_name
])).lower() == "false"
4864 # add always ns_config_info if primitive name is config
4865 if primitive_desc
["name"] == "config":
4866 if "ns_config_info" in instantiation_params
:
4867 calculated_params
["ns_config_info"] = instantiation_params
[
4870 return calculated_params
4872 def _look_for_deployed_vca(
4879 ee_descriptor_id
=None,
4881 # find vca_deployed record for this action. Raise LcmException if not found or there is not any id.
4882 for vca
in deployed_vca
:
4885 if member_vnf_index
!= vca
["member-vnf-index"] or vdu_id
!= vca
["vdu_id"]:
4888 vdu_count_index
is not None
4889 and vdu_count_index
!= vca
["vdu_count_index"]
4892 if kdu_name
and kdu_name
!= vca
["kdu_name"]:
4894 if ee_descriptor_id
and ee_descriptor_id
!= vca
["ee_descriptor_id"]:
4898 # vca_deployed not found
4900 "charm for member_vnf_index={} vdu_id={}.{} kdu_name={} execution-environment-list.id={}"
4901 " is not deployed".format(
4910 ee_id
= vca
.get("ee_id")
4912 "type", "lxc_proxy_charm"
4913 ) # default value for backward compatibility - proxy charm
4916 "charm for member_vnf_index={} vdu_id={} kdu_name={} vdu_count_index={} has not "
4917 "execution environment".format(
4918 member_vnf_index
, vdu_id
, kdu_name
, vdu_count_index
4921 return ee_id
, vca_type
4923 async def _ns_execute_primitive(
4929 retries_interval
=30,
4936 if primitive
== "config":
4937 primitive_params
= {"params": primitive_params
}
4939 vca_type
= vca_type
or "lxc_proxy_charm"
4943 output
= await asyncio
.wait_for(
4944 self
.vca_map
[vca_type
].exec_primitive(
4946 primitive_name
=primitive
,
4947 params_dict
=primitive_params
,
4948 progress_timeout
=self
.timeout
.progress_primitive
,
4949 total_timeout
=self
.timeout
.primitive
,
4954 timeout
=timeout
or self
.timeout
.primitive
,
4958 except asyncio
.CancelledError
:
4960 except Exception as e
:
4964 "Error executing action {} on {} -> {}".format(
4969 await asyncio
.sleep(retries_interval
)
4971 if isinstance(e
, asyncio
.TimeoutError
):
4973 message
="Timed out waiting for action to complete"
4975 return "FAILED", getattr(e
, "message", repr(e
))
4977 return "COMPLETED", output
4979 except (LcmException
, asyncio
.CancelledError
):
4981 except Exception as e
:
4982 return "FAIL", "Error executing action {}: {}".format(primitive
, e
)
4984 async def vca_status_refresh(self
, nsr_id
, nslcmop_id
):
4986 Updating the vca_status with latest juju information in nsrs record
4987 :param: nsr_id: Id of the nsr
4988 :param: nslcmop_id: Id of the nslcmop
4992 self
.logger
.debug("Task ns={} action={} Enter".format(nsr_id
, nslcmop_id
))
4993 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
4994 vca_id
= self
.get_vca_id({}, db_nsr
)
4995 if db_nsr
["_admin"]["deployed"]["K8s"]:
4996 for _
, k8s
in enumerate(db_nsr
["_admin"]["deployed"]["K8s"]):
4997 cluster_uuid
, kdu_instance
, cluster_type
= (
4998 k8s
["k8scluster-uuid"],
4999 k8s
["kdu-instance"],
5000 k8s
["k8scluster-type"],
5002 await self
._on
_update
_k
8s
_db
(
5003 cluster_uuid
=cluster_uuid
,
5004 kdu_instance
=kdu_instance
,
5005 filter={"_id": nsr_id
},
5007 cluster_type
=cluster_type
,
5010 for vca_index
, _
in enumerate(db_nsr
["_admin"]["deployed"]["VCA"]):
5011 table
, filter = "nsrs", {"_id": nsr_id
}
5012 path
= "_admin.deployed.VCA.{}.".format(vca_index
)
5013 await self
._on
_update
_n
2vc
_db
(table
, filter, path
, {})
5015 self
.logger
.debug("Task ns={} action={} Exit".format(nsr_id
, nslcmop_id
))
5016 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_vca_status_refresh")
5018 async def action(self
, nsr_id
, nslcmop_id
):
5019 # Try to lock HA task here
5020 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA("ns", "nslcmops", nslcmop_id
)
5021 if not task_is_locked_by_me
:
5024 logging_text
= "Task ns={} action={} ".format(nsr_id
, nslcmop_id
)
5025 self
.logger
.debug(logging_text
+ "Enter")
5026 # get all needed from database
5030 db_nslcmop_update
= {}
5031 nslcmop_operation_state
= None
5032 error_description_nslcmop
= None
5036 # wait for any previous tasks in process
5037 step
= "Waiting for previous operations to terminate"
5038 await self
.lcm_tasks
.waitfor_related_HA("ns", "nslcmops", nslcmop_id
)
5040 self
._write
_ns
_status
(
5043 current_operation
="RUNNING ACTION",
5044 current_operation_id
=nslcmop_id
,
5047 step
= "Getting information from database"
5048 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
5049 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
5050 if db_nslcmop
["operationParams"].get("primitive_params"):
5051 db_nslcmop
["operationParams"]["primitive_params"] = json
.loads(
5052 db_nslcmop
["operationParams"]["primitive_params"]
5055 nsr_deployed
= db_nsr
["_admin"].get("deployed")
5056 vnf_index
= db_nslcmop
["operationParams"].get("member_vnf_index")
5057 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
5058 kdu_name
= db_nslcmop
["operationParams"].get("kdu_name")
5059 vdu_count_index
= db_nslcmop
["operationParams"].get("vdu_count_index")
5060 primitive
= db_nslcmop
["operationParams"]["primitive"]
5061 primitive_params
= db_nslcmop
["operationParams"]["primitive_params"]
5062 timeout_ns_action
= db_nslcmop
["operationParams"].get(
5063 "timeout_ns_action", self
.timeout
.primitive
5067 step
= "Getting vnfr from database"
5068 db_vnfr
= self
.db
.get_one(
5069 "vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
}
5071 if db_vnfr
.get("kdur"):
5073 for kdur
in db_vnfr
["kdur"]:
5074 if kdur
.get("additionalParams"):
5075 kdur
["additionalParams"] = json
.loads(
5076 kdur
["additionalParams"]
5078 kdur_list
.append(kdur
)
5079 db_vnfr
["kdur"] = kdur_list
5080 step
= "Getting vnfd from database"
5081 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
5083 # Sync filesystem before running a primitive
5084 self
.fs
.sync(db_vnfr
["vnfd-id"])
5086 step
= "Getting nsd from database"
5087 db_nsd
= self
.db
.get_one("nsds", {"_id": db_nsr
["nsd-id"]})
5089 vca_id
= self
.get_vca_id(db_vnfr
, db_nsr
)
5090 # for backward compatibility
5091 if nsr_deployed
and isinstance(nsr_deployed
.get("VCA"), dict):
5092 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
5093 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
5094 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
5096 # look for primitive
5097 config_primitive_desc
= descriptor_configuration
= None
5099 descriptor_configuration
= get_configuration(db_vnfd
, vdu_id
)
5101 descriptor_configuration
= get_configuration(db_vnfd
, kdu_name
)
5103 descriptor_configuration
= get_configuration(db_vnfd
, db_vnfd
["id"])
5105 descriptor_configuration
= db_nsd
.get("ns-configuration")
5107 if descriptor_configuration
and descriptor_configuration
.get(
5110 for config_primitive
in descriptor_configuration
["config-primitive"]:
5111 if config_primitive
["name"] == primitive
:
5112 config_primitive_desc
= config_primitive
5115 if not config_primitive_desc
:
5116 if not (kdu_name
and primitive
in ("upgrade", "rollback", "status")):
5118 "Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".format(
5122 primitive_name
= primitive
5123 ee_descriptor_id
= None
5125 primitive_name
= config_primitive_desc
.get(
5126 "execution-environment-primitive", primitive
5128 ee_descriptor_id
= config_primitive_desc
.get(
5129 "execution-environment-ref"
5135 (x
for x
in db_vnfr
["vdur"] if x
["vdu-id-ref"] == vdu_id
), None
5137 desc_params
= parse_yaml_strings(vdur
.get("additionalParams"))
5140 (x
for x
in db_vnfr
["kdur"] if x
["kdu-name"] == kdu_name
), None
5142 desc_params
= parse_yaml_strings(kdur
.get("additionalParams"))
5144 desc_params
= parse_yaml_strings(
5145 db_vnfr
.get("additionalParamsForVnf")
5148 desc_params
= parse_yaml_strings(db_nsr
.get("additionalParamsForNs"))
5149 if kdu_name
and get_configuration(db_vnfd
, kdu_name
):
5150 kdu_configuration
= get_configuration(db_vnfd
, kdu_name
)
5152 for primitive
in kdu_configuration
.get("initial-config-primitive", []):
5153 actions
.add(primitive
["name"])
5154 for primitive
in kdu_configuration
.get("config-primitive", []):
5155 actions
.add(primitive
["name"])
5157 nsr_deployed
["K8s"],
5158 lambda kdu
: kdu_name
== kdu
["kdu-name"]
5159 and kdu
["member-vnf-index"] == vnf_index
,
5163 if primitive_name
in actions
5164 and kdu
["k8scluster-type"] not in ("helm-chart", "helm-chart-v3")
5168 # TODO check if ns is in a proper status
5170 primitive_name
in ("upgrade", "rollback", "status") or kdu_action
5172 # kdur and desc_params already set from before
5173 if primitive_params
:
5174 desc_params
.update(primitive_params
)
5175 # TODO Check if we will need something at vnf level
5176 for index
, kdu
in enumerate(get_iterable(nsr_deployed
, "K8s")):
5178 kdu_name
== kdu
["kdu-name"]
5179 and kdu
["member-vnf-index"] == vnf_index
5184 "KDU '{}' for vnf '{}' not deployed".format(kdu_name
, vnf_index
)
5187 if kdu
.get("k8scluster-type") not in self
.k8scluster_map
:
5188 msg
= "unknown k8scluster-type '{}'".format(
5189 kdu
.get("k8scluster-type")
5191 raise LcmException(msg
)
5194 "collection": "nsrs",
5195 "filter": {"_id": nsr_id
},
5196 "path": "_admin.deployed.K8s.{}".format(index
),
5200 + "Exec k8s {} on {}.{}".format(primitive_name
, vnf_index
, kdu_name
)
5202 step
= "Executing kdu {}".format(primitive_name
)
5203 if primitive_name
== "upgrade":
5204 if desc_params
.get("kdu_model"):
5205 kdu_model
= desc_params
.get("kdu_model")
5206 del desc_params
["kdu_model"]
5208 kdu_model
= kdu
.get("kdu-model")
5209 if kdu_model
.count("/") < 2: # helm chart is not embedded
5210 parts
= kdu_model
.split(sep
=":")
5212 kdu_model
= parts
[0]
5213 if desc_params
.get("kdu_atomic_upgrade"):
5214 atomic_upgrade
= desc_params
.get(
5215 "kdu_atomic_upgrade"
5216 ).lower() in ("yes", "true", "1")
5217 del desc_params
["kdu_atomic_upgrade"]
5219 atomic_upgrade
= True
5221 detailed_status
= await asyncio
.wait_for(
5222 self
.k8scluster_map
[kdu
["k8scluster-type"]].upgrade(
5223 cluster_uuid
=kdu
.get("k8scluster-uuid"),
5224 kdu_instance
=kdu
.get("kdu-instance"),
5225 atomic
=atomic_upgrade
,
5226 kdu_model
=kdu_model
,
5229 timeout
=timeout_ns_action
,
5231 timeout
=timeout_ns_action
+ 10,
5234 logging_text
+ " Upgrade of kdu {} done".format(detailed_status
)
5236 elif primitive_name
== "rollback":
5237 detailed_status
= await asyncio
.wait_for(
5238 self
.k8scluster_map
[kdu
["k8scluster-type"]].rollback(
5239 cluster_uuid
=kdu
.get("k8scluster-uuid"),
5240 kdu_instance
=kdu
.get("kdu-instance"),
5243 timeout
=timeout_ns_action
,
5245 elif primitive_name
== "status":
5246 detailed_status
= await asyncio
.wait_for(
5247 self
.k8scluster_map
[kdu
["k8scluster-type"]].status_kdu(
5248 cluster_uuid
=kdu
.get("k8scluster-uuid"),
5249 kdu_instance
=kdu
.get("kdu-instance"),
5252 timeout
=timeout_ns_action
,
5255 kdu_instance
= kdu
.get("kdu-instance") or "{}-{}".format(
5256 kdu
["kdu-name"], nsr_id
5258 params
= self
._map
_primitive
_params
(
5259 config_primitive_desc
, primitive_params
, desc_params
5262 detailed_status
= await asyncio
.wait_for(
5263 self
.k8scluster_map
[kdu
["k8scluster-type"]].exec_primitive(
5264 cluster_uuid
=kdu
.get("k8scluster-uuid"),
5265 kdu_instance
=kdu_instance
,
5266 primitive_name
=primitive_name
,
5269 timeout
=timeout_ns_action
,
5272 timeout
=timeout_ns_action
,
5276 nslcmop_operation_state
= "COMPLETED"
5278 detailed_status
= ""
5279 nslcmop_operation_state
= "FAILED"
5281 ee_id
, vca_type
= self
._look
_for
_deployed
_vca
(
5282 nsr_deployed
["VCA"],
5283 member_vnf_index
=vnf_index
,
5285 vdu_count_index
=vdu_count_index
,
5286 ee_descriptor_id
=ee_descriptor_id
,
5288 for vca_index
, vca_deployed
in enumerate(
5289 db_nsr
["_admin"]["deployed"]["VCA"]
5291 if vca_deployed
.get("member-vnf-index") == vnf_index
:
5293 "collection": "nsrs",
5294 "filter": {"_id": nsr_id
},
5295 "path": "_admin.deployed.VCA.{}.".format(vca_index
),
5299 nslcmop_operation_state
,
5301 ) = await self
._ns
_execute
_primitive
(
5303 primitive
=primitive_name
,
5304 primitive_params
=self
._map
_primitive
_params
(
5305 config_primitive_desc
, primitive_params
, desc_params
5307 timeout
=timeout_ns_action
,
5313 db_nslcmop_update
["detailed-status"] = detailed_status
5314 error_description_nslcmop
= (
5315 detailed_status
if nslcmop_operation_state
== "FAILED" else ""
5319 + "Done with result {} {}".format(
5320 nslcmop_operation_state
, detailed_status
5323 return # database update is called inside finally
5325 except (DbException
, LcmException
, N2VCException
, K8sException
) as e
:
5326 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
5328 except asyncio
.CancelledError
:
5330 logging_text
+ "Cancelled Exception while '{}'".format(step
)
5332 exc
= "Operation was cancelled"
5333 except asyncio
.TimeoutError
:
5334 self
.logger
.error(logging_text
+ "Timeout while '{}'".format(step
))
5336 except Exception as e
:
5337 exc
= traceback
.format_exc()
5338 self
.logger
.critical(
5339 logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
),
5348 ) = error_description_nslcmop
= "FAILED {}: {}".format(step
, exc
)
5349 nslcmop_operation_state
= "FAILED"
5351 self
._write
_ns
_status
(
5355 ], # TODO check if degraded. For the moment use previous status
5356 current_operation
="IDLE",
5357 current_operation_id
=None,
5358 # error_description=error_description_nsr,
5359 # error_detail=error_detail,
5360 other_update
=db_nsr_update
,
5363 self
._write
_op
_status
(
5366 error_message
=error_description_nslcmop
,
5367 operation_state
=nslcmop_operation_state
,
5368 other_update
=db_nslcmop_update
,
5371 if nslcmop_operation_state
:
5373 await self
.msg
.aiowrite(
5378 "nslcmop_id": nslcmop_id
,
5379 "operationState": nslcmop_operation_state
,
5382 except Exception as e
:
5384 logging_text
+ "kafka_write notification Exception {}".format(e
)
5386 self
.logger
.debug(logging_text
+ "Exit")
5387 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_action")
5388 return nslcmop_operation_state
, detailed_status
5390 async def terminate_vdus(
5391 self
, db_vnfr
, member_vnf_index
, db_nsr
, update_db_nslcmops
, stage
, logging_text
5393 """This method terminates VDUs
5396 db_vnfr: VNF instance record
5397 member_vnf_index: VNF index to identify the VDUs to be removed
5398 db_nsr: NS instance record
5399 update_db_nslcmops: Nslcmop update record
5401 vca_scaling_info
= []
5402 scaling_info
= {"scaling_group_name": "vdu_autoscale", "vdu": [], "kdu": []}
5403 scaling_info
["scaling_direction"] = "IN"
5404 scaling_info
["vdu-delete"] = {}
5405 scaling_info
["kdu-delete"] = {}
5406 db_vdur
= db_vnfr
.get("vdur")
5407 vdur_list
= copy(db_vdur
)
5409 for index
, vdu
in enumerate(vdur_list
):
5410 vca_scaling_info
.append(
5412 "osm_vdu_id": vdu
["vdu-id-ref"],
5413 "member-vnf-index": member_vnf_index
,
5415 "vdu_index": count_index
,
5418 scaling_info
["vdu-delete"][vdu
["vdu-id-ref"]] = count_index
5419 scaling_info
["vdu"].append(
5421 "name": vdu
.get("name") or vdu
.get("vdu-name"),
5422 "vdu_id": vdu
["vdu-id-ref"],
5426 for interface
in vdu
["interfaces"]:
5427 scaling_info
["vdu"][index
]["interface"].append(
5429 "name": interface
["name"],
5430 "ip_address": interface
["ip-address"],
5431 "mac_address": interface
.get("mac-address"),
5434 self
.logger
.info("NS update scaling info{}".format(scaling_info
))
5435 stage
[2] = "Terminating VDUs"
5436 if scaling_info
.get("vdu-delete"):
5437 # scale_process = "RO"
5438 if self
.ro_config
.ng
:
5439 await self
._scale
_ng
_ro
(
5448 async def remove_vnf(self
, nsr_id
, nslcmop_id
, vnf_instance_id
):
5449 """This method is to Remove VNF instances from NS.
5452 nsr_id: NS instance id
5453 nslcmop_id: nslcmop id of update
5454 vnf_instance_id: id of the VNF instance to be removed
5457 result: (str, str) COMPLETED/FAILED, details
5461 logging_text
= "Task ns={} update ".format(nsr_id
)
5462 check_vnfr_count
= len(self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
}))
5463 self
.logger
.info("check_vnfr_count {}".format(check_vnfr_count
))
5464 if check_vnfr_count
> 1:
5465 stage
= ["", "", ""]
5466 step
= "Getting nslcmop from database"
5468 step
+ " after having waited for previous tasks to be completed"
5470 # db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
5471 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
5472 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnf_instance_id
})
5473 member_vnf_index
= db_vnfr
["member-vnf-index-ref"]
5474 """ db_vnfr = self.db.get_one(
5475 "vnfrs", {"member-vnf-index-ref": member_vnf_index, "nsr-id-ref": nsr_id}) """
5477 update_db_nslcmops
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
5478 await self
.terminate_vdus(
5487 constituent_vnfr
= db_nsr
.get("constituent-vnfr-ref")
5488 constituent_vnfr
.remove(db_vnfr
.get("_id"))
5489 db_nsr_update
["constituent-vnfr-ref"] = db_nsr
.get(
5490 "constituent-vnfr-ref"
5492 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
5493 self
.db
.del_one("vnfrs", {"_id": db_vnfr
.get("_id")})
5494 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
5495 return "COMPLETED", "Done"
5497 step
= "Terminate VNF Failed with"
5499 "{} Cannot terminate the last VNF in this NS.".format(
5503 except (LcmException
, asyncio
.CancelledError
):
5505 except Exception as e
:
5506 self
.logger
.debug("Error removing VNF {}".format(e
))
5507 return "FAILED", "Error removing VNF {}".format(e
)
5509 async def _ns_redeploy_vnf(
5517 """This method updates and redeploys VNF instances
5520 nsr_id: NS instance id
5521 nslcmop_id: nslcmop id
5522 db_vnfd: VNF descriptor
5523 db_vnfr: VNF instance record
5524 db_nsr: NS instance record
5527 result: (str, str) COMPLETED/FAILED, details
5531 stage
= ["", "", ""]
5532 logging_text
= "Task ns={} update ".format(nsr_id
)
5533 latest_vnfd_revision
= db_vnfd
["_admin"].get("revision")
5534 member_vnf_index
= db_vnfr
["member-vnf-index-ref"]
5536 # Terminate old VNF resources
5537 update_db_nslcmops
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
5538 await self
.terminate_vdus(
5547 # old_vnfd_id = db_vnfr["vnfd-id"]
5548 # new_db_vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
5549 new_db_vnfd
= db_vnfd
5550 # new_vnfd_ref = new_db_vnfd["id"]
5551 # new_vnfd_id = vnfd_id
5555 for cp
in new_db_vnfd
.get("ext-cpd", ()):
5557 "name": cp
.get("id"),
5558 "connection-point-id": cp
.get("int-cpd", {}).get("cpd"),
5559 "connection-point-vdu-id": cp
.get("int-cpd", {}).get("vdu-id"),
5562 new_vnfr_cp
.append(vnf_cp
)
5563 new_vdur
= update_db_nslcmops
["operationParams"]["newVdur"]
5564 # new_vdur = self._create_vdur_descriptor_from_vnfd(db_nsd, db_vnfd, old_db_vnfd, vnfd_id, db_nsr, member_vnf_index)
5565 # new_vnfr_update = {"vnfd-ref": new_vnfd_ref, "vnfd-id": new_vnfd_id, "connection-point": new_vnfr_cp, "vdur": new_vdur, "ip-address": ""}
5567 "revision": latest_vnfd_revision
,
5568 "connection-point": new_vnfr_cp
,
5572 self
.update_db_2("vnfrs", db_vnfr
["_id"], new_vnfr_update
)
5573 updated_db_vnfr
= self
.db
.get_one(
5575 {"member-vnf-index-ref": member_vnf_index
, "nsr-id-ref": nsr_id
},
5578 # Instantiate new VNF resources
5579 # update_db_nslcmops = self.db.get_one("nslcmops", {"_id": nslcmop_id})
5580 vca_scaling_info
= []
5581 scaling_info
= {"scaling_group_name": "vdu_autoscale", "vdu": [], "kdu": []}
5582 scaling_info
["scaling_direction"] = "OUT"
5583 scaling_info
["vdu-create"] = {}
5584 scaling_info
["kdu-create"] = {}
5585 vdud_instantiate_list
= db_vnfd
["vdu"]
5586 for index
, vdud
in enumerate(vdud_instantiate_list
):
5587 cloud_init_text
= self
._get
_vdu
_cloud
_init
_content
(vdud
, db_vnfd
)
5589 additional_params
= (
5590 self
._get
_vdu
_additional
_params
(updated_db_vnfr
, vdud
["id"])
5593 cloud_init_list
= []
5595 # TODO Information of its own ip is not available because db_vnfr is not updated.
5596 additional_params
["OSM"] = get_osm_params(
5597 updated_db_vnfr
, vdud
["id"], 1
5599 cloud_init_list
.append(
5600 self
._parse
_cloud
_init
(
5607 vca_scaling_info
.append(
5609 "osm_vdu_id": vdud
["id"],
5610 "member-vnf-index": member_vnf_index
,
5612 "vdu_index": count_index
,
5615 scaling_info
["vdu-create"][vdud
["id"]] = count_index
5616 if self
.ro_config
.ng
:
5618 "New Resources to be deployed: {}".format(scaling_info
)
5620 await self
._scale
_ng
_ro
(
5628 return "COMPLETED", "Done"
5629 except (LcmException
, asyncio
.CancelledError
):
5631 except Exception as e
:
5632 self
.logger
.debug("Error updating VNF {}".format(e
))
5633 return "FAILED", "Error updating VNF {}".format(e
)
5635 async def _ns_charm_upgrade(
5641 timeout
: float = None,
5643 """This method upgrade charms in VNF instances
5646 ee_id: Execution environment id
5647 path: Local path to the charm
5649 charm_type: Charm type can be lxc-proxy-charm, native-charm or k8s-proxy-charm
5650 timeout: (Float) Timeout for the ns update operation
5653 result: (str, str) COMPLETED/FAILED, details
5656 charm_type
= charm_type
or "lxc_proxy_charm"
5657 output
= await self
.vca_map
[charm_type
].upgrade_charm(
5661 charm_type
=charm_type
,
5662 timeout
=timeout
or self
.timeout
.ns_update
,
5666 return "COMPLETED", output
5668 except (LcmException
, asyncio
.CancelledError
):
5671 except Exception as e
:
5672 self
.logger
.debug("Error upgrading charm {}".format(path
))
5674 return "FAILED", "Error upgrading charm {}: {}".format(path
, e
)
5676 async def update(self
, nsr_id
, nslcmop_id
):
5677 """Update NS according to different update types
5679 This method performs upgrade of VNF instances then updates the revision
5680 number in VNF record
5683 nsr_id: Network service will be updated
5684 nslcmop_id: ns lcm operation id
5687 It may raise DbException, LcmException, N2VCException, K8sException
5690 # Try to lock HA task here
5691 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA("ns", "nslcmops", nslcmop_id
)
5692 if not task_is_locked_by_me
:
5695 logging_text
= "Task ns={} update={} ".format(nsr_id
, nslcmop_id
)
5696 self
.logger
.debug(logging_text
+ "Enter")
5698 # Set the required variables to be filled up later
5700 db_nslcmop_update
= {}
5702 nslcmop_operation_state
= None
5704 error_description_nslcmop
= ""
5706 change_type
= "updated"
5707 detailed_status
= ""
5708 member_vnf_index
= None
5711 # wait for any previous tasks in process
5712 step
= "Waiting for previous operations to terminate"
5713 await self
.lcm_tasks
.waitfor_related_HA("ns", "nslcmops", nslcmop_id
)
5714 self
._write
_ns
_status
(
5717 current_operation
="UPDATING",
5718 current_operation_id
=nslcmop_id
,
5721 step
= "Getting nslcmop from database"
5722 db_nslcmop
= self
.db
.get_one(
5723 "nslcmops", {"_id": nslcmop_id
}, fail_on_empty
=False
5725 update_type
= db_nslcmop
["operationParams"]["updateType"]
5727 step
= "Getting nsr from database"
5728 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
5729 old_operational_status
= db_nsr
["operational-status"]
5730 db_nsr_update
["operational-status"] = "updating"
5731 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
5732 nsr_deployed
= db_nsr
["_admin"].get("deployed")
5734 if update_type
== "CHANGE_VNFPKG":
5735 # Get the input parameters given through update request
5736 vnf_instance_id
= db_nslcmop
["operationParams"][
5737 "changeVnfPackageData"
5738 ].get("vnfInstanceId")
5740 vnfd_id
= db_nslcmop
["operationParams"]["changeVnfPackageData"].get(
5743 timeout_seconds
= db_nslcmop
["operationParams"].get("timeout_ns_update")
5745 step
= "Getting vnfr from database"
5746 db_vnfr
= self
.db
.get_one(
5747 "vnfrs", {"_id": vnf_instance_id
}, fail_on_empty
=False
5750 step
= "Getting vnfds from database"
5752 latest_vnfd
= self
.db
.get_one(
5753 "vnfds", {"_id": vnfd_id
}, fail_on_empty
=False
5755 latest_vnfd_revision
= latest_vnfd
["_admin"].get("revision")
5758 current_vnf_revision
= db_vnfr
.get("revision", 1)
5759 current_vnfd
= self
.db
.get_one(
5761 {"_id": vnfd_id
+ ":" + str(current_vnf_revision
)},
5762 fail_on_empty
=False,
5764 # Charm artifact paths will be filled up later
5766 current_charm_artifact_path
,
5767 target_charm_artifact_path
,
5768 charm_artifact_paths
,
5770 ) = ([], [], [], [])
5772 step
= "Checking if revision has changed in VNFD"
5773 if current_vnf_revision
!= latest_vnfd_revision
:
5774 change_type
= "policy_updated"
5776 # There is new revision of VNFD, update operation is required
5777 current_vnfd_path
= vnfd_id
+ ":" + str(current_vnf_revision
)
5778 latest_vnfd_path
= vnfd_id
+ ":" + str(latest_vnfd_revision
)
5780 step
= "Removing the VNFD packages if they exist in the local path"
5781 shutil
.rmtree(self
.fs
.path
+ current_vnfd_path
, ignore_errors
=True)
5782 shutil
.rmtree(self
.fs
.path
+ latest_vnfd_path
, ignore_errors
=True)
5784 step
= "Get the VNFD packages from FSMongo"
5785 self
.fs
.sync(from_path
=latest_vnfd_path
)
5786 self
.fs
.sync(from_path
=current_vnfd_path
)
5789 "Get the charm-type, charm-id, ee-id if there is deployed VCA"
5791 current_base_folder
= current_vnfd
["_admin"]["storage"]
5792 latest_base_folder
= latest_vnfd
["_admin"]["storage"]
5794 for vca_index
, vca_deployed
in enumerate(
5795 get_iterable(nsr_deployed
, "VCA")
5797 vnf_index
= db_vnfr
.get("member-vnf-index-ref")
5799 # Getting charm-id and charm-type
5800 if vca_deployed
.get("member-vnf-index") == vnf_index
:
5801 vca_id
= self
.get_vca_id(db_vnfr
, db_nsr
)
5802 vca_type
= vca_deployed
.get("type")
5803 vdu_count_index
= vca_deployed
.get("vdu_count_index")
5806 ee_id
= vca_deployed
.get("ee_id")
5808 step
= "Getting descriptor config"
5809 if current_vnfd
.get("kdu"):
5810 search_key
= "kdu_name"
5812 search_key
= "vnfd_id"
5814 entity_id
= vca_deployed
.get(search_key
)
5816 descriptor_config
= get_configuration(
5817 current_vnfd
, entity_id
5820 if "execution-environment-list" in descriptor_config
:
5821 ee_list
= descriptor_config
.get(
5822 "execution-environment-list", []
5827 # There could be several charm used in the same VNF
5828 for ee_item
in ee_list
:
5829 if ee_item
.get("juju"):
5830 step
= "Getting charm name"
5831 charm_name
= ee_item
["juju"].get("charm")
5833 step
= "Setting Charm artifact paths"
5834 current_charm_artifact_path
.append(
5835 get_charm_artifact_path(
5836 current_base_folder
,
5839 current_vnf_revision
,
5842 target_charm_artifact_path
.append(
5843 get_charm_artifact_path(
5847 latest_vnfd_revision
,
5850 elif ee_item
.get("helm-chart"):
5851 # add chart to list and all parameters
5852 step
= "Getting helm chart name"
5853 chart_name
= ee_item
.get("helm-chart")
5855 ee_item
.get("helm-version")
5856 and ee_item
.get("helm-version") == "v2"
5860 vca_type
= "helm-v3"
5861 step
= "Setting Helm chart artifact paths"
5863 helm_artifacts
.append(
5865 "current_artifact_path": get_charm_artifact_path(
5866 current_base_folder
,
5869 current_vnf_revision
,
5871 "target_artifact_path": get_charm_artifact_path(
5875 latest_vnfd_revision
,
5878 "vca_index": vca_index
,
5879 "vdu_index": vdu_count_index
,
5883 charm_artifact_paths
= zip(
5884 current_charm_artifact_path
, target_charm_artifact_path
5887 step
= "Checking if software version has changed in VNFD"
5888 if find_software_version(current_vnfd
) != find_software_version(
5891 step
= "Checking if existing VNF has charm"
5892 for current_charm_path
, target_charm_path
in list(
5893 charm_artifact_paths
5895 if current_charm_path
:
5897 "Software version change is not supported as VNF instance {} has charm.".format(
5902 # There is no change in the charm package, then redeploy the VNF
5903 # based on new descriptor
5904 step
= "Redeploying VNF"
5905 member_vnf_index
= db_vnfr
["member-vnf-index-ref"]
5906 (result
, detailed_status
) = await self
._ns
_redeploy
_vnf
(
5907 nsr_id
, nslcmop_id
, latest_vnfd
, db_vnfr
, db_nsr
5909 if result
== "FAILED":
5910 nslcmop_operation_state
= result
5911 error_description_nslcmop
= detailed_status
5912 db_nslcmop_update
["detailed-status"] = detailed_status
5915 + " step {} Done with result {} {}".format(
5916 step
, nslcmop_operation_state
, detailed_status
5921 step
= "Checking if any charm package has changed or not"
5922 for current_charm_path
, target_charm_path
in list(
5923 charm_artifact_paths
5927 and target_charm_path
5928 and self
.check_charm_hash_changed(
5929 current_charm_path
, target_charm_path
5932 step
= "Checking whether VNF uses juju bundle"
5933 if check_juju_bundle_existence(current_vnfd
):
5935 "Charm upgrade is not supported for the instance which"
5936 " uses juju-bundle: {}".format(
5937 check_juju_bundle_existence(current_vnfd
)
5941 step
= "Upgrading Charm"
5945 ) = await self
._ns
_charm
_upgrade
(
5948 charm_type
=vca_type
,
5949 path
=self
.fs
.path
+ target_charm_path
,
5950 timeout
=timeout_seconds
,
5953 if result
== "FAILED":
5954 nslcmop_operation_state
= result
5955 error_description_nslcmop
= detailed_status
5957 db_nslcmop_update
["detailed-status"] = detailed_status
5960 + " step {} Done with result {} {}".format(
5961 step
, nslcmop_operation_state
, detailed_status
5965 step
= "Updating policies"
5966 member_vnf_index
= db_vnfr
["member-vnf-index-ref"]
5967 result
= "COMPLETED"
5968 detailed_status
= "Done"
5969 db_nslcmop_update
["detailed-status"] = "Done"
5972 for item
in helm_artifacts
:
5974 item
["current_artifact_path"]
5975 and item
["target_artifact_path"]
5976 and self
.check_charm_hash_changed(
5977 item
["current_artifact_path"],
5978 item
["target_artifact_path"],
5982 db_update_entry
= "_admin.deployed.VCA.{}.".format(
5985 vnfr_id
= db_vnfr
["_id"]
5986 osm_config
= {"osm": {"ns_id": nsr_id
, "vnf_id": vnfr_id
}}
5988 "collection": "nsrs",
5989 "filter": {"_id": nsr_id
},
5990 "path": db_update_entry
,
5992 vca_type
, namespace
, helm_id
= get_ee_id_parts(item
["ee_id"])
5993 await self
.vca_map
[vca_type
].upgrade_execution_environment(
5994 namespace
=namespace
,
5998 artifact_path
=item
["target_artifact_path"],
6001 vnf_id
= db_vnfr
.get("vnfd-ref")
6002 config_descriptor
= get_configuration(latest_vnfd
, vnf_id
)
6003 self
.logger
.debug("get ssh key block")
6007 ("config-access", "ssh-access", "required"),
6009 # Needed to inject a ssh key
6012 ("config-access", "ssh-access", "default-user"),
6015 "Install configuration Software, getting public ssh key"
6017 pub_key
= await self
.vca_map
[
6019 ].get_ee_ssh_public__key(
6020 ee_id
=ee_id
, db_dict
=db_dict
, vca_id
=vca_id
6024 "Insert public key into VM user={} ssh_key={}".format(
6028 self
.logger
.debug(logging_text
+ step
)
6030 # wait for RO (ip-address) Insert pub_key into VM
6031 rw_mgmt_ip
= await self
.wait_vm_up_insert_key_ro(
6041 initial_config_primitive_list
= config_descriptor
.get(
6042 "initial-config-primitive"
6044 config_primitive
= next(
6047 for p
in initial_config_primitive_list
6048 if p
["name"] == "config"
6052 if not config_primitive
:
6055 deploy_params
= {"OSM": get_osm_params(db_vnfr
)}
6057 deploy_params
["rw_mgmt_ip"] = rw_mgmt_ip
6058 if db_vnfr
.get("additionalParamsForVnf"):
6059 deploy_params
.update(
6061 db_vnfr
["additionalParamsForVnf"].copy()
6064 primitive_params_
= self
._map
_primitive
_params
(
6065 config_primitive
, {}, deploy_params
6068 step
= "execute primitive '{}' params '{}'".format(
6069 config_primitive
["name"], primitive_params_
6071 self
.logger
.debug(logging_text
+ step
)
6072 await self
.vca_map
[vca_type
].exec_primitive(
6074 primitive_name
=config_primitive
["name"],
6075 params_dict
=primitive_params_
,
6081 step
= "Updating policies"
6082 member_vnf_index
= db_vnfr
["member-vnf-index-ref"]
6083 detailed_status
= "Done"
6084 db_nslcmop_update
["detailed-status"] = "Done"
6086 # If nslcmop_operation_state is None, so any operation is not failed.
6087 if not nslcmop_operation_state
:
6088 nslcmop_operation_state
= "COMPLETED"
6090 # If update CHANGE_VNFPKG nslcmop_operation is successful
6091 # vnf revision need to be updated
6092 vnfr_update
["revision"] = latest_vnfd_revision
6093 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
6097 + " task Done with result {} {}".format(
6098 nslcmop_operation_state
, detailed_status
6101 elif update_type
== "REMOVE_VNF":
6102 # This part is included in https://osm.etsi.org/gerrit/11876
6103 vnf_instance_id
= db_nslcmop
["operationParams"]["removeVnfInstanceId"]
6104 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnf_instance_id
})
6105 member_vnf_index
= db_vnfr
["member-vnf-index-ref"]
6106 step
= "Removing VNF"
6107 (result
, detailed_status
) = await self
.remove_vnf(
6108 nsr_id
, nslcmop_id
, vnf_instance_id
6110 if result
== "FAILED":
6111 nslcmop_operation_state
= result
6112 error_description_nslcmop
= detailed_status
6113 db_nslcmop_update
["detailed-status"] = detailed_status
6114 change_type
= "vnf_terminated"
6115 if not nslcmop_operation_state
:
6116 nslcmop_operation_state
= "COMPLETED"
6119 + " task Done with result {} {}".format(
6120 nslcmop_operation_state
, detailed_status
6124 elif update_type
== "OPERATE_VNF":
6125 vnf_id
= db_nslcmop
["operationParams"]["operateVnfData"][
6128 operation_type
= db_nslcmop
["operationParams"]["operateVnfData"][
6131 additional_param
= db_nslcmop
["operationParams"]["operateVnfData"][
6134 (result
, detailed_status
) = await self
.rebuild_start_stop(
6135 nsr_id
, nslcmop_id
, vnf_id
, additional_param
, operation_type
6137 if result
== "FAILED":
6138 nslcmop_operation_state
= result
6139 error_description_nslcmop
= detailed_status
6140 db_nslcmop_update
["detailed-status"] = detailed_status
6141 if not nslcmop_operation_state
:
6142 nslcmop_operation_state
= "COMPLETED"
6145 + " task Done with result {} {}".format(
6146 nslcmop_operation_state
, detailed_status
6150 # If nslcmop_operation_state is None, so any operation is not failed.
6151 # All operations are executed in overall.
6152 if not nslcmop_operation_state
:
6153 nslcmop_operation_state
= "COMPLETED"
6154 db_nsr_update
["operational-status"] = old_operational_status
6156 except (DbException
, LcmException
, N2VCException
, K8sException
) as e
:
6157 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
6159 except asyncio
.CancelledError
:
6161 logging_text
+ "Cancelled Exception while '{}'".format(step
)
6163 exc
= "Operation was cancelled"
6164 except asyncio
.TimeoutError
:
6165 self
.logger
.error(logging_text
+ "Timeout while '{}'".format(step
))
6167 except Exception as e
:
6168 exc
= traceback
.format_exc()
6169 self
.logger
.critical(
6170 logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
),
6179 ) = error_description_nslcmop
= "FAILED {}: {}".format(step
, exc
)
6180 nslcmop_operation_state
= "FAILED"
6181 db_nsr_update
["operational-status"] = old_operational_status
6183 self
._write
_ns
_status
(
6185 ns_state
=db_nsr
["nsState"],
6186 current_operation
="IDLE",
6187 current_operation_id
=None,
6188 other_update
=db_nsr_update
,
6191 self
._write
_op
_status
(
6194 error_message
=error_description_nslcmop
,
6195 operation_state
=nslcmop_operation_state
,
6196 other_update
=db_nslcmop_update
,
6199 if nslcmop_operation_state
:
6203 "nslcmop_id": nslcmop_id
,
6204 "operationState": nslcmop_operation_state
,
6207 change_type
in ("vnf_terminated", "policy_updated")
6208 and member_vnf_index
6210 msg
.update({"vnf_member_index": member_vnf_index
})
6211 await self
.msg
.aiowrite("ns", change_type
, msg
)
6212 except Exception as e
:
6214 logging_text
+ "kafka_write notification Exception {}".format(e
)
6216 self
.logger
.debug(logging_text
+ "Exit")
6217 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_update")
6218 return nslcmop_operation_state
, detailed_status
6220 async def scale(self
, nsr_id
, nslcmop_id
):
6221 # Try to lock HA task here
6222 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA("ns", "nslcmops", nslcmop_id
)
6223 if not task_is_locked_by_me
:
6226 logging_text
= "Task ns={} scale={} ".format(nsr_id
, nslcmop_id
)
6227 stage
= ["", "", ""]
6228 tasks_dict_info
= {}
6229 # ^ stage, step, VIM progress
6230 self
.logger
.debug(logging_text
+ "Enter")
6231 # get all needed from database
6233 db_nslcmop_update
= {}
6236 # in case of error, indicates what part of scale was failed to put nsr at error status
6237 scale_process
= None
6238 old_operational_status
= ""
6239 old_config_status
= ""
6242 # wait for any previous tasks in process
6243 step
= "Waiting for previous operations to terminate"
6244 await self
.lcm_tasks
.waitfor_related_HA("ns", "nslcmops", nslcmop_id
)
6245 self
._write
_ns
_status
(
6248 current_operation
="SCALING",
6249 current_operation_id
=nslcmop_id
,
6252 step
= "Getting nslcmop from database"
6254 step
+ " after having waited for previous tasks to be completed"
6256 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
6258 step
= "Getting nsr from database"
6259 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
6260 old_operational_status
= db_nsr
["operational-status"]
6261 old_config_status
= db_nsr
["config-status"]
6263 step
= "Parsing scaling parameters"
6264 db_nsr_update
["operational-status"] = "scaling"
6265 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
6266 nsr_deployed
= db_nsr
["_admin"].get("deployed")
6268 vnf_index
= db_nslcmop
["operationParams"]["scaleVnfData"][
6270 ]["member-vnf-index"]
6271 scaling_group
= db_nslcmop
["operationParams"]["scaleVnfData"][
6273 ]["scaling-group-descriptor"]
6274 scaling_type
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleVnfType"]
6275 # for backward compatibility
6276 if nsr_deployed
and isinstance(nsr_deployed
.get("VCA"), dict):
6277 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
6278 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
6279 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
6281 step
= "Getting vnfr from database"
6282 db_vnfr
= self
.db
.get_one(
6283 "vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
}
6286 vca_id
= self
.get_vca_id(db_vnfr
, db_nsr
)
6288 step
= "Getting vnfd from database"
6289 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
6291 base_folder
= db_vnfd
["_admin"]["storage"]
6293 step
= "Getting scaling-group-descriptor"
6294 scaling_descriptor
= find_in_list(
6295 get_scaling_aspect(db_vnfd
),
6296 lambda scale_desc
: scale_desc
["name"] == scaling_group
,
6298 if not scaling_descriptor
:
6300 "input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
6301 "at vnfd:scaling-group-descriptor".format(scaling_group
)
6304 step
= "Sending scale order to VIM"
6305 # TODO check if ns is in a proper status
6307 if not db_nsr
["_admin"].get("scaling-group"):
6312 "_admin.scaling-group": [
6313 {"name": scaling_group
, "nb-scale-op": 0}
6317 admin_scale_index
= 0
6319 for admin_scale_index
, admin_scale_info
in enumerate(
6320 db_nsr
["_admin"]["scaling-group"]
6322 if admin_scale_info
["name"] == scaling_group
:
6323 nb_scale_op
= admin_scale_info
.get("nb-scale-op", 0)
6325 else: # not found, set index one plus last element and add new entry with the name
6326 admin_scale_index
+= 1
6328 "_admin.scaling-group.{}.name".format(admin_scale_index
)
6331 vca_scaling_info
= []
6332 scaling_info
= {"scaling_group_name": scaling_group
, "vdu": [], "kdu": []}
6333 if scaling_type
== "SCALE_OUT":
6334 if "aspect-delta-details" not in scaling_descriptor
:
6336 "Aspect delta details not fount in scaling descriptor {}".format(
6337 scaling_descriptor
["name"]
6340 # count if max-instance-count is reached
6341 deltas
= scaling_descriptor
.get("aspect-delta-details")["deltas"]
6343 scaling_info
["scaling_direction"] = "OUT"
6344 scaling_info
["vdu-create"] = {}
6345 scaling_info
["kdu-create"] = {}
6346 for delta
in deltas
:
6347 for vdu_delta
in delta
.get("vdu-delta", {}):
6348 vdud
= get_vdu(db_vnfd
, vdu_delta
["id"])
6349 # vdu_index also provides the number of instance of the targeted vdu
6350 vdu_count
= vdu_index
= get_vdur_index(db_vnfr
, vdu_delta
)
6351 cloud_init_text
= self
._get
_vdu
_cloud
_init
_content
(
6355 additional_params
= (
6356 self
._get
_vdu
_additional
_params
(db_vnfr
, vdud
["id"])
6359 cloud_init_list
= []
6361 vdu_profile
= get_vdu_profile(db_vnfd
, vdu_delta
["id"])
6362 max_instance_count
= 10
6363 if vdu_profile
and "max-number-of-instances" in vdu_profile
:
6364 max_instance_count
= vdu_profile
.get(
6365 "max-number-of-instances", 10
6368 default_instance_num
= get_number_of_instances(
6371 instances_number
= vdu_delta
.get("number-of-instances", 1)
6372 nb_scale_op
+= instances_number
6374 new_instance_count
= nb_scale_op
+ default_instance_num
6375 # Control if new count is over max and vdu count is less than max.
6376 # Then assign new instance count
6377 if new_instance_count
> max_instance_count
> vdu_count
:
6378 instances_number
= new_instance_count
- max_instance_count
6380 instances_number
= instances_number
6382 if new_instance_count
> max_instance_count
:
6384 "reached the limit of {} (max-instance-count) "
6385 "scaling-out operations for the "
6386 "scaling-group-descriptor '{}'".format(
6387 nb_scale_op
, scaling_group
6390 for x
in range(vdu_delta
.get("number-of-instances", 1)):
6392 # TODO Information of its own ip is not available because db_vnfr is not updated.
6393 additional_params
["OSM"] = get_osm_params(
6394 db_vnfr
, vdu_delta
["id"], vdu_index
+ x
6396 cloud_init_list
.append(
6397 self
._parse
_cloud
_init
(
6404 vca_scaling_info
.append(
6406 "osm_vdu_id": vdu_delta
["id"],
6407 "member-vnf-index": vnf_index
,
6409 "vdu_index": vdu_index
+ x
,
6412 scaling_info
["vdu-create"][vdu_delta
["id"]] = instances_number
6413 for kdu_delta
in delta
.get("kdu-resource-delta", {}):
6414 kdu_profile
= get_kdu_resource_profile(db_vnfd
, kdu_delta
["id"])
6415 kdu_name
= kdu_profile
["kdu-name"]
6416 resource_name
= kdu_profile
.get("resource-name", "")
6418 # Might have different kdus in the same delta
6419 # Should have list for each kdu
6420 if not scaling_info
["kdu-create"].get(kdu_name
, None):
6421 scaling_info
["kdu-create"][kdu_name
] = []
6423 kdur
= get_kdur(db_vnfr
, kdu_name
)
6424 if kdur
.get("helm-chart"):
6425 k8s_cluster_type
= "helm-chart-v3"
6426 self
.logger
.debug("kdur: {}".format(kdur
))
6428 kdur
.get("helm-version")
6429 and kdur
.get("helm-version") == "v2"
6431 k8s_cluster_type
= "helm-chart"
6432 elif kdur
.get("juju-bundle"):
6433 k8s_cluster_type
= "juju-bundle"
6436 "kdu type for kdu='{}.{}' is neither helm-chart nor "
6437 "juju-bundle. Maybe an old NBI version is running".format(
6438 db_vnfr
["member-vnf-index-ref"], kdu_name
6442 max_instance_count
= 10
6443 if kdu_profile
and "max-number-of-instances" in kdu_profile
:
6444 max_instance_count
= kdu_profile
.get(
6445 "max-number-of-instances", 10
6448 nb_scale_op
+= kdu_delta
.get("number-of-instances", 1)
6449 deployed_kdu
, _
= get_deployed_kdu(
6450 nsr_deployed
, kdu_name
, vnf_index
6452 if deployed_kdu
is None:
6454 "KDU '{}' for vnf '{}' not deployed".format(
6458 kdu_instance
= deployed_kdu
.get("kdu-instance")
6459 instance_num
= await self
.k8scluster_map
[
6465 cluster_uuid
=deployed_kdu
.get("k8scluster-uuid"),
6466 kdu_model
=deployed_kdu
.get("kdu-model"),
6468 kdu_replica_count
= instance_num
+ kdu_delta
.get(
6469 "number-of-instances", 1
6472 # Control if new count is over max and instance_num is less than max.
6473 # Then assign max instance number to kdu replica count
6474 if kdu_replica_count
> max_instance_count
> instance_num
:
6475 kdu_replica_count
= max_instance_count
6476 if kdu_replica_count
> max_instance_count
:
6478 "reached the limit of {} (max-instance-count) "
6479 "scaling-out operations for the "
6480 "scaling-group-descriptor '{}'".format(
6481 instance_num
, scaling_group
6485 for x
in range(kdu_delta
.get("number-of-instances", 1)):
6486 vca_scaling_info
.append(
6488 "osm_kdu_id": kdu_name
,
6489 "member-vnf-index": vnf_index
,
6491 "kdu_index": instance_num
+ x
- 1,
6494 scaling_info
["kdu-create"][kdu_name
].append(
6496 "member-vnf-index": vnf_index
,
6498 "k8s-cluster-type": k8s_cluster_type
,
6499 "resource-name": resource_name
,
6500 "scale": kdu_replica_count
,
6503 elif scaling_type
== "SCALE_IN":
6504 deltas
= scaling_descriptor
.get("aspect-delta-details")["deltas"]
6506 scaling_info
["scaling_direction"] = "IN"
6507 scaling_info
["vdu-delete"] = {}
6508 scaling_info
["kdu-delete"] = {}
6510 for delta
in deltas
:
6511 for vdu_delta
in delta
.get("vdu-delta", {}):
6512 vdu_count
= vdu_index
= get_vdur_index(db_vnfr
, vdu_delta
)
6513 min_instance_count
= 0
6514 vdu_profile
= get_vdu_profile(db_vnfd
, vdu_delta
["id"])
6515 if vdu_profile
and "min-number-of-instances" in vdu_profile
:
6516 min_instance_count
= vdu_profile
["min-number-of-instances"]
6518 default_instance_num
= get_number_of_instances(
6519 db_vnfd
, vdu_delta
["id"]
6521 instance_num
= vdu_delta
.get("number-of-instances", 1)
6522 nb_scale_op
-= instance_num
6524 new_instance_count
= nb_scale_op
+ default_instance_num
6526 if new_instance_count
< min_instance_count
< vdu_count
:
6527 instances_number
= min_instance_count
- new_instance_count
6529 instances_number
= instance_num
6531 if new_instance_count
< min_instance_count
:
6533 "reached the limit of {} (min-instance-count) scaling-in operations for the "
6534 "scaling-group-descriptor '{}'".format(
6535 nb_scale_op
, scaling_group
6538 for x
in range(vdu_delta
.get("number-of-instances", 1)):
6539 vca_scaling_info
.append(
6541 "osm_vdu_id": vdu_delta
["id"],
6542 "member-vnf-index": vnf_index
,
6544 "vdu_index": vdu_index
- 1 - x
,
6547 scaling_info
["vdu-delete"][vdu_delta
["id"]] = instances_number
6548 for kdu_delta
in delta
.get("kdu-resource-delta", {}):
6549 kdu_profile
= get_kdu_resource_profile(db_vnfd
, kdu_delta
["id"])
6550 kdu_name
= kdu_profile
["kdu-name"]
6551 resource_name
= kdu_profile
.get("resource-name", "")
6553 if not scaling_info
["kdu-delete"].get(kdu_name
, None):
6554 scaling_info
["kdu-delete"][kdu_name
] = []
6556 kdur
= get_kdur(db_vnfr
, kdu_name
)
6557 if kdur
.get("helm-chart"):
6558 k8s_cluster_type
= "helm-chart-v3"
6559 self
.logger
.debug("kdur: {}".format(kdur
))
6561 kdur
.get("helm-version")
6562 and kdur
.get("helm-version") == "v2"
6564 k8s_cluster_type
= "helm-chart"
6565 elif kdur
.get("juju-bundle"):
6566 k8s_cluster_type
= "juju-bundle"
6569 "kdu type for kdu='{}.{}' is neither helm-chart nor "
6570 "juju-bundle. Maybe an old NBI version is running".format(
6571 db_vnfr
["member-vnf-index-ref"], kdur
["kdu-name"]
6575 min_instance_count
= 0
6576 if kdu_profile
and "min-number-of-instances" in kdu_profile
:
6577 min_instance_count
= kdu_profile
["min-number-of-instances"]
6579 nb_scale_op
-= kdu_delta
.get("number-of-instances", 1)
6580 deployed_kdu
, _
= get_deployed_kdu(
6581 nsr_deployed
, kdu_name
, vnf_index
6583 if deployed_kdu
is None:
6585 "KDU '{}' for vnf '{}' not deployed".format(
6589 kdu_instance
= deployed_kdu
.get("kdu-instance")
6590 instance_num
= await self
.k8scluster_map
[
6596 cluster_uuid
=deployed_kdu
.get("k8scluster-uuid"),
6597 kdu_model
=deployed_kdu
.get("kdu-model"),
6599 kdu_replica_count
= instance_num
- kdu_delta
.get(
6600 "number-of-instances", 1
6603 if kdu_replica_count
< min_instance_count
< instance_num
:
6604 kdu_replica_count
= min_instance_count
6605 if kdu_replica_count
< min_instance_count
:
6607 "reached the limit of {} (min-instance-count) scaling-in operations for the "
6608 "scaling-group-descriptor '{}'".format(
6609 instance_num
, scaling_group
6613 for x
in range(kdu_delta
.get("number-of-instances", 1)):
6614 vca_scaling_info
.append(
6616 "osm_kdu_id": kdu_name
,
6617 "member-vnf-index": vnf_index
,
6619 "kdu_index": instance_num
- x
- 1,
6622 scaling_info
["kdu-delete"][kdu_name
].append(
6624 "member-vnf-index": vnf_index
,
6626 "k8s-cluster-type": k8s_cluster_type
,
6627 "resource-name": resource_name
,
6628 "scale": kdu_replica_count
,
6632 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
6633 vdu_delete
= copy(scaling_info
.get("vdu-delete"))
6634 if scaling_info
["scaling_direction"] == "IN":
6635 for vdur
in reversed(db_vnfr
["vdur"]):
6636 if vdu_delete
.get(vdur
["vdu-id-ref"]):
6637 vdu_delete
[vdur
["vdu-id-ref"]] -= 1
6638 scaling_info
["vdu"].append(
6640 "name": vdur
.get("name") or vdur
.get("vdu-name"),
6641 "vdu_id": vdur
["vdu-id-ref"],
6645 for interface
in vdur
["interfaces"]:
6646 scaling_info
["vdu"][-1]["interface"].append(
6648 "name": interface
["name"],
6649 "ip_address": interface
["ip-address"],
6650 "mac_address": interface
.get("mac-address"),
6653 # vdu_delete = vdu_scaling_info.pop("vdu-delete")
6656 step
= "Executing pre-scale vnf-config-primitive"
6657 if scaling_descriptor
.get("scaling-config-action"):
6658 for scaling_config_action
in scaling_descriptor
[
6659 "scaling-config-action"
6662 scaling_config_action
.get("trigger") == "pre-scale-in"
6663 and scaling_type
== "SCALE_IN"
6665 scaling_config_action
.get("trigger") == "pre-scale-out"
6666 and scaling_type
== "SCALE_OUT"
6668 vnf_config_primitive
= scaling_config_action
[
6669 "vnf-config-primitive-name-ref"
6671 step
= db_nslcmop_update
[
6673 ] = "executing pre-scale scaling-config-action '{}'".format(
6674 vnf_config_primitive
6677 # look for primitive
6678 for config_primitive
in (
6679 get_configuration(db_vnfd
, db_vnfd
["id"]) or {}
6680 ).get("config-primitive", ()):
6681 if config_primitive
["name"] == vnf_config_primitive
:
6685 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
6686 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
6687 "primitive".format(scaling_group
, vnf_config_primitive
)
6690 vnfr_params
= {"VDU_SCALE_INFO": scaling_info
}
6691 if db_vnfr
.get("additionalParamsForVnf"):
6692 vnfr_params
.update(db_vnfr
["additionalParamsForVnf"])
6694 scale_process
= "VCA"
6695 db_nsr_update
["config-status"] = "configuring pre-scaling"
6696 primitive_params
= self
._map
_primitive
_params
(
6697 config_primitive
, {}, vnfr_params
6700 # Pre-scale retry check: Check if this sub-operation has been executed before
6701 op_index
= self
._check
_or
_add
_scale
_suboperation
(
6704 vnf_config_primitive
,
6708 if op_index
== self
.SUBOPERATION_STATUS_SKIP
:
6709 # Skip sub-operation
6710 result
= "COMPLETED"
6711 result_detail
= "Done"
6714 + "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
6715 vnf_config_primitive
, result
, result_detail
6719 if op_index
== self
.SUBOPERATION_STATUS_NEW
:
6720 # New sub-operation: Get index of this sub-operation
6722 len(db_nslcmop
.get("_admin", {}).get("operations"))
6727 + "vnf_config_primitive={} New sub-operation".format(
6728 vnf_config_primitive
6732 # retry: Get registered params for this existing sub-operation
6733 op
= db_nslcmop
.get("_admin", {}).get("operations", [])[
6736 vnf_index
= op
.get("member_vnf_index")
6737 vnf_config_primitive
= op
.get("primitive")
6738 primitive_params
= op
.get("primitive_params")
6741 + "vnf_config_primitive={} Sub-operation retry".format(
6742 vnf_config_primitive
6745 # Execute the primitive, either with new (first-time) or registered (reintent) args
6746 ee_descriptor_id
= config_primitive
.get(
6747 "execution-environment-ref"
6749 primitive_name
= config_primitive
.get(
6750 "execution-environment-primitive", vnf_config_primitive
6752 ee_id
, vca_type
= self
._look
_for
_deployed
_vca
(
6753 nsr_deployed
["VCA"],
6754 member_vnf_index
=vnf_index
,
6756 vdu_count_index
=None,
6757 ee_descriptor_id
=ee_descriptor_id
,
6759 result
, result_detail
= await self
._ns
_execute
_primitive
(
6768 + "vnf_config_primitive={} Done with result {} {}".format(
6769 vnf_config_primitive
, result
, result_detail
6772 # Update operationState = COMPLETED | FAILED
6773 self
._update
_suboperation
_status
(
6774 db_nslcmop
, op_index
, result
, result_detail
6777 if result
== "FAILED":
6778 raise LcmException(result_detail
)
6779 db_nsr_update
["config-status"] = old_config_status
6780 scale_process
= None
6784 "_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index
)
6787 "_admin.scaling-group.{}.time".format(admin_scale_index
)
6790 # SCALE-IN VCA - BEGIN
6791 if vca_scaling_info
:
6792 step
= db_nslcmop_update
[
6794 ] = "Deleting the execution environments"
6795 scale_process
= "VCA"
6796 for vca_info
in vca_scaling_info
:
6797 if vca_info
["type"] == "delete" and not vca_info
.get("osm_kdu_id"):
6798 member_vnf_index
= str(vca_info
["member-vnf-index"])
6800 logging_text
+ "vdu info: {}".format(vca_info
)
6802 if vca_info
.get("osm_vdu_id"):
6803 vdu_id
= vca_info
["osm_vdu_id"]
6804 vdu_index
= int(vca_info
["vdu_index"])
6807 ] = "Scaling member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
6808 member_vnf_index
, vdu_id
, vdu_index
6810 stage
[2] = step
= "Scaling in VCA"
6811 self
._write
_op
_status
(op_id
=nslcmop_id
, stage
=stage
)
6812 vca_update
= db_nsr
["_admin"]["deployed"]["VCA"]
6813 config_update
= db_nsr
["configurationStatus"]
6814 for vca_index
, vca
in enumerate(vca_update
):
6816 (vca
or vca
.get("ee_id"))
6817 and vca
["member-vnf-index"] == member_vnf_index
6818 and vca
["vdu_count_index"] == vdu_index
6820 if vca
.get("vdu_id"):
6821 config_descriptor
= get_configuration(
6822 db_vnfd
, vca
.get("vdu_id")
6824 elif vca
.get("kdu_name"):
6825 config_descriptor
= get_configuration(
6826 db_vnfd
, vca
.get("kdu_name")
6829 config_descriptor
= get_configuration(
6830 db_vnfd
, db_vnfd
["id"]
6832 operation_params
= (
6833 db_nslcmop
.get("operationParams") or {}
6835 exec_terminate_primitives
= not operation_params
.get(
6836 "skip_terminate_primitives"
6837 ) and vca
.get("needed_terminate")
6838 task
= asyncio
.ensure_future(
6847 exec_primitives
=exec_terminate_primitives
,
6851 timeout
=self
.timeout
.charm_delete
,
6854 tasks_dict_info
[task
] = "Terminating VCA {}".format(
6857 del vca_update
[vca_index
]
6858 del config_update
[vca_index
]
6859 # wait for pending tasks of terminate primitives
6863 + "Waiting for tasks {}".format(
6864 list(tasks_dict_info
.keys())
6867 error_list
= await self
._wait
_for
_tasks
(
6871 self
.timeout
.charm_delete
, self
.timeout
.ns_terminate
6876 tasks_dict_info
.clear()
6878 raise LcmException("; ".join(error_list
))
6880 db_vca_and_config_update
= {
6881 "_admin.deployed.VCA": vca_update
,
6882 "configurationStatus": config_update
,
6885 "nsrs", db_nsr
["_id"], db_vca_and_config_update
6887 scale_process
= None
6888 # SCALE-IN VCA - END
6891 if scaling_info
.get("vdu-create") or scaling_info
.get("vdu-delete"):
6892 scale_process
= "RO"
6893 if self
.ro_config
.ng
:
6894 await self
._scale
_ng
_ro
(
6895 logging_text
, db_nsr
, db_nslcmop
, db_vnfr
, scaling_info
, stage
6897 scaling_info
.pop("vdu-create", None)
6898 scaling_info
.pop("vdu-delete", None)
6900 scale_process
= None
6904 if scaling_info
.get("kdu-create") or scaling_info
.get("kdu-delete"):
6905 scale_process
= "KDU"
6906 await self
._scale
_kdu
(
6907 logging_text
, nsr_id
, nsr_deployed
, db_vnfd
, vca_id
, scaling_info
6909 scaling_info
.pop("kdu-create", None)
6910 scaling_info
.pop("kdu-delete", None)
6912 scale_process
= None
6916 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
6918 # SCALE-UP VCA - BEGIN
6919 if vca_scaling_info
:
6920 step
= db_nslcmop_update
[
6922 ] = "Creating new execution environments"
6923 scale_process
= "VCA"
6924 for vca_info
in vca_scaling_info
:
6925 if vca_info
["type"] == "create" and not vca_info
.get("osm_kdu_id"):
6926 member_vnf_index
= str(vca_info
["member-vnf-index"])
6928 logging_text
+ "vdu info: {}".format(vca_info
)
6930 vnfd_id
= db_vnfr
["vnfd-ref"]
6931 if vca_info
.get("osm_vdu_id"):
6932 vdu_index
= int(vca_info
["vdu_index"])
6933 deploy_params
= {"OSM": get_osm_params(db_vnfr
)}
6934 if db_vnfr
.get("additionalParamsForVnf"):
6935 deploy_params
.update(
6937 db_vnfr
["additionalParamsForVnf"].copy()
6940 descriptor_config
= get_configuration(
6941 db_vnfd
, db_vnfd
["id"]
6943 if descriptor_config
:
6949 logging_text
=logging_text
6950 + "member_vnf_index={} ".format(member_vnf_index
),
6953 nslcmop_id
=nslcmop_id
,
6959 kdu_index
=kdu_index
,
6960 member_vnf_index
=member_vnf_index
,
6961 vdu_index
=vdu_index
,
6963 deploy_params
=deploy_params
,
6964 descriptor_config
=descriptor_config
,
6965 base_folder
=base_folder
,
6966 task_instantiation_info
=tasks_dict_info
,
6969 vdu_id
= vca_info
["osm_vdu_id"]
6970 vdur
= find_in_list(
6971 db_vnfr
["vdur"], lambda vdu
: vdu
["vdu-id-ref"] == vdu_id
6973 descriptor_config
= get_configuration(db_vnfd
, vdu_id
)
6974 if vdur
.get("additionalParams"):
6975 deploy_params_vdu
= parse_yaml_strings(
6976 vdur
["additionalParams"]
6979 deploy_params_vdu
= deploy_params
6980 deploy_params_vdu
["OSM"] = get_osm_params(
6981 db_vnfr
, vdu_id
, vdu_count_index
=vdu_index
6983 if descriptor_config
:
6989 ] = "Scaling member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
6990 member_vnf_index
, vdu_id
, vdu_index
6992 stage
[2] = step
= "Scaling out VCA"
6993 self
._write
_op
_status
(op_id
=nslcmop_id
, stage
=stage
)
6995 logging_text
=logging_text
6996 + "member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
6997 member_vnf_index
, vdu_id
, vdu_index
7001 nslcmop_id
=nslcmop_id
,
7007 member_vnf_index
=member_vnf_index
,
7008 vdu_index
=vdu_index
,
7009 kdu_index
=kdu_index
,
7011 deploy_params
=deploy_params_vdu
,
7012 descriptor_config
=descriptor_config
,
7013 base_folder
=base_folder
,
7014 task_instantiation_info
=tasks_dict_info
,
7017 # SCALE-UP VCA - END
7018 scale_process
= None
7021 # execute primitive service POST-SCALING
7022 step
= "Executing post-scale vnf-config-primitive"
7023 if scaling_descriptor
.get("scaling-config-action"):
7024 for scaling_config_action
in scaling_descriptor
[
7025 "scaling-config-action"
7028 scaling_config_action
.get("trigger") == "post-scale-in"
7029 and scaling_type
== "SCALE_IN"
7031 scaling_config_action
.get("trigger") == "post-scale-out"
7032 and scaling_type
== "SCALE_OUT"
7034 vnf_config_primitive
= scaling_config_action
[
7035 "vnf-config-primitive-name-ref"
7037 step
= db_nslcmop_update
[
7039 ] = "executing post-scale scaling-config-action '{}'".format(
7040 vnf_config_primitive
7043 vnfr_params
= {"VDU_SCALE_INFO": scaling_info
}
7044 if db_vnfr
.get("additionalParamsForVnf"):
7045 vnfr_params
.update(db_vnfr
["additionalParamsForVnf"])
7047 # look for primitive
7048 for config_primitive
in (
7049 get_configuration(db_vnfd
, db_vnfd
["id"]) or {}
7050 ).get("config-primitive", ()):
7051 if config_primitive
["name"] == vnf_config_primitive
:
7055 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-"
7056 "action[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:"
7057 "config-primitive".format(
7058 scaling_group
, vnf_config_primitive
7061 scale_process
= "VCA"
7062 db_nsr_update
["config-status"] = "configuring post-scaling"
7063 primitive_params
= self
._map
_primitive
_params
(
7064 config_primitive
, {}, vnfr_params
7067 # Post-scale retry check: Check if this sub-operation has been executed before
7068 op_index
= self
._check
_or
_add
_scale
_suboperation
(
7071 vnf_config_primitive
,
7075 if op_index
== self
.SUBOPERATION_STATUS_SKIP
:
7076 # Skip sub-operation
7077 result
= "COMPLETED"
7078 result_detail
= "Done"
7081 + "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
7082 vnf_config_primitive
, result
, result_detail
7086 if op_index
== self
.SUBOPERATION_STATUS_NEW
:
7087 # New sub-operation: Get index of this sub-operation
7089 len(db_nslcmop
.get("_admin", {}).get("operations"))
7094 + "vnf_config_primitive={} New sub-operation".format(
7095 vnf_config_primitive
7099 # retry: Get registered params for this existing sub-operation
7100 op
= db_nslcmop
.get("_admin", {}).get("operations", [])[
7103 vnf_index
= op
.get("member_vnf_index")
7104 vnf_config_primitive
= op
.get("primitive")
7105 primitive_params
= op
.get("primitive_params")
7108 + "vnf_config_primitive={} Sub-operation retry".format(
7109 vnf_config_primitive
7112 # Execute the primitive, either with new (first-time) or registered (reintent) args
7113 ee_descriptor_id
= config_primitive
.get(
7114 "execution-environment-ref"
7116 primitive_name
= config_primitive
.get(
7117 "execution-environment-primitive", vnf_config_primitive
7119 ee_id
, vca_type
= self
._look
_for
_deployed
_vca
(
7120 nsr_deployed
["VCA"],
7121 member_vnf_index
=vnf_index
,
7123 vdu_count_index
=None,
7124 ee_descriptor_id
=ee_descriptor_id
,
7126 result
, result_detail
= await self
._ns
_execute
_primitive
(
7135 + "vnf_config_primitive={} Done with result {} {}".format(
7136 vnf_config_primitive
, result
, result_detail
7139 # Update operationState = COMPLETED | FAILED
7140 self
._update
_suboperation
_status
(
7141 db_nslcmop
, op_index
, result
, result_detail
7144 if result
== "FAILED":
7145 raise LcmException(result_detail
)
7146 db_nsr_update
["config-status"] = old_config_status
7147 scale_process
= None
7152 ] = "" # "scaled {} {}".format(scaling_group, scaling_type)
7153 db_nsr_update
["operational-status"] = (
7155 if old_operational_status
== "failed"
7156 else old_operational_status
7158 db_nsr_update
["config-status"] = old_config_status
7161 ROclient
.ROClientException
,
7166 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
7168 except asyncio
.CancelledError
:
7170 logging_text
+ "Cancelled Exception while '{}'".format(step
)
7172 exc
= "Operation was cancelled"
7173 except Exception as e
:
7174 exc
= traceback
.format_exc()
7175 self
.logger
.critical(
7176 logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
),
7180 self
._write
_ns
_status
(
7183 current_operation
="IDLE",
7184 current_operation_id
=None,
7187 stage
[1] = "Waiting for instantiate pending tasks."
7188 self
.logger
.debug(logging_text
+ stage
[1])
7189 exc
= await self
._wait
_for
_tasks
(
7192 self
.timeout
.ns_deploy
,
7200 ] = error_description_nslcmop
= "FAILED {}: {}".format(step
, exc
)
7201 nslcmop_operation_state
= "FAILED"
7203 db_nsr_update
["operational-status"] = old_operational_status
7204 db_nsr_update
["config-status"] = old_config_status
7205 db_nsr_update
["detailed-status"] = ""
7207 if "VCA" in scale_process
:
7208 db_nsr_update
["config-status"] = "failed"
7209 if "RO" in scale_process
:
7210 db_nsr_update
["operational-status"] = "failed"
7213 ] = "FAILED scaling nslcmop={} {}: {}".format(
7214 nslcmop_id
, step
, exc
7217 error_description_nslcmop
= None
7218 nslcmop_operation_state
= "COMPLETED"
7219 db_nslcmop_update
["detailed-status"] = "Done"
7221 self
._write
_op
_status
(
7224 error_message
=error_description_nslcmop
,
7225 operation_state
=nslcmop_operation_state
,
7226 other_update
=db_nslcmop_update
,
7229 self
._write
_ns
_status
(
7232 current_operation
="IDLE",
7233 current_operation_id
=None,
7234 other_update
=db_nsr_update
,
7237 if nslcmop_operation_state
:
7241 "nslcmop_id": nslcmop_id
,
7242 "operationState": nslcmop_operation_state
,
7244 await self
.msg
.aiowrite("ns", "scaled", msg
)
7245 except Exception as e
:
7247 logging_text
+ "kafka_write notification Exception {}".format(e
)
7249 self
.logger
.debug(logging_text
+ "Exit")
7250 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_scale")
7252 async def _scale_kdu(
7253 self
, logging_text
, nsr_id
, nsr_deployed
, db_vnfd
, vca_id
, scaling_info
7255 _scaling_info
= scaling_info
.get("kdu-create") or scaling_info
.get("kdu-delete")
7256 for kdu_name
in _scaling_info
:
7257 for kdu_scaling_info
in _scaling_info
[kdu_name
]:
7258 deployed_kdu
, index
= get_deployed_kdu(
7259 nsr_deployed
, kdu_name
, kdu_scaling_info
["member-vnf-index"]
7261 cluster_uuid
= deployed_kdu
["k8scluster-uuid"]
7262 kdu_instance
= deployed_kdu
["kdu-instance"]
7263 kdu_model
= deployed_kdu
.get("kdu-model")
7264 scale
= int(kdu_scaling_info
["scale"])
7265 k8s_cluster_type
= kdu_scaling_info
["k8s-cluster-type"]
7268 "collection": "nsrs",
7269 "filter": {"_id": nsr_id
},
7270 "path": "_admin.deployed.K8s.{}".format(index
),
7273 step
= "scaling application {}".format(
7274 kdu_scaling_info
["resource-name"]
7276 self
.logger
.debug(logging_text
+ step
)
7278 if kdu_scaling_info
["type"] == "delete":
7279 kdu_config
= get_configuration(db_vnfd
, kdu_name
)
7282 and kdu_config
.get("terminate-config-primitive")
7283 and get_juju_ee_ref(db_vnfd
, kdu_name
) is None
7285 terminate_config_primitive_list
= kdu_config
.get(
7286 "terminate-config-primitive"
7288 terminate_config_primitive_list
.sort(
7289 key
=lambda val
: int(val
["seq"])
7293 terminate_config_primitive
7294 ) in terminate_config_primitive_list
:
7295 primitive_params_
= self
._map
_primitive
_params
(
7296 terminate_config_primitive
, {}, {}
7298 step
= "execute terminate config primitive"
7299 self
.logger
.debug(logging_text
+ step
)
7300 await asyncio
.wait_for(
7301 self
.k8scluster_map
[k8s_cluster_type
].exec_primitive(
7302 cluster_uuid
=cluster_uuid
,
7303 kdu_instance
=kdu_instance
,
7304 primitive_name
=terminate_config_primitive
["name"],
7305 params
=primitive_params_
,
7307 total_timeout
=self
.timeout
.primitive
,
7310 timeout
=self
.timeout
.primitive
7311 * self
.timeout
.primitive_outer_factor
,
7314 await asyncio
.wait_for(
7315 self
.k8scluster_map
[k8s_cluster_type
].scale(
7316 kdu_instance
=kdu_instance
,
7318 resource_name
=kdu_scaling_info
["resource-name"],
7319 total_timeout
=self
.timeout
.scale_on_error
,
7321 cluster_uuid
=cluster_uuid
,
7322 kdu_model
=kdu_model
,
7326 timeout
=self
.timeout
.scale_on_error
7327 * self
.timeout
.scale_on_error_outer_factor
,
7330 if kdu_scaling_info
["type"] == "create":
7331 kdu_config
= get_configuration(db_vnfd
, kdu_name
)
7334 and kdu_config
.get("initial-config-primitive")
7335 and get_juju_ee_ref(db_vnfd
, kdu_name
) is None
7337 initial_config_primitive_list
= kdu_config
.get(
7338 "initial-config-primitive"
7340 initial_config_primitive_list
.sort(
7341 key
=lambda val
: int(val
["seq"])
7344 for initial_config_primitive
in initial_config_primitive_list
:
7345 primitive_params_
= self
._map
_primitive
_params
(
7346 initial_config_primitive
, {}, {}
7348 step
= "execute initial config primitive"
7349 self
.logger
.debug(logging_text
+ step
)
7350 await asyncio
.wait_for(
7351 self
.k8scluster_map
[k8s_cluster_type
].exec_primitive(
7352 cluster_uuid
=cluster_uuid
,
7353 kdu_instance
=kdu_instance
,
7354 primitive_name
=initial_config_primitive
["name"],
7355 params
=primitive_params_
,
7362 async def _scale_ng_ro(
7363 self
, logging_text
, db_nsr
, db_nslcmop
, db_vnfr
, vdu_scaling_info
, stage
7365 nsr_id
= db_nslcmop
["nsInstanceId"]
7366 db_nsd
= self
.db
.get_one("nsds", {"_id": db_nsr
["nsd-id"]})
7369 # read from db: vnfd's for every vnf
7372 # for each vnf in ns, read vnfd
7373 for vnfr
in self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
}):
7374 db_vnfrs
[vnfr
["member-vnf-index-ref"]] = vnfr
7375 vnfd_id
= vnfr
["vnfd-id"] # vnfd uuid for this vnf
7376 # if we haven't this vnfd, read it from db
7377 if not find_in_list(db_vnfds
, lambda a_vnfd
: a_vnfd
["id"] == vnfd_id
):
7379 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
7380 db_vnfds
.append(vnfd
)
7381 n2vc_key
= self
.n2vc
.get_public_key()
7382 n2vc_key_list
= [n2vc_key
]
7385 vdu_scaling_info
.get("vdu-create"),
7386 vdu_scaling_info
.get("vdu-delete"),
7389 # db_vnfr has been updated, update db_vnfrs to use it
7390 db_vnfrs
[db_vnfr
["member-vnf-index-ref"]] = db_vnfr
7391 await self
._instantiate
_ng
_ro
(
7401 start_deploy
=time(),
7402 timeout_ns_deploy
=self
.timeout
.ns_deploy
,
7404 if vdu_scaling_info
.get("vdu-delete"):
7406 db_vnfr
, None, vdu_scaling_info
["vdu-delete"], mark_delete
=False
7409 async def extract_prometheus_scrape_jobs(
7413 ee_config_descriptor
: dict,
7418 vnf_member_index
: str = "",
7420 vdu_index
: int = None,
7422 kdu_index
: int = None,
7424 """Method to extract prometheus scrape jobs from EE's Prometheus template job file
7425 This method will wait until the corresponding VDU or KDU is fully instantiated
7428 ee_id (str): Execution Environment ID
7429 artifact_path (str): Path where the EE's content is (including the Prometheus template file)
7430 ee_config_descriptor (dict): Execution Environment's configuration descriptor
7431 vnfr_id (str): VNFR ID where this EE applies
7432 nsr_id (str): NSR ID where this EE applies
7433 target_ip (str): VDU/KDU instance IP address
7434 element_type (str): NS or VNF or VDU or KDU
7435 vnf_member_index (str, optional): VNF index where this EE applies. Defaults to "".
7436 vdu_id (str, optional): VDU ID where this EE applies. Defaults to "".
7437 vdu_index (int, optional): VDU index where this EE applies. Defaults to None.
7438 kdu_name (str, optional): KDU name where this EE applies. Defaults to "".
7439 kdu_index (int, optional): KDU index where this EE applies. Defaults to None.
7442 LcmException: When the VDU or KDU instance was not found in an hour
7445 _type_: Prometheus jobs
7447 # default the vdur and kdur names to an empty string, to avoid any later
7448 # problem with Prometheus when the element type is not VDU or KDU
7452 # look if exist a file called 'prometheus*.j2' and
7453 artifact_content
= self
.fs
.dir_ls(artifact_path
)
7457 for f
in artifact_content
7458 if f
.startswith("prometheus") and f
.endswith(".j2")
7464 self
.logger
.debug("Artifact path{}".format(artifact_path
))
7465 self
.logger
.debug("job file{}".format(job_file
))
7466 with self
.fs
.file_open((artifact_path
, job_file
), "r") as f
:
7469 # obtain the VDUR or KDUR, if the element type is VDU or KDU
7470 if element_type
in ("VDU", "KDU"):
7471 for _
in range(360):
7472 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnfr_id
})
7473 if vdu_id
and vdu_index
is not None:
7477 for x
in get_iterable(db_vnfr
, "vdur")
7479 x
.get("vdu-id-ref") == vdu_id
7480 and x
.get("count-index") == vdu_index
7485 if vdur
.get("name"):
7486 vdur_name
= vdur
.get("name")
7488 if kdu_name
and kdu_index
is not None:
7492 for x
in get_iterable(db_vnfr
, "kdur")
7494 x
.get("kdu-name") == kdu_name
7495 and x
.get("count-index") == kdu_index
7500 if kdur
.get("name"):
7501 kdur_name
= kdur
.get("name")
7504 await asyncio
.sleep(10)
7506 if vdu_id
and vdu_index
is not None:
7508 f
"Timeout waiting VDU with name={vdu_id} and index={vdu_index} to be intantiated"
7510 if kdu_name
and kdu_index
is not None:
7512 f
"Timeout waiting KDU with name={kdu_name} and index={kdu_index} to be intantiated"
7515 if ee_id
is not None:
7516 _
, namespace
, helm_id
= get_ee_id_parts(
7518 ) # get namespace and EE gRPC service name
7519 host_name
= f
'{helm_id}-{ee_config_descriptor["metric-service"]}.{namespace}.svc' # svc_name.namespace.svc
7521 vnfr_id
= vnfr_id
.replace("-", "")
7523 "JOB_NAME": vnfr_id
,
7524 "TARGET_IP": target_ip
,
7525 "EXPORTER_POD_IP": host_name
,
7526 "EXPORTER_POD_PORT": host_port
,
7528 "VNF_MEMBER_INDEX": vnf_member_index
,
7529 "VDUR_NAME": vdur_name
,
7530 "KDUR_NAME": kdur_name
,
7531 "ELEMENT_TYPE": element_type
,
7534 metric_path
= ee_config_descriptor
["metric-path"]
7535 target_port
= ee_config_descriptor
["metric-port"]
7536 vnfr_id
= vnfr_id
.replace("-", "")
7538 "JOB_NAME": vnfr_id
,
7539 "TARGET_IP": target_ip
,
7540 "TARGET_PORT": target_port
,
7541 "METRIC_PATH": metric_path
,
7544 job_list
= parse_job(job_data
, variables
)
7545 # ensure job_name is using the vnfr_id. Adding the metadata nsr_id
7546 for job
in job_list
:
7548 not isinstance(job
.get("job_name"), str)
7549 or vnfr_id
not in job
["job_name"]
7551 job
["job_name"] = vnfr_id
+ "_" + str(SystemRandom().randint(1, 10000))
7552 job
["nsr_id"] = nsr_id
7553 job
["vnfr_id"] = vnfr_id
7556 async def rebuild_start_stop(
7557 self
, nsr_id
, nslcmop_id
, vnf_id
, additional_param
, operation_type
7559 logging_text
= "Task ns={} {}={} ".format(nsr_id
, operation_type
, nslcmop_id
)
7560 self
.logger
.info(logging_text
+ "Enter")
7561 stage
= ["Preparing the environment", ""]
7562 # database nsrs record
7566 # in case of error, indicates what part of scale was failed to put nsr at error status
7567 start_deploy
= time()
7569 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnf_id
})
7570 vim_account_id
= db_vnfr
.get("vim-account-id")
7571 vim_info_key
= "vim:" + vim_account_id
7572 vdu_id
= additional_param
["vdu_id"]
7573 vdurs
= [item
for item
in db_vnfr
["vdur"] if item
["vdu-id-ref"] == vdu_id
]
7574 vdur
= find_in_list(
7575 vdurs
, lambda vdu
: vdu
["count-index"] == additional_param
["count-index"]
7578 vdu_vim_name
= vdur
["name"]
7579 vim_vm_id
= vdur
["vim_info"][vim_info_key
]["vim_id"]
7580 target_vim
, _
= next(k_v
for k_v
in vdur
["vim_info"].items())
7582 raise LcmException("Target vdu is not found")
7583 self
.logger
.info("vdu_vim_name >> {} ".format(vdu_vim_name
))
7584 # wait for any previous tasks in process
7585 stage
[1] = "Waiting for previous operations to terminate"
7586 self
.logger
.info(stage
[1])
7587 await self
.lcm_tasks
.waitfor_related_HA("ns", "nslcmops", nslcmop_id
)
7589 stage
[1] = "Reading from database."
7590 self
.logger
.info(stage
[1])
7591 self
._write
_ns
_status
(
7594 current_operation
=operation_type
.upper(),
7595 current_operation_id
=nslcmop_id
,
7597 self
._write
_op
_status
(op_id
=nslcmop_id
, stage
=stage
, queuePosition
=0)
7600 stage
[1] = "Getting nsr={} from db.".format(nsr_id
)
7601 db_nsr_update
["operational-status"] = operation_type
7602 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
7606 "vim_vm_id": vim_vm_id
,
7608 "vdu_index": additional_param
["count-index"],
7609 "vdu_id": vdur
["id"],
7610 "target_vim": target_vim
,
7611 "vim_account_id": vim_account_id
,
7614 stage
[1] = "Sending rebuild request to RO... {}".format(desc
)
7615 self
._write
_op
_status
(op_id
=nslcmop_id
, stage
=stage
, queuePosition
=0)
7616 self
.logger
.info("ro nsr id: {}".format(nsr_id
))
7617 result_dict
= await self
.RO
.operate(nsr_id
, desc
, operation_type
)
7618 self
.logger
.info("response from RO: {}".format(result_dict
))
7619 action_id
= result_dict
["action_id"]
7620 await self
._wait
_ng
_ro
(
7625 self
.timeout
.operate
,
7627 "start_stop_rebuild",
7629 return "COMPLETED", "Done"
7630 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
7631 self
.logger
.error("Exit Exception {}".format(e
))
7633 except asyncio
.CancelledError
:
7634 self
.logger
.error("Cancelled Exception while '{}'".format(stage
))
7635 exc
= "Operation was cancelled"
7636 except Exception as e
:
7637 exc
= traceback
.format_exc()
7638 self
.logger
.critical(
7639 "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True
7641 return "FAILED", "Error in operate VNF {}".format(exc
)
7643 async def migrate(self
, nsr_id
, nslcmop_id
):
7645 Migrate VNFs and VDUs instances in a NS
7647 :param: nsr_id: NS Instance ID
7648 :param: nslcmop_id: nslcmop ID of migrate
7651 # Try to lock HA task here
7652 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA("ns", "nslcmops", nslcmop_id
)
7653 if not task_is_locked_by_me
:
7655 logging_text
= "Task ns={} migrate ".format(nsr_id
)
7656 self
.logger
.debug(logging_text
+ "Enter")
7657 # get all needed from database
7659 db_nslcmop_update
= {}
7660 nslcmop_operation_state
= None
7664 # in case of error, indicates what part of scale was failed to put nsr at error status
7665 start_deploy
= time()
7668 # wait for any previous tasks in process
7669 step
= "Waiting for previous operations to terminate"
7670 await self
.lcm_tasks
.waitfor_related_HA("ns", "nslcmops", nslcmop_id
)
7672 self
._write
_ns
_status
(
7675 current_operation
="MIGRATING",
7676 current_operation_id
=nslcmop_id
,
7678 step
= "Getting nslcmop from database"
7680 step
+ " after having waited for previous tasks to be completed"
7682 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
7683 migrate_params
= db_nslcmop
.get("operationParams")
7686 target
.update(migrate_params
)
7687 desc
= await self
.RO
.migrate(nsr_id
, target
)
7688 self
.logger
.debug("RO return > {}".format(desc
))
7689 action_id
= desc
["action_id"]
7690 await self
._wait
_ng
_ro
(
7695 self
.timeout
.migrate
,
7696 operation
="migrate",
7698 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
7699 self
.logger
.error("Exit Exception {}".format(e
))
7701 except asyncio
.CancelledError
:
7702 self
.logger
.error("Cancelled Exception while '{}'".format(step
))
7703 exc
= "Operation was cancelled"
7704 except Exception as e
:
7705 exc
= traceback
.format_exc()
7706 self
.logger
.critical(
7707 "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True
7710 self
._write
_ns
_status
(
7713 current_operation
="IDLE",
7714 current_operation_id
=None,
7717 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
7718 nslcmop_operation_state
= "FAILED"
7720 nslcmop_operation_state
= "COMPLETED"
7721 db_nslcmop_update
["detailed-status"] = "Done"
7722 db_nsr_update
["detailed-status"] = "Done"
7724 self
._write
_op
_status
(
7728 operation_state
=nslcmop_operation_state
,
7729 other_update
=db_nslcmop_update
,
7731 if nslcmop_operation_state
:
7735 "nslcmop_id": nslcmop_id
,
7736 "operationState": nslcmop_operation_state
,
7738 await self
.msg
.aiowrite("ns", "migrated", msg
)
7739 except Exception as e
:
7741 logging_text
+ "kafka_write notification Exception {}".format(e
)
7743 self
.logger
.debug(logging_text
+ "Exit")
7744 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_migrate")
7746 async def heal(self
, nsr_id
, nslcmop_id
):
7750 :param nsr_id: ns instance to heal
7751 :param nslcmop_id: operation to run
7755 # Try to lock HA task here
7756 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA("ns", "nslcmops", nslcmop_id
)
7757 if not task_is_locked_by_me
:
7760 logging_text
= "Task ns={} heal={} ".format(nsr_id
, nslcmop_id
)
7761 stage
= ["", "", ""]
7762 tasks_dict_info
= {}
7763 # ^ stage, step, VIM progress
7764 self
.logger
.debug(logging_text
+ "Enter")
7765 # get all needed from database
7767 db_nslcmop_update
= {}
7769 db_vnfrs
= {} # vnf's info indexed by _id
7771 old_operational_status
= ""
7772 old_config_status
= ""
7775 # wait for any previous tasks in process
7776 step
= "Waiting for previous operations to terminate"
7777 await self
.lcm_tasks
.waitfor_related_HA("ns", "nslcmops", nslcmop_id
)
7778 self
._write
_ns
_status
(
7781 current_operation
="HEALING",
7782 current_operation_id
=nslcmop_id
,
7785 step
= "Getting nslcmop from database"
7787 step
+ " after having waited for previous tasks to be completed"
7789 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
7791 step
= "Getting nsr from database"
7792 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
7793 old_operational_status
= db_nsr
["operational-status"]
7794 old_config_status
= db_nsr
["config-status"]
7797 "_admin.deployed.RO.operational-status": "healing",
7799 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
7801 step
= "Sending heal order to VIM"
7803 logging_text
=logging_text
,
7805 db_nslcmop
=db_nslcmop
,
7810 stage
[1] = "Getting nsd={} from db.".format(db_nsr
["nsd-id"])
7811 self
.logger
.debug(logging_text
+ stage
[1])
7812 nsd
= self
.db
.get_one("nsds", {"_id": db_nsr
["nsd-id"]})
7813 self
.fs
.sync(db_nsr
["nsd-id"])
7815 # read from db: vnfr's of this ns
7816 step
= "Getting vnfrs from db"
7817 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
7818 for vnfr
in db_vnfrs_list
:
7819 db_vnfrs
[vnfr
["_id"]] = vnfr
7820 self
.logger
.debug("ns.heal db_vnfrs={}".format(db_vnfrs
))
7822 # Check for each target VNF
7823 target_list
= db_nslcmop
.get("operationParams", {}).get("healVnfData", {})
7824 for target_vnf
in target_list
:
7825 # Find this VNF in the list from DB
7826 vnfr_id
= target_vnf
.get("vnfInstanceId", None)
7828 db_vnfr
= db_vnfrs
[vnfr_id
]
7829 vnfd_id
= db_vnfr
.get("vnfd-id")
7830 vnfd_ref
= db_vnfr
.get("vnfd-ref")
7831 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
7832 base_folder
= vnfd
["_admin"]["storage"]
7837 nsi_id
= None # TODO put nsi_id when this nsr belongs to a NSI
7838 member_vnf_index
= db_vnfr
.get("member-vnf-index-ref")
7840 # Check each target VDU and deploy N2VC
7841 target_vdu_list
= target_vnf
.get("additionalParams", {}).get(
7844 if not target_vdu_list
:
7845 # Codigo nuevo para crear diccionario
7846 target_vdu_list
= []
7847 for existing_vdu
in db_vnfr
.get("vdur"):
7848 vdu_name
= existing_vdu
.get("vdu-name", None)
7849 vdu_index
= existing_vdu
.get("count-index", 0)
7850 vdu_run_day1
= target_vnf
.get("additionalParams", {}).get(
7853 vdu_to_be_healed
= {
7855 "count-index": vdu_index
,
7856 "run-day1": vdu_run_day1
,
7858 target_vdu_list
.append(vdu_to_be_healed
)
7859 for target_vdu
in target_vdu_list
:
7860 deploy_params_vdu
= target_vdu
7861 # Set run-day1 vnf level value if not vdu level value exists
7862 if not deploy_params_vdu
.get("run-day1") and target_vnf
.get(
7863 "additionalParams", {}
7865 deploy_params_vdu
["run-day1"] = target_vnf
[
7868 vdu_name
= target_vdu
.get("vdu-id", None)
7869 # TODO: Get vdu_id from vdud.
7871 # For multi instance VDU count-index is mandatory
7872 # For single session VDU count-indes is 0
7873 vdu_index
= target_vdu
.get("count-index", 0)
7875 # n2vc_redesign STEP 3 to 6 Deploy N2VC
7876 stage
[1] = "Deploying Execution Environments."
7877 self
.logger
.debug(logging_text
+ stage
[1])
7879 # VNF Level charm. Normal case when proxy charms.
7880 # If target instance is management machine continue with actions: recreate EE for native charms or reinject juju key for proxy charms.
7881 descriptor_config
= get_configuration(vnfd
, vnfd_ref
)
7882 if descriptor_config
:
7883 # Continue if healed machine is management machine
7884 vnf_ip_address
= db_vnfr
.get("ip-address")
7885 target_instance
= None
7886 for instance
in db_vnfr
.get("vdur", None):
7888 instance
["vdu-name"] == vdu_name
7889 and instance
["count-index"] == vdu_index
7891 target_instance
= instance
7893 if vnf_ip_address
== target_instance
.get("ip-address"):
7895 logging_text
=logging_text
7896 + "member_vnf_index={}, vdu_name={}, vdu_index={} ".format(
7897 member_vnf_index
, vdu_name
, vdu_index
7901 nslcmop_id
=nslcmop_id
,
7907 member_vnf_index
=member_vnf_index
,
7910 deploy_params
=deploy_params_vdu
,
7911 descriptor_config
=descriptor_config
,
7912 base_folder
=base_folder
,
7913 task_instantiation_info
=tasks_dict_info
,
7917 # VDU Level charm. Normal case with native charms.
7918 descriptor_config
= get_configuration(vnfd
, vdu_name
)
7919 if descriptor_config
:
7921 logging_text
=logging_text
7922 + "member_vnf_index={}, vdu_name={}, vdu_index={} ".format(
7923 member_vnf_index
, vdu_name
, vdu_index
7927 nslcmop_id
=nslcmop_id
,
7933 member_vnf_index
=member_vnf_index
,
7934 vdu_index
=vdu_index
,
7936 deploy_params
=deploy_params_vdu
,
7937 descriptor_config
=descriptor_config
,
7938 base_folder
=base_folder
,
7939 task_instantiation_info
=tasks_dict_info
,
7944 ROclient
.ROClientException
,
7949 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
7951 except asyncio
.CancelledError
:
7953 logging_text
+ "Cancelled Exception while '{}'".format(step
)
7955 exc
= "Operation was cancelled"
7956 except Exception as e
:
7957 exc
= traceback
.format_exc()
7958 self
.logger
.critical(
7959 logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
),
7964 stage
[1] = "Waiting for healing pending tasks."
7965 self
.logger
.debug(logging_text
+ stage
[1])
7966 exc
= await self
._wait
_for
_tasks
(
7969 self
.timeout
.ns_deploy
,
7977 ] = error_description_nslcmop
= "FAILED {}: {}".format(step
, exc
)
7978 nslcmop_operation_state
= "FAILED"
7980 db_nsr_update
["operational-status"] = old_operational_status
7981 db_nsr_update
["config-status"] = old_config_status
7984 ] = "FAILED healing nslcmop={} {}: {}".format(nslcmop_id
, step
, exc
)
7985 for task
, task_name
in tasks_dict_info
.items():
7986 if not task
.done() or task
.cancelled() or task
.exception():
7987 if task_name
.startswith(self
.task_name_deploy_vca
):
7988 # A N2VC task is pending
7989 db_nsr_update
["config-status"] = "failed"
7991 # RO task is pending
7992 db_nsr_update
["operational-status"] = "failed"
7994 error_description_nslcmop
= None
7995 nslcmop_operation_state
= "COMPLETED"
7996 db_nslcmop_update
["detailed-status"] = "Done"
7997 db_nsr_update
["detailed-status"] = "Done"
7998 db_nsr_update
["operational-status"] = "running"
7999 db_nsr_update
["config-status"] = "configured"
8001 self
._write
_op
_status
(
8004 error_message
=error_description_nslcmop
,
8005 operation_state
=nslcmop_operation_state
,
8006 other_update
=db_nslcmop_update
,
8009 self
._write
_ns
_status
(
8012 current_operation
="IDLE",
8013 current_operation_id
=None,
8014 other_update
=db_nsr_update
,
8017 if nslcmop_operation_state
:
8021 "nslcmop_id": nslcmop_id
,
8022 "operationState": nslcmop_operation_state
,
8024 await self
.msg
.aiowrite("ns", "healed", msg
)
8025 except Exception as e
:
8027 logging_text
+ "kafka_write notification Exception {}".format(e
)
8029 self
.logger
.debug(logging_text
+ "Exit")
8030 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_heal")
8041 :param logging_text: preffix text to use at logging
8042 :param nsr_id: nsr identity
8043 :param db_nslcmop: database content of ns operation, in this case, 'instantiate'
8044 :param stage: list with 3 items: [general stage, tasks, vim_specific]. This task will write over vim_specific
8045 :return: None or exception
8048 def get_vim_account(vim_account_id
):
8050 if vim_account_id
in db_vims
:
8051 return db_vims
[vim_account_id
]
8052 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_account_id
})
8053 db_vims
[vim_account_id
] = db_vim
8058 ns_params
= db_nslcmop
.get("operationParams")
8059 if ns_params
and ns_params
.get("timeout_ns_heal"):
8060 timeout_ns_heal
= ns_params
["timeout_ns_heal"]
8062 timeout_ns_heal
= self
.timeout
.ns_heal
8066 nslcmop_id
= db_nslcmop
["_id"]
8068 "action_id": nslcmop_id
,
8070 self
.logger
.warning(
8071 "db_nslcmop={} and timeout_ns_heal={}".format(
8072 db_nslcmop
, timeout_ns_heal
8075 target
.update(db_nslcmop
.get("operationParams", {}))
8077 self
.logger
.debug("Send to RO > nsr_id={} target={}".format(nsr_id
, target
))
8078 desc
= await self
.RO
.recreate(nsr_id
, target
)
8079 self
.logger
.debug("RO return > {}".format(desc
))
8080 action_id
= desc
["action_id"]
8081 # waits for RO to complete because Reinjecting juju key at ro can find VM in state Deleted
8082 await self
._wait
_ng
_ro
(
8089 operation
="healing",
8094 "_admin.deployed.RO.operational-status": "running",
8095 "detailed-status": " ".join(stage
),
8097 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
8098 self
._write
_op
_status
(nslcmop_id
, stage
)
8100 logging_text
+ "ns healed at RO. RO_id={}".format(action_id
)
8103 except Exception as e
:
8104 stage
[2] = "ERROR healing at VIM"
8105 # self.set_vnfr_at_error(db_vnfrs, str(e))
8107 "Error healing at VIM {}".format(e
),
8108 exc_info
=not isinstance(
8111 ROclient
.ROClientException
,
8137 task_instantiation_info
,
8140 # launch instantiate_N2VC in a asyncio task and register task object
8141 # Look where information of this charm is at database <nsrs>._admin.deployed.VCA
8142 # if not found, create one entry and update database
8143 # fill db_nsr._admin.deployed.VCA.<index>
8146 logging_text
+ "_deploy_n2vc vnfd_id={}, vdu_id={}".format(vnfd_id
, vdu_id
)
8150 get_charm_name
= False
8151 if "execution-environment-list" in descriptor_config
:
8152 ee_list
= descriptor_config
.get("execution-environment-list", [])
8153 elif "juju" in descriptor_config
:
8154 ee_list
= [descriptor_config
] # ns charms
8155 if "execution-environment-list" not in descriptor_config
:
8156 # charm name is only required for ns charms
8157 get_charm_name
= True
8158 else: # other types as script are not supported
8161 for ee_item
in ee_list
:
8164 + "_deploy_n2vc ee_item juju={}, helm={}".format(
8165 ee_item
.get("juju"), ee_item
.get("helm-chart")
8168 ee_descriptor_id
= ee_item
.get("id")
8169 if ee_item
.get("juju"):
8170 vca_name
= ee_item
["juju"].get("charm")
8172 charm_name
= self
.find_charm_name(db_nsr
, str(vca_name
))
8175 if ee_item
["juju"].get("charm") is not None
8178 if ee_item
["juju"].get("cloud") == "k8s":
8179 vca_type
= "k8s_proxy_charm"
8180 elif ee_item
["juju"].get("proxy") is False:
8181 vca_type
= "native_charm"
8182 elif ee_item
.get("helm-chart"):
8183 vca_name
= ee_item
["helm-chart"]
8184 if ee_item
.get("helm-version") and ee_item
.get("helm-version") == "v2":
8187 vca_type
= "helm-v3"
8190 logging_text
+ "skipping non juju neither charm configuration"
8195 for vca_index
, vca_deployed
in enumerate(
8196 db_nsr
["_admin"]["deployed"]["VCA"]
8198 if not vca_deployed
:
8201 vca_deployed
.get("member-vnf-index") == member_vnf_index
8202 and vca_deployed
.get("vdu_id") == vdu_id
8203 and vca_deployed
.get("kdu_name") == kdu_name
8204 and vca_deployed
.get("vdu_count_index", 0) == vdu_index
8205 and vca_deployed
.get("ee_descriptor_id") == ee_descriptor_id
8209 # not found, create one.
8211 "ns" if not member_vnf_index
else "vnf/{}".format(member_vnf_index
)
8214 target
+= "/vdu/{}/{}".format(vdu_id
, vdu_index
or 0)
8216 target
+= "/kdu/{}".format(kdu_name
)
8218 "target_element": target
,
8219 # ^ target_element will replace member-vnf-index, kdu_name, vdu_id ... in a single string
8220 "member-vnf-index": member_vnf_index
,
8222 "kdu_name": kdu_name
,
8223 "vdu_count_index": vdu_index
,
8224 "operational-status": "init", # TODO revise
8225 "detailed-status": "", # TODO revise
8226 "step": "initial-deploy", # TODO revise
8228 "vdu_name": vdu_name
,
8230 "ee_descriptor_id": ee_descriptor_id
,
8231 "charm_name": charm_name
,
8235 # create VCA and configurationStatus in db
8237 "_admin.deployed.VCA.{}".format(vca_index
): vca_deployed
,
8238 "configurationStatus.{}".format(vca_index
): dict(),
8240 self
.update_db_2("nsrs", nsr_id
, db_dict
)
8242 db_nsr
["_admin"]["deployed"]["VCA"].append(vca_deployed
)
8244 self
.logger
.debug("N2VC > NSR_ID > {}".format(nsr_id
))
8245 self
.logger
.debug("N2VC > DB_NSR > {}".format(db_nsr
))
8246 self
.logger
.debug("N2VC > VCA_DEPLOYED > {}".format(vca_deployed
))
8249 task_n2vc
= asyncio
.ensure_future(
8251 logging_text
=logging_text
,
8252 vca_index
=vca_index
,
8258 vdu_index
=vdu_index
,
8259 deploy_params
=deploy_params
,
8260 config_descriptor
=descriptor_config
,
8261 base_folder
=base_folder
,
8262 nslcmop_id
=nslcmop_id
,
8266 ee_config_descriptor
=ee_item
,
8269 self
.lcm_tasks
.register(
8273 "instantiate_N2VC-{}".format(vca_index
),
8276 task_instantiation_info
[
8278 ] = self
.task_name_deploy_vca
+ " {}.{}".format(
8279 member_vnf_index
or "", vdu_id
or ""
8282 async def heal_N2VC(
8299 ee_config_descriptor
,
8301 nsr_id
= db_nsr
["_id"]
8302 db_update_entry
= "_admin.deployed.VCA.{}.".format(vca_index
)
8303 vca_deployed_list
= db_nsr
["_admin"]["deployed"]["VCA"]
8304 vca_deployed
= db_nsr
["_admin"]["deployed"]["VCA"][vca_index
]
8305 osm_config
= {"osm": {"ns_id": db_nsr
["_id"]}}
8307 "collection": "nsrs",
8308 "filter": {"_id": nsr_id
},
8309 "path": db_update_entry
,
8314 element_under_configuration
= nsr_id
8318 vnfr_id
= db_vnfr
["_id"]
8319 osm_config
["osm"]["vnf_id"] = vnfr_id
8321 namespace
= "{nsi}.{ns}".format(nsi
=nsi_id
if nsi_id
else "", ns
=nsr_id
)
8323 if vca_type
== "native_charm":
8326 index_number
= vdu_index
or 0
8329 element_type
= "VNF"
8330 element_under_configuration
= vnfr_id
8331 namespace
+= ".{}-{}".format(vnfr_id
, index_number
)
8333 namespace
+= ".{}-{}".format(vdu_id
, index_number
)
8334 element_type
= "VDU"
8335 element_under_configuration
= "{}-{}".format(vdu_id
, index_number
)
8336 osm_config
["osm"]["vdu_id"] = vdu_id
8338 namespace
+= ".{}".format(kdu_name
)
8339 element_type
= "KDU"
8340 element_under_configuration
= kdu_name
8341 osm_config
["osm"]["kdu_name"] = kdu_name
8344 if base_folder
["pkg-dir"]:
8345 artifact_path
= "{}/{}/{}/{}".format(
8346 base_folder
["folder"],
8347 base_folder
["pkg-dir"],
8350 in ("native_charm", "lxc_proxy_charm", "k8s_proxy_charm")
8355 artifact_path
= "{}/Scripts/{}/{}/".format(
8356 base_folder
["folder"],
8359 in ("native_charm", "lxc_proxy_charm", "k8s_proxy_charm")
8364 self
.logger
.debug("Artifact path > {}".format(artifact_path
))
8366 # get initial_config_primitive_list that applies to this element
8367 initial_config_primitive_list
= config_descriptor
.get(
8368 "initial-config-primitive"
8372 "Initial config primitive list > {}".format(
8373 initial_config_primitive_list
8377 # add config if not present for NS charm
8378 ee_descriptor_id
= ee_config_descriptor
.get("id")
8379 self
.logger
.debug("EE Descriptor > {}".format(ee_descriptor_id
))
8380 initial_config_primitive_list
= get_ee_sorted_initial_config_primitive_list(
8381 initial_config_primitive_list
, vca_deployed
, ee_descriptor_id
8385 "Initial config primitive list #2 > {}".format(
8386 initial_config_primitive_list
8389 # n2vc_redesign STEP 3.1
8390 # find old ee_id if exists
8391 ee_id
= vca_deployed
.get("ee_id")
8393 vca_id
= self
.get_vca_id(db_vnfr
, db_nsr
)
8394 # create or register execution environment in VCA. Only for native charms when healing
8395 if vca_type
== "native_charm":
8396 step
= "Waiting to VM being up and getting IP address"
8397 self
.logger
.debug(logging_text
+ step
)
8398 rw_mgmt_ip
= await self
.wait_vm_up_insert_key_ro(
8407 credentials
= {"hostname": rw_mgmt_ip
}
8409 username
= deep_get(
8410 config_descriptor
, ("config-access", "ssh-access", "default-user")
8412 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
8413 # merged. Meanwhile let's get username from initial-config-primitive
8414 if not username
and initial_config_primitive_list
:
8415 for config_primitive
in initial_config_primitive_list
:
8416 for param
in config_primitive
.get("parameter", ()):
8417 if param
["name"] == "ssh-username":
8418 username
= param
["value"]
8422 "Cannot determine the username neither with 'initial-config-primitive' nor with "
8423 "'config-access.ssh-access.default-user'"
8425 credentials
["username"] = username
8427 # n2vc_redesign STEP 3.2
8428 # TODO: Before healing at RO it is needed to destroy native charm units to be deleted.
8429 self
._write
_configuration
_status
(
8431 vca_index
=vca_index
,
8432 status
="REGISTERING",
8433 element_under_configuration
=element_under_configuration
,
8434 element_type
=element_type
,
8437 step
= "register execution environment {}".format(credentials
)
8438 self
.logger
.debug(logging_text
+ step
)
8439 ee_id
= await self
.vca_map
[vca_type
].register_execution_environment(
8440 credentials
=credentials
,
8441 namespace
=namespace
,
8446 # update ee_id en db
8448 "_admin.deployed.VCA.{}.ee_id".format(vca_index
): ee_id
,
8450 self
.update_db_2("nsrs", nsr_id
, db_dict_ee_id
)
8452 # for compatibility with MON/POL modules, the need model and application name at database
8453 # TODO ask MON/POL if needed to not assuming anymore the format "model_name.application_name"
8454 # Not sure if this need to be done when healing
8456 ee_id_parts = ee_id.split(".")
8457 db_nsr_update = {db_update_entry + "ee_id": ee_id}
8458 if len(ee_id_parts) >= 2:
8459 model_name = ee_id_parts[0]
8460 application_name = ee_id_parts[1]
8461 db_nsr_update[db_update_entry + "model"] = model_name
8462 db_nsr_update[db_update_entry + "application"] = application_name
8465 # n2vc_redesign STEP 3.3
8466 # Install configuration software. Only for native charms.
8467 step
= "Install configuration Software"
8469 self
._write
_configuration
_status
(
8471 vca_index
=vca_index
,
8472 status
="INSTALLING SW",
8473 element_under_configuration
=element_under_configuration
,
8474 element_type
=element_type
,
8475 # other_update=db_nsr_update,
8479 # TODO check if already done
8480 self
.logger
.debug(logging_text
+ step
)
8482 if vca_type
== "native_charm":
8483 config_primitive
= next(
8484 (p
for p
in initial_config_primitive_list
if p
["name"] == "config"),
8487 if config_primitive
:
8488 config
= self
._map
_primitive
_params
(
8489 config_primitive
, {}, deploy_params
8491 await self
.vca_map
[vca_type
].install_configuration_sw(
8493 artifact_path
=artifact_path
,
8501 # write in db flag of configuration_sw already installed
8503 "nsrs", nsr_id
, {db_update_entry
+ "config_sw_installed": True}
8506 # Not sure if this need to be done when healing
8508 # add relations for this VCA (wait for other peers related with this VCA)
8509 await self._add_vca_relations(
8510 logging_text=logging_text,
8513 vca_index=vca_index,
8517 # if SSH access is required, then get execution environment SSH public
8518 # if native charm we have waited already to VM be UP
8519 if vca_type
in ("k8s_proxy_charm", "lxc_proxy_charm", "helm", "helm-v3"):
8522 # self.logger.debug("get ssh key block")
8524 config_descriptor
, ("config-access", "ssh-access", "required")
8526 # self.logger.debug("ssh key needed")
8527 # Needed to inject a ssh key
8530 ("config-access", "ssh-access", "default-user"),
8532 step
= "Install configuration Software, getting public ssh key"
8533 pub_key
= await self
.vca_map
[vca_type
].get_ee_ssh_public__key(
8534 ee_id
=ee_id
, db_dict
=db_dict
, vca_id
=vca_id
8537 step
= "Insert public key into VM user={} ssh_key={}".format(
8541 # self.logger.debug("no need to get ssh key")
8542 step
= "Waiting to VM being up and getting IP address"
8543 self
.logger
.debug(logging_text
+ step
)
8545 # n2vc_redesign STEP 5.1
8546 # wait for RO (ip-address) Insert pub_key into VM
8547 # IMPORTANT: We need do wait for RO to complete healing operation.
8548 await self
._wait
_heal
_ro
(nsr_id
, self
.timeout
.ns_heal
)
8551 rw_mgmt_ip
= await self
.wait_kdu_up(
8552 logging_text
, nsr_id
, vnfr_id
, kdu_name
8555 rw_mgmt_ip
= await self
.wait_vm_up_insert_key_ro(
8565 rw_mgmt_ip
= None # This is for a NS configuration
8567 self
.logger
.debug(logging_text
+ " VM_ip_address={}".format(rw_mgmt_ip
))
8569 # store rw_mgmt_ip in deploy params for later replacement
8570 deploy_params
["rw_mgmt_ip"] = rw_mgmt_ip
8573 # get run-day1 operation parameter
8574 runDay1
= deploy_params
.get("run-day1", False)
8576 "Healing vnf={}, vdu={}, runDay1 ={}".format(vnfr_id
, vdu_id
, runDay1
)
8579 # n2vc_redesign STEP 6 Execute initial config primitive
8580 step
= "execute initial config primitive"
8582 # wait for dependent primitives execution (NS -> VNF -> VDU)
8583 if initial_config_primitive_list
:
8584 await self
._wait
_dependent
_n
2vc
(
8585 nsr_id
, vca_deployed_list
, vca_index
8588 # stage, in function of element type: vdu, kdu, vnf or ns
8589 my_vca
= vca_deployed_list
[vca_index
]
8590 if my_vca
.get("vdu_id") or my_vca
.get("kdu_name"):
8592 stage
[0] = "Stage 3/5: running Day-1 primitives for VDU."
8593 elif my_vca
.get("member-vnf-index"):
8595 stage
[0] = "Stage 4/5: running Day-1 primitives for VNF."
8598 stage
[0] = "Stage 5/5: running Day-1 primitives for NS."
8600 self
._write
_configuration
_status
(
8601 nsr_id
=nsr_id
, vca_index
=vca_index
, status
="EXECUTING PRIMITIVE"
8604 self
._write
_op
_status
(op_id
=nslcmop_id
, stage
=stage
)
8606 check_if_terminated_needed
= True
8607 for initial_config_primitive
in initial_config_primitive_list
:
8608 # adding information on the vca_deployed if it is a NS execution environment
8609 if not vca_deployed
["member-vnf-index"]:
8610 deploy_params
["ns_config_info"] = json
.dumps(
8611 self
._get
_ns
_config
_info
(nsr_id
)
8613 # TODO check if already done
8614 primitive_params_
= self
._map
_primitive
_params
(
8615 initial_config_primitive
, {}, deploy_params
8618 step
= "execute primitive '{}' params '{}'".format(
8619 initial_config_primitive
["name"], primitive_params_
8621 self
.logger
.debug(logging_text
+ step
)
8622 await self
.vca_map
[vca_type
].exec_primitive(
8624 primitive_name
=initial_config_primitive
["name"],
8625 params_dict
=primitive_params_
,
8630 # Once some primitive has been exec, check and write at db if it needs to exec terminated primitives
8631 if check_if_terminated_needed
:
8632 if config_descriptor
.get("terminate-config-primitive"):
8636 {db_update_entry
+ "needed_terminate": True},
8638 check_if_terminated_needed
= False
8640 # TODO register in database that primitive is done
8642 # STEP 7 Configure metrics
8643 # Not sure if this need to be done when healing
8645 if vca_type == "helm" or vca_type == "helm-v3":
8646 prometheus_jobs = await self.extract_prometheus_scrape_jobs(
8648 artifact_path=artifact_path,
8649 ee_config_descriptor=ee_config_descriptor,
8652 target_ip=rw_mgmt_ip,
8658 {db_update_entry + "prometheus_jobs": prometheus_jobs},
8661 for job in prometheus_jobs:
8664 {"job_name": job["job_name"]},
8667 fail_on_empty=False,
8671 step
= "instantiated at VCA"
8672 self
.logger
.debug(logging_text
+ step
)
8674 self
._write
_configuration
_status
(
8675 nsr_id
=nsr_id
, vca_index
=vca_index
, status
="READY"
8678 except Exception as e
: # TODO not use Exception but N2VC exception
8679 # self.update_db_2("nsrs", nsr_id, {db_update_entry + "instantiation": "FAILED"})
8681 e
, (DbException
, N2VCException
, LcmException
, asyncio
.CancelledError
)
8684 "Exception while {} : {}".format(step
, e
), exc_info
=True
8686 self
._write
_configuration
_status
(
8687 nsr_id
=nsr_id
, vca_index
=vca_index
, status
="BROKEN"
8689 raise LcmException("{} {}".format(step
, e
)) from e
8691 async def _wait_heal_ro(
8697 while time() <= start_time
+ timeout
:
8698 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
8699 operational_status_ro
= db_nsr
["_admin"]["deployed"]["RO"][
8700 "operational-status"
8702 self
.logger
.debug("Wait Heal RO > {}".format(operational_status_ro
))
8703 if operational_status_ro
!= "healing":
8705 await asyncio
.sleep(15)
8706 else: # timeout_ns_deploy
8707 raise NgRoException("Timeout waiting ns to deploy")
8709 async def vertical_scale(self
, nsr_id
, nslcmop_id
):
8711 Vertical Scale the VDUs in a NS
8713 :param: nsr_id: NS Instance ID
8714 :param: nslcmop_id: nslcmop ID of migrate
8717 # Try to lock HA task here
8718 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA("ns", "nslcmops", nslcmop_id
)
8719 if not task_is_locked_by_me
:
8721 logging_text
= "Task ns={} vertical scale ".format(nsr_id
)
8722 self
.logger
.debug(logging_text
+ "Enter")
8723 # get all needed from database
8725 db_nslcmop_update
= {}
8726 nslcmop_operation_state
= None
8730 # in case of error, indicates what part of scale was failed to put nsr at error status
8731 start_deploy
= time()
8734 # wait for any previous tasks in process
8735 step
= "Waiting for previous operations to terminate"
8736 await self
.lcm_tasks
.waitfor_related_HA("ns", "nslcmops", nslcmop_id
)
8738 self
._write
_ns
_status
(
8741 current_operation
="VerticalScale",
8742 current_operation_id
=nslcmop_id
,
8744 step
= "Getting nslcmop from database"
8746 step
+ " after having waited for previous tasks to be completed"
8748 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
8749 operationParams
= db_nslcmop
.get("operationParams")
8751 target
.update(operationParams
)
8752 desc
= await self
.RO
.vertical_scale(nsr_id
, target
)
8753 self
.logger
.debug("RO return > {}".format(desc
))
8754 action_id
= desc
["action_id"]
8755 await self
._wait
_ng
_ro
(
8760 self
.timeout
.verticalscale
,
8761 operation
="verticalscale",
8763 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
8764 self
.logger
.error("Exit Exception {}".format(e
))
8766 except asyncio
.CancelledError
:
8767 self
.logger
.error("Cancelled Exception while '{}'".format(step
))
8768 exc
= "Operation was cancelled"
8769 except Exception as e
:
8770 exc
= traceback
.format_exc()
8771 self
.logger
.critical(
8772 "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True
8775 self
._write
_ns
_status
(
8778 current_operation
="IDLE",
8779 current_operation_id
=None,
8782 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
8783 nslcmop_operation_state
= "FAILED"
8785 nslcmop_operation_state
= "COMPLETED"
8786 db_nslcmop_update
["detailed-status"] = "Done"
8787 db_nsr_update
["detailed-status"] = "Done"
8789 self
._write
_op
_status
(
8793 operation_state
=nslcmop_operation_state
,
8794 other_update
=db_nslcmop_update
,
8796 if nslcmop_operation_state
:
8800 "nslcmop_id": nslcmop_id
,
8801 "operationState": nslcmop_operation_state
,
8803 await self
.msg
.aiowrite("ns", "verticalscaled", msg
)
8804 except Exception as e
:
8806 logging_text
+ "kafka_write notification Exception {}".format(e
)
8808 self
.logger
.debug(logging_text
+ "Exit")
8809 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_verticalscale")