bcd675bca44059471bd27bd93da1b7479edbab38
[osm/LCM.git] / osm_lcm / ns.py
1 # -*- coding: utf-8 -*-
2
3 ##
4 # Copyright 2018 Telefonica S.A.
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License"); you may
7 # not use this file except in compliance with the License. You may obtain
8 # a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 # License for the specific language governing permissions and limitations
16 # under the License.
17 ##
18
19 import asyncio
20 import yaml
21 import logging
22 import logging.handlers
23 import traceback
24 import json
25 from jinja2 import Environment, Template, meta, TemplateError, TemplateNotFound, TemplateSyntaxError
26
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
31
32 from osm_common.dbbase import DbException
33 from osm_common.fsbase import FsException
34
35 from n2vc.n2vc_juju_conn import N2VCJujuConnector
36 from n2vc.exceptions import N2VCException, N2VCNotFound, K8sException
37
38 from copy import copy, deepcopy
39 from http import HTTPStatus
40 from time import time
41 from uuid import uuid4
42 from functools import partial
43
44 __author__ = "Alfonso Tierno"
45
46
47 class NsLcm(LcmBase):
48 timeout_vca_on_error = 5 * 60 # Time for charm from first time at blocked,error status to mark as failed
49 timeout_ns_deploy = 2 * 3600 # default global timeout for deployment a ns
50 timeout_ns_terminate = 1800 # default global timeout for un deployment a ns
51 timeout_charm_delete = 10 * 60
52 timeout_primitive = 30 * 60 # timeout for primitive execution
53 timeout_progress_primitive = 10 * 60 # timeout for some progress in a primitive execution
54
55 SUBOPERATION_STATUS_NOT_FOUND = -1
56 SUBOPERATION_STATUS_NEW = -2
57 SUBOPERATION_STATUS_SKIP = -3
58 task_name_deploy_vca = "Deploying VCA"
59
60 def __init__(self, db, msg, fs, lcm_tasks, config, loop):
61 """
62 Init, Connect to database, filesystem storage, and messaging
63 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
64 :return: None
65 """
66 super().__init__(
67 db=db,
68 msg=msg,
69 fs=fs,
70 logger=logging.getLogger('lcm.ns')
71 )
72
73 self.loop = loop
74 self.lcm_tasks = lcm_tasks
75 self.timeout = config["timeout"]
76 self.ro_config = config["ro_config"]
77 self.vca_config = config["VCA"].copy()
78
79 # create N2VC connector
80 self.n2vc = N2VCJujuConnector(
81 db=self.db,
82 fs=self.fs,
83 log=self.logger,
84 loop=self.loop,
85 url='{}:{}'.format(self.vca_config['host'], self.vca_config['port']),
86 username=self.vca_config.get('user', None),
87 vca_config=self.vca_config,
88 on_update_db=self._on_update_n2vc_db
89 )
90
91 self.k8sclusterhelm = K8sHelmConnector(
92 kubectl_command=self.vca_config.get("kubectlpath"),
93 helm_command=self.vca_config.get("helmpath"),
94 fs=self.fs,
95 log=self.logger,
96 db=self.db,
97 on_update_db=None,
98 )
99
100 self.k8sclusterjuju = K8sJujuConnector(
101 kubectl_command=self.vca_config.get("kubectlpath"),
102 juju_command=self.vca_config.get("jujupath"),
103 fs=self.fs,
104 log=self.logger,
105 db=self.db,
106 on_update_db=None,
107 )
108
109 self.k8scluster_map = {
110 "helm-chart": self.k8sclusterhelm,
111 "chart": self.k8sclusterhelm,
112 "juju-bundle": self.k8sclusterjuju,
113 "juju": self.k8sclusterjuju,
114 }
115 # create RO client
116 self.RO = ROclient.ROClient(self.loop, **self.ro_config)
117
118 def _on_update_ro_db(self, nsrs_id, ro_descriptor):
119
120 # self.logger.debug('_on_update_ro_db(nsrs_id={}'.format(nsrs_id))
121
122 try:
123 # TODO filter RO descriptor fields...
124
125 # write to database
126 db_dict = dict()
127 # db_dict['deploymentStatus'] = yaml.dump(ro_descriptor, default_flow_style=False, indent=2)
128 db_dict['deploymentStatus'] = ro_descriptor
129 self.update_db_2("nsrs", nsrs_id, db_dict)
130
131 except Exception as e:
132 self.logger.warn('Cannot write database RO deployment for ns={} -> {}'.format(nsrs_id, e))
133
134 async def _on_update_n2vc_db(self, table, filter, path, updated_data):
135
136 # remove last dot from path (if exists)
137 if path.endswith('.'):
138 path = path[:-1]
139
140 # self.logger.debug('_on_update_n2vc_db(table={}, filter={}, path={}, updated_data={}'
141 # .format(table, filter, path, updated_data))
142
143 try:
144
145 nsr_id = filter.get('_id')
146
147 # read ns record from database
148 nsr = self.db.get_one(table='nsrs', q_filter=filter)
149 current_ns_status = nsr.get('nsState')
150
151 # get vca status for NS
152 status_dict = await self.n2vc.get_status(namespace='.' + nsr_id, yaml_format=False)
153
154 # vcaStatus
155 db_dict = dict()
156 db_dict['vcaStatus'] = status_dict
157
158 # update configurationStatus for this VCA
159 try:
160 vca_index = int(path[path.rfind(".")+1:])
161
162 vca_list = deep_get(target_dict=nsr, key_list=('_admin', 'deployed', 'VCA'))
163 vca_status = vca_list[vca_index].get('status')
164
165 configuration_status_list = nsr.get('configurationStatus')
166 config_status = configuration_status_list[vca_index].get('status')
167
168 if config_status == 'BROKEN' and vca_status != 'failed':
169 db_dict['configurationStatus'][vca_index] = 'READY'
170 elif config_status != 'BROKEN' and vca_status == 'failed':
171 db_dict['configurationStatus'][vca_index] = 'BROKEN'
172 except Exception as e:
173 # not update configurationStatus
174 self.logger.debug('Error updating vca_index (ignore): {}'.format(e))
175
176 # if nsState = 'READY' check if juju is reporting some error => nsState = 'DEGRADED'
177 # if nsState = 'DEGRADED' check if all is OK
178 is_degraded = False
179 if current_ns_status in ('READY', 'DEGRADED'):
180 error_description = ''
181 # check machines
182 if status_dict.get('machines'):
183 for machine_id in status_dict.get('machines'):
184 machine = status_dict.get('machines').get(machine_id)
185 # check machine agent-status
186 if machine.get('agent-status'):
187 s = machine.get('agent-status').get('status')
188 if s != 'started':
189 is_degraded = True
190 error_description += 'machine {} agent-status={} ; '.format(machine_id, s)
191 # check machine instance status
192 if machine.get('instance-status'):
193 s = machine.get('instance-status').get('status')
194 if s != 'running':
195 is_degraded = True
196 error_description += 'machine {} instance-status={} ; '.format(machine_id, s)
197 # check applications
198 if status_dict.get('applications'):
199 for app_id in status_dict.get('applications'):
200 app = status_dict.get('applications').get(app_id)
201 # check application status
202 if app.get('status'):
203 s = app.get('status').get('status')
204 if s != 'active':
205 is_degraded = True
206 error_description += 'application {} status={} ; '.format(app_id, s)
207
208 if error_description:
209 db_dict['errorDescription'] = error_description
210 if current_ns_status == 'READY' and is_degraded:
211 db_dict['nsState'] = 'DEGRADED'
212 if current_ns_status == 'DEGRADED' and not is_degraded:
213 db_dict['nsState'] = 'READY'
214
215 # write to database
216 self.update_db_2("nsrs", nsr_id, db_dict)
217
218 except (asyncio.CancelledError, asyncio.TimeoutError):
219 raise
220 except Exception as e:
221 self.logger.warn('Error updating NS state for ns={}: {}'.format(nsr_id, e))
222
223 def vnfd2RO(self, vnfd, new_id=None, additionalParams=None, nsrId=None):
224 """
225 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
226 :param vnfd: input vnfd
227 :param new_id: overrides vnf id if provided
228 :param additionalParams: Instantiation params for VNFs provided
229 :param nsrId: Id of the NSR
230 :return: copy of vnfd
231 """
232 try:
233 vnfd_RO = deepcopy(vnfd)
234 # remove unused by RO configuration, monitoring, scaling and internal keys
235 vnfd_RO.pop("_id", None)
236 vnfd_RO.pop("_admin", None)
237 vnfd_RO.pop("vnf-configuration", None)
238 vnfd_RO.pop("monitoring-param", None)
239 vnfd_RO.pop("scaling-group-descriptor", None)
240 vnfd_RO.pop("kdu", None)
241 vnfd_RO.pop("k8s-cluster", None)
242 if new_id:
243 vnfd_RO["id"] = new_id
244
245 # parse cloud-init or cloud-init-file with the provided variables using Jinja2
246 for vdu in get_iterable(vnfd_RO, "vdu"):
247 cloud_init_file = None
248 if vdu.get("cloud-init-file"):
249 base_folder = vnfd["_admin"]["storage"]
250 cloud_init_file = "{}/{}/cloud_init/{}".format(base_folder["folder"], base_folder["pkg-dir"],
251 vdu["cloud-init-file"])
252 with self.fs.file_open(cloud_init_file, "r") as ci_file:
253 cloud_init_content = ci_file.read()
254 vdu.pop("cloud-init-file", None)
255 elif vdu.get("cloud-init"):
256 cloud_init_content = vdu["cloud-init"]
257 else:
258 continue
259
260 env = Environment()
261 ast = env.parse(cloud_init_content)
262 mandatory_vars = meta.find_undeclared_variables(ast)
263 if mandatory_vars:
264 for var in mandatory_vars:
265 if not additionalParams or var not in additionalParams.keys():
266 raise LcmException("Variable '{}' defined at vnfd[id={}]:vdu[id={}]:cloud-init/cloud-init-"
267 "file, must be provided in the instantiation parameters inside the "
268 "'additionalParamsForVnf' block".format(var, vnfd["id"], vdu["id"]))
269 template = Template(cloud_init_content)
270 cloud_init_content = template.render(additionalParams or {})
271 vdu["cloud-init"] = cloud_init_content
272
273 return vnfd_RO
274 except FsException as e:
275 raise LcmException("Error reading vnfd[id={}]:vdu[id={}]:cloud-init-file={}: {}".
276 format(vnfd["id"], vdu["id"], cloud_init_file, e))
277 except (TemplateError, TemplateNotFound, TemplateSyntaxError) as e:
278 raise LcmException("Error parsing Jinja2 to cloud-init content at vnfd[id={}]:vdu[id={}]: {}".
279 format(vnfd["id"], vdu["id"], e))
280
281 def _ns_params_2_RO(self, ns_params, nsd, vnfd_dict, db_vnfrs, n2vc_key_list):
282 """
283 Creates a RO ns descriptor from OSM ns_instantiate params
284 :param ns_params: OSM instantiate params
285 :param vnfd_dict: database content of vnfds, indexed by id (not _id). {id: {vnfd_object}, ...}
286 :param db_vnfrs: database content of vnfrs, indexed by member-vnf-index. {member-vnf-index: {vnfr_object}, ...}
287 :return: The RO ns descriptor
288 """
289 vim_2_RO = {}
290 wim_2_RO = {}
291 # TODO feature 1417: Check that no instantiation is set over PDU
292 # check if PDU forces a concrete vim-network-id and add it
293 # check if PDU contains a SDN-assist info (dpid, switch, port) and pass it to RO
294
295 def vim_account_2_RO(vim_account):
296 if vim_account in vim_2_RO:
297 return vim_2_RO[vim_account]
298
299 db_vim = self.db.get_one("vim_accounts", {"_id": vim_account})
300 if db_vim["_admin"]["operationalState"] != "ENABLED":
301 raise LcmException("VIM={} is not available. operationalState={}".format(
302 vim_account, db_vim["_admin"]["operationalState"]))
303 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
304 vim_2_RO[vim_account] = RO_vim_id
305 return RO_vim_id
306
307 def wim_account_2_RO(wim_account):
308 if isinstance(wim_account, str):
309 if wim_account in wim_2_RO:
310 return wim_2_RO[wim_account]
311
312 db_wim = self.db.get_one("wim_accounts", {"_id": wim_account})
313 if db_wim["_admin"]["operationalState"] != "ENABLED":
314 raise LcmException("WIM={} is not available. operationalState={}".format(
315 wim_account, db_wim["_admin"]["operationalState"]))
316 RO_wim_id = db_wim["_admin"]["deployed"]["RO-account"]
317 wim_2_RO[wim_account] = RO_wim_id
318 return RO_wim_id
319 else:
320 return wim_account
321
322 def ip_profile_2_RO(ip_profile):
323 RO_ip_profile = deepcopy((ip_profile))
324 if "dns-server" in RO_ip_profile:
325 if isinstance(RO_ip_profile["dns-server"], list):
326 RO_ip_profile["dns-address"] = []
327 for ds in RO_ip_profile.pop("dns-server"):
328 RO_ip_profile["dns-address"].append(ds['address'])
329 else:
330 RO_ip_profile["dns-address"] = RO_ip_profile.pop("dns-server")
331 if RO_ip_profile.get("ip-version") == "ipv4":
332 RO_ip_profile["ip-version"] = "IPv4"
333 if RO_ip_profile.get("ip-version") == "ipv6":
334 RO_ip_profile["ip-version"] = "IPv6"
335 if "dhcp-params" in RO_ip_profile:
336 RO_ip_profile["dhcp"] = RO_ip_profile.pop("dhcp-params")
337 return RO_ip_profile
338
339 if not ns_params:
340 return None
341 RO_ns_params = {
342 # "name": ns_params["nsName"],
343 # "description": ns_params.get("nsDescription"),
344 "datacenter": vim_account_2_RO(ns_params["vimAccountId"]),
345 "wim_account": wim_account_2_RO(ns_params.get("wimAccountId")),
346 # "scenario": ns_params["nsdId"],
347 }
348 # set vim_account of each vnf if different from general vim_account.
349 # Get this information from <vnfr> database content, key vim-account-id
350 # Vim account can be set by placement_engine and it may be different from
351 # the instantiate parameters (vnfs.member-vnf-index.datacenter).
352 for vnf_index, vnfr in db_vnfrs.items():
353 if vnfr.get("vim-account-id") and vnfr["vim-account-id"] != ns_params["vimAccountId"]:
354 populate_dict(RO_ns_params, ("vnfs", vnf_index, "datacenter"), vim_account_2_RO(vnfr["vim-account-id"]))
355
356 n2vc_key_list = n2vc_key_list or []
357 for vnfd_ref, vnfd in vnfd_dict.items():
358 vdu_needed_access = []
359 mgmt_cp = None
360 if vnfd.get("vnf-configuration"):
361 ssh_required = deep_get(vnfd, ("vnf-configuration", "config-access", "ssh-access", "required"))
362 if ssh_required and vnfd.get("mgmt-interface"):
363 if vnfd["mgmt-interface"].get("vdu-id"):
364 vdu_needed_access.append(vnfd["mgmt-interface"]["vdu-id"])
365 elif vnfd["mgmt-interface"].get("cp"):
366 mgmt_cp = vnfd["mgmt-interface"]["cp"]
367
368 for vdu in vnfd.get("vdu", ()):
369 if vdu.get("vdu-configuration"):
370 ssh_required = deep_get(vdu, ("vdu-configuration", "config-access", "ssh-access", "required"))
371 if ssh_required:
372 vdu_needed_access.append(vdu["id"])
373 elif mgmt_cp:
374 for vdu_interface in vdu.get("interface"):
375 if vdu_interface.get("external-connection-point-ref") and \
376 vdu_interface["external-connection-point-ref"] == mgmt_cp:
377 vdu_needed_access.append(vdu["id"])
378 mgmt_cp = None
379 break
380
381 if vdu_needed_access:
382 for vnf_member in nsd.get("constituent-vnfd"):
383 if vnf_member["vnfd-id-ref"] != vnfd_ref:
384 continue
385 for vdu in vdu_needed_access:
386 populate_dict(RO_ns_params,
387 ("vnfs", vnf_member["member-vnf-index"], "vdus", vdu, "mgmt_keys"),
388 n2vc_key_list)
389
390 if ns_params.get("vduImage"):
391 RO_ns_params["vduImage"] = ns_params["vduImage"]
392
393 if ns_params.get("ssh_keys"):
394 RO_ns_params["cloud-config"] = {"key-pairs": ns_params["ssh_keys"]}
395 for vnf_params in get_iterable(ns_params, "vnf"):
396 for constituent_vnfd in nsd["constituent-vnfd"]:
397 if constituent_vnfd["member-vnf-index"] == vnf_params["member-vnf-index"]:
398 vnf_descriptor = vnfd_dict[constituent_vnfd["vnfd-id-ref"]]
399 break
400 else:
401 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index={} is not present at nsd:"
402 "constituent-vnfd".format(vnf_params["member-vnf-index"]))
403
404 for vdu_params in get_iterable(vnf_params, "vdu"):
405 # TODO feature 1417: check that this VDU exist and it is not a PDU
406 if vdu_params.get("volume"):
407 for volume_params in vdu_params["volume"]:
408 if volume_params.get("vim-volume-id"):
409 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
410 vdu_params["id"], "devices", volume_params["name"], "vim_id"),
411 volume_params["vim-volume-id"])
412 if vdu_params.get("interface"):
413 for interface_params in vdu_params["interface"]:
414 if interface_params.get("ip-address"):
415 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
416 vdu_params["id"], "interfaces", interface_params["name"],
417 "ip_address"),
418 interface_params["ip-address"])
419 if interface_params.get("mac-address"):
420 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
421 vdu_params["id"], "interfaces", interface_params["name"],
422 "mac_address"),
423 interface_params["mac-address"])
424 if interface_params.get("floating-ip-required"):
425 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
426 vdu_params["id"], "interfaces", interface_params["name"],
427 "floating-ip"),
428 interface_params["floating-ip-required"])
429
430 for internal_vld_params in get_iterable(vnf_params, "internal-vld"):
431 if internal_vld_params.get("vim-network-name"):
432 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "networks",
433 internal_vld_params["name"], "vim-network-name"),
434 internal_vld_params["vim-network-name"])
435 if internal_vld_params.get("vim-network-id"):
436 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "networks",
437 internal_vld_params["name"], "vim-network-id"),
438 internal_vld_params["vim-network-id"])
439 if internal_vld_params.get("ip-profile"):
440 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "networks",
441 internal_vld_params["name"], "ip-profile"),
442 ip_profile_2_RO(internal_vld_params["ip-profile"]))
443 if internal_vld_params.get("provider-network"):
444
445 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "networks",
446 internal_vld_params["name"], "provider-network"),
447 internal_vld_params["provider-network"].copy())
448
449 for icp_params in get_iterable(internal_vld_params, "internal-connection-point"):
450 # look for interface
451 iface_found = False
452 for vdu_descriptor in vnf_descriptor["vdu"]:
453 for vdu_interface in vdu_descriptor["interface"]:
454 if vdu_interface.get("internal-connection-point-ref") == icp_params["id-ref"]:
455 if icp_params.get("ip-address"):
456 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
457 vdu_descriptor["id"], "interfaces",
458 vdu_interface["name"], "ip_address"),
459 icp_params["ip-address"])
460
461 if icp_params.get("mac-address"):
462 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
463 vdu_descriptor["id"], "interfaces",
464 vdu_interface["name"], "mac_address"),
465 icp_params["mac-address"])
466 iface_found = True
467 break
468 if iface_found:
469 break
470 else:
471 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
472 "internal-vld:id-ref={} is not present at vnfd:internal-"
473 "connection-point".format(vnf_params["member-vnf-index"],
474 icp_params["id-ref"]))
475
476 for vld_params in get_iterable(ns_params, "vld"):
477 if "ip-profile" in vld_params:
478 populate_dict(RO_ns_params, ("networks", vld_params["name"], "ip-profile"),
479 ip_profile_2_RO(vld_params["ip-profile"]))
480
481 if vld_params.get("provider-network"):
482
483 populate_dict(RO_ns_params, ("networks", vld_params["name"], "provider-network"),
484 vld_params["provider-network"].copy())
485
486 if "wimAccountId" in vld_params and vld_params["wimAccountId"] is not None:
487 populate_dict(RO_ns_params, ("networks", vld_params["name"], "wim_account"),
488 wim_account_2_RO(vld_params["wimAccountId"])),
489 if vld_params.get("vim-network-name"):
490 RO_vld_sites = []
491 if isinstance(vld_params["vim-network-name"], dict):
492 for vim_account, vim_net in vld_params["vim-network-name"].items():
493 RO_vld_sites.append({
494 "netmap-use": vim_net,
495 "datacenter": vim_account_2_RO(vim_account)
496 })
497 else: # isinstance str
498 RO_vld_sites.append({"netmap-use": vld_params["vim-network-name"]})
499 if RO_vld_sites:
500 populate_dict(RO_ns_params, ("networks", vld_params["name"], "sites"), RO_vld_sites)
501
502 if vld_params.get("vim-network-id"):
503 RO_vld_sites = []
504 if isinstance(vld_params["vim-network-id"], dict):
505 for vim_account, vim_net in vld_params["vim-network-id"].items():
506 RO_vld_sites.append({
507 "netmap-use": vim_net,
508 "datacenter": vim_account_2_RO(vim_account)
509 })
510 else: # isinstance str
511 RO_vld_sites.append({"netmap-use": vld_params["vim-network-id"]})
512 if RO_vld_sites:
513 populate_dict(RO_ns_params, ("networks", vld_params["name"], "sites"), RO_vld_sites)
514 if vld_params.get("ns-net"):
515 if isinstance(vld_params["ns-net"], dict):
516 for vld_id, instance_scenario_id in vld_params["ns-net"].items():
517 RO_vld_ns_net = {"instance_scenario_id": instance_scenario_id, "osm_id": vld_id}
518 populate_dict(RO_ns_params, ("networks", vld_params["name"], "use-network"), RO_vld_ns_net)
519 if "vnfd-connection-point-ref" in vld_params:
520 for cp_params in vld_params["vnfd-connection-point-ref"]:
521 # look for interface
522 for constituent_vnfd in nsd["constituent-vnfd"]:
523 if constituent_vnfd["member-vnf-index"] == cp_params["member-vnf-index-ref"]:
524 vnf_descriptor = vnfd_dict[constituent_vnfd["vnfd-id-ref"]]
525 break
526 else:
527 raise LcmException(
528 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={} "
529 "is not present at nsd:constituent-vnfd".format(cp_params["member-vnf-index-ref"]))
530 match_cp = False
531 for vdu_descriptor in vnf_descriptor["vdu"]:
532 for interface_descriptor in vdu_descriptor["interface"]:
533 if interface_descriptor.get("external-connection-point-ref") == \
534 cp_params["vnfd-connection-point-ref"]:
535 match_cp = True
536 break
537 if match_cp:
538 break
539 else:
540 raise LcmException(
541 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={}:"
542 "vnfd-connection-point-ref={} is not present at vnfd={}".format(
543 cp_params["member-vnf-index-ref"],
544 cp_params["vnfd-connection-point-ref"],
545 vnf_descriptor["id"]))
546 if cp_params.get("ip-address"):
547 populate_dict(RO_ns_params, ("vnfs", cp_params["member-vnf-index-ref"], "vdus",
548 vdu_descriptor["id"], "interfaces",
549 interface_descriptor["name"], "ip_address"),
550 cp_params["ip-address"])
551 if cp_params.get("mac-address"):
552 populate_dict(RO_ns_params, ("vnfs", cp_params["member-vnf-index-ref"], "vdus",
553 vdu_descriptor["id"], "interfaces",
554 interface_descriptor["name"], "mac_address"),
555 cp_params["mac-address"])
556 return RO_ns_params
557
558 def scale_vnfr(self, db_vnfr, vdu_create=None, vdu_delete=None):
559 # make a copy to do not change
560 vdu_create = copy(vdu_create)
561 vdu_delete = copy(vdu_delete)
562
563 vdurs = db_vnfr.get("vdur")
564 if vdurs is None:
565 vdurs = []
566 vdu_index = len(vdurs)
567 while vdu_index:
568 vdu_index -= 1
569 vdur = vdurs[vdu_index]
570 if vdur.get("pdu-type"):
571 continue
572 vdu_id_ref = vdur["vdu-id-ref"]
573 if vdu_create and vdu_create.get(vdu_id_ref):
574 for index in range(0, vdu_create[vdu_id_ref]):
575 vdur = deepcopy(vdur)
576 vdur["_id"] = str(uuid4())
577 vdur["count-index"] += 1
578 vdurs.insert(vdu_index+1+index, vdur)
579 del vdu_create[vdu_id_ref]
580 if vdu_delete and vdu_delete.get(vdu_id_ref):
581 del vdurs[vdu_index]
582 vdu_delete[vdu_id_ref] -= 1
583 if not vdu_delete[vdu_id_ref]:
584 del vdu_delete[vdu_id_ref]
585 # check all operations are done
586 if vdu_create or vdu_delete:
587 raise LcmException("Error scaling OUT VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
588 vdu_create))
589 if vdu_delete:
590 raise LcmException("Error scaling IN VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
591 vdu_delete))
592
593 vnfr_update = {"vdur": vdurs}
594 db_vnfr["vdur"] = vdurs
595 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
596
597 def ns_update_nsr(self, ns_update_nsr, db_nsr, nsr_desc_RO):
598 """
599 Updates database nsr with the RO info for the created vld
600 :param ns_update_nsr: dictionary to be filled with the updated info
601 :param db_nsr: content of db_nsr. This is also modified
602 :param nsr_desc_RO: nsr descriptor from RO
603 :return: Nothing, LcmException is raised on errors
604 """
605
606 for vld_index, vld in enumerate(get_iterable(db_nsr, "vld")):
607 for net_RO in get_iterable(nsr_desc_RO, "nets"):
608 if vld["id"] != net_RO.get("ns_net_osm_id"):
609 continue
610 vld["vim-id"] = net_RO.get("vim_net_id")
611 vld["name"] = net_RO.get("vim_name")
612 vld["status"] = net_RO.get("status")
613 vld["status-detailed"] = net_RO.get("error_msg")
614 ns_update_nsr["vld.{}".format(vld_index)] = vld
615 break
616 else:
617 raise LcmException("ns_update_nsr: Not found vld={} at RO info".format(vld["id"]))
618
619 def set_vnfr_at_error(self, db_vnfrs, error_text):
620 try:
621 for db_vnfr in db_vnfrs.values():
622 vnfr_update = {"status": "ERROR"}
623 for vdu_index, vdur in enumerate(get_iterable(db_vnfr, "vdur")):
624 if "status" not in vdur:
625 vdur["status"] = "ERROR"
626 vnfr_update["vdur.{}.status".format(vdu_index)] = "ERROR"
627 if error_text:
628 vdur["status-detailed"] = str(error_text)
629 vnfr_update["vdur.{}.status-detailed".format(vdu_index)] = "ERROR"
630 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
631 except DbException as e:
632 self.logger.error("Cannot update vnf. {}".format(e))
633
634 def ns_update_vnfr(self, db_vnfrs, nsr_desc_RO):
635 """
636 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
637 :param db_vnfrs: dictionary with member-vnf-index: vnfr-content
638 :param nsr_desc_RO: nsr descriptor from RO
639 :return: Nothing, LcmException is raised on errors
640 """
641 for vnf_index, db_vnfr in db_vnfrs.items():
642 for vnf_RO in nsr_desc_RO["vnfs"]:
643 if vnf_RO["member_vnf_index"] != vnf_index:
644 continue
645 vnfr_update = {}
646 if vnf_RO.get("ip_address"):
647 db_vnfr["ip-address"] = vnfr_update["ip-address"] = vnf_RO["ip_address"].split(";")[0]
648 elif not db_vnfr.get("ip-address"):
649 if db_vnfr.get("vdur"): # if not VDUs, there is not ip_address
650 raise LcmExceptionNoMgmtIP("ns member_vnf_index '{}' has no IP address".format(vnf_index))
651
652 for vdu_index, vdur in enumerate(get_iterable(db_vnfr, "vdur")):
653 vdur_RO_count_index = 0
654 if vdur.get("pdu-type"):
655 continue
656 for vdur_RO in get_iterable(vnf_RO, "vms"):
657 if vdur["vdu-id-ref"] != vdur_RO["vdu_osm_id"]:
658 continue
659 if vdur["count-index"] != vdur_RO_count_index:
660 vdur_RO_count_index += 1
661 continue
662 vdur["vim-id"] = vdur_RO.get("vim_vm_id")
663 if vdur_RO.get("ip_address"):
664 vdur["ip-address"] = vdur_RO["ip_address"].split(";")[0]
665 else:
666 vdur["ip-address"] = None
667 vdur["vdu-id-ref"] = vdur_RO.get("vdu_osm_id")
668 vdur["name"] = vdur_RO.get("vim_name")
669 vdur["status"] = vdur_RO.get("status")
670 vdur["status-detailed"] = vdur_RO.get("error_msg")
671 for ifacer in get_iterable(vdur, "interfaces"):
672 for interface_RO in get_iterable(vdur_RO, "interfaces"):
673 if ifacer["name"] == interface_RO.get("internal_name"):
674 ifacer["ip-address"] = interface_RO.get("ip_address")
675 ifacer["mac-address"] = interface_RO.get("mac_address")
676 break
677 else:
678 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} interface={} "
679 "from VIM info"
680 .format(vnf_index, vdur["vdu-id-ref"], ifacer["name"]))
681 vnfr_update["vdur.{}".format(vdu_index)] = vdur
682 break
683 else:
684 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} count_index={} from "
685 "VIM info".format(vnf_index, vdur["vdu-id-ref"], vdur["count-index"]))
686
687 for vld_index, vld in enumerate(get_iterable(db_vnfr, "vld")):
688 for net_RO in get_iterable(nsr_desc_RO, "nets"):
689 if vld["id"] != net_RO.get("vnf_net_osm_id"):
690 continue
691 vld["vim-id"] = net_RO.get("vim_net_id")
692 vld["name"] = net_RO.get("vim_name")
693 vld["status"] = net_RO.get("status")
694 vld["status-detailed"] = net_RO.get("error_msg")
695 vnfr_update["vld.{}".format(vld_index)] = vld
696 break
697 else:
698 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vld={} from VIM info".format(
699 vnf_index, vld["id"]))
700
701 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
702 break
703
704 else:
705 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} from VIM info".format(vnf_index))
706
707 def _get_ns_config_info(self, nsr_id):
708 """
709 Generates a mapping between vnf,vdu elements and the N2VC id
710 :param nsr_id: id of nsr to get last database _admin.deployed.VCA that contains this list
711 :return: a dictionary with {osm-config-mapping: {}} where its element contains:
712 "<member-vnf-index>": <N2VC-id> for a vnf configuration, or
713 "<member-vnf-index>.<vdu.id>.<vdu replica(0, 1,..)>": <N2VC-id> for a vdu configuration
714 """
715 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
716 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
717 mapping = {}
718 ns_config_info = {"osm-config-mapping": mapping}
719 for vca in vca_deployed_list:
720 if not vca["member-vnf-index"]:
721 continue
722 if not vca["vdu_id"]:
723 mapping[vca["member-vnf-index"]] = vca["application"]
724 else:
725 mapping["{}.{}.{}".format(vca["member-vnf-index"], vca["vdu_id"], vca["vdu_count_index"])] =\
726 vca["application"]
727 return ns_config_info
728
729 @staticmethod
730 def _get_initial_config_primitive_list(desc_primitive_list, vca_deployed):
731 """
732 Generates a list of initial-config-primitive based on the list provided by the descriptor. It includes internal
733 primitives as verify-ssh-credentials, or config when needed
734 :param desc_primitive_list: information of the descriptor
735 :param vca_deployed: information of the deployed, needed for known if it is related to an NS, VNF, VDU and if
736 this element contains a ssh public key
737 :return: The modified list. Can ba an empty list, but always a list
738 """
739 if desc_primitive_list:
740 primitive_list = desc_primitive_list.copy()
741 else:
742 primitive_list = []
743 # look for primitive config, and get the position. None if not present
744 config_position = None
745 for index, primitive in enumerate(primitive_list):
746 if primitive["name"] == "config":
747 config_position = index
748 break
749
750 # for NS, add always a config primitive if not present (bug 874)
751 if not vca_deployed["member-vnf-index"] and config_position is None:
752 primitive_list.insert(0, {"name": "config", "parameter": []})
753 config_position = 0
754 # for VNF/VDU add verify-ssh-credentials after config
755 if vca_deployed["member-vnf-index"] and config_position is not None and vca_deployed.get("ssh-public-key"):
756 primitive_list.insert(config_position + 1, {"name": "verify-ssh-credentials", "parameter": []})
757 return primitive_list
758
759 async def instantiate_RO(self, logging_text, nsr_id, nsd, db_nsr, db_nslcmop, db_vnfrs, db_vnfds_ref,
760 n2vc_key_list, stage):
761 """
762 Instantiate at RO
763 :param logging_text: preffix text to use at logging
764 :param nsr_id: nsr identity
765 :param nsd: database content of ns descriptor
766 :param db_nsr: database content of ns record
767 :param db_nslcmop: database content of ns operation, in this case, 'instantiate'
768 :param db_vnfrs:
769 :param db_vnfds_ref: database content of vnfds, indexed by id (not _id). {id: {vnfd_object}, ...}
770 :param n2vc_key_list: ssh-public-key list to be inserted to management vdus via cloud-init
771 :param stage: list with 3 items: [general stage, tasks, vim_specific]. This task will write over vim_specific
772 :return: None or exception
773 """
774 try:
775 db_nsr_update = {}
776 RO_descriptor_number = 0 # number of descriptors created at RO
777 vnf_index_2_RO_id = {} # map between vnfd/nsd id to the id used at RO
778 nslcmop_id = db_nslcmop["_id"]
779 start_deploy = time()
780 ns_params = db_nslcmop.get("operationParams")
781 if ns_params and ns_params.get("timeout_ns_deploy"):
782 timeout_ns_deploy = ns_params["timeout_ns_deploy"]
783 else:
784 timeout_ns_deploy = self.timeout.get("ns_deploy", self.timeout_ns_deploy)
785
786 # Check for and optionally request placement optimization. Database will be updated if placement activated
787 stage[2] = "Waiting for Placement."
788 if await self._do_placement(logging_text, db_nslcmop, db_vnfrs):
789 # in case of placement change ns_params[vimAcountId) if not present at any vnfrs
790 for vnfr in db_vnfrs.values():
791 if ns_params["vimAccountId"] == vnfr["vim-account-id"]:
792 break
793 else:
794 ns_params["vimAccountId"] == vnfr["vim-account-id"]
795
796 # deploy RO
797 # get vnfds, instantiate at RO
798 for c_vnf in nsd.get("constituent-vnfd", ()):
799 member_vnf_index = c_vnf["member-vnf-index"]
800 vnfd = db_vnfds_ref[c_vnf['vnfd-id-ref']]
801 vnfd_ref = vnfd["id"]
802
803 stage[2] = "Creating vnfd='{}' member_vnf_index='{}' at RO".format(vnfd_ref, member_vnf_index)
804 db_nsr_update["detailed-status"] = " ".join(stage)
805 self.update_db_2("nsrs", nsr_id, db_nsr_update)
806 self._write_op_status(nslcmop_id, stage)
807
808 # self.logger.debug(logging_text + stage[2])
809 vnfd_id_RO = "{}.{}.{}".format(nsr_id, RO_descriptor_number, member_vnf_index[:23])
810 vnf_index_2_RO_id[member_vnf_index] = vnfd_id_RO
811 RO_descriptor_number += 1
812
813 # look position at deployed.RO.vnfd if not present it will be appended at the end
814 for index, vnf_deployed in enumerate(db_nsr["_admin"]["deployed"]["RO"]["vnfd"]):
815 if vnf_deployed["member-vnf-index"] == member_vnf_index:
816 break
817 else:
818 index = len(db_nsr["_admin"]["deployed"]["RO"]["vnfd"])
819 db_nsr["_admin"]["deployed"]["RO"]["vnfd"].append(None)
820
821 # look if present
822 RO_update = {"member-vnf-index": member_vnf_index}
823 vnfd_list = await self.RO.get_list("vnfd", filter_by={"osm_id": vnfd_id_RO})
824 if vnfd_list:
825 RO_update["id"] = vnfd_list[0]["uuid"]
826 self.logger.debug(logging_text + "vnfd='{}' member_vnf_index='{}' exists at RO. Using RO_id={}".
827 format(vnfd_ref, member_vnf_index, vnfd_list[0]["uuid"]))
828 else:
829 vnfd_RO = self.vnfd2RO(vnfd, vnfd_id_RO, db_vnfrs[c_vnf["member-vnf-index"]].
830 get("additionalParamsForVnf"), nsr_id)
831 desc = await self.RO.create("vnfd", descriptor=vnfd_RO)
832 RO_update["id"] = desc["uuid"]
833 self.logger.debug(logging_text + "vnfd='{}' member_vnf_index='{}' created at RO. RO_id={}".format(
834 vnfd_ref, member_vnf_index, desc["uuid"]))
835 db_nsr_update["_admin.deployed.RO.vnfd.{}".format(index)] = RO_update
836 db_nsr["_admin"]["deployed"]["RO"]["vnfd"][index] = RO_update
837
838 # create nsd at RO
839 nsd_ref = nsd["id"]
840
841 stage[2] = "Creating nsd={} at RO".format(nsd_ref)
842 db_nsr_update["detailed-status"] = " ".join(stage)
843 self.update_db_2("nsrs", nsr_id, db_nsr_update)
844 self._write_op_status(nslcmop_id, stage)
845
846 # self.logger.debug(logging_text + stage[2])
847 RO_osm_nsd_id = "{}.{}.{}".format(nsr_id, RO_descriptor_number, nsd_ref[:23])
848 RO_descriptor_number += 1
849 nsd_list = await self.RO.get_list("nsd", filter_by={"osm_id": RO_osm_nsd_id})
850 if nsd_list:
851 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = nsd_list[0]["uuid"]
852 self.logger.debug(logging_text + "nsd={} exists at RO. Using RO_id={}".format(
853 nsd_ref, RO_nsd_uuid))
854 else:
855 nsd_RO = deepcopy(nsd)
856 nsd_RO["id"] = RO_osm_nsd_id
857 nsd_RO.pop("_id", None)
858 nsd_RO.pop("_admin", None)
859 for c_vnf in nsd_RO.get("constituent-vnfd", ()):
860 member_vnf_index = c_vnf["member-vnf-index"]
861 c_vnf["vnfd-id-ref"] = vnf_index_2_RO_id[member_vnf_index]
862 for c_vld in nsd_RO.get("vld", ()):
863 for cp in c_vld.get("vnfd-connection-point-ref", ()):
864 member_vnf_index = cp["member-vnf-index-ref"]
865 cp["vnfd-id-ref"] = vnf_index_2_RO_id[member_vnf_index]
866
867 desc = await self.RO.create("nsd", descriptor=nsd_RO)
868 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
869 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = desc["uuid"]
870 self.logger.debug(logging_text + "nsd={} created at RO. RO_id={}".format(nsd_ref, RO_nsd_uuid))
871 self.update_db_2("nsrs", nsr_id, db_nsr_update)
872
873 # Crate ns at RO
874 stage[2] = "Creating nsd={} at RO".format(nsd_ref)
875 db_nsr_update["detailed-status"] = " ".join(stage)
876 self.update_db_2("nsrs", nsr_id, db_nsr_update)
877 self._write_op_status(nslcmop_id, stage)
878
879 # if present use it unless in error status
880 RO_nsr_id = deep_get(db_nsr, ("_admin", "deployed", "RO", "nsr_id"))
881 if RO_nsr_id:
882 try:
883 stage[2] = "Looking for existing ns at RO"
884 db_nsr_update["detailed-status"] = " ".join(stage)
885 self.update_db_2("nsrs", nsr_id, db_nsr_update)
886 self._write_op_status(nslcmop_id, stage)
887 # self.logger.debug(logging_text + stage[2] + " RO_ns_id={}".format(RO_nsr_id))
888 desc = await self.RO.show("ns", RO_nsr_id)
889
890 except ROclient.ROClientException as e:
891 if e.http_code != HTTPStatus.NOT_FOUND:
892 raise
893 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
894 if RO_nsr_id:
895 ns_status, ns_status_info = self.RO.check_ns_status(desc)
896 db_nsr_update["_admin.deployed.RO.nsr_status"] = ns_status
897 if ns_status == "ERROR":
898 stage[2] = "Deleting ns at RO. RO_ns_id={}".format(RO_nsr_id)
899 self.logger.debug(logging_text + stage[2])
900 await self.RO.delete("ns", RO_nsr_id)
901 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
902 if not RO_nsr_id:
903 stage[2] = "Checking dependencies"
904 db_nsr_update["detailed-status"] = " ".join(stage)
905 self.update_db_2("nsrs", nsr_id, db_nsr_update)
906 self._write_op_status(nslcmop_id, stage)
907 # self.logger.debug(logging_text + stage[2])
908
909 # check if VIM is creating and wait look if previous tasks in process
910 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account", ns_params["vimAccountId"])
911 if task_dependency:
912 stage[2] = "Waiting for related tasks '{}' to be completed".format(task_name)
913 self.logger.debug(logging_text + stage[2])
914 await asyncio.wait(task_dependency, timeout=3600)
915 if ns_params.get("vnf"):
916 for vnf in ns_params["vnf"]:
917 if "vimAccountId" in vnf:
918 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account",
919 vnf["vimAccountId"])
920 if task_dependency:
921 stage[2] = "Waiting for related tasks '{}' to be completed.".format(task_name)
922 self.logger.debug(logging_text + stage[2])
923 await asyncio.wait(task_dependency, timeout=3600)
924
925 stage[2] = "Checking instantiation parameters."
926 RO_ns_params = self._ns_params_2_RO(ns_params, nsd, db_vnfds_ref, db_vnfrs, n2vc_key_list)
927 stage[2] = "Deploying ns at VIM."
928 db_nsr_update["detailed-status"] = " ".join(stage)
929 self.update_db_2("nsrs", nsr_id, db_nsr_update)
930 self._write_op_status(nslcmop_id, stage)
931
932 desc = await self.RO.create("ns", descriptor=RO_ns_params, name=db_nsr["name"], scenario=RO_nsd_uuid)
933 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = desc["uuid"]
934 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
935 db_nsr_update["_admin.deployed.RO.nsr_status"] = "BUILD"
936 self.logger.debug(logging_text + "ns created at RO. RO_id={}".format(desc["uuid"]))
937
938 # wait until NS is ready
939 stage[2] = "Waiting VIM to deploy ns."
940 db_nsr_update["detailed-status"] = " ".join(stage)
941 self.update_db_2("nsrs", nsr_id, db_nsr_update)
942 self._write_op_status(nslcmop_id, stage)
943 detailed_status_old = None
944 self.logger.debug(logging_text + stage[2] + " RO_ns_id={}".format(RO_nsr_id))
945
946 old_desc = None
947 while time() <= start_deploy + timeout_ns_deploy:
948 desc = await self.RO.show("ns", RO_nsr_id)
949
950 # deploymentStatus
951 if desc != old_desc:
952 # desc has changed => update db
953 self._on_update_ro_db(nsrs_id=nsr_id, ro_descriptor=desc)
954 old_desc = desc
955
956 ns_status, ns_status_info = self.RO.check_ns_status(desc)
957 db_nsr_update["_admin.deployed.RO.nsr_status"] = ns_status
958 if ns_status == "ERROR":
959 raise ROclient.ROClientException(ns_status_info)
960 elif ns_status == "BUILD":
961 stage[2] = "VIM: ({})".format(ns_status_info)
962 elif ns_status == "ACTIVE":
963 stage[2] = "Waiting for management IP address reported by the VIM. Updating VNFRs."
964 try:
965 self.ns_update_vnfr(db_vnfrs, desc)
966 break
967 except LcmExceptionNoMgmtIP:
968 pass
969 else:
970 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
971 if stage[2] != detailed_status_old:
972 detailed_status_old = stage[2]
973 db_nsr_update["detailed-status"] = " ".join(stage)
974 self.update_db_2("nsrs", nsr_id, db_nsr_update)
975 self._write_op_status(nslcmop_id, stage)
976 await asyncio.sleep(5, loop=self.loop)
977 else: # timeout_ns_deploy
978 raise ROclient.ROClientException("Timeout waiting ns to be ready")
979
980 # Updating NSR
981 self.ns_update_nsr(db_nsr_update, db_nsr, desc)
982
983 db_nsr_update["_admin.deployed.RO.operational-status"] = "running"
984 # db_nsr["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
985 stage[2] = "Deployed at VIM"
986 db_nsr_update["detailed-status"] = " ".join(stage)
987 self.update_db_2("nsrs", nsr_id, db_nsr_update)
988 self._write_op_status(nslcmop_id, stage)
989 # await self._on_update_n2vc_db("nsrs", {"_id": nsr_id}, "_admin.deployed", db_nsr_update)
990 # self.logger.debug(logging_text + "Deployed at VIM")
991 except (ROclient.ROClientException, LcmException, DbException) as e:
992 stage[2] = "ERROR deploying at VIM"
993 self.set_vnfr_at_error(db_vnfrs, str(e))
994 raise
995
996 async def wait_vm_up_insert_key_ro(self, logging_text, nsr_id, vnfr_id, vdu_id, vdu_index, pub_key=None, user=None):
997 """
998 Wait for ip addres at RO, and optionally, insert public key in virtual machine
999 :param logging_text: prefix use for logging
1000 :param nsr_id:
1001 :param vnfr_id:
1002 :param vdu_id:
1003 :param vdu_index:
1004 :param pub_key: public ssh key to inject, None to skip
1005 :param user: user to apply the public ssh key
1006 :return: IP address
1007 """
1008
1009 # self.logger.debug(logging_text + "Starting wait_vm_up_insert_key_ro")
1010 ro_nsr_id = None
1011 ip_address = None
1012 nb_tries = 0
1013 target_vdu_id = None
1014 ro_retries = 0
1015
1016 while True:
1017
1018 ro_retries += 1
1019 if ro_retries >= 360: # 1 hour
1020 raise LcmException("Not found _admin.deployed.RO.nsr_id for nsr_id: {}".format(nsr_id))
1021
1022 await asyncio.sleep(10, loop=self.loop)
1023
1024 # get ip address
1025 if not target_vdu_id:
1026 db_vnfr = self.db.get_one("vnfrs", {"_id": vnfr_id})
1027
1028 if not vdu_id: # for the VNF case
1029 if db_vnfr.get("status") == "ERROR":
1030 raise LcmException("Cannot inject ssh-key because target VNF is in error state")
1031 ip_address = db_vnfr.get("ip-address")
1032 if not ip_address:
1033 continue
1034 vdur = next((x for x in get_iterable(db_vnfr, "vdur") if x.get("ip-address") == ip_address), None)
1035 else: # VDU case
1036 vdur = next((x for x in get_iterable(db_vnfr, "vdur")
1037 if x.get("vdu-id-ref") == vdu_id and x.get("count-index") == vdu_index), None)
1038
1039 if not vdur and len(db_vnfr.get("vdur", ())) == 1: # If only one, this should be the target vdu
1040 vdur = db_vnfr["vdur"][0]
1041 if not vdur:
1042 raise LcmException("Not found vnfr_id={}, vdu_id={}, vdu_index={}".format(vnfr_id, vdu_id,
1043 vdu_index))
1044
1045 if vdur.get("pdu-type") or vdur.get("status") == "ACTIVE":
1046 ip_address = vdur.get("ip-address")
1047 if not ip_address:
1048 continue
1049 target_vdu_id = vdur["vdu-id-ref"]
1050 elif vdur.get("status") == "ERROR":
1051 raise LcmException("Cannot inject ssh-key because target VM is in error state")
1052
1053 if not target_vdu_id:
1054 continue
1055
1056 # inject public key into machine
1057 if pub_key and user:
1058 # wait until NS is deployed at RO
1059 if not ro_nsr_id:
1060 db_nsrs = self.db.get_one("nsrs", {"_id": nsr_id})
1061 ro_nsr_id = deep_get(db_nsrs, ("_admin", "deployed", "RO", "nsr_id"))
1062 if not ro_nsr_id:
1063 continue
1064
1065 # self.logger.debug(logging_text + "Inserting RO key")
1066 if vdur.get("pdu-type"):
1067 self.logger.error(logging_text + "Cannot inject ssh-ky to a PDU")
1068 return ip_address
1069 try:
1070 ro_vm_id = "{}-{}".format(db_vnfr["member-vnf-index-ref"], target_vdu_id) # TODO add vdu_index
1071 result_dict = await self.RO.create_action(
1072 item="ns",
1073 item_id_name=ro_nsr_id,
1074 descriptor={"add_public_key": pub_key, "vms": [ro_vm_id], "user": user}
1075 )
1076 # result_dict contains the format {VM-id: {vim_result: 200, description: text}}
1077 if not result_dict or not isinstance(result_dict, dict):
1078 raise LcmException("Unknown response from RO when injecting key")
1079 for result in result_dict.values():
1080 if result.get("vim_result") == 200:
1081 break
1082 else:
1083 raise ROclient.ROClientException("error injecting key: {}".format(
1084 result.get("description")))
1085 break
1086 except ROclient.ROClientException as e:
1087 if not nb_tries:
1088 self.logger.debug(logging_text + "error injecting key: {}. Retrying until {} seconds".
1089 format(e, 20*10))
1090 nb_tries += 1
1091 if nb_tries >= 20:
1092 raise LcmException("Reaching max tries injecting key. Error: {}".format(e))
1093 else:
1094 break
1095
1096 return ip_address
1097
1098 async def _wait_dependent_n2vc(self, nsr_id, vca_deployed_list, vca_index):
1099 """
1100 Wait until dependent VCA deployments have been finished. NS wait for VNFs and VDUs. VNFs for VDUs
1101 """
1102 my_vca = vca_deployed_list[vca_index]
1103 if my_vca.get("vdu_id") or my_vca.get("kdu_name"):
1104 # vdu or kdu: no dependencies
1105 return
1106 timeout = 300
1107 while timeout >= 0:
1108 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1109 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
1110 configuration_status_list = db_nsr["configurationStatus"]
1111 for index, vca_deployed in enumerate(configuration_status_list):
1112 if index == vca_index:
1113 # myself
1114 continue
1115 if not my_vca.get("member-vnf-index") or \
1116 (vca_deployed.get("member-vnf-index") == my_vca.get("member-vnf-index")):
1117 internal_status = configuration_status_list[index].get("status")
1118 if internal_status == 'READY':
1119 continue
1120 elif internal_status == 'BROKEN':
1121 raise LcmException("Configuration aborted because dependent charm/s has failed")
1122 else:
1123 break
1124 else:
1125 # no dependencies, return
1126 return
1127 await asyncio.sleep(10)
1128 timeout -= 1
1129
1130 raise LcmException("Configuration aborted because dependent charm/s timeout")
1131
1132 async def instantiate_N2VC(self, logging_text, vca_index, nsi_id, db_nsr, db_vnfr, vdu_id, kdu_name, vdu_index,
1133 config_descriptor, deploy_params, base_folder, nslcmop_id, stage):
1134 nsr_id = db_nsr["_id"]
1135 db_update_entry = "_admin.deployed.VCA.{}.".format(vca_index)
1136 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
1137 vca_deployed = db_nsr["_admin"]["deployed"]["VCA"][vca_index]
1138 db_dict = {
1139 'collection': 'nsrs',
1140 'filter': {'_id': nsr_id},
1141 'path': db_update_entry
1142 }
1143 step = ""
1144 try:
1145
1146 element_type = 'NS'
1147 element_under_configuration = nsr_id
1148
1149 vnfr_id = None
1150 if db_vnfr:
1151 vnfr_id = db_vnfr["_id"]
1152
1153 namespace = "{nsi}.{ns}".format(
1154 nsi=nsi_id if nsi_id else "",
1155 ns=nsr_id)
1156
1157 if vnfr_id:
1158 element_type = 'VNF'
1159 element_under_configuration = vnfr_id
1160 namespace += ".{}".format(vnfr_id)
1161 if vdu_id:
1162 namespace += ".{}-{}".format(vdu_id, vdu_index or 0)
1163 element_type = 'VDU'
1164 element_under_configuration = "{}-{}".format(vdu_id, vdu_index or 0)
1165 elif kdu_name:
1166 namespace += ".{}".format(kdu_name)
1167 element_type = 'KDU'
1168 element_under_configuration = kdu_name
1169
1170 # Get artifact path
1171 artifact_path = "{}/{}/charms/{}".format(
1172 base_folder["folder"],
1173 base_folder["pkg-dir"],
1174 config_descriptor["juju"]["charm"]
1175 )
1176
1177 is_proxy_charm = deep_get(config_descriptor, ('juju', 'charm')) is not None
1178 if deep_get(config_descriptor, ('juju', 'proxy')) is False:
1179 is_proxy_charm = False
1180
1181 # n2vc_redesign STEP 3.1
1182
1183 # find old ee_id if exists
1184 ee_id = vca_deployed.get("ee_id")
1185
1186 # create or register execution environment in VCA
1187 if is_proxy_charm:
1188
1189 self._write_configuration_status(
1190 nsr_id=nsr_id,
1191 vca_index=vca_index,
1192 status='CREATING',
1193 element_under_configuration=element_under_configuration,
1194 element_type=element_type
1195 )
1196
1197 step = "create execution environment"
1198 self.logger.debug(logging_text + step)
1199 ee_id, credentials = await self.n2vc.create_execution_environment(namespace=namespace,
1200 reuse_ee_id=ee_id,
1201 db_dict=db_dict)
1202
1203 else:
1204 step = "Waiting to VM being up and getting IP address"
1205 self.logger.debug(logging_text + step)
1206 rw_mgmt_ip = await self.wait_vm_up_insert_key_ro(logging_text, nsr_id, vnfr_id, vdu_id, vdu_index,
1207 user=None, pub_key=None)
1208 credentials = {"hostname": rw_mgmt_ip}
1209 # get username
1210 username = deep_get(config_descriptor, ("config-access", "ssh-access", "default-user"))
1211 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1212 # merged. Meanwhile let's get username from initial-config-primitive
1213 if not username and config_descriptor.get("initial-config-primitive"):
1214 for config_primitive in config_descriptor["initial-config-primitive"]:
1215 for param in config_primitive.get("parameter", ()):
1216 if param["name"] == "ssh-username":
1217 username = param["value"]
1218 break
1219 if not username:
1220 raise LcmException("Cannot determine the username neither with 'initial-config-promitive' nor with "
1221 "'config-access.ssh-access.default-user'")
1222 credentials["username"] = username
1223 # n2vc_redesign STEP 3.2
1224
1225 self._write_configuration_status(
1226 nsr_id=nsr_id,
1227 vca_index=vca_index,
1228 status='REGISTERING',
1229 element_under_configuration=element_under_configuration,
1230 element_type=element_type
1231 )
1232
1233 step = "register execution environment {}".format(credentials)
1234 self.logger.debug(logging_text + step)
1235 ee_id = await self.n2vc.register_execution_environment(credentials=credentials, namespace=namespace,
1236 db_dict=db_dict)
1237
1238 # for compatibility with MON/POL modules, the need model and application name at database
1239 # TODO ask to N2VC instead of assuming the format "model_name.application_name"
1240 ee_id_parts = ee_id.split('.')
1241 model_name = ee_id_parts[0]
1242 application_name = ee_id_parts[1]
1243 db_nsr_update = {db_update_entry + "model": model_name,
1244 db_update_entry + "application": application_name,
1245 db_update_entry + "ee_id": ee_id}
1246
1247 # n2vc_redesign STEP 3.3
1248
1249 step = "Install configuration Software"
1250
1251 self._write_configuration_status(
1252 nsr_id=nsr_id,
1253 vca_index=vca_index,
1254 status='INSTALLING SW',
1255 element_under_configuration=element_under_configuration,
1256 element_type=element_type,
1257 other_update=db_nsr_update
1258 )
1259
1260 # TODO check if already done
1261 self.logger.debug(logging_text + step)
1262 config = None
1263 if not is_proxy_charm:
1264 initial_config_primitive_list = config_descriptor.get('initial-config-primitive')
1265 if initial_config_primitive_list:
1266 for primitive in initial_config_primitive_list:
1267 if primitive["name"] == "config":
1268 config = self._map_primitive_params(
1269 primitive,
1270 {},
1271 deploy_params
1272 )
1273 break
1274 await self.n2vc.install_configuration_sw(
1275 ee_id=ee_id,
1276 artifact_path=artifact_path,
1277 db_dict=db_dict,
1278 config=config
1279 )
1280
1281 # write in db flag of configuration_sw already installed
1282 self.update_db_2("nsrs", nsr_id, {db_update_entry + "config_sw_installed": True})
1283
1284 # add relations for this VCA (wait for other peers related with this VCA)
1285 await self._add_vca_relations(logging_text=logging_text, nsr_id=nsr_id, vca_index=vca_index)
1286
1287 # if SSH access is required, then get execution environment SSH public
1288 if is_proxy_charm: # if native charm we have waited already to VM be UP
1289 pub_key = None
1290 user = None
1291 if deep_get(config_descriptor, ("config-access", "ssh-access", "required")):
1292 # Needed to inject a ssh key
1293 user = deep_get(config_descriptor, ("config-access", "ssh-access", "default-user"))
1294 step = "Install configuration Software, getting public ssh key"
1295 pub_key = await self.n2vc.get_ee_ssh_public__key(ee_id=ee_id, db_dict=db_dict)
1296
1297 step = "Insert public key into VM user={} ssh_key={}".format(user, pub_key)
1298 else:
1299 step = "Waiting to VM being up and getting IP address"
1300 self.logger.debug(logging_text + step)
1301
1302 # n2vc_redesign STEP 5.1
1303 # wait for RO (ip-address) Insert pub_key into VM
1304 if vnfr_id:
1305 rw_mgmt_ip = await self.wait_vm_up_insert_key_ro(logging_text, nsr_id, vnfr_id, vdu_id, vdu_index,
1306 user=user, pub_key=pub_key)
1307 else:
1308 rw_mgmt_ip = None # This is for a NS configuration
1309
1310 self.logger.debug(logging_text + ' VM_ip_address={}'.format(rw_mgmt_ip))
1311
1312 # store rw_mgmt_ip in deploy params for later replacement
1313 deploy_params["rw_mgmt_ip"] = rw_mgmt_ip
1314
1315 # n2vc_redesign STEP 6 Execute initial config primitive
1316 step = 'execute initial config primitive'
1317 initial_config_primitive_list = config_descriptor.get('initial-config-primitive')
1318
1319 # sort initial config primitives by 'seq'
1320 if initial_config_primitive_list:
1321 try:
1322 initial_config_primitive_list.sort(key=lambda val: int(val['seq']))
1323 except Exception as e:
1324 self.logger.error(logging_text + step + ": " + str(e))
1325 else:
1326 self.logger.debug(logging_text + step + ": No initial-config-primitive")
1327
1328 # add config if not present for NS charm
1329 initial_config_primitive_list = self._get_initial_config_primitive_list(initial_config_primitive_list,
1330 vca_deployed)
1331
1332 # wait for dependent primitives execution (NS -> VNF -> VDU)
1333 if initial_config_primitive_list:
1334 await self._wait_dependent_n2vc(nsr_id, vca_deployed_list, vca_index)
1335
1336 # stage, in function of element type: vdu, kdu, vnf or ns
1337 my_vca = vca_deployed_list[vca_index]
1338 if my_vca.get("vdu_id") or my_vca.get("kdu_name"):
1339 # VDU or KDU
1340 stage[0] = 'Stage 3/5: running Day-1 primitives for VDU.'
1341 elif my_vca.get("member-vnf-index"):
1342 # VNF
1343 stage[0] = 'Stage 4/5: running Day-1 primitives for VNF.'
1344 else:
1345 # NS
1346 stage[0] = 'Stage 5/5: running Day-1 primitives for NS.'
1347
1348 self._write_configuration_status(
1349 nsr_id=nsr_id,
1350 vca_index=vca_index,
1351 status='EXECUTING PRIMITIVE'
1352 )
1353
1354 self._write_op_status(
1355 op_id=nslcmop_id,
1356 stage=stage
1357 )
1358
1359 check_if_terminated_needed = True
1360 for initial_config_primitive in initial_config_primitive_list:
1361 # adding information on the vca_deployed if it is a NS execution environment
1362 if not vca_deployed["member-vnf-index"]:
1363 deploy_params["ns_config_info"] = json.dumps(self._get_ns_config_info(nsr_id))
1364 # TODO check if already done
1365 primitive_params_ = self._map_primitive_params(initial_config_primitive, {}, deploy_params)
1366
1367 step = "execute primitive '{}' params '{}'".format(initial_config_primitive["name"], primitive_params_)
1368 self.logger.debug(logging_text + step)
1369 await self.n2vc.exec_primitive(
1370 ee_id=ee_id,
1371 primitive_name=initial_config_primitive["name"],
1372 params_dict=primitive_params_,
1373 db_dict=db_dict
1374 )
1375 # Once some primitive has been exec, check and write at db if it needs to exec terminated primitives
1376 if check_if_terminated_needed:
1377 if config_descriptor.get('terminate-config-primitive'):
1378 self.update_db_2("nsrs", nsr_id, {db_update_entry + "needed_terminate": True})
1379 check_if_terminated_needed = False
1380
1381 # TODO register in database that primitive is done
1382
1383 step = "instantiated at VCA"
1384 self.logger.debug(logging_text + step)
1385
1386 self._write_configuration_status(
1387 nsr_id=nsr_id,
1388 vca_index=vca_index,
1389 status='READY'
1390 )
1391
1392 except Exception as e: # TODO not use Exception but N2VC exception
1393 # self.update_db_2("nsrs", nsr_id, {db_update_entry + "instantiation": "FAILED"})
1394 if not isinstance(e, (DbException, N2VCException, LcmException, asyncio.CancelledError)):
1395 self.logger.error("Exception while {} : {}".format(step, e), exc_info=True)
1396 self._write_configuration_status(
1397 nsr_id=nsr_id,
1398 vca_index=vca_index,
1399 status='BROKEN'
1400 )
1401 raise LcmException("{} {}".format(step, e)) from e
1402
1403 def _write_ns_status(self, nsr_id: str, ns_state: str, current_operation: str, current_operation_id: str,
1404 error_description: str = None, error_detail: str = None, other_update: dict = None):
1405 """
1406 Update db_nsr fields.
1407 :param nsr_id:
1408 :param ns_state:
1409 :param current_operation:
1410 :param current_operation_id:
1411 :param error_description:
1412 :param error_detail:
1413 :param other_update: Other required changes at database if provided, will be cleared
1414 :return:
1415 """
1416 try:
1417 db_dict = other_update or {}
1418 db_dict["_admin.nslcmop"] = current_operation_id # for backward compatibility
1419 db_dict["_admin.current-operation"] = current_operation_id
1420 db_dict["_admin.operation-type"] = current_operation if current_operation != "IDLE" else None
1421 db_dict["currentOperation"] = current_operation
1422 db_dict["currentOperationID"] = current_operation_id
1423 db_dict["errorDescription"] = error_description
1424 db_dict["errorDetail"] = error_detail
1425
1426 if ns_state:
1427 db_dict["nsState"] = ns_state
1428 self.update_db_2("nsrs", nsr_id, db_dict)
1429 except DbException as e:
1430 self.logger.warn('Error writing NS status, ns={}: {}'.format(nsr_id, e))
1431
1432 def _write_op_status(self, op_id: str, stage: list = None, error_message: str = None, queuePosition: int = 0,
1433 operation_state: str = None, other_update: dict = None):
1434 try:
1435 db_dict = other_update or {}
1436 db_dict['queuePosition'] = queuePosition
1437 if isinstance(stage, list):
1438 db_dict['stage'] = stage[0]
1439 db_dict['detailed-status'] = " ".join(stage)
1440 elif stage is not None:
1441 db_dict['stage'] = str(stage)
1442
1443 if error_message is not None:
1444 db_dict['errorMessage'] = error_message
1445 if operation_state is not None:
1446 db_dict['operationState'] = operation_state
1447 db_dict["statusEnteredTime"] = time()
1448 self.update_db_2("nslcmops", op_id, db_dict)
1449 except DbException as e:
1450 self.logger.warn('Error writing OPERATION status for op_id: {} -> {}'.format(op_id, e))
1451
1452 def _write_all_config_status(self, db_nsr: dict, status: str):
1453 try:
1454 nsr_id = db_nsr["_id"]
1455 # configurationStatus
1456 config_status = db_nsr.get('configurationStatus')
1457 if config_status:
1458 db_nsr_update = {"configurationStatus.{}.status".format(index): status for index, v in
1459 enumerate(config_status) if v}
1460 # update status
1461 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1462
1463 except DbException as e:
1464 self.logger.warn('Error writing all configuration status, ns={}: {}'.format(nsr_id, e))
1465
1466 def _write_configuration_status(self, nsr_id: str, vca_index: int, status: str = None,
1467 element_under_configuration: str = None, element_type: str = None,
1468 other_update: dict = None):
1469
1470 # self.logger.debug('_write_configuration_status(): vca_index={}, status={}'
1471 # .format(vca_index, status))
1472
1473 try:
1474 db_path = 'configurationStatus.{}.'.format(vca_index)
1475 db_dict = other_update or {}
1476 if status:
1477 db_dict[db_path + 'status'] = status
1478 if element_under_configuration:
1479 db_dict[db_path + 'elementUnderConfiguration'] = element_under_configuration
1480 if element_type:
1481 db_dict[db_path + 'elementType'] = element_type
1482 self.update_db_2("nsrs", nsr_id, db_dict)
1483 except DbException as e:
1484 self.logger.warn('Error writing configuration status={}, ns={}, vca_index={}: {}'
1485 .format(status, nsr_id, vca_index, e))
1486
1487 async def _do_placement(self, logging_text, db_nslcmop, db_vnfrs):
1488 """
1489 Check and computes the placement, (vim account where to deploy). If it is decided by an external tool, it
1490 sends the request via kafka and wait until the result is wrote at database (nslcmops _admin.plca).
1491 Database is used because the result can be obtained from a different LCM worker in case of HA.
1492 :param logging_text: contains the prefix for logging, with the ns and nslcmop identifiers
1493 :param db_nslcmop: database content of nslcmop
1494 :param db_vnfrs: database content of vnfrs, indexed by member-vnf-index.
1495 :return: True if some modification is done. Modifies database vnfrs and parameter db_vnfr with the
1496 computed 'vim-account-id'
1497 """
1498 modified = False
1499 nslcmop_id = db_nslcmop['_id']
1500 placement_engine = deep_get(db_nslcmop, ('operationParams', 'placement-engine'))
1501 if placement_engine == "PLA":
1502 self.logger.debug(logging_text + "Invoke and wait for placement optimization")
1503 await self.msg.aiowrite("pla", "get_placement", {'nslcmopId': nslcmop_id}, loop=self.loop)
1504 db_poll_interval = 5
1505 wait = db_poll_interval * 10
1506 pla_result = None
1507 while not pla_result and wait >= 0:
1508 await asyncio.sleep(db_poll_interval)
1509 wait -= db_poll_interval
1510 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
1511 pla_result = deep_get(db_nslcmop, ('_admin', 'pla'))
1512
1513 if not pla_result:
1514 raise LcmException("Placement timeout for nslcmopId={}".format(nslcmop_id))
1515
1516 for pla_vnf in pla_result['vnf']:
1517 vnfr = db_vnfrs.get(pla_vnf['member-vnf-index'])
1518 if not pla_vnf.get('vimAccountId') or not vnfr:
1519 continue
1520 modified = True
1521 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, {"vim-account-id": pla_vnf['vimAccountId']})
1522 # Modifies db_vnfrs
1523 vnfr["vim-account-id"] = pla_vnf['vimAccountId']
1524 return modified
1525
1526 def update_nsrs_with_pla_result(self, params):
1527 try:
1528 nslcmop_id = deep_get(params, ('placement', 'nslcmopId'))
1529 self.update_db_2("nslcmops", nslcmop_id, {"_admin.pla": params.get('placement')})
1530 except Exception as e:
1531 self.logger.warn('Update failed for nslcmop_id={}:{}'.format(nslcmop_id, e))
1532
1533 async def instantiate(self, nsr_id, nslcmop_id):
1534 """
1535
1536 :param nsr_id: ns instance to deploy
1537 :param nslcmop_id: operation to run
1538 :return:
1539 """
1540
1541 # Try to lock HA task here
1542 task_is_locked_by_me = self.lcm_tasks.lock_HA('ns', 'nslcmops', nslcmop_id)
1543 if not task_is_locked_by_me:
1544 self.logger.debug('instantiate() task is not locked by me, ns={}'.format(nsr_id))
1545 return
1546
1547 logging_text = "Task ns={} instantiate={} ".format(nsr_id, nslcmop_id)
1548 self.logger.debug(logging_text + "Enter")
1549
1550 # Sync from FSMongo
1551 self.fs.sync()
1552
1553 # get all needed from database
1554
1555 # database nsrs record
1556 db_nsr = None
1557
1558 # database nslcmops record
1559 db_nslcmop = None
1560
1561 # update operation on nsrs
1562 db_nsr_update = {}
1563 # update operation on nslcmops
1564 db_nslcmop_update = {}
1565
1566 nslcmop_operation_state = None
1567 db_vnfrs = {} # vnf's info indexed by member-index
1568 # n2vc_info = {}
1569 tasks_dict_info = {} # from task to info text
1570 exc = None
1571 error_list = []
1572 stage = ['Stage 1/5: preparation of the environment.', "Waiting for previous operations to terminate.", ""]
1573 # ^ stage, step, VIM progress
1574 try:
1575 # wait for any previous tasks in process
1576 await self.lcm_tasks.waitfor_related_HA('ns', 'nslcmops', nslcmop_id)
1577
1578 # STEP 0: Reading database (nslcmops, nsrs, nsds, vnfrs, vnfds)
1579 stage[1] = "Reading from database,"
1580 # nsState="BUILDING", currentOperation="INSTANTIATING", currentOperationID=nslcmop_id
1581 db_nsr_update["detailed-status"] = "creating"
1582 db_nsr_update["operational-status"] = "init"
1583 self._write_ns_status(
1584 nsr_id=nsr_id,
1585 ns_state="BUILDING",
1586 current_operation="INSTANTIATING",
1587 current_operation_id=nslcmop_id,
1588 other_update=db_nsr_update
1589 )
1590 self._write_op_status(
1591 op_id=nslcmop_id,
1592 stage=stage,
1593 queuePosition=0
1594 )
1595
1596 # read from db: operation
1597 stage[1] = "Getting nslcmop={} from db".format(nslcmop_id)
1598 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
1599 ns_params = db_nslcmop.get("operationParams")
1600 if ns_params and ns_params.get("timeout_ns_deploy"):
1601 timeout_ns_deploy = ns_params["timeout_ns_deploy"]
1602 else:
1603 timeout_ns_deploy = self.timeout.get("ns_deploy", self.timeout_ns_deploy)
1604
1605 # read from db: ns
1606 stage[1] = "Getting nsr={} from db".format(nsr_id)
1607 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1608 stage[1] = "Getting nsd={} from db".format(db_nsr["nsd-id"])
1609 nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
1610 db_nsr["nsd"] = nsd
1611 # nsr_name = db_nsr["name"] # TODO short-name??
1612
1613 # read from db: vnf's of this ns
1614 stage[1] = "Getting vnfrs from db"
1615 self.logger.debug(logging_text + stage[1])
1616 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1617
1618 # read from db: vnfd's for every vnf
1619 db_vnfds_ref = {} # every vnfd data indexed by vnf name
1620 db_vnfds = {} # every vnfd data indexed by vnf id
1621 db_vnfds_index = {} # every vnfd data indexed by vnf member-index
1622
1623 # for each vnf in ns, read vnfd
1624 for vnfr in db_vnfrs_list:
1625 db_vnfrs[vnfr["member-vnf-index-ref"]] = vnfr # vnf's dict indexed by member-index: '1', '2', etc
1626 vnfd_id = vnfr["vnfd-id"] # vnfd uuid for this vnf
1627 vnfd_ref = vnfr["vnfd-ref"] # vnfd name for this vnf
1628 # if we haven't this vnfd, read it from db
1629 if vnfd_id not in db_vnfds:
1630 # read from db
1631 stage[1] = "Getting vnfd={} id='{}' from db".format(vnfd_id, vnfd_ref)
1632 self.logger.debug(logging_text + stage[1])
1633 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
1634
1635 # store vnfd
1636 db_vnfds_ref[vnfd_ref] = vnfd # vnfd's indexed by name
1637 db_vnfds[vnfd_id] = vnfd # vnfd's indexed by id
1638 db_vnfds_index[vnfr["member-vnf-index-ref"]] = db_vnfds[vnfd_id] # vnfd's indexed by member-index
1639
1640 # Get or generates the _admin.deployed.VCA list
1641 vca_deployed_list = None
1642 if db_nsr["_admin"].get("deployed"):
1643 vca_deployed_list = db_nsr["_admin"]["deployed"].get("VCA")
1644 if vca_deployed_list is None:
1645 vca_deployed_list = []
1646 configuration_status_list = []
1647 db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
1648 db_nsr_update["configurationStatus"] = configuration_status_list
1649 # add _admin.deployed.VCA to db_nsr dictionary, value=vca_deployed_list
1650 populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
1651 elif isinstance(vca_deployed_list, dict):
1652 # maintain backward compatibility. Change a dict to list at database
1653 vca_deployed_list = list(vca_deployed_list.values())
1654 db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
1655 populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
1656
1657 if not isinstance(deep_get(db_nsr, ("_admin", "deployed", "RO", "vnfd")), list):
1658 populate_dict(db_nsr, ("_admin", "deployed", "RO", "vnfd"), [])
1659 db_nsr_update["_admin.deployed.RO.vnfd"] = []
1660
1661 # set state to INSTANTIATED. When instantiated NBI will not delete directly
1662 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
1663 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1664
1665 # n2vc_redesign STEP 2 Deploy Network Scenario
1666 stage[0] = 'Stage 2/5: deployment of KDUs, VMs and execution environments.'
1667 self._write_op_status(
1668 op_id=nslcmop_id,
1669 stage=stage
1670 )
1671
1672 stage[1] = "Deploying KDUs,"
1673 # self.logger.debug(logging_text + "Before deploy_kdus")
1674 # Call to deploy_kdus in case exists the "vdu:kdu" param
1675 await self.deploy_kdus(
1676 logging_text=logging_text,
1677 nsr_id=nsr_id,
1678 nslcmop_id=nslcmop_id,
1679 db_vnfrs=db_vnfrs,
1680 db_vnfds=db_vnfds,
1681 task_instantiation_info=tasks_dict_info,
1682 )
1683
1684 stage[1] = "Getting VCA public key."
1685 # n2vc_redesign STEP 1 Get VCA public ssh-key
1686 # feature 1429. Add n2vc public key to needed VMs
1687 n2vc_key = self.n2vc.get_public_key()
1688 n2vc_key_list = [n2vc_key]
1689 if self.vca_config.get("public_key"):
1690 n2vc_key_list.append(self.vca_config["public_key"])
1691
1692 stage[1] = "Deploying NS at VIM."
1693 task_ro = asyncio.ensure_future(
1694 self.instantiate_RO(
1695 logging_text=logging_text,
1696 nsr_id=nsr_id,
1697 nsd=nsd,
1698 db_nsr=db_nsr,
1699 db_nslcmop=db_nslcmop,
1700 db_vnfrs=db_vnfrs,
1701 db_vnfds_ref=db_vnfds_ref,
1702 n2vc_key_list=n2vc_key_list,
1703 stage=stage
1704 )
1705 )
1706 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "instantiate_RO", task_ro)
1707 tasks_dict_info[task_ro] = "Deploying at VIM"
1708
1709 # n2vc_redesign STEP 3 to 6 Deploy N2VC
1710 stage[1] = "Deploying Execution Environments."
1711 self.logger.debug(logging_text + stage[1])
1712
1713 nsi_id = None # TODO put nsi_id when this nsr belongs to a NSI
1714 # get_iterable() returns a value from a dict or empty tuple if key does not exist
1715 for c_vnf in get_iterable(nsd, "constituent-vnfd"):
1716 vnfd_id = c_vnf["vnfd-id-ref"]
1717 vnfd = db_vnfds_ref[vnfd_id]
1718 member_vnf_index = str(c_vnf["member-vnf-index"])
1719 db_vnfr = db_vnfrs[member_vnf_index]
1720 base_folder = vnfd["_admin"]["storage"]
1721 vdu_id = None
1722 vdu_index = 0
1723 vdu_name = None
1724 kdu_name = None
1725
1726 # Get additional parameters
1727 deploy_params = {}
1728 if db_vnfr.get("additionalParamsForVnf"):
1729 deploy_params = self._format_additional_params(db_vnfr["additionalParamsForVnf"].copy())
1730
1731 descriptor_config = vnfd.get("vnf-configuration")
1732 if descriptor_config and descriptor_config.get("juju"):
1733 self._deploy_n2vc(
1734 logging_text=logging_text + "member_vnf_index={} ".format(member_vnf_index),
1735 db_nsr=db_nsr,
1736 db_vnfr=db_vnfr,
1737 nslcmop_id=nslcmop_id,
1738 nsr_id=nsr_id,
1739 nsi_id=nsi_id,
1740 vnfd_id=vnfd_id,
1741 vdu_id=vdu_id,
1742 kdu_name=kdu_name,
1743 member_vnf_index=member_vnf_index,
1744 vdu_index=vdu_index,
1745 vdu_name=vdu_name,
1746 deploy_params=deploy_params,
1747 descriptor_config=descriptor_config,
1748 base_folder=base_folder,
1749 task_instantiation_info=tasks_dict_info,
1750 stage=stage
1751 )
1752
1753 # Deploy charms for each VDU that supports one.
1754 for vdud in get_iterable(vnfd, 'vdu'):
1755 vdu_id = vdud["id"]
1756 descriptor_config = vdud.get('vdu-configuration')
1757 vdur = next((x for x in db_vnfr["vdur"] if x["vdu-id-ref"] == vdu_id), None)
1758 if vdur.get("additionalParams"):
1759 deploy_params_vdu = self._format_additional_params(vdur["additionalParams"])
1760 else:
1761 deploy_params_vdu = deploy_params
1762 if descriptor_config and descriptor_config.get("juju"):
1763 # look for vdu index in the db_vnfr["vdu"] section
1764 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
1765 # if vdur["vdu-id-ref"] == vdu_id:
1766 # break
1767 # else:
1768 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
1769 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
1770 # vdu_name = vdur.get("name")
1771 vdu_name = None
1772 kdu_name = None
1773 for vdu_index in range(int(vdud.get("count", 1))):
1774 # TODO vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
1775 self._deploy_n2vc(
1776 logging_text=logging_text + "member_vnf_index={}, vdu_id={}, vdu_index={} ".format(
1777 member_vnf_index, vdu_id, vdu_index),
1778 db_nsr=db_nsr,
1779 db_vnfr=db_vnfr,
1780 nslcmop_id=nslcmop_id,
1781 nsr_id=nsr_id,
1782 nsi_id=nsi_id,
1783 vnfd_id=vnfd_id,
1784 vdu_id=vdu_id,
1785 kdu_name=kdu_name,
1786 member_vnf_index=member_vnf_index,
1787 vdu_index=vdu_index,
1788 vdu_name=vdu_name,
1789 deploy_params=deploy_params_vdu,
1790 descriptor_config=descriptor_config,
1791 base_folder=base_folder,
1792 task_instantiation_info=tasks_dict_info,
1793 stage=stage
1794 )
1795 for kdud in get_iterable(vnfd, 'kdu'):
1796 kdu_name = kdud["name"]
1797 descriptor_config = kdud.get('kdu-configuration')
1798 if descriptor_config and descriptor_config.get("juju"):
1799 vdu_id = None
1800 vdu_index = 0
1801 vdu_name = None
1802 # look for vdu index in the db_vnfr["vdu"] section
1803 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
1804 # if vdur["vdu-id-ref"] == vdu_id:
1805 # break
1806 # else:
1807 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
1808 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
1809 # vdu_name = vdur.get("name")
1810 # vdu_name = None
1811
1812 self._deploy_n2vc(
1813 logging_text=logging_text,
1814 db_nsr=db_nsr,
1815 db_vnfr=db_vnfr,
1816 nslcmop_id=nslcmop_id,
1817 nsr_id=nsr_id,
1818 nsi_id=nsi_id,
1819 vnfd_id=vnfd_id,
1820 vdu_id=vdu_id,
1821 kdu_name=kdu_name,
1822 member_vnf_index=member_vnf_index,
1823 vdu_index=vdu_index,
1824 vdu_name=vdu_name,
1825 deploy_params=deploy_params,
1826 descriptor_config=descriptor_config,
1827 base_folder=base_folder,
1828 task_instantiation_info=tasks_dict_info,
1829 stage=stage
1830 )
1831
1832 # Check if this NS has a charm configuration
1833 descriptor_config = nsd.get("ns-configuration")
1834 if descriptor_config and descriptor_config.get("juju"):
1835 vnfd_id = None
1836 db_vnfr = None
1837 member_vnf_index = None
1838 vdu_id = None
1839 kdu_name = None
1840 vdu_index = 0
1841 vdu_name = None
1842
1843 # Get additional parameters
1844 deploy_params = {}
1845 if db_nsr.get("additionalParamsForNs"):
1846 deploy_params = self._format_additional_params(db_nsr["additionalParamsForNs"].copy())
1847 base_folder = nsd["_admin"]["storage"]
1848 self._deploy_n2vc(
1849 logging_text=logging_text,
1850 db_nsr=db_nsr,
1851 db_vnfr=db_vnfr,
1852 nslcmop_id=nslcmop_id,
1853 nsr_id=nsr_id,
1854 nsi_id=nsi_id,
1855 vnfd_id=vnfd_id,
1856 vdu_id=vdu_id,
1857 kdu_name=kdu_name,
1858 member_vnf_index=member_vnf_index,
1859 vdu_index=vdu_index,
1860 vdu_name=vdu_name,
1861 deploy_params=deploy_params,
1862 descriptor_config=descriptor_config,
1863 base_folder=base_folder,
1864 task_instantiation_info=tasks_dict_info,
1865 stage=stage
1866 )
1867
1868 # rest of staff will be done at finally
1869
1870 except (ROclient.ROClientException, DbException, LcmException, N2VCException) as e:
1871 self.logger.error(logging_text + "Exit Exception while '{}': {}".format(stage[1], e))
1872 exc = e
1873 except asyncio.CancelledError:
1874 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(stage[1]))
1875 exc = "Operation was cancelled"
1876 except Exception as e:
1877 exc = traceback.format_exc()
1878 self.logger.critical(logging_text + "Exit Exception while '{}': {}".format(stage[1], e), exc_info=True)
1879 finally:
1880 if exc:
1881 error_list.append(str(exc))
1882 try:
1883 # wait for pending tasks
1884 if tasks_dict_info:
1885 stage[1] = "Waiting for instantiate pending tasks."
1886 self.logger.debug(logging_text + stage[1])
1887 error_list += await self._wait_for_tasks(logging_text, tasks_dict_info, timeout_ns_deploy,
1888 stage, nslcmop_id, nsr_id=nsr_id)
1889 stage[1] = stage[2] = ""
1890 except asyncio.CancelledError:
1891 error_list.append("Cancelled")
1892 # TODO cancel all tasks
1893 except Exception as exc:
1894 error_list.append(str(exc))
1895
1896 # update operation-status
1897 db_nsr_update["operational-status"] = "running"
1898 # let's begin with VCA 'configured' status (later we can change it)
1899 db_nsr_update["config-status"] = "configured"
1900 for task, task_name in tasks_dict_info.items():
1901 if not task.done() or task.cancelled() or task.exception():
1902 if task_name.startswith(self.task_name_deploy_vca):
1903 # A N2VC task is pending
1904 db_nsr_update["config-status"] = "failed"
1905 else:
1906 # RO or KDU task is pending
1907 db_nsr_update["operational-status"] = "failed"
1908
1909 # update status at database
1910 if error_list:
1911 error_detail = ". ".join(error_list)
1912 self.logger.error(logging_text + error_detail)
1913 error_description_nslcmop = 'Stage: {}. Detail: {}'.format(stage[0], error_detail)
1914 error_description_nsr = 'Operation: INSTANTIATING.{}, Stage {}'.format(nslcmop_id, stage[0])
1915
1916 db_nsr_update["detailed-status"] = error_description_nsr + " Detail: " + error_detail
1917 db_nslcmop_update["detailed-status"] = error_detail
1918 nslcmop_operation_state = "FAILED"
1919 ns_state = "BROKEN"
1920 else:
1921 error_detail = None
1922 error_description_nsr = error_description_nslcmop = None
1923 ns_state = "READY"
1924 db_nsr_update["detailed-status"] = "Done"
1925 db_nslcmop_update["detailed-status"] = "Done"
1926 nslcmop_operation_state = "COMPLETED"
1927
1928 if db_nsr:
1929 self._write_ns_status(
1930 nsr_id=nsr_id,
1931 ns_state=ns_state,
1932 current_operation="IDLE",
1933 current_operation_id=None,
1934 error_description=error_description_nsr,
1935 error_detail=error_detail,
1936 other_update=db_nsr_update
1937 )
1938 self._write_op_status(
1939 op_id=nslcmop_id,
1940 stage="",
1941 error_message=error_description_nslcmop,
1942 operation_state=nslcmop_operation_state,
1943 other_update=db_nslcmop_update,
1944 )
1945
1946 if nslcmop_operation_state:
1947 try:
1948 await self.msg.aiowrite("ns", "instantiated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
1949 "operationState": nslcmop_operation_state},
1950 loop=self.loop)
1951 except Exception as e:
1952 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1953
1954 self.logger.debug(logging_text + "Exit")
1955 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_instantiate")
1956
1957 async def _add_vca_relations(self, logging_text, nsr_id, vca_index: int, timeout: int = 3600) -> bool:
1958
1959 # steps:
1960 # 1. find all relations for this VCA
1961 # 2. wait for other peers related
1962 # 3. add relations
1963
1964 try:
1965
1966 # STEP 1: find all relations for this VCA
1967
1968 # read nsr record
1969 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1970 nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
1971
1972 # this VCA data
1973 my_vca = deep_get(db_nsr, ('_admin', 'deployed', 'VCA'))[vca_index]
1974
1975 # read all ns-configuration relations
1976 ns_relations = list()
1977 db_ns_relations = deep_get(nsd, ('ns-configuration', 'relation'))
1978 if db_ns_relations:
1979 for r in db_ns_relations:
1980 # check if this VCA is in the relation
1981 if my_vca.get('member-vnf-index') in\
1982 (r.get('entities')[0].get('id'), r.get('entities')[1].get('id')):
1983 ns_relations.append(r)
1984
1985 # read all vnf-configuration relations
1986 vnf_relations = list()
1987 db_vnfd_list = db_nsr.get('vnfd-id')
1988 if db_vnfd_list:
1989 for vnfd in db_vnfd_list:
1990 db_vnfd = self.db.get_one("vnfds", {"_id": vnfd})
1991 db_vnf_relations = deep_get(db_vnfd, ('vnf-configuration', 'relation'))
1992 if db_vnf_relations:
1993 for r in db_vnf_relations:
1994 # check if this VCA is in the relation
1995 if my_vca.get('vdu_id') in (r.get('entities')[0].get('id'), r.get('entities')[1].get('id')):
1996 vnf_relations.append(r)
1997
1998 # if no relations, terminate
1999 if not ns_relations and not vnf_relations:
2000 self.logger.debug(logging_text + ' No relations')
2001 return True
2002
2003 self.logger.debug(logging_text + ' adding relations\n {}\n {}'.format(ns_relations, vnf_relations))
2004
2005 # add all relations
2006 start = time()
2007 while True:
2008 # check timeout
2009 now = time()
2010 if now - start >= timeout:
2011 self.logger.error(logging_text + ' : timeout adding relations')
2012 return False
2013
2014 # reload nsr from database (we need to update record: _admin.deloyed.VCA)
2015 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2016
2017 # for each defined NS relation, find the VCA's related
2018 for r in ns_relations:
2019 from_vca_ee_id = None
2020 to_vca_ee_id = None
2021 from_vca_endpoint = None
2022 to_vca_endpoint = None
2023 vca_list = deep_get(db_nsr, ('_admin', 'deployed', 'VCA'))
2024 for vca in vca_list:
2025 if vca.get('member-vnf-index') == r.get('entities')[0].get('id') \
2026 and vca.get('config_sw_installed'):
2027 from_vca_ee_id = vca.get('ee_id')
2028 from_vca_endpoint = r.get('entities')[0].get('endpoint')
2029 if vca.get('member-vnf-index') == r.get('entities')[1].get('id') \
2030 and vca.get('config_sw_installed'):
2031 to_vca_ee_id = vca.get('ee_id')
2032 to_vca_endpoint = r.get('entities')[1].get('endpoint')
2033 if from_vca_ee_id and to_vca_ee_id:
2034 # add relation
2035 await self.n2vc.add_relation(
2036 ee_id_1=from_vca_ee_id,
2037 ee_id_2=to_vca_ee_id,
2038 endpoint_1=from_vca_endpoint,
2039 endpoint_2=to_vca_endpoint)
2040 # remove entry from relations list
2041 ns_relations.remove(r)
2042 else:
2043 # check failed peers
2044 try:
2045 vca_status_list = db_nsr.get('configurationStatus')
2046 if vca_status_list:
2047 for i in range(len(vca_list)):
2048 vca = vca_list[i]
2049 vca_status = vca_status_list[i]
2050 if vca.get('member-vnf-index') == r.get('entities')[0].get('id'):
2051 if vca_status.get('status') == 'BROKEN':
2052 # peer broken: remove relation from list
2053 ns_relations.remove(r)
2054 if vca.get('member-vnf-index') == r.get('entities')[1].get('id'):
2055 if vca_status.get('status') == 'BROKEN':
2056 # peer broken: remove relation from list
2057 ns_relations.remove(r)
2058 except Exception:
2059 # ignore
2060 pass
2061
2062 # for each defined VNF relation, find the VCA's related
2063 for r in vnf_relations:
2064 from_vca_ee_id = None
2065 to_vca_ee_id = None
2066 from_vca_endpoint = None
2067 to_vca_endpoint = None
2068 vca_list = deep_get(db_nsr, ('_admin', 'deployed', 'VCA'))
2069 for vca in vca_list:
2070 key_to_check = "vdu_id"
2071 if vca.get("vdu_id") is None:
2072 key_to_check = "vnfd_id"
2073 if vca.get(key_to_check) == r.get('entities')[0].get('id') and vca.get('config_sw_installed'):
2074 from_vca_ee_id = vca.get('ee_id')
2075 from_vca_endpoint = r.get('entities')[0].get('endpoint')
2076 if vca.get(key_to_check) == r.get('entities')[1].get('id') and vca.get('config_sw_installed'):
2077 to_vca_ee_id = vca.get('ee_id')
2078 to_vca_endpoint = r.get('entities')[1].get('endpoint')
2079 if from_vca_ee_id and to_vca_ee_id:
2080 # add relation
2081 await self.n2vc.add_relation(
2082 ee_id_1=from_vca_ee_id,
2083 ee_id_2=to_vca_ee_id,
2084 endpoint_1=from_vca_endpoint,
2085 endpoint_2=to_vca_endpoint)
2086 # remove entry from relations list
2087 vnf_relations.remove(r)
2088 else:
2089 # check failed peers
2090 try:
2091 vca_status_list = db_nsr.get('configurationStatus')
2092 if vca_status_list:
2093 for i in range(len(vca_list)):
2094 vca = vca_list[i]
2095 vca_status = vca_status_list[i]
2096 if vca.get('vdu_id') == r.get('entities')[0].get('id'):
2097 if vca_status.get('status') == 'BROKEN':
2098 # peer broken: remove relation from list
2099 ns_relations.remove(r)
2100 if vca.get('vdu_id') == r.get('entities')[1].get('id'):
2101 if vca_status.get('status') == 'BROKEN':
2102 # peer broken: remove relation from list
2103 ns_relations.remove(r)
2104 except Exception:
2105 # ignore
2106 pass
2107
2108 # wait for next try
2109 await asyncio.sleep(5.0)
2110
2111 if not ns_relations and not vnf_relations:
2112 self.logger.debug('Relations added')
2113 break
2114
2115 return True
2116
2117 except Exception as e:
2118 self.logger.warn(logging_text + ' ERROR adding relations: {}'.format(e))
2119 return False
2120
2121 def _write_db_callback(self, task, item, _id, on_done=None, on_exc=None):
2122 """
2123 callback for kdu install intended to store the returned kdu_instance at database
2124 :return: None
2125 """
2126 db_update = {}
2127 try:
2128 result = task.result()
2129 if on_done:
2130 db_update[on_done] = str(result)
2131 except Exception as e:
2132 if on_exc:
2133 db_update[on_exc] = str(e)
2134 if db_update:
2135 try:
2136 self.update_db_2(item, _id, db_update)
2137 except Exception:
2138 pass
2139
2140 async def deploy_kdus(self, logging_text, nsr_id, nslcmop_id, db_vnfrs, db_vnfds, task_instantiation_info):
2141 # Launch kdus if present in the descriptor
2142
2143 k8scluster_id_2_uuic = {"helm-chart": {}, "juju-bundle": {}}
2144
2145 def _get_cluster_id(cluster_id, cluster_type):
2146 nonlocal k8scluster_id_2_uuic
2147 if cluster_id in k8scluster_id_2_uuic[cluster_type]:
2148 return k8scluster_id_2_uuic[cluster_type][cluster_id]
2149
2150 db_k8scluster = self.db.get_one("k8sclusters", {"_id": cluster_id}, fail_on_empty=False)
2151 if not db_k8scluster:
2152 raise LcmException("K8s cluster {} cannot be found".format(cluster_id))
2153 k8s_id = deep_get(db_k8scluster, ("_admin", cluster_type, "id"))
2154 if not k8s_id:
2155 raise LcmException("K8s cluster '{}' has not been initilized for '{}'".format(cluster_id, cluster_type))
2156 k8scluster_id_2_uuic[cluster_type][cluster_id] = k8s_id
2157 return k8s_id
2158
2159 logging_text += "Deploy kdus: "
2160 step = ""
2161 try:
2162 db_nsr_update = {"_admin.deployed.K8s": []}
2163 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2164
2165 index = 0
2166 updated_cluster_list = []
2167
2168 for vnfr_data in db_vnfrs.values():
2169 for kdur in get_iterable(vnfr_data, "kdur"):
2170 desc_params = self._format_additional_params(kdur.get("additionalParams"))
2171 vnfd_id = vnfr_data.get('vnfd-id')
2172 namespace = kdur.get("k8s-namespace")
2173 if kdur.get("helm-chart"):
2174 kdumodel = kdur["helm-chart"]
2175 k8sclustertype = "helm-chart"
2176 elif kdur.get("juju-bundle"):
2177 kdumodel = kdur["juju-bundle"]
2178 k8sclustertype = "juju-bundle"
2179 else:
2180 raise LcmException("kdu type for kdu='{}.{}' is neither helm-chart nor "
2181 "juju-bundle. Maybe an old NBI version is running".
2182 format(vnfr_data["member-vnf-index-ref"], kdur["kdu-name"]))
2183 # check if kdumodel is a file and exists
2184 try:
2185 storage = deep_get(db_vnfds.get(vnfd_id), ('_admin', 'storage'))
2186 if storage and storage.get('pkg-dir'): # may be not present if vnfd has not artifacts
2187 # path format: /vnfdid/pkkdir/helm-charts|juju-bundles/kdumodel
2188 filename = '{}/{}/{}s/{}'.format(storage["folder"], storage["pkg-dir"], k8sclustertype,
2189 kdumodel)
2190 if self.fs.file_exists(filename, mode='file') or self.fs.file_exists(filename, mode='dir'):
2191 kdumodel = self.fs.path + filename
2192 except (asyncio.TimeoutError, asyncio.CancelledError):
2193 raise
2194 except Exception: # it is not a file
2195 pass
2196
2197 k8s_cluster_id = kdur["k8s-cluster"]["id"]
2198 step = "Synchronize repos for k8s cluster '{}'".format(k8s_cluster_id)
2199 cluster_uuid = _get_cluster_id(k8s_cluster_id, k8sclustertype)
2200
2201 if k8sclustertype == "helm-chart" and cluster_uuid not in updated_cluster_list:
2202 del_repo_list, added_repo_dict = await asyncio.ensure_future(
2203 self.k8sclusterhelm.synchronize_repos(cluster_uuid=cluster_uuid))
2204 if del_repo_list or added_repo_dict:
2205 unset = {'_admin.helm_charts_added.' + item: None for item in del_repo_list}
2206 updated = {'_admin.helm_charts_added.' +
2207 item: name for item, name in added_repo_dict.items()}
2208 self.logger.debug(logging_text + "repos synchronized on k8s cluster '{}' to_delete: {}, "
2209 "to_add: {}".format(k8s_cluster_id, del_repo_list,
2210 added_repo_dict))
2211 self.db.set_one("k8sclusters", {"_id": k8s_cluster_id}, updated, unset=unset)
2212 updated_cluster_list.append(cluster_uuid)
2213
2214 step = "Instantiating KDU {}.{} in k8s cluster {}".format(vnfr_data["member-vnf-index-ref"],
2215 kdur["kdu-name"], k8s_cluster_id)
2216
2217 k8s_instace_info = {"kdu-instance": None,
2218 "k8scluster-uuid": cluster_uuid,
2219 "k8scluster-type": k8sclustertype,
2220 "member-vnf-index": vnfr_data["member-vnf-index-ref"],
2221 "kdu-name": kdur["kdu-name"],
2222 "kdu-model": kdumodel,
2223 "namespace": namespace}
2224 db_path = "_admin.deployed.K8s.{}".format(index)
2225 db_nsr_update[db_path] = k8s_instace_info
2226 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2227
2228 db_dict = {"collection": "nsrs",
2229 "filter": {"_id": nsr_id},
2230 "path": db_path}
2231
2232 task = asyncio.ensure_future(
2233 self.k8scluster_map[k8sclustertype].install(cluster_uuid=cluster_uuid, kdu_model=kdumodel,
2234 atomic=True, params=desc_params,
2235 db_dict=db_dict, timeout=600,
2236 kdu_name=kdur["kdu-name"], namespace=namespace))
2237
2238 task.add_done_callback(partial(self._write_db_callback, item="nsrs", _id=nsr_id,
2239 on_done=db_path + ".kdu-instance",
2240 on_exc=db_path + ".detailed-status"))
2241 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "instantiate_KDU-{}".format(index), task)
2242 task_instantiation_info[task] = "Deploying KDU {}".format(kdur["kdu-name"])
2243
2244 index += 1
2245
2246 except (LcmException, asyncio.CancelledError):
2247 raise
2248 except Exception as e:
2249 msg = "Exception {} while {}: {}".format(type(e).__name__, step, e)
2250 if isinstance(e, (N2VCException, DbException)):
2251 self.logger.error(logging_text + msg)
2252 else:
2253 self.logger.critical(logging_text + msg, exc_info=True)
2254 raise LcmException(msg)
2255 finally:
2256 if db_nsr_update:
2257 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2258
2259 def _deploy_n2vc(self, logging_text, db_nsr, db_vnfr, nslcmop_id, nsr_id, nsi_id, vnfd_id, vdu_id,
2260 kdu_name, member_vnf_index, vdu_index, vdu_name, deploy_params, descriptor_config,
2261 base_folder, task_instantiation_info, stage):
2262 # launch instantiate_N2VC in a asyncio task and register task object
2263 # Look where information of this charm is at database <nsrs>._admin.deployed.VCA
2264 # if not found, create one entry and update database
2265
2266 # fill db_nsr._admin.deployed.VCA.<index>
2267 vca_index = -1
2268 for vca_index, vca_deployed in enumerate(db_nsr["_admin"]["deployed"]["VCA"]):
2269 if not vca_deployed:
2270 continue
2271 if vca_deployed.get("member-vnf-index") == member_vnf_index and \
2272 vca_deployed.get("vdu_id") == vdu_id and \
2273 vca_deployed.get("kdu_name") == kdu_name and \
2274 vca_deployed.get("vdu_count_index", 0) == vdu_index:
2275 break
2276 else:
2277 # not found, create one.
2278 vca_deployed = {
2279 "member-vnf-index": member_vnf_index,
2280 "vdu_id": vdu_id,
2281 "kdu_name": kdu_name,
2282 "vdu_count_index": vdu_index,
2283 "operational-status": "init", # TODO revise
2284 "detailed-status": "", # TODO revise
2285 "step": "initial-deploy", # TODO revise
2286 "vnfd_id": vnfd_id,
2287 "vdu_name": vdu_name,
2288 }
2289 vca_index += 1
2290
2291 # create VCA and configurationStatus in db
2292 db_dict = {
2293 "_admin.deployed.VCA.{}".format(vca_index): vca_deployed,
2294 "configurationStatus.{}".format(vca_index): dict()
2295 }
2296 self.update_db_2("nsrs", nsr_id, db_dict)
2297
2298 db_nsr["_admin"]["deployed"]["VCA"].append(vca_deployed)
2299
2300 # Launch task
2301 task_n2vc = asyncio.ensure_future(
2302 self.instantiate_N2VC(
2303 logging_text=logging_text,
2304 vca_index=vca_index,
2305 nsi_id=nsi_id,
2306 db_nsr=db_nsr,
2307 db_vnfr=db_vnfr,
2308 vdu_id=vdu_id,
2309 kdu_name=kdu_name,
2310 vdu_index=vdu_index,
2311 deploy_params=deploy_params,
2312 config_descriptor=descriptor_config,
2313 base_folder=base_folder,
2314 nslcmop_id=nslcmop_id,
2315 stage=stage
2316 )
2317 )
2318 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "instantiate_N2VC-{}".format(vca_index), task_n2vc)
2319 task_instantiation_info[task_n2vc] = self.task_name_deploy_vca + " {}.{}".format(
2320 member_vnf_index or "", vdu_id or "")
2321
2322 # Check if this VNFD has a configured terminate action
2323 def _has_terminate_config_primitive(self, vnfd):
2324 vnf_config = vnfd.get("vnf-configuration")
2325 if vnf_config and vnf_config.get("terminate-config-primitive"):
2326 return True
2327 else:
2328 return False
2329
2330 @staticmethod
2331 def _get_terminate_config_primitive_seq_list(vnfd):
2332 """ Get a numerically sorted list of the sequences for this VNFD's terminate action """
2333 # No need to check for existing primitive twice, already done before
2334 vnf_config = vnfd.get("vnf-configuration")
2335 seq_list = vnf_config.get("terminate-config-primitive")
2336 # Get all 'seq' tags in seq_list, order sequences numerically, ascending.
2337 seq_list_sorted = sorted(seq_list, key=lambda x: int(x['seq']))
2338 return seq_list_sorted
2339
2340 @staticmethod
2341 def _create_nslcmop(nsr_id, operation, params):
2342 """
2343 Creates a ns-lcm-opp content to be stored at database.
2344 :param nsr_id: internal id of the instance
2345 :param operation: instantiate, terminate, scale, action, ...
2346 :param params: user parameters for the operation
2347 :return: dictionary following SOL005 format
2348 """
2349 # Raise exception if invalid arguments
2350 if not (nsr_id and operation and params):
2351 raise LcmException(
2352 "Parameters 'nsr_id', 'operation' and 'params' needed to create primitive not provided")
2353 now = time()
2354 _id = str(uuid4())
2355 nslcmop = {
2356 "id": _id,
2357 "_id": _id,
2358 # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2359 "operationState": "PROCESSING",
2360 "statusEnteredTime": now,
2361 "nsInstanceId": nsr_id,
2362 "lcmOperationType": operation,
2363 "startTime": now,
2364 "isAutomaticInvocation": False,
2365 "operationParams": params,
2366 "isCancelPending": False,
2367 "links": {
2368 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
2369 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
2370 }
2371 }
2372 return nslcmop
2373
2374 def _format_additional_params(self, params):
2375 params = params or {}
2376 for key, value in params.items():
2377 if str(value).startswith("!!yaml "):
2378 params[key] = yaml.safe_load(value[7:])
2379 return params
2380
2381 def _get_terminate_primitive_params(self, seq, vnf_index):
2382 primitive = seq.get('name')
2383 primitive_params = {}
2384 params = {
2385 "member_vnf_index": vnf_index,
2386 "primitive": primitive,
2387 "primitive_params": primitive_params,
2388 }
2389 desc_params = {}
2390 return self._map_primitive_params(seq, params, desc_params)
2391
2392 # sub-operations
2393
2394 def _retry_or_skip_suboperation(self, db_nslcmop, op_index):
2395 op = deep_get(db_nslcmop, ('_admin', 'operations'), [])[op_index]
2396 if op.get('operationState') == 'COMPLETED':
2397 # b. Skip sub-operation
2398 # _ns_execute_primitive() or RO.create_action() will NOT be executed
2399 return self.SUBOPERATION_STATUS_SKIP
2400 else:
2401 # c. retry executing sub-operation
2402 # The sub-operation exists, and operationState != 'COMPLETED'
2403 # Update operationState = 'PROCESSING' to indicate a retry.
2404 operationState = 'PROCESSING'
2405 detailed_status = 'In progress'
2406 self._update_suboperation_status(
2407 db_nslcmop, op_index, operationState, detailed_status)
2408 # Return the sub-operation index
2409 # _ns_execute_primitive() or RO.create_action() will be called from scale()
2410 # with arguments extracted from the sub-operation
2411 return op_index
2412
2413 # Find a sub-operation where all keys in a matching dictionary must match
2414 # Returns the index of the matching sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if no match
2415 def _find_suboperation(self, db_nslcmop, match):
2416 if db_nslcmop and match:
2417 op_list = db_nslcmop.get('_admin', {}).get('operations', [])
2418 for i, op in enumerate(op_list):
2419 if all(op.get(k) == match[k] for k in match):
2420 return i
2421 return self.SUBOPERATION_STATUS_NOT_FOUND
2422
2423 # Update status for a sub-operation given its index
2424 def _update_suboperation_status(self, db_nslcmop, op_index, operationState, detailed_status):
2425 # Update DB for HA tasks
2426 q_filter = {'_id': db_nslcmop['_id']}
2427 update_dict = {'_admin.operations.{}.operationState'.format(op_index): operationState,
2428 '_admin.operations.{}.detailed-status'.format(op_index): detailed_status}
2429 self.db.set_one("nslcmops",
2430 q_filter=q_filter,
2431 update_dict=update_dict,
2432 fail_on_empty=False)
2433
2434 # Add sub-operation, return the index of the added sub-operation
2435 # Optionally, set operationState, detailed-status, and operationType
2436 # Status and type are currently set for 'scale' sub-operations:
2437 # 'operationState' : 'PROCESSING' | 'COMPLETED' | 'FAILED'
2438 # 'detailed-status' : status message
2439 # 'operationType': may be any type, in the case of scaling: 'PRE-SCALE' | 'POST-SCALE'
2440 # Status and operation type are currently only used for 'scale', but NOT for 'terminate' sub-operations.
2441 def _add_suboperation(self, db_nslcmop, vnf_index, vdu_id, vdu_count_index, vdu_name, primitive,
2442 mapped_primitive_params, operationState=None, detailed_status=None, operationType=None,
2443 RO_nsr_id=None, RO_scaling_info=None):
2444 if not db_nslcmop:
2445 return self.SUBOPERATION_STATUS_NOT_FOUND
2446 # Get the "_admin.operations" list, if it exists
2447 db_nslcmop_admin = db_nslcmop.get('_admin', {})
2448 op_list = db_nslcmop_admin.get('operations')
2449 # Create or append to the "_admin.operations" list
2450 new_op = {'member_vnf_index': vnf_index,
2451 'vdu_id': vdu_id,
2452 'vdu_count_index': vdu_count_index,
2453 'primitive': primitive,
2454 'primitive_params': mapped_primitive_params}
2455 if operationState:
2456 new_op['operationState'] = operationState
2457 if detailed_status:
2458 new_op['detailed-status'] = detailed_status
2459 if operationType:
2460 new_op['lcmOperationType'] = operationType
2461 if RO_nsr_id:
2462 new_op['RO_nsr_id'] = RO_nsr_id
2463 if RO_scaling_info:
2464 new_op['RO_scaling_info'] = RO_scaling_info
2465 if not op_list:
2466 # No existing operations, create key 'operations' with current operation as first list element
2467 db_nslcmop_admin.update({'operations': [new_op]})
2468 op_list = db_nslcmop_admin.get('operations')
2469 else:
2470 # Existing operations, append operation to list
2471 op_list.append(new_op)
2472
2473 db_nslcmop_update = {'_admin.operations': op_list}
2474 self.update_db_2("nslcmops", db_nslcmop['_id'], db_nslcmop_update)
2475 op_index = len(op_list) - 1
2476 return op_index
2477
2478 # Helper methods for scale() sub-operations
2479
2480 # pre-scale/post-scale:
2481 # Check for 3 different cases:
2482 # a. New: First time execution, return SUBOPERATION_STATUS_NEW
2483 # b. Skip: Existing sub-operation exists, operationState == 'COMPLETED', return SUBOPERATION_STATUS_SKIP
2484 # c. retry: Existing sub-operation exists, operationState != 'COMPLETED', return op_index to re-execute
2485 def _check_or_add_scale_suboperation(self, db_nslcmop, vnf_index, vnf_config_primitive, primitive_params,
2486 operationType, RO_nsr_id=None, RO_scaling_info=None):
2487 # Find this sub-operation
2488 if RO_nsr_id and RO_scaling_info:
2489 operationType = 'SCALE-RO'
2490 match = {
2491 'member_vnf_index': vnf_index,
2492 'RO_nsr_id': RO_nsr_id,
2493 'RO_scaling_info': RO_scaling_info,
2494 }
2495 else:
2496 match = {
2497 'member_vnf_index': vnf_index,
2498 'primitive': vnf_config_primitive,
2499 'primitive_params': primitive_params,
2500 'lcmOperationType': operationType
2501 }
2502 op_index = self._find_suboperation(db_nslcmop, match)
2503 if op_index == self.SUBOPERATION_STATUS_NOT_FOUND:
2504 # a. New sub-operation
2505 # The sub-operation does not exist, add it.
2506 # _ns_execute_primitive() will be called from scale() as usual, with non-modified arguments
2507 # The following parameters are set to None for all kind of scaling:
2508 vdu_id = None
2509 vdu_count_index = None
2510 vdu_name = None
2511 if RO_nsr_id and RO_scaling_info:
2512 vnf_config_primitive = None
2513 primitive_params = None
2514 else:
2515 RO_nsr_id = None
2516 RO_scaling_info = None
2517 # Initial status for sub-operation
2518 operationState = 'PROCESSING'
2519 detailed_status = 'In progress'
2520 # Add sub-operation for pre/post-scaling (zero or more operations)
2521 self._add_suboperation(db_nslcmop,
2522 vnf_index,
2523 vdu_id,
2524 vdu_count_index,
2525 vdu_name,
2526 vnf_config_primitive,
2527 primitive_params,
2528 operationState,
2529 detailed_status,
2530 operationType,
2531 RO_nsr_id,
2532 RO_scaling_info)
2533 return self.SUBOPERATION_STATUS_NEW
2534 else:
2535 # Return either SUBOPERATION_STATUS_SKIP (operationState == 'COMPLETED'),
2536 # or op_index (operationState != 'COMPLETED')
2537 return self._retry_or_skip_suboperation(db_nslcmop, op_index)
2538
2539 # Function to return execution_environment id
2540
2541 def _get_ee_id(self, vnf_index, vdu_id, vca_deployed_list):
2542 # TODO vdu_index_count
2543 for vca in vca_deployed_list:
2544 if vca["member-vnf-index"] == vnf_index and vca["vdu_id"] == vdu_id:
2545 return vca["ee_id"]
2546
2547 async def destroy_N2VC(self, logging_text, db_nslcmop, vca_deployed, config_descriptor, vca_index, destroy_ee=True):
2548 """
2549 Execute the terminate primitives and destroy the execution environment (if destroy_ee=False
2550 :param logging_text:
2551 :param db_nslcmop:
2552 :param vca_deployed: Dictionary of deployment info at db_nsr._admin.depoloyed.VCA.<INDEX>
2553 :param config_descriptor: Configuration descriptor of the NSD, VNFD, VNFD.vdu or VNFD.kdu
2554 :param vca_index: index in the database _admin.deployed.VCA
2555 :param destroy_ee: False to do not destroy, because it will be destroyed all of then at once
2556 :return: None or exception
2557 """
2558 # execute terminate_primitives
2559 terminate_primitives = config_descriptor.get("terminate-config-primitive")
2560 vdu_id = vca_deployed.get("vdu_id")
2561 vdu_count_index = vca_deployed.get("vdu_count_index")
2562 vdu_name = vca_deployed.get("vdu_name")
2563 vnf_index = vca_deployed.get("member-vnf-index")
2564 if terminate_primitives and vca_deployed.get("needed_terminate"):
2565 # Get all 'seq' tags in seq_list, order sequences numerically, ascending.
2566 terminate_primitives = sorted(terminate_primitives, key=lambda x: int(x['seq']))
2567 for seq in terminate_primitives:
2568 # For each sequence in list, get primitive and call _ns_execute_primitive()
2569 step = "Calling terminate action for vnf_member_index={} primitive={}".format(
2570 vnf_index, seq.get("name"))
2571 self.logger.debug(logging_text + step)
2572 # Create the primitive for each sequence, i.e. "primitive": "touch"
2573 primitive = seq.get('name')
2574 mapped_primitive_params = self._get_terminate_primitive_params(seq, vnf_index)
2575 # The following 3 parameters are currently set to None for 'terminate':
2576 # vdu_id, vdu_count_index, vdu_name
2577
2578 # Add sub-operation
2579 self._add_suboperation(db_nslcmop,
2580 vnf_index,
2581 vdu_id,
2582 vdu_count_index,
2583 vdu_name,
2584 primitive,
2585 mapped_primitive_params)
2586 # Sub-operations: Call _ns_execute_primitive() instead of action()
2587 try:
2588 result, result_detail = await self._ns_execute_primitive(vca_deployed["ee_id"], primitive,
2589 mapped_primitive_params)
2590 except LcmException:
2591 # this happens when VCA is not deployed. In this case it is not needed to terminate
2592 continue
2593 result_ok = ['COMPLETED', 'PARTIALLY_COMPLETED']
2594 if result not in result_ok:
2595 raise LcmException("terminate_primitive {} for vnf_member_index={} fails with "
2596 "error {}".format(seq.get("name"), vnf_index, result_detail))
2597 # set that this VCA do not need terminated
2598 db_update_entry = "_admin.deployed.VCA.{}.needed_terminate".format(vca_index)
2599 self.update_db_2("nsrs", db_nslcmop["nsInstanceId"], {db_update_entry: False})
2600
2601 if destroy_ee:
2602 await self.n2vc.delete_execution_environment(vca_deployed["ee_id"])
2603
2604 async def _delete_all_N2VC(self, db_nsr: dict):
2605 self._write_all_config_status(db_nsr=db_nsr, status='TERMINATING')
2606 namespace = "." + db_nsr["_id"]
2607 try:
2608 await self.n2vc.delete_namespace(namespace=namespace, total_timeout=self.timeout_charm_delete)
2609 except N2VCNotFound: # already deleted. Skip
2610 pass
2611 self._write_all_config_status(db_nsr=db_nsr, status='DELETED')
2612
2613 async def _terminate_RO(self, logging_text, nsr_deployed, nsr_id, nslcmop_id, stage):
2614 """
2615 Terminates a deployment from RO
2616 :param logging_text:
2617 :param nsr_deployed: db_nsr._admin.deployed
2618 :param nsr_id:
2619 :param nslcmop_id:
2620 :param stage: list of string with the content to write on db_nslcmop.detailed-status.
2621 this method will update only the index 2, but it will write on database the concatenated content of the list
2622 :return:
2623 """
2624 db_nsr_update = {}
2625 failed_detail = []
2626 ro_nsr_id = ro_delete_action = None
2627 if nsr_deployed and nsr_deployed.get("RO"):
2628 ro_nsr_id = nsr_deployed["RO"].get("nsr_id")
2629 ro_delete_action = nsr_deployed["RO"].get("nsr_delete_action_id")
2630 try:
2631 if ro_nsr_id:
2632 stage[2] = "Deleting ns from VIM."
2633 db_nsr_update["detailed-status"] = " ".join(stage)
2634 self._write_op_status(nslcmop_id, stage)
2635 self.logger.debug(logging_text + stage[2])
2636 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2637 self._write_op_status(nslcmop_id, stage)
2638 desc = await self.RO.delete("ns", ro_nsr_id)
2639 ro_delete_action = desc["action_id"]
2640 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = ro_delete_action
2641 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
2642 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
2643 if ro_delete_action:
2644 # wait until NS is deleted from VIM
2645 stage[2] = "Waiting ns deleted from VIM."
2646 detailed_status_old = None
2647 self.logger.debug(logging_text + stage[2] + " RO_id={} ro_delete_action={}".format(ro_nsr_id,
2648 ro_delete_action))
2649 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2650 self._write_op_status(nslcmop_id, stage)
2651
2652 delete_timeout = 20 * 60 # 20 minutes
2653 while delete_timeout > 0:
2654 desc = await self.RO.show(
2655 "ns",
2656 item_id_name=ro_nsr_id,
2657 extra_item="action",
2658 extra_item_id=ro_delete_action)
2659
2660 # deploymentStatus
2661 self._on_update_ro_db(nsrs_id=nsr_id, ro_descriptor=desc)
2662
2663 ns_status, ns_status_info = self.RO.check_action_status(desc)
2664 if ns_status == "ERROR":
2665 raise ROclient.ROClientException(ns_status_info)
2666 elif ns_status == "BUILD":
2667 stage[2] = "Deleting from VIM {}".format(ns_status_info)
2668 elif ns_status == "ACTIVE":
2669 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
2670 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
2671 break
2672 else:
2673 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
2674 if stage[2] != detailed_status_old:
2675 detailed_status_old = stage[2]
2676 db_nsr_update["detailed-status"] = " ".join(stage)
2677 self._write_op_status(nslcmop_id, stage)
2678 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2679 await asyncio.sleep(5, loop=self.loop)
2680 delete_timeout -= 5
2681 else: # delete_timeout <= 0:
2682 raise ROclient.ROClientException("Timeout waiting ns deleted from VIM")
2683
2684 except Exception as e:
2685 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2686 if isinstance(e, ROclient.ROClientException) and e.http_code == 404: # not found
2687 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
2688 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
2689 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
2690 self.logger.debug(logging_text + "RO_ns_id={} already deleted".format(ro_nsr_id))
2691 elif isinstance(e, ROclient.ROClientException) and e.http_code == 409: # conflict
2692 failed_detail.append("delete conflict: {}".format(e))
2693 self.logger.debug(logging_text + "RO_ns_id={} delete conflict: {}".format(ro_nsr_id, e))
2694 else:
2695 failed_detail.append("delete error: {}".format(e))
2696 self.logger.error(logging_text + "RO_ns_id={} delete error: {}".format(ro_nsr_id, e))
2697
2698 # Delete nsd
2699 if not failed_detail and deep_get(nsr_deployed, ("RO", "nsd_id")):
2700 ro_nsd_id = nsr_deployed["RO"]["nsd_id"]
2701 try:
2702 stage[2] = "Deleting nsd from RO."
2703 db_nsr_update["detailed-status"] = " ".join(stage)
2704 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2705 self._write_op_status(nslcmop_id, stage)
2706 await self.RO.delete("nsd", ro_nsd_id)
2707 self.logger.debug(logging_text + "ro_nsd_id={} deleted".format(ro_nsd_id))
2708 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
2709 except Exception as e:
2710 if isinstance(e, ROclient.ROClientException) and e.http_code == 404: # not found
2711 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
2712 self.logger.debug(logging_text + "ro_nsd_id={} already deleted".format(ro_nsd_id))
2713 elif isinstance(e, ROclient.ROClientException) and e.http_code == 409: # conflict
2714 failed_detail.append("ro_nsd_id={} delete conflict: {}".format(ro_nsd_id, e))
2715 self.logger.debug(logging_text + failed_detail[-1])
2716 else:
2717 failed_detail.append("ro_nsd_id={} delete error: {}".format(ro_nsd_id, e))
2718 self.logger.error(logging_text + failed_detail[-1])
2719
2720 if not failed_detail and deep_get(nsr_deployed, ("RO", "vnfd")):
2721 for index, vnf_deployed in enumerate(nsr_deployed["RO"]["vnfd"]):
2722 if not vnf_deployed or not vnf_deployed["id"]:
2723 continue
2724 try:
2725 ro_vnfd_id = vnf_deployed["id"]
2726 stage[2] = "Deleting member_vnf_index={} ro_vnfd_id={} from RO.".format(
2727 vnf_deployed["member-vnf-index"], ro_vnfd_id)
2728 db_nsr_update["detailed-status"] = " ".join(stage)
2729 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2730 self._write_op_status(nslcmop_id, stage)
2731 await self.RO.delete("vnfd", ro_vnfd_id)
2732 self.logger.debug(logging_text + "ro_vnfd_id={} deleted".format(ro_vnfd_id))
2733 db_nsr_update["_admin.deployed.RO.vnfd.{}.id".format(index)] = None
2734 except Exception as e:
2735 if isinstance(e, ROclient.ROClientException) and e.http_code == 404: # not found
2736 db_nsr_update["_admin.deployed.RO.vnfd.{}.id".format(index)] = None
2737 self.logger.debug(logging_text + "ro_vnfd_id={} already deleted ".format(ro_vnfd_id))
2738 elif isinstance(e, ROclient.ROClientException) and e.http_code == 409: # conflict
2739 failed_detail.append("ro_vnfd_id={} delete conflict: {}".format(ro_vnfd_id, e))
2740 self.logger.debug(logging_text + failed_detail[-1])
2741 else:
2742 failed_detail.append("ro_vnfd_id={} delete error: {}".format(ro_vnfd_id, e))
2743 self.logger.error(logging_text + failed_detail[-1])
2744
2745 if failed_detail:
2746 stage[2] = "Error deleting from VIM"
2747 else:
2748 stage[2] = "Deleted from VIM"
2749 db_nsr_update["detailed-status"] = " ".join(stage)
2750 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2751 self._write_op_status(nslcmop_id, stage)
2752
2753 if failed_detail:
2754 raise LcmException("; ".join(failed_detail))
2755
2756 async def terminate(self, nsr_id, nslcmop_id):
2757 # Try to lock HA task here
2758 task_is_locked_by_me = self.lcm_tasks.lock_HA('ns', 'nslcmops', nslcmop_id)
2759 if not task_is_locked_by_me:
2760 return
2761
2762 logging_text = "Task ns={} terminate={} ".format(nsr_id, nslcmop_id)
2763 self.logger.debug(logging_text + "Enter")
2764 timeout_ns_terminate = self.timeout_ns_terminate
2765 db_nsr = None
2766 db_nslcmop = None
2767 operation_params = None
2768 exc = None
2769 error_list = [] # annotates all failed error messages
2770 db_nslcmop_update = {}
2771 autoremove = False # autoremove after terminated
2772 tasks_dict_info = {}
2773 db_nsr_update = {}
2774 stage = ["Stage 1/3: Preparing task.", "Waiting for previous operations to terminate.", ""]
2775 # ^ contains [stage, step, VIM-status]
2776 try:
2777 # wait for any previous tasks in process
2778 await self.lcm_tasks.waitfor_related_HA("ns", 'nslcmops', nslcmop_id)
2779
2780 stage[1] = "Getting nslcmop={} from db.".format(nslcmop_id)
2781 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
2782 operation_params = db_nslcmop.get("operationParams") or {}
2783 if operation_params.get("timeout_ns_terminate"):
2784 timeout_ns_terminate = operation_params["timeout_ns_terminate"]
2785 stage[1] = "Getting nsr={} from db.".format(nsr_id)
2786 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2787
2788 db_nsr_update["operational-status"] = "terminating"
2789 db_nsr_update["config-status"] = "terminating"
2790 self._write_ns_status(
2791 nsr_id=nsr_id,
2792 ns_state="TERMINATING",
2793 current_operation="TERMINATING",
2794 current_operation_id=nslcmop_id,
2795 other_update=db_nsr_update
2796 )
2797 self._write_op_status(
2798 op_id=nslcmop_id,
2799 queuePosition=0,
2800 stage=stage
2801 )
2802 nsr_deployed = deepcopy(db_nsr["_admin"].get("deployed")) or {}
2803 if db_nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
2804 return
2805
2806 stage[1] = "Getting vnf descriptors from db."
2807 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
2808 db_vnfds_from_id = {}
2809 db_vnfds_from_member_index = {}
2810 # Loop over VNFRs
2811 for vnfr in db_vnfrs_list:
2812 vnfd_id = vnfr["vnfd-id"]
2813 if vnfd_id not in db_vnfds_from_id:
2814 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
2815 db_vnfds_from_id[vnfd_id] = vnfd
2816 db_vnfds_from_member_index[vnfr["member-vnf-index-ref"]] = db_vnfds_from_id[vnfd_id]
2817
2818 # Destroy individual execution environments when there are terminating primitives.
2819 # Rest of EE will be deleted at once
2820 if not operation_params.get("skip_terminate_primitives"):
2821 stage[0] = "Stage 2/3 execute terminating primitives."
2822 stage[1] = "Looking execution environment that needs terminate."
2823 self.logger.debug(logging_text + stage[1])
2824 for vca_index, vca in enumerate(get_iterable(nsr_deployed, "VCA")):
2825 config_descriptor = None
2826 if not vca or not vca.get("ee_id") or not vca.get("needed_terminate"):
2827 continue
2828 if not vca.get("member-vnf-index"):
2829 # ns
2830 config_descriptor = db_nsr.get("ns-configuration")
2831 elif vca.get("vdu_id"):
2832 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
2833 vdud = next((vdu for vdu in db_vnfd.get("vdu", ()) if vdu["id"] == vca.get("vdu_id")), None)
2834 if vdud:
2835 config_descriptor = vdud.get("vdu-configuration")
2836 elif vca.get("kdu_name"):
2837 db_vnfd = db_vnfds_from_member_index[vca["member-vnf-index"]]
2838 kdud = next((kdu for kdu in db_vnfd.get("kdu", ()) if kdu["name"] == vca.get("kdu_name")), None)
2839 if kdud:
2840 config_descriptor = kdud.get("kdu-configuration")
2841 else:
2842 config_descriptor = db_vnfds_from_member_index[vca["member-vnf-index"]].get("vnf-configuration")
2843 task = asyncio.ensure_future(self.destroy_N2VC(logging_text, db_nslcmop, vca, config_descriptor,
2844 vca_index, False))
2845 tasks_dict_info[task] = "Terminating VCA {}".format(vca.get("ee_id"))
2846
2847 # wait for pending tasks of terminate primitives
2848 if tasks_dict_info:
2849 self.logger.debug(logging_text + 'Waiting for terminate primitive pending tasks...')
2850 error_list = await self._wait_for_tasks(logging_text, tasks_dict_info,
2851 min(self.timeout_charm_delete, timeout_ns_terminate),
2852 stage, nslcmop_id)
2853 if error_list:
2854 return # raise LcmException("; ".join(error_list))
2855 tasks_dict_info.clear()
2856
2857 # remove All execution environments at once
2858 stage[0] = "Stage 3/3 delete all."
2859
2860 if nsr_deployed.get("VCA"):
2861 stage[1] = "Deleting all execution environments."
2862 self.logger.debug(logging_text + stage[1])
2863 task_delete_ee = asyncio.ensure_future(asyncio.wait_for(self._delete_all_N2VC(db_nsr=db_nsr),
2864 timeout=self.timeout_charm_delete))
2865 # task_delete_ee = asyncio.ensure_future(self.n2vc.delete_namespace(namespace="." + nsr_id))
2866 tasks_dict_info[task_delete_ee] = "Terminating all VCA"
2867
2868 # Delete from k8scluster
2869 stage[1] = "Deleting KDUs."
2870 self.logger.debug(logging_text + stage[1])
2871 # print(nsr_deployed)
2872 for kdu in get_iterable(nsr_deployed, "K8s"):
2873 if not kdu or not kdu.get("kdu-instance"):
2874 continue
2875 kdu_instance = kdu.get("kdu-instance")
2876 if kdu.get("k8scluster-type") in self.k8scluster_map:
2877 task_delete_kdu_instance = asyncio.ensure_future(
2878 self.k8scluster_map[kdu["k8scluster-type"]].uninstall(
2879 cluster_uuid=kdu.get("k8scluster-uuid"),
2880 kdu_instance=kdu_instance))
2881 else:
2882 self.logger.error(logging_text + "Unknown k8s deployment type {}".
2883 format(kdu.get("k8scluster-type")))
2884 continue
2885 tasks_dict_info[task_delete_kdu_instance] = "Terminating KDU '{}'".format(kdu.get("kdu-name"))
2886
2887 # remove from RO
2888 stage[1] = "Deleting ns from VIM."
2889 task_delete_ro = asyncio.ensure_future(
2890 self._terminate_RO(logging_text, nsr_deployed, nsr_id, nslcmop_id, stage))
2891 tasks_dict_info[task_delete_ro] = "Removing deployment from VIM"
2892
2893 # rest of staff will be done at finally
2894
2895 except (ROclient.ROClientException, DbException, LcmException, N2VCException) as e:
2896 self.logger.error(logging_text + "Exit Exception {}".format(e))
2897 exc = e
2898 except asyncio.CancelledError:
2899 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(stage[1]))
2900 exc = "Operation was cancelled"
2901 except Exception as e:
2902 exc = traceback.format_exc()
2903 self.logger.critical(logging_text + "Exit Exception while '{}': {}".format(stage[1], e), exc_info=True)
2904 finally:
2905 if exc:
2906 error_list.append(str(exc))
2907 try:
2908 # wait for pending tasks
2909 if tasks_dict_info:
2910 stage[1] = "Waiting for terminate pending tasks."
2911 self.logger.debug(logging_text + stage[1])
2912 error_list += await self._wait_for_tasks(logging_text, tasks_dict_info, timeout_ns_terminate,
2913 stage, nslcmop_id)
2914 stage[1] = stage[2] = ""
2915 except asyncio.CancelledError:
2916 error_list.append("Cancelled")
2917 # TODO cancell all tasks
2918 except Exception as exc:
2919 error_list.append(str(exc))
2920 # update status at database
2921 if error_list:
2922 error_detail = "; ".join(error_list)
2923 # self.logger.error(logging_text + error_detail)
2924 error_description_nslcmop = 'Stage: {}. Detail: {}'.format(stage[0], error_detail)
2925 error_description_nsr = 'Operation: TERMINATING.{}, Stage {}.'.format(nslcmop_id, stage[0])
2926
2927 db_nsr_update["operational-status"] = "failed"
2928 db_nsr_update["detailed-status"] = error_description_nsr + " Detail: " + error_detail
2929 db_nslcmop_update["detailed-status"] = error_detail
2930 nslcmop_operation_state = "FAILED"
2931 ns_state = "BROKEN"
2932 else:
2933 error_detail = None
2934 error_description_nsr = error_description_nslcmop = None
2935 ns_state = "NOT_INSTANTIATED"
2936 db_nsr_update["operational-status"] = "terminated"
2937 db_nsr_update["detailed-status"] = "Done"
2938 db_nsr_update["_admin.nsState"] = "NOT_INSTANTIATED"
2939 db_nslcmop_update["detailed-status"] = "Done"
2940 nslcmop_operation_state = "COMPLETED"
2941
2942 if db_nsr:
2943 self._write_ns_status(
2944 nsr_id=nsr_id,
2945 ns_state=ns_state,
2946 current_operation="IDLE",
2947 current_operation_id=None,
2948 error_description=error_description_nsr,
2949 error_detail=error_detail,
2950 other_update=db_nsr_update
2951 )
2952 self._write_op_status(
2953 op_id=nslcmop_id,
2954 stage="",
2955 error_message=error_description_nslcmop,
2956 operation_state=nslcmop_operation_state,
2957 other_update=db_nslcmop_update,
2958 )
2959 if operation_params:
2960 autoremove = operation_params.get("autoremove", False)
2961 if nslcmop_operation_state:
2962 try:
2963 await self.msg.aiowrite("ns", "terminated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
2964 "operationState": nslcmop_operation_state,
2965 "autoremove": autoremove},
2966 loop=self.loop)
2967 except Exception as e:
2968 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
2969
2970 self.logger.debug(logging_text + "Exit")
2971 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_terminate")
2972
2973 async def _wait_for_tasks(self, logging_text, created_tasks_info, timeout, stage, nslcmop_id, nsr_id=None):
2974 time_start = time()
2975 error_detail_list = []
2976 error_list = []
2977 pending_tasks = list(created_tasks_info.keys())
2978 num_tasks = len(pending_tasks)
2979 num_done = 0
2980 stage[1] = "{}/{}.".format(num_done, num_tasks)
2981 self._write_op_status(nslcmop_id, stage)
2982 while pending_tasks:
2983 new_error = None
2984 _timeout = timeout + time_start - time()
2985 done, pending_tasks = await asyncio.wait(pending_tasks, timeout=_timeout,
2986 return_when=asyncio.FIRST_COMPLETED)
2987 num_done += len(done)
2988 if not done: # Timeout
2989 for task in pending_tasks:
2990 new_error = created_tasks_info[task] + ": Timeout"
2991 error_detail_list.append(new_error)
2992 error_list.append(new_error)
2993 break
2994 for task in done:
2995 if task.cancelled():
2996 exc = "Cancelled"
2997 else:
2998 exc = task.exception()
2999 if exc:
3000 if isinstance(exc, asyncio.TimeoutError):
3001 exc = "Timeout"
3002 new_error = created_tasks_info[task] + ": {}".format(exc)
3003 error_list.append(created_tasks_info[task])
3004 error_detail_list.append(new_error)
3005 if isinstance(exc, (str, DbException, N2VCException, ROclient.ROClientException, LcmException,
3006 K8sException)):
3007 self.logger.error(logging_text + new_error)
3008 else:
3009 exc_traceback = "".join(traceback.format_exception(None, exc, exc.__traceback__))
3010 self.logger.error(logging_text + created_tasks_info[task] + exc_traceback)
3011 else:
3012 self.logger.debug(logging_text + created_tasks_info[task] + ": Done")
3013 stage[1] = "{}/{}.".format(num_done, num_tasks)
3014 if new_error:
3015 stage[1] += " Errors: " + ". ".join(error_detail_list) + "."
3016 if nsr_id: # update also nsr
3017 self.update_db_2("nsrs", nsr_id, {"errorDescription": "Error at: " + ", ".join(error_list),
3018 "errorDetail": ". ".join(error_detail_list)})
3019 self._write_op_status(nslcmop_id, stage)
3020 return error_detail_list
3021
3022 @staticmethod
3023 def _map_primitive_params(primitive_desc, params, instantiation_params):
3024 """
3025 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
3026 The default-value is used. If it is between < > it look for a value at instantiation_params
3027 :param primitive_desc: portion of VNFD/NSD that describes primitive
3028 :param params: Params provided by user
3029 :param instantiation_params: Instantiation params provided by user
3030 :return: a dictionary with the calculated params
3031 """
3032 calculated_params = {}
3033 for parameter in primitive_desc.get("parameter", ()):
3034 param_name = parameter["name"]
3035 if param_name in params:
3036 calculated_params[param_name] = params[param_name]
3037 elif "default-value" in parameter or "value" in parameter:
3038 if "value" in parameter:
3039 calculated_params[param_name] = parameter["value"]
3040 else:
3041 calculated_params[param_name] = parameter["default-value"]
3042 if isinstance(calculated_params[param_name], str) and calculated_params[param_name].startswith("<") \
3043 and calculated_params[param_name].endswith(">"):
3044 if calculated_params[param_name][1:-1] in instantiation_params:
3045 calculated_params[param_name] = instantiation_params[calculated_params[param_name][1:-1]]
3046 else:
3047 raise LcmException("Parameter {} needed to execute primitive {} not provided".
3048 format(calculated_params[param_name], primitive_desc["name"]))
3049 else:
3050 raise LcmException("Parameter {} needed to execute primitive {} not provided".
3051 format(param_name, primitive_desc["name"]))
3052
3053 if isinstance(calculated_params[param_name], (dict, list, tuple)):
3054 calculated_params[param_name] = yaml.safe_dump(calculated_params[param_name], default_flow_style=True,
3055 width=256)
3056 elif isinstance(calculated_params[param_name], str) and calculated_params[param_name].startswith("!!yaml "):
3057 calculated_params[param_name] = calculated_params[param_name][7:]
3058
3059 # add always ns_config_info if primitive name is config
3060 if primitive_desc["name"] == "config":
3061 if "ns_config_info" in instantiation_params:
3062 calculated_params["ns_config_info"] = instantiation_params["ns_config_info"]
3063 return calculated_params
3064
3065 def _look_for_deployed_vca(self, deployed_vca, member_vnf_index, vdu_id, vdu_count_index, kdu_name=None):
3066 # find vca_deployed record for this action. Raise LcmException if not found or there is not any id.
3067 for vca in deployed_vca:
3068 if not vca:
3069 continue
3070 if member_vnf_index != vca["member-vnf-index"] or vdu_id != vca["vdu_id"]:
3071 continue
3072 if vdu_count_index is not None and vdu_count_index != vca["vdu_count_index"]:
3073 continue
3074 if kdu_name and kdu_name != vca["kdu_name"]:
3075 continue
3076 break
3077 else:
3078 # vca_deployed not found
3079 raise LcmException("charm for member_vnf_index={} vdu_id={} kdu_name={} vdu_count_index={} is not "
3080 "deployed".format(member_vnf_index, vdu_id, kdu_name, vdu_count_index))
3081
3082 # get ee_id
3083 ee_id = vca.get("ee_id")
3084 if not ee_id:
3085 raise LcmException("charm for member_vnf_index={} vdu_id={} kdu_name={} vdu_count_index={} has not "
3086 "execution environment"
3087 .format(member_vnf_index, vdu_id, kdu_name, vdu_count_index))
3088 return ee_id
3089
3090 async def _ns_execute_primitive(self, ee_id, primitive, primitive_params, retries=0,
3091 retries_interval=30, timeout=None) -> (str, str):
3092 try:
3093 if primitive == "config":
3094 primitive_params = {"params": primitive_params}
3095
3096 while retries >= 0:
3097 try:
3098 output = await asyncio.wait_for(
3099 self.n2vc.exec_primitive(
3100 ee_id=ee_id,
3101 primitive_name=primitive,
3102 params_dict=primitive_params,
3103 progress_timeout=self.timeout_progress_primitive,
3104 total_timeout=self.timeout_primitive),
3105 timeout=timeout or self.timeout_primitive)
3106 # execution was OK
3107 break
3108 except asyncio.CancelledError:
3109 raise
3110 except Exception as e: # asyncio.TimeoutError
3111 if isinstance(e, asyncio.TimeoutError):
3112 e = "Timeout"
3113 retries -= 1
3114 if retries >= 0:
3115 self.logger.debug('Error executing action {} on {} -> {}'.format(primitive, ee_id, e))
3116 # wait and retry
3117 await asyncio.sleep(retries_interval, loop=self.loop)
3118 else:
3119 return 'FAILED', str(e)
3120
3121 return 'COMPLETED', output
3122
3123 except (LcmException, asyncio.CancelledError):
3124 raise
3125 except Exception as e:
3126 return 'FAIL', 'Error executing action {}: {}'.format(primitive, e)
3127
3128 async def action(self, nsr_id, nslcmop_id):
3129
3130 # Try to lock HA task here
3131 task_is_locked_by_me = self.lcm_tasks.lock_HA('ns', 'nslcmops', nslcmop_id)
3132 if not task_is_locked_by_me:
3133 return
3134
3135 logging_text = "Task ns={} action={} ".format(nsr_id, nslcmop_id)
3136 self.logger.debug(logging_text + "Enter")
3137 # get all needed from database
3138 db_nsr = None
3139 db_nslcmop = None
3140 db_nsr_update = {}
3141 db_nslcmop_update = {}
3142 nslcmop_operation_state = None
3143 error_description_nslcmop = None
3144 exc = None
3145 try:
3146 # wait for any previous tasks in process
3147 step = "Waiting for previous operations to terminate"
3148 await self.lcm_tasks.waitfor_related_HA('ns', 'nslcmops', nslcmop_id)
3149
3150 self._write_ns_status(
3151 nsr_id=nsr_id,
3152 ns_state=None,
3153 current_operation="RUNNING ACTION",
3154 current_operation_id=nslcmop_id
3155 )
3156
3157 step = "Getting information from database"
3158 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
3159 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
3160
3161 nsr_deployed = db_nsr["_admin"].get("deployed")
3162 vnf_index = db_nslcmop["operationParams"].get("member_vnf_index")
3163 vdu_id = db_nslcmop["operationParams"].get("vdu_id")
3164 kdu_name = db_nslcmop["operationParams"].get("kdu_name")
3165 vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
3166 primitive = db_nslcmop["operationParams"]["primitive"]
3167 primitive_params = db_nslcmop["operationParams"]["primitive_params"]
3168 timeout_ns_action = db_nslcmop["operationParams"].get("timeout_ns_action", self.timeout_primitive)
3169
3170 if vnf_index:
3171 step = "Getting vnfr from database"
3172 db_vnfr = self.db.get_one("vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id})
3173 step = "Getting vnfd from database"
3174 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
3175 else:
3176 step = "Getting nsd from database"
3177 db_nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
3178
3179 # for backward compatibility
3180 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
3181 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
3182 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
3183 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3184
3185 # look for primitive
3186 config_primitive_desc = None
3187 if vdu_id:
3188 for vdu in get_iterable(db_vnfd, "vdu"):
3189 if vdu_id == vdu["id"]:
3190 for config_primitive in deep_get(vdu, ("vdu-configuration", "config-primitive"), ()):
3191 if config_primitive["name"] == primitive:
3192 config_primitive_desc = config_primitive
3193 break
3194 break
3195 elif kdu_name:
3196 for kdu in get_iterable(db_vnfd, "kdu"):
3197 if kdu_name == kdu["name"]:
3198 for config_primitive in deep_get(kdu, ("kdu-configuration", "config-primitive"), ()):
3199 if config_primitive["name"] == primitive:
3200 config_primitive_desc = config_primitive
3201 break
3202 break
3203 elif vnf_index:
3204 for config_primitive in deep_get(db_vnfd, ("vnf-configuration", "config-primitive"), ()):
3205 if config_primitive["name"] == primitive:
3206 config_primitive_desc = config_primitive
3207 break
3208 else:
3209 for config_primitive in deep_get(db_nsd, ("ns-configuration", "config-primitive"), ()):
3210 if config_primitive["name"] == primitive:
3211 config_primitive_desc = config_primitive
3212 break
3213
3214 if not config_primitive_desc and not (kdu_name and primitive in ("upgrade", "rollback", "status")):
3215 raise LcmException("Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".
3216 format(primitive))
3217
3218 if vnf_index:
3219 if vdu_id:
3220 vdur = next((x for x in db_vnfr["vdur"] if x["vdu-id-ref"] == vdu_id), None)
3221 desc_params = self._format_additional_params(vdur.get("additionalParams"))
3222 elif kdu_name:
3223 kdur = next((x for x in db_vnfr["kdur"] if x["kdu-name"] == kdu_name), None)
3224 desc_params = self._format_additional_params(kdur.get("additionalParams"))
3225 else:
3226 desc_params = self._format_additional_params(db_vnfr.get("additionalParamsForVnf"))
3227 else:
3228 desc_params = self._format_additional_params(db_nsr.get("additionalParamsForNs"))
3229
3230 if kdu_name:
3231 kdu_action = True if not deep_get(kdu, ("kdu-configuration", "juju")) else False
3232
3233 # TODO check if ns is in a proper status
3234 if kdu_name and (primitive in ("upgrade", "rollback", "status") or kdu_action):
3235 # kdur and desc_params already set from before
3236 if primitive_params:
3237 desc_params.update(primitive_params)
3238 # TODO Check if we will need something at vnf level
3239 for index, kdu in enumerate(get_iterable(nsr_deployed, "K8s")):
3240 if kdu_name == kdu["kdu-name"] and kdu["member-vnf-index"] == vnf_index:
3241 break
3242 else:
3243 raise LcmException("KDU '{}' for vnf '{}' not deployed".format(kdu_name, vnf_index))
3244
3245 if kdu.get("k8scluster-type") not in self.k8scluster_map:
3246 msg = "unknown k8scluster-type '{}'".format(kdu.get("k8scluster-type"))
3247 raise LcmException(msg)
3248
3249 db_dict = {"collection": "nsrs",
3250 "filter": {"_id": nsr_id},
3251 "path": "_admin.deployed.K8s.{}".format(index)}
3252 self.logger.debug(logging_text + "Exec k8s {} on {}.{}".format(primitive, vnf_index, kdu_name))
3253 step = "Executing kdu {}".format(primitive)
3254 if primitive == "upgrade":
3255 if desc_params.get("kdu_model"):
3256 kdu_model = desc_params.get("kdu_model")
3257 del desc_params["kdu_model"]
3258 else:
3259 kdu_model = kdu.get("kdu-model")
3260 parts = kdu_model.split(sep=":")
3261 if len(parts) == 2:
3262 kdu_model = parts[0]
3263
3264 detailed_status = await asyncio.wait_for(
3265 self.k8scluster_map[kdu["k8scluster-type"]].upgrade(
3266 cluster_uuid=kdu.get("k8scluster-uuid"),
3267 kdu_instance=kdu.get("kdu-instance"),
3268 atomic=True, kdu_model=kdu_model,
3269 params=desc_params, db_dict=db_dict,
3270 timeout=timeout_ns_action),
3271 timeout=timeout_ns_action + 10)
3272 self.logger.debug(logging_text + " Upgrade of kdu {} done".format(detailed_status))
3273 elif primitive == "rollback":
3274 detailed_status = await asyncio.wait_for(
3275 self.k8scluster_map[kdu["k8scluster-type"]].rollback(
3276 cluster_uuid=kdu.get("k8scluster-uuid"),
3277 kdu_instance=kdu.get("kdu-instance"),
3278 db_dict=db_dict),
3279 timeout=timeout_ns_action)
3280 elif primitive == "status":
3281 detailed_status = await asyncio.wait_for(
3282 self.k8scluster_map[kdu["k8scluster-type"]].status_kdu(
3283 cluster_uuid=kdu.get("k8scluster-uuid"),
3284 kdu_instance=kdu.get("kdu-instance")),
3285 timeout=timeout_ns_action)
3286 else:
3287 kdu_instance = kdu.get("kdu-instance") or "{}-{}".format(kdu["kdu-name"], nsr_id)
3288 params = self._map_primitive_params(config_primitive_desc, primitive_params, desc_params)
3289
3290 detailed_status = await asyncio.wait_for(
3291 self.k8scluster_map[kdu["k8scluster-type"]].exec_primitive(
3292 cluster_uuid=kdu.get("k8scluster-uuid"),
3293 kdu_instance=kdu_instance,
3294 primitive_name=primitive,
3295 params=params, db_dict=db_dict,
3296 timeout=timeout_ns_action),
3297 timeout=timeout_ns_action)
3298
3299 if detailed_status:
3300 nslcmop_operation_state = 'COMPLETED'
3301 else:
3302 detailed_status = ''
3303 nslcmop_operation_state = 'FAILED'
3304 else:
3305 nslcmop_operation_state, detailed_status = await self._ns_execute_primitive(
3306 self._look_for_deployed_vca(nsr_deployed["VCA"],
3307 member_vnf_index=vnf_index,
3308 vdu_id=vdu_id,
3309 vdu_count_index=vdu_count_index),
3310 primitive=primitive,
3311 primitive_params=self._map_primitive_params(config_primitive_desc, primitive_params, desc_params),
3312 timeout=timeout_ns_action)
3313
3314 db_nslcmop_update["detailed-status"] = detailed_status
3315 error_description_nslcmop = detailed_status if nslcmop_operation_state == "FAILED" else ""
3316 self.logger.debug(logging_text + " task Done with result {} {}".format(nslcmop_operation_state,
3317 detailed_status))
3318 return # database update is called inside finally
3319
3320 except (DbException, LcmException, N2VCException, K8sException) as e:
3321 self.logger.error(logging_text + "Exit Exception {}".format(e))
3322 exc = e
3323 except asyncio.CancelledError:
3324 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
3325 exc = "Operation was cancelled"
3326 except asyncio.TimeoutError:
3327 self.logger.error(logging_text + "Timeout while '{}'".format(step))
3328 exc = "Timeout"
3329 except Exception as e:
3330 exc = traceback.format_exc()
3331 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
3332 finally:
3333 if exc:
3334 db_nslcmop_update["detailed-status"] = detailed_status = error_description_nslcmop = \
3335 "FAILED {}: {}".format(step, exc)
3336 nslcmop_operation_state = "FAILED"
3337 if db_nsr:
3338 self._write_ns_status(
3339 nsr_id=nsr_id,
3340 ns_state=db_nsr["nsState"], # TODO check if degraded. For the moment use previous status
3341 current_operation="IDLE",
3342 current_operation_id=None,
3343 # error_description=error_description_nsr,
3344 # error_detail=error_detail,
3345 other_update=db_nsr_update
3346 )
3347
3348 self._write_op_status(
3349 op_id=nslcmop_id,
3350 stage="",
3351 error_message=error_description_nslcmop,
3352 operation_state=nslcmop_operation_state,
3353 other_update=db_nslcmop_update,
3354 )
3355
3356 if nslcmop_operation_state:
3357 try:
3358 await self.msg.aiowrite("ns", "actioned", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
3359 "operationState": nslcmop_operation_state},
3360 loop=self.loop)
3361 except Exception as e:
3362 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
3363 self.logger.debug(logging_text + "Exit")
3364 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_action")
3365 return nslcmop_operation_state, detailed_status
3366
3367 async def scale(self, nsr_id, nslcmop_id):
3368
3369 # Try to lock HA task here
3370 task_is_locked_by_me = self.lcm_tasks.lock_HA('ns', 'nslcmops', nslcmop_id)
3371 if not task_is_locked_by_me:
3372 return
3373
3374 logging_text = "Task ns={} scale={} ".format(nsr_id, nslcmop_id)
3375 self.logger.debug(logging_text + "Enter")
3376 # get all needed from database
3377 db_nsr = None
3378 db_nslcmop = None
3379 db_nslcmop_update = {}
3380 nslcmop_operation_state = None
3381 db_nsr_update = {}
3382 exc = None
3383 # in case of error, indicates what part of scale was failed to put nsr at error status
3384 scale_process = None
3385 old_operational_status = ""
3386 old_config_status = ""
3387 vnfr_scaled = False
3388 try:
3389 # wait for any previous tasks in process
3390 step = "Waiting for previous operations to terminate"
3391 await self.lcm_tasks.waitfor_related_HA('ns', 'nslcmops', nslcmop_id)
3392
3393 self._write_ns_status(
3394 nsr_id=nsr_id,
3395 ns_state=None,
3396 current_operation="SCALING",
3397 current_operation_id=nslcmop_id
3398 )
3399
3400 step = "Getting nslcmop from database"
3401 self.logger.debug(step + " after having waited for previous tasks to be completed")
3402 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
3403 step = "Getting nsr from database"
3404 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
3405
3406 old_operational_status = db_nsr["operational-status"]
3407 old_config_status = db_nsr["config-status"]
3408 step = "Parsing scaling parameters"
3409 # self.logger.debug(step)
3410 db_nsr_update["operational-status"] = "scaling"
3411 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3412 nsr_deployed = db_nsr["_admin"].get("deployed")
3413
3414 #######
3415 nsr_deployed = db_nsr["_admin"].get("deployed")
3416 vnf_index = db_nslcmop["operationParams"].get("member_vnf_index")
3417 # vdu_id = db_nslcmop["operationParams"].get("vdu_id")
3418 # vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
3419 # vdu_name = db_nslcmop["operationParams"].get("vdu_name")
3420 #######
3421
3422 RO_nsr_id = nsr_deployed["RO"]["nsr_id"]
3423 vnf_index = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
3424 scaling_group = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
3425 scaling_type = db_nslcmop["operationParams"]["scaleVnfData"]["scaleVnfType"]
3426 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
3427
3428 # for backward compatibility
3429 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
3430 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
3431 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
3432 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3433
3434 step = "Getting vnfr from database"
3435 db_vnfr = self.db.get_one("vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id})
3436 step = "Getting vnfd from database"
3437 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
3438
3439 step = "Getting scaling-group-descriptor"
3440 for scaling_descriptor in db_vnfd["scaling-group-descriptor"]:
3441 if scaling_descriptor["name"] == scaling_group:
3442 break
3443 else:
3444 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
3445 "at vnfd:scaling-group-descriptor".format(scaling_group))
3446
3447 # cooldown_time = 0
3448 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
3449 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
3450 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
3451 # break
3452
3453 # TODO check if ns is in a proper status
3454 step = "Sending scale order to VIM"
3455 nb_scale_op = 0
3456 if not db_nsr["_admin"].get("scaling-group"):
3457 self.update_db_2("nsrs", nsr_id, {"_admin.scaling-group": [{"name": scaling_group, "nb-scale-op": 0}]})
3458 admin_scale_index = 0
3459 else:
3460 for admin_scale_index, admin_scale_info in enumerate(db_nsr["_admin"]["scaling-group"]):
3461 if admin_scale_info["name"] == scaling_group:
3462 nb_scale_op = admin_scale_info.get("nb-scale-op", 0)
3463 break
3464 else: # not found, set index one plus last element and add new entry with the name
3465 admin_scale_index += 1
3466 db_nsr_update["_admin.scaling-group.{}.name".format(admin_scale_index)] = scaling_group
3467 RO_scaling_info = []
3468 vdu_scaling_info = {"scaling_group_name": scaling_group, "vdu": []}
3469 if scaling_type == "SCALE_OUT":
3470 # count if max-instance-count is reached
3471 max_instance_count = scaling_descriptor.get("max-instance-count", 10)
3472 # self.logger.debug("MAX_INSTANCE_COUNT is {}".format(max_instance_count))
3473 if nb_scale_op >= max_instance_count:
3474 raise LcmException("reached the limit of {} (max-instance-count) "
3475 "scaling-out operations for the "
3476 "scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group))
3477
3478 nb_scale_op += 1
3479 vdu_scaling_info["scaling_direction"] = "OUT"
3480 vdu_scaling_info["vdu-create"] = {}
3481 for vdu_scale_info in scaling_descriptor["vdu"]:
3482 RO_scaling_info.append({"osm_vdu_id": vdu_scale_info["vdu-id-ref"], "member-vnf-index": vnf_index,
3483 "type": "create", "count": vdu_scale_info.get("count", 1)})
3484 vdu_scaling_info["vdu-create"][vdu_scale_info["vdu-id-ref"]] = vdu_scale_info.get("count", 1)
3485
3486 elif scaling_type == "SCALE_IN":
3487 # count if min-instance-count is reached
3488 min_instance_count = 0
3489 if "min-instance-count" in scaling_descriptor and scaling_descriptor["min-instance-count"] is not None:
3490 min_instance_count = int(scaling_descriptor["min-instance-count"])
3491 if nb_scale_op <= min_instance_count:
3492 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
3493 "scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group))
3494 nb_scale_op -= 1
3495 vdu_scaling_info["scaling_direction"] = "IN"
3496 vdu_scaling_info["vdu-delete"] = {}
3497 for vdu_scale_info in scaling_descriptor["vdu"]:
3498 RO_scaling_info.append({"osm_vdu_id": vdu_scale_info["vdu-id-ref"], "member-vnf-index": vnf_index,
3499 "type": "delete", "count": vdu_scale_info.get("count", 1)})
3500 vdu_scaling_info["vdu-delete"][vdu_scale_info["vdu-id-ref"]] = vdu_scale_info.get("count", 1)
3501
3502 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
3503 vdu_create = vdu_scaling_info.get("vdu-create")
3504 vdu_delete = copy(vdu_scaling_info.get("vdu-delete"))
3505 if vdu_scaling_info["scaling_direction"] == "IN":
3506 for vdur in reversed(db_vnfr["vdur"]):
3507 if vdu_delete.get(vdur["vdu-id-ref"]):
3508 vdu_delete[vdur["vdu-id-ref"]] -= 1
3509 vdu_scaling_info["vdu"].append({
3510 "name": vdur["name"],
3511 "vdu_id": vdur["vdu-id-ref"],
3512 "interface": []
3513 })
3514 for interface in vdur["interfaces"]:
3515 vdu_scaling_info["vdu"][-1]["interface"].append({
3516 "name": interface["name"],
3517 "ip_address": interface["ip-address"],
3518 "mac_address": interface.get("mac-address"),
3519 })
3520 vdu_delete = vdu_scaling_info.pop("vdu-delete")
3521
3522 # PRE-SCALE BEGIN
3523 step = "Executing pre-scale vnf-config-primitive"
3524 if scaling_descriptor.get("scaling-config-action"):
3525 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
3526 if (scaling_config_action.get("trigger") == "pre-scale-in" and scaling_type == "SCALE_IN") \
3527 or (scaling_config_action.get("trigger") == "pre-scale-out" and scaling_type == "SCALE_OUT"):
3528 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
3529 step = db_nslcmop_update["detailed-status"] = \
3530 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive)
3531
3532 # look for primitive
3533 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
3534 if config_primitive["name"] == vnf_config_primitive:
3535 break
3536 else:
3537 raise LcmException(
3538 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
3539 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
3540 "primitive".format(scaling_group, config_primitive))
3541
3542 vnfr_params = {"VDU_SCALE_INFO": vdu_scaling_info}
3543 if db_vnfr.get("additionalParamsForVnf"):
3544 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
3545
3546 scale_process = "VCA"
3547 db_nsr_update["config-status"] = "configuring pre-scaling"
3548 primitive_params = self._map_primitive_params(config_primitive, {}, vnfr_params)
3549
3550 # Pre-scale retry check: Check if this sub-operation has been executed before
3551 op_index = self._check_or_add_scale_suboperation(
3552 db_nslcmop, nslcmop_id, vnf_index, vnf_config_primitive, primitive_params, 'PRE-SCALE')
3553 if op_index == self.SUBOPERATION_STATUS_SKIP:
3554 # Skip sub-operation
3555 result = 'COMPLETED'
3556 result_detail = 'Done'
3557 self.logger.debug(logging_text +
3558 "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
3559 vnf_config_primitive, result, result_detail))
3560 else:
3561 if op_index == self.SUBOPERATION_STATUS_NEW:
3562 # New sub-operation: Get index of this sub-operation
3563 op_index = len(db_nslcmop.get('_admin', {}).get('operations')) - 1
3564 self.logger.debug(logging_text + "vnf_config_primitive={} New sub-operation".
3565 format(vnf_config_primitive))
3566 else:
3567 # retry: Get registered params for this existing sub-operation
3568 op = db_nslcmop.get('_admin', {}).get('operations', [])[op_index]
3569 vnf_index = op.get('member_vnf_index')
3570 vnf_config_primitive = op.get('primitive')
3571 primitive_params = op.get('primitive_params')
3572 self.logger.debug(logging_text + "vnf_config_primitive={} Sub-operation retry".
3573 format(vnf_config_primitive))
3574 # Execute the primitive, either with new (first-time) or registered (retry) args
3575 result, result_detail = await self._ns_execute_primitive(
3576 self._look_for_deployed_vca(nsr_deployed["VCA"],
3577 member_vnf_index=vnf_index,
3578 vdu_id=None,
3579 vdu_count_index=None),
3580 vnf_config_primitive, primitive_params)
3581 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
3582 vnf_config_primitive, result, result_detail))
3583 # Update operationState = COMPLETED | FAILED
3584 self._update_suboperation_status(
3585 db_nslcmop, op_index, result, result_detail)
3586
3587 if result == "FAILED":
3588 raise LcmException(result_detail)
3589 db_nsr_update["config-status"] = old_config_status
3590 scale_process = None
3591 # PRE-SCALE END
3592
3593 # SCALE RO - BEGIN
3594 # Should this block be skipped if 'RO_nsr_id' == None ?
3595 # if (RO_nsr_id and RO_scaling_info):
3596 if RO_scaling_info:
3597 scale_process = "RO"
3598 # Scale RO retry check: Check if this sub-operation has been executed before
3599 op_index = self._check_or_add_scale_suboperation(
3600 db_nslcmop, vnf_index, None, None, 'SCALE-RO', RO_nsr_id, RO_scaling_info)
3601 if op_index == self.SUBOPERATION_STATUS_SKIP:
3602 # Skip sub-operation
3603 result = 'COMPLETED'
3604 result_detail = 'Done'
3605 self.logger.debug(logging_text + "Skipped sub-operation RO, result {} {}".format(
3606 result, result_detail))
3607 else:
3608 if op_index == self.SUBOPERATION_STATUS_NEW:
3609 # New sub-operation: Get index of this sub-operation
3610 op_index = len(db_nslcmop.get('_admin', {}).get('operations')) - 1
3611 self.logger.debug(logging_text + "New sub-operation RO")
3612 else:
3613 # retry: Get registered params for this existing sub-operation
3614 op = db_nslcmop.get('_admin', {}).get('operations', [])[op_index]
3615 RO_nsr_id = op.get('RO_nsr_id')
3616 RO_scaling_info = op.get('RO_scaling_info')
3617 self.logger.debug(logging_text + "Sub-operation RO retry for primitive {}".format(
3618 vnf_config_primitive))
3619
3620 RO_desc = await self.RO.create_action("ns", RO_nsr_id, {"vdu-scaling": RO_scaling_info})
3621 db_nsr_update["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index)] = nb_scale_op
3622 db_nsr_update["_admin.scaling-group.{}.time".format(admin_scale_index)] = time()
3623 # wait until ready
3624 RO_nslcmop_id = RO_desc["instance_action_id"]
3625 db_nslcmop_update["_admin.deploy.RO"] = RO_nslcmop_id
3626
3627 RO_task_done = False
3628 step = detailed_status = "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id)
3629 detailed_status_old = None
3630 self.logger.debug(logging_text + step)
3631
3632 deployment_timeout = 1 * 3600 # One hour
3633 while deployment_timeout > 0:
3634 if not RO_task_done:
3635 desc = await self.RO.show("ns", item_id_name=RO_nsr_id, extra_item="action",
3636 extra_item_id=RO_nslcmop_id)
3637
3638 # deploymentStatus
3639 self._on_update_ro_db(nsrs_id=nsr_id, ro_descriptor=desc)
3640
3641 ns_status, ns_status_info = self.RO.check_action_status(desc)
3642 if ns_status == "ERROR":
3643 raise ROclient.ROClientException(ns_status_info)
3644 elif ns_status == "BUILD":
3645 detailed_status = step + "; {}".format(ns_status_info)
3646 elif ns_status == "ACTIVE":
3647 RO_task_done = True
3648 step = detailed_status = "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id)
3649 self.logger.debug(logging_text + step)
3650 else:
3651 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
3652 else:
3653
3654 if ns_status == "ERROR":
3655 raise ROclient.ROClientException(ns_status_info)
3656 elif ns_status == "BUILD":
3657 detailed_status = step + "; {}".format(ns_status_info)
3658 elif ns_status == "ACTIVE":
3659 step = detailed_status = \
3660 "Waiting for management IP address reported by the VIM. Updating VNFRs"
3661 if not vnfr_scaled:
3662 self.scale_vnfr(db_vnfr, vdu_create=vdu_create, vdu_delete=vdu_delete)
3663 vnfr_scaled = True
3664 try:
3665 desc = await self.RO.show("ns", RO_nsr_id)
3666
3667 # deploymentStatus
3668 self._on_update_ro_db(nsrs_id=nsr_id, ro_descriptor=desc)
3669
3670 # nsr_deployed["nsr_ip"] = RO.get_ns_vnf_info(desc)
3671 self.ns_update_vnfr({db_vnfr["member-vnf-index-ref"]: db_vnfr}, desc)
3672 break
3673 except LcmExceptionNoMgmtIP:
3674 pass
3675 else:
3676 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
3677 if detailed_status != detailed_status_old:
3678 self._update_suboperation_status(
3679 db_nslcmop, op_index, 'COMPLETED', detailed_status)
3680 detailed_status_old = db_nslcmop_update["detailed-status"] = detailed_status
3681 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
3682
3683 await asyncio.sleep(5, loop=self.loop)
3684 deployment_timeout -= 5
3685 if deployment_timeout <= 0:
3686 self._update_suboperation_status(
3687 db_nslcmop, nslcmop_id, op_index, 'FAILED', "Timeout when waiting for ns to get ready")
3688 raise ROclient.ROClientException("Timeout waiting ns to be ready")
3689
3690 # update VDU_SCALING_INFO with the obtained ip_addresses
3691 if vdu_scaling_info["scaling_direction"] == "OUT":
3692 for vdur in reversed(db_vnfr["vdur"]):
3693 if vdu_scaling_info["vdu-create"].get(vdur["vdu-id-ref"]):
3694 vdu_scaling_info["vdu-create"][vdur["vdu-id-ref"]] -= 1
3695 vdu_scaling_info["vdu"].append({
3696 "name": vdur["name"],
3697 "vdu_id": vdur["vdu-id-ref"],
3698 "interface": []
3699 })
3700 for interface in vdur["interfaces"]:
3701 vdu_scaling_info["vdu"][-1]["interface"].append({
3702 "name": interface["name"],
3703 "ip_address": interface["ip-address"],
3704 "mac_address": interface.get("mac-address"),
3705 })
3706 del vdu_scaling_info["vdu-create"]
3707
3708 self._update_suboperation_status(db_nslcmop, op_index, 'COMPLETED', 'Done')
3709 # SCALE RO - END
3710
3711 scale_process = None
3712 if db_nsr_update:
3713 self.update_db_2("nsrs", nsr_id, db_nsr_update)
3714
3715 # POST-SCALE BEGIN
3716 # execute primitive service POST-SCALING
3717 step = "Executing post-scale vnf-config-primitive"
3718 if scaling_descriptor.get("scaling-config-action"):
3719 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
3720 if (scaling_config_action.get("trigger") == "post-scale-in" and scaling_type == "SCALE_IN") \
3721 or (scaling_config_action.get("trigger") == "post-scale-out" and scaling_type == "SCALE_OUT"):
3722 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
3723 step = db_nslcmop_update["detailed-status"] = \
3724 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive)
3725
3726 vnfr_params = {"VDU_SCALE_INFO": vdu_scaling_info}
3727 if db_vnfr.get("additionalParamsForVnf"):
3728 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
3729
3730 # look for primitive
3731 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
3732 if config_primitive["name"] == vnf_config_primitive:
3733 break
3734 else:
3735 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
3736 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
3737 "match any vnf-configuration:config-primitive".format(scaling_group,
3738 config_primitive))
3739 scale_process = "VCA"
3740 db_nsr_update["config-status"] = "configuring post-scaling"
3741 primitive_params = self._map_primitive_params(config_primitive, {}, vnfr_params)
3742
3743 # Post-scale retry check: Check if this sub-operation has been executed before
3744 op_index = self._check_or_add_scale_suboperation(
3745 db_nslcmop, nslcmop_id, vnf_index, vnf_config_primitive, primitive_params, 'POST-SCALE')
3746 if op_index == self.SUBOPERATION_STATUS_SKIP:
3747 # Skip sub-operation
3748 result = 'COMPLETED'
3749 result_detail = 'Done'
3750 self.logger.debug(logging_text +
3751 "vnf_config_primitive={} Skipped sub-operation, result {} {}".
3752 format(vnf_config_primitive, result, result_detail))
3753 else:
3754 if op_index == self.SUBOPERATION_STATUS_NEW:
3755 # New sub-operation: Get index of this sub-operation
3756 op_index = len(db_nslcmop.get('_admin', {}).get('operations')) - 1
3757 self.logger.debug(logging_text + "vnf_config_primitive={} New sub-operation".
3758 format(vnf_config_primitive))
3759 else:
3760 # retry: Get registered params for this existing sub-operation
3761 op = db_nslcmop.get('_admin', {}).get('operations', [])[op_index]
3762 vnf_index = op.get('member_vnf_index')
3763 vnf_config_primitive = op.get('primitive')
3764 primitive_params = op.get('primitive_params')
3765 self.logger.debug(logging_text + "vnf_config_primitive={} Sub-operation retry".
3766 format(vnf_config_primitive))
3767 # Execute the primitive, either with new (first-time) or registered (retry) args
3768 result, result_detail = await self._ns_execute_primitive(
3769 self._look_for_deployed_vca(nsr_deployed["VCA"],
3770 member_vnf_index=vnf_index,
3771 vdu_id=None,
3772 vdu_count_index=None),
3773 vnf_config_primitive, primitive_params)
3774 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
3775 vnf_config_primitive, result, result_detail))
3776 # Update operationState = COMPLETED | FAILED
3777 self._update_suboperation_status(
3778 db_nslcmop, op_index, result, result_detail)
3779
3780 if result == "FAILED":
3781 raise LcmException(result_detail)
3782 db_nsr_update["config-status"] = old_config_status
3783 scale_process = None
3784 # POST-SCALE END
3785
3786 db_nsr_update["detailed-status"] = "" # "scaled {} {}".format(scaling_group, scaling_type)
3787 db_nsr_update["operational-status"] = "running" if old_operational_status == "failed" \
3788 else old_operational_status
3789 db_nsr_update["config-status"] = old_config_status
3790 return
3791 except (ROclient.ROClientException, DbException, LcmException) as e:
3792 self.logger.error(logging_text + "Exit Exception {}".format(e))
3793 exc = e
3794 except asyncio.CancelledError:
3795 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
3796 exc = "Operation was cancelled"
3797 except Exception as e:
3798 exc = traceback.format_exc()
3799 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
3800 finally:
3801 self._write_ns_status(
3802 nsr_id=nsr_id,
3803 ns_state=None,
3804 current_operation="IDLE",
3805 current_operation_id=None
3806 )
3807 if exc:
3808 db_nslcmop_update["detailed-status"] = error_description_nslcmop = "FAILED {}: {}".format(step, exc)
3809 nslcmop_operation_state = "FAILED"
3810 if db_nsr:
3811 db_nsr_update["operational-status"] = old_operational_status
3812 db_nsr_update["config-status"] = old_config_status
3813 db_nsr_update["detailed-status"] = ""
3814 if scale_process:
3815 if "VCA" in scale_process:
3816 db_nsr_update["config-status"] = "failed"
3817 if "RO" in scale_process:
3818 db_nsr_update["operational-status"] = "failed"
3819 db_nsr_update["detailed-status"] = "FAILED scaling nslcmop={} {}: {}".format(nslcmop_id, step,
3820 exc)
3821 else:
3822 error_description_nslcmop = None
3823 nslcmop_operation_state = "COMPLETED"
3824 db_nslcmop_update["detailed-status"] = "Done"
3825
3826 self._write_op_status(
3827 op_id=nslcmop_id,
3828 stage="",
3829 error_message=error_description_nslcmop,
3830 operation_state=nslcmop_operation_state,
3831 other_update=db_nslcmop_update,
3832 )
3833 if db_nsr:
3834 self._write_ns_status(
3835 nsr_id=nsr_id,
3836 ns_state=None,
3837 current_operation="IDLE",
3838 current_operation_id=None,
3839 other_update=db_nsr_update
3840 )
3841
3842 if nslcmop_operation_state:
3843 try:
3844 await self.msg.aiowrite("ns", "scaled", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
3845 "operationState": nslcmop_operation_state},
3846 loop=self.loop)
3847 # if cooldown_time:
3848 # await asyncio.sleep(cooldown_time, loop=self.loop)
3849 # await self.msg.aiowrite("ns","scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
3850 except Exception as e:
3851 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
3852 self.logger.debug(logging_text + "Exit")
3853 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_scale")