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
25 from jinja2
import Environment
, Template
, meta
, TemplateError
, TemplateNotFound
, TemplateSyntaxError
27 from osm_lcm
import ROclient
28 from osm_lcm
.ng_ro
import NgRoClient
, NgRoException
29 from osm_lcm
.lcm_utils
import LcmException
, LcmExceptionNoMgmtIP
, LcmBase
, deep_get
, get_iterable
, populate_dict
30 from n2vc
.k8s_helm_conn
import K8sHelmConnector
31 from n2vc
.k8s_juju_conn
import K8sJujuConnector
33 from osm_common
.dbbase
import DbException
34 from osm_common
.fsbase
import FsException
36 from n2vc
.n2vc_juju_conn
import N2VCJujuConnector
37 from n2vc
.exceptions
import N2VCException
, N2VCNotFound
, K8sException
39 from copy
import copy
, deepcopy
40 from http
import HTTPStatus
42 from uuid
import uuid4
43 from functools
import partial
45 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
49 timeout_vca_on_error
= 5 * 60 # Time for charm from first time at blocked,error status to mark as failed
50 timeout_ns_deploy
= 2 * 3600 # default global timeout for deployment a ns
51 timeout_ns_terminate
= 1800 # default global timeout for un deployment a ns
52 timeout_charm_delete
= 10 * 60
53 timeout_primitive
= 30 * 60 # timeout for primitive execution
54 timeout_progress_primitive
= 10 * 60 # timeout for some progress in a primitive execution
56 SUBOPERATION_STATUS_NOT_FOUND
= -1
57 SUBOPERATION_STATUS_NEW
= -2
58 SUBOPERATION_STATUS_SKIP
= -3
59 task_name_deploy_vca
= "Deploying VCA"
61 def __init__(self
, db
, msg
, fs
, lcm_tasks
, config
, loop
):
63 Init, Connect to database, filesystem storage, and messaging
64 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
71 logger
=logging
.getLogger('lcm.ns')
75 self
.lcm_tasks
= lcm_tasks
76 self
.timeout
= config
["timeout"]
77 self
.ro_config
= config
["ro_config"]
78 self
.ng_ro
= config
["ro_config"].get("ng")
79 self
.vca_config
= config
["VCA"].copy()
81 # create N2VC connector
82 self
.n2vc
= N2VCJujuConnector(
87 url
='{}:{}'.format(self
.vca_config
['host'], self
.vca_config
['port']),
88 username
=self
.vca_config
.get('user', None),
89 vca_config
=self
.vca_config
,
90 on_update_db
=self
._on
_update
_n
2vc
_db
93 self
.k8sclusterhelm
= K8sHelmConnector(
94 kubectl_command
=self
.vca_config
.get("kubectlpath"),
95 helm_command
=self
.vca_config
.get("helmpath"),
102 self
.k8sclusterjuju
= K8sJujuConnector(
103 kubectl_command
=self
.vca_config
.get("kubectlpath"),
104 juju_command
=self
.vca_config
.get("jujupath"),
111 self
.k8scluster_map
= {
112 "helm-chart": self
.k8sclusterhelm
,
113 "chart": self
.k8sclusterhelm
,
114 "juju-bundle": self
.k8sclusterjuju
,
115 "juju": self
.k8sclusterjuju
,
119 self
.RO
= NgRoClient(self
.loop
, **self
.ro_config
)
121 self
.RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
123 def _on_update_ro_db(self
, nsrs_id
, ro_descriptor
):
125 # self.logger.debug('_on_update_ro_db(nsrs_id={}'.format(nsrs_id))
128 # TODO filter RO descriptor fields...
132 # db_dict['deploymentStatus'] = yaml.dump(ro_descriptor, default_flow_style=False, indent=2)
133 db_dict
['deploymentStatus'] = ro_descriptor
134 self
.update_db_2("nsrs", nsrs_id
, db_dict
)
136 except Exception as e
:
137 self
.logger
.warn('Cannot write database RO deployment for ns={} -> {}'.format(nsrs_id
, e
))
139 async def _on_update_n2vc_db(self
, table
, filter, path
, updated_data
):
141 # remove last dot from path (if exists)
142 if path
.endswith('.'):
145 # self.logger.debug('_on_update_n2vc_db(table={}, filter={}, path={}, updated_data={}'
146 # .format(table, filter, path, updated_data))
150 nsr_id
= filter.get('_id')
152 # read ns record from database
153 nsr
= self
.db
.get_one(table
='nsrs', q_filter
=filter)
154 current_ns_status
= nsr
.get('nsState')
156 # get vca status for NS
157 status_dict
= await self
.n2vc
.get_status(namespace
='.' + nsr_id
, yaml_format
=False)
161 db_dict
['vcaStatus'] = status_dict
163 # update configurationStatus for this VCA
165 vca_index
= int(path
[path
.rfind(".")+1:])
167 vca_list
= deep_get(target_dict
=nsr
, key_list
=('_admin', 'deployed', 'VCA'))
168 vca_status
= vca_list
[vca_index
].get('status')
170 configuration_status_list
= nsr
.get('configurationStatus')
171 config_status
= configuration_status_list
[vca_index
].get('status')
173 if config_status
== 'BROKEN' and vca_status
!= 'failed':
174 db_dict
['configurationStatus'][vca_index
] = 'READY'
175 elif config_status
!= 'BROKEN' and vca_status
== 'failed':
176 db_dict
['configurationStatus'][vca_index
] = 'BROKEN'
177 except Exception as e
:
178 # not update configurationStatus
179 self
.logger
.debug('Error updating vca_index (ignore): {}'.format(e
))
181 # if nsState = 'READY' check if juju is reporting some error => nsState = 'DEGRADED'
182 # if nsState = 'DEGRADED' check if all is OK
184 if current_ns_status
in ('READY', 'DEGRADED'):
185 error_description
= ''
187 if status_dict
.get('machines'):
188 for machine_id
in status_dict
.get('machines'):
189 machine
= status_dict
.get('machines').get(machine_id
)
190 # check machine agent-status
191 if machine
.get('agent-status'):
192 s
= machine
.get('agent-status').get('status')
195 error_description
+= 'machine {} agent-status={} ; '.format(machine_id
, s
)
196 # check machine instance status
197 if machine
.get('instance-status'):
198 s
= machine
.get('instance-status').get('status')
201 error_description
+= 'machine {} instance-status={} ; '.format(machine_id
, s
)
203 if status_dict
.get('applications'):
204 for app_id
in status_dict
.get('applications'):
205 app
= status_dict
.get('applications').get(app_id
)
206 # check application status
207 if app
.get('status'):
208 s
= app
.get('status').get('status')
211 error_description
+= 'application {} status={} ; '.format(app_id
, s
)
213 if error_description
:
214 db_dict
['errorDescription'] = error_description
215 if current_ns_status
== 'READY' and is_degraded
:
216 db_dict
['nsState'] = 'DEGRADED'
217 if current_ns_status
== 'DEGRADED' and not is_degraded
:
218 db_dict
['nsState'] = 'READY'
221 self
.update_db_2("nsrs", nsr_id
, db_dict
)
223 except (asyncio
.CancelledError
, asyncio
.TimeoutError
):
225 except Exception as e
:
226 self
.logger
.warn('Error updating NS state for ns={}: {}'.format(nsr_id
, e
))
228 def vnfd2RO(self
, vnfd
, new_id
=None, additionalParams
=None, nsrId
=None):
230 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
231 :param vnfd: input vnfd
232 :param new_id: overrides vnf id if provided
233 :param additionalParams: Instantiation params for VNFs provided
234 :param nsrId: Id of the NSR
235 :return: copy of vnfd
238 vnfd_RO
= deepcopy(vnfd
)
239 # remove unused by RO configuration, monitoring, scaling and internal keys
240 vnfd_RO
.pop("_id", None)
241 vnfd_RO
.pop("_admin", None)
242 vnfd_RO
.pop("vnf-configuration", None)
243 vnfd_RO
.pop("monitoring-param", None)
244 vnfd_RO
.pop("scaling-group-descriptor", None)
245 vnfd_RO
.pop("kdu", None)
246 vnfd_RO
.pop("k8s-cluster", None)
248 vnfd_RO
["id"] = new_id
250 # parse cloud-init or cloud-init-file with the provided variables using Jinja2
251 for vdu
in get_iterable(vnfd_RO
, "vdu"):
252 cloud_init_file
= None
253 if vdu
.get("cloud-init-file"):
254 base_folder
= vnfd
["_admin"]["storage"]
255 cloud_init_file
= "{}/{}/cloud_init/{}".format(base_folder
["folder"], base_folder
["pkg-dir"],
256 vdu
["cloud-init-file"])
257 with self
.fs
.file_open(cloud_init_file
, "r") as ci_file
:
258 cloud_init_content
= ci_file
.read()
259 vdu
.pop("cloud-init-file", None)
260 elif vdu
.get("cloud-init"):
261 cloud_init_content
= vdu
["cloud-init"]
266 ast
= env
.parse(cloud_init_content
)
267 mandatory_vars
= meta
.find_undeclared_variables(ast
)
269 for var
in mandatory_vars
:
270 if not additionalParams
or var
not in additionalParams
.keys():
271 raise LcmException("Variable '{}' defined at vnfd[id={}]:vdu[id={}]:cloud-init/cloud-init-"
272 "file, must be provided in the instantiation parameters inside the "
273 "'additionalParamsForVnf' block".format(var
, vnfd
["id"], vdu
["id"]))
274 template
= Template(cloud_init_content
)
275 cloud_init_content
= template
.render(additionalParams
or {})
276 vdu
["cloud-init"] = cloud_init_content
279 except FsException
as e
:
280 raise LcmException("Error reading vnfd[id={}]:vdu[id={}]:cloud-init-file={}: {}".
281 format(vnfd
["id"], vdu
["id"], cloud_init_file
, e
))
282 except (TemplateError
, TemplateNotFound
, TemplateSyntaxError
) as e
:
283 raise LcmException("Error parsing Jinja2 to cloud-init content at vnfd[id={}]:vdu[id={}]: {}".
284 format(vnfd
["id"], vdu
["id"], e
))
286 def _ns_params_2_RO(self
, ns_params
, nsd
, vnfd_dict
, db_vnfrs
, n2vc_key_list
):
288 Creates a RO ns descriptor from OSM ns_instantiate params
289 :param ns_params: OSM instantiate params
290 :param vnfd_dict: database content of vnfds, indexed by id (not _id). {id: {vnfd_object}, ...}
291 :param db_vnfrs: database content of vnfrs, indexed by member-vnf-index. {member-vnf-index: {vnfr_object}, ...}
292 :return: The RO ns descriptor
296 # TODO feature 1417: Check that no instantiation is set over PDU
297 # check if PDU forces a concrete vim-network-id and add it
298 # check if PDU contains a SDN-assist info (dpid, switch, port) and pass it to RO
300 def vim_account_2_RO(vim_account
):
301 if vim_account
in vim_2_RO
:
302 return vim_2_RO
[vim_account
]
304 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_account
})
305 if db_vim
["_admin"]["operationalState"] != "ENABLED":
306 raise LcmException("VIM={} is not available. operationalState={}".format(
307 vim_account
, db_vim
["_admin"]["operationalState"]))
308 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
309 vim_2_RO
[vim_account
] = RO_vim_id
312 def wim_account_2_RO(wim_account
):
313 if isinstance(wim_account
, str):
314 if wim_account
in wim_2_RO
:
315 return wim_2_RO
[wim_account
]
317 db_wim
= self
.db
.get_one("wim_accounts", {"_id": wim_account
})
318 if db_wim
["_admin"]["operationalState"] != "ENABLED":
319 raise LcmException("WIM={} is not available. operationalState={}".format(
320 wim_account
, db_wim
["_admin"]["operationalState"]))
321 RO_wim_id
= db_wim
["_admin"]["deployed"]["RO-account"]
322 wim_2_RO
[wim_account
] = RO_wim_id
327 def ip_profile_2_RO(ip_profile
):
328 RO_ip_profile
= deepcopy((ip_profile
))
329 if "dns-server" in RO_ip_profile
:
330 if isinstance(RO_ip_profile
["dns-server"], list):
331 RO_ip_profile
["dns-address"] = []
332 for ds
in RO_ip_profile
.pop("dns-server"):
333 RO_ip_profile
["dns-address"].append(ds
['address'])
335 RO_ip_profile
["dns-address"] = RO_ip_profile
.pop("dns-server")
336 if RO_ip_profile
.get("ip-version") == "ipv4":
337 RO_ip_profile
["ip-version"] = "IPv4"
338 if RO_ip_profile
.get("ip-version") == "ipv6":
339 RO_ip_profile
["ip-version"] = "IPv6"
340 if "dhcp-params" in RO_ip_profile
:
341 RO_ip_profile
["dhcp"] = RO_ip_profile
.pop("dhcp-params")
347 # "name": ns_params["nsName"],
348 # "description": ns_params.get("nsDescription"),
349 "datacenter": vim_account_2_RO(ns_params
["vimAccountId"]),
350 "wim_account": wim_account_2_RO(ns_params
.get("wimAccountId")),
351 # "scenario": ns_params["nsdId"],
353 # set vim_account of each vnf if different from general vim_account.
354 # Get this information from <vnfr> database content, key vim-account-id
355 # Vim account can be set by placement_engine and it may be different from
356 # the instantiate parameters (vnfs.member-vnf-index.datacenter).
357 for vnf_index
, vnfr
in db_vnfrs
.items():
358 if vnfr
.get("vim-account-id") and vnfr
["vim-account-id"] != ns_params
["vimAccountId"]:
359 populate_dict(RO_ns_params
, ("vnfs", vnf_index
, "datacenter"), vim_account_2_RO(vnfr
["vim-account-id"]))
361 n2vc_key_list
= n2vc_key_list
or []
362 for vnfd_ref
, vnfd
in vnfd_dict
.items():
363 vdu_needed_access
= []
365 if vnfd
.get("vnf-configuration"):
366 ssh_required
= deep_get(vnfd
, ("vnf-configuration", "config-access", "ssh-access", "required"))
367 if ssh_required
and vnfd
.get("mgmt-interface"):
368 if vnfd
["mgmt-interface"].get("vdu-id"):
369 vdu_needed_access
.append(vnfd
["mgmt-interface"]["vdu-id"])
370 elif vnfd
["mgmt-interface"].get("cp"):
371 mgmt_cp
= vnfd
["mgmt-interface"]["cp"]
373 for vdu
in vnfd
.get("vdu", ()):
374 if vdu
.get("vdu-configuration"):
375 ssh_required
= deep_get(vdu
, ("vdu-configuration", "config-access", "ssh-access", "required"))
377 vdu_needed_access
.append(vdu
["id"])
379 for vdu_interface
in vdu
.get("interface"):
380 if vdu_interface
.get("external-connection-point-ref") and \
381 vdu_interface
["external-connection-point-ref"] == mgmt_cp
:
382 vdu_needed_access
.append(vdu
["id"])
386 if vdu_needed_access
:
387 for vnf_member
in nsd
.get("constituent-vnfd"):
388 if vnf_member
["vnfd-id-ref"] != vnfd_ref
:
390 for vdu
in vdu_needed_access
:
391 populate_dict(RO_ns_params
,
392 ("vnfs", vnf_member
["member-vnf-index"], "vdus", vdu
, "mgmt_keys"),
395 if ns_params
.get("vduImage"):
396 RO_ns_params
["vduImage"] = ns_params
["vduImage"]
398 if ns_params
.get("ssh_keys"):
399 RO_ns_params
["cloud-config"] = {"key-pairs": ns_params
["ssh_keys"]}
400 for vnf_params
in get_iterable(ns_params
, "vnf"):
401 for constituent_vnfd
in nsd
["constituent-vnfd"]:
402 if constituent_vnfd
["member-vnf-index"] == vnf_params
["member-vnf-index"]:
403 vnf_descriptor
= vnfd_dict
[constituent_vnfd
["vnfd-id-ref"]]
406 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index={} is not present at nsd:"
407 "constituent-vnfd".format(vnf_params
["member-vnf-index"]))
409 for vdu_params
in get_iterable(vnf_params
, "vdu"):
410 # TODO feature 1417: check that this VDU exist and it is not a PDU
411 if vdu_params
.get("volume"):
412 for volume_params
in vdu_params
["volume"]:
413 if volume_params
.get("vim-volume-id"):
414 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
415 vdu_params
["id"], "devices", volume_params
["name"], "vim_id"),
416 volume_params
["vim-volume-id"])
417 if vdu_params
.get("interface"):
418 for interface_params
in vdu_params
["interface"]:
419 if interface_params
.get("ip-address"):
420 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
421 vdu_params
["id"], "interfaces", interface_params
["name"],
423 interface_params
["ip-address"])
424 if interface_params
.get("mac-address"):
425 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
426 vdu_params
["id"], "interfaces", interface_params
["name"],
428 interface_params
["mac-address"])
429 if interface_params
.get("floating-ip-required"):
430 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
431 vdu_params
["id"], "interfaces", interface_params
["name"],
433 interface_params
["floating-ip-required"])
435 for internal_vld_params
in get_iterable(vnf_params
, "internal-vld"):
436 if internal_vld_params
.get("vim-network-name"):
437 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
438 internal_vld_params
["name"], "vim-network-name"),
439 internal_vld_params
["vim-network-name"])
440 if internal_vld_params
.get("vim-network-id"):
441 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
442 internal_vld_params
["name"], "vim-network-id"),
443 internal_vld_params
["vim-network-id"])
444 if internal_vld_params
.get("ip-profile"):
445 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
446 internal_vld_params
["name"], "ip-profile"),
447 ip_profile_2_RO(internal_vld_params
["ip-profile"]))
448 if internal_vld_params
.get("provider-network"):
450 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
451 internal_vld_params
["name"], "provider-network"),
452 internal_vld_params
["provider-network"].copy())
454 for icp_params
in get_iterable(internal_vld_params
, "internal-connection-point"):
457 for vdu_descriptor
in vnf_descriptor
["vdu"]:
458 for vdu_interface
in vdu_descriptor
["interface"]:
459 if vdu_interface
.get("internal-connection-point-ref") == icp_params
["id-ref"]:
460 if icp_params
.get("ip-address"):
461 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
462 vdu_descriptor
["id"], "interfaces",
463 vdu_interface
["name"], "ip_address"),
464 icp_params
["ip-address"])
466 if icp_params
.get("mac-address"):
467 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
468 vdu_descriptor
["id"], "interfaces",
469 vdu_interface
["name"], "mac_address"),
470 icp_params
["mac-address"])
476 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
477 "internal-vld:id-ref={} is not present at vnfd:internal-"
478 "connection-point".format(vnf_params
["member-vnf-index"],
479 icp_params
["id-ref"]))
481 for vld_params
in get_iterable(ns_params
, "vld"):
482 if "ip-profile" in vld_params
:
483 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "ip-profile"),
484 ip_profile_2_RO(vld_params
["ip-profile"]))
486 if vld_params
.get("provider-network"):
488 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "provider-network"),
489 vld_params
["provider-network"].copy())
491 if "wimAccountId" in vld_params
and vld_params
["wimAccountId"] is not None:
492 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "wim_account"),
493 wim_account_2_RO(vld_params
["wimAccountId"])),
494 if vld_params
.get("vim-network-name"):
496 if isinstance(vld_params
["vim-network-name"], dict):
497 for vim_account
, vim_net
in vld_params
["vim-network-name"].items():
498 RO_vld_sites
.append({
499 "netmap-use": vim_net
,
500 "datacenter": vim_account_2_RO(vim_account
)
502 else: # isinstance str
503 RO_vld_sites
.append({"netmap-use": vld_params
["vim-network-name"]})
505 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "sites"), RO_vld_sites
)
507 if vld_params
.get("vim-network-id"):
509 if isinstance(vld_params
["vim-network-id"], dict):
510 for vim_account
, vim_net
in vld_params
["vim-network-id"].items():
511 RO_vld_sites
.append({
512 "netmap-use": vim_net
,
513 "datacenter": vim_account_2_RO(vim_account
)
515 else: # isinstance str
516 RO_vld_sites
.append({"netmap-use": vld_params
["vim-network-id"]})
518 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "sites"), RO_vld_sites
)
519 if vld_params
.get("ns-net"):
520 if isinstance(vld_params
["ns-net"], dict):
521 for vld_id
, instance_scenario_id
in vld_params
["ns-net"].items():
522 RO_vld_ns_net
= {"instance_scenario_id": instance_scenario_id
, "osm_id": vld_id
}
523 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "use-network"), RO_vld_ns_net
)
524 if "vnfd-connection-point-ref" in vld_params
:
525 for cp_params
in vld_params
["vnfd-connection-point-ref"]:
527 for constituent_vnfd
in nsd
["constituent-vnfd"]:
528 if constituent_vnfd
["member-vnf-index"] == cp_params
["member-vnf-index-ref"]:
529 vnf_descriptor
= vnfd_dict
[constituent_vnfd
["vnfd-id-ref"]]
533 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={} "
534 "is not present at nsd:constituent-vnfd".format(cp_params
["member-vnf-index-ref"]))
536 for vdu_descriptor
in vnf_descriptor
["vdu"]:
537 for interface_descriptor
in vdu_descriptor
["interface"]:
538 if interface_descriptor
.get("external-connection-point-ref") == \
539 cp_params
["vnfd-connection-point-ref"]:
546 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={}:"
547 "vnfd-connection-point-ref={} is not present at vnfd={}".format(
548 cp_params
["member-vnf-index-ref"],
549 cp_params
["vnfd-connection-point-ref"],
550 vnf_descriptor
["id"]))
551 if cp_params
.get("ip-address"):
552 populate_dict(RO_ns_params
, ("vnfs", cp_params
["member-vnf-index-ref"], "vdus",
553 vdu_descriptor
["id"], "interfaces",
554 interface_descriptor
["name"], "ip_address"),
555 cp_params
["ip-address"])
556 if cp_params
.get("mac-address"):
557 populate_dict(RO_ns_params
, ("vnfs", cp_params
["member-vnf-index-ref"], "vdus",
558 vdu_descriptor
["id"], "interfaces",
559 interface_descriptor
["name"], "mac_address"),
560 cp_params
["mac-address"])
563 def scale_vnfr(self
, db_vnfr
, vdu_create
=None, vdu_delete
=None):
564 # make a copy to do not change
565 vdu_create
= copy(vdu_create
)
566 vdu_delete
= copy(vdu_delete
)
568 vdurs
= db_vnfr
.get("vdur")
571 vdu_index
= len(vdurs
)
574 vdur
= vdurs
[vdu_index
]
575 if vdur
.get("pdu-type"):
577 vdu_id_ref
= vdur
["vdu-id-ref"]
578 if vdu_create
and vdu_create
.get(vdu_id_ref
):
579 for index
in range(0, vdu_create
[vdu_id_ref
]):
580 vdur
= deepcopy(vdur
)
581 vdur
["_id"] = str(uuid4())
582 vdur
["count-index"] += 1
583 vdurs
.insert(vdu_index
+1+index
, vdur
)
584 del vdu_create
[vdu_id_ref
]
585 if vdu_delete
and vdu_delete
.get(vdu_id_ref
):
587 vdu_delete
[vdu_id_ref
] -= 1
588 if not vdu_delete
[vdu_id_ref
]:
589 del vdu_delete
[vdu_id_ref
]
590 # check all operations are done
591 if vdu_create
or vdu_delete
:
592 raise LcmException("Error scaling OUT VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
595 raise LcmException("Error scaling IN VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
598 vnfr_update
= {"vdur": vdurs
}
599 db_vnfr
["vdur"] = vdurs
600 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
602 def ns_update_nsr(self
, ns_update_nsr
, db_nsr
, nsr_desc_RO
):
604 Updates database nsr with the RO info for the created vld
605 :param ns_update_nsr: dictionary to be filled with the updated info
606 :param db_nsr: content of db_nsr. This is also modified
607 :param nsr_desc_RO: nsr descriptor from RO
608 :return: Nothing, LcmException is raised on errors
611 for vld_index
, vld
in enumerate(get_iterable(db_nsr
, "vld")):
612 for net_RO
in get_iterable(nsr_desc_RO
, "nets"):
613 if vld
["id"] != net_RO
.get("ns_net_osm_id"):
615 vld
["vim-id"] = net_RO
.get("vim_net_id")
616 vld
["name"] = net_RO
.get("vim_name")
617 vld
["status"] = net_RO
.get("status")
618 vld
["status-detailed"] = net_RO
.get("error_msg")
619 ns_update_nsr
["vld.{}".format(vld_index
)] = vld
622 raise LcmException("ns_update_nsr: Not found vld={} at RO info".format(vld
["id"]))
624 def set_vnfr_at_error(self
, db_vnfrs
, error_text
):
626 for db_vnfr
in db_vnfrs
.values():
627 vnfr_update
= {"status": "ERROR"}
628 for vdu_index
, vdur
in enumerate(get_iterable(db_vnfr
, "vdur")):
629 if "status" not in vdur
:
630 vdur
["status"] = "ERROR"
631 vnfr_update
["vdur.{}.status".format(vdu_index
)] = "ERROR"
633 vdur
["status-detailed"] = str(error_text
)
634 vnfr_update
["vdur.{}.status-detailed".format(vdu_index
)] = "ERROR"
635 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
636 except DbException
as e
:
637 self
.logger
.error("Cannot update vnf. {}".format(e
))
639 def ns_update_vnfr(self
, db_vnfrs
, nsr_desc_RO
):
641 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
642 :param db_vnfrs: dictionary with member-vnf-index: vnfr-content
643 :param nsr_desc_RO: nsr descriptor from RO
644 :return: Nothing, LcmException is raised on errors
646 for vnf_index
, db_vnfr
in db_vnfrs
.items():
647 for vnf_RO
in nsr_desc_RO
["vnfs"]:
648 if vnf_RO
["member_vnf_index"] != vnf_index
:
651 if vnf_RO
.get("ip_address"):
652 db_vnfr
["ip-address"] = vnfr_update
["ip-address"] = vnf_RO
["ip_address"].split(";")[0]
653 elif not db_vnfr
.get("ip-address"):
654 if db_vnfr
.get("vdur"): # if not VDUs, there is not ip_address
655 raise LcmExceptionNoMgmtIP("ns member_vnf_index '{}' has no IP address".format(vnf_index
))
657 for vdu_index
, vdur
in enumerate(get_iterable(db_vnfr
, "vdur")):
658 vdur_RO_count_index
= 0
659 if vdur
.get("pdu-type"):
661 for vdur_RO
in get_iterable(vnf_RO
, "vms"):
662 if vdur
["vdu-id-ref"] != vdur_RO
["vdu_osm_id"]:
664 if vdur
["count-index"] != vdur_RO_count_index
:
665 vdur_RO_count_index
+= 1
667 vdur
["vim-id"] = vdur_RO
.get("vim_vm_id")
668 if vdur_RO
.get("ip_address"):
669 vdur
["ip-address"] = vdur_RO
["ip_address"].split(";")[0]
671 vdur
["ip-address"] = None
672 vdur
["vdu-id-ref"] = vdur_RO
.get("vdu_osm_id")
673 vdur
["name"] = vdur_RO
.get("vim_name")
674 vdur
["status"] = vdur_RO
.get("status")
675 vdur
["status-detailed"] = vdur_RO
.get("error_msg")
676 for ifacer
in get_iterable(vdur
, "interfaces"):
677 for interface_RO
in get_iterable(vdur_RO
, "interfaces"):
678 if ifacer
["name"] == interface_RO
.get("internal_name"):
679 ifacer
["ip-address"] = interface_RO
.get("ip_address")
680 ifacer
["mac-address"] = interface_RO
.get("mac_address")
683 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} interface={} "
685 .format(vnf_index
, vdur
["vdu-id-ref"], ifacer
["name"]))
686 vnfr_update
["vdur.{}".format(vdu_index
)] = vdur
689 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} count_index={} from "
690 "VIM info".format(vnf_index
, vdur
["vdu-id-ref"], vdur
["count-index"]))
692 for vld_index
, vld
in enumerate(get_iterable(db_vnfr
, "vld")):
693 for net_RO
in get_iterable(nsr_desc_RO
, "nets"):
694 if vld
["id"] != net_RO
.get("vnf_net_osm_id"):
696 vld
["vim-id"] = net_RO
.get("vim_net_id")
697 vld
["name"] = net_RO
.get("vim_name")
698 vld
["status"] = net_RO
.get("status")
699 vld
["status-detailed"] = net_RO
.get("error_msg")
700 vnfr_update
["vld.{}".format(vld_index
)] = vld
703 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vld={} from VIM info".format(
704 vnf_index
, vld
["id"]))
706 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
710 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} from VIM info".format(vnf_index
))
712 def _get_ns_config_info(self
, nsr_id
):
714 Generates a mapping between vnf,vdu elements and the N2VC id
715 :param nsr_id: id of nsr to get last database _admin.deployed.VCA that contains this list
716 :return: a dictionary with {osm-config-mapping: {}} where its element contains:
717 "<member-vnf-index>": <N2VC-id> for a vnf configuration, or
718 "<member-vnf-index>.<vdu.id>.<vdu replica(0, 1,..)>": <N2VC-id> for a vdu configuration
720 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
721 vca_deployed_list
= db_nsr
["_admin"]["deployed"]["VCA"]
723 ns_config_info
= {"osm-config-mapping": mapping
}
724 for vca
in vca_deployed_list
:
725 if not vca
["member-vnf-index"]:
727 if not vca
["vdu_id"]:
728 mapping
[vca
["member-vnf-index"]] = vca
["application"]
730 mapping
["{}.{}.{}".format(vca
["member-vnf-index"], vca
["vdu_id"], vca
["vdu_count_index"])] =\
732 return ns_config_info
735 def _get_initial_config_primitive_list(desc_primitive_list
, vca_deployed
):
737 Generates a list of initial-config-primitive based on the list provided by the descriptor. It includes internal
738 primitives as verify-ssh-credentials, or config when needed
739 :param desc_primitive_list: information of the descriptor
740 :param vca_deployed: information of the deployed, needed for known if it is related to an NS, VNF, VDU and if
741 this element contains a ssh public key
742 :return: The modified list. Can ba an empty list, but always a list
744 if desc_primitive_list
:
745 primitive_list
= desc_primitive_list
.copy()
748 # look for primitive config, and get the position. None if not present
749 config_position
= None
750 for index
, primitive
in enumerate(primitive_list
):
751 if primitive
["name"] == "config":
752 config_position
= index
755 # for NS, add always a config primitive if not present (bug 874)
756 if not vca_deployed
["member-vnf-index"] and config_position
is None:
757 primitive_list
.insert(0, {"name": "config", "parameter": []})
759 # for VNF/VDU add verify-ssh-credentials after config
760 if vca_deployed
["member-vnf-index"] and config_position
is not None and vca_deployed
.get("ssh-public-key"):
761 primitive_list
.insert(config_position
+ 1, {"name": "verify-ssh-credentials", "parameter": []})
762 return primitive_list
764 async def _instantiate_ng_ro(self
, logging_text
, nsr_id
, nsd
, db_nsr
, db_nslcmop
, db_vnfrs
, db_vnfds_ref
,
765 n2vc_key_list
, stage
, start_deploy
, timeout_ns_deploy
):
766 nslcmop_id
= db_nslcmop
["_id"]
768 "name": db_nsr
["name"],
771 "image": deepcopy(db_nsr
["image"]),
772 "flavor": deepcopy(db_nsr
["flavor"]),
773 "action_id": nslcmop_id
,
775 for image
in target
["image"]:
776 image
["vim_info"] = []
777 for flavor
in target
["flavor"]:
778 flavor
["vim_info"] = []
780 ns_params
= db_nslcmop
.get("operationParams")
782 if ns_params
.get("ssh_keys"):
783 ssh_keys
+= ns_params
.get("ssh_keys")
785 ssh_keys
+= n2vc_key_list
788 for vld_index
, vld
in enumerate(nsd
.get("vld")):
789 target_vld
= {"id": vld
["id"],
791 "mgmt-network": vld
.get("mgmt-network", False),
792 "type": vld
.get("type"),
793 "vim_info": [{"vim-network-name": vld
.get("vim-network-name"),
794 "vim_account_id": ns_params
["vimAccountId"]}],
796 for cp
in vld
["vnfd-connection-point-ref"]:
797 cp2target
["member_vnf:{}.{}".format(cp
["member-vnf-index-ref"], cp
["vnfd-connection-point-ref"])] = \
798 "nsrs:{}:vld.{}".format(nsr_id
, vld_index
)
799 target
["ns"]["vld"].append(target_vld
)
800 for vnfr
in db_vnfrs
.values():
801 vnfd
= db_vnfds_ref
[vnfr
["vnfd-ref"]]
802 target_vnf
= deepcopy(vnfr
)
803 for vld
in target_vnf
.get("vld", ()):
804 # check if connected to a ns.vld
805 vnf_cp
= next((cp
for cp
in vnfd
.get("connection-point", ()) if
806 cp
.get("internal-vld-ref") == vld
["id"]), None)
808 ns_cp
= "member_vnf:{}.{}".format(vnfr
["member-vnf-index-ref"], vnf_cp
["id"])
809 if cp2target
.get(ns_cp
):
810 vld
["target"] = cp2target
[ns_cp
]
811 vld
["vim_info"] = [{"vim-network-name": vld
.get("vim-network-name"),
812 "vim_account_id": vnfr
["vim-account-id"]}]
814 for vdur
in target_vnf
.get("vdur", ()):
815 vdur
["vim_info"] = [{"vim_account_id": vnfr
["vim-account-id"]}]
816 vdud_index
, vdud
= next(k
for k
in enumerate(vnfd
["vdu"]) if k
[1]["id"] == vdur
["vdu-id-ref"])
817 # vdur["additionalParams"] = vnfr.get("additionalParamsForVnf") # TODO additional params for VDU
820 if deep_get(vdud
, ("vdu-configuration", "config-access", "ssh-access", "required")):
821 vdur
["ssh-keys"] = ssh_keys
822 vdur
["ssh-access-required"] = True
823 elif deep_get(vnfd
, ("vnf-configuration", "config-access", "ssh-access", "required")) and \
824 any(iface
.get("mgmt-vnf") for iface
in vdur
["interfaces"]):
825 vdur
["ssh-keys"] = ssh_keys
826 vdur
["ssh-access-required"] = True
829 if vdud
.get("cloud-init-file"):
830 vdur
["cloud-init"] = "{}:file:{}".format(vnfd
["_id"], vdud
.get("cloud-init-file"))
831 elif vdud
.get("cloud-init"):
832 vdur
["cloud-init"] = "{}:vdu:{}".format(vnfd
["_id"], vdud_index
)
835 ns_flavor
= target
["flavor"][int(vdur
["ns-flavor-id"])]
836 if not next((vi
for vi
in ns_flavor
["vim_info"] if
837 vi
and vi
.get("vim_account_id") == vnfr
["vim-account-id"]), None):
838 ns_flavor
["vim_info"].append({"vim_account_id": vnfr
["vim-account-id"]})
840 ns_image
= target
["image"][int(vdur
["ns-image-id"])]
841 if not next((vi
for vi
in ns_image
["vim_info"] if
842 vi
and vi
.get("vim_account_id") == vnfr
["vim-account-id"]), None):
843 ns_image
["vim_info"].append({"vim_account_id": vnfr
["vim-account-id"]})
845 vdur
["vim_info"] = [{"vim_account_id": vnfr
["vim-account-id"]}]
846 target
["vnf"].append(target_vnf
)
848 desc
= await self
.RO
.deploy(nsr_id
, target
)
849 action_id
= desc
["action_id"]
850 await self
._wait
_ng
_ro
(self
, nsr_id
, action_id
, nslcmop_id
, start_deploy
, timeout_ns_deploy
, stage
)
854 "_admin.deployed.RO.operational-status": "running",
855 "detailed-status": " ".join(stage
)
857 # db_nsr["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
858 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
859 self
._write
_op
_status
(nslcmop_id
, stage
)
860 self
.logger
.debug(logging_text
+ "ns deployed at RO. RO_id={}".format(action_id
))
863 async def _wait_ng_ro(self
, nsr_id
, action_id
, nslcmop_id
, start_time
, timeout
, stage
):
864 detailed_status_old
= None
866 while time() <= start_time
+ timeout
:
867 desc_status
= await self
.RO
.status(nsr_id
, action_id
)
868 if desc_status
["status"] == "FAILED":
869 raise NgRoException(desc_status
["details"])
870 elif desc_status
["status"] == "BUILD":
871 stage
[2] = "VIM: ({})".format(desc_status
["details"])
872 elif desc_status
["status"] == "DONE":
873 stage
[2] = "Deployed at VIM"
876 assert False, "ROclient.check_ns_status returns unknown {}".format(desc_status
["status"])
877 if stage
[2] != detailed_status_old
:
878 detailed_status_old
= stage
[2]
879 db_nsr_update
["detailed-status"] = " ".join(stage
)
880 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
881 self
._write
_op
_status
(nslcmop_id
, stage
)
882 await asyncio
.sleep(5, loop
=self
.loop
)
883 else: # timeout_ns_deploy
884 raise NgRoException("Timeout waiting ns to deploy")
886 async def _terminate_ng_ro(self
, logging_text
, nsr_deployed
, nsr_id
, nslcmop_id
, stage
):
890 start_deploy
= time()
898 desc
= await self
.RO
.deploy(nsr_id
, target
)
899 action_id
= desc
["action_id"]
900 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = action_id
901 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETING"
902 self
.logger
.debug(logging_text
+ "ns terminate action at RO. action_id={}".format(action_id
))
905 delete_timeout
= 20 * 60 # 20 minutes
906 await self
._wait
_ng
_ro
(self
, nsr_id
, action_id
, nslcmop_id
, start_deploy
, delete_timeout
, stage
)
908 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
909 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
911 await self
.RO
.delete(nsr_id
)
912 except Exception as e
:
913 if isinstance(e
, NgRoException
) and e
.http_code
== 404: # not found
914 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
915 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
916 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
917 self
.logger
.debug(logging_text
+ "RO_action_id={} already deleted".format(action_id
))
918 elif isinstance(e
, NgRoException
) and e
.http_code
== 409: # conflict
919 failed_detail
.append("delete conflict: {}".format(e
))
920 self
.logger
.debug(logging_text
+ "RO_action_id={} delete conflict: {}".format(action_id
, e
))
922 failed_detail
.append("delete error: {}".format(e
))
923 self
.logger
.error(logging_text
+ "RO_action_id={} delete error: {}".format(action_id
, e
))
926 stage
[2] = "Error deleting from VIM"
928 stage
[2] = "Deleted from VIM"
929 db_nsr_update
["detailed-status"] = " ".join(stage
)
930 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
931 self
._write
_op
_status
(nslcmop_id
, stage
)
934 raise LcmException("; ".join(failed_detail
))
937 async def instantiate_RO(self
, logging_text
, nsr_id
, nsd
, db_nsr
, db_nslcmop
, db_vnfrs
, db_vnfds_ref
,
938 n2vc_key_list
, stage
):
941 :param logging_text: preffix text to use at logging
942 :param nsr_id: nsr identity
943 :param nsd: database content of ns descriptor
944 :param db_nsr: database content of ns record
945 :param db_nslcmop: database content of ns operation, in this case, 'instantiate'
947 :param db_vnfds_ref: database content of vnfds, indexed by id (not _id). {id: {vnfd_object}, ...}
948 :param n2vc_key_list: ssh-public-key list to be inserted to management vdus via cloud-init
949 :param stage: list with 3 items: [general stage, tasks, vim_specific]. This task will write over vim_specific
950 :return: None or exception
954 RO_descriptor_number
= 0 # number of descriptors created at RO
955 vnf_index_2_RO_id
= {} # map between vnfd/nsd id to the id used at RO
956 nslcmop_id
= db_nslcmop
["_id"]
957 start_deploy
= time()
958 ns_params
= db_nslcmop
.get("operationParams")
959 if ns_params
and ns_params
.get("timeout_ns_deploy"):
960 timeout_ns_deploy
= ns_params
["timeout_ns_deploy"]
962 timeout_ns_deploy
= self
.timeout
.get("ns_deploy", self
.timeout_ns_deploy
)
964 # Check for and optionally request placement optimization. Database will be updated if placement activated
965 stage
[2] = "Waiting for Placement."
966 if await self
._do
_placement
(logging_text
, db_nslcmop
, db_vnfrs
):
967 # in case of placement change ns_params[vimAcountId) if not present at any vnfrs
968 for vnfr
in db_vnfrs
.values():
969 if ns_params
["vimAccountId"] == vnfr
["vim-account-id"]:
972 ns_params
["vimAccountId"] == vnfr
["vim-account-id"]
975 return await self
._instantiate
_ng
_ro
(logging_text
, nsr_id
, nsd
, db_nsr
, db_nslcmop
, db_vnfrs
,
976 db_vnfds_ref
, n2vc_key_list
, stage
, start_deploy
,
979 # get vnfds, instantiate at RO
980 for c_vnf
in nsd
.get("constituent-vnfd", ()):
981 member_vnf_index
= c_vnf
["member-vnf-index"]
982 vnfd
= db_vnfds_ref
[c_vnf
['vnfd-id-ref']]
983 vnfd_ref
= vnfd
["id"]
985 stage
[2] = "Creating vnfd='{}' member_vnf_index='{}' at RO".format(vnfd_ref
, member_vnf_index
)
986 db_nsr_update
["detailed-status"] = " ".join(stage
)
987 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
988 self
._write
_op
_status
(nslcmop_id
, stage
)
990 # self.logger.debug(logging_text + stage[2])
991 vnfd_id_RO
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, member_vnf_index
[:23])
992 vnf_index_2_RO_id
[member_vnf_index
] = vnfd_id_RO
993 RO_descriptor_number
+= 1
995 # look position at deployed.RO.vnfd if not present it will be appended at the end
996 for index
, vnf_deployed
in enumerate(db_nsr
["_admin"]["deployed"]["RO"]["vnfd"]):
997 if vnf_deployed
["member-vnf-index"] == member_vnf_index
:
1000 index
= len(db_nsr
["_admin"]["deployed"]["RO"]["vnfd"])
1001 db_nsr
["_admin"]["deployed"]["RO"]["vnfd"].append(None)
1004 RO_update
= {"member-vnf-index": member_vnf_index
}
1005 vnfd_list
= await self
.RO
.get_list("vnfd", filter_by
={"osm_id": vnfd_id_RO
})
1007 RO_update
["id"] = vnfd_list
[0]["uuid"]
1008 self
.logger
.debug(logging_text
+ "vnfd='{}' member_vnf_index='{}' exists at RO. Using RO_id={}".
1009 format(vnfd_ref
, member_vnf_index
, vnfd_list
[0]["uuid"]))
1011 vnfd_RO
= self
.vnfd2RO(vnfd
, vnfd_id_RO
, db_vnfrs
[c_vnf
["member-vnf-index"]].
1012 get("additionalParamsForVnf"), nsr_id
)
1013 desc
= await self
.RO
.create("vnfd", descriptor
=vnfd_RO
)
1014 RO_update
["id"] = desc
["uuid"]
1015 self
.logger
.debug(logging_text
+ "vnfd='{}' member_vnf_index='{}' created at RO. RO_id={}".format(
1016 vnfd_ref
, member_vnf_index
, desc
["uuid"]))
1017 db_nsr_update
["_admin.deployed.RO.vnfd.{}".format(index
)] = RO_update
1018 db_nsr
["_admin"]["deployed"]["RO"]["vnfd"][index
] = RO_update
1023 stage
[2] = "Creating nsd={} at RO".format(nsd_ref
)
1024 db_nsr_update
["detailed-status"] = " ".join(stage
)
1025 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1026 self
._write
_op
_status
(nslcmop_id
, stage
)
1028 # self.logger.debug(logging_text + stage[2])
1029 RO_osm_nsd_id
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, nsd_ref
[:23])
1030 RO_descriptor_number
+= 1
1031 nsd_list
= await self
.RO
.get_list("nsd", filter_by
={"osm_id": RO_osm_nsd_id
})
1033 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= nsd_list
[0]["uuid"]
1034 self
.logger
.debug(logging_text
+ "nsd={} exists at RO. Using RO_id={}".format(
1035 nsd_ref
, RO_nsd_uuid
))
1037 nsd_RO
= deepcopy(nsd
)
1038 nsd_RO
["id"] = RO_osm_nsd_id
1039 nsd_RO
.pop("_id", None)
1040 nsd_RO
.pop("_admin", None)
1041 for c_vnf
in nsd_RO
.get("constituent-vnfd", ()):
1042 member_vnf_index
= c_vnf
["member-vnf-index"]
1043 c_vnf
["vnfd-id-ref"] = vnf_index_2_RO_id
[member_vnf_index
]
1044 for c_vld
in nsd_RO
.get("vld", ()):
1045 for cp
in c_vld
.get("vnfd-connection-point-ref", ()):
1046 member_vnf_index
= cp
["member-vnf-index-ref"]
1047 cp
["vnfd-id-ref"] = vnf_index_2_RO_id
[member_vnf_index
]
1049 desc
= await self
.RO
.create("nsd", descriptor
=nsd_RO
)
1050 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1051 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= desc
["uuid"]
1052 self
.logger
.debug(logging_text
+ "nsd={} created at RO. RO_id={}".format(nsd_ref
, RO_nsd_uuid
))
1053 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1056 stage
[2] = "Creating nsd={} at RO".format(nsd_ref
)
1057 db_nsr_update
["detailed-status"] = " ".join(stage
)
1058 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1059 self
._write
_op
_status
(nslcmop_id
, stage
)
1061 # if present use it unless in error status
1062 RO_nsr_id
= deep_get(db_nsr
, ("_admin", "deployed", "RO", "nsr_id"))
1065 stage
[2] = "Looking for existing ns at RO"
1066 db_nsr_update
["detailed-status"] = " ".join(stage
)
1067 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1068 self
._write
_op
_status
(nslcmop_id
, stage
)
1069 # self.logger.debug(logging_text + stage[2] + " RO_ns_id={}".format(RO_nsr_id))
1070 desc
= await self
.RO
.show("ns", RO_nsr_id
)
1072 except ROclient
.ROClientException
as e
:
1073 if e
.http_code
!= HTTPStatus
.NOT_FOUND
:
1075 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1077 ns_status
, ns_status_info
= self
.RO
.check_ns_status(desc
)
1078 db_nsr_update
["_admin.deployed.RO.nsr_status"] = ns_status
1079 if ns_status
== "ERROR":
1080 stage
[2] = "Deleting ns at RO. RO_ns_id={}".format(RO_nsr_id
)
1081 self
.logger
.debug(logging_text
+ stage
[2])
1082 await self
.RO
.delete("ns", RO_nsr_id
)
1083 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1085 stage
[2] = "Checking dependencies"
1086 db_nsr_update
["detailed-status"] = " ".join(stage
)
1087 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1088 self
._write
_op
_status
(nslcmop_id
, stage
)
1089 # self.logger.debug(logging_text + stage[2])
1091 # check if VIM is creating and wait look if previous tasks in process
1092 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account", ns_params
["vimAccountId"])
1094 stage
[2] = "Waiting for related tasks '{}' to be completed".format(task_name
)
1095 self
.logger
.debug(logging_text
+ stage
[2])
1096 await asyncio
.wait(task_dependency
, timeout
=3600)
1097 if ns_params
.get("vnf"):
1098 for vnf
in ns_params
["vnf"]:
1099 if "vimAccountId" in vnf
:
1100 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account",
1101 vnf
["vimAccountId"])
1103 stage
[2] = "Waiting for related tasks '{}' to be completed.".format(task_name
)
1104 self
.logger
.debug(logging_text
+ stage
[2])
1105 await asyncio
.wait(task_dependency
, timeout
=3600)
1107 stage
[2] = "Checking instantiation parameters."
1108 RO_ns_params
= self
._ns
_params
_2_RO
(ns_params
, nsd
, db_vnfds_ref
, db_vnfrs
, n2vc_key_list
)
1109 stage
[2] = "Deploying ns at VIM."
1110 db_nsr_update
["detailed-status"] = " ".join(stage
)
1111 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1112 self
._write
_op
_status
(nslcmop_id
, stage
)
1114 desc
= await self
.RO
.create("ns", descriptor
=RO_ns_params
, name
=db_nsr
["name"], scenario
=RO_nsd_uuid
)
1115 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = desc
["uuid"]
1116 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1117 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "BUILD"
1118 self
.logger
.debug(logging_text
+ "ns created at RO. RO_id={}".format(desc
["uuid"]))
1120 # wait until NS is ready
1121 stage
[2] = "Waiting VIM to deploy ns."
1122 db_nsr_update
["detailed-status"] = " ".join(stage
)
1123 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1124 self
._write
_op
_status
(nslcmop_id
, stage
)
1125 detailed_status_old
= None
1126 self
.logger
.debug(logging_text
+ stage
[2] + " RO_ns_id={}".format(RO_nsr_id
))
1129 while time() <= start_deploy
+ timeout_ns_deploy
:
1130 desc
= await self
.RO
.show("ns", RO_nsr_id
)
1133 if desc
!= old_desc
:
1134 # desc has changed => update db
1135 self
._on
_update
_ro
_db
(nsrs_id
=nsr_id
, ro_descriptor
=desc
)
1138 ns_status
, ns_status_info
= self
.RO
.check_ns_status(desc
)
1139 db_nsr_update
["_admin.deployed.RO.nsr_status"] = ns_status
1140 if ns_status
== "ERROR":
1141 raise ROclient
.ROClientException(ns_status_info
)
1142 elif ns_status
== "BUILD":
1143 stage
[2] = "VIM: ({})".format(ns_status_info
)
1144 elif ns_status
== "ACTIVE":
1145 stage
[2] = "Waiting for management IP address reported by the VIM. Updating VNFRs."
1147 self
.ns_update_vnfr(db_vnfrs
, desc
)
1149 except LcmExceptionNoMgmtIP
:
1152 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
1153 if stage
[2] != detailed_status_old
:
1154 detailed_status_old
= stage
[2]
1155 db_nsr_update
["detailed-status"] = " ".join(stage
)
1156 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1157 self
._write
_op
_status
(nslcmop_id
, stage
)
1158 await asyncio
.sleep(5, loop
=self
.loop
)
1159 else: # timeout_ns_deploy
1160 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
1163 self
.ns_update_nsr(db_nsr_update
, db_nsr
, desc
)
1165 db_nsr_update
["_admin.deployed.RO.operational-status"] = "running"
1166 # db_nsr["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
1167 stage
[2] = "Deployed at VIM"
1168 db_nsr_update
["detailed-status"] = " ".join(stage
)
1169 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1170 self
._write
_op
_status
(nslcmop_id
, stage
)
1171 # await self._on_update_n2vc_db("nsrs", {"_id": nsr_id}, "_admin.deployed", db_nsr_update)
1172 # self.logger.debug(logging_text + "Deployed at VIM")
1173 except (ROclient
.ROClientException
, LcmException
, DbException
, NgRoException
) as e
:
1174 stage
[2] = "ERROR deploying at VIM"
1175 self
.set_vnfr_at_error(db_vnfrs
, str(e
))
1178 async def wait_vm_up_insert_key_ro(self
, logging_text
, nsr_id
, vnfr_id
, vdu_id
, vdu_index
, pub_key
=None, user
=None):
1180 Wait for ip addres at RO, and optionally, insert public key in virtual machine
1181 :param logging_text: prefix use for logging
1186 :param pub_key: public ssh key to inject, None to skip
1187 :param user: user to apply the public ssh key
1191 # self.logger.debug(logging_text + "Starting wait_vm_up_insert_key_ro")
1195 target_vdu_id
= None
1201 if ro_retries
>= 360: # 1 hour
1202 raise LcmException("Not found _admin.deployed.RO.nsr_id for nsr_id: {}".format(nsr_id
))
1204 await asyncio
.sleep(10, loop
=self
.loop
)
1207 if not target_vdu_id
:
1208 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnfr_id
})
1210 if not vdu_id
: # for the VNF case
1211 if db_vnfr
.get("status") == "ERROR":
1212 raise LcmException("Cannot inject ssh-key because target VNF is in error state")
1213 ip_address
= db_vnfr
.get("ip-address")
1216 vdur
= next((x
for x
in get_iterable(db_vnfr
, "vdur") if x
.get("ip-address") == ip_address
), None)
1218 vdur
= next((x
for x
in get_iterable(db_vnfr
, "vdur")
1219 if x
.get("vdu-id-ref") == vdu_id
and x
.get("count-index") == vdu_index
), None)
1221 if not vdur
and len(db_vnfr
.get("vdur", ())) == 1: # If only one, this should be the target vdu
1222 vdur
= db_vnfr
["vdur"][0]
1224 raise LcmException("Not found vnfr_id={}, vdu_id={}, vdu_index={}".format(vnfr_id
, vdu_id
,
1227 if vdur
.get("pdu-type") or vdur
.get("status") == "ACTIVE":
1228 ip_address
= vdur
.get("ip-address")
1231 target_vdu_id
= vdur
["vdu-id-ref"]
1232 elif vdur
.get("status") == "ERROR":
1233 raise LcmException("Cannot inject ssh-key because target VM is in error state")
1235 if not target_vdu_id
:
1238 # inject public key into machine
1239 if pub_key
and user
:
1240 # wait until NS is deployed at RO
1242 db_nsrs
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1243 ro_nsr_id
= deep_get(db_nsrs
, ("_admin", "deployed", "RO", "nsr_id"))
1247 # self.logger.debug(logging_text + "Inserting RO key")
1248 if vdur
.get("pdu-type"):
1249 self
.logger
.error(logging_text
+ "Cannot inject ssh-ky to a PDU")
1252 ro_vm_id
= "{}-{}".format(db_vnfr
["member-vnf-index-ref"], target_vdu_id
) # TODO add vdu_index
1254 target
= {"action": "inject_ssh_key", "key": pub_key
, "user": user
,
1255 "vnf": [{"_id": vnfr_id
, "vdur": [{"id": vdu_id
}]}],
1257 await self
.RO
.deploy(nsr_id
, target
)
1259 result_dict
= await self
.RO
.create_action(
1261 item_id_name
=ro_nsr_id
,
1262 descriptor
={"add_public_key": pub_key
, "vms": [ro_vm_id
], "user": user
}
1264 # result_dict contains the format {VM-id: {vim_result: 200, description: text}}
1265 if not result_dict
or not isinstance(result_dict
, dict):
1266 raise LcmException("Unknown response from RO when injecting key")
1267 for result
in result_dict
.values():
1268 if result
.get("vim_result") == 200:
1271 raise ROclient
.ROClientException("error injecting key: {}".format(
1272 result
.get("description")))
1274 except NgRoException
as e
:
1275 raise LcmException("Reaching max tries injecting key. Error: {}".format(e
))
1276 except ROclient
.ROClientException
as e
:
1278 self
.logger
.debug(logging_text
+ "error injecting key: {}. Retrying until {} seconds".
1282 raise LcmException("Reaching max tries injecting key. Error: {}".format(e
))
1288 async def _wait_dependent_n2vc(self
, nsr_id
, vca_deployed_list
, vca_index
):
1290 Wait until dependent VCA deployments have been finished. NS wait for VNFs and VDUs. VNFs for VDUs
1292 my_vca
= vca_deployed_list
[vca_index
]
1293 if my_vca
.get("vdu_id") or my_vca
.get("kdu_name"):
1294 # vdu or kdu: no dependencies
1298 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1299 vca_deployed_list
= db_nsr
["_admin"]["deployed"]["VCA"]
1300 configuration_status_list
= db_nsr
["configurationStatus"]
1301 for index
, vca_deployed
in enumerate(configuration_status_list
):
1302 if index
== vca_index
:
1305 if not my_vca
.get("member-vnf-index") or \
1306 (vca_deployed
.get("member-vnf-index") == my_vca
.get("member-vnf-index")):
1307 internal_status
= configuration_status_list
[index
].get("status")
1308 if internal_status
== 'READY':
1310 elif internal_status
== 'BROKEN':
1311 raise LcmException("Configuration aborted because dependent charm/s has failed")
1315 # no dependencies, return
1317 await asyncio
.sleep(10)
1320 raise LcmException("Configuration aborted because dependent charm/s timeout")
1322 async def instantiate_N2VC(self
, logging_text
, vca_index
, nsi_id
, db_nsr
, db_vnfr
, vdu_id
, kdu_name
, vdu_index
,
1323 config_descriptor
, deploy_params
, base_folder
, nslcmop_id
, stage
):
1324 nsr_id
= db_nsr
["_id"]
1325 db_update_entry
= "_admin.deployed.VCA.{}.".format(vca_index
)
1326 vca_deployed_list
= db_nsr
["_admin"]["deployed"]["VCA"]
1327 vca_deployed
= db_nsr
["_admin"]["deployed"]["VCA"][vca_index
]
1329 'collection': 'nsrs',
1330 'filter': {'_id': nsr_id
},
1331 'path': db_update_entry
1337 element_under_configuration
= nsr_id
1341 vnfr_id
= db_vnfr
["_id"]
1343 namespace
= "{nsi}.{ns}".format(
1344 nsi
=nsi_id
if nsi_id
else "",
1348 element_type
= 'VNF'
1349 element_under_configuration
= vnfr_id
1350 namespace
+= ".{}".format(vnfr_id
)
1352 namespace
+= ".{}-{}".format(vdu_id
, vdu_index
or 0)
1353 element_type
= 'VDU'
1354 element_under_configuration
= "{}-{}".format(vdu_id
, vdu_index
or 0)
1356 namespace
+= ".{}".format(kdu_name
)
1357 element_type
= 'KDU'
1358 element_under_configuration
= kdu_name
1361 artifact_path
= "{}/{}/charms/{}".format(
1362 base_folder
["folder"],
1363 base_folder
["pkg-dir"],
1364 config_descriptor
["juju"]["charm"]
1367 is_proxy_charm
= deep_get(config_descriptor
, ('juju', 'charm')) is not None
1368 if deep_get(config_descriptor
, ('juju', 'proxy')) is False:
1369 is_proxy_charm
= False
1371 # n2vc_redesign STEP 3.1
1373 # find old ee_id if exists
1374 ee_id
= vca_deployed
.get("ee_id")
1376 # create or register execution environment in VCA
1379 self
._write
_configuration
_status
(
1381 vca_index
=vca_index
,
1383 element_under_configuration
=element_under_configuration
,
1384 element_type
=element_type
1387 step
= "create execution environment"
1388 self
.logger
.debug(logging_text
+ step
)
1389 ee_id
, credentials
= await self
.n2vc
.create_execution_environment(namespace
=namespace
,
1394 step
= "Waiting to VM being up and getting IP address"
1395 self
.logger
.debug(logging_text
+ step
)
1396 rw_mgmt_ip
= await self
.wait_vm_up_insert_key_ro(logging_text
, nsr_id
, vnfr_id
, vdu_id
, vdu_index
,
1397 user
=None, pub_key
=None)
1398 credentials
= {"hostname": rw_mgmt_ip
}
1400 username
= deep_get(config_descriptor
, ("config-access", "ssh-access", "default-user"))
1401 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1402 # merged. Meanwhile let's get username from initial-config-primitive
1403 if not username
and config_descriptor
.get("initial-config-primitive"):
1404 for config_primitive
in config_descriptor
["initial-config-primitive"]:
1405 for param
in config_primitive
.get("parameter", ()):
1406 if param
["name"] == "ssh-username":
1407 username
= param
["value"]
1410 raise LcmException("Cannot determine the username neither with 'initial-config-promitive' nor with "
1411 "'config-access.ssh-access.default-user'")
1412 credentials
["username"] = username
1413 # n2vc_redesign STEP 3.2
1415 self
._write
_configuration
_status
(
1417 vca_index
=vca_index
,
1418 status
='REGISTERING',
1419 element_under_configuration
=element_under_configuration
,
1420 element_type
=element_type
1423 step
= "register execution environment {}".format(credentials
)
1424 self
.logger
.debug(logging_text
+ step
)
1425 ee_id
= await self
.n2vc
.register_execution_environment(credentials
=credentials
, namespace
=namespace
,
1428 # for compatibility with MON/POL modules, the need model and application name at database
1429 # TODO ask to N2VC instead of assuming the format "model_name.application_name"
1430 ee_id_parts
= ee_id
.split('.')
1431 model_name
= ee_id_parts
[0]
1432 application_name
= ee_id_parts
[1]
1433 db_nsr_update
= {db_update_entry
+ "model": model_name
,
1434 db_update_entry
+ "application": application_name
,
1435 db_update_entry
+ "ee_id": ee_id
}
1437 # n2vc_redesign STEP 3.3
1439 step
= "Install configuration Software"
1441 self
._write
_configuration
_status
(
1443 vca_index
=vca_index
,
1444 status
='INSTALLING SW',
1445 element_under_configuration
=element_under_configuration
,
1446 element_type
=element_type
,
1447 other_update
=db_nsr_update
1450 # TODO check if already done
1451 self
.logger
.debug(logging_text
+ step
)
1453 if not is_proxy_charm
:
1454 initial_config_primitive_list
= config_descriptor
.get('initial-config-primitive')
1455 if initial_config_primitive_list
:
1456 for primitive
in initial_config_primitive_list
:
1457 if primitive
["name"] == "config":
1458 config
= self
._map
_primitive
_params
(
1466 if element_type
== "NS":
1467 num_units
= db_nsr
.get("config-units") or 1
1468 elif element_type
== "VNF":
1469 num_units
= db_vnfr
.get("config-units") or 1
1470 elif element_type
== "VDU":
1471 for v
in db_vnfr
["vdur"]:
1472 if vdu_id
== v
["vdu-id-ref"]:
1473 num_units
= v
.get("config-units") or 1
1476 await self
.n2vc
.install_configuration_sw(
1478 artifact_path
=artifact_path
,
1484 # write in db flag of configuration_sw already installed
1485 self
.update_db_2("nsrs", nsr_id
, {db_update_entry
+ "config_sw_installed": True})
1487 # add relations for this VCA (wait for other peers related with this VCA)
1488 await self
._add
_vca
_relations
(logging_text
=logging_text
, nsr_id
=nsr_id
, vca_index
=vca_index
)
1490 # if SSH access is required, then get execution environment SSH public
1491 if is_proxy_charm
: # if native charm we have waited already to VM be UP
1494 if deep_get(config_descriptor
, ("config-access", "ssh-access", "required")):
1495 # Needed to inject a ssh key
1496 user
= deep_get(config_descriptor
, ("config-access", "ssh-access", "default-user"))
1497 step
= "Install configuration Software, getting public ssh key"
1498 pub_key
= await self
.n2vc
.get_ee_ssh_public__key(ee_id
=ee_id
, db_dict
=db_dict
)
1500 step
= "Insert public key into VM user={} ssh_key={}".format(user
, pub_key
)
1502 step
= "Waiting to VM being up and getting IP address"
1503 self
.logger
.debug(logging_text
+ step
)
1505 # n2vc_redesign STEP 5.1
1506 # wait for RO (ip-address) Insert pub_key into VM
1508 rw_mgmt_ip
= await self
.wait_vm_up_insert_key_ro(logging_text
, nsr_id
, vnfr_id
, vdu_id
, vdu_index
,
1509 user
=user
, pub_key
=pub_key
)
1511 rw_mgmt_ip
= None # This is for a NS configuration
1513 self
.logger
.debug(logging_text
+ ' VM_ip_address={}'.format(rw_mgmt_ip
))
1515 # store rw_mgmt_ip in deploy params for later replacement
1516 deploy_params
["rw_mgmt_ip"] = rw_mgmt_ip
1518 # n2vc_redesign STEP 6 Execute initial config primitive
1519 step
= 'execute initial config primitive'
1520 initial_config_primitive_list
= config_descriptor
.get('initial-config-primitive')
1522 # sort initial config primitives by 'seq'
1523 if initial_config_primitive_list
:
1525 initial_config_primitive_list
.sort(key
=lambda val
: int(val
['seq']))
1526 except Exception as e
:
1527 self
.logger
.error(logging_text
+ step
+ ": " + str(e
))
1529 self
.logger
.debug(logging_text
+ step
+ ": No initial-config-primitive")
1531 # add config if not present for NS charm
1532 initial_config_primitive_list
= self
._get
_initial
_config
_primitive
_list
(initial_config_primitive_list
,
1535 # wait for dependent primitives execution (NS -> VNF -> VDU)
1536 if initial_config_primitive_list
:
1537 await self
._wait
_dependent
_n
2vc
(nsr_id
, vca_deployed_list
, vca_index
)
1539 # stage, in function of element type: vdu, kdu, vnf or ns
1540 my_vca
= vca_deployed_list
[vca_index
]
1541 if my_vca
.get("vdu_id") or my_vca
.get("kdu_name"):
1543 stage
[0] = 'Stage 3/5: running Day-1 primitives for VDU.'
1544 elif my_vca
.get("member-vnf-index"):
1546 stage
[0] = 'Stage 4/5: running Day-1 primitives for VNF.'
1549 stage
[0] = 'Stage 5/5: running Day-1 primitives for NS.'
1551 self
._write
_configuration
_status
(
1553 vca_index
=vca_index
,
1554 status
='EXECUTING PRIMITIVE'
1557 self
._write
_op
_status
(
1562 check_if_terminated_needed
= True
1563 for initial_config_primitive
in initial_config_primitive_list
:
1564 # adding information on the vca_deployed if it is a NS execution environment
1565 if not vca_deployed
["member-vnf-index"]:
1566 deploy_params
["ns_config_info"] = json
.dumps(self
._get
_ns
_config
_info
(nsr_id
))
1567 # TODO check if already done
1568 primitive_params_
= self
._map
_primitive
_params
(initial_config_primitive
, {}, deploy_params
)
1570 step
= "execute primitive '{}' params '{}'".format(initial_config_primitive
["name"], primitive_params_
)
1571 self
.logger
.debug(logging_text
+ step
)
1572 await self
.n2vc
.exec_primitive(
1574 primitive_name
=initial_config_primitive
["name"],
1575 params_dict
=primitive_params_
,
1578 # Once some primitive has been exec, check and write at db if it needs to exec terminated primitives
1579 if check_if_terminated_needed
:
1580 if config_descriptor
.get('terminate-config-primitive'):
1581 self
.update_db_2("nsrs", nsr_id
, {db_update_entry
+ "needed_terminate": True})
1582 check_if_terminated_needed
= False
1584 # TODO register in database that primitive is done
1586 step
= "instantiated at VCA"
1587 self
.logger
.debug(logging_text
+ step
)
1589 self
._write
_configuration
_status
(
1591 vca_index
=vca_index
,
1595 except Exception as e
: # TODO not use Exception but N2VC exception
1596 # self.update_db_2("nsrs", nsr_id, {db_update_entry + "instantiation": "FAILED"})
1597 if not isinstance(e
, (DbException
, N2VCException
, LcmException
, asyncio
.CancelledError
)):
1598 self
.logger
.error("Exception while {} : {}".format(step
, e
), exc_info
=True)
1599 self
._write
_configuration
_status
(
1601 vca_index
=vca_index
,
1604 raise LcmException("{} {}".format(step
, e
)) from e
1606 def _write_ns_status(self
, nsr_id
: str, ns_state
: str, current_operation
: str, current_operation_id
: str,
1607 error_description
: str = None, error_detail
: str = None, other_update
: dict = None):
1609 Update db_nsr fields.
1612 :param current_operation:
1613 :param current_operation_id:
1614 :param error_description:
1615 :param error_detail:
1616 :param other_update: Other required changes at database if provided, will be cleared
1620 db_dict
= other_update
or {}
1621 db_dict
["_admin.nslcmop"] = current_operation_id
# for backward compatibility
1622 db_dict
["_admin.current-operation"] = current_operation_id
1623 db_dict
["_admin.operation-type"] = current_operation
if current_operation
!= "IDLE" else None
1624 db_dict
["currentOperation"] = current_operation
1625 db_dict
["currentOperationID"] = current_operation_id
1626 db_dict
["errorDescription"] = error_description
1627 db_dict
["errorDetail"] = error_detail
1630 db_dict
["nsState"] = ns_state
1631 self
.update_db_2("nsrs", nsr_id
, db_dict
)
1632 except DbException
as e
:
1633 self
.logger
.warn('Error writing NS status, ns={}: {}'.format(nsr_id
, e
))
1635 def _write_op_status(self
, op_id
: str, stage
: list = None, error_message
: str = None, queuePosition
: int = 0,
1636 operation_state
: str = None, other_update
: dict = None):
1638 db_dict
= other_update
or {}
1639 db_dict
['queuePosition'] = queuePosition
1640 if isinstance(stage
, list):
1641 db_dict
['stage'] = stage
[0]
1642 db_dict
['detailed-status'] = " ".join(stage
)
1643 elif stage
is not None:
1644 db_dict
['stage'] = str(stage
)
1646 if error_message
is not None:
1647 db_dict
['errorMessage'] = error_message
1648 if operation_state
is not None:
1649 db_dict
['operationState'] = operation_state
1650 db_dict
["statusEnteredTime"] = time()
1651 self
.update_db_2("nslcmops", op_id
, db_dict
)
1652 except DbException
as e
:
1653 self
.logger
.warn('Error writing OPERATION status for op_id: {} -> {}'.format(op_id
, e
))
1655 def _write_all_config_status(self
, db_nsr
: dict, status
: str):
1657 nsr_id
= db_nsr
["_id"]
1658 # configurationStatus
1659 config_status
= db_nsr
.get('configurationStatus')
1661 db_nsr_update
= {"configurationStatus.{}.status".format(index
): status
for index
, v
in
1662 enumerate(config_status
) if v
}
1664 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1666 except DbException
as e
:
1667 self
.logger
.warn('Error writing all configuration status, ns={}: {}'.format(nsr_id
, e
))
1669 def _write_configuration_status(self
, nsr_id
: str, vca_index
: int, status
: str = None,
1670 element_under_configuration
: str = None, element_type
: str = None,
1671 other_update
: dict = None):
1673 # self.logger.debug('_write_configuration_status(): vca_index={}, status={}'
1674 # .format(vca_index, status))
1677 db_path
= 'configurationStatus.{}.'.format(vca_index
)
1678 db_dict
= other_update
or {}
1680 db_dict
[db_path
+ 'status'] = status
1681 if element_under_configuration
:
1682 db_dict
[db_path
+ 'elementUnderConfiguration'] = element_under_configuration
1684 db_dict
[db_path
+ 'elementType'] = element_type
1685 self
.update_db_2("nsrs", nsr_id
, db_dict
)
1686 except DbException
as e
:
1687 self
.logger
.warn('Error writing configuration status={}, ns={}, vca_index={}: {}'
1688 .format(status
, nsr_id
, vca_index
, e
))
1690 async def _do_placement(self
, logging_text
, db_nslcmop
, db_vnfrs
):
1692 Check and computes the placement, (vim account where to deploy). If it is decided by an external tool, it
1693 sends the request via kafka and wait until the result is wrote at database (nslcmops _admin.plca).
1694 Database is used because the result can be obtained from a different LCM worker in case of HA.
1695 :param logging_text: contains the prefix for logging, with the ns and nslcmop identifiers
1696 :param db_nslcmop: database content of nslcmop
1697 :param db_vnfrs: database content of vnfrs, indexed by member-vnf-index.
1698 :return: True if some modification is done. Modifies database vnfrs and parameter db_vnfr with the
1699 computed 'vim-account-id'
1702 nslcmop_id
= db_nslcmop
['_id']
1703 placement_engine
= deep_get(db_nslcmop
, ('operationParams', 'placement-engine'))
1704 if placement_engine
== "PLA":
1705 self
.logger
.debug(logging_text
+ "Invoke and wait for placement optimization")
1706 await self
.msg
.aiowrite("pla", "get_placement", {'nslcmopId': nslcmop_id
}, loop
=self
.loop
)
1707 db_poll_interval
= 5
1708 wait
= db_poll_interval
* 10
1710 while not pla_result
and wait
>= 0:
1711 await asyncio
.sleep(db_poll_interval
)
1712 wait
-= db_poll_interval
1713 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1714 pla_result
= deep_get(db_nslcmop
, ('_admin', 'pla'))
1717 raise LcmException("Placement timeout for nslcmopId={}".format(nslcmop_id
))
1719 for pla_vnf
in pla_result
['vnf']:
1720 vnfr
= db_vnfrs
.get(pla_vnf
['member-vnf-index'])
1721 if not pla_vnf
.get('vimAccountId') or not vnfr
:
1724 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, {"vim-account-id": pla_vnf
['vimAccountId']})
1726 vnfr
["vim-account-id"] = pla_vnf
['vimAccountId']
1729 def update_nsrs_with_pla_result(self
, params
):
1731 nslcmop_id
= deep_get(params
, ('placement', 'nslcmopId'))
1732 self
.update_db_2("nslcmops", nslcmop_id
, {"_admin.pla": params
.get('placement')})
1733 except Exception as e
:
1734 self
.logger
.warn('Update failed for nslcmop_id={}:{}'.format(nslcmop_id
, e
))
1736 async def instantiate(self
, nsr_id
, nslcmop_id
):
1739 :param nsr_id: ns instance to deploy
1740 :param nslcmop_id: operation to run
1744 # Try to lock HA task here
1745 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
1746 if not task_is_locked_by_me
:
1747 self
.logger
.debug('instantiate() task is not locked by me, ns={}'.format(nsr_id
))
1750 logging_text
= "Task ns={} instantiate={} ".format(nsr_id
, nslcmop_id
)
1751 self
.logger
.debug(logging_text
+ "Enter")
1756 # get all needed from database
1758 # database nsrs record
1761 # database nslcmops record
1764 # update operation on nsrs
1766 # update operation on nslcmops
1767 db_nslcmop_update
= {}
1769 nslcmop_operation_state
= None
1770 db_vnfrs
= {} # vnf's info indexed by member-index
1772 tasks_dict_info
= {} # from task to info text
1775 stage
= ['Stage 1/5: preparation of the environment.', "Waiting for previous operations to terminate.", ""]
1776 # ^ stage, step, VIM progress
1778 # wait for any previous tasks in process
1779 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
1781 # STEP 0: Reading database (nslcmops, nsrs, nsds, vnfrs, vnfds)
1782 stage
[1] = "Reading from database,"
1783 # nsState="BUILDING", currentOperation="INSTANTIATING", currentOperationID=nslcmop_id
1784 db_nsr_update
["detailed-status"] = "creating"
1785 db_nsr_update
["operational-status"] = "init"
1786 self
._write
_ns
_status
(
1788 ns_state
="BUILDING",
1789 current_operation
="INSTANTIATING",
1790 current_operation_id
=nslcmop_id
,
1791 other_update
=db_nsr_update
1793 self
._write
_op
_status
(
1799 # read from db: operation
1800 stage
[1] = "Getting nslcmop={} from db".format(nslcmop_id
)
1801 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1802 ns_params
= db_nslcmop
.get("operationParams")
1803 if ns_params
and ns_params
.get("timeout_ns_deploy"):
1804 timeout_ns_deploy
= ns_params
["timeout_ns_deploy"]
1806 timeout_ns_deploy
= self
.timeout
.get("ns_deploy", self
.timeout_ns_deploy
)
1809 stage
[1] = "Getting nsr={} from db".format(nsr_id
)
1810 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1811 stage
[1] = "Getting nsd={} from db".format(db_nsr
["nsd-id"])
1812 nsd
= self
.db
.get_one("nsds", {"_id": db_nsr
["nsd-id"]})
1814 # nsr_name = db_nsr["name"] # TODO short-name??
1816 # read from db: vnf's of this ns
1817 stage
[1] = "Getting vnfrs from db"
1818 self
.logger
.debug(logging_text
+ stage
[1])
1819 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1821 # read from db: vnfd's for every vnf
1822 db_vnfds_ref
= {} # every vnfd data indexed by vnf name
1823 db_vnfds
= {} # every vnfd data indexed by vnf id
1824 db_vnfds_index
= {} # every vnfd data indexed by vnf member-index
1826 # for each vnf in ns, read vnfd
1827 for vnfr
in db_vnfrs_list
:
1828 db_vnfrs
[vnfr
["member-vnf-index-ref"]] = vnfr
# vnf's dict indexed by member-index: '1', '2', etc
1829 vnfd_id
= vnfr
["vnfd-id"] # vnfd uuid for this vnf
1830 vnfd_ref
= vnfr
["vnfd-ref"] # vnfd name for this vnf
1831 # if we haven't this vnfd, read it from db
1832 if vnfd_id
not in db_vnfds
:
1834 stage
[1] = "Getting vnfd={} id='{}' from db".format(vnfd_id
, vnfd_ref
)
1835 self
.logger
.debug(logging_text
+ stage
[1])
1836 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
1839 db_vnfds_ref
[vnfd_ref
] = vnfd
# vnfd's indexed by name
1840 db_vnfds
[vnfd_id
] = vnfd
# vnfd's indexed by id
1841 db_vnfds_index
[vnfr
["member-vnf-index-ref"]] = db_vnfds
[vnfd_id
] # vnfd's indexed by member-index
1843 # Get or generates the _admin.deployed.VCA list
1844 vca_deployed_list
= None
1845 if db_nsr
["_admin"].get("deployed"):
1846 vca_deployed_list
= db_nsr
["_admin"]["deployed"].get("VCA")
1847 if vca_deployed_list
is None:
1848 vca_deployed_list
= []
1849 configuration_status_list
= []
1850 db_nsr_update
["_admin.deployed.VCA"] = vca_deployed_list
1851 db_nsr_update
["configurationStatus"] = configuration_status_list
1852 # add _admin.deployed.VCA to db_nsr dictionary, value=vca_deployed_list
1853 populate_dict(db_nsr
, ("_admin", "deployed", "VCA"), vca_deployed_list
)
1854 elif isinstance(vca_deployed_list
, dict):
1855 # maintain backward compatibility. Change a dict to list at database
1856 vca_deployed_list
= list(vca_deployed_list
.values())
1857 db_nsr_update
["_admin.deployed.VCA"] = vca_deployed_list
1858 populate_dict(db_nsr
, ("_admin", "deployed", "VCA"), vca_deployed_list
)
1860 if not isinstance(deep_get(db_nsr
, ("_admin", "deployed", "RO", "vnfd")), list):
1861 populate_dict(db_nsr
, ("_admin", "deployed", "RO", "vnfd"), [])
1862 db_nsr_update
["_admin.deployed.RO.vnfd"] = []
1864 # set state to INSTANTIATED. When instantiated NBI will not delete directly
1865 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1866 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1868 # n2vc_redesign STEP 2 Deploy Network Scenario
1869 stage
[0] = 'Stage 2/5: deployment of KDUs, VMs and execution environments.'
1870 self
._write
_op
_status
(
1875 stage
[1] = "Deploying KDUs,"
1876 # self.logger.debug(logging_text + "Before deploy_kdus")
1877 # Call to deploy_kdus in case exists the "vdu:kdu" param
1878 await self
.deploy_kdus(
1879 logging_text
=logging_text
,
1881 nslcmop_id
=nslcmop_id
,
1884 task_instantiation_info
=tasks_dict_info
,
1887 stage
[1] = "Getting VCA public key."
1888 # n2vc_redesign STEP 1 Get VCA public ssh-key
1889 # feature 1429. Add n2vc public key to needed VMs
1890 n2vc_key
= self
.n2vc
.get_public_key()
1891 n2vc_key_list
= [n2vc_key
]
1892 if self
.vca_config
.get("public_key"):
1893 n2vc_key_list
.append(self
.vca_config
["public_key"])
1895 stage
[1] = "Deploying NS at VIM."
1896 task_ro
= asyncio
.ensure_future(
1897 self
.instantiate_RO(
1898 logging_text
=logging_text
,
1902 db_nslcmop
=db_nslcmop
,
1904 db_vnfds_ref
=db_vnfds_ref
,
1905 n2vc_key_list
=n2vc_key_list
,
1909 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_RO", task_ro
)
1910 tasks_dict_info
[task_ro
] = "Deploying at VIM"
1912 # n2vc_redesign STEP 3 to 6 Deploy N2VC
1913 stage
[1] = "Deploying Execution Environments."
1914 self
.logger
.debug(logging_text
+ stage
[1])
1916 nsi_id
= None # TODO put nsi_id when this nsr belongs to a NSI
1917 # get_iterable() returns a value from a dict or empty tuple if key does not exist
1918 for c_vnf
in get_iterable(nsd
, "constituent-vnfd"):
1919 vnfd_id
= c_vnf
["vnfd-id-ref"]
1920 vnfd
= db_vnfds_ref
[vnfd_id
]
1921 member_vnf_index
= str(c_vnf
["member-vnf-index"])
1922 db_vnfr
= db_vnfrs
[member_vnf_index
]
1923 base_folder
= vnfd
["_admin"]["storage"]
1929 # Get additional parameters
1931 if db_vnfr
.get("additionalParamsForVnf"):
1932 deploy_params
= self
._format
_additional
_params
(db_vnfr
["additionalParamsForVnf"].copy())
1934 descriptor_config
= vnfd
.get("vnf-configuration")
1935 if descriptor_config
and descriptor_config
.get("juju"):
1937 logging_text
=logging_text
+ "member_vnf_index={} ".format(member_vnf_index
),
1940 nslcmop_id
=nslcmop_id
,
1946 member_vnf_index
=member_vnf_index
,
1947 vdu_index
=vdu_index
,
1949 deploy_params
=deploy_params
,
1950 descriptor_config
=descriptor_config
,
1951 base_folder
=base_folder
,
1952 task_instantiation_info
=tasks_dict_info
,
1956 # Deploy charms for each VDU that supports one.
1957 for vdud
in get_iterable(vnfd
, 'vdu'):
1959 descriptor_config
= vdud
.get('vdu-configuration')
1960 vdur
= next((x
for x
in db_vnfr
["vdur"] if x
["vdu-id-ref"] == vdu_id
), None)
1961 if vdur
.get("additionalParams"):
1962 deploy_params_vdu
= self
._format
_additional
_params
(vdur
["additionalParams"])
1964 deploy_params_vdu
= deploy_params
1965 if descriptor_config
and descriptor_config
.get("juju"):
1966 # look for vdu index in the db_vnfr["vdu"] section
1967 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
1968 # if vdur["vdu-id-ref"] == vdu_id:
1971 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
1972 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
1973 # vdu_name = vdur.get("name")
1976 for vdu_index
in range(int(vdud
.get("count", 1))):
1977 # TODO vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
1979 logging_text
=logging_text
+ "member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
1980 member_vnf_index
, vdu_id
, vdu_index
),
1983 nslcmop_id
=nslcmop_id
,
1989 member_vnf_index
=member_vnf_index
,
1990 vdu_index
=vdu_index
,
1992 deploy_params
=deploy_params_vdu
,
1993 descriptor_config
=descriptor_config
,
1994 base_folder
=base_folder
,
1995 task_instantiation_info
=tasks_dict_info
,
1998 for kdud
in get_iterable(vnfd
, 'kdu'):
1999 kdu_name
= kdud
["name"]
2000 descriptor_config
= kdud
.get('kdu-configuration')
2001 if descriptor_config
and descriptor_config
.get("juju"):
2005 # look for vdu index in the db_vnfr["vdu"] section
2006 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
2007 # if vdur["vdu-id-ref"] == vdu_id:
2010 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
2011 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
2012 # vdu_name = vdur.get("name")
2016 logging_text
=logging_text
,
2019 nslcmop_id
=nslcmop_id
,
2025 member_vnf_index
=member_vnf_index
,
2026 vdu_index
=vdu_index
,
2028 deploy_params
=deploy_params
,
2029 descriptor_config
=descriptor_config
,
2030 base_folder
=base_folder
,
2031 task_instantiation_info
=tasks_dict_info
,
2035 # Check if this NS has a charm configuration
2036 descriptor_config
= nsd
.get("ns-configuration")
2037 if descriptor_config
and descriptor_config
.get("juju"):
2040 member_vnf_index
= None
2046 # Get additional parameters
2048 if db_nsr
.get("additionalParamsForNs"):
2049 deploy_params
= self
._format
_additional
_params
(db_nsr
["additionalParamsForNs"].copy())
2050 base_folder
= nsd
["_admin"]["storage"]
2052 logging_text
=logging_text
,
2055 nslcmop_id
=nslcmop_id
,
2061 member_vnf_index
=member_vnf_index
,
2062 vdu_index
=vdu_index
,
2064 deploy_params
=deploy_params
,
2065 descriptor_config
=descriptor_config
,
2066 base_folder
=base_folder
,
2067 task_instantiation_info
=tasks_dict_info
,
2071 # rest of staff will be done at finally
2073 except (ROclient
.ROClientException
, DbException
, LcmException
, N2VCException
) as e
:
2074 self
.logger
.error(logging_text
+ "Exit Exception while '{}': {}".format(stage
[1], e
))
2076 except asyncio
.CancelledError
:
2077 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(stage
[1]))
2078 exc
= "Operation was cancelled"
2079 except Exception as e
:
2080 exc
= traceback
.format_exc()
2081 self
.logger
.critical(logging_text
+ "Exit Exception while '{}': {}".format(stage
[1], e
), exc_info
=True)
2084 error_list
.append(str(exc
))
2086 # wait for pending tasks
2088 stage
[1] = "Waiting for instantiate pending tasks."
2089 self
.logger
.debug(logging_text
+ stage
[1])
2090 error_list
+= await self
._wait
_for
_tasks
(logging_text
, tasks_dict_info
, timeout_ns_deploy
,
2091 stage
, nslcmop_id
, nsr_id
=nsr_id
)
2092 stage
[1] = stage
[2] = ""
2093 except asyncio
.CancelledError
:
2094 error_list
.append("Cancelled")
2095 # TODO cancel all tasks
2096 except Exception as exc
:
2097 error_list
.append(str(exc
))
2099 # update operation-status
2100 db_nsr_update
["operational-status"] = "running"
2101 # let's begin with VCA 'configured' status (later we can change it)
2102 db_nsr_update
["config-status"] = "configured"
2103 for task
, task_name
in tasks_dict_info
.items():
2104 if not task
.done() or task
.cancelled() or task
.exception():
2105 if task_name
.startswith(self
.task_name_deploy_vca
):
2106 # A N2VC task is pending
2107 db_nsr_update
["config-status"] = "failed"
2109 # RO or KDU task is pending
2110 db_nsr_update
["operational-status"] = "failed"
2112 # update status at database
2114 error_detail
= ". ".join(error_list
)
2115 self
.logger
.error(logging_text
+ error_detail
)
2116 error_description_nslcmop
= 'Stage: {}. Detail: {}'.format(stage
[0], error_detail
)
2117 error_description_nsr
= 'Operation: INSTANTIATING.{}, Stage {}'.format(nslcmop_id
, stage
[0])
2119 db_nsr_update
["detailed-status"] = error_description_nsr
+ " Detail: " + error_detail
2120 db_nslcmop_update
["detailed-status"] = error_detail
2121 nslcmop_operation_state
= "FAILED"
2125 error_description_nsr
= error_description_nslcmop
= None
2127 db_nsr_update
["detailed-status"] = "Done"
2128 db_nslcmop_update
["detailed-status"] = "Done"
2129 nslcmop_operation_state
= "COMPLETED"
2132 self
._write
_ns
_status
(
2135 current_operation
="IDLE",
2136 current_operation_id
=None,
2137 error_description
=error_description_nsr
,
2138 error_detail
=error_detail
,
2139 other_update
=db_nsr_update
2141 self
._write
_op
_status
(
2144 error_message
=error_description_nslcmop
,
2145 operation_state
=nslcmop_operation_state
,
2146 other_update
=db_nslcmop_update
,
2149 if nslcmop_operation_state
:
2151 await self
.msg
.aiowrite("ns", "instantiated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2152 "operationState": nslcmop_operation_state
},
2154 except Exception as e
:
2155 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
2157 self
.logger
.debug(logging_text
+ "Exit")
2158 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_instantiate")
2160 async def _add_vca_relations(self
, logging_text
, nsr_id
, vca_index
: int, timeout
: int = 3600) -> bool:
2163 # 1. find all relations for this VCA
2164 # 2. wait for other peers related
2169 # STEP 1: find all relations for this VCA
2172 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2173 nsd
= self
.db
.get_one("nsds", {"_id": db_nsr
["nsd-id"]})
2176 my_vca
= deep_get(db_nsr
, ('_admin', 'deployed', 'VCA'))[vca_index
]
2178 # read all ns-configuration relations
2179 ns_relations
= list()
2180 db_ns_relations
= deep_get(nsd
, ('ns-configuration', 'relation'))
2182 for r
in db_ns_relations
:
2183 # check if this VCA is in the relation
2184 if my_vca
.get('member-vnf-index') in\
2185 (r
.get('entities')[0].get('id'), r
.get('entities')[1].get('id')):
2186 ns_relations
.append(r
)
2188 # read all vnf-configuration relations
2189 vnf_relations
= list()
2190 db_vnfd_list
= db_nsr
.get('vnfd-id')
2192 for vnfd
in db_vnfd_list
:
2193 db_vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd
})
2194 db_vnf_relations
= deep_get(db_vnfd
, ('vnf-configuration', 'relation'))
2195 if db_vnf_relations
:
2196 for r
in db_vnf_relations
:
2197 # check if this VCA is in the relation
2198 if my_vca
.get('vdu_id') in (r
.get('entities')[0].get('id'), r
.get('entities')[1].get('id')):
2199 vnf_relations
.append(r
)
2201 # if no relations, terminate
2202 if not ns_relations
and not vnf_relations
:
2203 self
.logger
.debug(logging_text
+ ' No relations')
2206 self
.logger
.debug(logging_text
+ ' adding relations\n {}\n {}'.format(ns_relations
, vnf_relations
))
2213 if now
- start
>= timeout
:
2214 self
.logger
.error(logging_text
+ ' : timeout adding relations')
2217 # reload nsr from database (we need to update record: _admin.deloyed.VCA)
2218 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2220 # for each defined NS relation, find the VCA's related
2221 for r
in ns_relations
:
2222 from_vca_ee_id
= None
2224 from_vca_endpoint
= None
2225 to_vca_endpoint
= None
2226 vca_list
= deep_get(db_nsr
, ('_admin', 'deployed', 'VCA'))
2227 for vca
in vca_list
:
2228 if vca
.get('member-vnf-index') == r
.get('entities')[0].get('id') \
2229 and vca
.get('config_sw_installed'):
2230 from_vca_ee_id
= vca
.get('ee_id')
2231 from_vca_endpoint
= r
.get('entities')[0].get('endpoint')
2232 if vca
.get('member-vnf-index') == r
.get('entities')[1].get('id') \
2233 and vca
.get('config_sw_installed'):
2234 to_vca_ee_id
= vca
.get('ee_id')
2235 to_vca_endpoint
= r
.get('entities')[1].get('endpoint')
2236 if from_vca_ee_id
and to_vca_ee_id
:
2238 await self
.n2vc
.add_relation(
2239 ee_id_1
=from_vca_ee_id
,
2240 ee_id_2
=to_vca_ee_id
,
2241 endpoint_1
=from_vca_endpoint
,
2242 endpoint_2
=to_vca_endpoint
)
2243 # remove entry from relations list
2244 ns_relations
.remove(r
)
2246 # check failed peers
2248 vca_status_list
= db_nsr
.get('configurationStatus')
2250 for i
in range(len(vca_list
)):
2252 vca_status
= vca_status_list
[i
]
2253 if vca
.get('member-vnf-index') == r
.get('entities')[0].get('id'):
2254 if vca_status
.get('status') == 'BROKEN':
2255 # peer broken: remove relation from list
2256 ns_relations
.remove(r
)
2257 if vca
.get('member-vnf-index') == r
.get('entities')[1].get('id'):
2258 if vca_status
.get('status') == 'BROKEN':
2259 # peer broken: remove relation from list
2260 ns_relations
.remove(r
)
2265 # for each defined VNF relation, find the VCA's related
2266 for r
in vnf_relations
:
2267 from_vca_ee_id
= None
2269 from_vca_endpoint
= None
2270 to_vca_endpoint
= None
2271 vca_list
= deep_get(db_nsr
, ('_admin', 'deployed', 'VCA'))
2272 for vca
in vca_list
:
2273 if vca
.get('vdu_id') == r
.get('entities')[0].get('id') and vca
.get('config_sw_installed'):
2274 from_vca_ee_id
= vca
.get('ee_id')
2275 from_vca_endpoint
= r
.get('entities')[0].get('endpoint')
2276 if vca
.get('vdu_id') == r
.get('entities')[1].get('id') and vca
.get('config_sw_installed'):
2277 to_vca_ee_id
= vca
.get('ee_id')
2278 to_vca_endpoint
= r
.get('entities')[1].get('endpoint')
2279 if from_vca_ee_id
and to_vca_ee_id
:
2281 await self
.n2vc
.add_relation(
2282 ee_id_1
=from_vca_ee_id
,
2283 ee_id_2
=to_vca_ee_id
,
2284 endpoint_1
=from_vca_endpoint
,
2285 endpoint_2
=to_vca_endpoint
)
2286 # remove entry from relations list
2287 vnf_relations
.remove(r
)
2289 # check failed peers
2291 vca_status_list
= db_nsr
.get('configurationStatus')
2293 for i
in range(len(vca_list
)):
2295 vca_status
= vca_status_list
[i
]
2296 if vca
.get('vdu_id') == r
.get('entities')[0].get('id'):
2297 if vca_status
.get('status') == 'BROKEN':
2298 # peer broken: remove relation from list
2299 ns_relations
.remove(r
)
2300 if vca
.get('vdu_id') == r
.get('entities')[1].get('id'):
2301 if vca_status
.get('status') == 'BROKEN':
2302 # peer broken: remove relation from list
2303 ns_relations
.remove(r
)
2309 await asyncio
.sleep(5.0)
2311 if not ns_relations
and not vnf_relations
:
2312 self
.logger
.debug('Relations added')
2317 except Exception as e
:
2318 self
.logger
.warn(logging_text
+ ' ERROR adding relations: {}'.format(e
))
2321 def _write_db_callback(self
, task
, item
, _id
, on_done
=None, on_exc
=None):
2323 callback for kdu install intended to store the returned kdu_instance at database
2328 result
= task
.result()
2330 db_update
[on_done
] = str(result
)
2331 except Exception as e
:
2333 db_update
[on_exc
] = str(e
)
2336 self
.update_db_2(item
, _id
, db_update
)
2340 async def deploy_kdus(self
, logging_text
, nsr_id
, nslcmop_id
, db_vnfrs
, db_vnfds
, task_instantiation_info
):
2341 # Launch kdus if present in the descriptor
2343 k8scluster_id_2_uuic
= {"helm-chart": {}, "juju-bundle": {}}
2345 def _get_cluster_id(cluster_id
, cluster_type
):
2346 nonlocal k8scluster_id_2_uuic
2347 if cluster_id
in k8scluster_id_2_uuic
[cluster_type
]:
2348 return k8scluster_id_2_uuic
[cluster_type
][cluster_id
]
2350 db_k8scluster
= self
.db
.get_one("k8sclusters", {"_id": cluster_id
}, fail_on_empty
=False)
2351 if not db_k8scluster
:
2352 raise LcmException("K8s cluster {} cannot be found".format(cluster_id
))
2353 k8s_id
= deep_get(db_k8scluster
, ("_admin", cluster_type
, "id"))
2355 raise LcmException("K8s cluster '{}' has not been initilized for '{}'".format(cluster_id
, cluster_type
))
2356 k8scluster_id_2_uuic
[cluster_type
][cluster_id
] = k8s_id
2359 logging_text
+= "Deploy kdus: "
2362 db_nsr_update
= {"_admin.deployed.K8s": []}
2363 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2366 updated_cluster_list
= []
2368 for vnfr_data
in db_vnfrs
.values():
2369 for kdur
in get_iterable(vnfr_data
, "kdur"):
2370 desc_params
= self
._format
_additional
_params
(kdur
.get("additionalParams"))
2371 vnfd_id
= vnfr_data
.get('vnfd-id')
2372 namespace
= kdur
.get("k8s-namespace")
2373 if kdur
.get("helm-chart"):
2374 kdumodel
= kdur
["helm-chart"]
2375 k8sclustertype
= "helm-chart"
2376 elif kdur
.get("juju-bundle"):
2377 kdumodel
= kdur
["juju-bundle"]
2378 k8sclustertype
= "juju-bundle"
2380 raise LcmException("kdu type for kdu='{}.{}' is neither helm-chart nor "
2381 "juju-bundle. Maybe an old NBI version is running".
2382 format(vnfr_data
["member-vnf-index-ref"], kdur
["kdu-name"]))
2383 # check if kdumodel is a file and exists
2385 storage
= deep_get(db_vnfds
.get(vnfd_id
), ('_admin', 'storage'))
2386 if storage
and storage
.get('pkg-dir'): # may be not present if vnfd has not artifacts
2387 # path format: /vnfdid/pkkdir/helm-charts|juju-bundles/kdumodel
2388 filename
= '{}/{}/{}s/{}'.format(storage
["folder"], storage
["pkg-dir"], k8sclustertype
,
2390 if self
.fs
.file_exists(filename
, mode
='file') or self
.fs
.file_exists(filename
, mode
='dir'):
2391 kdumodel
= self
.fs
.path
+ filename
2392 except (asyncio
.TimeoutError
, asyncio
.CancelledError
):
2394 except Exception: # it is not a file
2397 k8s_cluster_id
= kdur
["k8s-cluster"]["id"]
2398 step
= "Synchronize repos for k8s cluster '{}'".format(k8s_cluster_id
)
2399 cluster_uuid
= _get_cluster_id(k8s_cluster_id
, k8sclustertype
)
2401 if k8sclustertype
== "helm-chart" and cluster_uuid
not in updated_cluster_list
:
2402 del_repo_list
, added_repo_dict
= await asyncio
.ensure_future(
2403 self
.k8sclusterhelm
.synchronize_repos(cluster_uuid
=cluster_uuid
))
2404 if del_repo_list
or added_repo_dict
:
2405 unset
= {'_admin.helm_charts_added.' + item
: None for item
in del_repo_list
}
2406 updated
= {'_admin.helm_charts_added.' +
2407 item
: name
for item
, name
in added_repo_dict
.items()}
2408 self
.logger
.debug(logging_text
+ "repos synchronized on k8s cluster '{}' to_delete: {}, "
2409 "to_add: {}".format(k8s_cluster_id
, del_repo_list
,
2411 self
.db
.set_one("k8sclusters", {"_id": k8s_cluster_id
}, updated
, unset
=unset
)
2412 updated_cluster_list
.append(cluster_uuid
)
2414 step
= "Instantiating KDU {}.{} in k8s cluster {}".format(vnfr_data
["member-vnf-index-ref"],
2415 kdur
["kdu-name"], k8s_cluster_id
)
2417 k8s_instace_info
= {"kdu-instance": None,
2418 "k8scluster-uuid": cluster_uuid
,
2419 "k8scluster-type": k8sclustertype
,
2420 "member-vnf-index": vnfr_data
["member-vnf-index-ref"],
2421 "kdu-name": kdur
["kdu-name"],
2422 "kdu-model": kdumodel
,
2423 "namespace": namespace
}
2424 db_path
= "_admin.deployed.K8s.{}".format(index
)
2425 db_nsr_update
[db_path
] = k8s_instace_info
2426 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2428 db_dict
= {"collection": "nsrs",
2429 "filter": {"_id": nsr_id
},
2432 task
= asyncio
.ensure_future(
2433 self
.k8scluster_map
[k8sclustertype
].install(cluster_uuid
=cluster_uuid
, kdu_model
=kdumodel
,
2434 atomic
=True, params
=desc_params
,
2435 db_dict
=db_dict
, timeout
=600,
2436 kdu_name
=kdur
["kdu-name"], namespace
=namespace
))
2438 task
.add_done_callback(partial(self
._write
_db
_callback
, item
="nsrs", _id
=nsr_id
,
2439 on_done
=db_path
+ ".kdu-instance",
2440 on_exc
=db_path
+ ".detailed-status"))
2441 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_KDU-{}".format(index
), task
)
2442 task_instantiation_info
[task
] = "Deploying KDU {}".format(kdur
["kdu-name"])
2446 except (LcmException
, asyncio
.CancelledError
):
2448 except Exception as e
:
2449 msg
= "Exception {} while {}: {}".format(type(e
).__name
__, step
, e
)
2450 if isinstance(e
, (N2VCException
, DbException
)):
2451 self
.logger
.error(logging_text
+ msg
)
2453 self
.logger
.critical(logging_text
+ msg
, exc_info
=True)
2454 raise LcmException(msg
)
2457 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2459 def _deploy_n2vc(self
, logging_text
, db_nsr
, db_vnfr
, nslcmop_id
, nsr_id
, nsi_id
, vnfd_id
, vdu_id
,
2460 kdu_name
, member_vnf_index
, vdu_index
, vdu_name
, deploy_params
, descriptor_config
,
2461 base_folder
, task_instantiation_info
, stage
):
2462 # launch instantiate_N2VC in a asyncio task and register task object
2463 # Look where information of this charm is at database <nsrs>._admin.deployed.VCA
2464 # if not found, create one entry and update database
2466 # fill db_nsr._admin.deployed.VCA.<index>
2468 for vca_index
, vca_deployed
in enumerate(db_nsr
["_admin"]["deployed"]["VCA"]):
2469 if not vca_deployed
:
2471 if vca_deployed
.get("member-vnf-index") == member_vnf_index
and \
2472 vca_deployed
.get("vdu_id") == vdu_id
and \
2473 vca_deployed
.get("kdu_name") == kdu_name
and \
2474 vca_deployed
.get("vdu_count_index", 0) == vdu_index
:
2477 # not found, create one.
2479 "member-vnf-index": member_vnf_index
,
2481 "kdu_name": kdu_name
,
2482 "vdu_count_index": vdu_index
,
2483 "operational-status": "init", # TODO revise
2484 "detailed-status": "", # TODO revise
2485 "step": "initial-deploy", # TODO revise
2487 "vdu_name": vdu_name
,
2491 # create VCA and configurationStatus in db
2493 "_admin.deployed.VCA.{}".format(vca_index
): vca_deployed
,
2494 "configurationStatus.{}".format(vca_index
): dict()
2496 self
.update_db_2("nsrs", nsr_id
, db_dict
)
2498 db_nsr
["_admin"]["deployed"]["VCA"].append(vca_deployed
)
2501 task_n2vc
= asyncio
.ensure_future(
2502 self
.instantiate_N2VC(
2503 logging_text
=logging_text
,
2504 vca_index
=vca_index
,
2510 vdu_index
=vdu_index
,
2511 deploy_params
=deploy_params
,
2512 config_descriptor
=descriptor_config
,
2513 base_folder
=base_folder
,
2514 nslcmop_id
=nslcmop_id
,
2518 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_N2VC-{}".format(vca_index
), task_n2vc
)
2519 task_instantiation_info
[task_n2vc
] = self
.task_name_deploy_vca
+ " {}.{}".format(
2520 member_vnf_index
or "", vdu_id
or "")
2522 # Check if this VNFD has a configured terminate action
2523 def _has_terminate_config_primitive(self
, vnfd
):
2524 vnf_config
= vnfd
.get("vnf-configuration")
2525 if vnf_config
and vnf_config
.get("terminate-config-primitive"):
2531 def _get_terminate_config_primitive_seq_list(vnfd
):
2532 """ Get a numerically sorted list of the sequences for this VNFD's terminate action """
2533 # No need to check for existing primitive twice, already done before
2534 vnf_config
= vnfd
.get("vnf-configuration")
2535 seq_list
= vnf_config
.get("terminate-config-primitive")
2536 # Get all 'seq' tags in seq_list, order sequences numerically, ascending.
2537 seq_list_sorted
= sorted(seq_list
, key
=lambda x
: int(x
['seq']))
2538 return seq_list_sorted
2541 def _create_nslcmop(nsr_id
, operation
, params
):
2543 Creates a ns-lcm-opp content to be stored at database.
2544 :param nsr_id: internal id of the instance
2545 :param operation: instantiate, terminate, scale, action, ...
2546 :param params: user parameters for the operation
2547 :return: dictionary following SOL005 format
2549 # Raise exception if invalid arguments
2550 if not (nsr_id
and operation
and params
):
2552 "Parameters 'nsr_id', 'operation' and 'params' needed to create primitive not provided")
2558 # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2559 "operationState": "PROCESSING",
2560 "statusEnteredTime": now
,
2561 "nsInstanceId": nsr_id
,
2562 "lcmOperationType": operation
,
2564 "isAutomaticInvocation": False,
2565 "operationParams": params
,
2566 "isCancelPending": False,
2568 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
2569 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
2574 def _format_additional_params(self
, params
):
2575 params
= params
or {}
2576 for key
, value
in params
.items():
2577 if str(value
).startswith("!!yaml "):
2578 params
[key
] = yaml
.safe_load(value
[7:])
2581 def _get_terminate_primitive_params(self
, seq
, vnf_index
):
2582 primitive
= seq
.get('name')
2583 primitive_params
= {}
2585 "member_vnf_index": vnf_index
,
2586 "primitive": primitive
,
2587 "primitive_params": primitive_params
,
2590 return self
._map
_primitive
_params
(seq
, params
, desc_params
)
2594 def _retry_or_skip_suboperation(self
, db_nslcmop
, op_index
):
2595 op
= deep_get(db_nslcmop
, ('_admin', 'operations'), [])[op_index
]
2596 if op
.get('operationState') == 'COMPLETED':
2597 # b. Skip sub-operation
2598 # _ns_execute_primitive() or RO.create_action() will NOT be executed
2599 return self
.SUBOPERATION_STATUS_SKIP
2601 # c. retry executing sub-operation
2602 # The sub-operation exists, and operationState != 'COMPLETED'
2603 # Update operationState = 'PROCESSING' to indicate a retry.
2604 operationState
= 'PROCESSING'
2605 detailed_status
= 'In progress'
2606 self
._update
_suboperation
_status
(
2607 db_nslcmop
, op_index
, operationState
, detailed_status
)
2608 # Return the sub-operation index
2609 # _ns_execute_primitive() or RO.create_action() will be called from scale()
2610 # with arguments extracted from the sub-operation
2613 # Find a sub-operation where all keys in a matching dictionary must match
2614 # Returns the index of the matching sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if no match
2615 def _find_suboperation(self
, db_nslcmop
, match
):
2616 if db_nslcmop
and match
:
2617 op_list
= db_nslcmop
.get('_admin', {}).get('operations', [])
2618 for i
, op
in enumerate(op_list
):
2619 if all(op
.get(k
) == match
[k
] for k
in match
):
2621 return self
.SUBOPERATION_STATUS_NOT_FOUND
2623 # Update status for a sub-operation given its index
2624 def _update_suboperation_status(self
, db_nslcmop
, op_index
, operationState
, detailed_status
):
2625 # Update DB for HA tasks
2626 q_filter
= {'_id': db_nslcmop
['_id']}
2627 update_dict
= {'_admin.operations.{}.operationState'.format(op_index
): operationState
,
2628 '_admin.operations.{}.detailed-status'.format(op_index
): detailed_status
}
2629 self
.db
.set_one("nslcmops",
2631 update_dict
=update_dict
,
2632 fail_on_empty
=False)
2634 # Add sub-operation, return the index of the added sub-operation
2635 # Optionally, set operationState, detailed-status, and operationType
2636 # Status and type are currently set for 'scale' sub-operations:
2637 # 'operationState' : 'PROCESSING' | 'COMPLETED' | 'FAILED'
2638 # 'detailed-status' : status message
2639 # 'operationType': may be any type, in the case of scaling: 'PRE-SCALE' | 'POST-SCALE'
2640 # Status and operation type are currently only used for 'scale', but NOT for 'terminate' sub-operations.
2641 def _add_suboperation(self
, db_nslcmop
, vnf_index
, vdu_id
, vdu_count_index
, vdu_name
, primitive
,
2642 mapped_primitive_params
, operationState
=None, detailed_status
=None, operationType
=None,
2643 RO_nsr_id
=None, RO_scaling_info
=None):
2645 return self
.SUBOPERATION_STATUS_NOT_FOUND
2646 # Get the "_admin.operations" list, if it exists
2647 db_nslcmop_admin
= db_nslcmop
.get('_admin', {})
2648 op_list
= db_nslcmop_admin
.get('operations')
2649 # Create or append to the "_admin.operations" list
2650 new_op
= {'member_vnf_index': vnf_index
,
2652 'vdu_count_index': vdu_count_index
,
2653 'primitive': primitive
,
2654 'primitive_params': mapped_primitive_params
}
2656 new_op
['operationState'] = operationState
2658 new_op
['detailed-status'] = detailed_status
2660 new_op
['lcmOperationType'] = operationType
2662 new_op
['RO_nsr_id'] = RO_nsr_id
2664 new_op
['RO_scaling_info'] = RO_scaling_info
2666 # No existing operations, create key 'operations' with current operation as first list element
2667 db_nslcmop_admin
.update({'operations': [new_op
]})
2668 op_list
= db_nslcmop_admin
.get('operations')
2670 # Existing operations, append operation to list
2671 op_list
.append(new_op
)
2673 db_nslcmop_update
= {'_admin.operations': op_list
}
2674 self
.update_db_2("nslcmops", db_nslcmop
['_id'], db_nslcmop_update
)
2675 op_index
= len(op_list
) - 1
2678 # Helper methods for scale() sub-operations
2680 # pre-scale/post-scale:
2681 # Check for 3 different cases:
2682 # a. New: First time execution, return SUBOPERATION_STATUS_NEW
2683 # b. Skip: Existing sub-operation exists, operationState == 'COMPLETED', return SUBOPERATION_STATUS_SKIP
2684 # c. retry: Existing sub-operation exists, operationState != 'COMPLETED', return op_index to re-execute
2685 def _check_or_add_scale_suboperation(self
, db_nslcmop
, vnf_index
, vnf_config_primitive
, primitive_params
,
2686 operationType
, RO_nsr_id
=None, RO_scaling_info
=None):
2687 # Find this sub-operation
2688 if RO_nsr_id
and RO_scaling_info
:
2689 operationType
= 'SCALE-RO'
2691 'member_vnf_index': vnf_index
,
2692 'RO_nsr_id': RO_nsr_id
,
2693 'RO_scaling_info': RO_scaling_info
,
2697 'member_vnf_index': vnf_index
,
2698 'primitive': vnf_config_primitive
,
2699 'primitive_params': primitive_params
,
2700 'lcmOperationType': operationType
2702 op_index
= self
._find
_suboperation
(db_nslcmop
, match
)
2703 if op_index
== self
.SUBOPERATION_STATUS_NOT_FOUND
:
2704 # a. New sub-operation
2705 # The sub-operation does not exist, add it.
2706 # _ns_execute_primitive() will be called from scale() as usual, with non-modified arguments
2707 # The following parameters are set to None for all kind of scaling:
2709 vdu_count_index
= None
2711 if RO_nsr_id
and RO_scaling_info
:
2712 vnf_config_primitive
= None
2713 primitive_params
= None
2716 RO_scaling_info
= None
2717 # Initial status for sub-operation
2718 operationState
= 'PROCESSING'
2719 detailed_status
= 'In progress'
2720 # Add sub-operation for pre/post-scaling (zero or more operations)
2721 self
._add
_suboperation
(db_nslcmop
,
2726 vnf_config_primitive
,
2733 return self
.SUBOPERATION_STATUS_NEW
2735 # Return either SUBOPERATION_STATUS_SKIP (operationState == 'COMPLETED'),
2736 # or op_index (operationState != 'COMPLETED')
2737 return self
._retry
_or
_skip
_suboperation
(db_nslcmop
, op_index
)
2739 # Function to return execution_environment id
2741 def _get_ee_id(self
, vnf_index
, vdu_id
, vca_deployed_list
):
2742 # TODO vdu_index_count
2743 for vca
in vca_deployed_list
:
2744 if vca
["member-vnf-index"] == vnf_index
and vca
["vdu_id"] == vdu_id
:
2747 async def destroy_N2VC(self
, logging_text
, db_nslcmop
, vca_deployed
, config_descriptor
, vca_index
, destroy_ee
=True):
2749 Execute the terminate primitives and destroy the execution environment (if destroy_ee=False
2750 :param logging_text:
2752 :param vca_deployed: Dictionary of deployment info at db_nsr._admin.depoloyed.VCA.<INDEX>
2753 :param config_descriptor: Configuration descriptor of the NSD, VNFD, VNFD.vdu or VNFD.kdu
2754 :param vca_index: index in the database _admin.deployed.VCA
2755 :param destroy_ee: False to do not destroy, because it will be destroyed all of then at once
2756 :return: None or exception
2758 # execute terminate_primitives
2759 terminate_primitives
= config_descriptor
.get("terminate-config-primitive")
2760 vdu_id
= vca_deployed
.get("vdu_id")
2761 vdu_count_index
= vca_deployed
.get("vdu_count_index")
2762 vdu_name
= vca_deployed
.get("vdu_name")
2763 vnf_index
= vca_deployed
.get("member-vnf-index")
2764 if terminate_primitives
and vca_deployed
.get("needed_terminate"):
2765 # Get all 'seq' tags in seq_list, order sequences numerically, ascending.
2766 terminate_primitives
= sorted(terminate_primitives
, key
=lambda x
: int(x
['seq']))
2767 for seq
in terminate_primitives
:
2768 # For each sequence in list, get primitive and call _ns_execute_primitive()
2769 step
= "Calling terminate action for vnf_member_index={} primitive={}".format(
2770 vnf_index
, seq
.get("name"))
2771 self
.logger
.debug(logging_text
+ step
)
2772 # Create the primitive for each sequence, i.e. "primitive": "touch"
2773 primitive
= seq
.get('name')
2774 mapped_primitive_params
= self
._get
_terminate
_primitive
_params
(seq
, vnf_index
)
2775 # The following 3 parameters are currently set to None for 'terminate':
2776 # vdu_id, vdu_count_index, vdu_name
2779 self
._add
_suboperation
(db_nslcmop
,
2785 mapped_primitive_params
)
2786 # Sub-operations: Call _ns_execute_primitive() instead of action()
2788 result
, result_detail
= await self
._ns
_execute
_primitive
(vca_deployed
["ee_id"], primitive
,
2789 mapped_primitive_params
)
2790 except LcmException
:
2791 # this happens when VCA is not deployed. In this case it is not needed to terminate
2793 result_ok
= ['COMPLETED', 'PARTIALLY_COMPLETED']
2794 if result
not in result_ok
:
2795 raise LcmException("terminate_primitive {} for vnf_member_index={} fails with "
2796 "error {}".format(seq
.get("name"), vnf_index
, result_detail
))
2797 # set that this VCA do not need terminated
2798 db_update_entry
= "_admin.deployed.VCA.{}.needed_terminate".format(vca_index
)
2799 self
.update_db_2("nsrs", db_nslcmop
["nsInstanceId"], {db_update_entry
: False})
2802 await self
.n2vc
.delete_execution_environment(vca_deployed
["ee_id"])
2804 async def _delete_all_N2VC(self
, db_nsr
: dict):
2805 self
._write
_all
_config
_status
(db_nsr
=db_nsr
, status
='TERMINATING')
2806 namespace
= "." + db_nsr
["_id"]
2808 await self
.n2vc
.delete_namespace(namespace
=namespace
, total_timeout
=self
.timeout_charm_delete
)
2809 except N2VCNotFound
: # already deleted. Skip
2811 self
._write
_all
_config
_status
(db_nsr
=db_nsr
, status
='DELETED')
2813 async def _terminate_RO(self
, logging_text
, nsr_deployed
, nsr_id
, nslcmop_id
, stage
):
2815 Terminates a deployment from RO
2816 :param logging_text:
2817 :param nsr_deployed: db_nsr._admin.deployed
2820 :param stage: list of string with the content to write on db_nslcmop.detailed-status.
2821 this method will update only the index 2, but it will write on database the concatenated content of the list
2826 ro_nsr_id
= ro_delete_action
= None
2827 if nsr_deployed
and nsr_deployed
.get("RO"):
2828 ro_nsr_id
= nsr_deployed
["RO"].get("nsr_id")
2829 ro_delete_action
= nsr_deployed
["RO"].get("nsr_delete_action_id")
2832 stage
[2] = "Deleting ns from VIM."
2833 db_nsr_update
["detailed-status"] = " ".join(stage
)
2834 self
._write
_op
_status
(nslcmop_id
, stage
)
2835 self
.logger
.debug(logging_text
+ stage
[2])
2836 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2837 self
._write
_op
_status
(nslcmop_id
, stage
)
2838 desc
= await self
.RO
.delete("ns", ro_nsr_id
)
2839 ro_delete_action
= desc
["action_id"]
2840 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = ro_delete_action
2841 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
2842 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
2843 if ro_delete_action
:
2844 # wait until NS is deleted from VIM
2845 stage
[2] = "Waiting ns deleted from VIM."
2846 detailed_status_old
= None
2847 self
.logger
.debug(logging_text
+ stage
[2] + " RO_id={} ro_delete_action={}".format(ro_nsr_id
,
2849 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2850 self
._write
_op
_status
(nslcmop_id
, stage
)
2852 delete_timeout
= 20 * 60 # 20 minutes
2853 while delete_timeout
> 0:
2854 desc
= await self
.RO
.show(
2856 item_id_name
=ro_nsr_id
,
2857 extra_item
="action",
2858 extra_item_id
=ro_delete_action
)
2861 self
._on
_update
_ro
_db
(nsrs_id
=nsr_id
, ro_descriptor
=desc
)
2863 ns_status
, ns_status_info
= self
.RO
.check_action_status(desc
)
2864 if ns_status
== "ERROR":
2865 raise ROclient
.ROClientException(ns_status_info
)
2866 elif ns_status
== "BUILD":
2867 stage
[2] = "Deleting from VIM {}".format(ns_status_info
)
2868 elif ns_status
== "ACTIVE":
2869 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
2870 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
2873 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
2874 if stage
[2] != detailed_status_old
:
2875 detailed_status_old
= stage
[2]
2876 db_nsr_update
["detailed-status"] = " ".join(stage
)
2877 self
._write
_op
_status
(nslcmop_id
, stage
)
2878 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2879 await asyncio
.sleep(5, loop
=self
.loop
)
2881 else: # delete_timeout <= 0:
2882 raise ROclient
.ROClientException("Timeout waiting ns deleted from VIM")
2884 except Exception as e
:
2885 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2886 if isinstance(e
, ROclient
.ROClientException
) and e
.http_code
== 404: # not found
2887 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
2888 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
2889 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
2890 self
.logger
.debug(logging_text
+ "RO_ns_id={} already deleted".format(ro_nsr_id
))
2891 elif isinstance(e
, ROclient
.ROClientException
) and e
.http_code
== 409: # conflict
2892 failed_detail
.append("delete conflict: {}".format(e
))
2893 self
.logger
.debug(logging_text
+ "RO_ns_id={} delete conflict: {}".format(ro_nsr_id
, e
))
2895 failed_detail
.append("delete error: {}".format(e
))
2896 self
.logger
.error(logging_text
+ "RO_ns_id={} delete error: {}".format(ro_nsr_id
, e
))
2899 if not failed_detail
and deep_get(nsr_deployed
, ("RO", "nsd_id")):
2900 ro_nsd_id
= nsr_deployed
["RO"]["nsd_id"]
2902 stage
[2] = "Deleting nsd from RO."
2903 db_nsr_update
["detailed-status"] = " ".join(stage
)
2904 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2905 self
._write
_op
_status
(nslcmop_id
, stage
)
2906 await self
.RO
.delete("nsd", ro_nsd_id
)
2907 self
.logger
.debug(logging_text
+ "ro_nsd_id={} deleted".format(ro_nsd_id
))
2908 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
2909 except Exception as e
:
2910 if isinstance(e
, ROclient
.ROClientException
) and e
.http_code
== 404: # not found
2911 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
2912 self
.logger
.debug(logging_text
+ "ro_nsd_id={} already deleted".format(ro_nsd_id
))
2913 elif isinstance(e
, ROclient
.ROClientException
) and e
.http_code
== 409: # conflict
2914 failed_detail
.append("ro_nsd_id={} delete conflict: {}".format(ro_nsd_id
, e
))
2915 self
.logger
.debug(logging_text
+ failed_detail
[-1])
2917 failed_detail
.append("ro_nsd_id={} delete error: {}".format(ro_nsd_id
, e
))
2918 self
.logger
.error(logging_text
+ failed_detail
[-1])
2920 if not failed_detail
and deep_get(nsr_deployed
, ("RO", "vnfd")):
2921 for index
, vnf_deployed
in enumerate(nsr_deployed
["RO"]["vnfd"]):
2922 if not vnf_deployed
or not vnf_deployed
["id"]:
2925 ro_vnfd_id
= vnf_deployed
["id"]
2926 stage
[2] = "Deleting member_vnf_index={} ro_vnfd_id={} from RO.".format(
2927 vnf_deployed
["member-vnf-index"], ro_vnfd_id
)
2928 db_nsr_update
["detailed-status"] = " ".join(stage
)
2929 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2930 self
._write
_op
_status
(nslcmop_id
, stage
)
2931 await self
.RO
.delete("vnfd", ro_vnfd_id
)
2932 self
.logger
.debug(logging_text
+ "ro_vnfd_id={} deleted".format(ro_vnfd_id
))
2933 db_nsr_update
["_admin.deployed.RO.vnfd.{}.id".format(index
)] = None
2934 except Exception as e
:
2935 if isinstance(e
, ROclient
.ROClientException
) and e
.http_code
== 404: # not found
2936 db_nsr_update
["_admin.deployed.RO.vnfd.{}.id".format(index
)] = None
2937 self
.logger
.debug(logging_text
+ "ro_vnfd_id={} already deleted ".format(ro_vnfd_id
))
2938 elif isinstance(e
, ROclient
.ROClientException
) and e
.http_code
== 409: # conflict
2939 failed_detail
.append("ro_vnfd_id={} delete conflict: {}".format(ro_vnfd_id
, e
))
2940 self
.logger
.debug(logging_text
+ failed_detail
[-1])
2942 failed_detail
.append("ro_vnfd_id={} delete error: {}".format(ro_vnfd_id
, e
))
2943 self
.logger
.error(logging_text
+ failed_detail
[-1])
2946 stage
[2] = "Error deleting from VIM"
2948 stage
[2] = "Deleted from VIM"
2949 db_nsr_update
["detailed-status"] = " ".join(stage
)
2950 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2951 self
._write
_op
_status
(nslcmop_id
, stage
)
2954 raise LcmException("; ".join(failed_detail
))
2956 async def terminate(self
, nsr_id
, nslcmop_id
):
2957 # Try to lock HA task here
2958 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
2959 if not task_is_locked_by_me
:
2962 logging_text
= "Task ns={} terminate={} ".format(nsr_id
, nslcmop_id
)
2963 self
.logger
.debug(logging_text
+ "Enter")
2964 timeout_ns_terminate
= self
.timeout_ns_terminate
2967 operation_params
= None
2969 error_list
= [] # annotates all failed error messages
2970 db_nslcmop_update
= {}
2971 autoremove
= False # autoremove after terminated
2972 tasks_dict_info
= {}
2974 stage
= ["Stage 1/3: Preparing task.", "Waiting for previous operations to terminate.", ""]
2975 # ^ contains [stage, step, VIM-status]
2977 # wait for any previous tasks in process
2978 await self
.lcm_tasks
.waitfor_related_HA("ns", 'nslcmops', nslcmop_id
)
2980 stage
[1] = "Getting nslcmop={} from db.".format(nslcmop_id
)
2981 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
2982 operation_params
= db_nslcmop
.get("operationParams") or {}
2983 if operation_params
.get("timeout_ns_terminate"):
2984 timeout_ns_terminate
= operation_params
["timeout_ns_terminate"]
2985 stage
[1] = "Getting nsr={} from db.".format(nsr_id
)
2986 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2988 db_nsr_update
["operational-status"] = "terminating"
2989 db_nsr_update
["config-status"] = "terminating"
2990 self
._write
_ns
_status
(
2992 ns_state
="TERMINATING",
2993 current_operation
="TERMINATING",
2994 current_operation_id
=nslcmop_id
,
2995 other_update
=db_nsr_update
2997 self
._write
_op
_status
(
3002 nsr_deployed
= deepcopy(db_nsr
["_admin"].get("deployed")) or {}
3003 if db_nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
3006 stage
[1] = "Getting vnf descriptors from db."
3007 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
3008 db_vnfds_from_id
= {}
3009 db_vnfds_from_member_index
= {}
3011 for vnfr
in db_vnfrs_list
:
3012 vnfd_id
= vnfr
["vnfd-id"]
3013 if vnfd_id
not in db_vnfds_from_id
:
3014 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
3015 db_vnfds_from_id
[vnfd_id
] = vnfd
3016 db_vnfds_from_member_index
[vnfr
["member-vnf-index-ref"]] = db_vnfds_from_id
[vnfd_id
]
3018 # Destroy individual execution environments when there are terminating primitives.
3019 # Rest of EE will be deleted at once
3020 if not operation_params
.get("skip_terminate_primitives"):
3021 stage
[0] = "Stage 2/3 execute terminating primitives."
3022 stage
[1] = "Looking execution environment that needs terminate."
3023 self
.logger
.debug(logging_text
+ stage
[1])
3024 for vca_index
, vca
in enumerate(get_iterable(nsr_deployed
, "VCA")):
3025 config_descriptor
= None
3026 if not vca
or not vca
.get("ee_id") or not vca
.get("needed_terminate"):
3028 if not vca
.get("member-vnf-index"):
3030 config_descriptor
= db_nsr
.get("ns-configuration")
3031 elif vca
.get("vdu_id"):
3032 db_vnfd
= db_vnfds_from_member_index
[vca
["member-vnf-index"]]
3033 vdud
= next((vdu
for vdu
in db_vnfd
.get("vdu", ()) if vdu
["id"] == vca
.get("vdu_id")), None)
3035 config_descriptor
= vdud
.get("vdu-configuration")
3036 elif vca
.get("kdu_name"):
3037 db_vnfd
= db_vnfds_from_member_index
[vca
["member-vnf-index"]]
3038 kdud
= next((kdu
for kdu
in db_vnfd
.get("kdu", ()) if kdu
["name"] == vca
.get("kdu_name")), None)
3040 config_descriptor
= kdud
.get("kdu-configuration")
3042 config_descriptor
= db_vnfds_from_member_index
[vca
["member-vnf-index"]].get("vnf-configuration")
3043 task
= asyncio
.ensure_future(self
.destroy_N2VC(logging_text
, db_nslcmop
, vca
, config_descriptor
,
3045 tasks_dict_info
[task
] = "Terminating VCA {}".format(vca
.get("ee_id"))
3047 # wait for pending tasks of terminate primitives
3049 self
.logger
.debug(logging_text
+ 'Waiting for terminate primitive pending tasks...')
3050 error_list
= await self
._wait
_for
_tasks
(logging_text
, tasks_dict_info
,
3051 min(self
.timeout_charm_delete
, timeout_ns_terminate
),
3054 return # raise LcmException("; ".join(error_list))
3055 tasks_dict_info
.clear()
3057 # remove All execution environments at once
3058 stage
[0] = "Stage 3/3 delete all."
3060 if nsr_deployed
.get("VCA"):
3061 stage
[1] = "Deleting all execution environments."
3062 self
.logger
.debug(logging_text
+ stage
[1])
3063 task_delete_ee
= asyncio
.ensure_future(asyncio
.wait_for(self
._delete
_all
_N
2VC
(db_nsr
=db_nsr
),
3064 timeout
=self
.timeout_charm_delete
))
3065 # task_delete_ee = asyncio.ensure_future(self.n2vc.delete_namespace(namespace="." + nsr_id))
3066 tasks_dict_info
[task_delete_ee
] = "Terminating all VCA"
3068 # Delete from k8scluster
3069 stage
[1] = "Deleting KDUs."
3070 self
.logger
.debug(logging_text
+ stage
[1])
3071 # print(nsr_deployed)
3072 for kdu
in get_iterable(nsr_deployed
, "K8s"):
3073 if not kdu
or not kdu
.get("kdu-instance"):
3075 kdu_instance
= kdu
.get("kdu-instance")
3076 if kdu
.get("k8scluster-type") in self
.k8scluster_map
:
3077 task_delete_kdu_instance
= asyncio
.ensure_future(
3078 self
.k8scluster_map
[kdu
["k8scluster-type"]].uninstall(
3079 cluster_uuid
=kdu
.get("k8scluster-uuid"),
3080 kdu_instance
=kdu_instance
))
3082 self
.logger
.error(logging_text
+ "Unknown k8s deployment type {}".
3083 format(kdu
.get("k8scluster-type")))
3085 tasks_dict_info
[task_delete_kdu_instance
] = "Terminating KDU '{}'".format(kdu
.get("kdu-name"))
3088 stage
[1] = "Deleting ns from VIM."
3090 task_delete_ro
= asyncio
.ensure_future(
3091 self
._terminate
_ng
_ro
(logging_text
, nsr_deployed
, nsr_id
, nslcmop_id
, stage
))
3093 task_delete_ro
= asyncio
.ensure_future(
3094 self
._terminate
_RO
(logging_text
, nsr_deployed
, nsr_id
, nslcmop_id
, stage
))
3095 tasks_dict_info
[task_delete_ro
] = "Removing deployment from VIM"
3097 # rest of staff will be done at finally
3099 except (ROclient
.ROClientException
, DbException
, LcmException
, N2VCException
) as e
:
3100 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
3102 except asyncio
.CancelledError
:
3103 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(stage
[1]))
3104 exc
= "Operation was cancelled"
3105 except Exception as e
:
3106 exc
= traceback
.format_exc()
3107 self
.logger
.critical(logging_text
+ "Exit Exception while '{}': {}".format(stage
[1], e
), exc_info
=True)
3110 error_list
.append(str(exc
))
3112 # wait for pending tasks
3114 stage
[1] = "Waiting for terminate pending tasks."
3115 self
.logger
.debug(logging_text
+ stage
[1])
3116 error_list
+= await self
._wait
_for
_tasks
(logging_text
, tasks_dict_info
, timeout_ns_terminate
,
3118 stage
[1] = stage
[2] = ""
3119 except asyncio
.CancelledError
:
3120 error_list
.append("Cancelled")
3121 # TODO cancell all tasks
3122 except Exception as exc
:
3123 error_list
.append(str(exc
))
3124 # update status at database
3126 error_detail
= "; ".join(error_list
)
3127 # self.logger.error(logging_text + error_detail)
3128 error_description_nslcmop
= 'Stage: {}. Detail: {}'.format(stage
[0], error_detail
)
3129 error_description_nsr
= 'Operation: TERMINATING.{}, Stage {}.'.format(nslcmop_id
, stage
[0])
3131 db_nsr_update
["operational-status"] = "failed"
3132 db_nsr_update
["detailed-status"] = error_description_nsr
+ " Detail: " + error_detail
3133 db_nslcmop_update
["detailed-status"] = error_detail
3134 nslcmop_operation_state
= "FAILED"
3138 error_description_nsr
= error_description_nslcmop
= None
3139 ns_state
= "NOT_INSTANTIATED"
3140 db_nsr_update
["operational-status"] = "terminated"
3141 db_nsr_update
["detailed-status"] = "Done"
3142 db_nsr_update
["_admin.nsState"] = "NOT_INSTANTIATED"
3143 db_nslcmop_update
["detailed-status"] = "Done"
3144 nslcmop_operation_state
= "COMPLETED"
3147 self
._write
_ns
_status
(
3150 current_operation
="IDLE",
3151 current_operation_id
=None,
3152 error_description
=error_description_nsr
,
3153 error_detail
=error_detail
,
3154 other_update
=db_nsr_update
3156 self
._write
_op
_status
(
3159 error_message
=error_description_nslcmop
,
3160 operation_state
=nslcmop_operation_state
,
3161 other_update
=db_nslcmop_update
,
3163 if operation_params
:
3164 autoremove
= operation_params
.get("autoremove", False)
3165 if nslcmop_operation_state
:
3167 await self
.msg
.aiowrite("ns", "terminated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
3168 "operationState": nslcmop_operation_state
,
3169 "autoremove": autoremove
},
3171 except Exception as e
:
3172 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
3174 self
.logger
.debug(logging_text
+ "Exit")
3175 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_terminate")
3177 async def _wait_for_tasks(self
, logging_text
, created_tasks_info
, timeout
, stage
, nslcmop_id
, nsr_id
=None):
3179 error_detail_list
= []
3181 pending_tasks
= list(created_tasks_info
.keys())
3182 num_tasks
= len(pending_tasks
)
3184 stage
[1] = "{}/{}.".format(num_done
, num_tasks
)
3185 self
._write
_op
_status
(nslcmop_id
, stage
)
3186 while pending_tasks
:
3188 _timeout
= timeout
+ time_start
- time()
3189 done
, pending_tasks
= await asyncio
.wait(pending_tasks
, timeout
=_timeout
,
3190 return_when
=asyncio
.FIRST_COMPLETED
)
3191 num_done
+= len(done
)
3192 if not done
: # Timeout
3193 for task
in pending_tasks
:
3194 new_error
= created_tasks_info
[task
] + ": Timeout"
3195 error_detail_list
.append(new_error
)
3196 error_list
.append(new_error
)
3199 if task
.cancelled():
3202 exc
= task
.exception()
3204 if isinstance(exc
, asyncio
.TimeoutError
):
3206 new_error
= created_tasks_info
[task
] + ": {}".format(exc
)
3207 error_list
.append(created_tasks_info
[task
])
3208 error_detail_list
.append(new_error
)
3209 if isinstance(exc
, (str, DbException
, N2VCException
, ROclient
.ROClientException
, LcmException
,
3211 self
.logger
.error(logging_text
+ new_error
)
3213 exc_traceback
= "".join(traceback
.format_exception(None, exc
, exc
.__traceback
__))
3214 self
.logger
.error(logging_text
+ created_tasks_info
[task
] + exc_traceback
)
3216 self
.logger
.debug(logging_text
+ created_tasks_info
[task
] + ": Done")
3217 stage
[1] = "{}/{}.".format(num_done
, num_tasks
)
3219 stage
[1] += " Errors: " + ". ".join(error_detail_list
) + "."
3220 if nsr_id
: # update also nsr
3221 self
.update_db_2("nsrs", nsr_id
, {"errorDescription": "Error at: " + ", ".join(error_list
),
3222 "errorDetail": ". ".join(error_detail_list
)})
3223 self
._write
_op
_status
(nslcmop_id
, stage
)
3224 return error_detail_list
3227 def _map_primitive_params(primitive_desc
, params
, instantiation_params
):
3229 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
3230 The default-value is used. If it is between < > it look for a value at instantiation_params
3231 :param primitive_desc: portion of VNFD/NSD that describes primitive
3232 :param params: Params provided by user
3233 :param instantiation_params: Instantiation params provided by user
3234 :return: a dictionary with the calculated params
3236 calculated_params
= {}
3237 for parameter
in primitive_desc
.get("parameter", ()):
3238 param_name
= parameter
["name"]
3239 if param_name
in params
:
3240 calculated_params
[param_name
] = params
[param_name
]
3241 elif "default-value" in parameter
or "value" in parameter
:
3242 if "value" in parameter
:
3243 calculated_params
[param_name
] = parameter
["value"]
3245 calculated_params
[param_name
] = parameter
["default-value"]
3246 if isinstance(calculated_params
[param_name
], str) and calculated_params
[param_name
].startswith("<") \
3247 and calculated_params
[param_name
].endswith(">"):
3248 if calculated_params
[param_name
][1:-1] in instantiation_params
:
3249 calculated_params
[param_name
] = instantiation_params
[calculated_params
[param_name
][1:-1]]
3251 raise LcmException("Parameter {} needed to execute primitive {} not provided".
3252 format(calculated_params
[param_name
], primitive_desc
["name"]))
3254 raise LcmException("Parameter {} needed to execute primitive {} not provided".
3255 format(param_name
, primitive_desc
["name"]))
3257 if isinstance(calculated_params
[param_name
], (dict, list, tuple)):
3258 calculated_params
[param_name
] = yaml
.safe_dump(calculated_params
[param_name
], default_flow_style
=True,
3260 elif isinstance(calculated_params
[param_name
], str) and calculated_params
[param_name
].startswith("!!yaml "):
3261 calculated_params
[param_name
] = calculated_params
[param_name
][7:]
3263 # add always ns_config_info if primitive name is config
3264 if primitive_desc
["name"] == "config":
3265 if "ns_config_info" in instantiation_params
:
3266 calculated_params
["ns_config_info"] = instantiation_params
["ns_config_info"]
3267 return calculated_params
3269 def _look_for_deployed_vca(self
, deployed_vca
, member_vnf_index
, vdu_id
, vdu_count_index
, kdu_name
=None):
3270 # find vca_deployed record for this action. Raise LcmException if not found or there is not any id.
3271 for vca
in deployed_vca
:
3274 if member_vnf_index
!= vca
["member-vnf-index"] or vdu_id
!= vca
["vdu_id"]:
3276 if vdu_count_index
is not None and vdu_count_index
!= vca
["vdu_count_index"]:
3278 if kdu_name
and kdu_name
!= vca
["kdu_name"]:
3282 # vca_deployed not found
3283 raise LcmException("charm for member_vnf_index={} vdu_id={} kdu_name={} vdu_count_index={} is not "
3284 "deployed".format(member_vnf_index
, vdu_id
, kdu_name
, vdu_count_index
))
3287 ee_id
= vca
.get("ee_id")
3289 raise LcmException("charm for member_vnf_index={} vdu_id={} kdu_name={} vdu_count_index={} has not "
3290 "execution environment"
3291 .format(member_vnf_index
, vdu_id
, kdu_name
, vdu_count_index
))
3294 async def _ns_execute_primitive(self
, ee_id
, primitive
, primitive_params
, retries
=0,
3295 retries_interval
=30, timeout
=None) -> (str, str):
3297 if primitive
== "config":
3298 primitive_params
= {"params": primitive_params
}
3302 output
= await asyncio
.wait_for(
3303 self
.n2vc
.exec_primitive(
3305 primitive_name
=primitive
,
3306 params_dict
=primitive_params
,
3307 progress_timeout
=self
.timeout_progress_primitive
,
3308 total_timeout
=self
.timeout_primitive
),
3309 timeout
=timeout
or self
.timeout_primitive
)
3312 except asyncio
.CancelledError
:
3314 except Exception as e
: # asyncio.TimeoutError
3315 if isinstance(e
, asyncio
.TimeoutError
):
3319 self
.logger
.debug('Error executing action {} on {} -> {}'.format(primitive
, ee_id
, e
))
3321 await asyncio
.sleep(retries_interval
, loop
=self
.loop
)
3323 return 'FAILED', str(e
)
3325 return 'COMPLETED', output
3327 except (LcmException
, asyncio
.CancelledError
):
3329 except Exception as e
:
3330 return 'FAIL', 'Error executing action {}: {}'.format(primitive
, e
)
3332 async def action(self
, nsr_id
, nslcmop_id
):
3334 # Try to lock HA task here
3335 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
3336 if not task_is_locked_by_me
:
3339 logging_text
= "Task ns={} action={} ".format(nsr_id
, nslcmop_id
)
3340 self
.logger
.debug(logging_text
+ "Enter")
3341 # get all needed from database
3345 db_nslcmop_update
= {}
3346 nslcmop_operation_state
= None
3347 error_description_nslcmop
= None
3350 # wait for any previous tasks in process
3351 step
= "Waiting for previous operations to terminate"
3352 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
3354 self
._write
_ns
_status
(
3357 current_operation
="RUNNING ACTION",
3358 current_operation_id
=nslcmop_id
3361 step
= "Getting information from database"
3362 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
3363 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
3365 nsr_deployed
= db_nsr
["_admin"].get("deployed")
3366 vnf_index
= db_nslcmop
["operationParams"].get("member_vnf_index")
3367 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
3368 kdu_name
= db_nslcmop
["operationParams"].get("kdu_name")
3369 vdu_count_index
= db_nslcmop
["operationParams"].get("vdu_count_index")
3370 primitive
= db_nslcmop
["operationParams"]["primitive"]
3371 primitive_params
= db_nslcmop
["operationParams"]["primitive_params"]
3372 timeout_ns_action
= db_nslcmop
["operationParams"].get("timeout_ns_action", self
.timeout_primitive
)
3375 step
= "Getting vnfr from database"
3376 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
3377 step
= "Getting vnfd from database"
3378 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
3380 step
= "Getting nsd from database"
3381 db_nsd
= self
.db
.get_one("nsds", {"_id": db_nsr
["nsd-id"]})
3383 # for backward compatibility
3384 if nsr_deployed
and isinstance(nsr_deployed
.get("VCA"), dict):
3385 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
3386 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
3387 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
3389 # look for primitive
3390 config_primitive_desc
= None
3392 for vdu
in get_iterable(db_vnfd
, "vdu"):
3393 if vdu_id
== vdu
["id"]:
3394 for config_primitive
in deep_get(vdu
, ("vdu-configuration", "config-primitive"), ()):
3395 if config_primitive
["name"] == primitive
:
3396 config_primitive_desc
= config_primitive
3400 for kdu
in get_iterable(db_vnfd
, "kdu"):
3401 if kdu_name
== kdu
["name"]:
3402 for config_primitive
in deep_get(kdu
, ("kdu-configuration", "config-primitive"), ()):
3403 if config_primitive
["name"] == primitive
:
3404 config_primitive_desc
= config_primitive
3408 for config_primitive
in deep_get(db_vnfd
, ("vnf-configuration", "config-primitive"), ()):
3409 if config_primitive
["name"] == primitive
:
3410 config_primitive_desc
= config_primitive
3413 for config_primitive
in deep_get(db_nsd
, ("ns-configuration", "config-primitive"), ()):
3414 if config_primitive
["name"] == primitive
:
3415 config_primitive_desc
= config_primitive
3418 if not config_primitive_desc
and not (kdu_name
and primitive
in ("upgrade", "rollback", "status")):
3419 raise LcmException("Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".
3424 vdur
= next((x
for x
in db_vnfr
["vdur"] if x
["vdu-id-ref"] == vdu_id
), None)
3425 desc_params
= self
._format
_additional
_params
(vdur
.get("additionalParams"))
3427 kdur
= next((x
for x
in db_vnfr
["kdur"] if x
["kdu-name"] == kdu_name
), None)
3428 desc_params
= self
._format
_additional
_params
(kdur
.get("additionalParams"))
3430 desc_params
= self
._format
_additional
_params
(db_vnfr
.get("additionalParamsForVnf"))
3432 desc_params
= self
._format
_additional
_params
(db_nsr
.get("additionalParamsForNs"))
3435 kdu_action
= True if not deep_get(kdu
, ("kdu-configuration", "juju")) else False
3437 # TODO check if ns is in a proper status
3438 if kdu_name
and (primitive
in ("upgrade", "rollback", "status") or kdu_action
):
3439 # kdur and desc_params already set from before
3440 if primitive_params
:
3441 desc_params
.update(primitive_params
)
3442 # TODO Check if we will need something at vnf level
3443 for index
, kdu
in enumerate(get_iterable(nsr_deployed
, "K8s")):
3444 if kdu_name
== kdu
["kdu-name"] and kdu
["member-vnf-index"] == vnf_index
:
3447 raise LcmException("KDU '{}' for vnf '{}' not deployed".format(kdu_name
, vnf_index
))
3449 if kdu
.get("k8scluster-type") not in self
.k8scluster_map
:
3450 msg
= "unknown k8scluster-type '{}'".format(kdu
.get("k8scluster-type"))
3451 raise LcmException(msg
)
3453 db_dict
= {"collection": "nsrs",
3454 "filter": {"_id": nsr_id
},
3455 "path": "_admin.deployed.K8s.{}".format(index
)}
3456 self
.logger
.debug(logging_text
+ "Exec k8s {} on {}.{}".format(primitive
, vnf_index
, kdu_name
))
3457 step
= "Executing kdu {}".format(primitive
)
3458 if primitive
== "upgrade":
3459 if desc_params
.get("kdu_model"):
3460 kdu_model
= desc_params
.get("kdu_model")
3461 del desc_params
["kdu_model"]
3463 kdu_model
= kdu
.get("kdu-model")
3464 parts
= kdu_model
.split(sep
=":")
3466 kdu_model
= parts
[0]
3468 detailed_status
= await asyncio
.wait_for(
3469 self
.k8scluster_map
[kdu
["k8scluster-type"]].upgrade(
3470 cluster_uuid
=kdu
.get("k8scluster-uuid"),
3471 kdu_instance
=kdu
.get("kdu-instance"),
3472 atomic
=True, kdu_model
=kdu_model
,
3473 params
=desc_params
, db_dict
=db_dict
,
3474 timeout
=timeout_ns_action
),
3475 timeout
=timeout_ns_action
+ 10)
3476 self
.logger
.debug(logging_text
+ " Upgrade of kdu {} done".format(detailed_status
))
3477 elif primitive
== "rollback":
3478 detailed_status
= await asyncio
.wait_for(
3479 self
.k8scluster_map
[kdu
["k8scluster-type"]].rollback(
3480 cluster_uuid
=kdu
.get("k8scluster-uuid"),
3481 kdu_instance
=kdu
.get("kdu-instance"),
3483 timeout
=timeout_ns_action
)
3484 elif primitive
== "status":
3485 detailed_status
= await asyncio
.wait_for(
3486 self
.k8scluster_map
[kdu
["k8scluster-type"]].status_kdu(
3487 cluster_uuid
=kdu
.get("k8scluster-uuid"),
3488 kdu_instance
=kdu
.get("kdu-instance")),
3489 timeout
=timeout_ns_action
)
3491 kdu_instance
= kdu
.get("kdu-instance") or "{}-{}".format(kdu
["kdu-name"], nsr_id
)
3492 params
= self
._map
_primitive
_params
(config_primitive_desc
, primitive_params
, desc_params
)
3494 detailed_status
= await asyncio
.wait_for(
3495 self
.k8scluster_map
[kdu
["k8scluster-type"]].exec_primitive(
3496 cluster_uuid
=kdu
.get("k8scluster-uuid"),
3497 kdu_instance
=kdu_instance
,
3498 primitive_name
=primitive
,
3499 params
=params
, db_dict
=db_dict
,
3500 timeout
=timeout_ns_action
),
3501 timeout
=timeout_ns_action
)
3504 nslcmop_operation_state
= 'COMPLETED'
3506 detailed_status
= ''
3507 nslcmop_operation_state
= 'FAILED'
3509 nslcmop_operation_state
, detailed_status
= await self
._ns
_execute
_primitive
(
3510 self
._look
_for
_deployed
_vca
(nsr_deployed
["VCA"],
3511 member_vnf_index
=vnf_index
,
3513 vdu_count_index
=vdu_count_index
),
3514 primitive
=primitive
,
3515 primitive_params
=self
._map
_primitive
_params
(config_primitive_desc
, primitive_params
, desc_params
),
3516 timeout
=timeout_ns_action
)
3518 db_nslcmop_update
["detailed-status"] = detailed_status
3519 error_description_nslcmop
= detailed_status
if nslcmop_operation_state
== "FAILED" else ""
3520 self
.logger
.debug(logging_text
+ " task Done with result {} {}".format(nslcmop_operation_state
,
3522 return # database update is called inside finally
3524 except (DbException
, LcmException
, N2VCException
, K8sException
) as e
:
3525 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
3527 except asyncio
.CancelledError
:
3528 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
3529 exc
= "Operation was cancelled"
3530 except asyncio
.TimeoutError
:
3531 self
.logger
.error(logging_text
+ "Timeout while '{}'".format(step
))
3533 except Exception as e
:
3534 exc
= traceback
.format_exc()
3535 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
3538 db_nslcmop_update
["detailed-status"] = detailed_status
= error_description_nslcmop
= \
3539 "FAILED {}: {}".format(step
, exc
)
3540 nslcmop_operation_state
= "FAILED"
3542 self
._write
_ns
_status
(
3544 ns_state
=db_nsr
["nsState"], # TODO check if degraded. For the moment use previous status
3545 current_operation
="IDLE",
3546 current_operation_id
=None,
3547 # error_description=error_description_nsr,
3548 # error_detail=error_detail,
3549 other_update
=db_nsr_update
3552 self
._write
_op
_status
(
3555 error_message
=error_description_nslcmop
,
3556 operation_state
=nslcmop_operation_state
,
3557 other_update
=db_nslcmop_update
,
3560 if nslcmop_operation_state
:
3562 await self
.msg
.aiowrite("ns", "actioned", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
3563 "operationState": nslcmop_operation_state
},
3565 except Exception as e
:
3566 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
3567 self
.logger
.debug(logging_text
+ "Exit")
3568 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_action")
3569 return nslcmop_operation_state
, detailed_status
3571 async def scale(self
, nsr_id
, nslcmop_id
):
3573 # Try to lock HA task here
3574 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
3575 if not task_is_locked_by_me
:
3578 logging_text
= "Task ns={} scale={} ".format(nsr_id
, nslcmop_id
)
3579 self
.logger
.debug(logging_text
+ "Enter")
3580 # get all needed from database
3583 db_nslcmop_update
= {}
3584 nslcmop_operation_state
= None
3587 # in case of error, indicates what part of scale was failed to put nsr at error status
3588 scale_process
= None
3589 old_operational_status
= ""
3590 old_config_status
= ""
3593 # wait for any previous tasks in process
3594 step
= "Waiting for previous operations to terminate"
3595 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
3597 self
._write
_ns
_status
(
3600 current_operation
="SCALING",
3601 current_operation_id
=nslcmop_id
3604 step
= "Getting nslcmop from database"
3605 self
.logger
.debug(step
+ " after having waited for previous tasks to be completed")
3606 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
3607 step
= "Getting nsr from database"
3608 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
3610 old_operational_status
= db_nsr
["operational-status"]
3611 old_config_status
= db_nsr
["config-status"]
3612 step
= "Parsing scaling parameters"
3613 # self.logger.debug(step)
3614 db_nsr_update
["operational-status"] = "scaling"
3615 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
3616 nsr_deployed
= db_nsr
["_admin"].get("deployed")
3619 nsr_deployed
= db_nsr
["_admin"].get("deployed")
3620 vnf_index
= db_nslcmop
["operationParams"].get("member_vnf_index")
3621 # vdu_id = db_nslcmop["operationParams"].get("vdu_id")
3622 # vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
3623 # vdu_name = db_nslcmop["operationParams"].get("vdu_name")
3626 RO_nsr_id
= nsr_deployed
["RO"]["nsr_id"]
3627 vnf_index
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
3628 scaling_group
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
3629 scaling_type
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleVnfType"]
3630 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
3632 # for backward compatibility
3633 if nsr_deployed
and isinstance(nsr_deployed
.get("VCA"), dict):
3634 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
3635 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
3636 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
3638 step
= "Getting vnfr from database"
3639 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
3640 step
= "Getting vnfd from database"
3641 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
3643 step
= "Getting scaling-group-descriptor"
3644 for scaling_descriptor
in db_vnfd
["scaling-group-descriptor"]:
3645 if scaling_descriptor
["name"] == scaling_group
:
3648 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
3649 "at vnfd:scaling-group-descriptor".format(scaling_group
))
3652 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
3653 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
3654 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
3657 # TODO check if ns is in a proper status
3658 step
= "Sending scale order to VIM"
3660 if not db_nsr
["_admin"].get("scaling-group"):
3661 self
.update_db_2("nsrs", nsr_id
, {"_admin.scaling-group": [{"name": scaling_group
, "nb-scale-op": 0}]})
3662 admin_scale_index
= 0
3664 for admin_scale_index
, admin_scale_info
in enumerate(db_nsr
["_admin"]["scaling-group"]):
3665 if admin_scale_info
["name"] == scaling_group
:
3666 nb_scale_op
= admin_scale_info
.get("nb-scale-op", 0)
3668 else: # not found, set index one plus last element and add new entry with the name
3669 admin_scale_index
+= 1
3670 db_nsr_update
["_admin.scaling-group.{}.name".format(admin_scale_index
)] = scaling_group
3671 RO_scaling_info
= []
3672 vdu_scaling_info
= {"scaling_group_name": scaling_group
, "vdu": []}
3673 if scaling_type
== "SCALE_OUT":
3674 # count if max-instance-count is reached
3675 max_instance_count
= scaling_descriptor
.get("max-instance-count", 10)
3676 # self.logger.debug("MAX_INSTANCE_COUNT is {}".format(max_instance_count))
3677 if nb_scale_op
>= max_instance_count
:
3678 raise LcmException("reached the limit of {} (max-instance-count) "
3679 "scaling-out operations for the "
3680 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
3683 vdu_scaling_info
["scaling_direction"] = "OUT"
3684 vdu_scaling_info
["vdu-create"] = {}
3685 for vdu_scale_info
in scaling_descriptor
["vdu"]:
3686 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
3687 "type": "create", "count": vdu_scale_info
.get("count", 1)})
3688 vdu_scaling_info
["vdu-create"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
3690 elif scaling_type
== "SCALE_IN":
3691 # count if min-instance-count is reached
3692 min_instance_count
= 0
3693 if "min-instance-count" in scaling_descriptor
and scaling_descriptor
["min-instance-count"] is not None:
3694 min_instance_count
= int(scaling_descriptor
["min-instance-count"])
3695 if nb_scale_op
<= min_instance_count
:
3696 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
3697 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
3699 vdu_scaling_info
["scaling_direction"] = "IN"
3700 vdu_scaling_info
["vdu-delete"] = {}
3701 for vdu_scale_info
in scaling_descriptor
["vdu"]:
3702 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
3703 "type": "delete", "count": vdu_scale_info
.get("count", 1)})
3704 vdu_scaling_info
["vdu-delete"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
3706 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
3707 vdu_create
= vdu_scaling_info
.get("vdu-create")
3708 vdu_delete
= copy(vdu_scaling_info
.get("vdu-delete"))
3709 if vdu_scaling_info
["scaling_direction"] == "IN":
3710 for vdur
in reversed(db_vnfr
["vdur"]):
3711 if vdu_delete
.get(vdur
["vdu-id-ref"]):
3712 vdu_delete
[vdur
["vdu-id-ref"]] -= 1
3713 vdu_scaling_info
["vdu"].append({
3714 "name": vdur
["name"],
3715 "vdu_id": vdur
["vdu-id-ref"],
3718 for interface
in vdur
["interfaces"]:
3719 vdu_scaling_info
["vdu"][-1]["interface"].append({
3720 "name": interface
["name"],
3721 "ip_address": interface
["ip-address"],
3722 "mac_address": interface
.get("mac-address"),
3724 vdu_delete
= vdu_scaling_info
.pop("vdu-delete")
3727 step
= "Executing pre-scale vnf-config-primitive"
3728 if scaling_descriptor
.get("scaling-config-action"):
3729 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
3730 if (scaling_config_action
.get("trigger") == "pre-scale-in" and scaling_type
== "SCALE_IN") \
3731 or (scaling_config_action
.get("trigger") == "pre-scale-out" and scaling_type
== "SCALE_OUT"):
3732 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
3733 step
= db_nslcmop_update
["detailed-status"] = \
3734 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive
)
3736 # look for primitive
3737 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
3738 if config_primitive
["name"] == vnf_config_primitive
:
3742 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
3743 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
3744 "primitive".format(scaling_group
, config_primitive
))
3746 vnfr_params
= {"VDU_SCALE_INFO": vdu_scaling_info
}
3747 if db_vnfr
.get("additionalParamsForVnf"):
3748 vnfr_params
.update(db_vnfr
["additionalParamsForVnf"])
3750 scale_process
= "VCA"
3751 db_nsr_update
["config-status"] = "configuring pre-scaling"
3752 primitive_params
= self
._map
_primitive
_params
(config_primitive
, {}, vnfr_params
)
3754 # Pre-scale retry check: Check if this sub-operation has been executed before
3755 op_index
= self
._check
_or
_add
_scale
_suboperation
(
3756 db_nslcmop
, nslcmop_id
, vnf_index
, vnf_config_primitive
, primitive_params
, 'PRE-SCALE')
3757 if op_index
== self
.SUBOPERATION_STATUS_SKIP
:
3758 # Skip sub-operation
3759 result
= 'COMPLETED'
3760 result_detail
= 'Done'
3761 self
.logger
.debug(logging_text
+
3762 "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
3763 vnf_config_primitive
, result
, result_detail
))
3765 if op_index
== self
.SUBOPERATION_STATUS_NEW
:
3766 # New sub-operation: Get index of this sub-operation
3767 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
3768 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} New sub-operation".
3769 format(vnf_config_primitive
))
3771 # retry: Get registered params for this existing sub-operation
3772 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
3773 vnf_index
= op
.get('member_vnf_index')
3774 vnf_config_primitive
= op
.get('primitive')
3775 primitive_params
= op
.get('primitive_params')
3776 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Sub-operation retry".
3777 format(vnf_config_primitive
))
3778 # Execute the primitive, either with new (first-time) or registered (retry) args
3779 result
, result_detail
= await self
._ns
_execute
_primitive
(
3780 self
._look
_for
_deployed
_vca
(nsr_deployed
["VCA"],
3781 member_vnf_index
=vnf_index
,
3783 vdu_count_index
=None),
3784 vnf_config_primitive
, primitive_params
)
3785 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
3786 vnf_config_primitive
, result
, result_detail
))
3787 # Update operationState = COMPLETED | FAILED
3788 self
._update
_suboperation
_status
(
3789 db_nslcmop
, op_index
, result
, result_detail
)
3791 if result
== "FAILED":
3792 raise LcmException(result_detail
)
3793 db_nsr_update
["config-status"] = old_config_status
3794 scale_process
= None
3798 # Should this block be skipped if 'RO_nsr_id' == None ?
3799 # if (RO_nsr_id and RO_scaling_info):
3801 scale_process
= "RO"
3802 # Scale RO retry check: Check if this sub-operation has been executed before
3803 op_index
= self
._check
_or
_add
_scale
_suboperation
(
3804 db_nslcmop
, vnf_index
, None, None, 'SCALE-RO', RO_nsr_id
, RO_scaling_info
)
3805 if op_index
== self
.SUBOPERATION_STATUS_SKIP
:
3806 # Skip sub-operation
3807 result
= 'COMPLETED'
3808 result_detail
= 'Done'
3809 self
.logger
.debug(logging_text
+ "Skipped sub-operation RO, result {} {}".format(
3810 result
, result_detail
))
3812 if op_index
== self
.SUBOPERATION_STATUS_NEW
:
3813 # New sub-operation: Get index of this sub-operation
3814 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
3815 self
.logger
.debug(logging_text
+ "New sub-operation RO")
3817 # retry: Get registered params for this existing sub-operation
3818 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
3819 RO_nsr_id
= op
.get('RO_nsr_id')
3820 RO_scaling_info
= op
.get('RO_scaling_info')
3821 self
.logger
.debug(logging_text
+ "Sub-operation RO retry for primitive {}".format(
3822 vnf_config_primitive
))
3824 RO_desc
= await self
.RO
.create_action("ns", RO_nsr_id
, {"vdu-scaling": RO_scaling_info
})
3825 db_nsr_update
["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index
)] = nb_scale_op
3826 db_nsr_update
["_admin.scaling-group.{}.time".format(admin_scale_index
)] = time()
3828 RO_nslcmop_id
= RO_desc
["instance_action_id"]
3829 db_nslcmop_update
["_admin.deploy.RO"] = RO_nslcmop_id
3831 RO_task_done
= False
3832 step
= detailed_status
= "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id
)
3833 detailed_status_old
= None
3834 self
.logger
.debug(logging_text
+ step
)
3836 deployment_timeout
= 1 * 3600 # One hour
3837 while deployment_timeout
> 0:
3838 if not RO_task_done
:
3839 desc
= await self
.RO
.show("ns", item_id_name
=RO_nsr_id
, extra_item
="action",
3840 extra_item_id
=RO_nslcmop_id
)
3843 self
._on
_update
_ro
_db
(nsrs_id
=nsr_id
, ro_descriptor
=desc
)
3845 ns_status
, ns_status_info
= self
.RO
.check_action_status(desc
)
3846 if ns_status
== "ERROR":
3847 raise ROclient
.ROClientException(ns_status_info
)
3848 elif ns_status
== "BUILD":
3849 detailed_status
= step
+ "; {}".format(ns_status_info
)
3850 elif ns_status
== "ACTIVE":
3852 step
= detailed_status
= "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id
)
3853 self
.logger
.debug(logging_text
+ step
)
3855 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
3858 if ns_status
== "ERROR":
3859 raise ROclient
.ROClientException(ns_status_info
)
3860 elif ns_status
== "BUILD":
3861 detailed_status
= step
+ "; {}".format(ns_status_info
)
3862 elif ns_status
== "ACTIVE":
3863 step
= detailed_status
= \
3864 "Waiting for management IP address reported by the VIM. Updating VNFRs"
3866 self
.scale_vnfr(db_vnfr
, vdu_create
=vdu_create
, vdu_delete
=vdu_delete
)
3869 desc
= await self
.RO
.show("ns", RO_nsr_id
)
3872 self
._on
_update
_ro
_db
(nsrs_id
=nsr_id
, ro_descriptor
=desc
)
3874 # nsr_deployed["nsr_ip"] = RO.get_ns_vnf_info(desc)
3875 self
.ns_update_vnfr({db_vnfr
["member-vnf-index-ref"]: db_vnfr
}, desc
)
3877 except LcmExceptionNoMgmtIP
:
3880 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
3881 if detailed_status
!= detailed_status_old
:
3882 self
._update
_suboperation
_status
(
3883 db_nslcmop
, op_index
, 'COMPLETED', detailed_status
)
3884 detailed_status_old
= db_nslcmop_update
["detailed-status"] = detailed_status
3885 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
3887 await asyncio
.sleep(5, loop
=self
.loop
)
3888 deployment_timeout
-= 5
3889 if deployment_timeout
<= 0:
3890 self
._update
_suboperation
_status
(
3891 db_nslcmop
, nslcmop_id
, op_index
, 'FAILED', "Timeout when waiting for ns to get ready")
3892 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
3894 # update VDU_SCALING_INFO with the obtained ip_addresses
3895 if vdu_scaling_info
["scaling_direction"] == "OUT":
3896 for vdur
in reversed(db_vnfr
["vdur"]):
3897 if vdu_scaling_info
["vdu-create"].get(vdur
["vdu-id-ref"]):
3898 vdu_scaling_info
["vdu-create"][vdur
["vdu-id-ref"]] -= 1
3899 vdu_scaling_info
["vdu"].append({
3900 "name": vdur
["name"],
3901 "vdu_id": vdur
["vdu-id-ref"],
3904 for interface
in vdur
["interfaces"]:
3905 vdu_scaling_info
["vdu"][-1]["interface"].append({
3906 "name": interface
["name"],
3907 "ip_address": interface
["ip-address"],
3908 "mac_address": interface
.get("mac-address"),
3910 del vdu_scaling_info
["vdu-create"]
3912 self
._update
_suboperation
_status
(db_nslcmop
, op_index
, 'COMPLETED', 'Done')
3915 scale_process
= None
3917 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
3920 # execute primitive service POST-SCALING
3921 step
= "Executing post-scale vnf-config-primitive"
3922 if scaling_descriptor
.get("scaling-config-action"):
3923 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
3924 if (scaling_config_action
.get("trigger") == "post-scale-in" and scaling_type
== "SCALE_IN") \
3925 or (scaling_config_action
.get("trigger") == "post-scale-out" and scaling_type
== "SCALE_OUT"):
3926 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
3927 step
= db_nslcmop_update
["detailed-status"] = \
3928 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive
)
3930 vnfr_params
= {"VDU_SCALE_INFO": vdu_scaling_info
}
3931 if db_vnfr
.get("additionalParamsForVnf"):
3932 vnfr_params
.update(db_vnfr
["additionalParamsForVnf"])
3934 # look for primitive
3935 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
3936 if config_primitive
["name"] == vnf_config_primitive
:
3939 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
3940 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
3941 "match any vnf-configuration:config-primitive".format(scaling_group
,
3943 scale_process
= "VCA"
3944 db_nsr_update
["config-status"] = "configuring post-scaling"
3945 primitive_params
= self
._map
_primitive
_params
(config_primitive
, {}, vnfr_params
)
3947 # Post-scale retry check: Check if this sub-operation has been executed before
3948 op_index
= self
._check
_or
_add
_scale
_suboperation
(
3949 db_nslcmop
, nslcmop_id
, vnf_index
, vnf_config_primitive
, primitive_params
, 'POST-SCALE')
3950 if op_index
== self
.SUBOPERATION_STATUS_SKIP
:
3951 # Skip sub-operation
3952 result
= 'COMPLETED'
3953 result_detail
= 'Done'
3954 self
.logger
.debug(logging_text
+
3955 "vnf_config_primitive={} Skipped sub-operation, result {} {}".
3956 format(vnf_config_primitive
, result
, result_detail
))
3958 if op_index
== self
.SUBOPERATION_STATUS_NEW
:
3959 # New sub-operation: Get index of this sub-operation
3960 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
3961 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} New sub-operation".
3962 format(vnf_config_primitive
))
3964 # retry: Get registered params for this existing sub-operation
3965 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
3966 vnf_index
= op
.get('member_vnf_index')
3967 vnf_config_primitive
= op
.get('primitive')
3968 primitive_params
= op
.get('primitive_params')
3969 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Sub-operation retry".
3970 format(vnf_config_primitive
))
3971 # Execute the primitive, either with new (first-time) or registered (retry) args
3972 result
, result_detail
= await self
._ns
_execute
_primitive
(
3973 self
._look
_for
_deployed
_vca
(nsr_deployed
["VCA"],
3974 member_vnf_index
=vnf_index
,
3976 vdu_count_index
=None),
3977 vnf_config_primitive
, primitive_params
)
3978 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
3979 vnf_config_primitive
, result
, result_detail
))
3980 # Update operationState = COMPLETED | FAILED
3981 self
._update
_suboperation
_status
(
3982 db_nslcmop
, op_index
, result
, result_detail
)
3984 if result
== "FAILED":
3985 raise LcmException(result_detail
)
3986 db_nsr_update
["config-status"] = old_config_status
3987 scale_process
= None
3990 db_nsr_update
["detailed-status"] = "" # "scaled {} {}".format(scaling_group, scaling_type)
3991 db_nsr_update
["operational-status"] = "running" if old_operational_status
== "failed" \
3992 else old_operational_status
3993 db_nsr_update
["config-status"] = old_config_status
3995 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
3996 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
3998 except asyncio
.CancelledError
:
3999 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
4000 exc
= "Operation was cancelled"
4001 except Exception as e
:
4002 exc
= traceback
.format_exc()
4003 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
4005 self
._write
_ns
_status
(
4008 current_operation
="IDLE",
4009 current_operation_id
=None
4012 db_nslcmop_update
["detailed-status"] = error_description_nslcmop
= "FAILED {}: {}".format(step
, exc
)
4013 nslcmop_operation_state
= "FAILED"
4015 db_nsr_update
["operational-status"] = old_operational_status
4016 db_nsr_update
["config-status"] = old_config_status
4017 db_nsr_update
["detailed-status"] = ""
4019 if "VCA" in scale_process
:
4020 db_nsr_update
["config-status"] = "failed"
4021 if "RO" in scale_process
:
4022 db_nsr_update
["operational-status"] = "failed"
4023 db_nsr_update
["detailed-status"] = "FAILED scaling nslcmop={} {}: {}".format(nslcmop_id
, step
,
4026 error_description_nslcmop
= None
4027 nslcmop_operation_state
= "COMPLETED"
4028 db_nslcmop_update
["detailed-status"] = "Done"
4030 self
._write
_op
_status
(
4033 error_message
=error_description_nslcmop
,
4034 operation_state
=nslcmop_operation_state
,
4035 other_update
=db_nslcmop_update
,
4038 self
._write
_ns
_status
(
4041 current_operation
="IDLE",
4042 current_operation_id
=None,
4043 other_update
=db_nsr_update
4046 if nslcmop_operation_state
:
4048 await self
.msg
.aiowrite("ns", "scaled", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
4049 "operationState": nslcmop_operation_state
},
4052 # await asyncio.sleep(cooldown_time, loop=self.loop)
4053 # await self.msg.aiowrite("ns","scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
4054 except Exception as e
:
4055 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
4056 self
.logger
.debug(logging_text
+ "Exit")
4057 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_scale")