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