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
22 import logging
.handlers
33 from osm_lcm
import ROclient
34 from osm_lcm
.data_utils
.nsr
import get_deployed_kdu
35 from osm_lcm
.ng_ro
import NgRoClient
, NgRoException
36 from osm_lcm
.lcm_utils
import (
44 from osm_lcm
.data_utils
.nsd
import get_vnf_profiles
45 from osm_lcm
.data_utils
.vnfd
import (
48 get_ee_sorted_initial_config_primitive_list
,
49 get_ee_sorted_terminate_config_primitive_list
,
51 get_virtual_link_profiles
,
56 get_number_of_instances
,
60 from osm_lcm
.data_utils
.list_utils
import find_in_list
61 from osm_lcm
.data_utils
.vnfr
import get_osm_params
, get_vdur_index
, get_kdur
62 from osm_lcm
.data_utils
.dict_utils
import parse_yaml_strings
63 from osm_lcm
.data_utils
.database
.vim_account
import VimAccountDB
64 from n2vc
.k8s_helm_conn
import K8sHelmConnector
65 from n2vc
.k8s_helm3_conn
import K8sHelm3Connector
66 from n2vc
.k8s_juju_conn
import K8sJujuConnector
68 from osm_common
.dbbase
import DbException
69 from osm_common
.fsbase
import FsException
71 from osm_lcm
.data_utils
.database
.database
import Database
72 from osm_lcm
.data_utils
.filesystem
.filesystem
import Filesystem
74 from n2vc
.n2vc_juju_conn
import N2VCJujuConnector
75 from n2vc
.exceptions
import N2VCException
, N2VCNotFound
, K8sException
77 from osm_lcm
.lcm_helm_conn
import LCMHelmConn
79 from copy
import copy
, deepcopy
81 from uuid
import uuid4
83 from random
import randint
85 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
89 timeout_vca_on_error
= (
91 ) # Time for charm from first time at blocked,error status to mark as failed
92 timeout_ns_deploy
= 2 * 3600 # default global timeout for deployment a ns
93 timeout_ns_terminate
= 1800 # default global timeout for un deployment a ns
94 timeout_charm_delete
= 10 * 60
95 timeout_primitive
= 30 * 60 # timeout for primitive execution
96 timeout_progress_primitive
= (
98 ) # timeout for some progress in a primitive execution
100 SUBOPERATION_STATUS_NOT_FOUND
= -1
101 SUBOPERATION_STATUS_NEW
= -2
102 SUBOPERATION_STATUS_SKIP
= -3
103 task_name_deploy_vca
= "Deploying VCA"
105 def __init__(self
, msg
, lcm_tasks
, config
, loop
, prometheus
=None):
107 Init, Connect to database, filesystem storage, and messaging
108 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
111 super().__init
__(msg
=msg
, logger
=logging
.getLogger("lcm.ns"))
113 self
.db
= Database().instance
.db
114 self
.fs
= Filesystem().instance
.fs
116 self
.lcm_tasks
= lcm_tasks
117 self
.timeout
= config
["timeout"]
118 self
.ro_config
= config
["ro_config"]
119 self
.ng_ro
= config
["ro_config"].get("ng")
120 self
.vca_config
= config
["VCA"].copy()
122 # create N2VC connector
123 self
.n2vc
= N2VCJujuConnector(
126 on_update_db
=self
._on
_update
_n
2vc
_db
,
131 self
.conn_helm_ee
= LCMHelmConn(
134 vca_config
=self
.vca_config
,
135 on_update_db
=self
._on
_update
_n
2vc
_db
,
138 self
.k8sclusterhelm2
= K8sHelmConnector(
139 kubectl_command
=self
.vca_config
.get("kubectlpath"),
140 helm_command
=self
.vca_config
.get("helmpath"),
147 self
.k8sclusterhelm3
= K8sHelm3Connector(
148 kubectl_command
=self
.vca_config
.get("kubectlpath"),
149 helm_command
=self
.vca_config
.get("helm3path"),
156 self
.k8sclusterjuju
= K8sJujuConnector(
157 kubectl_command
=self
.vca_config
.get("kubectlpath"),
158 juju_command
=self
.vca_config
.get("jujupath"),
161 on_update_db
=self
._on
_update
_k
8s
_db
,
166 self
.k8scluster_map
= {
167 "helm-chart": self
.k8sclusterhelm2
,
168 "helm-chart-v3": self
.k8sclusterhelm3
,
169 "chart": self
.k8sclusterhelm3
,
170 "juju-bundle": self
.k8sclusterjuju
,
171 "juju": self
.k8sclusterjuju
,
175 "lxc_proxy_charm": self
.n2vc
,
176 "native_charm": self
.n2vc
,
177 "k8s_proxy_charm": self
.n2vc
,
178 "helm": self
.conn_helm_ee
,
179 "helm-v3": self
.conn_helm_ee
,
182 self
.prometheus
= prometheus
185 self
.RO
= NgRoClient(self
.loop
, **self
.ro_config
)
188 def increment_ip_mac(ip_mac
, vm_index
=1):
189 if not isinstance(ip_mac
, str):
192 # try with ipv4 look for last dot
193 i
= ip_mac
.rfind(".")
196 return "{}{}".format(ip_mac
[:i
], int(ip_mac
[i
:]) + vm_index
)
197 # try with ipv6 or mac look for last colon. Operate in hex
198 i
= ip_mac
.rfind(":")
201 # format in hex, len can be 2 for mac or 4 for ipv6
202 return ("{}{:0" + str(len(ip_mac
) - i
) + "x}").format(
203 ip_mac
[:i
], int(ip_mac
[i
:], 16) + vm_index
209 def _on_update_ro_db(self
, nsrs_id
, ro_descriptor
):
211 # self.logger.debug('_on_update_ro_db(nsrs_id={}'.format(nsrs_id))
214 # TODO filter RO descriptor fields...
218 # db_dict['deploymentStatus'] = yaml.dump(ro_descriptor, default_flow_style=False, indent=2)
219 db_dict
["deploymentStatus"] = ro_descriptor
220 self
.update_db_2("nsrs", nsrs_id
, db_dict
)
222 except Exception as e
:
224 "Cannot write database RO deployment for ns={} -> {}".format(nsrs_id
, e
)
227 async def _on_update_n2vc_db(self
, table
, filter, path
, updated_data
, vca_id
=None):
229 # remove last dot from path (if exists)
230 if path
.endswith("."):
233 # self.logger.debug('_on_update_n2vc_db(table={}, filter={}, path={}, updated_data={}'
234 # .format(table, filter, path, updated_data))
237 nsr_id
= filter.get("_id")
239 # read ns record from database
240 nsr
= self
.db
.get_one(table
="nsrs", q_filter
=filter)
241 current_ns_status
= nsr
.get("nsState")
243 # get vca status for NS
244 status_dict
= await self
.n2vc
.get_status(
245 namespace
="." + nsr_id
, yaml_format
=False, vca_id
=vca_id
250 db_dict
["vcaStatus"] = status_dict
251 await self
.n2vc
.update_vca_status(db_dict
["vcaStatus"], vca_id
=vca_id
)
253 # update configurationStatus for this VCA
255 vca_index
= int(path
[path
.rfind(".") + 1 :])
258 target_dict
=nsr
, key_list
=("_admin", "deployed", "VCA")
260 vca_status
= vca_list
[vca_index
].get("status")
262 configuration_status_list
= nsr
.get("configurationStatus")
263 config_status
= configuration_status_list
[vca_index
].get("status")
265 if config_status
== "BROKEN" and vca_status
!= "failed":
266 db_dict
["configurationStatus"][vca_index
] = "READY"
267 elif config_status
!= "BROKEN" and vca_status
== "failed":
268 db_dict
["configurationStatus"][vca_index
] = "BROKEN"
269 except Exception as e
:
270 # not update configurationStatus
271 self
.logger
.debug("Error updating vca_index (ignore): {}".format(e
))
273 # if nsState = 'READY' check if juju is reporting some error => nsState = 'DEGRADED'
274 # if nsState = 'DEGRADED' check if all is OK
276 if current_ns_status
in ("READY", "DEGRADED"):
277 error_description
= ""
279 if status_dict
.get("machines"):
280 for machine_id
in status_dict
.get("machines"):
281 machine
= status_dict
.get("machines").get(machine_id
)
282 # check machine agent-status
283 if machine
.get("agent-status"):
284 s
= machine
.get("agent-status").get("status")
287 error_description
+= (
288 "machine {} agent-status={} ; ".format(
292 # check machine instance status
293 if machine
.get("instance-status"):
294 s
= machine
.get("instance-status").get("status")
297 error_description
+= (
298 "machine {} instance-status={} ; ".format(
303 if status_dict
.get("applications"):
304 for app_id
in status_dict
.get("applications"):
305 app
= status_dict
.get("applications").get(app_id
)
306 # check application status
307 if app
.get("status"):
308 s
= app
.get("status").get("status")
311 error_description
+= (
312 "application {} status={} ; ".format(app_id
, s
)
315 if error_description
:
316 db_dict
["errorDescription"] = error_description
317 if current_ns_status
== "READY" and is_degraded
:
318 db_dict
["nsState"] = "DEGRADED"
319 if current_ns_status
== "DEGRADED" and not is_degraded
:
320 db_dict
["nsState"] = "READY"
323 self
.update_db_2("nsrs", nsr_id
, db_dict
)
325 except (asyncio
.CancelledError
, asyncio
.TimeoutError
):
327 except Exception as e
:
328 self
.logger
.warn("Error updating NS state for ns={}: {}".format(nsr_id
, e
))
330 async def _on_update_k8s_db(
331 self
, cluster_uuid
, kdu_instance
, filter=None, vca_id
=None
334 Updating vca status in NSR record
335 :param cluster_uuid: UUID of a k8s cluster
336 :param kdu_instance: The unique name of the KDU instance
337 :param filter: To get nsr_id
341 # self.logger.debug("_on_update_k8s_db(cluster_uuid={}, kdu_instance={}, filter={}"
342 # .format(cluster_uuid, kdu_instance, filter))
345 nsr_id
= filter.get("_id")
347 # get vca status for NS
348 vca_status
= await self
.k8sclusterjuju
.status_kdu(
351 complete_status
=True,
357 db_dict
["vcaStatus"] = {nsr_id
: vca_status
}
359 await self
.k8sclusterjuju
.update_vca_status(
360 db_dict
["vcaStatus"],
366 self
.update_db_2("nsrs", nsr_id
, db_dict
)
368 except (asyncio
.CancelledError
, asyncio
.TimeoutError
):
370 except Exception as e
:
371 self
.logger
.warn("Error updating NS state for ns={}: {}".format(nsr_id
, e
))
374 def _parse_cloud_init(cloud_init_text
, additional_params
, vnfd_id
, vdu_id
):
376 env
= Environment(undefined
=StrictUndefined
)
377 template
= env
.from_string(cloud_init_text
)
378 return template
.render(additional_params
or {})
379 except UndefinedError
as e
:
381 "Variable {} at vnfd[id={}]:vdu[id={}]:cloud-init/cloud-init-"
382 "file, must be provided in the instantiation parameters inside the "
383 "'additionalParamsForVnf/Vdu' block".format(e
, vnfd_id
, vdu_id
)
385 except (TemplateError
, TemplateNotFound
) as e
:
387 "Error parsing Jinja2 to cloud-init content at vnfd[id={}]:vdu[id={}]: {}".format(
392 def _get_vdu_cloud_init_content(self
, vdu
, vnfd
):
393 cloud_init_content
= cloud_init_file
= None
395 if vdu
.get("cloud-init-file"):
396 base_folder
= vnfd
["_admin"]["storage"]
397 cloud_init_file
= "{}/{}/cloud_init/{}".format(
398 base_folder
["folder"],
399 base_folder
["pkg-dir"],
400 vdu
["cloud-init-file"],
402 with self
.fs
.file_open(cloud_init_file
, "r") as ci_file
:
403 cloud_init_content
= ci_file
.read()
404 elif vdu
.get("cloud-init"):
405 cloud_init_content
= vdu
["cloud-init"]
407 return cloud_init_content
408 except FsException
as e
:
410 "Error reading vnfd[id={}]:vdu[id={}]:cloud-init-file={}: {}".format(
411 vnfd
["id"], vdu
["id"], cloud_init_file
, e
415 def _get_vdu_additional_params(self
, db_vnfr
, vdu_id
):
417 vdur
for vdur
in db_vnfr
.get("vdur") if vdu_id
== vdur
["vdu-id-ref"]
419 additional_params
= vdur
.get("additionalParams")
420 return parse_yaml_strings(additional_params
)
422 def vnfd2RO(self
, vnfd
, new_id
=None, additionalParams
=None, nsrId
=None):
424 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
425 :param vnfd: input vnfd
426 :param new_id: overrides vnf id if provided
427 :param additionalParams: Instantiation params for VNFs provided
428 :param nsrId: Id of the NSR
429 :return: copy of vnfd
431 vnfd_RO
= deepcopy(vnfd
)
432 # remove unused by RO configuration, monitoring, scaling and internal keys
433 vnfd_RO
.pop("_id", None)
434 vnfd_RO
.pop("_admin", None)
435 vnfd_RO
.pop("monitoring-param", None)
436 vnfd_RO
.pop("scaling-group-descriptor", None)
437 vnfd_RO
.pop("kdu", None)
438 vnfd_RO
.pop("k8s-cluster", None)
440 vnfd_RO
["id"] = new_id
442 # parse cloud-init or cloud-init-file with the provided variables using Jinja2
443 for vdu
in get_iterable(vnfd_RO
, "vdu"):
444 vdu
.pop("cloud-init-file", None)
445 vdu
.pop("cloud-init", None)
449 def ip_profile_2_RO(ip_profile
):
450 RO_ip_profile
= deepcopy(ip_profile
)
451 if "dns-server" in RO_ip_profile
:
452 if isinstance(RO_ip_profile
["dns-server"], list):
453 RO_ip_profile
["dns-address"] = []
454 for ds
in RO_ip_profile
.pop("dns-server"):
455 RO_ip_profile
["dns-address"].append(ds
["address"])
457 RO_ip_profile
["dns-address"] = RO_ip_profile
.pop("dns-server")
458 if RO_ip_profile
.get("ip-version") == "ipv4":
459 RO_ip_profile
["ip-version"] = "IPv4"
460 if RO_ip_profile
.get("ip-version") == "ipv6":
461 RO_ip_profile
["ip-version"] = "IPv6"
462 if "dhcp-params" in RO_ip_profile
:
463 RO_ip_profile
["dhcp"] = RO_ip_profile
.pop("dhcp-params")
466 def _get_ro_vim_id_for_vim_account(self
, vim_account
):
467 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_account
})
468 if db_vim
["_admin"]["operationalState"] != "ENABLED":
470 "VIM={} is not available. operationalState={}".format(
471 vim_account
, db_vim
["_admin"]["operationalState"]
474 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
477 def get_ro_wim_id_for_wim_account(self
, wim_account
):
478 if isinstance(wim_account
, str):
479 db_wim
= self
.db
.get_one("wim_accounts", {"_id": wim_account
})
480 if db_wim
["_admin"]["operationalState"] != "ENABLED":
482 "WIM={} is not available. operationalState={}".format(
483 wim_account
, db_wim
["_admin"]["operationalState"]
486 RO_wim_id
= db_wim
["_admin"]["deployed"]["RO-account"]
491 def scale_vnfr(self
, db_vnfr
, vdu_create
=None, vdu_delete
=None, mark_delete
=False):
493 db_vdu_push_list
= []
494 db_update
= {"_admin.modified": time()}
496 for vdu_id
, vdu_count
in vdu_create
.items():
500 for vdur
in reversed(db_vnfr
["vdur"])
501 if vdur
["vdu-id-ref"] == vdu_id
507 "Error scaling OUT VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
512 for count
in range(vdu_count
):
513 vdur_copy
= deepcopy(vdur
)
514 vdur_copy
["status"] = "BUILD"
515 vdur_copy
["status-detailed"] = None
516 vdur_copy
["ip-address"] = None
517 vdur_copy
["_id"] = str(uuid4())
518 vdur_copy
["count-index"] += count
+ 1
519 vdur_copy
["id"] = "{}-{}".format(
520 vdur_copy
["vdu-id-ref"], vdur_copy
["count-index"]
522 vdur_copy
.pop("vim_info", None)
523 for iface
in vdur_copy
["interfaces"]:
524 if iface
.get("fixed-ip"):
525 iface
["ip-address"] = self
.increment_ip_mac(
526 iface
["ip-address"], count
+ 1
529 iface
.pop("ip-address", None)
530 if iface
.get("fixed-mac"):
531 iface
["mac-address"] = self
.increment_ip_mac(
532 iface
["mac-address"], count
+ 1
535 iface
.pop("mac-address", None)
538 ) # only first vdu can be managment of vnf
539 db_vdu_push_list
.append(vdur_copy
)
540 # self.logger.debug("scale out, adding vdu={}".format(vdur_copy))
542 for vdu_id
, vdu_count
in vdu_delete
.items():
544 indexes_to_delete
= [
546 for iv
in enumerate(db_vnfr
["vdur"])
547 if iv
[1]["vdu-id-ref"] == vdu_id
551 "vdur.{}.status".format(i
): "DELETING"
552 for i
in indexes_to_delete
[-vdu_count
:]
556 # it must be deleted one by one because common.db does not allow otherwise
559 for v
in reversed(db_vnfr
["vdur"])
560 if v
["vdu-id-ref"] == vdu_id
562 for vdu
in vdus_to_delete
[:vdu_count
]:
565 {"_id": db_vnfr
["_id"]},
567 pull
={"vdur": {"_id": vdu
["_id"]}},
569 db_push
= {"vdur": db_vdu_push_list
} if db_vdu_push_list
else None
570 self
.db
.set_one("vnfrs", {"_id": db_vnfr
["_id"]}, db_update
, push_list
=db_push
)
571 # modify passed dictionary db_vnfr
572 db_vnfr_
= self
.db
.get_one("vnfrs", {"_id": db_vnfr
["_id"]})
573 db_vnfr
["vdur"] = db_vnfr_
["vdur"]
575 def ns_update_nsr(self
, ns_update_nsr
, db_nsr
, nsr_desc_RO
):
577 Updates database nsr with the RO info for the created vld
578 :param ns_update_nsr: dictionary to be filled with the updated info
579 :param db_nsr: content of db_nsr. This is also modified
580 :param nsr_desc_RO: nsr descriptor from RO
581 :return: Nothing, LcmException is raised on errors
584 for vld_index
, vld
in enumerate(get_iterable(db_nsr
, "vld")):
585 for net_RO
in get_iterable(nsr_desc_RO
, "nets"):
586 if vld
["id"] != net_RO
.get("ns_net_osm_id"):
588 vld
["vim-id"] = net_RO
.get("vim_net_id")
589 vld
["name"] = net_RO
.get("vim_name")
590 vld
["status"] = net_RO
.get("status")
591 vld
["status-detailed"] = net_RO
.get("error_msg")
592 ns_update_nsr
["vld.{}".format(vld_index
)] = vld
596 "ns_update_nsr: Not found vld={} at RO info".format(vld
["id"])
599 def set_vnfr_at_error(self
, db_vnfrs
, error_text
):
601 for db_vnfr
in db_vnfrs
.values():
602 vnfr_update
= {"status": "ERROR"}
603 for vdu_index
, vdur
in enumerate(get_iterable(db_vnfr
, "vdur")):
604 if "status" not in vdur
:
605 vdur
["status"] = "ERROR"
606 vnfr_update
["vdur.{}.status".format(vdu_index
)] = "ERROR"
608 vdur
["status-detailed"] = str(error_text
)
610 "vdur.{}.status-detailed".format(vdu_index
)
612 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
613 except DbException
as e
:
614 self
.logger
.error("Cannot update vnf. {}".format(e
))
616 def ns_update_vnfr(self
, db_vnfrs
, nsr_desc_RO
):
618 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
619 :param db_vnfrs: dictionary with member-vnf-index: vnfr-content
620 :param nsr_desc_RO: nsr descriptor from RO
621 :return: Nothing, LcmException is raised on errors
623 for vnf_index
, db_vnfr
in db_vnfrs
.items():
624 for vnf_RO
in nsr_desc_RO
["vnfs"]:
625 if vnf_RO
["member_vnf_index"] != vnf_index
:
628 if vnf_RO
.get("ip_address"):
629 db_vnfr
["ip-address"] = vnfr_update
["ip-address"] = vnf_RO
[
632 elif not db_vnfr
.get("ip-address"):
633 if db_vnfr
.get("vdur"): # if not VDUs, there is not ip_address
634 raise LcmExceptionNoMgmtIP(
635 "ns member_vnf_index '{}' has no IP address".format(
640 for vdu_index
, vdur
in enumerate(get_iterable(db_vnfr
, "vdur")):
641 vdur_RO_count_index
= 0
642 if vdur
.get("pdu-type"):
644 for vdur_RO
in get_iterable(vnf_RO
, "vms"):
645 if vdur
["vdu-id-ref"] != vdur_RO
["vdu_osm_id"]:
647 if vdur
["count-index"] != vdur_RO_count_index
:
648 vdur_RO_count_index
+= 1
650 vdur
["vim-id"] = vdur_RO
.get("vim_vm_id")
651 if vdur_RO
.get("ip_address"):
652 vdur
["ip-address"] = vdur_RO
["ip_address"].split(";")[0]
654 vdur
["ip-address"] = None
655 vdur
["vdu-id-ref"] = vdur_RO
.get("vdu_osm_id")
656 vdur
["name"] = vdur_RO
.get("vim_name")
657 vdur
["status"] = vdur_RO
.get("status")
658 vdur
["status-detailed"] = vdur_RO
.get("error_msg")
659 for ifacer
in get_iterable(vdur
, "interfaces"):
660 for interface_RO
in get_iterable(vdur_RO
, "interfaces"):
661 if ifacer
["name"] == interface_RO
.get("internal_name"):
662 ifacer
["ip-address"] = interface_RO
.get(
665 ifacer
["mac-address"] = interface_RO
.get(
671 "ns_update_vnfr: Not found member_vnf_index={} vdur={} interface={} "
672 "from VIM info".format(
673 vnf_index
, vdur
["vdu-id-ref"], ifacer
["name"]
676 vnfr_update
["vdur.{}".format(vdu_index
)] = vdur
680 "ns_update_vnfr: Not found member_vnf_index={} vdur={} count_index={} from "
682 vnf_index
, vdur
["vdu-id-ref"], vdur
["count-index"]
686 for vld_index
, vld
in enumerate(get_iterable(db_vnfr
, "vld")):
687 for net_RO
in get_iterable(nsr_desc_RO
, "nets"):
688 if vld
["id"] != net_RO
.get("vnf_net_osm_id"):
690 vld
["vim-id"] = net_RO
.get("vim_net_id")
691 vld
["name"] = net_RO
.get("vim_name")
692 vld
["status"] = net_RO
.get("status")
693 vld
["status-detailed"] = net_RO
.get("error_msg")
694 vnfr_update
["vld.{}".format(vld_index
)] = vld
698 "ns_update_vnfr: Not found member_vnf_index={} vld={} from VIM info".format(
703 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
708 "ns_update_vnfr: Not found member_vnf_index={} from VIM info".format(
713 def _get_ns_config_info(self
, nsr_id
):
715 Generates a mapping between vnf,vdu elements and the N2VC id
716 :param nsr_id: id of nsr to get last database _admin.deployed.VCA that contains this list
717 :return: a dictionary with {osm-config-mapping: {}} where its element contains:
718 "<member-vnf-index>": <N2VC-id> for a vnf configuration, or
719 "<member-vnf-index>.<vdu.id>.<vdu replica(0, 1,..)>": <N2VC-id> for a vdu configuration
721 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
722 vca_deployed_list
= db_nsr
["_admin"]["deployed"]["VCA"]
724 ns_config_info
= {"osm-config-mapping": mapping
}
725 for vca
in vca_deployed_list
:
726 if not vca
["member-vnf-index"]:
728 if not vca
["vdu_id"]:
729 mapping
[vca
["member-vnf-index"]] = vca
["application"]
733 vca
["member-vnf-index"], vca
["vdu_id"], vca
["vdu_count_index"]
735 ] = vca
["application"]
736 return ns_config_info
738 async def _instantiate_ng_ro(
755 def get_vim_account(vim_account_id
):
757 if vim_account_id
in db_vims
:
758 return db_vims
[vim_account_id
]
759 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_account_id
})
760 db_vims
[vim_account_id
] = db_vim
763 # modify target_vld info with instantiation parameters
764 def parse_vld_instantiation_params(
765 target_vim
, target_vld
, vld_params
, target_sdn
767 if vld_params
.get("ip-profile"):
768 target_vld
["vim_info"][target_vim
]["ip_profile"] = vld_params
[
771 if vld_params
.get("provider-network"):
772 target_vld
["vim_info"][target_vim
]["provider_network"] = vld_params
[
775 if "sdn-ports" in vld_params
["provider-network"] and target_sdn
:
776 target_vld
["vim_info"][target_sdn
]["sdn-ports"] = vld_params
[
779 if vld_params
.get("wimAccountId"):
780 target_wim
= "wim:{}".format(vld_params
["wimAccountId"])
781 target_vld
["vim_info"][target_wim
] = {}
782 for param
in ("vim-network-name", "vim-network-id"):
783 if vld_params
.get(param
):
784 if isinstance(vld_params
[param
], dict):
785 for vim
, vim_net
in vld_params
[param
].items():
786 other_target_vim
= "vim:" + vim
788 target_vld
["vim_info"],
789 (other_target_vim
, param
.replace("-", "_")),
792 else: # isinstance str
793 target_vld
["vim_info"][target_vim
][
794 param
.replace("-", "_")
795 ] = vld_params
[param
]
796 if vld_params
.get("common_id"):
797 target_vld
["common_id"] = vld_params
.get("common_id")
799 # modify target["ns"]["vld"] with instantiation parameters to override vnf vim-account
800 def update_ns_vld_target(target
, ns_params
):
801 for vnf_params
in ns_params
.get("vnf", ()):
802 if vnf_params
.get("vimAccountId"):
806 for vnfr
in db_vnfrs
.values()
807 if vnf_params
["member-vnf-index"]
808 == vnfr
["member-vnf-index-ref"]
812 vdur
= next((vdur
for vdur
in target_vnf
.get("vdur", ())), None)
813 for a_index
, a_vld
in enumerate(target
["ns"]["vld"]):
814 target_vld
= find_in_list(
815 get_iterable(vdur
, "interfaces"),
816 lambda iface
: iface
.get("ns-vld-id") == a_vld
["name"],
819 if vnf_params
.get("vimAccountId") not in a_vld
.get(
822 target
["ns"]["vld"][a_index
].get("vim_info").update(
824 "vim:{}".format(vnf_params
["vimAccountId"]): {
825 "vim_network_name": ""
830 nslcmop_id
= db_nslcmop
["_id"]
832 "name": db_nsr
["name"],
835 "image": deepcopy(db_nsr
["image"]),
836 "flavor": deepcopy(db_nsr
["flavor"]),
837 "action_id": nslcmop_id
,
838 "cloud_init_content": {},
840 for image
in target
["image"]:
841 image
["vim_info"] = {}
842 for flavor
in target
["flavor"]:
843 flavor
["vim_info"] = {}
845 if db_nslcmop
.get("lcmOperationType") != "instantiate":
846 # get parameters of instantiation:
847 db_nslcmop_instantiate
= self
.db
.get_list(
850 "nsInstanceId": db_nslcmop
["nsInstanceId"],
851 "lcmOperationType": "instantiate",
854 ns_params
= db_nslcmop_instantiate
.get("operationParams")
856 ns_params
= db_nslcmop
.get("operationParams")
857 ssh_keys_instantiation
= ns_params
.get("ssh_keys") or []
858 ssh_keys_all
= ssh_keys_instantiation
+ (n2vc_key_list
or [])
861 for vld_index
, vld
in enumerate(db_nsr
.get("vld")):
862 target_vim
= "vim:{}".format(ns_params
["vimAccountId"])
866 "mgmt-network": vld
.get("mgmt-network", False),
867 "type": vld
.get("type"),
870 "vim_network_name": vld
.get("vim-network-name"),
871 "vim_account_id": ns_params
["vimAccountId"],
875 # check if this network needs SDN assist
876 if vld
.get("pci-interfaces"):
877 db_vim
= get_vim_account(ns_params
["vimAccountId"])
878 sdnc_id
= db_vim
["config"].get("sdn-controller")
880 sdn_vld
= "nsrs:{}:vld.{}".format(nsr_id
, vld
["id"])
881 target_sdn
= "sdn:{}".format(sdnc_id
)
882 target_vld
["vim_info"][target_sdn
] = {
884 "target_vim": target_vim
,
886 "type": vld
.get("type"),
889 nsd_vnf_profiles
= get_vnf_profiles(nsd
)
890 for nsd_vnf_profile
in nsd_vnf_profiles
:
891 for cp
in nsd_vnf_profile
["virtual-link-connectivity"]:
892 if cp
["virtual-link-profile-id"] == vld
["id"]:
894 "member_vnf:{}.{}".format(
895 cp
["constituent-cpd-id"][0][
896 "constituent-base-element-id"
898 cp
["constituent-cpd-id"][0]["constituent-cpd-id"],
900 ] = "nsrs:{}:vld.{}".format(nsr_id
, vld_index
)
902 # check at nsd descriptor, if there is an ip-profile
904 nsd_vlp
= find_in_list(
905 get_virtual_link_profiles(nsd
),
906 lambda a_link_profile
: a_link_profile
["virtual-link-desc-id"]
911 and nsd_vlp
.get("virtual-link-protocol-data")
912 and nsd_vlp
["virtual-link-protocol-data"].get("l3-protocol-data")
914 ip_profile_source_data
= nsd_vlp
["virtual-link-protocol-data"][
917 ip_profile_dest_data
= {}
918 if "ip-version" in ip_profile_source_data
:
919 ip_profile_dest_data
["ip-version"] = ip_profile_source_data
[
922 if "cidr" in ip_profile_source_data
:
923 ip_profile_dest_data
["subnet-address"] = ip_profile_source_data
[
926 if "gateway-ip" in ip_profile_source_data
:
927 ip_profile_dest_data
["gateway-address"] = ip_profile_source_data
[
930 if "dhcp-enabled" in ip_profile_source_data
:
931 ip_profile_dest_data
["dhcp-params"] = {
932 "enabled": ip_profile_source_data
["dhcp-enabled"]
934 vld_params
["ip-profile"] = ip_profile_dest_data
936 # update vld_params with instantiation params
937 vld_instantiation_params
= find_in_list(
938 get_iterable(ns_params
, "vld"),
939 lambda a_vld
: a_vld
["name"] in (vld
["name"], vld
["id"]),
941 if vld_instantiation_params
:
942 vld_params
.update(vld_instantiation_params
)
943 parse_vld_instantiation_params(target_vim
, target_vld
, vld_params
, None)
944 target
["ns"]["vld"].append(target_vld
)
945 # Update the target ns_vld if vnf vim_account is overriden by instantiation params
946 update_ns_vld_target(target
, ns_params
)
948 for vnfr
in db_vnfrs
.values():
950 db_vnfds
, lambda db_vnf
: db_vnf
["id"] == vnfr
["vnfd-ref"]
952 vnf_params
= find_in_list(
953 get_iterable(ns_params
, "vnf"),
954 lambda a_vnf
: a_vnf
["member-vnf-index"] == vnfr
["member-vnf-index-ref"],
956 target_vnf
= deepcopy(vnfr
)
957 target_vim
= "vim:{}".format(vnfr
["vim-account-id"])
958 for vld
in target_vnf
.get("vld", ()):
959 # check if connected to a ns.vld, to fill target'
960 vnf_cp
= find_in_list(
961 vnfd
.get("int-virtual-link-desc", ()),
962 lambda cpd
: cpd
.get("id") == vld
["id"],
965 ns_cp
= "member_vnf:{}.{}".format(
966 vnfr
["member-vnf-index-ref"], vnf_cp
["id"]
968 if cp2target
.get(ns_cp
):
969 vld
["target"] = cp2target
[ns_cp
]
972 target_vim
: {"vim_network_name": vld
.get("vim-network-name")}
974 # check if this network needs SDN assist
976 if vld
.get("pci-interfaces"):
977 db_vim
= get_vim_account(vnfr
["vim-account-id"])
978 sdnc_id
= db_vim
["config"].get("sdn-controller")
980 sdn_vld
= "vnfrs:{}:vld.{}".format(target_vnf
["_id"], vld
["id"])
981 target_sdn
= "sdn:{}".format(sdnc_id
)
982 vld
["vim_info"][target_sdn
] = {
984 "target_vim": target_vim
,
986 "type": vld
.get("type"),
989 # check at vnfd descriptor, if there is an ip-profile
991 vnfd_vlp
= find_in_list(
992 get_virtual_link_profiles(vnfd
),
993 lambda a_link_profile
: a_link_profile
["id"] == vld
["id"],
997 and vnfd_vlp
.get("virtual-link-protocol-data")
998 and vnfd_vlp
["virtual-link-protocol-data"].get("l3-protocol-data")
1000 ip_profile_source_data
= vnfd_vlp
["virtual-link-protocol-data"][
1003 ip_profile_dest_data
= {}
1004 if "ip-version" in ip_profile_source_data
:
1005 ip_profile_dest_data
["ip-version"] = ip_profile_source_data
[
1008 if "cidr" in ip_profile_source_data
:
1009 ip_profile_dest_data
["subnet-address"] = ip_profile_source_data
[
1012 if "gateway-ip" in ip_profile_source_data
:
1013 ip_profile_dest_data
[
1015 ] = ip_profile_source_data
["gateway-ip"]
1016 if "dhcp-enabled" in ip_profile_source_data
:
1017 ip_profile_dest_data
["dhcp-params"] = {
1018 "enabled": ip_profile_source_data
["dhcp-enabled"]
1021 vld_params
["ip-profile"] = ip_profile_dest_data
1022 # update vld_params with instantiation params
1024 vld_instantiation_params
= find_in_list(
1025 get_iterable(vnf_params
, "internal-vld"),
1026 lambda i_vld
: i_vld
["name"] == vld
["id"],
1028 if vld_instantiation_params
:
1029 vld_params
.update(vld_instantiation_params
)
1030 parse_vld_instantiation_params(target_vim
, vld
, vld_params
, target_sdn
)
1033 for vdur
in target_vnf
.get("vdur", ()):
1034 if vdur
.get("status") == "DELETING" or vdur
.get("pdu-type"):
1035 continue # This vdu must not be created
1036 vdur
["vim_info"] = {"vim_account_id": vnfr
["vim-account-id"]}
1038 self
.logger
.debug("NS > ssh_keys > {}".format(ssh_keys_all
))
1041 vdu_configuration
= get_configuration(vnfd
, vdur
["vdu-id-ref"])
1042 vnf_configuration
= get_configuration(vnfd
, vnfd
["id"])
1045 and vdu_configuration
.get("config-access")
1046 and vdu_configuration
.get("config-access").get("ssh-access")
1048 vdur
["ssh-keys"] = ssh_keys_all
1049 vdur
["ssh-access-required"] = vdu_configuration
[
1051 ]["ssh-access"]["required"]
1054 and vnf_configuration
.get("config-access")
1055 and vnf_configuration
.get("config-access").get("ssh-access")
1056 and any(iface
.get("mgmt-vnf") for iface
in vdur
["interfaces"])
1058 vdur
["ssh-keys"] = ssh_keys_all
1059 vdur
["ssh-access-required"] = vnf_configuration
[
1061 ]["ssh-access"]["required"]
1062 elif ssh_keys_instantiation
and find_in_list(
1063 vdur
["interfaces"], lambda iface
: iface
.get("mgmt-vnf")
1065 vdur
["ssh-keys"] = ssh_keys_instantiation
1067 self
.logger
.debug("NS > vdur > {}".format(vdur
))
1069 vdud
= get_vdu(vnfd
, vdur
["vdu-id-ref"])
1071 if vdud
.get("cloud-init-file"):
1072 vdur
["cloud-init"] = "{}:file:{}".format(
1073 vnfd
["_id"], vdud
.get("cloud-init-file")
1075 # read file and put content at target.cloul_init_content. Avoid ng_ro to use shared package system
1076 if vdur
["cloud-init"] not in target
["cloud_init_content"]:
1077 base_folder
= vnfd
["_admin"]["storage"]
1078 cloud_init_file
= "{}/{}/cloud_init/{}".format(
1079 base_folder
["folder"],
1080 base_folder
["pkg-dir"],
1081 vdud
.get("cloud-init-file"),
1083 with self
.fs
.file_open(cloud_init_file
, "r") as ci_file
:
1084 target
["cloud_init_content"][
1087 elif vdud
.get("cloud-init"):
1088 vdur
["cloud-init"] = "{}:vdu:{}".format(
1089 vnfd
["_id"], get_vdu_index(vnfd
, vdur
["vdu-id-ref"])
1091 # put content at target.cloul_init_content. Avoid ng_ro read vnfd descriptor
1092 target
["cloud_init_content"][vdur
["cloud-init"]] = vdud
[
1095 vdur
["additionalParams"] = vdur
.get("additionalParams") or {}
1096 deploy_params_vdu
= self
._format
_additional
_params
(
1097 vdur
.get("additionalParams") or {}
1099 deploy_params_vdu
["OSM"] = get_osm_params(
1100 vnfr
, vdur
["vdu-id-ref"], vdur
["count-index"]
1102 vdur
["additionalParams"] = deploy_params_vdu
1105 ns_flavor
= target
["flavor"][int(vdur
["ns-flavor-id"])]
1106 if target_vim
not in ns_flavor
["vim_info"]:
1107 ns_flavor
["vim_info"][target_vim
] = {}
1110 # in case alternative images are provided we must check if they should be applied
1111 # for the vim_type, modify the vim_type taking into account
1112 ns_image_id
= int(vdur
["ns-image-id"])
1113 if vdur
.get("alt-image-ids"):
1114 db_vim
= get_vim_account(vnfr
["vim-account-id"])
1115 vim_type
= db_vim
["vim_type"]
1116 for alt_image_id
in vdur
.get("alt-image-ids"):
1117 ns_alt_image
= target
["image"][int(alt_image_id
)]
1118 if vim_type
== ns_alt_image
.get("vim-type"):
1119 # must use alternative image
1121 "use alternative image id: {}".format(alt_image_id
)
1123 ns_image_id
= alt_image_id
1124 vdur
["ns-image-id"] = ns_image_id
1126 ns_image
= target
["image"][int(ns_image_id
)]
1127 if target_vim
not in ns_image
["vim_info"]:
1128 ns_image
["vim_info"][target_vim
] = {}
1130 vdur
["vim_info"] = {target_vim
: {}}
1131 # instantiation parameters
1133 # vdu_instantiation_params = next((v for v in get_iterable(vnf_params, "vdu") if v["id"] ==
1134 # vdud["id"]), None)
1135 vdur_list
.append(vdur
)
1136 target_vnf
["vdur"] = vdur_list
1137 target
["vnf"].append(target_vnf
)
1139 desc
= await self
.RO
.deploy(nsr_id
, target
)
1140 self
.logger
.debug("RO return > {}".format(desc
))
1141 action_id
= desc
["action_id"]
1142 await self
._wait
_ng
_ro
(
1143 nsr_id
, action_id
, nslcmop_id
, start_deploy
, timeout_ns_deploy
, stage
1148 "_admin.deployed.RO.operational-status": "running",
1149 "detailed-status": " ".join(stage
),
1151 # db_nsr["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
1152 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1153 self
._write
_op
_status
(nslcmop_id
, stage
)
1155 logging_text
+ "ns deployed at RO. RO_id={}".format(action_id
)
1159 async def _wait_ng_ro(
1168 detailed_status_old
= None
1170 start_time
= start_time
or time()
1171 while time() <= start_time
+ timeout
:
1172 desc_status
= await self
.RO
.status(nsr_id
, action_id
)
1173 self
.logger
.debug("Wait NG RO > {}".format(desc_status
))
1174 if desc_status
["status"] == "FAILED":
1175 raise NgRoException(desc_status
["details"])
1176 elif desc_status
["status"] == "BUILD":
1178 stage
[2] = "VIM: ({})".format(desc_status
["details"])
1179 elif desc_status
["status"] == "DONE":
1181 stage
[2] = "Deployed at VIM"
1184 assert False, "ROclient.check_ns_status returns unknown {}".format(
1185 desc_status
["status"]
1187 if stage
and nslcmop_id
and stage
[2] != detailed_status_old
:
1188 detailed_status_old
= stage
[2]
1189 db_nsr_update
["detailed-status"] = " ".join(stage
)
1190 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1191 self
._write
_op
_status
(nslcmop_id
, stage
)
1192 await asyncio
.sleep(15, loop
=self
.loop
)
1193 else: # timeout_ns_deploy
1194 raise NgRoException("Timeout waiting ns to deploy")
1196 async def _terminate_ng_ro(
1197 self
, logging_text
, nsr_deployed
, nsr_id
, nslcmop_id
, stage
1202 start_deploy
= time()
1209 "action_id": nslcmop_id
,
1211 desc
= await self
.RO
.deploy(nsr_id
, target
)
1212 action_id
= desc
["action_id"]
1213 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = action_id
1214 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETING"
1217 + "ns terminate action at RO. action_id={}".format(action_id
)
1221 delete_timeout
= 20 * 60 # 20 minutes
1222 await self
._wait
_ng
_ro
(
1223 nsr_id
, action_id
, nslcmop_id
, start_deploy
, delete_timeout
, stage
1226 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
1227 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
1229 await self
.RO
.delete(nsr_id
)
1230 except Exception as e
:
1231 if isinstance(e
, NgRoException
) and e
.http_code
== 404: # not found
1232 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1233 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
1234 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
1236 logging_text
+ "RO_action_id={} already deleted".format(action_id
)
1238 elif isinstance(e
, NgRoException
) and e
.http_code
== 409: # conflict
1239 failed_detail
.append("delete conflict: {}".format(e
))
1242 + "RO_action_id={} delete conflict: {}".format(action_id
, e
)
1245 failed_detail
.append("delete error: {}".format(e
))
1248 + "RO_action_id={} delete error: {}".format(action_id
, e
)
1252 stage
[2] = "Error deleting from VIM"
1254 stage
[2] = "Deleted from VIM"
1255 db_nsr_update
["detailed-status"] = " ".join(stage
)
1256 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1257 self
._write
_op
_status
(nslcmop_id
, stage
)
1260 raise LcmException("; ".join(failed_detail
))
1263 async def instantiate_RO(
1277 :param logging_text: preffix text to use at logging
1278 :param nsr_id: nsr identity
1279 :param nsd: database content of ns descriptor
1280 :param db_nsr: database content of ns record
1281 :param db_nslcmop: database content of ns operation, in this case, 'instantiate'
1283 :param db_vnfds: database content of vnfds, indexed by id (not _id). {id: {vnfd_object}, ...}
1284 :param n2vc_key_list: ssh-public-key list to be inserted to management vdus via cloud-init
1285 :param stage: list with 3 items: [general stage, tasks, vim_specific]. This task will write over vim_specific
1286 :return: None or exception
1289 start_deploy
= time()
1290 ns_params
= db_nslcmop
.get("operationParams")
1291 if ns_params
and ns_params
.get("timeout_ns_deploy"):
1292 timeout_ns_deploy
= ns_params
["timeout_ns_deploy"]
1294 timeout_ns_deploy
= self
.timeout
.get(
1295 "ns_deploy", self
.timeout_ns_deploy
1298 # Check for and optionally request placement optimization. Database will be updated if placement activated
1299 stage
[2] = "Waiting for Placement."
1300 if await self
._do
_placement
(logging_text
, db_nslcmop
, db_vnfrs
):
1301 # in case of placement change ns_params[vimAcountId) if not present at any vnfrs
1302 for vnfr
in db_vnfrs
.values():
1303 if ns_params
["vimAccountId"] == vnfr
["vim-account-id"]:
1306 ns_params
["vimAccountId"] == vnfr
["vim-account-id"]
1308 return await self
._instantiate
_ng
_ro
(
1321 except Exception as e
:
1322 stage
[2] = "ERROR deploying at VIM"
1323 self
.set_vnfr_at_error(db_vnfrs
, str(e
))
1325 "Error deploying at VIM {}".format(e
),
1326 exc_info
=not isinstance(
1329 ROclient
.ROClientException
,
1338 async def wait_kdu_up(self
, logging_text
, nsr_id
, vnfr_id
, kdu_name
):
1340 Wait for kdu to be up, get ip address
1341 :param logging_text: prefix use for logging
1348 # self.logger.debug(logging_text + "Starting wait_kdu_up")
1351 while nb_tries
< 360:
1352 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnfr_id
})
1356 for x
in get_iterable(db_vnfr
, "kdur")
1357 if x
.get("kdu-name") == kdu_name
1363 "Not found vnfr_id={}, kdu_name={}".format(vnfr_id
, kdu_name
)
1365 if kdur
.get("status"):
1366 if kdur
["status"] in ("READY", "ENABLED"):
1367 return kdur
.get("ip-address")
1370 "target KDU={} is in error state".format(kdu_name
)
1373 await asyncio
.sleep(10, loop
=self
.loop
)
1375 raise LcmException("Timeout waiting KDU={} instantiated".format(kdu_name
))
1377 async def wait_vm_up_insert_key_ro(
1378 self
, logging_text
, nsr_id
, vnfr_id
, vdu_id
, vdu_index
, pub_key
=None, user
=None
1381 Wait for ip addres at RO, and optionally, insert public key in virtual machine
1382 :param logging_text: prefix use for logging
1387 :param pub_key: public ssh key to inject, None to skip
1388 :param user: user to apply the public ssh key
1392 self
.logger
.debug(logging_text
+ "Starting wait_vm_up_insert_key_ro")
1396 target_vdu_id
= None
1402 if ro_retries
>= 360: # 1 hour
1404 "Not found _admin.deployed.RO.nsr_id for nsr_id: {}".format(nsr_id
)
1407 await asyncio
.sleep(10, loop
=self
.loop
)
1410 if not target_vdu_id
:
1411 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnfr_id
})
1413 if not vdu_id
: # for the VNF case
1414 if db_vnfr
.get("status") == "ERROR":
1416 "Cannot inject ssh-key because target VNF is in error state"
1418 ip_address
= db_vnfr
.get("ip-address")
1424 for x
in get_iterable(db_vnfr
, "vdur")
1425 if x
.get("ip-address") == ip_address
1433 for x
in get_iterable(db_vnfr
, "vdur")
1434 if x
.get("vdu-id-ref") == vdu_id
1435 and x
.get("count-index") == vdu_index
1441 not vdur
and len(db_vnfr
.get("vdur", ())) == 1
1442 ): # If only one, this should be the target vdu
1443 vdur
= db_vnfr
["vdur"][0]
1446 "Not found vnfr_id={}, vdu_id={}, vdu_index={}".format(
1447 vnfr_id
, vdu_id
, vdu_index
1450 # New generation RO stores information at "vim_info"
1453 if vdur
.get("vim_info"):
1455 t
for t
in vdur
["vim_info"]
1456 ) # there should be only one key
1457 ng_ro_status
= vdur
["vim_info"][target_vim
].get("vim_status")
1459 vdur
.get("pdu-type")
1460 or vdur
.get("status") == "ACTIVE"
1461 or ng_ro_status
== "ACTIVE"
1463 ip_address
= vdur
.get("ip-address")
1466 target_vdu_id
= vdur
["vdu-id-ref"]
1467 elif vdur
.get("status") == "ERROR" or ng_ro_status
== "ERROR":
1469 "Cannot inject ssh-key because target VM is in error state"
1472 if not target_vdu_id
:
1475 # inject public key into machine
1476 if pub_key
and user
:
1477 self
.logger
.debug(logging_text
+ "Inserting RO key")
1478 self
.logger
.debug("SSH > PubKey > {}".format(pub_key
))
1479 if vdur
.get("pdu-type"):
1480 self
.logger
.error(logging_text
+ "Cannot inject ssh-ky to a PDU")
1483 ro_vm_id
= "{}-{}".format(
1484 db_vnfr
["member-vnf-index-ref"], target_vdu_id
1485 ) # TODO add vdu_index
1489 "action": "inject_ssh_key",
1493 "vnf": [{"_id": vnfr_id
, "vdur": [{"id": vdur
["id"]}]}],
1495 desc
= await self
.RO
.deploy(nsr_id
, target
)
1496 action_id
= desc
["action_id"]
1497 await self
._wait
_ng
_ro
(nsr_id
, action_id
, timeout
=600)
1500 # wait until NS is deployed at RO
1502 db_nsrs
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1503 ro_nsr_id
= deep_get(
1504 db_nsrs
, ("_admin", "deployed", "RO", "nsr_id")
1508 result_dict
= await self
.RO
.create_action(
1510 item_id_name
=ro_nsr_id
,
1512 "add_public_key": pub_key
,
1517 # result_dict contains the format {VM-id: {vim_result: 200, description: text}}
1518 if not result_dict
or not isinstance(result_dict
, dict):
1520 "Unknown response from RO when injecting key"
1522 for result
in result_dict
.values():
1523 if result
.get("vim_result") == 200:
1526 raise ROclient
.ROClientException(
1527 "error injecting key: {}".format(
1528 result
.get("description")
1532 except NgRoException
as e
:
1534 "Reaching max tries injecting key. Error: {}".format(e
)
1536 except ROclient
.ROClientException
as e
:
1540 + "error injecting key: {}. Retrying until {} seconds".format(
1547 "Reaching max tries injecting key. Error: {}".format(e
)
1554 async def _wait_dependent_n2vc(self
, nsr_id
, vca_deployed_list
, vca_index
):
1556 Wait until dependent VCA deployments have been finished. NS wait for VNFs and VDUs. VNFs for VDUs
1558 my_vca
= vca_deployed_list
[vca_index
]
1559 if my_vca
.get("vdu_id") or my_vca
.get("kdu_name"):
1560 # vdu or kdu: no dependencies
1564 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1565 vca_deployed_list
= db_nsr
["_admin"]["deployed"]["VCA"]
1566 configuration_status_list
= db_nsr
["configurationStatus"]
1567 for index
, vca_deployed
in enumerate(configuration_status_list
):
1568 if index
== vca_index
:
1571 if not my_vca
.get("member-vnf-index") or (
1572 vca_deployed
.get("member-vnf-index")
1573 == my_vca
.get("member-vnf-index")
1575 internal_status
= configuration_status_list
[index
].get("status")
1576 if internal_status
== "READY":
1578 elif internal_status
== "BROKEN":
1580 "Configuration aborted because dependent charm/s has failed"
1585 # no dependencies, return
1587 await asyncio
.sleep(10)
1590 raise LcmException("Configuration aborted because dependent charm/s timeout")
1592 def get_vca_id(self
, db_vnfr
: dict, db_nsr
: dict):
1595 vca_id
= deep_get(db_vnfr
, ("vca-id",))
1597 vim_account_id
= deep_get(db_nsr
, ("instantiate_params", "vimAccountId"))
1598 vca_id
= VimAccountDB
.get_vim_account_with_id(vim_account_id
).get("vca")
1601 async def instantiate_N2VC(
1618 ee_config_descriptor
,
1620 nsr_id
= db_nsr
["_id"]
1621 db_update_entry
= "_admin.deployed.VCA.{}.".format(vca_index
)
1622 vca_deployed_list
= db_nsr
["_admin"]["deployed"]["VCA"]
1623 vca_deployed
= db_nsr
["_admin"]["deployed"]["VCA"][vca_index
]
1624 osm_config
= {"osm": {"ns_id": db_nsr
["_id"]}}
1626 "collection": "nsrs",
1627 "filter": {"_id": nsr_id
},
1628 "path": db_update_entry
,
1634 element_under_configuration
= nsr_id
1638 vnfr_id
= db_vnfr
["_id"]
1639 osm_config
["osm"]["vnf_id"] = vnfr_id
1641 namespace
= "{nsi}.{ns}".format(nsi
=nsi_id
if nsi_id
else "", ns
=nsr_id
)
1643 if vca_type
== "native_charm":
1646 index_number
= vdu_index
or 0
1649 element_type
= "VNF"
1650 element_under_configuration
= vnfr_id
1651 namespace
+= ".{}-{}".format(vnfr_id
, index_number
)
1653 namespace
+= ".{}-{}".format(vdu_id
, index_number
)
1654 element_type
= "VDU"
1655 element_under_configuration
= "{}-{}".format(vdu_id
, index_number
)
1656 osm_config
["osm"]["vdu_id"] = vdu_id
1658 namespace
+= ".{}".format(kdu_name
)
1659 element_type
= "KDU"
1660 element_under_configuration
= kdu_name
1661 osm_config
["osm"]["kdu_name"] = kdu_name
1664 artifact_path
= "{}/{}/{}/{}".format(
1665 base_folder
["folder"],
1666 base_folder
["pkg-dir"],
1668 if vca_type
in ("native_charm", "lxc_proxy_charm", "k8s_proxy_charm")
1673 self
.logger
.debug("Artifact path > {}".format(artifact_path
))
1675 # get initial_config_primitive_list that applies to this element
1676 initial_config_primitive_list
= config_descriptor
.get(
1677 "initial-config-primitive"
1681 "Initial config primitive list > {}".format(
1682 initial_config_primitive_list
1686 # add config if not present for NS charm
1687 ee_descriptor_id
= ee_config_descriptor
.get("id")
1688 self
.logger
.debug("EE Descriptor > {}".format(ee_descriptor_id
))
1689 initial_config_primitive_list
= get_ee_sorted_initial_config_primitive_list(
1690 initial_config_primitive_list
, vca_deployed
, ee_descriptor_id
1694 "Initial config primitive list #2 > {}".format(
1695 initial_config_primitive_list
1698 # n2vc_redesign STEP 3.1
1699 # find old ee_id if exists
1700 ee_id
= vca_deployed
.get("ee_id")
1702 vca_id
= self
.get_vca_id(db_vnfr
, db_nsr
)
1703 # create or register execution environment in VCA
1704 if vca_type
in ("lxc_proxy_charm", "k8s_proxy_charm", "helm", "helm-v3"):
1706 self
._write
_configuration
_status
(
1708 vca_index
=vca_index
,
1710 element_under_configuration
=element_under_configuration
,
1711 element_type
=element_type
,
1714 step
= "create execution environment"
1715 self
.logger
.debug(logging_text
+ step
)
1719 if vca_type
== "k8s_proxy_charm":
1720 ee_id
= await self
.vca_map
[vca_type
].install_k8s_proxy_charm(
1721 charm_name
=artifact_path
[artifact_path
.rfind("/") + 1 :],
1722 namespace
=namespace
,
1723 artifact_path
=artifact_path
,
1727 elif vca_type
== "helm" or vca_type
== "helm-v3":
1728 ee_id
, credentials
= await self
.vca_map
[
1730 ].create_execution_environment(
1731 namespace
=namespace
,
1735 artifact_path
=artifact_path
,
1739 ee_id
, credentials
= await self
.vca_map
[
1741 ].create_execution_environment(
1742 namespace
=namespace
,
1748 elif vca_type
== "native_charm":
1749 step
= "Waiting to VM being up and getting IP address"
1750 self
.logger
.debug(logging_text
+ step
)
1751 rw_mgmt_ip
= await self
.wait_vm_up_insert_key_ro(
1760 credentials
= {"hostname": rw_mgmt_ip
}
1762 username
= deep_get(
1763 config_descriptor
, ("config-access", "ssh-access", "default-user")
1765 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1766 # merged. Meanwhile let's get username from initial-config-primitive
1767 if not username
and initial_config_primitive_list
:
1768 for config_primitive
in initial_config_primitive_list
:
1769 for param
in config_primitive
.get("parameter", ()):
1770 if param
["name"] == "ssh-username":
1771 username
= param
["value"]
1775 "Cannot determine the username neither with 'initial-config-primitive' nor with "
1776 "'config-access.ssh-access.default-user'"
1778 credentials
["username"] = username
1779 # n2vc_redesign STEP 3.2
1781 self
._write
_configuration
_status
(
1783 vca_index
=vca_index
,
1784 status
="REGISTERING",
1785 element_under_configuration
=element_under_configuration
,
1786 element_type
=element_type
,
1789 step
= "register execution environment {}".format(credentials
)
1790 self
.logger
.debug(logging_text
+ step
)
1791 ee_id
= await self
.vca_map
[vca_type
].register_execution_environment(
1792 credentials
=credentials
,
1793 namespace
=namespace
,
1798 # for compatibility with MON/POL modules, the need model and application name at database
1799 # TODO ask MON/POL if needed to not assuming anymore the format "model_name.application_name"
1800 ee_id_parts
= ee_id
.split(".")
1801 db_nsr_update
= {db_update_entry
+ "ee_id": ee_id
}
1802 if len(ee_id_parts
) >= 2:
1803 model_name
= ee_id_parts
[0]
1804 application_name
= ee_id_parts
[1]
1805 db_nsr_update
[db_update_entry
+ "model"] = model_name
1806 db_nsr_update
[db_update_entry
+ "application"] = application_name
1808 # n2vc_redesign STEP 3.3
1809 step
= "Install configuration Software"
1811 self
._write
_configuration
_status
(
1813 vca_index
=vca_index
,
1814 status
="INSTALLING SW",
1815 element_under_configuration
=element_under_configuration
,
1816 element_type
=element_type
,
1817 other_update
=db_nsr_update
,
1820 # TODO check if already done
1821 self
.logger
.debug(logging_text
+ step
)
1823 if vca_type
== "native_charm":
1824 config_primitive
= next(
1825 (p
for p
in initial_config_primitive_list
if p
["name"] == "config"),
1828 if config_primitive
:
1829 config
= self
._map
_primitive
_params
(
1830 config_primitive
, {}, deploy_params
1833 if vca_type
== "lxc_proxy_charm":
1834 if element_type
== "NS":
1835 num_units
= db_nsr
.get("config-units") or 1
1836 elif element_type
== "VNF":
1837 num_units
= db_vnfr
.get("config-units") or 1
1838 elif element_type
== "VDU":
1839 for v
in db_vnfr
["vdur"]:
1840 if vdu_id
== v
["vdu-id-ref"]:
1841 num_units
= v
.get("config-units") or 1
1843 if vca_type
!= "k8s_proxy_charm":
1844 await self
.vca_map
[vca_type
].install_configuration_sw(
1846 artifact_path
=artifact_path
,
1849 num_units
=num_units
,
1854 # write in db flag of configuration_sw already installed
1856 "nsrs", nsr_id
, {db_update_entry
+ "config_sw_installed": True}
1859 # add relations for this VCA (wait for other peers related with this VCA)
1860 await self
._add
_vca
_relations
(
1861 logging_text
=logging_text
,
1863 vca_index
=vca_index
,
1868 # if SSH access is required, then get execution environment SSH public
1869 # if native charm we have waited already to VM be UP
1870 if vca_type
in ("k8s_proxy_charm", "lxc_proxy_charm", "helm", "helm-v3"):
1873 # self.logger.debug("get ssh key block")
1875 config_descriptor
, ("config-access", "ssh-access", "required")
1877 # self.logger.debug("ssh key needed")
1878 # Needed to inject a ssh key
1881 ("config-access", "ssh-access", "default-user"),
1883 step
= "Install configuration Software, getting public ssh key"
1884 pub_key
= await self
.vca_map
[vca_type
].get_ee_ssh_public__key(
1885 ee_id
=ee_id
, db_dict
=db_dict
, vca_id
=vca_id
1888 step
= "Insert public key into VM user={} ssh_key={}".format(
1892 # self.logger.debug("no need to get ssh key")
1893 step
= "Waiting to VM being up and getting IP address"
1894 self
.logger
.debug(logging_text
+ step
)
1896 # n2vc_redesign STEP 5.1
1897 # wait for RO (ip-address) Insert pub_key into VM
1900 rw_mgmt_ip
= await self
.wait_kdu_up(
1901 logging_text
, nsr_id
, vnfr_id
, kdu_name
1904 rw_mgmt_ip
= await self
.wait_vm_up_insert_key_ro(
1914 rw_mgmt_ip
= None # This is for a NS configuration
1916 self
.logger
.debug(logging_text
+ " VM_ip_address={}".format(rw_mgmt_ip
))
1918 # store rw_mgmt_ip in deploy params for later replacement
1919 deploy_params
["rw_mgmt_ip"] = rw_mgmt_ip
1921 # n2vc_redesign STEP 6 Execute initial config primitive
1922 step
= "execute initial config primitive"
1924 # wait for dependent primitives execution (NS -> VNF -> VDU)
1925 if initial_config_primitive_list
:
1926 await self
._wait
_dependent
_n
2vc
(nsr_id
, vca_deployed_list
, vca_index
)
1928 # stage, in function of element type: vdu, kdu, vnf or ns
1929 my_vca
= vca_deployed_list
[vca_index
]
1930 if my_vca
.get("vdu_id") or my_vca
.get("kdu_name"):
1932 stage
[0] = "Stage 3/5: running Day-1 primitives for VDU."
1933 elif my_vca
.get("member-vnf-index"):
1935 stage
[0] = "Stage 4/5: running Day-1 primitives for VNF."
1938 stage
[0] = "Stage 5/5: running Day-1 primitives for NS."
1940 self
._write
_configuration
_status
(
1941 nsr_id
=nsr_id
, vca_index
=vca_index
, status
="EXECUTING PRIMITIVE"
1944 self
._write
_op
_status
(op_id
=nslcmop_id
, stage
=stage
)
1946 check_if_terminated_needed
= True
1947 for initial_config_primitive
in initial_config_primitive_list
:
1948 # adding information on the vca_deployed if it is a NS execution environment
1949 if not vca_deployed
["member-vnf-index"]:
1950 deploy_params
["ns_config_info"] = json
.dumps(
1951 self
._get
_ns
_config
_info
(nsr_id
)
1953 # TODO check if already done
1954 primitive_params_
= self
._map
_primitive
_params
(
1955 initial_config_primitive
, {}, deploy_params
1958 step
= "execute primitive '{}' params '{}'".format(
1959 initial_config_primitive
["name"], primitive_params_
1961 self
.logger
.debug(logging_text
+ step
)
1962 await self
.vca_map
[vca_type
].exec_primitive(
1964 primitive_name
=initial_config_primitive
["name"],
1965 params_dict
=primitive_params_
,
1970 # Once some primitive has been exec, check and write at db if it needs to exec terminated primitives
1971 if check_if_terminated_needed
:
1972 if config_descriptor
.get("terminate-config-primitive"):
1974 "nsrs", nsr_id
, {db_update_entry
+ "needed_terminate": True}
1976 check_if_terminated_needed
= False
1978 # TODO register in database that primitive is done
1980 # STEP 7 Configure metrics
1981 if vca_type
== "helm" or vca_type
== "helm-v3":
1982 prometheus_jobs
= await self
.add_prometheus_metrics(
1984 artifact_path
=artifact_path
,
1985 ee_config_descriptor
=ee_config_descriptor
,
1988 target_ip
=rw_mgmt_ip
,
1994 {db_update_entry
+ "prometheus_jobs": prometheus_jobs
},
1997 step
= "instantiated at VCA"
1998 self
.logger
.debug(logging_text
+ step
)
2000 self
._write
_configuration
_status
(
2001 nsr_id
=nsr_id
, vca_index
=vca_index
, status
="READY"
2004 except Exception as e
: # TODO not use Exception but N2VC exception
2005 # self.update_db_2("nsrs", nsr_id, {db_update_entry + "instantiation": "FAILED"})
2007 e
, (DbException
, N2VCException
, LcmException
, asyncio
.CancelledError
)
2010 "Exception while {} : {}".format(step
, e
), exc_info
=True
2012 self
._write
_configuration
_status
(
2013 nsr_id
=nsr_id
, vca_index
=vca_index
, status
="BROKEN"
2015 raise LcmException("{} {}".format(step
, e
)) from e
2017 def _write_ns_status(
2021 current_operation
: str,
2022 current_operation_id
: str,
2023 error_description
: str = None,
2024 error_detail
: str = None,
2025 other_update
: dict = None,
2028 Update db_nsr fields.
2031 :param current_operation:
2032 :param current_operation_id:
2033 :param error_description:
2034 :param error_detail:
2035 :param other_update: Other required changes at database if provided, will be cleared
2039 db_dict
= other_update
or {}
2042 ] = current_operation_id
# for backward compatibility
2043 db_dict
["_admin.current-operation"] = current_operation_id
2044 db_dict
["_admin.operation-type"] = (
2045 current_operation
if current_operation
!= "IDLE" else None
2047 db_dict
["currentOperation"] = current_operation
2048 db_dict
["currentOperationID"] = current_operation_id
2049 db_dict
["errorDescription"] = error_description
2050 db_dict
["errorDetail"] = error_detail
2053 db_dict
["nsState"] = ns_state
2054 self
.update_db_2("nsrs", nsr_id
, db_dict
)
2055 except DbException
as e
:
2056 self
.logger
.warn("Error writing NS status, ns={}: {}".format(nsr_id
, e
))
2058 def _write_op_status(
2062 error_message
: str = None,
2063 queuePosition
: int = 0,
2064 operation_state
: str = None,
2065 other_update
: dict = None,
2068 db_dict
= other_update
or {}
2069 db_dict
["queuePosition"] = queuePosition
2070 if isinstance(stage
, list):
2071 db_dict
["stage"] = stage
[0]
2072 db_dict
["detailed-status"] = " ".join(stage
)
2073 elif stage
is not None:
2074 db_dict
["stage"] = str(stage
)
2076 if error_message
is not None:
2077 db_dict
["errorMessage"] = error_message
2078 if operation_state
is not None:
2079 db_dict
["operationState"] = operation_state
2080 db_dict
["statusEnteredTime"] = time()
2081 self
.update_db_2("nslcmops", op_id
, db_dict
)
2082 except DbException
as e
:
2084 "Error writing OPERATION status for op_id: {} -> {}".format(op_id
, e
)
2087 def _write_all_config_status(self
, db_nsr
: dict, status
: str):
2089 nsr_id
= db_nsr
["_id"]
2090 # configurationStatus
2091 config_status
= db_nsr
.get("configurationStatus")
2094 "configurationStatus.{}.status".format(index
): status
2095 for index
, v
in enumerate(config_status
)
2099 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2101 except DbException
as e
:
2103 "Error writing all configuration status, ns={}: {}".format(nsr_id
, e
)
2106 def _write_configuration_status(
2111 element_under_configuration
: str = None,
2112 element_type
: str = None,
2113 other_update
: dict = None,
2116 # self.logger.debug('_write_configuration_status(): vca_index={}, status={}'
2117 # .format(vca_index, status))
2120 db_path
= "configurationStatus.{}.".format(vca_index
)
2121 db_dict
= other_update
or {}
2123 db_dict
[db_path
+ "status"] = status
2124 if element_under_configuration
:
2126 db_path
+ "elementUnderConfiguration"
2127 ] = element_under_configuration
2129 db_dict
[db_path
+ "elementType"] = element_type
2130 self
.update_db_2("nsrs", nsr_id
, db_dict
)
2131 except DbException
as e
:
2133 "Error writing configuration status={}, ns={}, vca_index={}: {}".format(
2134 status
, nsr_id
, vca_index
, e
2138 async def _do_placement(self
, logging_text
, db_nslcmop
, db_vnfrs
):
2140 Check and computes the placement, (vim account where to deploy). If it is decided by an external tool, it
2141 sends the request via kafka and wait until the result is wrote at database (nslcmops _admin.plca).
2142 Database is used because the result can be obtained from a different LCM worker in case of HA.
2143 :param logging_text: contains the prefix for logging, with the ns and nslcmop identifiers
2144 :param db_nslcmop: database content of nslcmop
2145 :param db_vnfrs: database content of vnfrs, indexed by member-vnf-index.
2146 :return: True if some modification is done. Modifies database vnfrs and parameter db_vnfr with the
2147 computed 'vim-account-id'
2150 nslcmop_id
= db_nslcmop
["_id"]
2151 placement_engine
= deep_get(db_nslcmop
, ("operationParams", "placement-engine"))
2152 if placement_engine
== "PLA":
2154 logging_text
+ "Invoke and wait for placement optimization"
2156 await self
.msg
.aiowrite(
2157 "pla", "get_placement", {"nslcmopId": nslcmop_id
}, loop
=self
.loop
2159 db_poll_interval
= 5
2160 wait
= db_poll_interval
* 10
2162 while not pla_result
and wait
>= 0:
2163 await asyncio
.sleep(db_poll_interval
)
2164 wait
-= db_poll_interval
2165 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
2166 pla_result
= deep_get(db_nslcmop
, ("_admin", "pla"))
2170 "Placement timeout for nslcmopId={}".format(nslcmop_id
)
2173 for pla_vnf
in pla_result
["vnf"]:
2174 vnfr
= db_vnfrs
.get(pla_vnf
["member-vnf-index"])
2175 if not pla_vnf
.get("vimAccountId") or not vnfr
:
2180 {"_id": vnfr
["_id"]},
2181 {"vim-account-id": pla_vnf
["vimAccountId"]},
2184 vnfr
["vim-account-id"] = pla_vnf
["vimAccountId"]
2187 def update_nsrs_with_pla_result(self
, params
):
2189 nslcmop_id
= deep_get(params
, ("placement", "nslcmopId"))
2191 "nslcmops", nslcmop_id
, {"_admin.pla": params
.get("placement")}
2193 except Exception as e
:
2194 self
.logger
.warn("Update failed for nslcmop_id={}:{}".format(nslcmop_id
, e
))
2196 async def instantiate(self
, nsr_id
, nslcmop_id
):
2199 :param nsr_id: ns instance to deploy
2200 :param nslcmop_id: operation to run
2204 # Try to lock HA task here
2205 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA("ns", "nslcmops", nslcmop_id
)
2206 if not task_is_locked_by_me
:
2208 "instantiate() task is not locked by me, ns={}".format(nsr_id
)
2212 logging_text
= "Task ns={} instantiate={} ".format(nsr_id
, nslcmop_id
)
2213 self
.logger
.debug(logging_text
+ "Enter")
2215 # get all needed from database
2217 # database nsrs record
2220 # database nslcmops record
2223 # update operation on nsrs
2225 # update operation on nslcmops
2226 db_nslcmop_update
= {}
2228 nslcmop_operation_state
= None
2229 db_vnfrs
= {} # vnf's info indexed by member-index
2231 tasks_dict_info
= {} # from task to info text
2235 "Stage 1/5: preparation of the environment.",
2236 "Waiting for previous operations to terminate.",
2239 # ^ stage, step, VIM progress
2241 # wait for any previous tasks in process
2242 await self
.lcm_tasks
.waitfor_related_HA("ns", "nslcmops", nslcmop_id
)
2244 # STEP 0: Reading database (nslcmops, nsrs, nsds, vnfrs, vnfds)
2245 stage
[1] = "Reading from database."
2246 # nsState="BUILDING", currentOperation="INSTANTIATING", currentOperationID=nslcmop_id
2247 db_nsr_update
["detailed-status"] = "creating"
2248 db_nsr_update
["operational-status"] = "init"
2249 self
._write
_ns
_status
(
2251 ns_state
="BUILDING",
2252 current_operation
="INSTANTIATING",
2253 current_operation_id
=nslcmop_id
,
2254 other_update
=db_nsr_update
,
2256 self
._write
_op
_status
(op_id
=nslcmop_id
, stage
=stage
, queuePosition
=0)
2258 # read from db: operation
2259 stage
[1] = "Getting nslcmop={} from db.".format(nslcmop_id
)
2260 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
2261 if db_nslcmop
["operationParams"].get("additionalParamsForVnf"):
2262 db_nslcmop
["operationParams"]["additionalParamsForVnf"] = json
.loads(
2263 db_nslcmop
["operationParams"]["additionalParamsForVnf"]
2265 ns_params
= db_nslcmop
.get("operationParams")
2266 if ns_params
and ns_params
.get("timeout_ns_deploy"):
2267 timeout_ns_deploy
= ns_params
["timeout_ns_deploy"]
2269 timeout_ns_deploy
= self
.timeout
.get(
2270 "ns_deploy", self
.timeout_ns_deploy
2274 stage
[1] = "Getting nsr={} from db.".format(nsr_id
)
2275 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2276 stage
[1] = "Getting nsd={} from db.".format(db_nsr
["nsd-id"])
2277 nsd
= self
.db
.get_one("nsds", {"_id": db_nsr
["nsd-id"]})
2278 self
.fs
.sync(db_nsr
["nsd-id"])
2280 # nsr_name = db_nsr["name"] # TODO short-name??
2282 # read from db: vnf's of this ns
2283 stage
[1] = "Getting vnfrs from db."
2284 self
.logger
.debug(logging_text
+ stage
[1])
2285 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2287 # read from db: vnfd's for every vnf
2288 db_vnfds
= [] # every vnfd data
2290 # for each vnf in ns, read vnfd
2291 for vnfr
in db_vnfrs_list
:
2292 if vnfr
.get("kdur"):
2294 for kdur
in vnfr
["kdur"]:
2295 if kdur
.get("additionalParams"):
2296 kdur
["additionalParams"] = json
.loads(kdur
["additionalParams"])
2297 kdur_list
.append(kdur
)
2298 vnfr
["kdur"] = kdur_list
2300 db_vnfrs
[vnfr
["member-vnf-index-ref"]] = vnfr
2301 vnfd_id
= vnfr
["vnfd-id"]
2302 vnfd_ref
= vnfr
["vnfd-ref"]
2303 self
.fs
.sync(vnfd_id
)
2305 # if we haven't this vnfd, read it from db
2306 if vnfd_id
not in db_vnfds
:
2308 stage
[1] = "Getting vnfd={} id='{}' from db.".format(
2311 self
.logger
.debug(logging_text
+ stage
[1])
2312 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
2315 db_vnfds
.append(vnfd
)
2317 # Get or generates the _admin.deployed.VCA list
2318 vca_deployed_list
= None
2319 if db_nsr
["_admin"].get("deployed"):
2320 vca_deployed_list
= db_nsr
["_admin"]["deployed"].get("VCA")
2321 if vca_deployed_list
is None:
2322 vca_deployed_list
= []
2323 configuration_status_list
= []
2324 db_nsr_update
["_admin.deployed.VCA"] = vca_deployed_list
2325 db_nsr_update
["configurationStatus"] = configuration_status_list
2326 # add _admin.deployed.VCA to db_nsr dictionary, value=vca_deployed_list
2327 populate_dict(db_nsr
, ("_admin", "deployed", "VCA"), vca_deployed_list
)
2328 elif isinstance(vca_deployed_list
, dict):
2329 # maintain backward compatibility. Change a dict to list at database
2330 vca_deployed_list
= list(vca_deployed_list
.values())
2331 db_nsr_update
["_admin.deployed.VCA"] = vca_deployed_list
2332 populate_dict(db_nsr
, ("_admin", "deployed", "VCA"), vca_deployed_list
)
2335 deep_get(db_nsr
, ("_admin", "deployed", "RO", "vnfd")), list
2337 populate_dict(db_nsr
, ("_admin", "deployed", "RO", "vnfd"), [])
2338 db_nsr_update
["_admin.deployed.RO.vnfd"] = []
2340 # set state to INSTANTIATED. When instantiated NBI will not delete directly
2341 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
2342 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2344 "vnfrs", {"nsr-id-ref": nsr_id
}, {"_admin.nsState": "INSTANTIATED"}
2347 # n2vc_redesign STEP 2 Deploy Network Scenario
2348 stage
[0] = "Stage 2/5: deployment of KDUs, VMs and execution environments."
2349 self
._write
_op
_status
(op_id
=nslcmop_id
, stage
=stage
)
2351 stage
[1] = "Deploying KDUs."
2352 # self.logger.debug(logging_text + "Before deploy_kdus")
2353 # Call to deploy_kdus in case exists the "vdu:kdu" param
2354 await self
.deploy_kdus(
2355 logging_text
=logging_text
,
2357 nslcmop_id
=nslcmop_id
,
2360 task_instantiation_info
=tasks_dict_info
,
2363 stage
[1] = "Getting VCA public key."
2364 # n2vc_redesign STEP 1 Get VCA public ssh-key
2365 # feature 1429. Add n2vc public key to needed VMs
2366 n2vc_key
= self
.n2vc
.get_public_key()
2367 n2vc_key_list
= [n2vc_key
]
2368 if self
.vca_config
.get("public_key"):
2369 n2vc_key_list
.append(self
.vca_config
["public_key"])
2371 stage
[1] = "Deploying NS at VIM."
2372 task_ro
= asyncio
.ensure_future(
2373 self
.instantiate_RO(
2374 logging_text
=logging_text
,
2378 db_nslcmop
=db_nslcmop
,
2381 n2vc_key_list
=n2vc_key_list
,
2385 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_RO", task_ro
)
2386 tasks_dict_info
[task_ro
] = "Deploying at VIM"
2388 # n2vc_redesign STEP 3 to 6 Deploy N2VC
2389 stage
[1] = "Deploying Execution Environments."
2390 self
.logger
.debug(logging_text
+ stage
[1])
2392 nsi_id
= None # TODO put nsi_id when this nsr belongs to a NSI
2393 for vnf_profile
in get_vnf_profiles(nsd
):
2394 vnfd_id
= vnf_profile
["vnfd-id"]
2395 vnfd
= find_in_list(db_vnfds
, lambda a_vnf
: a_vnf
["id"] == vnfd_id
)
2396 member_vnf_index
= str(vnf_profile
["id"])
2397 db_vnfr
= db_vnfrs
[member_vnf_index
]
2398 base_folder
= vnfd
["_admin"]["storage"]
2404 # Get additional parameters
2405 deploy_params
= {"OSM": get_osm_params(db_vnfr
)}
2406 if db_vnfr
.get("additionalParamsForVnf"):
2407 deploy_params
.update(
2408 parse_yaml_strings(db_vnfr
["additionalParamsForVnf"].copy())
2411 descriptor_config
= get_configuration(vnfd
, vnfd
["id"])
2412 if descriptor_config
:
2414 logging_text
=logging_text
2415 + "member_vnf_index={} ".format(member_vnf_index
),
2418 nslcmop_id
=nslcmop_id
,
2424 member_vnf_index
=member_vnf_index
,
2425 vdu_index
=vdu_index
,
2427 deploy_params
=deploy_params
,
2428 descriptor_config
=descriptor_config
,
2429 base_folder
=base_folder
,
2430 task_instantiation_info
=tasks_dict_info
,
2434 # Deploy charms for each VDU that supports one.
2435 for vdud
in get_vdu_list(vnfd
):
2437 descriptor_config
= get_configuration(vnfd
, vdu_id
)
2438 vdur
= find_in_list(
2439 db_vnfr
["vdur"], lambda vdu
: vdu
["vdu-id-ref"] == vdu_id
2442 if vdur
.get("additionalParams"):
2443 deploy_params_vdu
= parse_yaml_strings(vdur
["additionalParams"])
2445 deploy_params_vdu
= deploy_params
2446 deploy_params_vdu
["OSM"] = get_osm_params(
2447 db_vnfr
, vdu_id
, vdu_count_index
=0
2449 vdud_count
= get_number_of_instances(vnfd
, vdu_id
)
2451 self
.logger
.debug("VDUD > {}".format(vdud
))
2453 "Descriptor config > {}".format(descriptor_config
)
2455 if descriptor_config
:
2458 for vdu_index
in range(vdud_count
):
2459 # TODO vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
2461 logging_text
=logging_text
2462 + "member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
2463 member_vnf_index
, vdu_id
, vdu_index
2467 nslcmop_id
=nslcmop_id
,
2473 member_vnf_index
=member_vnf_index
,
2474 vdu_index
=vdu_index
,
2476 deploy_params
=deploy_params_vdu
,
2477 descriptor_config
=descriptor_config
,
2478 base_folder
=base_folder
,
2479 task_instantiation_info
=tasks_dict_info
,
2482 for kdud
in get_kdu_list(vnfd
):
2483 kdu_name
= kdud
["name"]
2484 descriptor_config
= get_configuration(vnfd
, kdu_name
)
2485 if descriptor_config
:
2490 x
for x
in db_vnfr
["kdur"] if x
["kdu-name"] == kdu_name
2492 deploy_params_kdu
= {"OSM": get_osm_params(db_vnfr
)}
2493 if kdur
.get("additionalParams"):
2494 deploy_params_kdu
= parse_yaml_strings(
2495 kdur
["additionalParams"]
2499 logging_text
=logging_text
,
2502 nslcmop_id
=nslcmop_id
,
2508 member_vnf_index
=member_vnf_index
,
2509 vdu_index
=vdu_index
,
2511 deploy_params
=deploy_params_kdu
,
2512 descriptor_config
=descriptor_config
,
2513 base_folder
=base_folder
,
2514 task_instantiation_info
=tasks_dict_info
,
2518 # Check if this NS has a charm configuration
2519 descriptor_config
= nsd
.get("ns-configuration")
2520 if descriptor_config
and descriptor_config
.get("juju"):
2523 member_vnf_index
= None
2529 # Get additional parameters
2530 deploy_params
= {"OSM": {"vim_account_id": ns_params
["vimAccountId"]}}
2531 if db_nsr
.get("additionalParamsForNs"):
2532 deploy_params
.update(
2533 parse_yaml_strings(db_nsr
["additionalParamsForNs"].copy())
2535 base_folder
= nsd
["_admin"]["storage"]
2537 logging_text
=logging_text
,
2540 nslcmop_id
=nslcmop_id
,
2546 member_vnf_index
=member_vnf_index
,
2547 vdu_index
=vdu_index
,
2549 deploy_params
=deploy_params
,
2550 descriptor_config
=descriptor_config
,
2551 base_folder
=base_folder
,
2552 task_instantiation_info
=tasks_dict_info
,
2556 # rest of staff will be done at finally
2559 ROclient
.ROClientException
,
2565 logging_text
+ "Exit Exception while '{}': {}".format(stage
[1], e
)
2568 except asyncio
.CancelledError
:
2570 logging_text
+ "Cancelled Exception while '{}'".format(stage
[1])
2572 exc
= "Operation was cancelled"
2573 except Exception as e
:
2574 exc
= traceback
.format_exc()
2575 self
.logger
.critical(
2576 logging_text
+ "Exit Exception while '{}': {}".format(stage
[1], e
),
2581 error_list
.append(str(exc
))
2583 # wait for pending tasks
2585 stage
[1] = "Waiting for instantiate pending tasks."
2586 self
.logger
.debug(logging_text
+ stage
[1])
2587 error_list
+= await self
._wait
_for
_tasks
(
2595 stage
[1] = stage
[2] = ""
2596 except asyncio
.CancelledError
:
2597 error_list
.append("Cancelled")
2598 # TODO cancel all tasks
2599 except Exception as exc
:
2600 error_list
.append(str(exc
))
2602 # update operation-status
2603 db_nsr_update
["operational-status"] = "running"
2604 # let's begin with VCA 'configured' status (later we can change it)
2605 db_nsr_update
["config-status"] = "configured"
2606 for task
, task_name
in tasks_dict_info
.items():
2607 if not task
.done() or task
.cancelled() or task
.exception():
2608 if task_name
.startswith(self
.task_name_deploy_vca
):
2609 # A N2VC task is pending
2610 db_nsr_update
["config-status"] = "failed"
2612 # RO or KDU task is pending
2613 db_nsr_update
["operational-status"] = "failed"
2615 # update status at database
2617 error_detail
= ". ".join(error_list
)
2618 self
.logger
.error(logging_text
+ error_detail
)
2619 error_description_nslcmop
= "{} Detail: {}".format(
2620 stage
[0], error_detail
2622 error_description_nsr
= "Operation: INSTANTIATING.{}, {}".format(
2623 nslcmop_id
, stage
[0]
2626 db_nsr_update
["detailed-status"] = (
2627 error_description_nsr
+ " Detail: " + error_detail
2629 db_nslcmop_update
["detailed-status"] = error_detail
2630 nslcmop_operation_state
= "FAILED"
2634 error_description_nsr
= error_description_nslcmop
= None
2636 db_nsr_update
["detailed-status"] = "Done"
2637 db_nslcmop_update
["detailed-status"] = "Done"
2638 nslcmop_operation_state
= "COMPLETED"
2641 self
._write
_ns
_status
(
2644 current_operation
="IDLE",
2645 current_operation_id
=None,
2646 error_description
=error_description_nsr
,
2647 error_detail
=error_detail
,
2648 other_update
=db_nsr_update
,
2650 self
._write
_op
_status
(
2653 error_message
=error_description_nslcmop
,
2654 operation_state
=nslcmop_operation_state
,
2655 other_update
=db_nslcmop_update
,
2658 if nslcmop_operation_state
:
2660 await self
.msg
.aiowrite(
2665 "nslcmop_id": nslcmop_id
,
2666 "operationState": nslcmop_operation_state
,
2670 except Exception as e
:
2672 logging_text
+ "kafka_write notification Exception {}".format(e
)
2675 self
.logger
.debug(logging_text
+ "Exit")
2676 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_instantiate")
2678 async def _add_vca_relations(
2683 timeout
: int = 3600,
2684 vca_type
: str = None,
2689 # 1. find all relations for this VCA
2690 # 2. wait for other peers related
2694 vca_type
= vca_type
or "lxc_proxy_charm"
2696 # STEP 1: find all relations for this VCA
2699 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2700 nsd
= self
.db
.get_one("nsds", {"_id": db_nsr
["nsd-id"]})
2703 my_vca
= deep_get(db_nsr
, ("_admin", "deployed", "VCA"))[vca_index
]
2705 # read all ns-configuration relations
2706 ns_relations
= list()
2707 db_ns_relations
= deep_get(nsd
, ("ns-configuration", "relation"))
2709 for r
in db_ns_relations
:
2710 # check if this VCA is in the relation
2711 if my_vca
.get("member-vnf-index") in (
2712 r
.get("entities")[0].get("id"),
2713 r
.get("entities")[1].get("id"),
2715 ns_relations
.append(r
)
2717 # read all vnf-configuration relations
2718 vnf_relations
= list()
2719 db_vnfd_list
= db_nsr
.get("vnfd-id")
2721 for vnfd
in db_vnfd_list
:
2722 db_vnf_relations
= None
2723 db_vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd
})
2724 db_vnf_configuration
= get_configuration(db_vnfd
, db_vnfd
["id"])
2725 if db_vnf_configuration
:
2726 db_vnf_relations
= db_vnf_configuration
.get("relation", [])
2727 if db_vnf_relations
:
2728 for r
in db_vnf_relations
:
2729 # check if this VCA is in the relation
2730 if my_vca
.get("vdu_id") in (
2731 r
.get("entities")[0].get("id"),
2732 r
.get("entities")[1].get("id"),
2734 vnf_relations
.append(r
)
2736 # if no relations, terminate
2737 if not ns_relations
and not vnf_relations
:
2738 self
.logger
.debug(logging_text
+ " No relations")
2743 + " adding relations\n {}\n {}".format(
2744 ns_relations
, vnf_relations
2753 if now
- start
>= timeout
:
2754 self
.logger
.error(logging_text
+ " : timeout adding relations")
2757 # reload nsr from database (we need to update record: _admin.deloyed.VCA)
2758 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2760 # for each defined NS relation, find the VCA's related
2761 for r
in ns_relations
.copy():
2762 from_vca_ee_id
= None
2764 from_vca_endpoint
= None
2765 to_vca_endpoint
= None
2766 vca_list
= deep_get(db_nsr
, ("_admin", "deployed", "VCA"))
2767 for vca
in vca_list
:
2768 if vca
.get("member-vnf-index") == r
.get("entities")[0].get(
2770 ) and vca
.get("config_sw_installed"):
2771 from_vca_ee_id
= vca
.get("ee_id")
2772 from_vca_endpoint
= r
.get("entities")[0].get("endpoint")
2773 if vca
.get("member-vnf-index") == r
.get("entities")[1].get(
2775 ) and vca
.get("config_sw_installed"):
2776 to_vca_ee_id
= vca
.get("ee_id")
2777 to_vca_endpoint
= r
.get("entities")[1].get("endpoint")
2778 if from_vca_ee_id
and to_vca_ee_id
:
2780 await self
.vca_map
[vca_type
].add_relation(
2781 ee_id_1
=from_vca_ee_id
,
2782 ee_id_2
=to_vca_ee_id
,
2783 endpoint_1
=from_vca_endpoint
,
2784 endpoint_2
=to_vca_endpoint
,
2787 # remove entry from relations list
2788 ns_relations
.remove(r
)
2790 # check failed peers
2792 vca_status_list
= db_nsr
.get("configurationStatus")
2794 for i
in range(len(vca_list
)):
2796 vca_status
= vca_status_list
[i
]
2797 if vca
.get("member-vnf-index") == r
.get("entities")[
2800 if vca_status
.get("status") == "BROKEN":
2801 # peer broken: remove relation from list
2802 ns_relations
.remove(r
)
2803 if vca
.get("member-vnf-index") == r
.get("entities")[
2806 if vca_status
.get("status") == "BROKEN":
2807 # peer broken: remove relation from list
2808 ns_relations
.remove(r
)
2813 # for each defined VNF relation, find the VCA's related
2814 for r
in vnf_relations
.copy():
2815 from_vca_ee_id
= None
2817 from_vca_endpoint
= None
2818 to_vca_endpoint
= None
2819 vca_list
= deep_get(db_nsr
, ("_admin", "deployed", "VCA"))
2820 for vca
in vca_list
:
2821 key_to_check
= "vdu_id"
2822 if vca
.get("vdu_id") is None:
2823 key_to_check
= "vnfd_id"
2824 if vca
.get(key_to_check
) == r
.get("entities")[0].get(
2826 ) and vca
.get("config_sw_installed"):
2827 from_vca_ee_id
= vca
.get("ee_id")
2828 from_vca_endpoint
= r
.get("entities")[0].get("endpoint")
2829 if vca
.get(key_to_check
) == r
.get("entities")[1].get(
2831 ) and vca
.get("config_sw_installed"):
2832 to_vca_ee_id
= vca
.get("ee_id")
2833 to_vca_endpoint
= r
.get("entities")[1].get("endpoint")
2834 if from_vca_ee_id
and to_vca_ee_id
:
2836 await self
.vca_map
[vca_type
].add_relation(
2837 ee_id_1
=from_vca_ee_id
,
2838 ee_id_2
=to_vca_ee_id
,
2839 endpoint_1
=from_vca_endpoint
,
2840 endpoint_2
=to_vca_endpoint
,
2843 # remove entry from relations list
2844 vnf_relations
.remove(r
)
2846 # check failed peers
2848 vca_status_list
= db_nsr
.get("configurationStatus")
2850 for i
in range(len(vca_list
)):
2852 vca_status
= vca_status_list
[i
]
2853 if vca
.get("vdu_id") == r
.get("entities")[0].get(
2856 if vca_status
.get("status") == "BROKEN":
2857 # peer broken: remove relation from list
2858 vnf_relations
.remove(r
)
2859 if vca
.get("vdu_id") == r
.get("entities")[1].get(
2862 if vca_status
.get("status") == "BROKEN":
2863 # peer broken: remove relation from list
2864 vnf_relations
.remove(r
)
2870 await asyncio
.sleep(5.0)
2872 if not ns_relations
and not vnf_relations
:
2873 self
.logger
.debug("Relations added")
2878 except Exception as e
:
2879 self
.logger
.warn(logging_text
+ " ERROR adding relations: {}".format(e
))
2882 async def _install_kdu(
2890 k8s_instance_info
: dict,
2891 k8params
: dict = None,
2897 k8sclustertype
= k8s_instance_info
["k8scluster-type"]
2900 "collection": "nsrs",
2901 "filter": {"_id": nsr_id
},
2902 "path": nsr_db_path
,
2905 if k8s_instance_info
.get("kdu-deployment-name"):
2906 kdu_instance
= k8s_instance_info
.get("kdu-deployment-name")
2908 kdu_instance
= self
.k8scluster_map
[
2910 ].generate_kdu_instance_name(
2911 db_dict
=db_dict_install
,
2912 kdu_model
=k8s_instance_info
["kdu-model"],
2913 kdu_name
=k8s_instance_info
["kdu-name"],
2916 "nsrs", nsr_id
, {nsr_db_path
+ ".kdu-instance": kdu_instance
}
2918 await self
.k8scluster_map
[k8sclustertype
].install(
2919 cluster_uuid
=k8s_instance_info
["k8scluster-uuid"],
2920 kdu_model
=k8s_instance_info
["kdu-model"],
2923 db_dict
=db_dict_install
,
2925 kdu_name
=k8s_instance_info
["kdu-name"],
2926 namespace
=k8s_instance_info
["namespace"],
2927 kdu_instance
=kdu_instance
,
2931 "nsrs", nsr_id
, {nsr_db_path
+ ".kdu-instance": kdu_instance
}
2934 # Obtain services to obtain management service ip
2935 services
= await self
.k8scluster_map
[k8sclustertype
].get_services(
2936 cluster_uuid
=k8s_instance_info
["k8scluster-uuid"],
2937 kdu_instance
=kdu_instance
,
2938 namespace
=k8s_instance_info
["namespace"],
2941 # Obtain management service info (if exists)
2942 vnfr_update_dict
= {}
2943 kdu_config
= get_configuration(vnfd
, kdud
["name"])
2945 target_ee_list
= kdu_config
.get("execution-environment-list", [])
2950 vnfr_update_dict
["kdur.{}.services".format(kdu_index
)] = services
2953 for service
in kdud
.get("service", [])
2954 if service
.get("mgmt-service")
2956 for mgmt_service
in mgmt_services
:
2957 for service
in services
:
2958 if service
["name"].startswith(mgmt_service
["name"]):
2959 # Mgmt service found, Obtain service ip
2960 ip
= service
.get("external_ip", service
.get("cluster_ip"))
2961 if isinstance(ip
, list) and len(ip
) == 1:
2965 "kdur.{}.ip-address".format(kdu_index
)
2968 # Check if must update also mgmt ip at the vnf
2969 service_external_cp
= mgmt_service
.get(
2970 "external-connection-point-ref"
2972 if service_external_cp
:
2974 deep_get(vnfd
, ("mgmt-interface", "cp"))
2975 == service_external_cp
2977 vnfr_update_dict
["ip-address"] = ip
2982 "external-connection-point-ref", ""
2984 == service_external_cp
,
2987 "kdur.{}.ip-address".format(kdu_index
)
2992 "Mgmt service name: {} not found".format(
2993 mgmt_service
["name"]
2997 vnfr_update_dict
["kdur.{}.status".format(kdu_index
)] = "READY"
2998 self
.update_db_2("vnfrs", vnfr_data
.get("_id"), vnfr_update_dict
)
3000 kdu_config
= get_configuration(vnfd
, k8s_instance_info
["kdu-name"])
3003 and kdu_config
.get("initial-config-primitive")
3004 and get_juju_ee_ref(vnfd
, k8s_instance_info
["kdu-name"]) is None
3006 initial_config_primitive_list
= kdu_config
.get(
3007 "initial-config-primitive"
3009 initial_config_primitive_list
.sort(key
=lambda val
: int(val
["seq"]))
3011 for initial_config_primitive
in initial_config_primitive_list
:
3012 primitive_params_
= self
._map
_primitive
_params
(
3013 initial_config_primitive
, {}, {}
3016 await asyncio
.wait_for(
3017 self
.k8scluster_map
[k8sclustertype
].exec_primitive(
3018 cluster_uuid
=k8s_instance_info
["k8scluster-uuid"],
3019 kdu_instance
=kdu_instance
,
3020 primitive_name
=initial_config_primitive
["name"],
3021 params
=primitive_params_
,
3022 db_dict
=db_dict_install
,
3028 except Exception as e
:
3029 # Prepare update db with error and raise exception
3032 "nsrs", nsr_id
, {nsr_db_path
+ ".detailed-status": str(e
)}
3036 vnfr_data
.get("_id"),
3037 {"kdur.{}.status".format(kdu_index
): "ERROR"},
3040 # ignore to keep original exception
3042 # reraise original error
3047 async def deploy_kdus(
3054 task_instantiation_info
,
3056 # Launch kdus if present in the descriptor
3058 k8scluster_id_2_uuic
= {
3059 "helm-chart-v3": {},
3064 async def _get_cluster_id(cluster_id
, cluster_type
):
3065 nonlocal k8scluster_id_2_uuic
3066 if cluster_id
in k8scluster_id_2_uuic
[cluster_type
]:
3067 return k8scluster_id_2_uuic
[cluster_type
][cluster_id
]
3069 # check if K8scluster is creating and wait look if previous tasks in process
3070 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related(
3071 "k8scluster", cluster_id
3074 text
= "Waiting for related tasks '{}' on k8scluster {} to be completed".format(
3075 task_name
, cluster_id
3077 self
.logger
.debug(logging_text
+ text
)
3078 await asyncio
.wait(task_dependency
, timeout
=3600)
3080 db_k8scluster
= self
.db
.get_one(
3081 "k8sclusters", {"_id": cluster_id
}, fail_on_empty
=False
3083 if not db_k8scluster
:
3084 raise LcmException("K8s cluster {} cannot be found".format(cluster_id
))
3086 k8s_id
= deep_get(db_k8scluster
, ("_admin", cluster_type
, "id"))
3088 if cluster_type
== "helm-chart-v3":
3090 # backward compatibility for existing clusters that have not been initialized for helm v3
3091 k8s_credentials
= yaml
.safe_dump(
3092 db_k8scluster
.get("credentials")
3094 k8s_id
, uninstall_sw
= await self
.k8sclusterhelm3
.init_env(
3095 k8s_credentials
, reuse_cluster_uuid
=cluster_id
3097 db_k8scluster_update
= {}
3098 db_k8scluster_update
["_admin.helm-chart-v3.error_msg"] = None
3099 db_k8scluster_update
["_admin.helm-chart-v3.id"] = k8s_id
3100 db_k8scluster_update
[
3101 "_admin.helm-chart-v3.created"
3103 db_k8scluster_update
[
3104 "_admin.helm-chart-v3.operationalState"
3107 "k8sclusters", cluster_id
, db_k8scluster_update
3109 except Exception as e
:
3112 + "error initializing helm-v3 cluster: {}".format(str(e
))
3115 "K8s cluster '{}' has not been initialized for '{}'".format(
3116 cluster_id
, cluster_type
3121 "K8s cluster '{}' has not been initialized for '{}'".format(
3122 cluster_id
, cluster_type
3125 k8scluster_id_2_uuic
[cluster_type
][cluster_id
] = k8s_id
3128 logging_text
+= "Deploy kdus: "
3131 db_nsr_update
= {"_admin.deployed.K8s": []}
3132 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
3135 updated_cluster_list
= []
3136 updated_v3_cluster_list
= []
3138 for vnfr_data
in db_vnfrs
.values():
3139 vca_id
= self
.get_vca_id(vnfr_data
, {})
3140 for kdu_index
, kdur
in enumerate(get_iterable(vnfr_data
, "kdur")):
3141 # Step 0: Prepare and set parameters
3142 desc_params
= parse_yaml_strings(kdur
.get("additionalParams"))
3143 vnfd_id
= vnfr_data
.get("vnfd-id")
3144 vnfd_with_id
= find_in_list(
3145 db_vnfds
, lambda vnfd
: vnfd
["_id"] == vnfd_id
3149 for kdud
in vnfd_with_id
["kdu"]
3150 if kdud
["name"] == kdur
["kdu-name"]
3152 namespace
= kdur
.get("k8s-namespace")
3153 kdu_deployment_name
= kdur
.get("kdu-deployment-name")
3154 if kdur
.get("helm-chart"):
3155 kdumodel
= kdur
["helm-chart"]
3156 # Default version: helm3, if helm-version is v2 assign v2
3157 k8sclustertype
= "helm-chart-v3"
3158 self
.logger
.debug("kdur: {}".format(kdur
))
3160 kdur
.get("helm-version")
3161 and kdur
.get("helm-version") == "v2"
3163 k8sclustertype
= "helm-chart"
3164 elif kdur
.get("juju-bundle"):
3165 kdumodel
= kdur
["juju-bundle"]
3166 k8sclustertype
= "juju-bundle"
3169 "kdu type for kdu='{}.{}' is neither helm-chart nor "
3170 "juju-bundle. Maybe an old NBI version is running".format(
3171 vnfr_data
["member-vnf-index-ref"], kdur
["kdu-name"]
3174 # check if kdumodel is a file and exists
3176 vnfd_with_id
= find_in_list(
3177 db_vnfds
, lambda vnfd
: vnfd
["_id"] == vnfd_id
3179 storage
= deep_get(vnfd_with_id
, ("_admin", "storage"))
3180 if storage
and storage
.get(
3182 ): # may be not present if vnfd has not artifacts
3183 # path format: /vnfdid/pkkdir/helm-charts|juju-bundles/kdumodel
3184 filename
= "{}/{}/{}s/{}".format(
3190 if self
.fs
.file_exists(
3191 filename
, mode
="file"
3192 ) or self
.fs
.file_exists(filename
, mode
="dir"):
3193 kdumodel
= self
.fs
.path
+ filename
3194 except (asyncio
.TimeoutError
, asyncio
.CancelledError
):
3196 except Exception: # it is not a file
3199 k8s_cluster_id
= kdur
["k8s-cluster"]["id"]
3200 step
= "Synchronize repos for k8s cluster '{}'".format(
3203 cluster_uuid
= await _get_cluster_id(k8s_cluster_id
, k8sclustertype
)
3207 k8sclustertype
== "helm-chart"
3208 and cluster_uuid
not in updated_cluster_list
3210 k8sclustertype
== "helm-chart-v3"
3211 and cluster_uuid
not in updated_v3_cluster_list
3213 del_repo_list
, added_repo_dict
= await asyncio
.ensure_future(
3214 self
.k8scluster_map
[k8sclustertype
].synchronize_repos(
3215 cluster_uuid
=cluster_uuid
3218 if del_repo_list
or added_repo_dict
:
3219 if k8sclustertype
== "helm-chart":
3221 "_admin.helm_charts_added." + item
: None
3222 for item
in del_repo_list
3225 "_admin.helm_charts_added." + item
: name
3226 for item
, name
in added_repo_dict
.items()
3228 updated_cluster_list
.append(cluster_uuid
)
3229 elif k8sclustertype
== "helm-chart-v3":
3231 "_admin.helm_charts_v3_added." + item
: None
3232 for item
in del_repo_list
3235 "_admin.helm_charts_v3_added." + item
: name
3236 for item
, name
in added_repo_dict
.items()
3238 updated_v3_cluster_list
.append(cluster_uuid
)
3240 logging_text
+ "repos synchronized on k8s cluster "
3241 "'{}' to_delete: {}, to_add: {}".format(
3242 k8s_cluster_id
, del_repo_list
, added_repo_dict
3247 {"_id": k8s_cluster_id
},
3253 step
= "Instantiating KDU {}.{} in k8s cluster {}".format(
3254 vnfr_data
["member-vnf-index-ref"],
3258 k8s_instance_info
= {
3259 "kdu-instance": None,
3260 "k8scluster-uuid": cluster_uuid
,
3261 "k8scluster-type": k8sclustertype
,
3262 "member-vnf-index": vnfr_data
["member-vnf-index-ref"],
3263 "kdu-name": kdur
["kdu-name"],
3264 "kdu-model": kdumodel
,
3265 "namespace": namespace
,
3266 "kdu-deployment-name": kdu_deployment_name
,
3268 db_path
= "_admin.deployed.K8s.{}".format(index
)
3269 db_nsr_update
[db_path
] = k8s_instance_info
3270 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
3271 vnfd_with_id
= find_in_list(
3272 db_vnfds
, lambda vnf
: vnf
["_id"] == vnfd_id
3274 task
= asyncio
.ensure_future(
3283 k8params
=desc_params
,
3288 self
.lcm_tasks
.register(
3292 "instantiate_KDU-{}".format(index
),
3295 task_instantiation_info
[task
] = "Deploying KDU {}".format(
3301 except (LcmException
, asyncio
.CancelledError
):
3303 except Exception as e
:
3304 msg
= "Exception {} while {}: {}".format(type(e
).__name
__, step
, e
)
3305 if isinstance(e
, (N2VCException
, DbException
)):
3306 self
.logger
.error(logging_text
+ msg
)
3308 self
.logger
.critical(logging_text
+ msg
, exc_info
=True)
3309 raise LcmException(msg
)
3312 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
3331 task_instantiation_info
,
3334 # launch instantiate_N2VC in a asyncio task and register task object
3335 # Look where information of this charm is at database <nsrs>._admin.deployed.VCA
3336 # if not found, create one entry and update database
3337 # fill db_nsr._admin.deployed.VCA.<index>
3340 logging_text
+ "_deploy_n2vc vnfd_id={}, vdu_id={}".format(vnfd_id
, vdu_id
)
3342 if "execution-environment-list" in descriptor_config
:
3343 ee_list
= descriptor_config
.get("execution-environment-list", [])
3344 elif "juju" in descriptor_config
:
3345 ee_list
= [descriptor_config
] # ns charms
3346 else: # other types as script are not supported
3349 for ee_item
in ee_list
:
3352 + "_deploy_n2vc ee_item juju={}, helm={}".format(
3353 ee_item
.get("juju"), ee_item
.get("helm-chart")
3356 ee_descriptor_id
= ee_item
.get("id")
3357 if ee_item
.get("juju"):
3358 vca_name
= ee_item
["juju"].get("charm")
3361 if ee_item
["juju"].get("charm") is not None
3364 if ee_item
["juju"].get("cloud") == "k8s":
3365 vca_type
= "k8s_proxy_charm"
3366 elif ee_item
["juju"].get("proxy") is False:
3367 vca_type
= "native_charm"
3368 elif ee_item
.get("helm-chart"):
3369 vca_name
= ee_item
["helm-chart"]
3370 if ee_item
.get("helm-version") and ee_item
.get("helm-version") == "v2":
3373 vca_type
= "helm-v3"
3376 logging_text
+ "skipping non juju neither charm configuration"
3381 for vca_index
, vca_deployed
in enumerate(
3382 db_nsr
["_admin"]["deployed"]["VCA"]
3384 if not vca_deployed
:
3387 vca_deployed
.get("member-vnf-index") == member_vnf_index
3388 and vca_deployed
.get("vdu_id") == vdu_id
3389 and vca_deployed
.get("kdu_name") == kdu_name
3390 and vca_deployed
.get("vdu_count_index", 0) == vdu_index
3391 and vca_deployed
.get("ee_descriptor_id") == ee_descriptor_id
3395 # not found, create one.
3397 "ns" if not member_vnf_index
else "vnf/{}".format(member_vnf_index
)
3400 target
+= "/vdu/{}/{}".format(vdu_id
, vdu_index
or 0)
3402 target
+= "/kdu/{}".format(kdu_name
)
3404 "target_element": target
,
3405 # ^ target_element will replace member-vnf-index, kdu_name, vdu_id ... in a single string
3406 "member-vnf-index": member_vnf_index
,
3408 "kdu_name": kdu_name
,
3409 "vdu_count_index": vdu_index
,
3410 "operational-status": "init", # TODO revise
3411 "detailed-status": "", # TODO revise
3412 "step": "initial-deploy", # TODO revise
3414 "vdu_name": vdu_name
,
3416 "ee_descriptor_id": ee_descriptor_id
,
3420 # create VCA and configurationStatus in db
3422 "_admin.deployed.VCA.{}".format(vca_index
): vca_deployed
,
3423 "configurationStatus.{}".format(vca_index
): dict(),
3425 self
.update_db_2("nsrs", nsr_id
, db_dict
)
3427 db_nsr
["_admin"]["deployed"]["VCA"].append(vca_deployed
)
3429 self
.logger
.debug("N2VC > NSR_ID > {}".format(nsr_id
))
3430 self
.logger
.debug("N2VC > DB_NSR > {}".format(db_nsr
))
3431 self
.logger
.debug("N2VC > VCA_DEPLOYED > {}".format(vca_deployed
))
3434 task_n2vc
= asyncio
.ensure_future(
3435 self
.instantiate_N2VC(
3436 logging_text
=logging_text
,
3437 vca_index
=vca_index
,
3443 vdu_index
=vdu_index
,
3444 deploy_params
=deploy_params
,
3445 config_descriptor
=descriptor_config
,
3446 base_folder
=base_folder
,
3447 nslcmop_id
=nslcmop_id
,
3451 ee_config_descriptor
=ee_item
,
3454 self
.lcm_tasks
.register(
3458 "instantiate_N2VC-{}".format(vca_index
),
3461 task_instantiation_info
[
3463 ] = self
.task_name_deploy_vca
+ " {}.{}".format(
3464 member_vnf_index
or "", vdu_id
or ""
3468 def _create_nslcmop(nsr_id
, operation
, params
):
3470 Creates a ns-lcm-opp content to be stored at database.
3471 :param nsr_id: internal id of the instance
3472 :param operation: instantiate, terminate, scale, action, ...
3473 :param params: user parameters for the operation
3474 :return: dictionary following SOL005 format
3476 # Raise exception if invalid arguments
3477 if not (nsr_id
and operation
and params
):
3479 "Parameters 'nsr_id', 'operation' and 'params' needed to create primitive not provided"
3486 # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
3487 "operationState": "PROCESSING",
3488 "statusEnteredTime": now
,
3489 "nsInstanceId": nsr_id
,
3490 "lcmOperationType": operation
,
3492 "isAutomaticInvocation": False,
3493 "operationParams": params
,
3494 "isCancelPending": False,
3496 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
3497 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
3502 def _format_additional_params(self
, params
):
3503 params
= params
or {}
3504 for key
, value
in params
.items():
3505 if str(value
).startswith("!!yaml "):
3506 params
[key
] = yaml
.safe_load(value
[7:])
3509 def _get_terminate_primitive_params(self
, seq
, vnf_index
):
3510 primitive
= seq
.get("name")
3511 primitive_params
= {}
3513 "member_vnf_index": vnf_index
,
3514 "primitive": primitive
,
3515 "primitive_params": primitive_params
,
3518 return self
._map
_primitive
_params
(seq
, params
, desc_params
)
3522 def _retry_or_skip_suboperation(self
, db_nslcmop
, op_index
):
3523 op
= deep_get(db_nslcmop
, ("_admin", "operations"), [])[op_index
]
3524 if op
.get("operationState") == "COMPLETED":
3525 # b. Skip sub-operation
3526 # _ns_execute_primitive() or RO.create_action() will NOT be executed
3527 return self
.SUBOPERATION_STATUS_SKIP
3529 # c. retry executing sub-operation
3530 # The sub-operation exists, and operationState != 'COMPLETED'
3531 # Update operationState = 'PROCESSING' to indicate a retry.
3532 operationState
= "PROCESSING"
3533 detailed_status
= "In progress"
3534 self
._update
_suboperation
_status
(
3535 db_nslcmop
, op_index
, operationState
, detailed_status
3537 # Return the sub-operation index
3538 # _ns_execute_primitive() or RO.create_action() will be called from scale()
3539 # with arguments extracted from the sub-operation
3542 # Find a sub-operation where all keys in a matching dictionary must match
3543 # Returns the index of the matching sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if no match
3544 def _find_suboperation(self
, db_nslcmop
, match
):
3545 if db_nslcmop
and match
:
3546 op_list
= db_nslcmop
.get("_admin", {}).get("operations", [])
3547 for i
, op
in enumerate(op_list
):
3548 if all(op
.get(k
) == match
[k
] for k
in match
):
3550 return self
.SUBOPERATION_STATUS_NOT_FOUND
3552 # Update status for a sub-operation given its index
3553 def _update_suboperation_status(
3554 self
, db_nslcmop
, op_index
, operationState
, detailed_status
3556 # Update DB for HA tasks
3557 q_filter
= {"_id": db_nslcmop
["_id"]}
3559 "_admin.operations.{}.operationState".format(op_index
): operationState
,
3560 "_admin.operations.{}.detailed-status".format(op_index
): detailed_status
,
3563 "nslcmops", q_filter
=q_filter
, update_dict
=update_dict
, fail_on_empty
=False
3566 # Add sub-operation, return the index of the added sub-operation
3567 # Optionally, set operationState, detailed-status, and operationType
3568 # Status and type are currently set for 'scale' sub-operations:
3569 # 'operationState' : 'PROCESSING' | 'COMPLETED' | 'FAILED'
3570 # 'detailed-status' : status message
3571 # 'operationType': may be any type, in the case of scaling: 'PRE-SCALE' | 'POST-SCALE'
3572 # Status and operation type are currently only used for 'scale', but NOT for 'terminate' sub-operations.
3573 def _add_suboperation(
3581 mapped_primitive_params
,
3582 operationState
=None,
3583 detailed_status
=None,
3586 RO_scaling_info
=None,
3589 return self
.SUBOPERATION_STATUS_NOT_FOUND
3590 # Get the "_admin.operations" list, if it exists
3591 db_nslcmop_admin
= db_nslcmop
.get("_admin", {})
3592 op_list
= db_nslcmop_admin
.get("operations")
3593 # Create or append to the "_admin.operations" list
3595 "member_vnf_index": vnf_index
,
3597 "vdu_count_index": vdu_count_index
,
3598 "primitive": primitive
,
3599 "primitive_params": mapped_primitive_params
,
3602 new_op
["operationState"] = operationState
3604 new_op
["detailed-status"] = detailed_status
3606 new_op
["lcmOperationType"] = operationType
3608 new_op
["RO_nsr_id"] = RO_nsr_id
3610 new_op
["RO_scaling_info"] = RO_scaling_info
3612 # No existing operations, create key 'operations' with current operation as first list element
3613 db_nslcmop_admin
.update({"operations": [new_op
]})
3614 op_list
= db_nslcmop_admin
.get("operations")
3616 # Existing operations, append operation to list
3617 op_list
.append(new_op
)
3619 db_nslcmop_update
= {"_admin.operations": op_list
}
3620 self
.update_db_2("nslcmops", db_nslcmop
["_id"], db_nslcmop_update
)
3621 op_index
= len(op_list
) - 1
3624 # Helper methods for scale() sub-operations
3626 # pre-scale/post-scale:
3627 # Check for 3 different cases:
3628 # a. New: First time execution, return SUBOPERATION_STATUS_NEW
3629 # b. Skip: Existing sub-operation exists, operationState == 'COMPLETED', return SUBOPERATION_STATUS_SKIP
3630 # c. retry: Existing sub-operation exists, operationState != 'COMPLETED', return op_index to re-execute
3631 def _check_or_add_scale_suboperation(
3635 vnf_config_primitive
,
3639 RO_scaling_info
=None,
3641 # Find this sub-operation
3642 if RO_nsr_id
and RO_scaling_info
:
3643 operationType
= "SCALE-RO"
3645 "member_vnf_index": vnf_index
,
3646 "RO_nsr_id": RO_nsr_id
,
3647 "RO_scaling_info": RO_scaling_info
,
3651 "member_vnf_index": vnf_index
,
3652 "primitive": vnf_config_primitive
,
3653 "primitive_params": primitive_params
,
3654 "lcmOperationType": operationType
,
3656 op_index
= self
._find
_suboperation
(db_nslcmop
, match
)
3657 if op_index
== self
.SUBOPERATION_STATUS_NOT_FOUND
:
3658 # a. New sub-operation
3659 # The sub-operation does not exist, add it.
3660 # _ns_execute_primitive() will be called from scale() as usual, with non-modified arguments
3661 # The following parameters are set to None for all kind of scaling:
3663 vdu_count_index
= None
3665 if RO_nsr_id
and RO_scaling_info
:
3666 vnf_config_primitive
= None
3667 primitive_params
= None
3670 RO_scaling_info
= None
3671 # Initial status for sub-operation
3672 operationState
= "PROCESSING"
3673 detailed_status
= "In progress"
3674 # Add sub-operation for pre/post-scaling (zero or more operations)
3675 self
._add
_suboperation
(
3681 vnf_config_primitive
,
3689 return self
.SUBOPERATION_STATUS_NEW
3691 # Return either SUBOPERATION_STATUS_SKIP (operationState == 'COMPLETED'),
3692 # or op_index (operationState != 'COMPLETED')
3693 return self
._retry
_or
_skip
_suboperation
(db_nslcmop
, op_index
)
3695 # Function to return execution_environment id
3697 def _get_ee_id(self
, vnf_index
, vdu_id
, vca_deployed_list
):
3698 # TODO vdu_index_count
3699 for vca
in vca_deployed_list
:
3700 if vca
["member-vnf-index"] == vnf_index
and vca
["vdu_id"] == vdu_id
:
3703 async def destroy_N2VC(
3711 exec_primitives
=True,
3716 Execute the terminate primitives and destroy the execution environment (if destroy_ee=False
3717 :param logging_text:
3719 :param vca_deployed: Dictionary of deployment info at db_nsr._admin.depoloyed.VCA.<INDEX>
3720 :param config_descriptor: Configuration descriptor of the NSD, VNFD, VNFD.vdu or VNFD.kdu
3721 :param vca_index: index in the database _admin.deployed.VCA
3722 :param destroy_ee: False to do not destroy, because it will be destroyed all of then at once
3723 :param exec_primitives: False to do not execute terminate primitives, because the config is not completed or has
3724 not executed properly
3725 :param scaling_in: True destroys the application, False destroys the model
3726 :return: None or exception
3731 + " vca_index: {}, vca_deployed: {}, config_descriptor: {}, destroy_ee: {}".format(
3732 vca_index
, vca_deployed
, config_descriptor
, destroy_ee
3736 vca_type
= vca_deployed
.get("type", "lxc_proxy_charm")
3738 # execute terminate_primitives
3740 terminate_primitives
= get_ee_sorted_terminate_config_primitive_list(
3741 config_descriptor
.get("terminate-config-primitive"),
3742 vca_deployed
.get("ee_descriptor_id"),
3744 vdu_id
= vca_deployed
.get("vdu_id")
3745 vdu_count_index
= vca_deployed
.get("vdu_count_index")
3746 vdu_name
= vca_deployed
.get("vdu_name")
3747 vnf_index
= vca_deployed
.get("member-vnf-index")
3748 if terminate_primitives
and vca_deployed
.get("needed_terminate"):
3749 for seq
in terminate_primitives
:
3750 # For each sequence in list, get primitive and call _ns_execute_primitive()
3751 step
= "Calling terminate action for vnf_member_index={} primitive={}".format(
3752 vnf_index
, seq
.get("name")
3754 self
.logger
.debug(logging_text
+ step
)
3755 # Create the primitive for each sequence, i.e. "primitive": "touch"
3756 primitive
= seq
.get("name")
3757 mapped_primitive_params
= self
._get
_terminate
_primitive
_params
(
3762 self
._add
_suboperation
(
3769 mapped_primitive_params
,
3771 # Sub-operations: Call _ns_execute_primitive() instead of action()
3773 result
, result_detail
= await self
._ns
_execute
_primitive
(
3774 vca_deployed
["ee_id"],
3776 mapped_primitive_params
,
3780 except LcmException
:
3781 # this happens when VCA is not deployed. In this case it is not needed to terminate
3783 result_ok
= ["COMPLETED", "PARTIALLY_COMPLETED"]
3784 if result
not in result_ok
:
3786 "terminate_primitive {} for vnf_member_index={} fails with "
3787 "error {}".format(seq
.get("name"), vnf_index
, result_detail
)
3789 # set that this VCA do not need terminated
3790 db_update_entry
= "_admin.deployed.VCA.{}.needed_terminate".format(
3794 "nsrs", db_nslcmop
["nsInstanceId"], {db_update_entry
: False}
3797 if vca_deployed
.get("prometheus_jobs") and self
.prometheus
:
3798 await self
.prometheus
.update(remove_jobs
=vca_deployed
["prometheus_jobs"])
3801 await self
.vca_map
[vca_type
].delete_execution_environment(
3802 vca_deployed
["ee_id"],
3803 scaling_in
=scaling_in
,
3808 async def _delete_all_N2VC(self
, db_nsr
: dict, vca_id
: str = None):
3809 self
._write
_all
_config
_status
(db_nsr
=db_nsr
, status
="TERMINATING")
3810 namespace
= "." + db_nsr
["_id"]
3812 await self
.n2vc
.delete_namespace(
3813 namespace
=namespace
,
3814 total_timeout
=self
.timeout_charm_delete
,
3817 except N2VCNotFound
: # already deleted. Skip
3819 self
._write
_all
_config
_status
(db_nsr
=db_nsr
, status
="DELETED")
3821 async def _terminate_RO(
3822 self
, logging_text
, nsr_deployed
, nsr_id
, nslcmop_id
, stage
3825 Terminates a deployment from RO
3826 :param logging_text:
3827 :param nsr_deployed: db_nsr._admin.deployed
3830 :param stage: list of string with the content to write on db_nslcmop.detailed-status.
3831 this method will update only the index 2, but it will write on database the concatenated content of the list
3836 ro_nsr_id
= ro_delete_action
= None
3837 if nsr_deployed
and nsr_deployed
.get("RO"):
3838 ro_nsr_id
= nsr_deployed
["RO"].get("nsr_id")
3839 ro_delete_action
= nsr_deployed
["RO"].get("nsr_delete_action_id")
3842 stage
[2] = "Deleting ns from VIM."
3843 db_nsr_update
["detailed-status"] = " ".join(stage
)
3844 self
._write
_op
_status
(nslcmop_id
, stage
)
3845 self
.logger
.debug(logging_text
+ stage
[2])
3846 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
3847 self
._write
_op
_status
(nslcmop_id
, stage
)
3848 desc
= await self
.RO
.delete("ns", ro_nsr_id
)
3849 ro_delete_action
= desc
["action_id"]
3851 "_admin.deployed.RO.nsr_delete_action_id"
3852 ] = ro_delete_action
3853 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
3854 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
3855 if ro_delete_action
:
3856 # wait until NS is deleted from VIM
3857 stage
[2] = "Waiting ns deleted from VIM."
3858 detailed_status_old
= None
3862 + " RO_id={} ro_delete_action={}".format(
3863 ro_nsr_id
, ro_delete_action
3866 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
3867 self
._write
_op
_status
(nslcmop_id
, stage
)
3869 delete_timeout
= 20 * 60 # 20 minutes
3870 while delete_timeout
> 0:
3871 desc
= await self
.RO
.show(
3873 item_id_name
=ro_nsr_id
,
3874 extra_item
="action",
3875 extra_item_id
=ro_delete_action
,
3879 self
._on
_update
_ro
_db
(nsrs_id
=nsr_id
, ro_descriptor
=desc
)
3881 ns_status
, ns_status_info
= self
.RO
.check_action_status(desc
)
3882 if ns_status
== "ERROR":
3883 raise ROclient
.ROClientException(ns_status_info
)
3884 elif ns_status
== "BUILD":
3885 stage
[2] = "Deleting from VIM {}".format(ns_status_info
)
3886 elif ns_status
== "ACTIVE":
3887 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
3888 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
3893 ), "ROclient.check_action_status returns unknown {}".format(
3896 if stage
[2] != detailed_status_old
:
3897 detailed_status_old
= stage
[2]
3898 db_nsr_update
["detailed-status"] = " ".join(stage
)
3899 self
._write
_op
_status
(nslcmop_id
, stage
)
3900 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
3901 await asyncio
.sleep(5, loop
=self
.loop
)
3903 else: # delete_timeout <= 0:
3904 raise ROclient
.ROClientException(
3905 "Timeout waiting ns deleted from VIM"
3908 except Exception as e
:
3909 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
3911 isinstance(e
, ROclient
.ROClientException
) and e
.http_code
== 404
3913 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
3914 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
3915 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
3917 logging_text
+ "RO_ns_id={} already deleted".format(ro_nsr_id
)
3920 isinstance(e
, ROclient
.ROClientException
) and e
.http_code
== 409
3922 failed_detail
.append("delete conflict: {}".format(e
))
3925 + "RO_ns_id={} delete conflict: {}".format(ro_nsr_id
, e
)
3928 failed_detail
.append("delete error: {}".format(e
))
3930 logging_text
+ "RO_ns_id={} delete error: {}".format(ro_nsr_id
, e
)
3934 if not failed_detail
and deep_get(nsr_deployed
, ("RO", "nsd_id")):
3935 ro_nsd_id
= nsr_deployed
["RO"]["nsd_id"]
3937 stage
[2] = "Deleting nsd from RO."
3938 db_nsr_update
["detailed-status"] = " ".join(stage
)
3939 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
3940 self
._write
_op
_status
(nslcmop_id
, stage
)
3941 await self
.RO
.delete("nsd", ro_nsd_id
)
3943 logging_text
+ "ro_nsd_id={} deleted".format(ro_nsd_id
)
3945 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
3946 except Exception as e
:
3948 isinstance(e
, ROclient
.ROClientException
) and e
.http_code
== 404
3950 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
3952 logging_text
+ "ro_nsd_id={} already deleted".format(ro_nsd_id
)
3955 isinstance(e
, ROclient
.ROClientException
) and e
.http_code
== 409
3957 failed_detail
.append(
3958 "ro_nsd_id={} delete conflict: {}".format(ro_nsd_id
, e
)
3960 self
.logger
.debug(logging_text
+ failed_detail
[-1])
3962 failed_detail
.append(
3963 "ro_nsd_id={} delete error: {}".format(ro_nsd_id
, e
)
3965 self
.logger
.error(logging_text
+ failed_detail
[-1])
3967 if not failed_detail
and deep_get(nsr_deployed
, ("RO", "vnfd")):
3968 for index
, vnf_deployed
in enumerate(nsr_deployed
["RO"]["vnfd"]):
3969 if not vnf_deployed
or not vnf_deployed
["id"]:
3972 ro_vnfd_id
= vnf_deployed
["id"]
3975 ] = "Deleting member_vnf_index={} ro_vnfd_id={} from RO.".format(
3976 vnf_deployed
["member-vnf-index"], ro_vnfd_id
3978 db_nsr_update
["detailed-status"] = " ".join(stage
)
3979 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
3980 self
._write
_op
_status
(nslcmop_id
, stage
)
3981 await self
.RO
.delete("vnfd", ro_vnfd_id
)
3983 logging_text
+ "ro_vnfd_id={} deleted".format(ro_vnfd_id
)
3985 db_nsr_update
["_admin.deployed.RO.vnfd.{}.id".format(index
)] = None
3986 except Exception as e
:
3988 isinstance(e
, ROclient
.ROClientException
) and e
.http_code
== 404
3991 "_admin.deployed.RO.vnfd.{}.id".format(index
)
3995 + "ro_vnfd_id={} already deleted ".format(ro_vnfd_id
)
3998 isinstance(e
, ROclient
.ROClientException
) and e
.http_code
== 409
4000 failed_detail
.append(
4001 "ro_vnfd_id={} delete conflict: {}".format(ro_vnfd_id
, e
)
4003 self
.logger
.debug(logging_text
+ failed_detail
[-1])
4005 failed_detail
.append(
4006 "ro_vnfd_id={} delete error: {}".format(ro_vnfd_id
, e
)
4008 self
.logger
.error(logging_text
+ failed_detail
[-1])
4011 stage
[2] = "Error deleting from VIM"
4013 stage
[2] = "Deleted from VIM"
4014 db_nsr_update
["detailed-status"] = " ".join(stage
)
4015 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
4016 self
._write
_op
_status
(nslcmop_id
, stage
)
4019 raise LcmException("; ".join(failed_detail
))
4021 async def terminate(self
, nsr_id
, nslcmop_id
):
4022 # Try to lock HA task here
4023 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA("ns", "nslcmops", nslcmop_id
)
4024 if not task_is_locked_by_me
:
4027 logging_text
= "Task ns={} terminate={} ".format(nsr_id
, nslcmop_id
)
4028 self
.logger
.debug(logging_text
+ "Enter")
4029 timeout_ns_terminate
= self
.timeout_ns_terminate
4032 operation_params
= None
4034 error_list
= [] # annotates all failed error messages
4035 db_nslcmop_update
= {}
4036 autoremove
= False # autoremove after terminated
4037 tasks_dict_info
= {}
4040 "Stage 1/3: Preparing task.",
4041 "Waiting for previous operations to terminate.",
4044 # ^ contains [stage, step, VIM-status]
4046 # wait for any previous tasks in process
4047 await self
.lcm_tasks
.waitfor_related_HA("ns", "nslcmops", nslcmop_id
)
4049 stage
[1] = "Getting nslcmop={} from db.".format(nslcmop_id
)
4050 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
4051 operation_params
= db_nslcmop
.get("operationParams") or {}
4052 if operation_params
.get("timeout_ns_terminate"):
4053 timeout_ns_terminate
= operation_params
["timeout_ns_terminate"]
4054 stage
[1] = "Getting nsr={} from db.".format(nsr_id
)
4055 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
4057 db_nsr_update
["operational-status"] = "terminating"
4058 db_nsr_update
["config-status"] = "terminating"
4059 self
._write
_ns
_status
(
4061 ns_state
="TERMINATING",
4062 current_operation
="TERMINATING",
4063 current_operation_id
=nslcmop_id
,
4064 other_update
=db_nsr_update
,
4066 self
._write
_op
_status
(op_id
=nslcmop_id
, queuePosition
=0, stage
=stage
)
4067 nsr_deployed
= deepcopy(db_nsr
["_admin"].get("deployed")) or {}
4068 if db_nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
4071 stage
[1] = "Getting vnf descriptors from db."
4072 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
4074 db_vnfr
["member-vnf-index-ref"]: db_vnfr
for db_vnfr
in db_vnfrs_list
4076 db_vnfds_from_id
= {}
4077 db_vnfds_from_member_index
= {}
4079 for vnfr
in db_vnfrs_list
:
4080 vnfd_id
= vnfr
["vnfd-id"]
4081 if vnfd_id
not in db_vnfds_from_id
:
4082 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
4083 db_vnfds_from_id
[vnfd_id
] = vnfd
4084 db_vnfds_from_member_index
[
4085 vnfr
["member-vnf-index-ref"]
4086 ] = db_vnfds_from_id
[vnfd_id
]
4088 # Destroy individual execution environments when there are terminating primitives.
4089 # Rest of EE will be deleted at once
4090 # TODO - check before calling _destroy_N2VC
4091 # if not operation_params.get("skip_terminate_primitives"):#
4092 # or not vca.get("needed_terminate"):
4093 stage
[0] = "Stage 2/3 execute terminating primitives."
4094 self
.logger
.debug(logging_text
+ stage
[0])
4095 stage
[1] = "Looking execution environment that needs terminate."
4096 self
.logger
.debug(logging_text
+ stage
[1])
4098 for vca_index
, vca
in enumerate(get_iterable(nsr_deployed
, "VCA")):
4099 config_descriptor
= None
4100 vca_member_vnf_index
= vca
.get("member-vnf-index")
4101 vca_id
= self
.get_vca_id(
4102 db_vnfrs_dict
.get(vca_member_vnf_index
)
4103 if vca_member_vnf_index
4107 if not vca
or not vca
.get("ee_id"):
4109 if not vca
.get("member-vnf-index"):
4111 config_descriptor
= db_nsr
.get("ns-configuration")
4112 elif vca
.get("vdu_id"):
4113 db_vnfd
= db_vnfds_from_member_index
[vca
["member-vnf-index"]]
4114 config_descriptor
= get_configuration(db_vnfd
, vca
.get("vdu_id"))
4115 elif vca
.get("kdu_name"):
4116 db_vnfd
= db_vnfds_from_member_index
[vca
["member-vnf-index"]]
4117 config_descriptor
= get_configuration(db_vnfd
, vca
.get("kdu_name"))
4119 db_vnfd
= db_vnfds_from_member_index
[vca
["member-vnf-index"]]
4120 config_descriptor
= get_configuration(db_vnfd
, db_vnfd
["id"])
4121 vca_type
= vca
.get("type")
4122 exec_terminate_primitives
= not operation_params
.get(
4123 "skip_terminate_primitives"
4124 ) and vca
.get("needed_terminate")
4125 # For helm we must destroy_ee. Also for native_charm, as juju_model cannot be deleted if there are
4126 # pending native charms
4128 True if vca_type
in ("helm", "helm-v3", "native_charm") else False
4130 # self.logger.debug(logging_text + "vca_index: {}, ee_id: {}, vca_type: {} destroy_ee: {}".format(
4131 # vca_index, vca.get("ee_id"), vca_type, destroy_ee))
4132 task
= asyncio
.ensure_future(
4140 exec_terminate_primitives
,
4144 tasks_dict_info
[task
] = "Terminating VCA {}".format(vca
.get("ee_id"))
4146 # wait for pending tasks of terminate primitives
4150 + "Waiting for tasks {}".format(list(tasks_dict_info
.keys()))
4152 error_list
= await self
._wait
_for
_tasks
(
4155 min(self
.timeout_charm_delete
, timeout_ns_terminate
),
4159 tasks_dict_info
.clear()
4161 return # raise LcmException("; ".join(error_list))
4163 # remove All execution environments at once
4164 stage
[0] = "Stage 3/3 delete all."
4166 if nsr_deployed
.get("VCA"):
4167 stage
[1] = "Deleting all execution environments."
4168 self
.logger
.debug(logging_text
+ stage
[1])
4169 vca_id
= self
.get_vca_id({}, db_nsr
)
4170 task_delete_ee
= asyncio
.ensure_future(
4172 self
._delete
_all
_N
2VC
(db_nsr
=db_nsr
, vca_id
=vca_id
),
4173 timeout
=self
.timeout_charm_delete
,
4176 # task_delete_ee = asyncio.ensure_future(self.n2vc.delete_namespace(namespace="." + nsr_id))
4177 tasks_dict_info
[task_delete_ee
] = "Terminating all VCA"
4179 # Delete from k8scluster
4180 stage
[1] = "Deleting KDUs."
4181 self
.logger
.debug(logging_text
+ stage
[1])
4182 # print(nsr_deployed)
4183 for kdu
in get_iterable(nsr_deployed
, "K8s"):
4184 if not kdu
or not kdu
.get("kdu-instance"):
4186 kdu_instance
= kdu
.get("kdu-instance")
4187 if kdu
.get("k8scluster-type") in self
.k8scluster_map
:
4188 # TODO: Uninstall kdu instances taking into account they could be deployed in different VIMs
4189 vca_id
= self
.get_vca_id({}, db_nsr
)
4190 task_delete_kdu_instance
= asyncio
.ensure_future(
4191 self
.k8scluster_map
[kdu
["k8scluster-type"]].uninstall(
4192 cluster_uuid
=kdu
.get("k8scluster-uuid"),
4193 kdu_instance
=kdu_instance
,
4200 + "Unknown k8s deployment type {}".format(
4201 kdu
.get("k8scluster-type")
4206 task_delete_kdu_instance
4207 ] = "Terminating KDU '{}'".format(kdu
.get("kdu-name"))
4210 stage
[1] = "Deleting ns from VIM."
4212 task_delete_ro
= asyncio
.ensure_future(
4213 self
._terminate
_ng
_ro
(
4214 logging_text
, nsr_deployed
, nsr_id
, nslcmop_id
, stage
4218 task_delete_ro
= asyncio
.ensure_future(
4220 logging_text
, nsr_deployed
, nsr_id
, nslcmop_id
, stage
4223 tasks_dict_info
[task_delete_ro
] = "Removing deployment from VIM"
4225 # rest of staff will be done at finally
4228 ROclient
.ROClientException
,
4233 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
4235 except asyncio
.CancelledError
:
4237 logging_text
+ "Cancelled Exception while '{}'".format(stage
[1])
4239 exc
= "Operation was cancelled"
4240 except Exception as e
:
4241 exc
= traceback
.format_exc()
4242 self
.logger
.critical(
4243 logging_text
+ "Exit Exception while '{}': {}".format(stage
[1], e
),
4248 error_list
.append(str(exc
))
4250 # wait for pending tasks
4252 stage
[1] = "Waiting for terminate pending tasks."
4253 self
.logger
.debug(logging_text
+ stage
[1])
4254 error_list
+= await self
._wait
_for
_tasks
(
4257 timeout_ns_terminate
,
4261 stage
[1] = stage
[2] = ""
4262 except asyncio
.CancelledError
:
4263 error_list
.append("Cancelled")
4264 # TODO cancell all tasks
4265 except Exception as exc
:
4266 error_list
.append(str(exc
))
4267 # update status at database
4269 error_detail
= "; ".join(error_list
)
4270 # self.logger.error(logging_text + error_detail)
4271 error_description_nslcmop
= "{} Detail: {}".format(
4272 stage
[0], error_detail
4274 error_description_nsr
= "Operation: TERMINATING.{}, {}.".format(
4275 nslcmop_id
, stage
[0]
4278 db_nsr_update
["operational-status"] = "failed"
4279 db_nsr_update
["detailed-status"] = (
4280 error_description_nsr
+ " Detail: " + error_detail
4282 db_nslcmop_update
["detailed-status"] = error_detail
4283 nslcmop_operation_state
= "FAILED"
4287 error_description_nsr
= error_description_nslcmop
= None
4288 ns_state
= "NOT_INSTANTIATED"
4289 db_nsr_update
["operational-status"] = "terminated"
4290 db_nsr_update
["detailed-status"] = "Done"
4291 db_nsr_update
["_admin.nsState"] = "NOT_INSTANTIATED"
4292 db_nslcmop_update
["detailed-status"] = "Done"
4293 nslcmop_operation_state
= "COMPLETED"
4296 self
._write
_ns
_status
(
4299 current_operation
="IDLE",
4300 current_operation_id
=None,
4301 error_description
=error_description_nsr
,
4302 error_detail
=error_detail
,
4303 other_update
=db_nsr_update
,
4305 self
._write
_op
_status
(
4308 error_message
=error_description_nslcmop
,
4309 operation_state
=nslcmop_operation_state
,
4310 other_update
=db_nslcmop_update
,
4312 if ns_state
== "NOT_INSTANTIATED":
4316 {"nsr-id-ref": nsr_id
},
4317 {"_admin.nsState": "NOT_INSTANTIATED"},
4319 except DbException
as e
:
4322 + "Error writing VNFR status for nsr-id-ref: {} -> {}".format(
4326 if operation_params
:
4327 autoremove
= operation_params
.get("autoremove", False)
4328 if nslcmop_operation_state
:
4330 await self
.msg
.aiowrite(
4335 "nslcmop_id": nslcmop_id
,
4336 "operationState": nslcmop_operation_state
,
4337 "autoremove": autoremove
,
4341 except Exception as e
:
4343 logging_text
+ "kafka_write notification Exception {}".format(e
)
4346 self
.logger
.debug(logging_text
+ "Exit")
4347 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_terminate")
4349 async def _wait_for_tasks(
4350 self
, logging_text
, created_tasks_info
, timeout
, stage
, nslcmop_id
, nsr_id
=None
4353 error_detail_list
= []
4355 pending_tasks
= list(created_tasks_info
.keys())
4356 num_tasks
= len(pending_tasks
)
4358 stage
[1] = "{}/{}.".format(num_done
, num_tasks
)
4359 self
._write
_op
_status
(nslcmop_id
, stage
)
4360 while pending_tasks
:
4362 _timeout
= timeout
+ time_start
- time()
4363 done
, pending_tasks
= await asyncio
.wait(
4364 pending_tasks
, timeout
=_timeout
, return_when
=asyncio
.FIRST_COMPLETED
4366 num_done
+= len(done
)
4367 if not done
: # Timeout
4368 for task
in pending_tasks
:
4369 new_error
= created_tasks_info
[task
] + ": Timeout"
4370 error_detail_list
.append(new_error
)
4371 error_list
.append(new_error
)
4374 if task
.cancelled():
4377 exc
= task
.exception()
4379 if isinstance(exc
, asyncio
.TimeoutError
):
4381 new_error
= created_tasks_info
[task
] + ": {}".format(exc
)
4382 error_list
.append(created_tasks_info
[task
])
4383 error_detail_list
.append(new_error
)
4390 ROclient
.ROClientException
,
4396 self
.logger
.error(logging_text
+ new_error
)
4398 exc_traceback
= "".join(
4399 traceback
.format_exception(None, exc
, exc
.__traceback
__)
4403 + created_tasks_info
[task
]
4409 logging_text
+ created_tasks_info
[task
] + ": Done"
4411 stage
[1] = "{}/{}.".format(num_done
, num_tasks
)
4413 stage
[1] += " Errors: " + ". ".join(error_detail_list
) + "."
4414 if nsr_id
: # update also nsr
4419 "errorDescription": "Error at: " + ", ".join(error_list
),
4420 "errorDetail": ". ".join(error_detail_list
),
4423 self
._write
_op
_status
(nslcmop_id
, stage
)
4424 return error_detail_list
4427 def _map_primitive_params(primitive_desc
, params
, instantiation_params
):
4429 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
4430 The default-value is used. If it is between < > it look for a value at instantiation_params
4431 :param primitive_desc: portion of VNFD/NSD that describes primitive
4432 :param params: Params provided by user
4433 :param instantiation_params: Instantiation params provided by user
4434 :return: a dictionary with the calculated params
4436 calculated_params
= {}
4437 for parameter
in primitive_desc
.get("parameter", ()):
4438 param_name
= parameter
["name"]
4439 if param_name
in params
:
4440 calculated_params
[param_name
] = params
[param_name
]
4441 elif "default-value" in parameter
or "value" in parameter
:
4442 if "value" in parameter
:
4443 calculated_params
[param_name
] = parameter
["value"]
4445 calculated_params
[param_name
] = parameter
["default-value"]
4447 isinstance(calculated_params
[param_name
], str)
4448 and calculated_params
[param_name
].startswith("<")
4449 and calculated_params
[param_name
].endswith(">")
4451 if calculated_params
[param_name
][1:-1] in instantiation_params
:
4452 calculated_params
[param_name
] = instantiation_params
[
4453 calculated_params
[param_name
][1:-1]
4457 "Parameter {} needed to execute primitive {} not provided".format(
4458 calculated_params
[param_name
], primitive_desc
["name"]
4463 "Parameter {} needed to execute primitive {} not provided".format(
4464 param_name
, primitive_desc
["name"]
4468 if isinstance(calculated_params
[param_name
], (dict, list, tuple)):
4469 calculated_params
[param_name
] = yaml
.safe_dump(
4470 calculated_params
[param_name
], default_flow_style
=True, width
=256
4472 elif isinstance(calculated_params
[param_name
], str) and calculated_params
[
4474 ].startswith("!!yaml "):
4475 calculated_params
[param_name
] = calculated_params
[param_name
][7:]
4476 if parameter
.get("data-type") == "INTEGER":
4478 calculated_params
[param_name
] = int(calculated_params
[param_name
])
4479 except ValueError: # error converting string to int
4481 "Parameter {} of primitive {} must be integer".format(
4482 param_name
, primitive_desc
["name"]
4485 elif parameter
.get("data-type") == "BOOLEAN":
4486 calculated_params
[param_name
] = not (
4487 (str(calculated_params
[param_name
])).lower() == "false"
4490 # add always ns_config_info if primitive name is config
4491 if primitive_desc
["name"] == "config":
4492 if "ns_config_info" in instantiation_params
:
4493 calculated_params
["ns_config_info"] = instantiation_params
[
4496 return calculated_params
4498 def _look_for_deployed_vca(
4505 ee_descriptor_id
=None,
4507 # find vca_deployed record for this action. Raise LcmException if not found or there is not any id.
4508 for vca
in deployed_vca
:
4511 if member_vnf_index
!= vca
["member-vnf-index"] or vdu_id
!= vca
["vdu_id"]:
4514 vdu_count_index
is not None
4515 and vdu_count_index
!= vca
["vdu_count_index"]
4518 if kdu_name
and kdu_name
!= vca
["kdu_name"]:
4520 if ee_descriptor_id
and ee_descriptor_id
!= vca
["ee_descriptor_id"]:
4524 # vca_deployed not found
4526 "charm for member_vnf_index={} vdu_id={}.{} kdu_name={} execution-environment-list.id={}"
4527 " is not deployed".format(
4536 ee_id
= vca
.get("ee_id")
4538 "type", "lxc_proxy_charm"
4539 ) # default value for backward compatibility - proxy charm
4542 "charm for member_vnf_index={} vdu_id={} kdu_name={} vdu_count_index={} has not "
4543 "execution environment".format(
4544 member_vnf_index
, vdu_id
, kdu_name
, vdu_count_index
4547 return ee_id
, vca_type
4549 async def _ns_execute_primitive(
4555 retries_interval
=30,
4562 if primitive
== "config":
4563 primitive_params
= {"params": primitive_params
}
4565 vca_type
= vca_type
or "lxc_proxy_charm"
4569 output
= await asyncio
.wait_for(
4570 self
.vca_map
[vca_type
].exec_primitive(
4572 primitive_name
=primitive
,
4573 params_dict
=primitive_params
,
4574 progress_timeout
=self
.timeout_progress_primitive
,
4575 total_timeout
=self
.timeout_primitive
,
4580 timeout
=timeout
or self
.timeout_primitive
,
4584 except asyncio
.CancelledError
:
4586 except Exception as e
: # asyncio.TimeoutError
4587 if isinstance(e
, asyncio
.TimeoutError
):
4592 "Error executing action {} on {} -> {}".format(
4597 await asyncio
.sleep(retries_interval
, loop
=self
.loop
)
4599 return "FAILED", str(e
)
4601 return "COMPLETED", output
4603 except (LcmException
, asyncio
.CancelledError
):
4605 except Exception as e
:
4606 return "FAIL", "Error executing action {}: {}".format(primitive
, e
)
4608 async def vca_status_refresh(self
, nsr_id
, nslcmop_id
):
4610 Updating the vca_status with latest juju information in nsrs record
4611 :param: nsr_id: Id of the nsr
4612 :param: nslcmop_id: Id of the nslcmop
4616 self
.logger
.debug("Task ns={} action={} Enter".format(nsr_id
, nslcmop_id
))
4617 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
4618 vca_id
= self
.get_vca_id({}, db_nsr
)
4619 if db_nsr
["_admin"]["deployed"]["K8s"]:
4620 for k8s_index
, k8s
in enumerate(db_nsr
["_admin"]["deployed"]["K8s"]):
4621 cluster_uuid
, kdu_instance
= k8s
["k8scluster-uuid"], k8s
["kdu-instance"]
4622 await self
._on
_update
_k
8s
_db
(
4623 cluster_uuid
, kdu_instance
, filter={"_id": nsr_id
}, vca_id
=vca_id
4626 for vca_index
, _
in enumerate(db_nsr
["_admin"]["deployed"]["VCA"]):
4627 table
, filter = "nsrs", {"_id": nsr_id
}
4628 path
= "_admin.deployed.VCA.{}.".format(vca_index
)
4629 await self
._on
_update
_n
2vc
_db
(table
, filter, path
, {})
4631 self
.logger
.debug("Task ns={} action={} Exit".format(nsr_id
, nslcmop_id
))
4632 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_vca_status_refresh")
4634 async def action(self
, nsr_id
, nslcmop_id
):
4635 # Try to lock HA task here
4636 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA("ns", "nslcmops", nslcmop_id
)
4637 if not task_is_locked_by_me
:
4640 logging_text
= "Task ns={} action={} ".format(nsr_id
, nslcmop_id
)
4641 self
.logger
.debug(logging_text
+ "Enter")
4642 # get all needed from database
4646 db_nslcmop_update
= {}
4647 nslcmop_operation_state
= None
4648 error_description_nslcmop
= None
4651 # wait for any previous tasks in process
4652 step
= "Waiting for previous operations to terminate"
4653 await self
.lcm_tasks
.waitfor_related_HA("ns", "nslcmops", nslcmop_id
)
4655 self
._write
_ns
_status
(
4658 current_operation
="RUNNING ACTION",
4659 current_operation_id
=nslcmop_id
,
4662 step
= "Getting information from database"
4663 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
4664 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
4665 if db_nslcmop
["operationParams"].get("primitive_params"):
4666 db_nslcmop
["operationParams"]["primitive_params"] = json
.loads(
4667 db_nslcmop
["operationParams"]["primitive_params"]
4670 nsr_deployed
= db_nsr
["_admin"].get("deployed")
4671 vnf_index
= db_nslcmop
["operationParams"].get("member_vnf_index")
4672 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
4673 kdu_name
= db_nslcmop
["operationParams"].get("kdu_name")
4674 vdu_count_index
= db_nslcmop
["operationParams"].get("vdu_count_index")
4675 primitive
= db_nslcmop
["operationParams"]["primitive"]
4676 primitive_params
= db_nslcmop
["operationParams"]["primitive_params"]
4677 timeout_ns_action
= db_nslcmop
["operationParams"].get(
4678 "timeout_ns_action", self
.timeout_primitive
4682 step
= "Getting vnfr from database"
4683 db_vnfr
= self
.db
.get_one(
4684 "vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
}
4686 if db_vnfr
.get("kdur"):
4688 for kdur
in db_vnfr
["kdur"]:
4689 if kdur
.get("additionalParams"):
4690 kdur
["additionalParams"] = json
.loads(kdur
["additionalParams"])
4691 kdur_list
.append(kdur
)
4692 db_vnfr
["kdur"] = kdur_list
4693 step
= "Getting vnfd from database"
4694 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
4696 step
= "Getting nsd from database"
4697 db_nsd
= self
.db
.get_one("nsds", {"_id": db_nsr
["nsd-id"]})
4699 vca_id
= self
.get_vca_id(db_vnfr
, db_nsr
)
4700 # for backward compatibility
4701 if nsr_deployed
and isinstance(nsr_deployed
.get("VCA"), dict):
4702 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
4703 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
4704 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
4706 # look for primitive
4707 config_primitive_desc
= descriptor_configuration
= None
4709 descriptor_configuration
= get_configuration(db_vnfd
, vdu_id
)
4711 descriptor_configuration
= get_configuration(db_vnfd
, kdu_name
)
4713 descriptor_configuration
= get_configuration(db_vnfd
, db_vnfd
["id"])
4715 descriptor_configuration
= db_nsd
.get("ns-configuration")
4717 if descriptor_configuration
and descriptor_configuration
.get(
4720 for config_primitive
in descriptor_configuration
["config-primitive"]:
4721 if config_primitive
["name"] == primitive
:
4722 config_primitive_desc
= config_primitive
4725 if not config_primitive_desc
:
4726 if not (kdu_name
and primitive
in ("upgrade", "rollback", "status")):
4728 "Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".format(
4732 primitive_name
= primitive
4733 ee_descriptor_id
= None
4735 primitive_name
= config_primitive_desc
.get(
4736 "execution-environment-primitive", primitive
4738 ee_descriptor_id
= config_primitive_desc
.get(
4739 "execution-environment-ref"
4745 (x
for x
in db_vnfr
["vdur"] if x
["vdu-id-ref"] == vdu_id
), None
4747 desc_params
= parse_yaml_strings(vdur
.get("additionalParams"))
4750 (x
for x
in db_vnfr
["kdur"] if x
["kdu-name"] == kdu_name
), None
4752 desc_params
= parse_yaml_strings(kdur
.get("additionalParams"))
4754 desc_params
= parse_yaml_strings(
4755 db_vnfr
.get("additionalParamsForVnf")
4758 desc_params
= parse_yaml_strings(db_nsr
.get("additionalParamsForNs"))
4759 if kdu_name
and get_configuration(db_vnfd
, kdu_name
):
4760 kdu_configuration
= get_configuration(db_vnfd
, kdu_name
)
4762 for primitive
in kdu_configuration
.get("initial-config-primitive", []):
4763 actions
.add(primitive
["name"])
4764 for primitive
in kdu_configuration
.get("config-primitive", []):
4765 actions
.add(primitive
["name"])
4766 kdu_action
= True if primitive_name
in actions
else False
4768 # TODO check if ns is in a proper status
4770 primitive_name
in ("upgrade", "rollback", "status") or kdu_action
4772 # kdur and desc_params already set from before
4773 if primitive_params
:
4774 desc_params
.update(primitive_params
)
4775 # TODO Check if we will need something at vnf level
4776 for index
, kdu
in enumerate(get_iterable(nsr_deployed
, "K8s")):
4778 kdu_name
== kdu
["kdu-name"]
4779 and kdu
["member-vnf-index"] == vnf_index
4784 "KDU '{}' for vnf '{}' not deployed".format(kdu_name
, vnf_index
)
4787 if kdu
.get("k8scluster-type") not in self
.k8scluster_map
:
4788 msg
= "unknown k8scluster-type '{}'".format(
4789 kdu
.get("k8scluster-type")
4791 raise LcmException(msg
)
4794 "collection": "nsrs",
4795 "filter": {"_id": nsr_id
},
4796 "path": "_admin.deployed.K8s.{}".format(index
),
4800 + "Exec k8s {} on {}.{}".format(primitive_name
, vnf_index
, kdu_name
)
4802 step
= "Executing kdu {}".format(primitive_name
)
4803 if primitive_name
== "upgrade":
4804 if desc_params
.get("kdu_model"):
4805 kdu_model
= desc_params
.get("kdu_model")
4806 del desc_params
["kdu_model"]
4808 kdu_model
= kdu
.get("kdu-model")
4809 parts
= kdu_model
.split(sep
=":")
4811 kdu_model
= parts
[0]
4813 detailed_status
= await asyncio
.wait_for(
4814 self
.k8scluster_map
[kdu
["k8scluster-type"]].upgrade(
4815 cluster_uuid
=kdu
.get("k8scluster-uuid"),
4816 kdu_instance
=kdu
.get("kdu-instance"),
4818 kdu_model
=kdu_model
,
4821 timeout
=timeout_ns_action
,
4823 timeout
=timeout_ns_action
+ 10,
4826 logging_text
+ " Upgrade of kdu {} done".format(detailed_status
)
4828 elif primitive_name
== "rollback":
4829 detailed_status
= await asyncio
.wait_for(
4830 self
.k8scluster_map
[kdu
["k8scluster-type"]].rollback(
4831 cluster_uuid
=kdu
.get("k8scluster-uuid"),
4832 kdu_instance
=kdu
.get("kdu-instance"),
4835 timeout
=timeout_ns_action
,
4837 elif primitive_name
== "status":
4838 detailed_status
= await asyncio
.wait_for(
4839 self
.k8scluster_map
[kdu
["k8scluster-type"]].status_kdu(
4840 cluster_uuid
=kdu
.get("k8scluster-uuid"),
4841 kdu_instance
=kdu
.get("kdu-instance"),
4844 timeout
=timeout_ns_action
,
4847 kdu_instance
= kdu
.get("kdu-instance") or "{}-{}".format(
4848 kdu
["kdu-name"], nsr_id
4850 params
= self
._map
_primitive
_params
(
4851 config_primitive_desc
, primitive_params
, desc_params
4854 detailed_status
= await asyncio
.wait_for(
4855 self
.k8scluster_map
[kdu
["k8scluster-type"]].exec_primitive(
4856 cluster_uuid
=kdu
.get("k8scluster-uuid"),
4857 kdu_instance
=kdu_instance
,
4858 primitive_name
=primitive_name
,
4861 timeout
=timeout_ns_action
,
4864 timeout
=timeout_ns_action
,
4868 nslcmop_operation_state
= "COMPLETED"
4870 detailed_status
= ""
4871 nslcmop_operation_state
= "FAILED"
4873 ee_id
, vca_type
= self
._look
_for
_deployed
_vca
(
4874 nsr_deployed
["VCA"],
4875 member_vnf_index
=vnf_index
,
4877 vdu_count_index
=vdu_count_index
,
4878 ee_descriptor_id
=ee_descriptor_id
,
4880 for vca_index
, vca_deployed
in enumerate(
4881 db_nsr
["_admin"]["deployed"]["VCA"]
4883 if vca_deployed
.get("member-vnf-index") == vnf_index
:
4885 "collection": "nsrs",
4886 "filter": {"_id": nsr_id
},
4887 "path": "_admin.deployed.VCA.{}.".format(vca_index
),
4891 nslcmop_operation_state
,
4893 ) = await self
._ns
_execute
_primitive
(
4895 primitive
=primitive_name
,
4896 primitive_params
=self
._map
_primitive
_params
(
4897 config_primitive_desc
, primitive_params
, desc_params
4899 timeout
=timeout_ns_action
,
4905 db_nslcmop_update
["detailed-status"] = detailed_status
4906 error_description_nslcmop
= (
4907 detailed_status
if nslcmop_operation_state
== "FAILED" else ""
4911 + " task Done with result {} {}".format(
4912 nslcmop_operation_state
, detailed_status
4915 return # database update is called inside finally
4917 except (DbException
, LcmException
, N2VCException
, K8sException
) as e
:
4918 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
4920 except asyncio
.CancelledError
:
4922 logging_text
+ "Cancelled Exception while '{}'".format(step
)
4924 exc
= "Operation was cancelled"
4925 except asyncio
.TimeoutError
:
4926 self
.logger
.error(logging_text
+ "Timeout while '{}'".format(step
))
4928 except Exception as e
:
4929 exc
= traceback
.format_exc()
4930 self
.logger
.critical(
4931 logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
),
4940 ) = error_description_nslcmop
= "FAILED {}: {}".format(step
, exc
)
4941 nslcmop_operation_state
= "FAILED"
4943 self
._write
_ns
_status
(
4947 ], # TODO check if degraded. For the moment use previous status
4948 current_operation
="IDLE",
4949 current_operation_id
=None,
4950 # error_description=error_description_nsr,
4951 # error_detail=error_detail,
4952 other_update
=db_nsr_update
,
4955 self
._write
_op
_status
(
4958 error_message
=error_description_nslcmop
,
4959 operation_state
=nslcmop_operation_state
,
4960 other_update
=db_nslcmop_update
,
4963 if nslcmop_operation_state
:
4965 await self
.msg
.aiowrite(
4970 "nslcmop_id": nslcmop_id
,
4971 "operationState": nslcmop_operation_state
,
4975 except Exception as e
:
4977 logging_text
+ "kafka_write notification Exception {}".format(e
)
4979 self
.logger
.debug(logging_text
+ "Exit")
4980 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_action")
4981 return nslcmop_operation_state
, detailed_status
4983 async def scale(self
, nsr_id
, nslcmop_id
):
4984 # Try to lock HA task here
4985 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA("ns", "nslcmops", nslcmop_id
)
4986 if not task_is_locked_by_me
:
4989 logging_text
= "Task ns={} scale={} ".format(nsr_id
, nslcmop_id
)
4990 stage
= ["", "", ""]
4991 tasks_dict_info
= {}
4992 # ^ stage, step, VIM progress
4993 self
.logger
.debug(logging_text
+ "Enter")
4994 # get all needed from database
4996 db_nslcmop_update
= {}
4999 # in case of error, indicates what part of scale was failed to put nsr at error status
5000 scale_process
= None
5001 old_operational_status
= ""
5002 old_config_status
= ""
5005 # wait for any previous tasks in process
5006 step
= "Waiting for previous operations to terminate"
5007 await self
.lcm_tasks
.waitfor_related_HA("ns", "nslcmops", nslcmop_id
)
5008 self
._write
_ns
_status
(
5011 current_operation
="SCALING",
5012 current_operation_id
=nslcmop_id
,
5015 step
= "Getting nslcmop from database"
5017 step
+ " after having waited for previous tasks to be completed"
5019 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
5021 step
= "Getting nsr from database"
5022 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
5023 old_operational_status
= db_nsr
["operational-status"]
5024 old_config_status
= db_nsr
["config-status"]
5026 step
= "Parsing scaling parameters"
5027 db_nsr_update
["operational-status"] = "scaling"
5028 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
5029 nsr_deployed
= db_nsr
["_admin"].get("deployed")
5031 vnf_index
= db_nslcmop
["operationParams"]["scaleVnfData"][
5033 ]["member-vnf-index"]
5034 scaling_group
= db_nslcmop
["operationParams"]["scaleVnfData"][
5036 ]["scaling-group-descriptor"]
5037 scaling_type
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleVnfType"]
5038 # for backward compatibility
5039 if nsr_deployed
and isinstance(nsr_deployed
.get("VCA"), dict):
5040 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
5041 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
5042 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
5044 step
= "Getting vnfr from database"
5045 db_vnfr
= self
.db
.get_one(
5046 "vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
}
5049 vca_id
= self
.get_vca_id(db_vnfr
, db_nsr
)
5051 step
= "Getting vnfd from database"
5052 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
5054 base_folder
= db_vnfd
["_admin"]["storage"]
5056 step
= "Getting scaling-group-descriptor"
5057 scaling_descriptor
= find_in_list(
5058 get_scaling_aspect(db_vnfd
),
5059 lambda scale_desc
: scale_desc
["name"] == scaling_group
,
5061 if not scaling_descriptor
:
5063 "input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
5064 "at vnfd:scaling-group-descriptor".format(scaling_group
)
5067 step
= "Sending scale order to VIM"
5068 # TODO check if ns is in a proper status
5070 if not db_nsr
["_admin"].get("scaling-group"):
5075 "_admin.scaling-group": [
5076 {"name": scaling_group
, "nb-scale-op": 0}
5080 admin_scale_index
= 0
5082 for admin_scale_index
, admin_scale_info
in enumerate(
5083 db_nsr
["_admin"]["scaling-group"]
5085 if admin_scale_info
["name"] == scaling_group
:
5086 nb_scale_op
= admin_scale_info
.get("nb-scale-op", 0)
5088 else: # not found, set index one plus last element and add new entry with the name
5089 admin_scale_index
+= 1
5091 "_admin.scaling-group.{}.name".format(admin_scale_index
)
5094 vca_scaling_info
= []
5095 scaling_info
= {"scaling_group_name": scaling_group
, "vdu": [], "kdu": []}
5096 if scaling_type
== "SCALE_OUT":
5097 if "aspect-delta-details" not in scaling_descriptor
:
5099 "Aspect delta details not fount in scaling descriptor {}".format(
5100 scaling_descriptor
["name"]
5103 # count if max-instance-count is reached
5104 deltas
= scaling_descriptor
.get("aspect-delta-details")["deltas"]
5106 scaling_info
["scaling_direction"] = "OUT"
5107 scaling_info
["vdu-create"] = {}
5108 scaling_info
["kdu-create"] = {}
5109 for delta
in deltas
:
5110 for vdu_delta
in delta
.get("vdu-delta", {}):
5111 vdud
= get_vdu(db_vnfd
, vdu_delta
["id"])
5112 # vdu_index also provides the number of instance of the targeted vdu
5113 vdu_count
= vdu_index
= get_vdur_index(db_vnfr
, vdu_delta
)
5114 cloud_init_text
= self
._get
_vdu
_cloud
_init
_content
(
5118 additional_params
= (
5119 self
._get
_vdu
_additional
_params
(db_vnfr
, vdud
["id"])
5122 cloud_init_list
= []
5124 vdu_profile
= get_vdu_profile(db_vnfd
, vdu_delta
["id"])
5125 max_instance_count
= 10
5126 if vdu_profile
and "max-number-of-instances" in vdu_profile
:
5127 max_instance_count
= vdu_profile
.get(
5128 "max-number-of-instances", 10
5131 default_instance_num
= get_number_of_instances(
5134 instances_number
= vdu_delta
.get("number-of-instances", 1)
5135 nb_scale_op
+= instances_number
5137 new_instance_count
= nb_scale_op
+ default_instance_num
5138 # Control if new count is over max and vdu count is less than max.
5139 # Then assign new instance count
5140 if new_instance_count
> max_instance_count
> vdu_count
:
5141 instances_number
= new_instance_count
- max_instance_count
5143 instances_number
= instances_number
5145 if new_instance_count
> max_instance_count
:
5147 "reached the limit of {} (max-instance-count) "
5148 "scaling-out operations for the "
5149 "scaling-group-descriptor '{}'".format(
5150 nb_scale_op
, scaling_group
5153 for x
in range(vdu_delta
.get("number-of-instances", 1)):
5155 # TODO Information of its own ip is not available because db_vnfr is not updated.
5156 additional_params
["OSM"] = get_osm_params(
5157 db_vnfr
, vdu_delta
["id"], vdu_index
+ x
5159 cloud_init_list
.append(
5160 self
._parse
_cloud
_init
(
5167 vca_scaling_info
.append(
5169 "osm_vdu_id": vdu_delta
["id"],
5170 "member-vnf-index": vnf_index
,
5172 "vdu_index": vdu_index
+ x
,
5175 scaling_info
["vdu-create"][vdu_delta
["id"]] = instances_number
5176 for kdu_delta
in delta
.get("kdu-resource-delta", {}):
5177 kdu_profile
= get_kdu_profile(db_vnfd
, kdu_delta
["id"])
5178 kdu_name
= kdu_profile
["kdu-name"]
5179 resource_name
= kdu_profile
["resource-name"]
5181 # Might have different kdus in the same delta
5182 # Should have list for each kdu
5183 if not scaling_info
["kdu-create"].get(kdu_name
, None):
5184 scaling_info
["kdu-create"][kdu_name
] = []
5186 kdur
= get_kdur(db_vnfr
, kdu_name
)
5187 if kdur
.get("helm-chart"):
5188 k8s_cluster_type
= "helm-chart-v3"
5189 self
.logger
.debug("kdur: {}".format(kdur
))
5191 kdur
.get("helm-version")
5192 and kdur
.get("helm-version") == "v2"
5194 k8s_cluster_type
= "helm-chart"
5195 raise NotImplementedError
5196 elif kdur
.get("juju-bundle"):
5197 k8s_cluster_type
= "juju-bundle"
5200 "kdu type for kdu='{}.{}' is neither helm-chart nor "
5201 "juju-bundle. Maybe an old NBI version is running".format(
5202 db_vnfr
["member-vnf-index-ref"], kdu_name
5206 max_instance_count
= 10
5207 if kdu_profile
and "max-number-of-instances" in kdu_profile
:
5208 max_instance_count
= kdu_profile
.get(
5209 "max-number-of-instances", 10
5212 nb_scale_op
+= kdu_delta
.get("number-of-instances", 1)
5213 deployed_kdu
, _
= get_deployed_kdu(
5214 nsr_deployed
, kdu_name
, vnf_index
5216 if deployed_kdu
is None:
5218 "KDU '{}' for vnf '{}' not deployed".format(
5222 kdu_instance
= deployed_kdu
.get("kdu-instance")
5223 instance_num
= await self
.k8scluster_map
[
5225 ].get_scale_count(resource_name
, kdu_instance
, vca_id
=vca_id
)
5226 kdu_replica_count
= instance_num
+ kdu_delta
.get(
5227 "number-of-instances", 1
5230 # Control if new count is over max and instance_num is less than max.
5231 # Then assign max instance number to kdu replica count
5232 if kdu_replica_count
> max_instance_count
> instance_num
:
5233 kdu_replica_count
= max_instance_count
5234 if kdu_replica_count
> max_instance_count
:
5236 "reached the limit of {} (max-instance-count) "
5237 "scaling-out operations for the "
5238 "scaling-group-descriptor '{}'".format(
5239 instance_num
, scaling_group
5243 for x
in range(kdu_delta
.get("number-of-instances", 1)):
5244 vca_scaling_info
.append(
5246 "osm_kdu_id": kdu_name
,
5247 "member-vnf-index": vnf_index
,
5249 "kdu_index": instance_num
+ x
- 1,
5252 scaling_info
["kdu-create"][kdu_name
].append(
5254 "member-vnf-index": vnf_index
,
5256 "k8s-cluster-type": k8s_cluster_type
,
5257 "resource-name": resource_name
,
5258 "scale": kdu_replica_count
,
5261 elif scaling_type
== "SCALE_IN":
5262 deltas
= scaling_descriptor
.get("aspect-delta-details")["deltas"]
5264 scaling_info
["scaling_direction"] = "IN"
5265 scaling_info
["vdu-delete"] = {}
5266 scaling_info
["kdu-delete"] = {}
5268 for delta
in deltas
:
5269 for vdu_delta
in delta
.get("vdu-delta", {}):
5270 vdu_count
= vdu_index
= get_vdur_index(db_vnfr
, vdu_delta
)
5271 min_instance_count
= 0
5272 vdu_profile
= get_vdu_profile(db_vnfd
, vdu_delta
["id"])
5273 if vdu_profile
and "min-number-of-instances" in vdu_profile
:
5274 min_instance_count
= vdu_profile
["min-number-of-instances"]
5276 default_instance_num
= get_number_of_instances(
5277 db_vnfd
, vdu_delta
["id"]
5279 instance_num
= vdu_delta
.get("number-of-instances", 1)
5280 nb_scale_op
-= instance_num
5282 new_instance_count
= nb_scale_op
+ default_instance_num
5284 if new_instance_count
< min_instance_count
< vdu_count
:
5285 instances_number
= min_instance_count
- new_instance_count
5287 instances_number
= instance_num
5289 if new_instance_count
< min_instance_count
:
5291 "reached the limit of {} (min-instance-count) scaling-in operations for the "
5292 "scaling-group-descriptor '{}'".format(
5293 nb_scale_op
, scaling_group
5296 for x
in range(vdu_delta
.get("number-of-instances", 1)):
5297 vca_scaling_info
.append(
5299 "osm_vdu_id": vdu_delta
["id"],
5300 "member-vnf-index": vnf_index
,
5302 "vdu_index": vdu_index
- 1 - x
,
5305 scaling_info
["vdu-delete"][vdu_delta
["id"]] = instances_number
5306 for kdu_delta
in delta
.get("kdu-resource-delta", {}):
5307 kdu_profile
= get_kdu_profile(db_vnfd
, kdu_delta
["id"])
5308 kdu_name
= kdu_profile
["kdu-name"]
5309 resource_name
= kdu_profile
["resource-name"]
5311 if not scaling_info
["kdu-delete"].get(kdu_name
, None):
5312 scaling_info
["kdu-delete"][kdu_name
] = []
5314 kdur
= get_kdur(db_vnfr
, kdu_name
)
5315 if kdur
.get("helm-chart"):
5316 k8s_cluster_type
= "helm-chart-v3"
5317 self
.logger
.debug("kdur: {}".format(kdur
))
5319 kdur
.get("helm-version")
5320 and kdur
.get("helm-version") == "v2"
5322 k8s_cluster_type
= "helm-chart"
5323 raise NotImplementedError
5324 elif kdur
.get("juju-bundle"):
5325 k8s_cluster_type
= "juju-bundle"
5328 "kdu type for kdu='{}.{}' is neither helm-chart nor "
5329 "juju-bundle. Maybe an old NBI version is running".format(
5330 db_vnfr
["member-vnf-index-ref"], kdur
["kdu-name"]
5334 min_instance_count
= 0
5335 if kdu_profile
and "min-number-of-instances" in kdu_profile
:
5336 min_instance_count
= kdu_profile
["min-number-of-instances"]
5338 nb_scale_op
-= kdu_delta
.get("number-of-instances", 1)
5339 deployed_kdu
, _
= get_deployed_kdu(
5340 nsr_deployed
, kdu_name
, vnf_index
5342 if deployed_kdu
is None:
5344 "KDU '{}' for vnf '{}' not deployed".format(
5348 kdu_instance
= deployed_kdu
.get("kdu-instance")
5349 instance_num
= await self
.k8scluster_map
[
5351 ].get_scale_count(resource_name
, kdu_instance
, vca_id
=vca_id
)
5352 kdu_replica_count
= instance_num
- kdu_delta
.get(
5353 "number-of-instances", 1
5356 if kdu_replica_count
< min_instance_count
< instance_num
:
5357 kdu_replica_count
= min_instance_count
5358 if kdu_replica_count
< min_instance_count
:
5360 "reached the limit of {} (min-instance-count) scaling-in operations for the "
5361 "scaling-group-descriptor '{}'".format(
5362 instance_num
, scaling_group
5366 for x
in range(kdu_delta
.get("number-of-instances", 1)):
5367 vca_scaling_info
.append(
5369 "osm_kdu_id": kdu_name
,
5370 "member-vnf-index": vnf_index
,
5372 "kdu_index": instance_num
- x
- 1,
5375 scaling_info
["kdu-delete"][kdu_name
].append(
5377 "member-vnf-index": vnf_index
,
5379 "k8s-cluster-type": k8s_cluster_type
,
5380 "resource-name": resource_name
,
5381 "scale": kdu_replica_count
,
5385 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
5386 vdu_delete
= copy(scaling_info
.get("vdu-delete"))
5387 if scaling_info
["scaling_direction"] == "IN":
5388 for vdur
in reversed(db_vnfr
["vdur"]):
5389 if vdu_delete
.get(vdur
["vdu-id-ref"]):
5390 vdu_delete
[vdur
["vdu-id-ref"]] -= 1
5391 scaling_info
["vdu"].append(
5393 "name": vdur
.get("name") or vdur
.get("vdu-name"),
5394 "vdu_id": vdur
["vdu-id-ref"],
5398 for interface
in vdur
["interfaces"]:
5399 scaling_info
["vdu"][-1]["interface"].append(
5401 "name": interface
["name"],
5402 "ip_address": interface
["ip-address"],
5403 "mac_address": interface
.get("mac-address"),
5406 # vdu_delete = vdu_scaling_info.pop("vdu-delete")
5409 step
= "Executing pre-scale vnf-config-primitive"
5410 if scaling_descriptor
.get("scaling-config-action"):
5411 for scaling_config_action
in scaling_descriptor
[
5412 "scaling-config-action"
5415 scaling_config_action
.get("trigger") == "pre-scale-in"
5416 and scaling_type
== "SCALE_IN"
5418 scaling_config_action
.get("trigger") == "pre-scale-out"
5419 and scaling_type
== "SCALE_OUT"
5421 vnf_config_primitive
= scaling_config_action
[
5422 "vnf-config-primitive-name-ref"
5424 step
= db_nslcmop_update
[
5426 ] = "executing pre-scale scaling-config-action '{}'".format(
5427 vnf_config_primitive
5430 # look for primitive
5431 for config_primitive
in (
5432 get_configuration(db_vnfd
, db_vnfd
["id"]) or {}
5433 ).get("config-primitive", ()):
5434 if config_primitive
["name"] == vnf_config_primitive
:
5438 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
5439 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
5440 "primitive".format(scaling_group
, vnf_config_primitive
)
5443 vnfr_params
= {"VDU_SCALE_INFO": scaling_info
}
5444 if db_vnfr
.get("additionalParamsForVnf"):
5445 vnfr_params
.update(db_vnfr
["additionalParamsForVnf"])
5447 scale_process
= "VCA"
5448 db_nsr_update
["config-status"] = "configuring pre-scaling"
5449 primitive_params
= self
._map
_primitive
_params
(
5450 config_primitive
, {}, vnfr_params
5453 # Pre-scale retry check: Check if this sub-operation has been executed before
5454 op_index
= self
._check
_or
_add
_scale
_suboperation
(
5457 vnf_config_primitive
,
5461 if op_index
== self
.SUBOPERATION_STATUS_SKIP
:
5462 # Skip sub-operation
5463 result
= "COMPLETED"
5464 result_detail
= "Done"
5467 + "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
5468 vnf_config_primitive
, result
, result_detail
5472 if op_index
== self
.SUBOPERATION_STATUS_NEW
:
5473 # New sub-operation: Get index of this sub-operation
5475 len(db_nslcmop
.get("_admin", {}).get("operations"))
5480 + "vnf_config_primitive={} New sub-operation".format(
5481 vnf_config_primitive
5485 # retry: Get registered params for this existing sub-operation
5486 op
= db_nslcmop
.get("_admin", {}).get("operations", [])[
5489 vnf_index
= op
.get("member_vnf_index")
5490 vnf_config_primitive
= op
.get("primitive")
5491 primitive_params
= op
.get("primitive_params")
5494 + "vnf_config_primitive={} Sub-operation retry".format(
5495 vnf_config_primitive
5498 # Execute the primitive, either with new (first-time) or registered (reintent) args
5499 ee_descriptor_id
= config_primitive
.get(
5500 "execution-environment-ref"
5502 primitive_name
= config_primitive
.get(
5503 "execution-environment-primitive", vnf_config_primitive
5505 ee_id
, vca_type
= self
._look
_for
_deployed
_vca
(
5506 nsr_deployed
["VCA"],
5507 member_vnf_index
=vnf_index
,
5509 vdu_count_index
=None,
5510 ee_descriptor_id
=ee_descriptor_id
,
5512 result
, result_detail
= await self
._ns
_execute
_primitive
(
5521 + "vnf_config_primitive={} Done with result {} {}".format(
5522 vnf_config_primitive
, result
, result_detail
5525 # Update operationState = COMPLETED | FAILED
5526 self
._update
_suboperation
_status
(
5527 db_nslcmop
, op_index
, result
, result_detail
5530 if result
== "FAILED":
5531 raise LcmException(result_detail
)
5532 db_nsr_update
["config-status"] = old_config_status
5533 scale_process
= None
5537 "_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index
)
5540 "_admin.scaling-group.{}.time".format(admin_scale_index
)
5543 # SCALE-IN VCA - BEGIN
5544 if vca_scaling_info
:
5545 step
= db_nslcmop_update
[
5547 ] = "Deleting the execution environments"
5548 scale_process
= "VCA"
5549 for vca_info
in vca_scaling_info
:
5550 if vca_info
["type"] == "delete":
5551 member_vnf_index
= str(vca_info
["member-vnf-index"])
5553 logging_text
+ "vdu info: {}".format(vca_info
)
5555 if vca_info
.get("osm_vdu_id"):
5556 vdu_id
= vca_info
["osm_vdu_id"]
5557 vdu_index
= int(vca_info
["vdu_index"])
5560 ] = "Scaling member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
5561 member_vnf_index
, vdu_id
, vdu_index
5565 kdu_id
= vca_info
["osm_kdu_id"]
5568 ] = "Scaling member_vnf_index={}, kdu_id={}, vdu_index={} ".format(
5569 member_vnf_index
, kdu_id
, vdu_index
5571 stage
[2] = step
= "Scaling in VCA"
5572 self
._write
_op
_status
(op_id
=nslcmop_id
, stage
=stage
)
5573 vca_update
= db_nsr
["_admin"]["deployed"]["VCA"]
5574 config_update
= db_nsr
["configurationStatus"]
5575 for vca_index
, vca
in enumerate(vca_update
):
5577 (vca
or vca
.get("ee_id"))
5578 and vca
["member-vnf-index"] == member_vnf_index
5579 and vca
["vdu_count_index"] == vdu_index
5581 if vca
.get("vdu_id"):
5582 config_descriptor
= get_configuration(
5583 db_vnfd
, vca
.get("vdu_id")
5585 elif vca
.get("kdu_name"):
5586 config_descriptor
= get_configuration(
5587 db_vnfd
, vca
.get("kdu_name")
5590 config_descriptor
= get_configuration(
5591 db_vnfd
, db_vnfd
["id"]
5593 operation_params
= (
5594 db_nslcmop
.get("operationParams") or {}
5596 exec_terminate_primitives
= not operation_params
.get(
5597 "skip_terminate_primitives"
5598 ) and vca
.get("needed_terminate")
5599 task
= asyncio
.ensure_future(
5608 exec_primitives
=exec_terminate_primitives
,
5612 timeout
=self
.timeout_charm_delete
,
5615 tasks_dict_info
[task
] = "Terminating VCA {}".format(
5618 del vca_update
[vca_index
]
5619 del config_update
[vca_index
]
5620 # wait for pending tasks of terminate primitives
5624 + "Waiting for tasks {}".format(
5625 list(tasks_dict_info
.keys())
5628 error_list
= await self
._wait
_for
_tasks
(
5632 self
.timeout_charm_delete
, self
.timeout_ns_terminate
5637 tasks_dict_info
.clear()
5639 raise LcmException("; ".join(error_list
))
5641 db_vca_and_config_update
= {
5642 "_admin.deployed.VCA": vca_update
,
5643 "configurationStatus": config_update
,
5646 "nsrs", db_nsr
["_id"], db_vca_and_config_update
5648 scale_process
= None
5649 # SCALE-IN VCA - END
5652 if scaling_info
.get("vdu-create") or scaling_info
.get("vdu-delete"):
5653 scale_process
= "RO"
5654 if self
.ro_config
.get("ng"):
5655 await self
._scale
_ng
_ro
(
5656 logging_text
, db_nsr
, db_nslcmop
, db_vnfr
, scaling_info
, stage
5658 scaling_info
.pop("vdu-create", None)
5659 scaling_info
.pop("vdu-delete", None)
5661 scale_process
= None
5665 if scaling_info
.get("kdu-create") or scaling_info
.get("kdu-delete"):
5666 scale_process
= "KDU"
5667 await self
._scale
_kdu
(
5668 logging_text
, nsr_id
, nsr_deployed
, db_vnfd
, vca_id
, scaling_info
5670 scaling_info
.pop("kdu-create", None)
5671 scaling_info
.pop("kdu-delete", None)
5673 scale_process
= None
5677 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
5679 # SCALE-UP VCA - BEGIN
5680 if vca_scaling_info
:
5681 step
= db_nslcmop_update
[
5683 ] = "Creating new execution environments"
5684 scale_process
= "VCA"
5685 for vca_info
in vca_scaling_info
:
5686 if vca_info
["type"] == "create":
5687 member_vnf_index
= str(vca_info
["member-vnf-index"])
5689 logging_text
+ "vdu info: {}".format(vca_info
)
5691 vnfd_id
= db_vnfr
["vnfd-ref"]
5692 if vca_info
.get("osm_vdu_id"):
5693 vdu_index
= int(vca_info
["vdu_index"])
5694 deploy_params
= {"OSM": get_osm_params(db_vnfr
)}
5695 if db_vnfr
.get("additionalParamsForVnf"):
5696 deploy_params
.update(
5698 db_vnfr
["additionalParamsForVnf"].copy()
5701 descriptor_config
= get_configuration(
5702 db_vnfd
, db_vnfd
["id"]
5704 if descriptor_config
:
5709 logging_text
=logging_text
5710 + "member_vnf_index={} ".format(member_vnf_index
),
5713 nslcmop_id
=nslcmop_id
,
5719 member_vnf_index
=member_vnf_index
,
5720 vdu_index
=vdu_index
,
5722 deploy_params
=deploy_params
,
5723 descriptor_config
=descriptor_config
,
5724 base_folder
=base_folder
,
5725 task_instantiation_info
=tasks_dict_info
,
5728 vdu_id
= vca_info
["osm_vdu_id"]
5729 vdur
= find_in_list(
5730 db_vnfr
["vdur"], lambda vdu
: vdu
["vdu-id-ref"] == vdu_id
5732 descriptor_config
= get_configuration(db_vnfd
, vdu_id
)
5733 if vdur
.get("additionalParams"):
5734 deploy_params_vdu
= parse_yaml_strings(
5735 vdur
["additionalParams"]
5738 deploy_params_vdu
= deploy_params
5739 deploy_params_vdu
["OSM"] = get_osm_params(
5740 db_vnfr
, vdu_id
, vdu_count_index
=vdu_index
5742 if descriptor_config
:
5747 ] = "Scaling member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
5748 member_vnf_index
, vdu_id
, vdu_index
5750 stage
[2] = step
= "Scaling out VCA"
5751 self
._write
_op
_status
(op_id
=nslcmop_id
, stage
=stage
)
5753 logging_text
=logging_text
5754 + "member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
5755 member_vnf_index
, vdu_id
, vdu_index
5759 nslcmop_id
=nslcmop_id
,
5765 member_vnf_index
=member_vnf_index
,
5766 vdu_index
=vdu_index
,
5768 deploy_params
=deploy_params_vdu
,
5769 descriptor_config
=descriptor_config
,
5770 base_folder
=base_folder
,
5771 task_instantiation_info
=tasks_dict_info
,
5775 kdu_name
= vca_info
["osm_kdu_id"]
5776 descriptor_config
= get_configuration(db_vnfd
, kdu_name
)
5777 if descriptor_config
:
5779 kdu_index
= int(vca_info
["kdu_index"])
5783 for x
in db_vnfr
["kdur"]
5784 if x
["kdu-name"] == kdu_name
5786 deploy_params_kdu
= {"OSM": get_osm_params(db_vnfr
)}
5787 if kdur
.get("additionalParams"):
5788 deploy_params_kdu
= parse_yaml_strings(
5789 kdur
["additionalParams"]
5793 logging_text
=logging_text
,
5796 nslcmop_id
=nslcmop_id
,
5802 member_vnf_index
=member_vnf_index
,
5803 vdu_index
=kdu_index
,
5805 deploy_params
=deploy_params_kdu
,
5806 descriptor_config
=descriptor_config
,
5807 base_folder
=base_folder
,
5808 task_instantiation_info
=tasks_dict_info
,
5811 # SCALE-UP VCA - END
5812 scale_process
= None
5815 # execute primitive service POST-SCALING
5816 step
= "Executing post-scale vnf-config-primitive"
5817 if scaling_descriptor
.get("scaling-config-action"):
5818 for scaling_config_action
in scaling_descriptor
[
5819 "scaling-config-action"
5822 scaling_config_action
.get("trigger") == "post-scale-in"
5823 and scaling_type
== "SCALE_IN"
5825 scaling_config_action
.get("trigger") == "post-scale-out"
5826 and scaling_type
== "SCALE_OUT"
5828 vnf_config_primitive
= scaling_config_action
[
5829 "vnf-config-primitive-name-ref"
5831 step
= db_nslcmop_update
[
5833 ] = "executing post-scale scaling-config-action '{}'".format(
5834 vnf_config_primitive
5837 vnfr_params
= {"VDU_SCALE_INFO": scaling_info
}
5838 if db_vnfr
.get("additionalParamsForVnf"):
5839 vnfr_params
.update(db_vnfr
["additionalParamsForVnf"])
5841 # look for primitive
5842 for config_primitive
in (
5843 get_configuration(db_vnfd
, db_vnfd
["id"]) or {}
5844 ).get("config-primitive", ()):
5845 if config_primitive
["name"] == vnf_config_primitive
:
5849 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-"
5850 "action[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:"
5851 "config-primitive".format(
5852 scaling_group
, vnf_config_primitive
5855 scale_process
= "VCA"
5856 db_nsr_update
["config-status"] = "configuring post-scaling"
5857 primitive_params
= self
._map
_primitive
_params
(
5858 config_primitive
, {}, vnfr_params
5861 # Post-scale retry check: Check if this sub-operation has been executed before
5862 op_index
= self
._check
_or
_add
_scale
_suboperation
(
5865 vnf_config_primitive
,
5869 if op_index
== self
.SUBOPERATION_STATUS_SKIP
:
5870 # Skip sub-operation
5871 result
= "COMPLETED"
5872 result_detail
= "Done"
5875 + "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
5876 vnf_config_primitive
, result
, result_detail
5880 if op_index
== self
.SUBOPERATION_STATUS_NEW
:
5881 # New sub-operation: Get index of this sub-operation
5883 len(db_nslcmop
.get("_admin", {}).get("operations"))
5888 + "vnf_config_primitive={} New sub-operation".format(
5889 vnf_config_primitive
5893 # retry: Get registered params for this existing sub-operation
5894 op
= db_nslcmop
.get("_admin", {}).get("operations", [])[
5897 vnf_index
= op
.get("member_vnf_index")
5898 vnf_config_primitive
= op
.get("primitive")
5899 primitive_params
= op
.get("primitive_params")
5902 + "vnf_config_primitive={} Sub-operation retry".format(
5903 vnf_config_primitive
5906 # Execute the primitive, either with new (first-time) or registered (reintent) args
5907 ee_descriptor_id
= config_primitive
.get(
5908 "execution-environment-ref"
5910 primitive_name
= config_primitive
.get(
5911 "execution-environment-primitive", vnf_config_primitive
5913 ee_id
, vca_type
= self
._look
_for
_deployed
_vca
(
5914 nsr_deployed
["VCA"],
5915 member_vnf_index
=vnf_index
,
5917 vdu_count_index
=None,
5918 ee_descriptor_id
=ee_descriptor_id
,
5920 result
, result_detail
= await self
._ns
_execute
_primitive
(
5929 + "vnf_config_primitive={} Done with result {} {}".format(
5930 vnf_config_primitive
, result
, result_detail
5933 # Update operationState = COMPLETED | FAILED
5934 self
._update
_suboperation
_status
(
5935 db_nslcmop
, op_index
, result
, result_detail
5938 if result
== "FAILED":
5939 raise LcmException(result_detail
)
5940 db_nsr_update
["config-status"] = old_config_status
5941 scale_process
= None
5946 ] = "" # "scaled {} {}".format(scaling_group, scaling_type)
5947 db_nsr_update
["operational-status"] = (
5949 if old_operational_status
== "failed"
5950 else old_operational_status
5952 db_nsr_update
["config-status"] = old_config_status
5955 ROclient
.ROClientException
,
5960 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
5962 except asyncio
.CancelledError
:
5964 logging_text
+ "Cancelled Exception while '{}'".format(step
)
5966 exc
= "Operation was cancelled"
5967 except Exception as e
:
5968 exc
= traceback
.format_exc()
5969 self
.logger
.critical(
5970 logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
),
5974 self
._write
_ns
_status
(
5977 current_operation
="IDLE",
5978 current_operation_id
=None,
5981 stage
[1] = "Waiting for instantiate pending tasks."
5982 self
.logger
.debug(logging_text
+ stage
[1])
5983 exc
= await self
._wait
_for
_tasks
(
5986 self
.timeout_ns_deploy
,
5994 ] = error_description_nslcmop
= "FAILED {}: {}".format(step
, exc
)
5995 nslcmop_operation_state
= "FAILED"
5997 db_nsr_update
["operational-status"] = old_operational_status
5998 db_nsr_update
["config-status"] = old_config_status
5999 db_nsr_update
["detailed-status"] = ""
6001 if "VCA" in scale_process
:
6002 db_nsr_update
["config-status"] = "failed"
6003 if "RO" in scale_process
:
6004 db_nsr_update
["operational-status"] = "failed"
6007 ] = "FAILED scaling nslcmop={} {}: {}".format(
6008 nslcmop_id
, step
, exc
6011 error_description_nslcmop
= None
6012 nslcmop_operation_state
= "COMPLETED"
6013 db_nslcmop_update
["detailed-status"] = "Done"
6015 self
._write
_op
_status
(
6018 error_message
=error_description_nslcmop
,
6019 operation_state
=nslcmop_operation_state
,
6020 other_update
=db_nslcmop_update
,
6023 self
._write
_ns
_status
(
6026 current_operation
="IDLE",
6027 current_operation_id
=None,
6028 other_update
=db_nsr_update
,
6031 if nslcmop_operation_state
:
6035 "nslcmop_id": nslcmop_id
,
6036 "operationState": nslcmop_operation_state
,
6038 await self
.msg
.aiowrite("ns", "scaled", msg
, loop
=self
.loop
)
6039 except Exception as e
:
6041 logging_text
+ "kafka_write notification Exception {}".format(e
)
6043 self
.logger
.debug(logging_text
+ "Exit")
6044 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_scale")
6046 async def _scale_kdu(
6047 self
, logging_text
, nsr_id
, nsr_deployed
, db_vnfd
, vca_id
, scaling_info
6049 _scaling_info
= scaling_info
.get("kdu-create") or scaling_info
.get("kdu-delete")
6050 for kdu_name
in _scaling_info
:
6051 for kdu_scaling_info
in _scaling_info
[kdu_name
]:
6052 deployed_kdu
, index
= get_deployed_kdu(
6053 nsr_deployed
, kdu_name
, kdu_scaling_info
["member-vnf-index"]
6055 cluster_uuid
= deployed_kdu
["k8scluster-uuid"]
6056 kdu_instance
= deployed_kdu
["kdu-instance"]
6057 scale
= int(kdu_scaling_info
["scale"])
6058 k8s_cluster_type
= kdu_scaling_info
["k8s-cluster-type"]
6061 "collection": "nsrs",
6062 "filter": {"_id": nsr_id
},
6063 "path": "_admin.deployed.K8s.{}".format(index
),
6066 step
= "scaling application {}".format(
6067 kdu_scaling_info
["resource-name"]
6069 self
.logger
.debug(logging_text
+ step
)
6071 if kdu_scaling_info
["type"] == "delete":
6072 kdu_config
= get_configuration(db_vnfd
, kdu_name
)
6075 and kdu_config
.get("terminate-config-primitive")
6076 and get_juju_ee_ref(db_vnfd
, kdu_name
) is None
6078 terminate_config_primitive_list
= kdu_config
.get(
6079 "terminate-config-primitive"
6081 terminate_config_primitive_list
.sort(
6082 key
=lambda val
: int(val
["seq"])
6086 terminate_config_primitive
6087 ) in terminate_config_primitive_list
:
6088 primitive_params_
= self
._map
_primitive
_params
(
6089 terminate_config_primitive
, {}, {}
6091 step
= "execute terminate config primitive"
6092 self
.logger
.debug(logging_text
+ step
)
6093 await asyncio
.wait_for(
6094 self
.k8scluster_map
[k8s_cluster_type
].exec_primitive(
6095 cluster_uuid
=cluster_uuid
,
6096 kdu_instance
=kdu_instance
,
6097 primitive_name
=terminate_config_primitive
["name"],
6098 params
=primitive_params_
,
6105 await asyncio
.wait_for(
6106 self
.k8scluster_map
[k8s_cluster_type
].scale(
6109 kdu_scaling_info
["resource-name"],
6112 timeout
=self
.timeout_vca_on_error
,
6115 if kdu_scaling_info
["type"] == "create":
6116 kdu_config
= get_configuration(db_vnfd
, kdu_name
)
6119 and kdu_config
.get("initial-config-primitive")
6120 and get_juju_ee_ref(db_vnfd
, kdu_name
) is None
6122 initial_config_primitive_list
= kdu_config
.get(
6123 "initial-config-primitive"
6125 initial_config_primitive_list
.sort(
6126 key
=lambda val
: int(val
["seq"])
6129 for initial_config_primitive
in initial_config_primitive_list
:
6130 primitive_params_
= self
._map
_primitive
_params
(
6131 initial_config_primitive
, {}, {}
6133 step
= "execute initial config primitive"
6134 self
.logger
.debug(logging_text
+ step
)
6135 await asyncio
.wait_for(
6136 self
.k8scluster_map
[k8s_cluster_type
].exec_primitive(
6137 cluster_uuid
=cluster_uuid
,
6138 kdu_instance
=kdu_instance
,
6139 primitive_name
=initial_config_primitive
["name"],
6140 params
=primitive_params_
,
6147 async def _scale_ng_ro(
6148 self
, logging_text
, db_nsr
, db_nslcmop
, db_vnfr
, vdu_scaling_info
, stage
6150 nsr_id
= db_nslcmop
["nsInstanceId"]
6151 db_nsd
= self
.db
.get_one("nsds", {"_id": db_nsr
["nsd-id"]})
6154 # read from db: vnfd's for every vnf
6157 # for each vnf in ns, read vnfd
6158 for vnfr
in self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
}):
6159 db_vnfrs
[vnfr
["member-vnf-index-ref"]] = vnfr
6160 vnfd_id
= vnfr
["vnfd-id"] # vnfd uuid for this vnf
6161 # if we haven't this vnfd, read it from db
6162 if not find_in_list(db_vnfds
, lambda a_vnfd
: a_vnfd
["id"] == vnfd_id
):
6164 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
6165 db_vnfds
.append(vnfd
)
6166 n2vc_key
= self
.n2vc
.get_public_key()
6167 n2vc_key_list
= [n2vc_key
]
6170 vdu_scaling_info
.get("vdu-create"),
6171 vdu_scaling_info
.get("vdu-delete"),
6174 # db_vnfr has been updated, update db_vnfrs to use it
6175 db_vnfrs
[db_vnfr
["member-vnf-index-ref"]] = db_vnfr
6176 await self
._instantiate
_ng
_ro
(
6186 start_deploy
=time(),
6187 timeout_ns_deploy
=self
.timeout_ns_deploy
,
6189 if vdu_scaling_info
.get("vdu-delete"):
6191 db_vnfr
, None, vdu_scaling_info
["vdu-delete"], mark_delete
=False
6194 async def add_prometheus_metrics(
6195 self
, ee_id
, artifact_path
, ee_config_descriptor
, vnfr_id
, nsr_id
, target_ip
6197 if not self
.prometheus
:
6199 # look if exist a file called 'prometheus*.j2' and
6200 artifact_content
= self
.fs
.dir_ls(artifact_path
)
6204 for f
in artifact_content
6205 if f
.startswith("prometheus") and f
.endswith(".j2")
6211 with self
.fs
.file_open((artifact_path
, job_file
), "r") as f
:
6215 _
, _
, service
= ee_id
.partition(".") # remove prefix "namespace."
6216 host_name
= "{}-{}".format(service
, ee_config_descriptor
["metric-service"])
6218 vnfr_id
= vnfr_id
.replace("-", "")
6220 "JOB_NAME": vnfr_id
,
6221 "TARGET_IP": target_ip
,
6222 "EXPORTER_POD_IP": host_name
,
6223 "EXPORTER_POD_PORT": host_port
,
6225 job_list
= self
.prometheus
.parse_job(job_data
, variables
)
6226 # ensure job_name is using the vnfr_id. Adding the metadata nsr_id
6227 for job
in job_list
:
6229 not isinstance(job
.get("job_name"), str)
6230 or vnfr_id
not in job
["job_name"]
6232 job
["job_name"] = vnfr_id
+ "_" + str(randint(1, 10000))
6233 job
["nsr_id"] = nsr_id
6234 job_dict
= {jl
["job_name"]: jl
for jl
in job_list
}
6235 if await self
.prometheus
.update(job_dict
):
6236 return list(job_dict
.keys())
6238 def get_vca_cloud_and_credentials(self
, vim_account_id
: str) -> (str, str):
6240 Get VCA Cloud and VCA Cloud Credentials for the VIM account
6242 :param: vim_account_id: VIM Account ID
6244 :return: (cloud_name, cloud_credential)
6246 config
= VimAccountDB
.get_vim_account_with_id(vim_account_id
).get("config", {})
6247 return config
.get("vca_cloud"), config
.get("vca_cloud_credential")
6249 def get_vca_k8s_cloud_and_credentials(self
, vim_account_id
: str) -> (str, str):
6251 Get VCA K8s Cloud and VCA K8s Cloud Credentials for the VIM account
6253 :param: vim_account_id: VIM Account ID
6255 :return: (cloud_name, cloud_credential)
6257 config
= VimAccountDB
.get_vim_account_with_id(vim_account_id
).get("config", {})
6258 return config
.get("vca_k8s_cloud"), config
.get("vca_k8s_cloud_credential")