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
.lcm_utils
import LcmException
, LcmExceptionNoMgmtIP
, LcmBase
, deep_get
, get_iterable
, populate_dict
29 from n2vc
.k8s_helm_conn
import K8sHelmConnector
30 from n2vc
.k8s_juju_conn
import K8sJujuConnector
32 from osm_common
.dbbase
import DbException
33 from osm_common
.fsbase
import FsException
35 from n2vc
.n2vc_juju_conn
import N2VCJujuConnector
36 from n2vc
.exceptions
import N2VCException
38 from copy
import copy
, deepcopy
39 from http
import HTTPStatus
41 from uuid
import uuid4
43 __author__
= "Alfonso Tierno"
47 timeout_vca_on_error
= 5 * 60 # Time for charm from first time at blocked,error status to mark as failed
48 timeout_ns_deploy
= 2 * 3600 # default global timeout for deployment a ns
49 timeout_charm_delete
= 10 * 60
50 timeout_primitive
= 10 * 60 # timeout for primitive execution
52 SUBOPERATION_STATUS_NOT_FOUND
= -1
53 SUBOPERATION_STATUS_NEW
= -2
54 SUBOPERATION_STATUS_SKIP
= -3
56 def __init__(self
, db
, msg
, fs
, lcm_tasks
, config
, loop
):
58 Init, Connect to database, filesystem storage, and messaging
59 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
66 logger
=logging
.getLogger('lcm.ns')
70 self
.lcm_tasks
= lcm_tasks
71 self
.timeout
= config
["timeout"]
72 self
.ro_config
= config
["ro_config"]
73 self
.vca_config
= config
["VCA"].copy()
75 # create N2VC connector
76 self
.n2vc
= N2VCJujuConnector(
81 url
='{}:{}'.format(self
.vca_config
['host'], self
.vca_config
['port']),
82 username
=self
.vca_config
.get('user', None),
83 vca_config
=self
.vca_config
,
84 on_update_db
=self
._on
_update
_n
2vc
_db
87 self
.k8sclusterhelm
= K8sHelmConnector(
88 kubectl_command
=self
.vca_config
.get("kubectlpath"),
89 helm_command
=self
.vca_config
.get("helmpath"),
96 self
.k8sclusterjuju
= K8sJujuConnector(
97 kubectl_command
=self
.vca_config
.get("kubectlpath"),
98 juju_command
=self
.vca_config
.get("jujupath"),
106 self
.RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
108 def _on_update_ro_db(self
, nsrs_id
, ro_descriptor
):
110 # self.logger.debug('_on_update_ro_db(nsrs_id={}'.format(nsrs_id))
113 # TODO filter RO descriptor fields...
117 # db_dict['deploymentStatus'] = yaml.dump(ro_descriptor, default_flow_style=False, indent=2)
118 db_dict
['deploymentStatus'] = ro_descriptor
119 self
.update_db_2("nsrs", nsrs_id
, db_dict
)
121 except Exception as e
:
122 self
.logger
.warn('Cannot write database RO deployment for ns={} -> {}'.format(nsrs_id
, e
))
124 async def _on_update_n2vc_db(self
, table
, filter, path
, updated_data
):
126 # remove last dot from path (if exists)
127 if path
.endswith('.'):
130 # self.logger.debug('_on_update_n2vc_db(table={}, filter={}, path={}, updated_data={}'
131 # .format(table, filter, path, updated_data))
135 nsr_id
= filter.get('_id')
137 # read ns record from database
138 nsr
= self
.db
.get_one(table
='nsrs', q_filter
=filter)
139 current_ns_status
= nsr
.get('nsState')
141 # get vca status for NS
142 status_dict
= await self
.n2vc
.get_status(namespace
='.' + nsr_id
, yaml_format
=False)
146 db_dict
['vcaStatus'] = status_dict
148 # update configurationStatus for this VCA
150 vca_index
= int(path
[path
.rfind(".")+1:])
152 vca_list
= deep_get(target_dict
=nsr
, key_list
=('_admin', 'deployed', 'VCA'))
153 vca_status
= vca_list
[vca_index
].get('status')
155 configuration_status_list
= nsr
.get('configurationStatus')
156 config_status
= configuration_status_list
[vca_index
].get('status')
158 if config_status
== 'BROKEN' and vca_status
!= 'failed':
159 db_dict
['configurationStatus'][vca_index
] = 'READY'
160 elif config_status
!= 'BROKEN' and vca_status
== 'failed':
161 db_dict
['configurationStatus'][vca_index
] = 'BROKEN'
162 except Exception as e
:
163 # not update configurationStatus
164 self
.logger
.debug('Error updating vca_index (ignore): {}'.format(e
))
166 # if nsState = 'READY' check if juju is reporting some error => nsState = 'DEGRADED'
167 # if nsState = 'DEGRADED' check if all is OK
169 if current_ns_status
in ('READY', 'DEGRADED'):
170 error_description
= ''
172 if status_dict
.get('machines'):
173 for machine_id
in status_dict
.get('machines'):
174 machine
= status_dict
.get('machines').get(machine_id
)
175 # check machine agent-status
176 if machine
.get('agent-status'):
177 s
= machine
.get('agent-status').get('status')
180 error_description
+= 'machine {} agent-status={} ; '.format(machine_id
, s
)
181 # check machine instance status
182 if machine
.get('instance-status'):
183 s
= machine
.get('instance-status').get('status')
186 error_description
+= 'machine {} instance-status={} ; '.format(machine_id
, s
)
188 if status_dict
.get('applications'):
189 for app_id
in status_dict
.get('applications'):
190 app
= status_dict
.get('applications').get(app_id
)
191 # check application status
192 if app
.get('status'):
193 s
= app
.get('status').get('status')
196 error_description
+= 'application {} status={} ; '.format(app_id
, s
)
198 if error_description
:
199 db_dict
['errorDescription'] = error_description
200 if current_ns_status
== 'READY' and is_degraded
:
201 db_dict
['nsState'] = 'DEGRADED'
202 if current_ns_status
== 'DEGRADED' and not is_degraded
:
203 db_dict
['nsState'] = 'READY'
206 self
.update_db_2("nsrs", nsr_id
, db_dict
)
208 except Exception as e
:
209 self
.logger
.warn('Error updating NS state for ns={}: {}'.format(nsr_id
, e
))
213 def vnfd2RO(self
, vnfd
, new_id
=None, additionalParams
=None, nsrId
=None):
215 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
216 :param vnfd: input vnfd
217 :param new_id: overrides vnf id if provided
218 :param additionalParams: Instantiation params for VNFs provided
219 :param nsrId: Id of the NSR
220 :return: copy of vnfd
223 vnfd_RO
= deepcopy(vnfd
)
224 # remove unused by RO configuration, monitoring, scaling and internal keys
225 vnfd_RO
.pop("_id", None)
226 vnfd_RO
.pop("_admin", None)
227 vnfd_RO
.pop("vnf-configuration", None)
228 vnfd_RO
.pop("monitoring-param", None)
229 vnfd_RO
.pop("scaling-group-descriptor", None)
230 vnfd_RO
.pop("kdu", None)
231 vnfd_RO
.pop("k8s-cluster", None)
233 vnfd_RO
["id"] = new_id
235 # parse cloud-init or cloud-init-file with the provided variables using Jinja2
236 for vdu
in get_iterable(vnfd_RO
, "vdu"):
237 cloud_init_file
= None
238 if vdu
.get("cloud-init-file"):
239 base_folder
= vnfd
["_admin"]["storage"]
240 cloud_init_file
= "{}/{}/cloud_init/{}".format(base_folder
["folder"], base_folder
["pkg-dir"],
241 vdu
["cloud-init-file"])
242 with self
.fs
.file_open(cloud_init_file
, "r") as ci_file
:
243 cloud_init_content
= ci_file
.read()
244 vdu
.pop("cloud-init-file", None)
245 elif vdu
.get("cloud-init"):
246 cloud_init_content
= vdu
["cloud-init"]
251 ast
= env
.parse(cloud_init_content
)
252 mandatory_vars
= meta
.find_undeclared_variables(ast
)
254 for var
in mandatory_vars
:
255 if not additionalParams
or var
not in additionalParams
.keys():
256 raise LcmException("Variable '{}' defined at vnfd[id={}]:vdu[id={}]:cloud-init/cloud-init-"
257 "file, must be provided in the instantiation parameters inside the "
258 "'additionalParamsForVnf' block".format(var
, vnfd
["id"], vdu
["id"]))
259 template
= Template(cloud_init_content
)
260 cloud_init_content
= template
.render(additionalParams
or {})
261 vdu
["cloud-init"] = cloud_init_content
264 except FsException
as e
:
265 raise LcmException("Error reading vnfd[id={}]:vdu[id={}]:cloud-init-file={}: {}".
266 format(vnfd
["id"], vdu
["id"], cloud_init_file
, e
))
267 except (TemplateError
, TemplateNotFound
, TemplateSyntaxError
) as e
:
268 raise LcmException("Error parsing Jinja2 to cloud-init content at vnfd[id={}]:vdu[id={}]: {}".
269 format(vnfd
["id"], vdu
["id"], e
))
271 def ns_params_2_RO(self
, ns_params
, nsd
, vnfd_dict
, n2vc_key_list
):
273 Creates a RO ns descriptor from OSM ns_instantiate params
274 :param ns_params: OSM instantiate params
275 :return: The RO ns descriptor
279 # TODO feature 1417: Check that no instantiation is set over PDU
280 # check if PDU forces a concrete vim-network-id and add it
281 # check if PDU contains a SDN-assist info (dpid, switch, port) and pass it to RO
283 def vim_account_2_RO(vim_account
):
284 if vim_account
in vim_2_RO
:
285 return vim_2_RO
[vim_account
]
287 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_account
})
288 if db_vim
["_admin"]["operationalState"] != "ENABLED":
289 raise LcmException("VIM={} is not available. operationalState={}".format(
290 vim_account
, db_vim
["_admin"]["operationalState"]))
291 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
292 vim_2_RO
[vim_account
] = RO_vim_id
295 def wim_account_2_RO(wim_account
):
296 if isinstance(wim_account
, str):
297 if wim_account
in wim_2_RO
:
298 return wim_2_RO
[wim_account
]
300 db_wim
= self
.db
.get_one("wim_accounts", {"_id": wim_account
})
301 if db_wim
["_admin"]["operationalState"] != "ENABLED":
302 raise LcmException("WIM={} is not available. operationalState={}".format(
303 wim_account
, db_wim
["_admin"]["operationalState"]))
304 RO_wim_id
= db_wim
["_admin"]["deployed"]["RO-account"]
305 wim_2_RO
[wim_account
] = RO_wim_id
310 def ip_profile_2_RO(ip_profile
):
311 RO_ip_profile
= deepcopy((ip_profile
))
312 if "dns-server" in RO_ip_profile
:
313 if isinstance(RO_ip_profile
["dns-server"], list):
314 RO_ip_profile
["dns-address"] = []
315 for ds
in RO_ip_profile
.pop("dns-server"):
316 RO_ip_profile
["dns-address"].append(ds
['address'])
318 RO_ip_profile
["dns-address"] = RO_ip_profile
.pop("dns-server")
319 if RO_ip_profile
.get("ip-version") == "ipv4":
320 RO_ip_profile
["ip-version"] = "IPv4"
321 if RO_ip_profile
.get("ip-version") == "ipv6":
322 RO_ip_profile
["ip-version"] = "IPv6"
323 if "dhcp-params" in RO_ip_profile
:
324 RO_ip_profile
["dhcp"] = RO_ip_profile
.pop("dhcp-params")
330 # "name": ns_params["nsName"],
331 # "description": ns_params.get("nsDescription"),
332 "datacenter": vim_account_2_RO(ns_params
["vimAccountId"]),
333 "wim_account": wim_account_2_RO(ns_params
.get("wimAccountId")),
334 # "scenario": ns_params["nsdId"],
337 n2vc_key_list
= n2vc_key_list
or []
338 for vnfd_ref
, vnfd
in vnfd_dict
.items():
339 vdu_needed_access
= []
341 if vnfd
.get("vnf-configuration"):
342 ssh_required
= deep_get(vnfd
, ("vnf-configuration", "config-access", "ssh-access", "required"))
343 if ssh_required
and vnfd
.get("mgmt-interface"):
344 if vnfd
["mgmt-interface"].get("vdu-id"):
345 vdu_needed_access
.append(vnfd
["mgmt-interface"]["vdu-id"])
346 elif vnfd
["mgmt-interface"].get("cp"):
347 mgmt_cp
= vnfd
["mgmt-interface"]["cp"]
349 for vdu
in vnfd
.get("vdu", ()):
350 if vdu
.get("vdu-configuration"):
351 ssh_required
= deep_get(vdu
, ("vdu-configuration", "config-access", "ssh-access", "required"))
353 vdu_needed_access
.append(vdu
["id"])
355 for vdu_interface
in vdu
.get("interface"):
356 if vdu_interface
.get("external-connection-point-ref") and \
357 vdu_interface
["external-connection-point-ref"] == mgmt_cp
:
358 vdu_needed_access
.append(vdu
["id"])
362 if vdu_needed_access
:
363 for vnf_member
in nsd
.get("constituent-vnfd"):
364 if vnf_member
["vnfd-id-ref"] != vnfd_ref
:
366 for vdu
in vdu_needed_access
:
367 populate_dict(RO_ns_params
,
368 ("vnfs", vnf_member
["member-vnf-index"], "vdus", vdu
, "mgmt_keys"),
371 if ns_params
.get("vduImage"):
372 RO_ns_params
["vduImage"] = ns_params
["vduImage"]
374 if ns_params
.get("ssh_keys"):
375 RO_ns_params
["cloud-config"] = {"key-pairs": ns_params
["ssh_keys"]}
376 for vnf_params
in get_iterable(ns_params
, "vnf"):
377 for constituent_vnfd
in nsd
["constituent-vnfd"]:
378 if constituent_vnfd
["member-vnf-index"] == vnf_params
["member-vnf-index"]:
379 vnf_descriptor
= vnfd_dict
[constituent_vnfd
["vnfd-id-ref"]]
382 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index={} is not present at nsd:"
383 "constituent-vnfd".format(vnf_params
["member-vnf-index"]))
384 if vnf_params
.get("vimAccountId"):
385 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "datacenter"),
386 vim_account_2_RO(vnf_params
["vimAccountId"]))
388 for vdu_params
in get_iterable(vnf_params
, "vdu"):
389 # TODO feature 1417: check that this VDU exist and it is not a PDU
390 if vdu_params
.get("volume"):
391 for volume_params
in vdu_params
["volume"]:
392 if volume_params
.get("vim-volume-id"):
393 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
394 vdu_params
["id"], "devices", volume_params
["name"], "vim_id"),
395 volume_params
["vim-volume-id"])
396 if vdu_params
.get("interface"):
397 for interface_params
in vdu_params
["interface"]:
398 if interface_params
.get("ip-address"):
399 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
400 vdu_params
["id"], "interfaces", interface_params
["name"],
402 interface_params
["ip-address"])
403 if interface_params
.get("mac-address"):
404 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
405 vdu_params
["id"], "interfaces", interface_params
["name"],
407 interface_params
["mac-address"])
408 if interface_params
.get("floating-ip-required"):
409 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
410 vdu_params
["id"], "interfaces", interface_params
["name"],
412 interface_params
["floating-ip-required"])
414 for internal_vld_params
in get_iterable(vnf_params
, "internal-vld"):
415 if internal_vld_params
.get("vim-network-name"):
416 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
417 internal_vld_params
["name"], "vim-network-name"),
418 internal_vld_params
["vim-network-name"])
419 if internal_vld_params
.get("vim-network-id"):
420 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
421 internal_vld_params
["name"], "vim-network-id"),
422 internal_vld_params
["vim-network-id"])
423 if internal_vld_params
.get("ip-profile"):
424 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
425 internal_vld_params
["name"], "ip-profile"),
426 ip_profile_2_RO(internal_vld_params
["ip-profile"]))
427 if internal_vld_params
.get("provider-network"):
429 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
430 internal_vld_params
["name"], "provider-network"),
431 internal_vld_params
["provider-network"].copy())
433 for icp_params
in get_iterable(internal_vld_params
, "internal-connection-point"):
436 for vdu_descriptor
in vnf_descriptor
["vdu"]:
437 for vdu_interface
in vdu_descriptor
["interface"]:
438 if vdu_interface
.get("internal-connection-point-ref") == icp_params
["id-ref"]:
439 if icp_params
.get("ip-address"):
440 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
441 vdu_descriptor
["id"], "interfaces",
442 vdu_interface
["name"], "ip_address"),
443 icp_params
["ip-address"])
445 if icp_params
.get("mac-address"):
446 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
447 vdu_descriptor
["id"], "interfaces",
448 vdu_interface
["name"], "mac_address"),
449 icp_params
["mac-address"])
455 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
456 "internal-vld:id-ref={} is not present at vnfd:internal-"
457 "connection-point".format(vnf_params
["member-vnf-index"],
458 icp_params
["id-ref"]))
460 for vld_params
in get_iterable(ns_params
, "vld"):
461 if "ip-profile" in vld_params
:
462 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "ip-profile"),
463 ip_profile_2_RO(vld_params
["ip-profile"]))
465 if vld_params
.get("provider-network"):
467 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "provider-network"),
468 vld_params
["provider-network"].copy())
470 if "wimAccountId" in vld_params
and vld_params
["wimAccountId"] is not None:
471 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "wim_account"),
472 wim_account_2_RO(vld_params
["wimAccountId"])),
473 if vld_params
.get("vim-network-name"):
475 if isinstance(vld_params
["vim-network-name"], dict):
476 for vim_account
, vim_net
in vld_params
["vim-network-name"].items():
477 RO_vld_sites
.append({
478 "netmap-use": vim_net
,
479 "datacenter": vim_account_2_RO(vim_account
)
481 else: # isinstance str
482 RO_vld_sites
.append({"netmap-use": vld_params
["vim-network-name"]})
484 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "sites"), RO_vld_sites
)
486 if vld_params
.get("vim-network-id"):
488 if isinstance(vld_params
["vim-network-id"], dict):
489 for vim_account
, vim_net
in vld_params
["vim-network-id"].items():
490 RO_vld_sites
.append({
491 "netmap-use": vim_net
,
492 "datacenter": vim_account_2_RO(vim_account
)
494 else: # isinstance str
495 RO_vld_sites
.append({"netmap-use": vld_params
["vim-network-id"]})
497 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "sites"), RO_vld_sites
)
498 if vld_params
.get("ns-net"):
499 if isinstance(vld_params
["ns-net"], dict):
500 for vld_id
, instance_scenario_id
in vld_params
["ns-net"].items():
501 RO_vld_ns_net
= {"instance_scenario_id": instance_scenario_id
, "osm_id": vld_id
}
502 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "use-network"), RO_vld_ns_net
)
503 if "vnfd-connection-point-ref" in vld_params
:
504 for cp_params
in vld_params
["vnfd-connection-point-ref"]:
506 for constituent_vnfd
in nsd
["constituent-vnfd"]:
507 if constituent_vnfd
["member-vnf-index"] == cp_params
["member-vnf-index-ref"]:
508 vnf_descriptor
= vnfd_dict
[constituent_vnfd
["vnfd-id-ref"]]
512 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={} "
513 "is not present at nsd:constituent-vnfd".format(cp_params
["member-vnf-index-ref"]))
515 for vdu_descriptor
in vnf_descriptor
["vdu"]:
516 for interface_descriptor
in vdu_descriptor
["interface"]:
517 if interface_descriptor
.get("external-connection-point-ref") == \
518 cp_params
["vnfd-connection-point-ref"]:
525 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={}:"
526 "vnfd-connection-point-ref={} is not present at vnfd={}".format(
527 cp_params
["member-vnf-index-ref"],
528 cp_params
["vnfd-connection-point-ref"],
529 vnf_descriptor
["id"]))
530 if cp_params
.get("ip-address"):
531 populate_dict(RO_ns_params
, ("vnfs", cp_params
["member-vnf-index-ref"], "vdus",
532 vdu_descriptor
["id"], "interfaces",
533 interface_descriptor
["name"], "ip_address"),
534 cp_params
["ip-address"])
535 if cp_params
.get("mac-address"):
536 populate_dict(RO_ns_params
, ("vnfs", cp_params
["member-vnf-index-ref"], "vdus",
537 vdu_descriptor
["id"], "interfaces",
538 interface_descriptor
["name"], "mac_address"),
539 cp_params
["mac-address"])
542 def scale_vnfr(self
, db_vnfr
, vdu_create
=None, vdu_delete
=None):
543 # make a copy to do not change
544 vdu_create
= copy(vdu_create
)
545 vdu_delete
= copy(vdu_delete
)
547 vdurs
= db_vnfr
.get("vdur")
550 vdu_index
= len(vdurs
)
553 vdur
= vdurs
[vdu_index
]
554 if vdur
.get("pdu-type"):
556 vdu_id_ref
= vdur
["vdu-id-ref"]
557 if vdu_create
and vdu_create
.get(vdu_id_ref
):
558 for index
in range(0, vdu_create
[vdu_id_ref
]):
559 vdur
= deepcopy(vdur
)
560 vdur
["_id"] = str(uuid4())
561 vdur
["count-index"] += 1
562 vdurs
.insert(vdu_index
+1+index
, vdur
)
563 del vdu_create
[vdu_id_ref
]
564 if vdu_delete
and vdu_delete
.get(vdu_id_ref
):
566 vdu_delete
[vdu_id_ref
] -= 1
567 if not vdu_delete
[vdu_id_ref
]:
568 del vdu_delete
[vdu_id_ref
]
569 # check all operations are done
570 if vdu_create
or vdu_delete
:
571 raise LcmException("Error scaling OUT VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
574 raise LcmException("Error scaling IN VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
577 vnfr_update
= {"vdur": vdurs
}
578 db_vnfr
["vdur"] = vdurs
579 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
581 def ns_update_nsr(self
, ns_update_nsr
, db_nsr
, nsr_desc_RO
):
583 Updates database nsr with the RO info for the created vld
584 :param ns_update_nsr: dictionary to be filled with the updated info
585 :param db_nsr: content of db_nsr. This is also modified
586 :param nsr_desc_RO: nsr descriptor from RO
587 :return: Nothing, LcmException is raised on errors
590 for vld_index
, vld
in enumerate(get_iterable(db_nsr
, "vld")):
591 for net_RO
in get_iterable(nsr_desc_RO
, "nets"):
592 if vld
["id"] != net_RO
.get("ns_net_osm_id"):
594 vld
["vim-id"] = net_RO
.get("vim_net_id")
595 vld
["name"] = net_RO
.get("vim_name")
596 vld
["status"] = net_RO
.get("status")
597 vld
["status-detailed"] = net_RO
.get("error_msg")
598 ns_update_nsr
["vld.{}".format(vld_index
)] = vld
601 raise LcmException("ns_update_nsr: Not found vld={} at RO info".format(vld
["id"]))
603 def ns_update_vnfr(self
, db_vnfrs
, nsr_desc_RO
):
605 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
606 :param db_vnfrs: dictionary with member-vnf-index: vnfr-content
607 :param nsr_desc_RO: nsr descriptor from RO
608 :return: Nothing, LcmException is raised on errors
610 for vnf_index
, db_vnfr
in db_vnfrs
.items():
611 for vnf_RO
in nsr_desc_RO
["vnfs"]:
612 if vnf_RO
["member_vnf_index"] != vnf_index
:
615 if vnf_RO
.get("ip_address"):
616 db_vnfr
["ip-address"] = vnfr_update
["ip-address"] = vnf_RO
["ip_address"].split(";")[0]
617 elif not db_vnfr
.get("ip-address"):
618 raise LcmExceptionNoMgmtIP("ns member_vnf_index '{}' has no IP address".format(vnf_index
))
620 for vdu_index
, vdur
in enumerate(get_iterable(db_vnfr
, "vdur")):
621 vdur_RO_count_index
= 0
622 if vdur
.get("pdu-type"):
624 for vdur_RO
in get_iterable(vnf_RO
, "vms"):
625 if vdur
["vdu-id-ref"] != vdur_RO
["vdu_osm_id"]:
627 if vdur
["count-index"] != vdur_RO_count_index
:
628 vdur_RO_count_index
+= 1
630 vdur
["vim-id"] = vdur_RO
.get("vim_vm_id")
631 if vdur_RO
.get("ip_address"):
632 vdur
["ip-address"] = vdur_RO
["ip_address"].split(";")[0]
634 vdur
["ip-address"] = None
635 vdur
["vdu-id-ref"] = vdur_RO
.get("vdu_osm_id")
636 vdur
["name"] = vdur_RO
.get("vim_name")
637 vdur
["status"] = vdur_RO
.get("status")
638 vdur
["status-detailed"] = vdur_RO
.get("error_msg")
639 for ifacer
in get_iterable(vdur
, "interfaces"):
640 for interface_RO
in get_iterable(vdur_RO
, "interfaces"):
641 if ifacer
["name"] == interface_RO
.get("internal_name"):
642 ifacer
["ip-address"] = interface_RO
.get("ip_address")
643 ifacer
["mac-address"] = interface_RO
.get("mac_address")
646 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} interface={} "
648 .format(vnf_index
, vdur
["vdu-id-ref"], ifacer
["name"]))
649 vnfr_update
["vdur.{}".format(vdu_index
)] = vdur
652 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} count_index={} from "
653 "VIM info".format(vnf_index
, vdur
["vdu-id-ref"], vdur
["count-index"]))
655 for vld_index
, vld
in enumerate(get_iterable(db_vnfr
, "vld")):
656 for net_RO
in get_iterable(nsr_desc_RO
, "nets"):
657 if vld
["id"] != net_RO
.get("vnf_net_osm_id"):
659 vld
["vim-id"] = net_RO
.get("vim_net_id")
660 vld
["name"] = net_RO
.get("vim_name")
661 vld
["status"] = net_RO
.get("status")
662 vld
["status-detailed"] = net_RO
.get("error_msg")
663 vnfr_update
["vld.{}".format(vld_index
)] = vld
666 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vld={} from VIM info".format(
667 vnf_index
, vld
["id"]))
669 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
673 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} from VIM info".format(vnf_index
))
675 def _get_ns_config_info(self
, nsr_id
):
677 Generates a mapping between vnf,vdu elements and the N2VC id
678 :param nsr_id: id of nsr to get last database _admin.deployed.VCA that contains this list
679 :return: a dictionary with {osm-config-mapping: {}} where its element contains:
680 "<member-vnf-index>": <N2VC-id> for a vnf configuration, or
681 "<member-vnf-index>.<vdu.id>.<vdu replica(0, 1,..)>": <N2VC-id> for a vdu configuration
683 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
684 vca_deployed_list
= db_nsr
["_admin"]["deployed"]["VCA"]
686 ns_config_info
= {"osm-config-mapping": mapping
}
687 for vca
in vca_deployed_list
:
688 if not vca
["member-vnf-index"]:
690 if not vca
["vdu_id"]:
691 mapping
[vca
["member-vnf-index"]] = vca
["application"]
693 mapping
["{}.{}.{}".format(vca
["member-vnf-index"], vca
["vdu_id"], vca
["vdu_count_index"])] =\
695 return ns_config_info
698 def _get_initial_config_primitive_list(desc_primitive_list
, vca_deployed
):
700 Generates a list of initial-config-primitive based on the list provided by the descriptor. It includes internal
701 primitives as verify-ssh-credentials, or config when needed
702 :param desc_primitive_list: information of the descriptor
703 :param vca_deployed: information of the deployed, needed for known if it is related to an NS, VNF, VDU and if
704 this element contains a ssh public key
705 :return: The modified list. Can ba an empty list, but always a list
707 if desc_primitive_list
:
708 primitive_list
= desc_primitive_list
.copy()
711 # look for primitive config, and get the position. None if not present
712 config_position
= None
713 for index
, primitive
in enumerate(primitive_list
):
714 if primitive
["name"] == "config":
715 config_position
= index
718 # for NS, add always a config primitive if not present (bug 874)
719 if not vca_deployed
["member-vnf-index"] and config_position
is None:
720 primitive_list
.insert(0, {"name": "config", "parameter": []})
722 # for VNF/VDU add verify-ssh-credentials after config
723 if vca_deployed
["member-vnf-index"] and config_position
is not None and vca_deployed
.get("ssh-public-key"):
724 primitive_list
.insert(config_position
+ 1, {"name": "verify-ssh-credentials", "parameter": []})
725 return primitive_list
727 async def instantiate_RO(self
, logging_text
, nsr_id
, nsd
, db_nsr
,
728 db_nslcmop
, db_vnfrs
, db_vnfds_ref
, n2vc_key_list
):
731 RO_descriptor_number
= 0 # number of descriptors created at RO
732 vnf_index_2_RO_id
= {} # map between vnfd/nsd id to the id used at RO
733 start_deploy
= time()
734 vdu_flag
= False # If any of the VNFDs has VDUs
735 ns_params
= db_nslcmop
.get("operationParams")
736 if ns_params
and ns_params
.get("timeout_ns_deploy"):
737 timeout_ns_deploy
= ns_params
["timeout_ns_deploy"]
739 timeout_ns_deploy
= self
.timeout
.get("ns_deploy", self
.timeout_ns_deploy
)
743 # get vnfds, instantiate at RO
745 for c_vnf
in nsd
.get("constituent-vnfd", ()):
746 member_vnf_index
= c_vnf
["member-vnf-index"]
747 vnfd
= db_vnfds_ref
[c_vnf
['vnfd-id-ref']]
750 vnfd_ref
= vnfd
["id"]
751 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Creating vnfd='{}' member_vnf_index='{}' at" \
752 " RO".format(vnfd_ref
, member_vnf_index
)
753 # self.logger.debug(logging_text + step)
754 vnfd_id_RO
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, member_vnf_index
[:23])
755 vnf_index_2_RO_id
[member_vnf_index
] = vnfd_id_RO
756 RO_descriptor_number
+= 1
758 # look position at deployed.RO.vnfd if not present it will be appended at the end
759 for index
, vnf_deployed
in enumerate(db_nsr
["_admin"]["deployed"]["RO"]["vnfd"]):
760 if vnf_deployed
["member-vnf-index"] == member_vnf_index
:
763 index
= len(db_nsr
["_admin"]["deployed"]["RO"]["vnfd"])
764 db_nsr
["_admin"]["deployed"]["RO"]["vnfd"].append(None)
767 RO_update
= {"member-vnf-index": member_vnf_index
}
768 vnfd_list
= await self
.RO
.get_list("vnfd", filter_by
={"osm_id": vnfd_id_RO
})
770 RO_update
["id"] = vnfd_list
[0]["uuid"]
771 self
.logger
.debug(logging_text
+ "vnfd='{}' member_vnf_index='{}' exists at RO. Using RO_id={}".
772 format(vnfd_ref
, member_vnf_index
, vnfd_list
[0]["uuid"]))
774 vnfd_RO
= self
.vnfd2RO(vnfd
, vnfd_id_RO
, db_vnfrs
[c_vnf
["member-vnf-index"]].
775 get("additionalParamsForVnf"), nsr_id
)
776 desc
= await self
.RO
.create("vnfd", descriptor
=vnfd_RO
)
777 RO_update
["id"] = desc
["uuid"]
778 self
.logger
.debug(logging_text
+ "vnfd='{}' member_vnf_index='{}' created at RO. RO_id={}".format(
779 vnfd_ref
, member_vnf_index
, desc
["uuid"]))
780 db_nsr_update
["_admin.deployed.RO.vnfd.{}".format(index
)] = RO_update
781 db_nsr
["_admin"]["deployed"]["RO"]["vnfd"][index
] = RO_update
782 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
786 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Creating nsd={} at RO".format(nsd_ref
)
787 # self.logger.debug(logging_text + step)
789 RO_osm_nsd_id
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, nsd_ref
[:23])
790 RO_descriptor_number
+= 1
791 nsd_list
= await self
.RO
.get_list("nsd", filter_by
={"osm_id": RO_osm_nsd_id
})
793 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= nsd_list
[0]["uuid"]
794 self
.logger
.debug(logging_text
+ "nsd={} exists at RO. Using RO_id={}".format(
795 nsd_ref
, RO_nsd_uuid
))
797 nsd_RO
= deepcopy(nsd
)
798 nsd_RO
["id"] = RO_osm_nsd_id
799 nsd_RO
.pop("_id", None)
800 nsd_RO
.pop("_admin", None)
801 for c_vnf
in nsd_RO
.get("constituent-vnfd", ()):
802 member_vnf_index
= c_vnf
["member-vnf-index"]
803 c_vnf
["vnfd-id-ref"] = vnf_index_2_RO_id
[member_vnf_index
]
804 for c_vld
in nsd_RO
.get("vld", ()):
805 for cp
in c_vld
.get("vnfd-connection-point-ref", ()):
806 member_vnf_index
= cp
["member-vnf-index-ref"]
807 cp
["vnfd-id-ref"] = vnf_index_2_RO_id
[member_vnf_index
]
809 desc
= await self
.RO
.create("nsd", descriptor
=nsd_RO
)
810 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
811 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= desc
["uuid"]
812 self
.logger
.debug(logging_text
+ "nsd={} created at RO. RO_id={}".format(nsd_ref
, RO_nsd_uuid
))
813 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
816 # if present use it unless in error status
817 RO_nsr_id
= deep_get(db_nsr
, ("_admin", "deployed", "RO", "nsr_id"))
820 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Looking for existing ns at RO"
821 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
822 desc
= await self
.RO
.show("ns", RO_nsr_id
)
824 except ROclient
.ROClientException
as e
:
825 if e
.http_code
!= HTTPStatus
.NOT_FOUND
:
827 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
829 ns_status
, ns_status_info
= self
.RO
.check_ns_status(desc
)
830 db_nsr_update
["_admin.deployed.RO.nsr_status"] = ns_status
831 if ns_status
== "ERROR":
832 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Deleting ns at RO. RO_ns_id={}"\
834 self
.logger
.debug(logging_text
+ step
)
835 await self
.RO
.delete("ns", RO_nsr_id
)
836 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
838 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Checking dependencies"
839 # self.logger.debug(logging_text + step)
841 # check if VIM is creating and wait look if previous tasks in process
842 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account", ns_params
["vimAccountId"])
844 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
845 self
.logger
.debug(logging_text
+ step
)
846 await asyncio
.wait(task_dependency
, timeout
=3600)
847 if ns_params
.get("vnf"):
848 for vnf
in ns_params
["vnf"]:
849 if "vimAccountId" in vnf
:
850 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account",
853 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
854 self
.logger
.debug(logging_text
+ step
)
855 await asyncio
.wait(task_dependency
, timeout
=3600)
857 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Checking instantiation parameters"
859 RO_ns_params
= self
.ns_params_2_RO(ns_params
, nsd
, db_vnfds_ref
, n2vc_key_list
)
861 step
= db_nsr_update
["detailed-status"] = "Deploying ns at VIM"
862 # step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Deploying ns at VIM"
863 desc
= await self
.RO
.create("ns", descriptor
=RO_ns_params
, name
=db_nsr
["name"], scenario
=RO_nsd_uuid
)
864 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = desc
["uuid"]
865 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
866 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "BUILD"
867 self
.logger
.debug(logging_text
+ "ns created at RO. RO_id={}".format(desc
["uuid"]))
868 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
870 # wait until NS is ready
871 step
= ns_status_detailed
= detailed_status
= "Waiting VIM to deploy ns. RO_ns_id={}".format(RO_nsr_id
)
872 detailed_status_old
= None
873 self
.logger
.debug(logging_text
+ step
)
876 while time() <= start_deploy
+ timeout_ns_deploy
:
877 desc
= await self
.RO
.show("ns", RO_nsr_id
)
881 # desc has changed => update db
882 self
._on
_update
_ro
_db
(nsrs_id
=nsr_id
, ro_descriptor
=desc
)
885 ns_status
, ns_status_info
= self
.RO
.check_ns_status(desc
)
886 db_nsr_update
["_admin.deployed.RO.nsr_status"] = ns_status
887 if ns_status
== "ERROR":
888 raise ROclient
.ROClientException(ns_status_info
)
889 elif ns_status
== "BUILD":
890 detailed_status
= ns_status_detailed
+ "; {}".format(ns_status_info
)
891 elif ns_status
== "ACTIVE":
892 step
= detailed_status
= "Waiting for management IP address reported by the VIM. Updating VNFRs"
895 self
.ns_update_vnfr(db_vnfrs
, desc
)
897 except LcmExceptionNoMgmtIP
:
900 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
901 if detailed_status
!= detailed_status_old
:
902 detailed_status_old
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = detailed_status
903 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
904 await asyncio
.sleep(5, loop
=self
.loop
)
905 else: # timeout_ns_deploy
906 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
908 step
= "Updating NSR"
909 self
.ns_update_nsr(db_nsr_update
, db_nsr
, desc
)
911 db_nsr_update
["_admin.deployed.RO.operational-status"] = "running"
912 db_nsr
["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
913 db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
914 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
915 # await self._on_update_n2vc_db("nsrs", {"_id": nsr_id}, "_admin.deployed", db_nsr_update)
917 step
= "Deployed at VIM"
918 self
.logger
.debug(logging_text
+ step
)
920 async def wait_vm_up_insert_key_ro(self
, logging_text
, nsr_id
, vnfr_id
, vdu_id
, vdu_index
, pub_key
=None, user
=None):
922 Wait for ip addres at RO, and optionally, insert public key in virtual machine
923 :param logging_text: prefix use for logging
928 :param pub_key: public ssh key to inject, None to skip
929 :param user: user to apply the public ssh key
933 # self.logger.debug(logging_text + "Starting wait_vm_up_insert_key_ro")
943 if ro_retries
>= 360: # 1 hour
944 raise LcmException("Not found _admin.deployed.RO.nsr_id for nsr_id: {}".format(nsr_id
))
946 await asyncio
.sleep(10, loop
=self
.loop
)
947 # wait until NS is deployed at RO
949 db_nsrs
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
950 ro_nsr_id
= deep_get(db_nsrs
, ("_admin", "deployed", "RO", "nsr_id"))
955 if not target_vdu_id
:
956 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnfr_id
})
958 if not vdu_id
: # for the VNF case
959 ip_address
= db_vnfr
.get("ip-address")
962 vdur
= next((x
for x
in get_iterable(db_vnfr
, "vdur") if x
.get("ip-address") == ip_address
), None)
964 vdur
= next((x
for x
in get_iterable(db_vnfr
, "vdur")
965 if x
.get("vdu-id-ref") == vdu_id
and x
.get("count-index") == vdu_index
), None)
968 raise LcmException("Not found vnfr_id={}, vdu_index={}, vdu_index={}".format(
969 vnfr_id
, vdu_id
, vdu_index
972 if vdur
.get("status") == "ACTIVE":
973 ip_address
= vdur
.get("ip-address")
976 target_vdu_id
= vdur
["vdu-id-ref"]
977 elif vdur
.get("status") == "ERROR":
978 raise LcmException("Cannot inject ssh-key because target VM is in error state")
980 if not target_vdu_id
:
983 # self.logger.debug(logging_text + "IP address={}".format(ip_address))
985 # inject public key into machine
987 # self.logger.debug(logging_text + "Inserting RO key")
989 ro_vm_id
= "{}-{}".format(db_vnfr
["member-vnf-index-ref"], target_vdu_id
) # TODO add vdu_index
990 result_dict
= await self
.RO
.create_action(
992 item_id_name
=ro_nsr_id
,
993 descriptor
={"add_public_key": pub_key
, "vms": [ro_vm_id
], "user": user
}
995 # result_dict contains the format {VM-id: {vim_result: 200, description: text}}
996 if not result_dict
or not isinstance(result_dict
, dict):
997 raise LcmException("Unknown response from RO when injecting key")
998 for result
in result_dict
.values():
999 if result
.get("vim_result") == 200:
1002 raise ROclient
.ROClientException("error injecting key: {}".format(
1003 result
.get("description")))
1005 except ROclient
.ROClientException
as e
:
1007 self
.logger
.debug(logging_text
+ "error injecting key: {}. Retrying until {} seconds".
1011 raise LcmException("Reaching max tries injecting key. Error: {}".format(e
))
1017 async def _wait_dependent_n2vc(self
, nsr_id
, vca_deployed_list
, vca_index
):
1019 Wait until dependent VCA deployments have been finished. NS wait for VNFs and VDUs. VNFs for VDUs
1021 my_vca
= vca_deployed_list
[vca_index
]
1022 if my_vca
.get("vdu_id") or my_vca
.get("kdu_name"):
1023 # vdu or kdu: no dependencies
1027 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1028 vca_deployed_list
= db_nsr
["_admin"]["deployed"]["VCA"]
1029 configuration_status_list
= db_nsr
["configurationStatus"]
1030 for index
, vca_deployed
in enumerate(configuration_status_list
):
1031 if index
== vca_index
:
1034 if not my_vca
.get("member-vnf-index") or \
1035 (vca_deployed
.get("member-vnf-index") == my_vca
.get("member-vnf-index")):
1036 internal_status
= configuration_status_list
[index
].get("status")
1037 if internal_status
== 'READY':
1039 elif internal_status
== 'BROKEN':
1040 raise LcmException("Configuration aborted because dependent charm/s has failed")
1044 # no dependencies, return
1046 await asyncio
.sleep(10)
1049 raise LcmException("Configuration aborted because dependent charm/s timeout")
1051 async def instantiate_N2VC(self
, logging_text
, vca_index
, nsi_id
, db_nsr
, db_vnfr
, vdu_id
, kdu_name
,
1052 vdu_index
, config_descriptor
, deploy_params
, base_folder
, nslcmop_id
):
1053 nsr_id
= db_nsr
["_id"]
1054 db_update_entry
= "_admin.deployed.VCA.{}.".format(vca_index
)
1055 vca_deployed_list
= db_nsr
["_admin"]["deployed"]["VCA"]
1056 vca_deployed
= db_nsr
["_admin"]["deployed"]["VCA"][vca_index
]
1058 'collection': 'nsrs',
1059 'filter': {'_id': nsr_id
},
1060 'path': db_update_entry
1066 element_under_configuration
= nsr_id
1070 vnfr_id
= db_vnfr
["_id"]
1072 namespace
= "{nsi}.{ns}".format(
1073 nsi
=nsi_id
if nsi_id
else "",
1077 element_type
= 'VNF'
1078 element_under_configuration
= vnfr_id
1079 namespace
+= ".{}".format(vnfr_id
)
1081 namespace
+= ".{}-{}".format(vdu_id
, vdu_index
or 0)
1082 element_type
= 'VDU'
1083 element_under_configuration
= "{}-{}".format(vdu_id
, vdu_index
or 0)
1086 self
.fs
.sync() # Sync from FSMongo
1087 artifact_path
= "{}/{}/charms/{}".format(
1088 base_folder
["folder"],
1089 base_folder
["pkg-dir"],
1090 config_descriptor
["juju"]["charm"]
1093 is_proxy_charm
= deep_get(config_descriptor
, ('juju', 'charm')) is not None
1094 if deep_get(config_descriptor
, ('juju', 'proxy')) is False:
1095 is_proxy_charm
= False
1097 # n2vc_redesign STEP 3.1
1099 # find old ee_id if exists
1100 ee_id
= vca_deployed
.get("ee_id")
1102 # create or register execution environment in VCA
1105 self
._write
_configuration
_status
(
1107 vca_index
=vca_index
,
1109 element_under_configuration
=element_under_configuration
,
1110 element_type
=element_type
1113 step
= "create execution environment"
1114 self
.logger
.debug(logging_text
+ step
)
1115 ee_id
, credentials
= await self
.n2vc
.create_execution_environment(namespace
=namespace
,
1120 step
= "Waiting to VM being up and getting IP address"
1121 self
.logger
.debug(logging_text
+ step
)
1122 rw_mgmt_ip
= await self
.wait_vm_up_insert_key_ro(logging_text
, nsr_id
, vnfr_id
, vdu_id
, vdu_index
,
1123 user
=None, pub_key
=None)
1124 credentials
= {"hostname": rw_mgmt_ip
}
1126 username
= deep_get(config_descriptor
, ("config-access", "ssh-access", "default-user"))
1127 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1128 # merged. Meanwhile let's get username from initial-config-primitive
1129 if not username
and config_descriptor
.get("initial-config-primitive"):
1130 for config_primitive
in config_descriptor
["initial-config-primitive"]:
1131 for param
in config_primitive
.get("parameter", ()):
1132 if param
["name"] == "ssh-username":
1133 username
= param
["value"]
1136 raise LcmException("Cannot determine the username neither with 'initial-config-promitive' nor with "
1137 "'config-access.ssh-access.default-user'")
1138 credentials
["username"] = username
1139 # n2vc_redesign STEP 3.2
1141 self
._write
_configuration
_status
(
1143 vca_index
=vca_index
,
1144 status
='REGISTERING',
1145 element_under_configuration
=element_under_configuration
,
1146 element_type
=element_type
1149 step
= "register execution environment {}".format(credentials
)
1150 self
.logger
.debug(logging_text
+ step
)
1151 ee_id
= await self
.n2vc
.register_execution_environment(credentials
=credentials
, namespace
=namespace
,
1154 # for compatibility with MON/POL modules, the need model and application name at database
1155 # TODO ask to N2VC instead of assuming the format "model_name.application_name"
1156 ee_id_parts
= ee_id
.split('.')
1157 model_name
= ee_id_parts
[0]
1158 application_name
= ee_id_parts
[1]
1159 self
.update_db_2("nsrs", nsr_id
, {db_update_entry
+ "model": model_name
,
1160 db_update_entry
+ "application": application_name
,
1161 db_update_entry
+ "ee_id": ee_id
})
1163 # n2vc_redesign STEP 3.3
1165 step
= "Install configuration Software"
1167 self
._write
_configuration
_status
(
1169 vca_index
=vca_index
,
1170 status
='INSTALLING SW',
1171 element_under_configuration
=element_under_configuration
,
1172 element_type
=element_type
1175 # TODO check if already done
1176 self
.logger
.debug(logging_text
+ step
)
1177 await self
.n2vc
.install_configuration_sw(ee_id
=ee_id
, artifact_path
=artifact_path
, db_dict
=db_dict
)
1179 # write in db flag of configuration_sw already installed
1180 self
.update_db_2("nsrs", nsr_id
, {db_update_entry
+ "config_sw_installed": True})
1182 # add relations for this VCA (wait for other peers related with this VCA)
1183 await self
._add
_vca
_relations
(logging_text
=logging_text
, nsr_id
=nsr_id
, vca_index
=vca_index
)
1185 # if SSH access is required, then get execution environment SSH public
1186 if is_proxy_charm
: # if native charm we have waited already to VM be UP
1189 if deep_get(config_descriptor
, ("config-access", "ssh-access", "required")):
1190 # Needed to inject a ssh key
1191 user
= deep_get(config_descriptor
, ("config-access", "ssh-access", "default-user"))
1192 step
= "Install configuration Software, getting public ssh key"
1193 pub_key
= await self
.n2vc
.get_ee_ssh_public__key(ee_id
=ee_id
, db_dict
=db_dict
)
1195 step
= "Insert public key into VM user={} ssh_key={}".format(user
, pub_key
)
1197 step
= "Waiting to VM being up and getting IP address"
1198 self
.logger
.debug(logging_text
+ step
)
1200 # n2vc_redesign STEP 5.1
1201 # wait for RO (ip-address) Insert pub_key into VM
1203 rw_mgmt_ip
= await self
.wait_vm_up_insert_key_ro(logging_text
, nsr_id
, vnfr_id
, vdu_id
, vdu_index
,
1204 user
=user
, pub_key
=pub_key
)
1206 rw_mgmt_ip
= None # This is for a NS configuration
1208 self
.logger
.debug(logging_text
+ ' VM_ip_address={}'.format(rw_mgmt_ip
))
1210 # store rw_mgmt_ip in deploy params for later replacement
1211 deploy_params
["rw_mgmt_ip"] = rw_mgmt_ip
1213 # n2vc_redesign STEP 6 Execute initial config primitive
1214 step
= 'execute initial config primitive'
1215 initial_config_primitive_list
= config_descriptor
.get('initial-config-primitive')
1217 # sort initial config primitives by 'seq'
1218 if initial_config_primitive_list
:
1220 initial_config_primitive_list
.sort(key
=lambda val
: int(val
['seq']))
1221 except Exception as e
:
1222 self
.logger
.error(logging_text
+ step
+ ": " + str(e
))
1224 self
.logger
.debug(logging_text
+ step
+ ": No initial-config-primitive")
1226 # add config if not present for NS charm
1227 initial_config_primitive_list
= self
._get
_initial
_config
_primitive
_list
(initial_config_primitive_list
,
1230 # wait for dependent primitives execution (NS -> VNF -> VDU)
1231 if initial_config_primitive_list
:
1232 await self
._wait
_dependent
_n
2vc
(nsr_id
, vca_deployed_list
, vca_index
)
1234 # stage, in function of element type: vdu, kdu, vnf or ns
1235 my_vca
= vca_deployed_list
[vca_index
]
1236 if my_vca
.get("vdu_id") or my_vca
.get("kdu_name"):
1238 stage
= 'Stage 3/5: running Day-1 primitives for VDU'
1239 elif my_vca
.get("member-vnf-index"):
1241 stage
= 'Stage 4/5: running Day-1 primitives for VNF'
1244 stage
= 'Stage 5/5: running Day-1 primitives for NS'
1246 self
._write
_configuration
_status
(
1248 vca_index
=vca_index
,
1249 status
='EXECUTING PRIMITIVE'
1252 self
._write
_op
_status
(
1257 for initial_config_primitive
in initial_config_primitive_list
:
1258 # adding information on the vca_deployed if it is a NS execution environment
1259 if not vca_deployed
["member-vnf-index"]:
1260 deploy_params
["ns_config_info"] = json
.dumps(self
._get
_ns
_config
_info
(nsr_id
))
1261 # TODO check if already done
1262 primitive_params_
= self
._map
_primitive
_params
(initial_config_primitive
, {}, deploy_params
)
1264 step
= "execute primitive '{}' params '{}'".format(initial_config_primitive
["name"], primitive_params_
)
1265 self
.logger
.debug(logging_text
+ step
)
1266 await self
.n2vc
.exec_primitive(
1268 primitive_name
=initial_config_primitive
["name"],
1269 params_dict
=primitive_params_
,
1273 # TODO register in database that primitive is done
1275 step
= "instantiated at VCA"
1276 self
.logger
.debug(logging_text
+ step
)
1278 self
._write
_configuration
_status
(
1280 vca_index
=vca_index
,
1284 except Exception as e
: # TODO not use Exception but N2VC exception
1285 # self.update_db_2("nsrs", nsr_id, {db_update_entry + "instantiation": "FAILED"})
1286 self
._write
_configuration
_status
(
1288 vca_index
=vca_index
,
1291 raise Exception("{} {}".format(step
, e
)) from e
1292 # TODO raise N2VC exception with 'step' extra information
1294 def _write_ns_status(self
, nsr_id
: str, ns_state
: str, current_operation
: str, current_operation_id
: str,
1295 error_description
: str = None):
1299 db_dict
["nsState"] = ns_state
1300 db_dict
["currentOperation"] = current_operation
1301 db_dict
["currentOperationID"] = current_operation_id
1302 db_dict
["errorDescription"] = error_description
1303 self
.update_db_2("nsrs", nsr_id
, db_dict
)
1304 except Exception as e
:
1305 self
.logger
.warn('Error writing NS status, ns={}: {}'.format(nsr_id
, e
))
1307 def _write_op_status(self
, op_id
: str, stage
: str = None, error_message
: str = None, queuePosition
: int = 0):
1310 db_dict
['queuePosition'] = queuePosition
1311 db_dict
['stage'] = stage
1313 db_dict
['errorMessage'] = error_message
1314 self
.update_db_2("nslcmops", op_id
, db_dict
)
1315 except Exception as e
:
1316 self
.logger
.warn('Error writing OPERATION status for op_id: {} -> {}'.format(op_id
, e
))
1318 def _write_all_config_status(self
, nsr_id
: str, status
: str):
1321 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1322 # configurationStatus
1323 config_status
= db_nsr
.get('configurationStatus')
1327 db_dict
['configurationStatus'] = list()
1328 for c
in config_status
:
1329 c
['status'] = status
1330 db_dict
['configurationStatus'].append(c
)
1331 self
.update_db_2("nsrs", nsr_id
, db_dict
)
1333 except Exception as e
:
1334 self
.logger
.warn('Error writing all configuration status, ns={}: {}'.format(nsr_id
, e
))
1336 def _write_configuration_status(self
, nsr_id
: str, vca_index
: int, status
: str = None,
1337 element_under_configuration
: str = None, element_type
: str = None):
1339 # self.logger.debug('_write_configuration_status(): vca_index={}, status={}'
1340 # .format(vca_index, status))
1343 db_path
= 'configurationStatus.{}.'.format(vca_index
)
1346 db_dict
[db_path
+ 'status'] = status
1347 if element_under_configuration
:
1348 db_dict
[db_path
+ 'elementUnderConfiguration'] = element_under_configuration
1350 db_dict
[db_path
+ 'elementType'] = element_type
1351 self
.update_db_2("nsrs", nsr_id
, db_dict
)
1352 except Exception as e
:
1353 self
.logger
.warn('Error writing configuration status={}, ns={}, vca_index={}: {}'
1354 .format(status
, nsr_id
, vca_index
, e
))
1356 async def instantiate(self
, nsr_id
, nslcmop_id
):
1359 :param nsr_id: ns instance to deploy
1360 :param nslcmop_id: operation to run
1364 # Try to lock HA task here
1365 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
1366 if not task_is_locked_by_me
:
1367 self
.logger
.debug('instantiate() task is not locked by me, ns={}'.format(nsr_id
))
1370 logging_text
= "Task ns={} instantiate={} ".format(nsr_id
, nslcmop_id
)
1371 self
.logger
.debug(logging_text
+ "Enter")
1373 # get all needed from database
1375 # database nsrs record
1378 # database nslcmops record
1381 # update operation on nsrs
1382 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
1383 "_admin.current-operation": nslcmop_id
,
1384 "_admin.operation-type": "instantiate"}
1385 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1387 # update operation on nslcmops
1388 db_nslcmop_update
= {}
1390 nslcmop_operation_state
= None
1391 db_vnfrs
= {} # vnf's info indexed by member-index
1393 task_instantiation_list
= []
1394 task_instantiation_info
= {} # from task to info text
1397 # wait for any previous tasks in process
1398 step
= "Waiting for previous operations to terminate"
1399 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
1401 # STEP 0: Reading database (nslcmops, nsrs, nsds, vnfrs, vnfds)
1403 # nsState="BUILDING", currentOperation="INSTANTIATING", currentOperationID=nslcmop_id
1404 self
._write
_ns
_status
(
1406 ns_state
="BUILDING",
1407 current_operation
="INSTANTIATING",
1408 current_operation_id
=nslcmop_id
1411 # read from db: operation
1412 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
1413 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1414 ns_params
= db_nslcmop
.get("operationParams")
1415 if ns_params
and ns_params
.get("timeout_ns_deploy"):
1416 timeout_ns_deploy
= ns_params
["timeout_ns_deploy"]
1418 timeout_ns_deploy
= self
.timeout
.get("ns_deploy", self
.timeout_ns_deploy
)
1421 step
= "Getting nsr={} from db".format(nsr_id
)
1422 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1423 # nsd is replicated into ns (no db read)
1425 # nsr_name = db_nsr["name"] # TODO short-name??
1427 # read from db: vnf's of this ns
1428 step
= "Getting vnfrs from db"
1429 self
.logger
.debug(logging_text
+ step
)
1430 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1432 # read from db: vnfd's for every vnf
1433 db_vnfds_ref
= {} # every vnfd data indexed by vnf name
1434 db_vnfds
= {} # every vnfd data indexed by vnf id
1435 db_vnfds_index
= {} # every vnfd data indexed by vnf member-index
1437 self
._write
_op
_status
(
1439 stage
='Stage 1/5: preparation of the environment',
1443 # for each vnf in ns, read vnfd
1444 for vnfr
in db_vnfrs_list
:
1445 db_vnfrs
[vnfr
["member-vnf-index-ref"]] = vnfr
# vnf's dict indexed by member-index: '1', '2', etc
1446 vnfd_id
= vnfr
["vnfd-id"] # vnfd uuid for this vnf
1447 vnfd_ref
= vnfr
["vnfd-ref"] # vnfd name for this vnf
1448 # if we haven't this vnfd, read it from db
1449 if vnfd_id
not in db_vnfds
:
1451 step
= "Getting vnfd={} id='{}' from db".format(vnfd_id
, vnfd_ref
)
1452 self
.logger
.debug(logging_text
+ step
)
1453 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
1456 db_vnfds_ref
[vnfd_ref
] = vnfd
# vnfd's indexed by name
1457 db_vnfds
[vnfd_id
] = vnfd
# vnfd's indexed by id
1458 db_vnfds_index
[vnfr
["member-vnf-index-ref"]] = db_vnfds
[vnfd_id
] # vnfd's indexed by member-index
1460 # Get or generates the _admin.deployed.VCA list
1461 vca_deployed_list
= None
1462 if db_nsr
["_admin"].get("deployed"):
1463 vca_deployed_list
= db_nsr
["_admin"]["deployed"].get("VCA")
1464 if vca_deployed_list
is None:
1465 vca_deployed_list
= []
1466 configuration_status_list
= []
1467 db_nsr_update
["_admin.deployed.VCA"] = vca_deployed_list
1468 db_nsr_update
["configurationStatus"] = configuration_status_list
1469 # add _admin.deployed.VCA to db_nsr dictionary, value=vca_deployed_list
1470 populate_dict(db_nsr
, ("_admin", "deployed", "VCA"), vca_deployed_list
)
1471 elif isinstance(vca_deployed_list
, dict):
1472 # maintain backward compatibility. Change a dict to list at database
1473 vca_deployed_list
= list(vca_deployed_list
.values())
1474 db_nsr_update
["_admin.deployed.VCA"] = vca_deployed_list
1475 populate_dict(db_nsr
, ("_admin", "deployed", "VCA"), vca_deployed_list
)
1477 db_nsr_update
["detailed-status"] = "creating"
1478 db_nsr_update
["operational-status"] = "init"
1480 if not isinstance(deep_get(db_nsr
, ("_admin", "deployed", "RO", "vnfd")), list):
1481 populate_dict(db_nsr
, ("_admin", "deployed", "RO", "vnfd"), [])
1482 db_nsr_update
["_admin.deployed.RO.vnfd"] = []
1484 # set state to INSTANTIATED. When instantiated NBI will not delete directly
1485 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1486 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1488 # n2vc_redesign STEP 2 Deploy Network Scenario
1490 self
._write
_op
_status
(
1492 stage
='Stage 2/5: deployment of VMs and execution environments'
1495 self
.logger
.debug(logging_text
+ "Before deploy_kdus")
1496 # Call to deploy_kdus in case exists the "vdu:kdu" param
1497 task_kdu
= asyncio
.ensure_future(
1499 logging_text
=logging_text
,
1506 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_KDUs", task_kdu
)
1507 task_instantiation_info
[task_kdu
] = "Deploy KDUs"
1508 task_instantiation_list
.append(task_kdu
)
1509 # n2vc_redesign STEP 1 Get VCA public ssh-key
1510 # feature 1429. Add n2vc public key to needed VMs
1511 n2vc_key
= self
.n2vc
.get_public_key()
1512 n2vc_key_list
= [n2vc_key
]
1513 if self
.vca_config
.get("public_key"):
1514 n2vc_key_list
.append(self
.vca_config
["public_key"])
1516 task_ro
= asyncio
.ensure_future(
1517 self
.instantiate_RO(
1518 logging_text
=logging_text
,
1522 db_nslcmop
=db_nslcmop
,
1524 db_vnfds_ref
=db_vnfds_ref
,
1525 n2vc_key_list
=n2vc_key_list
1528 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_RO", task_ro
)
1529 task_instantiation_info
[task_ro
] = "Deploy at VIM"
1530 task_instantiation_list
.append(task_ro
)
1532 # n2vc_redesign STEP 3 to 6 Deploy N2VC
1533 step
= "Deploying proxy and native charms"
1534 self
.logger
.debug(logging_text
+ step
)
1536 nsi_id
= None # TODO put nsi_id when this nsr belongs to a NSI
1537 # get_iterable() returns a value from a dict or empty tuple if key does not exist
1538 for c_vnf
in get_iterable(nsd
, "constituent-vnfd"):
1539 vnfd_id
= c_vnf
["vnfd-id-ref"]
1540 vnfd
= db_vnfds_ref
[vnfd_id
]
1541 member_vnf_index
= str(c_vnf
["member-vnf-index"])
1542 db_vnfr
= db_vnfrs
[member_vnf_index
]
1543 base_folder
= vnfd
["_admin"]["storage"]
1549 # Get additional parameters
1551 if db_vnfr
.get("additionalParamsForVnf"):
1552 deploy_params
= self
._format
_additional
_params
(db_vnfr
["additionalParamsForVnf"].copy())
1554 descriptor_config
= vnfd
.get("vnf-configuration")
1555 if descriptor_config
and descriptor_config
.get("juju"):
1557 logging_text
=logging_text
+ "member_vnf_index={} ".format(member_vnf_index
),
1560 nslcmop_id
=nslcmop_id
,
1566 member_vnf_index
=member_vnf_index
,
1567 vdu_index
=vdu_index
,
1569 deploy_params
=deploy_params
,
1570 descriptor_config
=descriptor_config
,
1571 base_folder
=base_folder
,
1572 task_instantiation_list
=task_instantiation_list
,
1573 task_instantiation_info
=task_instantiation_info
1576 # Deploy charms for each VDU that supports one.
1577 for vdud
in get_iterable(vnfd
, 'vdu'):
1579 descriptor_config
= vdud
.get('vdu-configuration')
1580 vdur
= next((x
for x
in db_vnfr
["vdur"] if x
["vdu-id-ref"] == vdu_id
), None)
1581 if vdur
.get("additionalParams"):
1582 deploy_params_vdu
= self
._format
_additional
_params
(vdur
["additionalParams"])
1584 deploy_params_vdu
= deploy_params
1585 if descriptor_config
and descriptor_config
.get("juju"):
1586 # look for vdu index in the db_vnfr["vdu"] section
1587 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
1588 # if vdur["vdu-id-ref"] == vdu_id:
1591 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
1592 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
1593 # vdu_name = vdur.get("name")
1596 for vdu_index
in range(int(vdud
.get("count", 1))):
1597 # TODO vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
1599 logging_text
=logging_text
+ "member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
1600 member_vnf_index
, vdu_id
, vdu_index
),
1603 nslcmop_id
=nslcmop_id
,
1609 member_vnf_index
=member_vnf_index
,
1610 vdu_index
=vdu_index
,
1612 deploy_params
=deploy_params_vdu
,
1613 descriptor_config
=descriptor_config
,
1614 base_folder
=base_folder
,
1615 task_instantiation_list
=task_instantiation_list
,
1616 task_instantiation_info
=task_instantiation_info
1618 for kdud
in get_iterable(vnfd
, 'kdu'):
1619 kdu_name
= kdud
["name"]
1620 descriptor_config
= kdud
.get('kdu-configuration')
1621 if descriptor_config
and descriptor_config
.get("juju"):
1625 # look for vdu index in the db_vnfr["vdu"] section
1626 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
1627 # if vdur["vdu-id-ref"] == vdu_id:
1630 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
1631 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
1632 # vdu_name = vdur.get("name")
1636 logging_text
=logging_text
,
1639 nslcmop_id
=nslcmop_id
,
1645 member_vnf_index
=member_vnf_index
,
1646 vdu_index
=vdu_index
,
1648 deploy_params
=deploy_params
,
1649 descriptor_config
=descriptor_config
,
1650 base_folder
=base_folder
,
1651 task_instantiation_list
=task_instantiation_list
,
1652 task_instantiation_info
=task_instantiation_info
1655 # Check if this NS has a charm configuration
1656 descriptor_config
= nsd
.get("ns-configuration")
1657 if descriptor_config
and descriptor_config
.get("juju"):
1660 member_vnf_index
= None
1666 # Get additional parameters
1668 if db_nsr
.get("additionalParamsForNs"):
1669 deploy_params
= self
._format
_additional
_params
(db_nsr
["additionalParamsForNs"].copy())
1670 base_folder
= nsd
["_admin"]["storage"]
1672 logging_text
=logging_text
,
1675 nslcmop_id
=nslcmop_id
,
1681 member_vnf_index
=member_vnf_index
,
1682 vdu_index
=vdu_index
,
1684 deploy_params
=deploy_params
,
1685 descriptor_config
=descriptor_config
,
1686 base_folder
=base_folder
,
1687 task_instantiation_list
=task_instantiation_list
,
1688 task_instantiation_info
=task_instantiation_info
1691 # Wait until all tasks of "task_instantiation_list" have been finished
1693 error_text_list
= []
1695 # let's begin with all OK
1696 instantiated_ok
= True
1697 # let's begin with RO 'running' status (later we can change it)
1698 db_nsr_update
["operational-status"] = "running"
1699 # let's begin with VCA 'configured' status (later we can change it)
1700 db_nsr_update
["config-status"] = "configured"
1702 step
= "Waiting for tasks to be finished"
1703 if task_instantiation_list
:
1704 # wait for all tasks completion
1705 done
, pending
= await asyncio
.wait(task_instantiation_list
, timeout
=timeout_ns_deploy
)
1707 for task
in pending
:
1708 instantiated_ok
= False
1709 if task
in (task_ro
, task_kdu
):
1710 # RO or KDU task is pending
1711 db_nsr_update
["operational-status"] = "failed"
1713 # A N2VC task is pending
1714 db_nsr_update
["config-status"] = "failed"
1715 self
.logger
.error(logging_text
+ task_instantiation_info
[task
] + ": Timeout")
1716 error_text_list
.append(task_instantiation_info
[task
] + ": Timeout")
1718 if task
.cancelled():
1719 instantiated_ok
= False
1720 if task
in (task_ro
, task_kdu
):
1721 # RO or KDU task was cancelled
1722 db_nsr_update
["operational-status"] = "failed"
1724 # A N2VC was cancelled
1725 db_nsr_update
["config-status"] = "failed"
1726 self
.logger
.warn(logging_text
+ task_instantiation_info
[task
] + ": Cancelled")
1727 error_text_list
.append(task_instantiation_info
[task
] + ": Cancelled")
1729 exc
= task
.exception()
1731 instantiated_ok
= False
1732 if task
in (task_ro
, task_kdu
):
1733 # RO or KDU task raised an exception
1734 db_nsr_update
["operational-status"] = "failed"
1736 # A N2VC task raised an exception
1737 db_nsr_update
["config-status"] = "failed"
1738 self
.logger
.error(logging_text
+ task_instantiation_info
[task
] + ": Failed")
1740 if isinstance(exc
, (N2VCException
, ROclient
.ROClientException
)):
1741 error_text_list
.append(task_instantiation_info
[task
] + ": {}".format(exc
))
1743 exc_traceback
= "".join(traceback
.format_exception(None, exc
, exc
.__traceback
__))
1744 self
.logger
.error(logging_text
+ task_instantiation_info
[task
] + exc_traceback
)
1745 error_text_list
.append(task_instantiation_info
[task
] + ": " + exc_traceback
)
1747 self
.logger
.debug(logging_text
+ task_instantiation_info
[task
] + ": Done")
1750 error_text
= "\n".join(error_text_list
)
1751 db_nsr_update
["detailed-status"] = error_text
1752 db_nslcmop_update
["detailed-status"] = error_text
1753 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
1754 db_nslcmop_update
["statusEnteredTime"] = time()
1757 db_nsr_update
["detailed-status"] = "done"
1758 db_nslcmop_update
["detailed-status"] = "done"
1759 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
1760 db_nslcmop_update
["statusEnteredTime"] = time()
1762 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
1763 self
.logger
.error(logging_text
+ "Exit Exception while '{}': {}".format(step
, e
))
1765 except asyncio
.CancelledError
:
1766 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1767 exc
= "Operation was cancelled"
1768 except Exception as e
:
1769 exc
= traceback
.format_exc()
1770 self
.logger
.critical(logging_text
+ "Exit Exception {} while '{}': {}".format(type(e
).__name
__, step
, e
),
1775 db_nsr_update
["detailed-status"] = "ERROR {}: {}".format(step
, exc
)
1776 db_nsr_update
["operational-status"] = "failed"
1777 db_nsr_update
["config-status"] = "failed"
1779 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
1780 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
1781 db_nslcmop_update
["statusEnteredTime"] = time()
1784 db_nsr_update
["_admin.nslcmop"] = None
1785 db_nsr_update
["_admin.current-operation"] = None
1786 db_nsr_update
["_admin.operation-type"] = None
1787 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1789 # nsState="READY/BROKEN", currentOperation="IDLE", currentOperationID=None
1791 error_description
= None
1796 error_description
= 'Operation: INSTANTIATING.{}, step: {}'.format(nslcmop_id
, step
)
1798 self
._write
_ns
_status
(
1801 current_operation
="IDLE",
1802 current_operation_id
=None,
1803 error_description
=error_description
1806 self
._write
_op
_status
(
1808 error_message
=error_description
1811 if db_nslcmop_update
:
1812 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1814 self
.logger
.debug(logging_text
+ 'End of instantiation: {}'.format(instantiated_ok
))
1816 except DbException
as e
:
1817 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
1819 if nslcmop_operation_state
:
1821 await self
.msg
.aiowrite("ns", "instantiated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
1822 "operationState": nslcmop_operation_state
},
1824 except Exception as e
:
1825 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1827 self
.logger
.debug(logging_text
+ "Exit")
1828 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_instantiate")
1830 async def _add_vca_relations(self
, logging_text
, nsr_id
, vca_index
: int, timeout
: int = 3600) -> bool:
1833 # 1. find all relations for this VCA
1834 # 2. wait for other peers related
1839 # STEP 1: find all relations for this VCA
1842 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1845 my_vca
= deep_get(db_nsr
, ('_admin', 'deployed', 'VCA'))[vca_index
]
1847 # read all ns-configuration relations
1848 ns_relations
= list()
1849 db_ns_relations
= deep_get(db_nsr
, ('nsd', 'ns-configuration', 'relation'))
1851 for r
in db_ns_relations
:
1852 # check if this VCA is in the relation
1853 if my_vca
.get('member-vnf-index') in\
1854 (r
.get('entities')[0].get('id'), r
.get('entities')[1].get('id')):
1855 ns_relations
.append(r
)
1857 # read all vnf-configuration relations
1858 vnf_relations
= list()
1859 db_vnfd_list
= db_nsr
.get('vnfd-id')
1861 for vnfd
in db_vnfd_list
:
1862 db_vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd
})
1863 db_vnf_relations
= deep_get(db_vnfd
, ('vnf-configuration', 'relation'))
1864 if db_vnf_relations
:
1865 for r
in db_vnf_relations
:
1866 # check if this VCA is in the relation
1867 if my_vca
.get('vdu_id') in (r
.get('entities')[0].get('id'), r
.get('entities')[1].get('id')):
1868 vnf_relations
.append(r
)
1870 # if no relations, terminate
1871 if not ns_relations
and not vnf_relations
:
1872 self
.logger
.debug(logging_text
+ ' No relations')
1875 self
.logger
.debug(logging_text
+ ' adding relations\n {}\n {}'.format(ns_relations
, vnf_relations
))
1882 if now
- start
>= timeout
:
1883 self
.logger
.error(logging_text
+ ' : timeout adding relations')
1886 # reload nsr from database (we need to update record: _admin.deloyed.VCA)
1887 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1889 # for each defined NS relation, find the VCA's related
1890 for r
in ns_relations
:
1891 from_vca_ee_id
= None
1893 from_vca_endpoint
= None
1894 to_vca_endpoint
= None
1895 vca_list
= deep_get(db_nsr
, ('_admin', 'deployed', 'VCA'))
1896 for vca
in vca_list
:
1897 if vca
.get('member-vnf-index') == r
.get('entities')[0].get('id') \
1898 and vca
.get('config_sw_installed'):
1899 from_vca_ee_id
= vca
.get('ee_id')
1900 from_vca_endpoint
= r
.get('entities')[0].get('endpoint')
1901 if vca
.get('member-vnf-index') == r
.get('entities')[1].get('id') \
1902 and vca
.get('config_sw_installed'):
1903 to_vca_ee_id
= vca
.get('ee_id')
1904 to_vca_endpoint
= r
.get('entities')[1].get('endpoint')
1905 if from_vca_ee_id
and to_vca_ee_id
:
1907 await self
.n2vc
.add_relation(
1908 ee_id_1
=from_vca_ee_id
,
1909 ee_id_2
=to_vca_ee_id
,
1910 endpoint_1
=from_vca_endpoint
,
1911 endpoint_2
=to_vca_endpoint
)
1912 # remove entry from relations list
1913 ns_relations
.remove(r
)
1915 # check failed peers
1917 vca_status_list
= db_nsr
.get('configurationStatus')
1919 for i
in range(len(vca_list
)):
1921 vca_status
= vca_status_list
[i
]
1922 if vca
.get('member-vnf-index') == r
.get('entities')[0].get('id'):
1923 if vca_status
.get('status') == 'BROKEN':
1924 # peer broken: remove relation from list
1925 ns_relations
.remove(r
)
1926 if vca
.get('member-vnf-index') == r
.get('entities')[1].get('id'):
1927 if vca_status
.get('status') == 'BROKEN':
1928 # peer broken: remove relation from list
1929 ns_relations
.remove(r
)
1934 # for each defined VNF relation, find the VCA's related
1935 for r
in vnf_relations
:
1936 from_vca_ee_id
= None
1938 from_vca_endpoint
= None
1939 to_vca_endpoint
= None
1940 vca_list
= deep_get(db_nsr
, ('_admin', 'deployed', 'VCA'))
1941 for vca
in vca_list
:
1942 if vca
.get('vdu_id') == r
.get('entities')[0].get('id') and vca
.get('config_sw_installed'):
1943 from_vca_ee_id
= vca
.get('ee_id')
1944 from_vca_endpoint
= r
.get('entities')[0].get('endpoint')
1945 if vca
.get('vdu_id') == r
.get('entities')[1].get('id') and vca
.get('config_sw_installed'):
1946 to_vca_ee_id
= vca
.get('ee_id')
1947 to_vca_endpoint
= r
.get('entities')[1].get('endpoint')
1948 if from_vca_ee_id
and to_vca_ee_id
:
1950 await self
.n2vc
.add_relation(
1951 ee_id_1
=from_vca_ee_id
,
1952 ee_id_2
=to_vca_ee_id
,
1953 endpoint_1
=from_vca_endpoint
,
1954 endpoint_2
=to_vca_endpoint
)
1955 # remove entry from relations list
1956 vnf_relations
.remove(r
)
1958 # check failed peers
1960 vca_status_list
= db_nsr
.get('configurationStatus')
1962 for i
in range(len(vca_list
)):
1964 vca_status
= vca_status_list
[i
]
1965 if vca
.get('vdu_id') == r
.get('entities')[0].get('id'):
1966 if vca_status
.get('status') == 'BROKEN':
1967 # peer broken: remove relation from list
1968 ns_relations
.remove(r
)
1969 if vca
.get('vdu_id') == r
.get('entities')[1].get('id'):
1970 if vca_status
.get('status') == 'BROKEN':
1971 # peer broken: remove relation from list
1972 ns_relations
.remove(r
)
1978 await asyncio
.sleep(5.0)
1980 if not ns_relations
and not vnf_relations
:
1981 self
.logger
.debug('Relations added')
1986 except Exception as e
:
1987 self
.logger
.warn(logging_text
+ ' ERROR adding relations: {}'.format(e
))
1990 async def deploy_kdus(self
, logging_text
, nsr_id
, db_nsr
, db_vnfrs
, db_vnfds
):
1991 # Launch kdus if present in the descriptor
1995 k8scluster_id_2_uuic
= {"helm-chart": {}, "juju-bundle": {}}
1997 def _get_cluster_id(cluster_id
, cluster_type
):
1998 nonlocal k8scluster_id_2_uuic
1999 if cluster_id
in k8scluster_id_2_uuic
[cluster_type
]:
2000 return k8scluster_id_2_uuic
[cluster_type
][cluster_id
]
2002 db_k8scluster
= self
.db
.get_one("k8sclusters", {"_id": cluster_id
}, fail_on_empty
=False)
2003 if not db_k8scluster
:
2004 raise LcmException("K8s cluster {} cannot be found".format(cluster_id
))
2005 k8s_id
= deep_get(db_k8scluster
, ("_admin", cluster_type
, "id"))
2007 raise LcmException("K8s cluster '{}' has not been initilized for '{}'".format(cluster_id
, cluster_type
))
2008 k8scluster_id_2_uuic
[cluster_type
][cluster_id
] = k8s_id
2011 logging_text
+= "Deploy kdus: "
2013 db_nsr_update
= {"_admin.deployed.K8s": []}
2014 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2016 # Look for all vnfds
2019 for vnfr_data
in db_vnfrs
.values():
2020 for kdur
in get_iterable(vnfr_data
, "kdur"):
2021 desc_params
= self
._format
_additional
_params
(kdur
.get("additionalParams"))
2023 k8sclustertype
= None
2026 vnfd_id
= vnfr_data
.get('vnfd-id')
2027 pkgdir
= deep_get(db_vnfds
.get(vnfd_id
), ('_admin', 'storage', 'pkg-dir'))
2028 if kdur
.get("helm-chart"):
2029 kdumodel
= kdur
["helm-chart"]
2030 k8sclustertype
= "chart"
2031 k8sclustertype_full
= "helm-chart"
2032 elif kdur
.get("juju-bundle"):
2033 kdumodel
= kdur
["juju-bundle"]
2034 k8sclustertype
= "juju"
2035 k8sclustertype_full
= "juju-bundle"
2037 error_text
= "kdu type is neither helm-chart nor juju-bundle. Maybe an old NBI version is" \
2039 # check if kdumodel is a file and exists
2041 # path format: /vnfdid/pkkdir/kdumodel
2042 filename
= '{}/{}/{}s/{}'.format(vnfd_id
, pkgdir
, k8sclustertype_full
, kdumodel
)
2043 if self
.fs
.file_exists(filename
, mode
='file') or self
.fs
.file_exists(filename
, mode
='dir'):
2044 kdumodel
= self
.fs
.path
+ filename
2050 cluster_uuid
= _get_cluster_id(kdur
["k8s-cluster"]["id"], k8sclustertype_full
)
2051 except LcmException
as e
:
2055 step
= "Instantiate KDU {} in k8s cluster {}".format(kdur
["kdu-name"], cluster_uuid
)
2057 k8s_instace_info
= {"kdu-instance": None, "k8scluster-uuid": cluster_uuid
,
2058 "k8scluster-type": k8sclustertype
,
2059 "kdu-name": kdur
["kdu-name"], "kdu-model": kdumodel
}
2061 k8s_instace_info
["detailed-status"] = error_text
2062 db_nsr_update
["_admin.deployed.K8s.{}".format(index
)] = k8s_instace_info
2063 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2067 db_dict
= {"collection": "nsrs", "filter": {"_id": nsr_id
}, "path": "_admin.deployed.K8s."
2069 if k8sclustertype
== "chart":
2070 task
= asyncio
.ensure_future(
2071 self
.k8sclusterhelm
.install(cluster_uuid
=cluster_uuid
, kdu_model
=kdumodel
, atomic
=True,
2072 params
=desc_params
, db_dict
=db_dict
, timeout
=3600)
2075 task
= asyncio
.ensure_future(
2076 self
.k8sclusterjuju
.install(cluster_uuid
=cluster_uuid
, kdu_model
=kdumodel
,
2077 atomic
=True, params
=desc_params
,
2078 db_dict
=db_dict
, timeout
=600)
2081 pending_tasks
[task
] = "_admin.deployed.K8s.{}.".format(index
)
2083 if not pending_tasks
:
2085 self
.logger
.debug(logging_text
+ 'Waiting for terminate pending tasks...')
2086 pending_list
= list(pending_tasks
.keys())
2088 done_list
, pending_list
= await asyncio
.wait(pending_list
, timeout
=30*60,
2089 return_when
=asyncio
.FIRST_COMPLETED
)
2090 if not done_list
: # timeout
2091 for task
in pending_list
:
2092 db_nsr_update
[pending_tasks(task
) + "detailed-status"] = "Timeout"
2095 for task
in done_list
:
2096 exc
= task
.exception()
2098 db_nsr_update
[pending_tasks
[task
] + "detailed-status"] = "{}".format(exc
)
2101 db_nsr_update
[pending_tasks
[task
] + "kdu-instance"] = task
.result()
2104 raise LcmException('Cannot deploy KDUs')
2106 except Exception as e
:
2107 self
.logger
.critical(logging_text
+ "Exit Exception {} while '{}': {}".format(type(e
).__name
__, step
, e
))
2108 raise LcmException("{} Exit Exception {} while '{}': {}".format(logging_text
, type(e
).__name
__, step
, e
))
2111 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2113 def _deploy_n2vc(self
, logging_text
, db_nsr
, db_vnfr
, nslcmop_id
, nsr_id
, nsi_id
, vnfd_id
, vdu_id
,
2114 kdu_name
, member_vnf_index
, vdu_index
, vdu_name
, deploy_params
, descriptor_config
,
2115 base_folder
, task_instantiation_list
, task_instantiation_info
):
2116 # launch instantiate_N2VC in a asyncio task and register task object
2117 # Look where information of this charm is at database <nsrs>._admin.deployed.VCA
2118 # if not found, create one entry and update database
2120 # fill db_nsr._admin.deployed.VCA.<index>
2122 for vca_index
, vca_deployed
in enumerate(db_nsr
["_admin"]["deployed"]["VCA"]):
2123 if not vca_deployed
:
2125 if vca_deployed
.get("member-vnf-index") == member_vnf_index
and \
2126 vca_deployed
.get("vdu_id") == vdu_id
and \
2127 vca_deployed
.get("kdu_name") == kdu_name
and \
2128 vca_deployed
.get("vdu_count_index", 0) == vdu_index
:
2131 # not found, create one.
2133 "member-vnf-index": member_vnf_index
,
2135 "kdu_name": kdu_name
,
2136 "vdu_count_index": vdu_index
,
2137 "operational-status": "init", # TODO revise
2138 "detailed-status": "", # TODO revise
2139 "step": "initial-deploy", # TODO revise
2141 "vdu_name": vdu_name
,
2145 # create VCA and configurationStatus in db
2147 "_admin.deployed.VCA.{}".format(vca_index
): vca_deployed
,
2148 "configurationStatus.{}".format(vca_index
): dict()
2150 self
.update_db_2("nsrs", nsr_id
, db_dict
)
2152 db_nsr
["_admin"]["deployed"]["VCA"].append(vca_deployed
)
2155 task_n2vc
= asyncio
.ensure_future(
2156 self
.instantiate_N2VC(
2157 logging_text
=logging_text
,
2158 vca_index
=vca_index
,
2164 vdu_index
=vdu_index
,
2165 deploy_params
=deploy_params
,
2166 config_descriptor
=descriptor_config
,
2167 base_folder
=base_folder
,
2168 nslcmop_id
=nslcmop_id
2171 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_N2VC-{}".format(vca_index
), task_n2vc
)
2172 task_instantiation_info
[task_n2vc
] = "Deploy VCA {}.{}".format(member_vnf_index
or "", vdu_id
or "")
2173 task_instantiation_list
.append(task_n2vc
)
2175 # Check if this VNFD has a configured terminate action
2176 def _has_terminate_config_primitive(self
, vnfd
):
2177 vnf_config
= vnfd
.get("vnf-configuration")
2178 if vnf_config
and vnf_config
.get("terminate-config-primitive"):
2184 def _get_terminate_config_primitive_seq_list(vnfd
):
2185 """ Get a numerically sorted list of the sequences for this VNFD's terminate action """
2186 # No need to check for existing primitive twice, already done before
2187 vnf_config
= vnfd
.get("vnf-configuration")
2188 seq_list
= vnf_config
.get("terminate-config-primitive")
2189 # Get all 'seq' tags in seq_list, order sequences numerically, ascending.
2190 seq_list_sorted
= sorted(seq_list
, key
=lambda x
: int(x
['seq']))
2191 return seq_list_sorted
2194 def _create_nslcmop(nsr_id
, operation
, params
):
2196 Creates a ns-lcm-opp content to be stored at database.
2197 :param nsr_id: internal id of the instance
2198 :param operation: instantiate, terminate, scale, action, ...
2199 :param params: user parameters for the operation
2200 :return: dictionary following SOL005 format
2202 # Raise exception if invalid arguments
2203 if not (nsr_id
and operation
and params
):
2205 "Parameters 'nsr_id', 'operation' and 'params' needed to create primitive not provided")
2211 # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2212 "operationState": "PROCESSING",
2213 "statusEnteredTime": now
,
2214 "nsInstanceId": nsr_id
,
2215 "lcmOperationType": operation
,
2217 "isAutomaticInvocation": False,
2218 "operationParams": params
,
2219 "isCancelPending": False,
2221 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
2222 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
2227 def _format_additional_params(self
, params
):
2228 params
= params
or {}
2229 for key
, value
in params
.items():
2230 if str(value
).startswith("!!yaml "):
2231 params
[key
] = yaml
.safe_load(value
[7:])
2234 def _get_terminate_primitive_params(self
, seq
, vnf_index
):
2235 primitive
= seq
.get('name')
2236 primitive_params
= {}
2238 "member_vnf_index": vnf_index
,
2239 "primitive": primitive
,
2240 "primitive_params": primitive_params
,
2243 return self
._map
_primitive
_params
(seq
, params
, desc_params
)
2247 def _reintent_or_skip_suboperation(self
, db_nslcmop
, op_index
):
2248 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
2249 if (op
.get('operationState') == 'COMPLETED'):
2250 # b. Skip sub-operation
2251 # _ns_execute_primitive() or RO.create_action() will NOT be executed
2252 return self
.SUBOPERATION_STATUS_SKIP
2254 # c. Reintent executing sub-operation
2255 # The sub-operation exists, and operationState != 'COMPLETED'
2256 # Update operationState = 'PROCESSING' to indicate a reintent.
2257 operationState
= 'PROCESSING'
2258 detailed_status
= 'In progress'
2259 self
._update
_suboperation
_status
(
2260 db_nslcmop
, op_index
, operationState
, detailed_status
)
2261 # Return the sub-operation index
2262 # _ns_execute_primitive() or RO.create_action() will be called from scale()
2263 # with arguments extracted from the sub-operation
2266 # Find a sub-operation where all keys in a matching dictionary must match
2267 # Returns the index of the matching sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if no match
2268 def _find_suboperation(self
, db_nslcmop
, match
):
2269 if (db_nslcmop
and match
):
2270 op_list
= db_nslcmop
.get('_admin', {}).get('operations', [])
2271 for i
, op
in enumerate(op_list
):
2272 if all(op
.get(k
) == match
[k
] for k
in match
):
2274 return self
.SUBOPERATION_STATUS_NOT_FOUND
2276 # Update status for a sub-operation given its index
2277 def _update_suboperation_status(self
, db_nslcmop
, op_index
, operationState
, detailed_status
):
2278 # Update DB for HA tasks
2279 q_filter
= {'_id': db_nslcmop
['_id']}
2280 update_dict
= {'_admin.operations.{}.operationState'.format(op_index
): operationState
,
2281 '_admin.operations.{}.detailed-status'.format(op_index
): detailed_status
}
2282 self
.db
.set_one("nslcmops",
2284 update_dict
=update_dict
,
2285 fail_on_empty
=False)
2287 # Add sub-operation, return the index of the added sub-operation
2288 # Optionally, set operationState, detailed-status, and operationType
2289 # Status and type are currently set for 'scale' sub-operations:
2290 # 'operationState' : 'PROCESSING' | 'COMPLETED' | 'FAILED'
2291 # 'detailed-status' : status message
2292 # 'operationType': may be any type, in the case of scaling: 'PRE-SCALE' | 'POST-SCALE'
2293 # Status and operation type are currently only used for 'scale', but NOT for 'terminate' sub-operations.
2294 def _add_suboperation(self
, db_nslcmop
, vnf_index
, vdu_id
, vdu_count_index
, vdu_name
, primitive
,
2295 mapped_primitive_params
, operationState
=None, detailed_status
=None, operationType
=None,
2296 RO_nsr_id
=None, RO_scaling_info
=None):
2297 if not (db_nslcmop
):
2298 return self
.SUBOPERATION_STATUS_NOT_FOUND
2299 # Get the "_admin.operations" list, if it exists
2300 db_nslcmop_admin
= db_nslcmop
.get('_admin', {})
2301 op_list
= db_nslcmop_admin
.get('operations')
2302 # Create or append to the "_admin.operations" list
2303 new_op
= {'member_vnf_index': vnf_index
,
2305 'vdu_count_index': vdu_count_index
,
2306 'primitive': primitive
,
2307 'primitive_params': mapped_primitive_params
}
2309 new_op
['operationState'] = operationState
2311 new_op
['detailed-status'] = detailed_status
2313 new_op
['lcmOperationType'] = operationType
2315 new_op
['RO_nsr_id'] = RO_nsr_id
2317 new_op
['RO_scaling_info'] = RO_scaling_info
2319 # No existing operations, create key 'operations' with current operation as first list element
2320 db_nslcmop_admin
.update({'operations': [new_op
]})
2321 op_list
= db_nslcmop_admin
.get('operations')
2323 # Existing operations, append operation to list
2324 op_list
.append(new_op
)
2326 db_nslcmop_update
= {'_admin.operations': op_list
}
2327 self
.update_db_2("nslcmops", db_nslcmop
['_id'], db_nslcmop_update
)
2328 op_index
= len(op_list
) - 1
2331 # Helper methods for scale() sub-operations
2333 # pre-scale/post-scale:
2334 # Check for 3 different cases:
2335 # a. New: First time execution, return SUBOPERATION_STATUS_NEW
2336 # b. Skip: Existing sub-operation exists, operationState == 'COMPLETED', return SUBOPERATION_STATUS_SKIP
2337 # c. Reintent: Existing sub-operation exists, operationState != 'COMPLETED', return op_index to re-execute
2338 def _check_or_add_scale_suboperation(self
, db_nslcmop
, vnf_index
, vnf_config_primitive
, primitive_params
,
2339 operationType
, RO_nsr_id
=None, RO_scaling_info
=None):
2340 # Find this sub-operation
2341 if (RO_nsr_id
and RO_scaling_info
):
2342 operationType
= 'SCALE-RO'
2344 'member_vnf_index': vnf_index
,
2345 'RO_nsr_id': RO_nsr_id
,
2346 'RO_scaling_info': RO_scaling_info
,
2350 'member_vnf_index': vnf_index
,
2351 'primitive': vnf_config_primitive
,
2352 'primitive_params': primitive_params
,
2353 'lcmOperationType': operationType
2355 op_index
= self
._find
_suboperation
(db_nslcmop
, match
)
2356 if (op_index
== self
.SUBOPERATION_STATUS_NOT_FOUND
):
2357 # a. New sub-operation
2358 # The sub-operation does not exist, add it.
2359 # _ns_execute_primitive() will be called from scale() as usual, with non-modified arguments
2360 # The following parameters are set to None for all kind of scaling:
2362 vdu_count_index
= None
2364 if (RO_nsr_id
and RO_scaling_info
):
2365 vnf_config_primitive
= None
2366 primitive_params
= None
2369 RO_scaling_info
= None
2370 # Initial status for sub-operation
2371 operationState
= 'PROCESSING'
2372 detailed_status
= 'In progress'
2373 # Add sub-operation for pre/post-scaling (zero or more operations)
2374 self
._add
_suboperation
(db_nslcmop
,
2379 vnf_config_primitive
,
2386 return self
.SUBOPERATION_STATUS_NEW
2388 # Return either SUBOPERATION_STATUS_SKIP (operationState == 'COMPLETED'),
2389 # or op_index (operationState != 'COMPLETED')
2390 return self
._reintent
_or
_skip
_suboperation
(db_nslcmop
, op_index
)
2392 # Function to return execution_environment id
2394 def _get_ee_id(self
, vnf_index
, vdu_id
, vca_deployed_list
):
2395 for vca
in vca_deployed_list
:
2396 if vca
["member-vnf-index"] == vnf_index
and vca
["vdu_id"] == vdu_id
:
2399 # Helper methods for terminate()
2401 async def _terminate_action(self
, db_nslcmop
, nslcmop_id
, nsr_id
):
2402 """ Create a primitive with params from VNFD
2403 Called from terminate() before deleting instance
2404 Calls action() to execute the primitive """
2405 logging_text
= "Task ns={} _terminate_action={} ".format(nsr_id
, nslcmop_id
)
2406 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2407 vca_deployed_list
= db_nsr
["_admin"]["deployed"]["VCA"]
2408 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2411 for vnfr
in db_vnfrs_list
:
2412 vnfd_id
= vnfr
["vnfd-id"]
2413 vnf_index
= vnfr
["member-vnf-index-ref"]
2414 if vnfd_id
not in db_vnfds
:
2415 step
= "Getting vnfd={} id='{}' from db".format(vnfd_id
, vnfd_id
)
2416 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
2417 db_vnfds
[vnfd_id
] = vnfd
2418 vnfd
= db_vnfds
[vnfd_id
]
2419 if not self
._has
_terminate
_config
_primitive
(vnfd
):
2421 # Get the primitive's sorted sequence list
2422 seq_list
= self
._get
_terminate
_config
_primitive
_seq
_list
(vnfd
)
2423 for seq
in seq_list
:
2424 # For each sequence in list, get primitive and call _ns_execute_primitive()
2425 step
= "Calling terminate action for vnf_member_index={} primitive={}".format(
2426 vnf_index
, seq
.get("name"))
2427 self
.logger
.debug(logging_text
+ step
)
2428 # Create the primitive for each sequence, i.e. "primitive": "touch"
2429 primitive
= seq
.get('name')
2430 mapped_primitive_params
= self
._get
_terminate
_primitive
_params
(seq
, vnf_index
)
2431 # The following 3 parameters are currently set to None for 'terminate':
2432 # vdu_id, vdu_count_index, vdu_name
2433 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
2434 vdu_count_index
= db_nslcmop
["operationParams"].get("vdu_count_index")
2435 vdu_name
= db_nslcmop
["operationParams"].get("vdu_name")
2437 self
._add
_suboperation
(db_nslcmop
,
2444 mapped_primitive_params
)
2445 # Sub-operations: Call _ns_execute_primitive() instead of action()
2446 # db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2447 # nsr_deployed = db_nsr["_admin"]["deployed"]
2449 # nslcmop_operation_state, nslcmop_operation_state_detail = await self.action(
2450 # nsr_id, nslcmop_terminate_action_id)
2451 # Launch Exception if action() returns other than ['COMPLETED', 'PARTIALLY_COMPLETED']
2452 # result_ok = ['COMPLETED', 'PARTIALLY_COMPLETED']
2453 # if result not in result_ok:
2454 # raise LcmException(
2455 # "terminate_primitive_action for vnf_member_index={}",
2456 # " primitive={} fails with error {}".format(
2457 # vnf_index, seq.get("name"), result_detail))
2459 ee_id
= self
._get
_ee
_id
(vnf_index
, vdu_id
, vca_deployed_list
)
2461 await self
.n2vc
.exec_primitive(
2463 primitive_name
=primitive
,
2464 params_dict
=mapped_primitive_params
2466 except Exception as e
:
2467 self
.logger
.error('Error executing primitive {}: {}'.format(primitive
, e
))
2469 "terminate_primitive_action for vnf_member_index={}, primitive={} fails with error {}"
2470 .format(vnf_index
, seq
.get("name"), e
),
2473 async def _delete_N2VC(self
, nsr_id
: str):
2474 self
._write
_all
_config
_status
(nsr_id
=nsr_id
, status
='TERMINATING')
2475 namespace
= "." + nsr_id
2476 await self
.n2vc
.delete_namespace(namespace
=namespace
)
2477 self
._write
_all
_config
_status
(nsr_id
=nsr_id
, status
='DELETED')
2479 async def terminate(self
, nsr_id
, nslcmop_id
):
2481 # Try to lock HA task here
2482 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
2483 if not task_is_locked_by_me
:
2486 logging_text
= "Task ns={} terminate={} ".format(nsr_id
, nslcmop_id
)
2487 self
.logger
.debug(logging_text
+ "Enter")
2491 failed_detail
= [] # annotates all failed error messages
2492 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
2493 "_admin.current-operation": nslcmop_id
,
2494 "_admin.operation-type": "terminate"}
2495 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2496 db_nslcmop_update
= {}
2497 nslcmop_operation_state
= None
2498 autoremove
= False # autoremove after terminated
2501 # wait for any previous tasks in process
2502 step
= "Waiting for previous operations to terminate"
2503 await self
.lcm_tasks
.waitfor_related_HA("ns", 'nslcmops', nslcmop_id
)
2505 self
._write
_ns
_status
(
2507 ns_state
="TERMINATING",
2508 current_operation
="TERMINATING",
2509 current_operation_id
=nslcmop_id
2511 self
._write
_op
_status
(
2516 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
2517 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
2518 step
= "Getting nsr={} from db".format(nsr_id
)
2519 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2520 # nsd = db_nsr["nsd"]
2521 nsr_deployed
= deepcopy(db_nsr
["_admin"].get("deployed"))
2522 if db_nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
2524 # #TODO check if VIM is creating and wait
2525 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
2526 # Call internal terminate action
2527 await self
._terminate
_action
(db_nslcmop
, nslcmop_id
, nsr_id
)
2531 db_nsr_update
["operational-status"] = "terminating"
2532 db_nsr_update
["config-status"] = "terminating"
2536 step
= "delete execution environment"
2537 self
.logger
.debug(logging_text
+ step
)
2539 task_delete_ee
= asyncio
.ensure_future(self
._delete
_N
2VC
(nsr_id
=nsr_id
))
2540 # task_delete_ee = asyncio.ensure_future(self.n2vc.delete_namespace(namespace="." + nsr_id))
2542 pending_tasks
.append(task_delete_ee
)
2543 except Exception as e
:
2544 msg
= "Failed while deleting ns={} in VCA: {}".format(nsr_id
, e
)
2545 self
.logger
.error(msg
)
2546 failed_detail
.append(msg
)
2549 # Delete from k8scluster
2550 step
= "delete kdus"
2551 self
.logger
.debug(logging_text
+ step
)
2552 # print(nsr_deployed)
2554 for kdu
in nsr_deployed
.get("K8s", ()):
2555 kdu_instance
= kdu
.get("kdu-instance")
2556 if not kdu_instance
:
2558 if kdu
.get("k8scluster-type") == "chart":
2559 task_delete_kdu_instance
= asyncio
.ensure_future(
2560 self
.k8sclusterhelm
.uninstall(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2561 kdu_instance
=kdu_instance
))
2562 elif kdu
.get("k8scluster-type") == "juju":
2563 task_delete_kdu_instance
= asyncio
.ensure_future(
2564 self
.k8sclusterjuju
.uninstall(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2565 kdu_instance
=kdu_instance
))
2567 self
.error(logging_text
+ "Unknown k8s deployment type {}".
2568 format(kdu
.get("k8scluster-type")))
2570 pending_tasks
.append(task_delete_kdu_instance
)
2571 except LcmException
as e
:
2572 msg
= "Failed while deleting KDUs from ns={}: {}".format(nsr_id
, e
)
2573 self
.logger
.error(msg
)
2574 failed_detail
.append(msg
)
2580 RO_nsr_id
= RO_delete_action
= None
2581 if nsr_deployed
and nsr_deployed
.get("RO"):
2582 RO_nsr_id
= nsr_deployed
["RO"].get("nsr_id")
2583 RO_delete_action
= nsr_deployed
["RO"].get("nsr_delete_action_id")
2586 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] = \
2587 "Deleting ns from VIM"
2588 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2589 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2590 self
.logger
.debug(logging_text
+ step
)
2591 desc
= await self
.RO
.delete("ns", RO_nsr_id
)
2592 RO_delete_action
= desc
["action_id"]
2593 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = RO_delete_action
2594 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
2595 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
2596 if RO_delete_action
:
2597 # wait until NS is deleted from VIM
2598 step
= detailed_status
= "Waiting ns deleted from VIM. RO_id={} RO_delete_action={}".\
2599 format(RO_nsr_id
, RO_delete_action
)
2600 detailed_status_old
= None
2601 self
.logger
.debug(logging_text
+ step
)
2603 delete_timeout
= 20 * 60 # 20 minutes
2604 while delete_timeout
> 0:
2605 desc
= await self
.RO
.show(
2607 item_id_name
=RO_nsr_id
,
2608 extra_item
="action",
2609 extra_item_id
=RO_delete_action
)
2612 self
._on
_update
_ro
_db
(nsrs_id
=nsr_id
, ro_descriptor
=desc
)
2614 ns_status
, ns_status_info
= self
.RO
.check_action_status(desc
)
2615 if ns_status
== "ERROR":
2616 raise ROclient
.ROClientException(ns_status_info
)
2617 elif ns_status
== "BUILD":
2618 detailed_status
= step
+ "; {}".format(ns_status_info
)
2619 elif ns_status
== "ACTIVE":
2620 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
2621 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
2624 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
2625 if detailed_status
!= detailed_status_old
:
2626 detailed_status_old
= db_nslcmop_update
["detailed-status"] = \
2627 db_nsr_update
["detailed-status"] = detailed_status
2628 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2629 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2630 await asyncio
.sleep(5, loop
=self
.loop
)
2632 else: # delete_timeout <= 0:
2633 raise ROclient
.ROClientException("Timeout waiting ns deleted from VIM")
2635 except ROclient
.ROClientException
as e
:
2636 if e
.http_code
== 404: # not found
2637 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
2638 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
2639 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
2640 self
.logger
.debug(logging_text
+ "RO_ns_id={} already deleted".format(RO_nsr_id
))
2641 elif e
.http_code
== 409: # conflict
2642 failed_detail
.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id
, e
))
2643 self
.logger
.debug(logging_text
+ failed_detail
[-1])
2646 failed_detail
.append("RO_ns_id={} delete error: {}".format(RO_nsr_id
, e
))
2647 self
.logger
.error(logging_text
+ failed_detail
[-1])
2651 if not RO_fail
and nsr_deployed
and nsr_deployed
.get("RO") and nsr_deployed
["RO"].get("nsd_id"):
2652 RO_nsd_id
= nsr_deployed
["RO"]["nsd_id"]
2654 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
2655 "Deleting nsd from RO"
2656 await self
.RO
.delete("nsd", RO_nsd_id
)
2657 self
.logger
.debug(logging_text
+ "RO_nsd_id={} deleted".format(RO_nsd_id
))
2658 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
2659 except ROclient
.ROClientException
as e
:
2660 if e
.http_code
== 404: # not found
2661 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
2662 self
.logger
.debug(logging_text
+ "RO_nsd_id={} already deleted".format(RO_nsd_id
))
2663 elif e
.http_code
== 409: # conflict
2664 failed_detail
.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id
, e
))
2665 self
.logger
.debug(logging_text
+ failed_detail
[-1])
2668 failed_detail
.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id
, e
))
2669 self
.logger
.error(logging_text
+ failed_detail
[-1])
2672 if not RO_fail
and nsr_deployed
and nsr_deployed
.get("RO") and nsr_deployed
["RO"].get("vnfd"):
2673 for index
, vnf_deployed
in enumerate(nsr_deployed
["RO"]["vnfd"]):
2674 if not vnf_deployed
or not vnf_deployed
["id"]:
2677 RO_vnfd_id
= vnf_deployed
["id"]
2678 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
2679 "Deleting member_vnf_index={} RO_vnfd_id={} from RO".format(
2680 vnf_deployed
["member-vnf-index"], RO_vnfd_id
)
2681 await self
.RO
.delete("vnfd", RO_vnfd_id
)
2682 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} deleted".format(RO_vnfd_id
))
2683 db_nsr_update
["_admin.deployed.RO.vnfd.{}.id".format(index
)] = None
2684 except ROclient
.ROClientException
as e
:
2685 if e
.http_code
== 404: # not found
2686 db_nsr_update
["_admin.deployed.RO.vnfd.{}.id".format(index
)] = None
2687 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} already deleted ".format(RO_vnfd_id
))
2688 elif e
.http_code
== 409: # conflict
2689 failed_detail
.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id
, e
))
2690 self
.logger
.debug(logging_text
+ failed_detail
[-1])
2692 failed_detail
.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id
, e
))
2693 self
.logger
.error(logging_text
+ failed_detail
[-1])
2696 terminate_ok
= False
2697 self
.logger
.error(logging_text
+ " ;".join(failed_detail
))
2698 db_nsr_update
["operational-status"] = "failed"
2699 db_nsr_update
["detailed-status"] = "Deletion errors " + "; ".join(failed_detail
)
2700 db_nslcmop_update
["detailed-status"] = "; ".join(failed_detail
)
2701 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2702 db_nslcmop_update
["statusEnteredTime"] = time()
2705 db_nsr_update
["operational-status"] = "terminated"
2706 db_nsr_update
["detailed-status"] = "Done"
2707 db_nsr_update
["_admin.nsState"] = "NOT_INSTANTIATED"
2708 db_nslcmop_update
["detailed-status"] = "Done"
2709 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
2710 db_nslcmop_update
["statusEnteredTime"] = time()
2711 if db_nslcmop
["operationParams"].get("autoremove"):
2714 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
2715 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
2717 except asyncio
.CancelledError
:
2718 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
2719 exc
= "Operation was cancelled"
2720 except Exception as e
:
2721 exc
= traceback
.format_exc()
2722 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
2724 if exc
and db_nslcmop
:
2725 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
2726 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2727 db_nslcmop_update
["statusEnteredTime"] = time()
2729 if db_nslcmop
and db_nslcmop_update
:
2730 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2732 db_nsr_update
["_admin.nslcmop"] = None
2733 db_nsr_update
["_admin.current-operation"] = None
2734 db_nsr_update
["_admin.operation-type"] = None
2735 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2739 error_description
= None
2743 error_detail
= "; ".join(failed_detail
)
2744 error_description
= 'Operation: TERMINATING.{}, step: {}. Detail: {}'\
2745 .format(nslcmop_id
, step
, error_detail
)
2747 self
._write
_ns
_status
(
2750 current_operation
="IDLE",
2751 current_operation_id
=None,
2752 error_description
=error_description
2755 self
._write
_op
_status
(
2757 error_message
=error_description
2760 except DbException
as e
:
2761 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
2762 if nslcmop_operation_state
:
2764 await self
.msg
.aiowrite("ns", "terminated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2765 "operationState": nslcmop_operation_state
,
2766 "autoremove": autoremove
},
2768 except Exception as e
:
2769 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
2771 # wait for pending tasks
2775 self
.logger
.debug(logging_text
+ 'Waiting for terminate pending tasks...')
2776 done
, pending
= await asyncio
.wait(pending_tasks
, timeout
=3600)
2778 self
.logger
.debug(logging_text
+ 'All tasks finished...')
2780 self
.logger
.info(logging_text
+ 'There are pending tasks: {}'.format(pending
))
2782 self
.logger
.debug(logging_text
+ "Exit")
2783 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_terminate")
2786 def _map_primitive_params(primitive_desc
, params
, instantiation_params
):
2788 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
2789 The default-value is used. If it is between < > it look for a value at instantiation_params
2790 :param primitive_desc: portion of VNFD/NSD that describes primitive
2791 :param params: Params provided by user
2792 :param instantiation_params: Instantiation params provided by user
2793 :return: a dictionary with the calculated params
2795 calculated_params
= {}
2796 for parameter
in primitive_desc
.get("parameter", ()):
2797 param_name
= parameter
["name"]
2798 if param_name
in params
:
2799 calculated_params
[param_name
] = params
[param_name
]
2800 elif "default-value" in parameter
or "value" in parameter
:
2801 if "value" in parameter
:
2802 calculated_params
[param_name
] = parameter
["value"]
2804 calculated_params
[param_name
] = parameter
["default-value"]
2805 if isinstance(calculated_params
[param_name
], str) and calculated_params
[param_name
].startswith("<") \
2806 and calculated_params
[param_name
].endswith(">"):
2807 if calculated_params
[param_name
][1:-1] in instantiation_params
:
2808 calculated_params
[param_name
] = instantiation_params
[calculated_params
[param_name
][1:-1]]
2810 raise LcmException("Parameter {} needed to execute primitive {} not provided".
2811 format(calculated_params
[param_name
], primitive_desc
["name"]))
2813 raise LcmException("Parameter {} needed to execute primitive {} not provided".
2814 format(param_name
, primitive_desc
["name"]))
2816 if isinstance(calculated_params
[param_name
], (dict, list, tuple)):
2817 calculated_params
[param_name
] = yaml
.safe_dump(calculated_params
[param_name
], default_flow_style
=True,
2819 elif isinstance(calculated_params
[param_name
], str) and calculated_params
[param_name
].startswith("!!yaml "):
2820 calculated_params
[param_name
] = calculated_params
[param_name
][7:]
2822 # add always ns_config_info if primitive name is config
2823 if primitive_desc
["name"] == "config":
2824 if "ns_config_info" in instantiation_params
:
2825 calculated_params
["ns_config_info"] = instantiation_params
["ns_config_info"]
2826 return calculated_params
2828 async def _ns_execute_primitive(self
, db_deployed
, member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
,
2829 primitive
, primitive_params
, retries
=0, retries_interval
=30) -> (str, str):
2831 # find vca_deployed record for this action
2833 for vca_deployed
in db_deployed
["VCA"]:
2834 if not vca_deployed
:
2836 if member_vnf_index
!= vca_deployed
["member-vnf-index"] or vdu_id
!= vca_deployed
["vdu_id"]:
2838 if vdu_name
and vdu_name
!= vca_deployed
["vdu_name"]:
2840 if vdu_count_index
and vdu_count_index
!= vca_deployed
["vdu_count_index"]:
2844 # vca_deployed not found
2845 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} is not "
2846 "deployed".format(member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
))
2849 ee_id
= vca_deployed
.get("ee_id")
2851 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} has not "
2852 "execution environment"
2853 .format(member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
))
2855 if primitive
== "config":
2856 primitive_params
= {"params": primitive_params
}
2860 output
= await self
.n2vc
.exec_primitive(
2862 primitive_name
=primitive
,
2863 params_dict
=primitive_params
2867 except Exception as e
:
2870 self
.logger
.debug('Error executing action {} on {} -> {}'.format(primitive
, ee_id
, e
))
2872 await asyncio
.sleep(retries_interval
, loop
=self
.loop
)
2874 return 'Cannot execute action {} on {}: {}'.format(primitive
, ee_id
, e
), 'FAIL'
2878 except Exception as e
:
2879 return 'Error executing action {}: {}'.format(primitive
, e
), 'FAIL'
2881 async def action(self
, nsr_id
, nslcmop_id
):
2883 # Try to lock HA task here
2884 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
2885 if not task_is_locked_by_me
:
2888 logging_text
= "Task ns={} action={} ".format(nsr_id
, nslcmop_id
)
2889 self
.logger
.debug(logging_text
+ "Enter")
2890 # get all needed from database
2893 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
2894 "_admin.current-operation": nslcmop_id
,
2895 "_admin.operation-type": "action"}
2896 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2897 db_nslcmop_update
= {}
2898 nslcmop_operation_state
= None
2899 nslcmop_operation_state_detail
= None
2902 # wait for any previous tasks in process
2903 step
= "Waiting for previous operations to terminate"
2904 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
2906 self
._write
_ns
_status
(
2909 current_operation
="RUNNING ACTION",
2910 current_operation_id
=nslcmop_id
2913 step
= "Getting information from database"
2914 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
2915 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2917 nsr_deployed
= db_nsr
["_admin"].get("deployed")
2918 vnf_index
= db_nslcmop
["operationParams"].get("member_vnf_index")
2919 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
2920 kdu_name
= db_nslcmop
["operationParams"].get("kdu_name")
2921 vdu_count_index
= db_nslcmop
["operationParams"].get("vdu_count_index")
2922 vdu_name
= db_nslcmop
["operationParams"].get("vdu_name")
2925 step
= "Getting vnfr from database"
2926 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
2927 step
= "Getting vnfd from database"
2928 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
2930 if db_nsr
.get("nsd"):
2931 db_nsd
= db_nsr
.get("nsd") # TODO this will be removed
2933 step
= "Getting nsd from database"
2934 db_nsd
= self
.db
.get_one("nsds", {"_id": db_nsr
["nsd-id"]})
2936 # for backward compatibility
2937 if nsr_deployed
and isinstance(nsr_deployed
.get("VCA"), dict):
2938 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
2939 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
2940 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2942 primitive
= db_nslcmop
["operationParams"]["primitive"]
2943 primitive_params
= db_nslcmop
["operationParams"]["primitive_params"]
2945 # look for primitive
2946 config_primitive_desc
= None
2948 for vdu
in get_iterable(db_vnfd
, "vdu"):
2949 if vdu_id
== vdu
["id"]:
2950 for config_primitive
in vdu
.get("vdu-configuration", {}).get("config-primitive", ()):
2951 if config_primitive
["name"] == primitive
:
2952 config_primitive_desc
= config_primitive
2955 self
.logger
.debug(logging_text
+ "Checking actions in KDUs")
2956 kdur
= next((x
for x
in db_vnfr
["kdur"] if x
["kdu-name"] == kdu_name
), None)
2957 desc_params
= self
._format
_additional
_params
(kdur
.get("additionalParams")) or {}
2958 if primitive_params
:
2959 desc_params
.update(primitive_params
)
2960 # TODO Check if we will need something at vnf level
2962 for kdu
in get_iterable(nsr_deployed
, "K8s"):
2963 if kdu_name
== kdu
["kdu-name"]:
2964 db_dict
= {"collection": "nsrs", "filter": {"_id": nsr_id
},
2965 "path": "_admin.deployed.K8s.{}".format(index
)}
2966 if primitive
== "upgrade":
2967 if desc_params
.get("kdu_model"):
2968 kdu_model
= desc_params
.get("kdu_model")
2969 del desc_params
["kdu_model"]
2971 kdu_model
= kdu
.get("kdu-model")
2972 parts
= kdu_model
.split(sep
=":")
2974 kdu_model
= parts
[0]
2976 if kdu
.get("k8scluster-type") == "chart":
2977 output
= await self
.k8sclusterhelm
.upgrade(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2978 kdu_instance
=kdu
.get("kdu-instance"),
2979 atomic
=True, kdu_model
=kdu_model
,
2980 params
=desc_params
, db_dict
=db_dict
,
2982 elif kdu
.get("k8scluster-type") == "juju":
2983 output
= await self
.k8sclusterjuju
.upgrade(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2984 kdu_instance
=kdu
.get("kdu-instance"),
2985 atomic
=True, kdu_model
=kdu_model
,
2986 params
=desc_params
, db_dict
=db_dict
,
2990 msg
= "k8scluster-type not defined"
2991 raise LcmException(msg
)
2993 self
.logger
.debug(logging_text
+ " Upgrade of kdu {} done".format(output
))
2995 elif primitive
== "rollback":
2996 if kdu
.get("k8scluster-type") == "chart":
2997 output
= await self
.k8sclusterhelm
.rollback(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2998 kdu_instance
=kdu
.get("kdu-instance"),
3000 elif kdu
.get("k8scluster-type") == "juju":
3001 output
= await self
.k8sclusterjuju
.rollback(cluster_uuid
=kdu
.get("k8scluster-uuid"),
3002 kdu_instance
=kdu
.get("kdu-instance"),
3005 msg
= "k8scluster-type not defined"
3006 raise LcmException(msg
)
3008 elif primitive
== "status":
3009 if kdu
.get("k8scluster-type") == "chart":
3010 output
= await self
.k8sclusterhelm
.status_kdu(cluster_uuid
=kdu
.get("k8scluster-uuid"),
3011 kdu_instance
=kdu
.get("kdu-instance"))
3012 elif kdu
.get("k8scluster-type") == "juju":
3013 output
= await self
.k8sclusterjuju
.status_kdu(cluster_uuid
=kdu
.get("k8scluster-uuid"),
3014 kdu_instance
=kdu
.get("kdu-instance"))
3016 msg
= "k8scluster-type not defined"
3017 raise LcmException(msg
)
3022 raise LcmException("KDU '{}' not found".format(kdu_name
))
3024 db_nslcmop_update
["detailed-status"] = output
3025 db_nslcmop_update
["operationState"] = 'COMPLETED'
3026 db_nslcmop_update
["statusEnteredTime"] = time()
3028 db_nslcmop_update
["detailed-status"] = ''
3029 db_nslcmop_update
["operationState"] = 'FAILED'
3030 db_nslcmop_update
["statusEnteredTime"] = time()
3033 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
3034 if config_primitive
["name"] == primitive
:
3035 config_primitive_desc
= config_primitive
3038 for config_primitive
in db_nsd
.get("ns-configuration", {}).get("config-primitive", ()):
3039 if config_primitive
["name"] == primitive
:
3040 config_primitive_desc
= config_primitive
3043 if not config_primitive_desc
:
3044 raise LcmException("Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".
3049 if db_vnfr
.get("additionalParamsForVnf"):
3050 desc_params
= self
._format
_additional
_params
(db_vnfr
["additionalParamsForVnf"])
3052 vdur
= next((x
for x
in db_vnfr
["vdur"] if x
["vdu-id-ref"] == vdu_id
), None)
3053 if vdur
.get("additionalParams"):
3054 desc_params
= self
._format
_additional
_params
(vdur
["additionalParams"])
3056 if db_nsr
.get("additionalParamsForNs"):
3057 desc_params
.update(self
._format
_additional
_params
(db_nsr
["additionalParamsForNs"]))
3059 # TODO check if ns is in a proper status
3060 output
, detail
= await self
._ns
_execute
_primitive
(
3061 db_deployed
=nsr_deployed
,
3062 member_vnf_index
=vnf_index
,
3065 vdu_count_index
=vdu_count_index
,
3066 primitive
=primitive
,
3067 primitive_params
=self
._map
_primitive
_params
(config_primitive_desc
, primitive_params
, desc_params
))
3069 detailed_status
= output
3071 result
= 'COMPLETED'
3075 db_nslcmop_update
["detailed-status"] = nslcmop_operation_state_detail
= detailed_status
3076 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= result
3077 db_nslcmop_update
["statusEnteredTime"] = time()
3078 self
.logger
.debug(logging_text
+ " task Done with result {} {}".format(result
, detailed_status
))
3079 return # database update is called inside finally
3081 except (DbException
, LcmException
) as e
:
3082 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
3084 except asyncio
.CancelledError
:
3085 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
3086 exc
= "Operation was cancelled"
3087 except Exception as e
:
3088 exc
= traceback
.format_exc()
3089 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
3091 if exc
and db_nslcmop
:
3092 db_nslcmop_update
["detailed-status"] = nslcmop_operation_state_detail
= \
3093 "FAILED {}: {}".format(step
, exc
)
3094 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
3095 db_nslcmop_update
["statusEnteredTime"] = time()
3097 if db_nslcmop_update
:
3098 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
3100 db_nsr_update
["_admin.nslcmop"] = None
3101 db_nsr_update
["_admin.operation-type"] = None
3102 db_nsr_update
["_admin.nslcmop"] = None
3103 db_nsr_update
["_admin.current-operation"] = None
3104 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
3105 self
._write
_ns
_status
(
3108 current_operation
="IDLE",
3109 current_operation_id
=None
3112 self
._write
_op
_status
(
3114 error_message
=nslcmop_operation_state_detail
3116 except DbException
as e
:
3117 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
3118 self
.logger
.debug(logging_text
+ "Exit")
3119 if nslcmop_operation_state
:
3121 await self
.msg
.aiowrite("ns", "actioned", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
3122 "operationState": nslcmop_operation_state
},
3124 except Exception as e
:
3125 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
3126 self
.logger
.debug(logging_text
+ "Exit")
3127 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_action")
3128 return nslcmop_operation_state
, nslcmop_operation_state_detail
3130 async def scale(self
, nsr_id
, nslcmop_id
):
3132 # Try to lock HA task here
3133 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
3134 if not task_is_locked_by_me
:
3137 logging_text
= "Task ns={} scale={} ".format(nsr_id
, nslcmop_id
)
3138 self
.logger
.debug(logging_text
+ "Enter")
3139 # get all needed from database
3142 db_nslcmop_update
= {}
3143 nslcmop_operation_state
= None
3144 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
3145 "_admin.current-operation": nslcmop_id
,
3146 "_admin.operation-type": "scale"}
3147 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
3149 # in case of error, indicates what part of scale was failed to put nsr at error status
3150 scale_process
= None
3151 old_operational_status
= ""
3152 old_config_status
= ""
3155 # wait for any previous tasks in process
3156 step
= "Waiting for previous operations to terminate"
3157 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
3159 self
._write
_ns
_status
(
3162 current_operation
="SCALING",
3163 current_operation_id
=nslcmop_id
3166 step
= "Getting nslcmop from database"
3167 self
.logger
.debug(step
+ " after having waited for previous tasks to be completed")
3168 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
3169 step
= "Getting nsr from database"
3170 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
3172 old_operational_status
= db_nsr
["operational-status"]
3173 old_config_status
= db_nsr
["config-status"]
3174 step
= "Parsing scaling parameters"
3175 # self.logger.debug(step)
3176 db_nsr_update
["operational-status"] = "scaling"
3177 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
3178 nsr_deployed
= db_nsr
["_admin"].get("deployed")
3181 nsr_deployed
= db_nsr
["_admin"].get("deployed")
3182 vnf_index
= db_nslcmop
["operationParams"].get("member_vnf_index")
3183 # vdu_id = db_nslcmop["operationParams"].get("vdu_id")
3184 # vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
3185 # vdu_name = db_nslcmop["operationParams"].get("vdu_name")
3188 RO_nsr_id
= nsr_deployed
["RO"]["nsr_id"]
3189 vnf_index
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
3190 scaling_group
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
3191 scaling_type
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleVnfType"]
3192 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
3194 # for backward compatibility
3195 if nsr_deployed
and isinstance(nsr_deployed
.get("VCA"), dict):
3196 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
3197 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
3198 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
3200 step
= "Getting vnfr from database"
3201 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
3202 step
= "Getting vnfd from database"
3203 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
3205 step
= "Getting scaling-group-descriptor"
3206 for scaling_descriptor
in db_vnfd
["scaling-group-descriptor"]:
3207 if scaling_descriptor
["name"] == scaling_group
:
3210 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
3211 "at vnfd:scaling-group-descriptor".format(scaling_group
))
3214 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
3215 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
3216 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
3219 # TODO check if ns is in a proper status
3220 step
= "Sending scale order to VIM"
3222 if not db_nsr
["_admin"].get("scaling-group"):
3223 self
.update_db_2("nsrs", nsr_id
, {"_admin.scaling-group": [{"name": scaling_group
, "nb-scale-op": 0}]})
3224 admin_scale_index
= 0
3226 for admin_scale_index
, admin_scale_info
in enumerate(db_nsr
["_admin"]["scaling-group"]):
3227 if admin_scale_info
["name"] == scaling_group
:
3228 nb_scale_op
= admin_scale_info
.get("nb-scale-op", 0)
3230 else: # not found, set index one plus last element and add new entry with the name
3231 admin_scale_index
+= 1
3232 db_nsr_update
["_admin.scaling-group.{}.name".format(admin_scale_index
)] = scaling_group
3233 RO_scaling_info
= []
3234 vdu_scaling_info
= {"scaling_group_name": scaling_group
, "vdu": []}
3235 if scaling_type
== "SCALE_OUT":
3236 # count if max-instance-count is reached
3237 max_instance_count
= scaling_descriptor
.get("max-instance-count", 10)
3238 # self.logger.debug("MAX_INSTANCE_COUNT is {}".format(max_instance_count))
3239 if nb_scale_op
>= max_instance_count
:
3240 raise LcmException("reached the limit of {} (max-instance-count) "
3241 "scaling-out operations for the "
3242 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
3245 vdu_scaling_info
["scaling_direction"] = "OUT"
3246 vdu_scaling_info
["vdu-create"] = {}
3247 for vdu_scale_info
in scaling_descriptor
["vdu"]:
3248 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
3249 "type": "create", "count": vdu_scale_info
.get("count", 1)})
3250 vdu_scaling_info
["vdu-create"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
3252 elif scaling_type
== "SCALE_IN":
3253 # count if min-instance-count is reached
3254 min_instance_count
= 0
3255 if "min-instance-count" in scaling_descriptor
and scaling_descriptor
["min-instance-count"] is not None:
3256 min_instance_count
= int(scaling_descriptor
["min-instance-count"])
3257 if nb_scale_op
<= min_instance_count
:
3258 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
3259 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
3261 vdu_scaling_info
["scaling_direction"] = "IN"
3262 vdu_scaling_info
["vdu-delete"] = {}
3263 for vdu_scale_info
in scaling_descriptor
["vdu"]:
3264 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
3265 "type": "delete", "count": vdu_scale_info
.get("count", 1)})
3266 vdu_scaling_info
["vdu-delete"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
3268 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
3269 vdu_create
= vdu_scaling_info
.get("vdu-create")
3270 vdu_delete
= copy(vdu_scaling_info
.get("vdu-delete"))
3271 if vdu_scaling_info
["scaling_direction"] == "IN":
3272 for vdur
in reversed(db_vnfr
["vdur"]):
3273 if vdu_delete
.get(vdur
["vdu-id-ref"]):
3274 vdu_delete
[vdur
["vdu-id-ref"]] -= 1
3275 vdu_scaling_info
["vdu"].append({
3276 "name": vdur
["name"],
3277 "vdu_id": vdur
["vdu-id-ref"],
3280 for interface
in vdur
["interfaces"]:
3281 vdu_scaling_info
["vdu"][-1]["interface"].append({
3282 "name": interface
["name"],
3283 "ip_address": interface
["ip-address"],
3284 "mac_address": interface
.get("mac-address"),
3286 vdu_delete
= vdu_scaling_info
.pop("vdu-delete")
3289 step
= "Executing pre-scale vnf-config-primitive"
3290 if scaling_descriptor
.get("scaling-config-action"):
3291 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
3292 if (scaling_config_action
.get("trigger") == "pre-scale-in" and scaling_type
== "SCALE_IN") \
3293 or (scaling_config_action
.get("trigger") == "pre-scale-out" and scaling_type
== "SCALE_OUT"):
3294 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
3295 step
= db_nslcmop_update
["detailed-status"] = \
3296 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive
)
3298 # look for primitive
3299 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
3300 if config_primitive
["name"] == vnf_config_primitive
:
3304 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
3305 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
3306 "primitive".format(scaling_group
, config_primitive
))
3308 vnfr_params
= {"VDU_SCALE_INFO": vdu_scaling_info
}
3309 if db_vnfr
.get("additionalParamsForVnf"):
3310 vnfr_params
.update(db_vnfr
["additionalParamsForVnf"])
3312 scale_process
= "VCA"
3313 db_nsr_update
["config-status"] = "configuring pre-scaling"
3314 primitive_params
= self
._map
_primitive
_params
(config_primitive
, {}, vnfr_params
)
3316 # Pre-scale reintent check: Check if this sub-operation has been executed before
3317 op_index
= self
._check
_or
_add
_scale
_suboperation
(
3318 db_nslcmop
, nslcmop_id
, vnf_index
, vnf_config_primitive
, primitive_params
, 'PRE-SCALE')
3319 if (op_index
== self
.SUBOPERATION_STATUS_SKIP
):
3320 # Skip sub-operation
3321 result
= 'COMPLETED'
3322 result_detail
= 'Done'
3323 self
.logger
.debug(logging_text
+
3324 "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
3325 vnf_config_primitive
, result
, result_detail
))
3327 if (op_index
== self
.SUBOPERATION_STATUS_NEW
):
3328 # New sub-operation: Get index of this sub-operation
3329 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
3330 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} New sub-operation".
3331 format(vnf_config_primitive
))
3333 # Reintent: Get registered params for this existing sub-operation
3334 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
3335 vnf_index
= op
.get('member_vnf_index')
3336 vnf_config_primitive
= op
.get('primitive')
3337 primitive_params
= op
.get('primitive_params')
3338 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Sub-operation reintent".
3339 format(vnf_config_primitive
))
3340 # Execute the primitive, either with new (first-time) or registered (reintent) args
3341 result
, result_detail
= await self
._ns
_execute
_primitive
(
3342 nsr_deployed
, vnf_index
, None, None, None, vnf_config_primitive
, primitive_params
)
3343 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
3344 vnf_config_primitive
, result
, result_detail
))
3345 # Update operationState = COMPLETED | FAILED
3346 self
._update
_suboperation
_status
(
3347 db_nslcmop
, op_index
, result
, result_detail
)
3349 if result
== "FAILED":
3350 raise LcmException(result_detail
)
3351 db_nsr_update
["config-status"] = old_config_status
3352 scale_process
= None
3356 # Should this block be skipped if 'RO_nsr_id' == None ?
3357 # if (RO_nsr_id and RO_scaling_info):
3359 scale_process
= "RO"
3360 # Scale RO reintent check: Check if this sub-operation has been executed before
3361 op_index
= self
._check
_or
_add
_scale
_suboperation
(
3362 db_nslcmop
, vnf_index
, None, None, 'SCALE-RO', RO_nsr_id
, RO_scaling_info
)
3363 if (op_index
== self
.SUBOPERATION_STATUS_SKIP
):
3364 # Skip sub-operation
3365 result
= 'COMPLETED'
3366 result_detail
= 'Done'
3367 self
.logger
.debug(logging_text
+ "Skipped sub-operation RO, result {} {}".format(
3368 result
, result_detail
))
3370 if (op_index
== self
.SUBOPERATION_STATUS_NEW
):
3371 # New sub-operation: Get index of this sub-operation
3372 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
3373 self
.logger
.debug(logging_text
+ "New sub-operation RO")
3375 # Reintent: Get registered params for this existing sub-operation
3376 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
3377 RO_nsr_id
= op
.get('RO_nsr_id')
3378 RO_scaling_info
= op
.get('RO_scaling_info')
3379 self
.logger
.debug(logging_text
+ "Sub-operation RO reintent".format(
3380 vnf_config_primitive
))
3382 RO_desc
= await self
.RO
.create_action("ns", RO_nsr_id
, {"vdu-scaling": RO_scaling_info
})
3383 db_nsr_update
["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index
)] = nb_scale_op
3384 db_nsr_update
["_admin.scaling-group.{}.time".format(admin_scale_index
)] = time()
3386 RO_nslcmop_id
= RO_desc
["instance_action_id"]
3387 db_nslcmop_update
["_admin.deploy.RO"] = RO_nslcmop_id
3389 RO_task_done
= False
3390 step
= detailed_status
= "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id
)
3391 detailed_status_old
= None
3392 self
.logger
.debug(logging_text
+ step
)
3394 deployment_timeout
= 1 * 3600 # One hour
3395 while deployment_timeout
> 0:
3396 if not RO_task_done
:
3397 desc
= await self
.RO
.show("ns", item_id_name
=RO_nsr_id
, extra_item
="action",
3398 extra_item_id
=RO_nslcmop_id
)
3401 self
._on
_update
_ro
_db
(nsrs_id
=nsr_id
, ro_descriptor
=desc
)
3403 ns_status
, ns_status_info
= self
.RO
.check_action_status(desc
)
3404 if ns_status
== "ERROR":
3405 raise ROclient
.ROClientException(ns_status_info
)
3406 elif ns_status
== "BUILD":
3407 detailed_status
= step
+ "; {}".format(ns_status_info
)
3408 elif ns_status
== "ACTIVE":
3410 step
= detailed_status
= "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id
)
3411 self
.logger
.debug(logging_text
+ step
)
3413 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
3416 if ns_status
== "ERROR":
3417 raise ROclient
.ROClientException(ns_status_info
)
3418 elif ns_status
== "BUILD":
3419 detailed_status
= step
+ "; {}".format(ns_status_info
)
3420 elif ns_status
== "ACTIVE":
3421 step
= detailed_status
= \
3422 "Waiting for management IP address reported by the VIM. Updating VNFRs"
3424 self
.scale_vnfr(db_vnfr
, vdu_create
=vdu_create
, vdu_delete
=vdu_delete
)
3427 desc
= await self
.RO
.show("ns", RO_nsr_id
)
3430 self
._on
_update
_ro
_db
(nsrs_id
=nsr_id
, ro_descriptor
=desc
)
3432 # nsr_deployed["nsr_ip"] = RO.get_ns_vnf_info(desc)
3433 self
.ns_update_vnfr({db_vnfr
["member-vnf-index-ref"]: db_vnfr
}, desc
)
3435 except LcmExceptionNoMgmtIP
:
3438 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
3439 if detailed_status
!= detailed_status_old
:
3440 self
._update
_suboperation
_status
(
3441 db_nslcmop
, op_index
, 'COMPLETED', detailed_status
)
3442 detailed_status_old
= db_nslcmop_update
["detailed-status"] = detailed_status
3443 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
3445 await asyncio
.sleep(5, loop
=self
.loop
)
3446 deployment_timeout
-= 5
3447 if deployment_timeout
<= 0:
3448 self
._update
_suboperation
_status
(
3449 db_nslcmop
, nslcmop_id
, op_index
, 'FAILED', "Timeout when waiting for ns to get ready")
3450 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
3452 # update VDU_SCALING_INFO with the obtained ip_addresses
3453 if vdu_scaling_info
["scaling_direction"] == "OUT":
3454 for vdur
in reversed(db_vnfr
["vdur"]):
3455 if vdu_scaling_info
["vdu-create"].get(vdur
["vdu-id-ref"]):
3456 vdu_scaling_info
["vdu-create"][vdur
["vdu-id-ref"]] -= 1
3457 vdu_scaling_info
["vdu"].append({
3458 "name": vdur
["name"],
3459 "vdu_id": vdur
["vdu-id-ref"],
3462 for interface
in vdur
["interfaces"]:
3463 vdu_scaling_info
["vdu"][-1]["interface"].append({
3464 "name": interface
["name"],
3465 "ip_address": interface
["ip-address"],
3466 "mac_address": interface
.get("mac-address"),
3468 del vdu_scaling_info
["vdu-create"]
3470 self
._update
_suboperation
_status
(db_nslcmop
, op_index
, 'COMPLETED', 'Done')
3473 scale_process
= None
3475 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
3478 # execute primitive service POST-SCALING
3479 step
= "Executing post-scale vnf-config-primitive"
3480 if scaling_descriptor
.get("scaling-config-action"):
3481 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
3482 if (scaling_config_action
.get("trigger") == "post-scale-in" and scaling_type
== "SCALE_IN") \
3483 or (scaling_config_action
.get("trigger") == "post-scale-out" and scaling_type
== "SCALE_OUT"):
3484 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
3485 step
= db_nslcmop_update
["detailed-status"] = \
3486 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive
)
3488 vnfr_params
= {"VDU_SCALE_INFO": vdu_scaling_info
}
3489 if db_vnfr
.get("additionalParamsForVnf"):
3490 vnfr_params
.update(db_vnfr
["additionalParamsForVnf"])
3492 # look for primitive
3493 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
3494 if config_primitive
["name"] == vnf_config_primitive
:
3497 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
3498 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
3499 "match any vnf-configuration:config-primitive".format(scaling_group
,
3501 scale_process
= "VCA"
3502 db_nsr_update
["config-status"] = "configuring post-scaling"
3503 primitive_params
= self
._map
_primitive
_params
(config_primitive
, {}, vnfr_params
)
3505 # Post-scale reintent check: Check if this sub-operation has been executed before
3506 op_index
= self
._check
_or
_add
_scale
_suboperation
(
3507 db_nslcmop
, nslcmop_id
, vnf_index
, vnf_config_primitive
, primitive_params
, 'POST-SCALE')
3508 if op_index
== self
.SUBOPERATION_STATUS_SKIP
:
3509 # Skip sub-operation
3510 result
= 'COMPLETED'
3511 result_detail
= 'Done'
3512 self
.logger
.debug(logging_text
+
3513 "vnf_config_primitive={} Skipped sub-operation, result {} {}".
3514 format(vnf_config_primitive
, result
, result_detail
))
3516 if op_index
== self
.SUBOPERATION_STATUS_NEW
:
3517 # New sub-operation: Get index of this sub-operation
3518 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
3519 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} New sub-operation".
3520 format(vnf_config_primitive
))
3522 # Reintent: Get registered params for this existing sub-operation
3523 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
3524 vnf_index
= op
.get('member_vnf_index')
3525 vnf_config_primitive
= op
.get('primitive')
3526 primitive_params
= op
.get('primitive_params')
3527 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Sub-operation reintent".
3528 format(vnf_config_primitive
))
3529 # Execute the primitive, either with new (first-time) or registered (reintent) args
3530 result
, result_detail
= await self
._ns
_execute
_primitive
(
3531 nsr_deployed
, vnf_index
, None, None, None, vnf_config_primitive
, primitive_params
)
3532 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
3533 vnf_config_primitive
, result
, result_detail
))
3534 # Update operationState = COMPLETED | FAILED
3535 self
._update
_suboperation
_status
(
3536 db_nslcmop
, op_index
, result
, result_detail
)
3538 if result
== "FAILED":
3539 raise LcmException(result_detail
)
3540 db_nsr_update
["config-status"] = old_config_status
3541 scale_process
= None
3544 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
3545 db_nslcmop_update
["statusEnteredTime"] = time()
3546 db_nslcmop_update
["detailed-status"] = "done"
3547 db_nsr_update
["detailed-status"] = "" # "scaled {} {}".format(scaling_group, scaling_type)
3548 db_nsr_update
["operational-status"] = "running" if old_operational_status
== "failed" \
3549 else old_operational_status
3550 db_nsr_update
["config-status"] = old_config_status
3552 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
3553 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
3555 except asyncio
.CancelledError
:
3556 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
3557 exc
= "Operation was cancelled"
3558 except Exception as e
:
3559 exc
= traceback
.format_exc()
3560 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
3562 self
._write
_ns
_status
(
3565 current_operation
="IDLE",
3566 current_operation_id
=None
3570 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
3571 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
3572 db_nslcmop_update
["statusEnteredTime"] = time()
3574 db_nsr_update
["operational-status"] = old_operational_status
3575 db_nsr_update
["config-status"] = old_config_status
3576 db_nsr_update
["detailed-status"] = ""
3577 db_nsr_update
["_admin.nslcmop"] = None
3579 if "VCA" in scale_process
:
3580 db_nsr_update
["config-status"] = "failed"
3581 if "RO" in scale_process
:
3582 db_nsr_update
["operational-status"] = "failed"
3583 db_nsr_update
["detailed-status"] = "FAILED scaling nslcmop={} {}: {}".format(nslcmop_id
, step
,
3586 if db_nslcmop
and db_nslcmop_update
:
3587 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
3589 db_nsr_update
["_admin.current-operation"] = None
3590 db_nsr_update
["_admin.operation-type"] = None
3591 db_nsr_update
["_admin.nslcmop"] = None
3592 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
3594 self
._write
_ns
_status
(
3597 current_operation
="IDLE",
3598 current_operation_id
=None
3601 except DbException
as e
:
3602 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
3603 if nslcmop_operation_state
:
3605 await self
.msg
.aiowrite("ns", "scaled", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
3606 "operationState": nslcmop_operation_state
},
3609 # await asyncio.sleep(cooldown_time, loop=self.loop)
3610 # await self.msg.aiowrite("ns","scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
3611 except Exception as e
:
3612 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
3613 self
.logger
.debug(logging_text
+ "Exit")
3614 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_scale")