caadce1847952f8f15a80f961f2e3cbb783d3ab0
[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 functools
24 import traceback
25 from jinja2 import Environment, Template, meta, TemplateError, TemplateNotFound, TemplateSyntaxError
26
27 import ROclient
28 from lcm_utils import LcmException, LcmExceptionNoMgmtIP, LcmBase
29
30 from osm_common.dbbase import DbException
31 from osm_common.fsbase import FsException
32 from n2vc.vnf import N2VC, N2VCPrimitiveExecutionFailed, NetworkServiceDoesNotExist
33
34 from copy import copy, deepcopy
35 from http import HTTPStatus
36 from time import time
37 from uuid import uuid4
38
39 __author__ = "Alfonso Tierno"
40
41
42 def get_iterable(in_dict, in_key):
43 """
44 Similar to <dict>.get(), but if value is None, False, ..., An empty tuple is returned instead
45 :param in_dict: a dictionary
46 :param in_key: the key to look for at in_dict
47 :return: in_dict[in_var] or () if it is None or not present
48 """
49 if not in_dict.get(in_key):
50 return ()
51 return in_dict[in_key]
52
53
54 def populate_dict(target_dict, key_list, value):
55 """
56 Upate target_dict creating nested dictionaries with the key_list. Last key_list item is asigned the value.
57 Example target_dict={K: J}; key_list=[a,b,c]; target_dict will be {K: J, a: {b: {c: value}}}
58 :param target_dict: dictionary to be changed
59 :param key_list: list of keys to insert at target_dict
60 :param value:
61 :return: None
62 """
63 for key in key_list[0:-1]:
64 if key not in target_dict:
65 target_dict[key] = {}
66 target_dict = target_dict[key]
67 target_dict[key_list[-1]] = value
68
69
70 class NsLcm(LcmBase):
71 timeout_vca_on_error = 5 * 60 # Time for charm from first time at blocked,error status to mark as failed
72 total_deploy_timeout = 2 * 3600 # global timeout for deployment
73 timeout_charm_delete = 10 * 60
74 timeout_primitive = 10 * 60 # timeout for primitive execution
75
76 def __init__(self, db, msg, fs, lcm_tasks, ro_config, vca_config, loop):
77 """
78 Init, Connect to database, filesystem storage, and messaging
79 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
80 :return: None
81 """
82 # logging
83 self.logger = logging.getLogger('lcm.ns')
84 self.loop = loop
85 self.lcm_tasks = lcm_tasks
86
87 super().__init__(db, msg, fs, self.logger)
88
89 self.ro_config = ro_config
90
91 self.n2vc = N2VC(
92 log=self.logger,
93 server=vca_config['host'],
94 port=vca_config['port'],
95 user=vca_config['user'],
96 secret=vca_config['secret'],
97 # TODO: This should point to the base folder where charms are stored,
98 # if there is a common one (like object storage). Otherwise, leave
99 # it unset and pass it via DeployCharms
100 # artifacts=vca_config[''],
101 artifacts=None,
102 juju_public_key=vca_config.get('pubkey'),
103 ca_cert=vca_config.get('cacert'),
104 )
105
106 def vnfd2RO(self, vnfd, new_id=None, additionalParams=None, nsrId=None):
107 """
108 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
109 :param vnfd: input vnfd
110 :param new_id: overrides vnf id if provided
111 :param additionalParams: Instantiation params for VNFs provided
112 :param nsrId: Id of the NSR
113 :return: copy of vnfd
114 """
115 try:
116 vnfd_RO = deepcopy(vnfd)
117 # remove unused by RO configuration, monitoring, scaling and internal keys
118 vnfd_RO.pop("_id", None)
119 vnfd_RO.pop("_admin", None)
120 vnfd_RO.pop("vnf-configuration", None)
121 vnfd_RO.pop("monitoring-param", None)
122 vnfd_RO.pop("scaling-group-descriptor", None)
123 if new_id:
124 vnfd_RO["id"] = new_id
125
126 # parse cloud-init or cloud-init-file with the provided variables using Jinja2
127 for vdu in get_iterable(vnfd_RO, "vdu"):
128 cloud_init_file = None
129 if vdu.get("cloud-init-file"):
130 base_folder = vnfd["_admin"]["storage"]
131 cloud_init_file = "{}/{}/cloud_init/{}".format(base_folder["folder"], base_folder["pkg-dir"],
132 vdu["cloud-init-file"])
133 with self.fs.file_open(cloud_init_file, "r") as ci_file:
134 cloud_init_content = ci_file.read()
135 vdu.pop("cloud-init-file", None)
136 elif vdu.get("cloud-init"):
137 cloud_init_content = vdu["cloud-init"]
138 else:
139 continue
140
141 env = Environment()
142 ast = env.parse(cloud_init_content)
143 mandatory_vars = meta.find_undeclared_variables(ast)
144 if mandatory_vars:
145 for var in mandatory_vars:
146 if not additionalParams or var not in additionalParams.keys():
147 raise LcmException("Variable '{}' defined at vnfd[id={}]:vdu[id={}]:cloud-init/cloud-init-"
148 "file, must be provided in the instantiation parameters inside the "
149 "'additionalParamsForVnf' block".format(var, vnfd["id"], vdu["id"]))
150 template = Template(cloud_init_content)
151 cloud_init_content = template.render(additionalParams or {})
152 vdu["cloud-init"] = cloud_init_content
153
154 return vnfd_RO
155 except FsException as e:
156 raise LcmException("Error reading vnfd[id={}]:vdu[id={}]:cloud-init-file={}: {}".
157 format(vnfd["id"], vdu["id"], cloud_init_file, e))
158 except (TemplateError, TemplateNotFound, TemplateSyntaxError) as e:
159 raise LcmException("Error parsing Jinja2 to cloud-init content at vnfd[id={}]:vdu[id={}]: {}".
160 format(vnfd["id"], vdu["id"], e))
161
162 def n2vc_callback(self, model_name, application_name, status, message, n2vc_info, task=None):
163 """
164 Callback both for charm status change and task completion
165 :param model_name: Charm model name
166 :param application_name: Charm application name
167 :param status: Can be
168 - blocked: The unit needs manual intervention
169 - maintenance: The unit is actively deploying/configuring
170 - waiting: The unit is waiting for another charm to be ready
171 - active: The unit is deployed, configured, and ready
172 - error: The charm has failed and needs attention.
173 - terminated: The charm has been destroyed
174 - removing,
175 - removed
176 :param message: detailed message error
177 :param n2vc_info: dictionary with information shared with instantiate task. It contains:
178 nsr_id:
179 nslcmop_id:
180 lcmOperationType: currently "instantiate"
181 deployed: dictionary with {<application>: {operational-status: <status>, detailed-status: <text>}}
182 db_update: dictionary to be filled with the changes to be wrote to database with format key.key.key: value
183 n2vc_event: event used to notify instantiation task that some change has been produced
184 :param task: None for charm status change, or task for completion task callback
185 :return:
186 """
187 try:
188 nsr_id = n2vc_info["nsr_id"]
189 deployed = n2vc_info["deployed"]
190 db_nsr_update = n2vc_info["db_update"]
191 nslcmop_id = n2vc_info["nslcmop_id"]
192 ns_operation = n2vc_info["lcmOperationType"]
193 n2vc_event = n2vc_info["n2vc_event"]
194 logging_text = "Task ns={} {}={} [n2vc_callback] application={}".format(nsr_id, ns_operation, nslcmop_id,
195 application_name)
196 for vca_index, vca_deployed in enumerate(deployed):
197 if not vca_deployed:
198 continue
199 if model_name == vca_deployed["model"] and application_name == vca_deployed["application"]:
200 break
201 else:
202 self.logger.error(logging_text + " Not present at nsr._admin.deployed.VCA. Received model_name={}".
203 format(model_name))
204 return
205 if task:
206 if task.cancelled():
207 self.logger.debug(logging_text + " task Cancelled")
208 vca_deployed['operational-status'] = "error"
209 db_nsr_update["_admin.deployed.VCA.{}.operational-status".format(vca_index)] = "error"
210 vca_deployed['detailed-status'] = "Task Cancelled"
211 db_nsr_update["_admin.deployed.VCA.{}.detailed-status".format(vca_index)] = "Task Cancelled"
212
213 elif task.done():
214 exc = task.exception()
215 if exc:
216 self.logger.error(logging_text + " task Exception={}".format(exc))
217 vca_deployed['operational-status'] = "error"
218 db_nsr_update["_admin.deployed.VCA.{}.operational-status".format(vca_index)] = "error"
219 vca_deployed['detailed-status'] = str(exc)
220 db_nsr_update["_admin.deployed.VCA.{}.detailed-status".format(vca_index)] = str(exc)
221 else:
222 self.logger.debug(logging_text + " task Done")
223 # task is Done, but callback is still ongoing. So ignore
224 return
225 elif status:
226 self.logger.debug(logging_text + " Enter status={} message={}".format(status, message))
227 if vca_deployed['operational-status'] == status:
228 return # same status, ignore
229 vca_deployed['operational-status'] = status
230 db_nsr_update["_admin.deployed.VCA.{}.operational-status".format(vca_index)] = status
231 vca_deployed['detailed-status'] = str(message)
232 db_nsr_update["_admin.deployed.VCA.{}.detailed-status".format(vca_index)] = str(message)
233 else:
234 self.logger.critical(logging_text + " Enter with bad parameters", exc_info=True)
235 return
236 # wake up instantiate task
237 n2vc_event.set()
238 except Exception as e:
239 self.logger.critical(logging_text + " Exception {}".format(e), exc_info=True)
240
241 def ns_params_2_RO(self, ns_params, nsd, vnfd_dict, n2vc_key_list):
242 """
243 Creates a RO ns descriptor from OSM ns_instantiate params
244 :param ns_params: OSM instantiate params
245 :return: The RO ns descriptor
246 """
247 vim_2_RO = {}
248 wim_2_RO = {}
249 # TODO feature 1417: Check that no instantiation is set over PDU
250 # check if PDU forces a concrete vim-network-id and add it
251 # check if PDU contains a SDN-assist info (dpid, switch, port) and pass it to RO
252
253 def vim_account_2_RO(vim_account):
254 if vim_account in vim_2_RO:
255 return vim_2_RO[vim_account]
256
257 db_vim = self.db.get_one("vim_accounts", {"_id": vim_account})
258 if db_vim["_admin"]["operationalState"] != "ENABLED":
259 raise LcmException("VIM={} is not available. operationalState={}".format(
260 vim_account, db_vim["_admin"]["operationalState"]))
261 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
262 vim_2_RO[vim_account] = RO_vim_id
263 return RO_vim_id
264
265 def wim_account_2_RO(wim_account):
266 if isinstance(wim_account, str):
267 if wim_account in wim_2_RO:
268 return wim_2_RO[wim_account]
269
270 db_wim = self.db.get_one("wim_accounts", {"_id": wim_account})
271 if db_wim["_admin"]["operationalState"] != "ENABLED":
272 raise LcmException("WIM={} is not available. operationalState={}".format(
273 wim_account, db_wim["_admin"]["operationalState"]))
274 RO_wim_id = db_wim["_admin"]["deployed"]["RO-account"]
275 wim_2_RO[wim_account] = RO_wim_id
276 return RO_wim_id
277 else:
278 return wim_account
279
280 def ip_profile_2_RO(ip_profile):
281 RO_ip_profile = deepcopy((ip_profile))
282 if "dns-server" in RO_ip_profile:
283 if isinstance(RO_ip_profile["dns-server"], list):
284 RO_ip_profile["dns-address"] = []
285 for ds in RO_ip_profile.pop("dns-server"):
286 RO_ip_profile["dns-address"].append(ds['address'])
287 else:
288 RO_ip_profile["dns-address"] = RO_ip_profile.pop("dns-server")
289 if RO_ip_profile.get("ip-version") == "ipv4":
290 RO_ip_profile["ip-version"] = "IPv4"
291 if RO_ip_profile.get("ip-version") == "ipv6":
292 RO_ip_profile["ip-version"] = "IPv6"
293 if "dhcp-params" in RO_ip_profile:
294 RO_ip_profile["dhcp"] = RO_ip_profile.pop("dhcp-params")
295 return RO_ip_profile
296
297 if not ns_params:
298 return None
299 RO_ns_params = {
300 # "name": ns_params["nsName"],
301 # "description": ns_params.get("nsDescription"),
302 "datacenter": vim_account_2_RO(ns_params["vimAccountId"]),
303 "wim_account": wim_account_2_RO(ns_params.get("wimAccountId")),
304 # "scenario": ns_params["nsdId"],
305 }
306 if n2vc_key_list:
307 for vnfd_ref, vnfd in vnfd_dict.items():
308 vdu_needed_access = []
309 mgmt_cp = None
310 if vnfd.get("vnf-configuration"):
311 if vnfd.get("mgmt-interface"):
312 if vnfd["mgmt-interface"].get("vdu-id"):
313 vdu_needed_access.append(vnfd["mgmt-interface"]["vdu-id"])
314 elif vnfd["mgmt-interface"].get("cp"):
315 mgmt_cp = vnfd["mgmt-interface"]["cp"]
316
317 for vdu in vnfd.get("vdu", ()):
318 if vdu.get("vdu-configuration"):
319 vdu_needed_access.append(vdu["id"])
320 elif mgmt_cp:
321 for vdu_interface in vdu.get("interface"):
322 if vdu_interface.get("external-connection-point-ref") and \
323 vdu_interface["external-connection-point-ref"] == mgmt_cp:
324 vdu_needed_access.append(vdu["id"])
325 mgmt_cp = None
326 break
327
328 if vdu_needed_access:
329 for vnf_member in nsd.get("constituent-vnfd"):
330 if vnf_member["vnfd-id-ref"] != vnfd_ref:
331 continue
332 for vdu in vdu_needed_access:
333 populate_dict(RO_ns_params,
334 ("vnfs", vnf_member["member-vnf-index"], "vdus", vdu, "mgmt_keys"),
335 n2vc_key_list)
336
337 if ns_params.get("vduImage"):
338 RO_ns_params["vduImage"] = ns_params["vduImage"]
339
340 if ns_params.get("ssh_keys"):
341 RO_ns_params["cloud-config"] = {"key-pairs": ns_params["ssh_keys"]}
342 for vnf_params in get_iterable(ns_params, "vnf"):
343 for constituent_vnfd in nsd["constituent-vnfd"]:
344 if constituent_vnfd["member-vnf-index"] == vnf_params["member-vnf-index"]:
345 vnf_descriptor = vnfd_dict[constituent_vnfd["vnfd-id-ref"]]
346 break
347 else:
348 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index={} is not present at nsd:"
349 "constituent-vnfd".format(vnf_params["member-vnf-index"]))
350 if vnf_params.get("vimAccountId"):
351 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "datacenter"),
352 vim_account_2_RO(vnf_params["vimAccountId"]))
353
354 for vdu_params in get_iterable(vnf_params, "vdu"):
355 # TODO feature 1417: check that this VDU exist and it is not a PDU
356 if vdu_params.get("volume"):
357 for volume_params in vdu_params["volume"]:
358 if volume_params.get("vim-volume-id"):
359 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
360 vdu_params["id"], "devices", volume_params["name"], "vim_id"),
361 volume_params["vim-volume-id"])
362 if vdu_params.get("interface"):
363 for interface_params in vdu_params["interface"]:
364 if interface_params.get("ip-address"):
365 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
366 vdu_params["id"], "interfaces", interface_params["name"],
367 "ip_address"),
368 interface_params["ip-address"])
369 if interface_params.get("mac-address"):
370 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
371 vdu_params["id"], "interfaces", interface_params["name"],
372 "mac_address"),
373 interface_params["mac-address"])
374 if interface_params.get("floating-ip-required"):
375 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
376 vdu_params["id"], "interfaces", interface_params["name"],
377 "floating-ip"),
378 interface_params["floating-ip-required"])
379
380 for internal_vld_params in get_iterable(vnf_params, "internal-vld"):
381 if internal_vld_params.get("vim-network-name"):
382 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "networks",
383 internal_vld_params["name"], "vim-network-name"),
384 internal_vld_params["vim-network-name"])
385 if internal_vld_params.get("vim-network-id"):
386 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "networks",
387 internal_vld_params["name"], "vim-network-id"),
388 internal_vld_params["vim-network-id"])
389 if internal_vld_params.get("ip-profile"):
390 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "networks",
391 internal_vld_params["name"], "ip-profile"),
392 ip_profile_2_RO(internal_vld_params["ip-profile"]))
393
394 for icp_params in get_iterable(internal_vld_params, "internal-connection-point"):
395 # look for interface
396 iface_found = False
397 for vdu_descriptor in vnf_descriptor["vdu"]:
398 for vdu_interface in vdu_descriptor["interface"]:
399 if vdu_interface.get("internal-connection-point-ref") == icp_params["id-ref"]:
400 if icp_params.get("ip-address"):
401 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
402 vdu_descriptor["id"], "interfaces",
403 vdu_interface["name"], "ip_address"),
404 icp_params["ip-address"])
405
406 if icp_params.get("mac-address"):
407 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
408 vdu_descriptor["id"], "interfaces",
409 vdu_interface["name"], "mac_address"),
410 icp_params["mac-address"])
411 iface_found = True
412 break
413 if iface_found:
414 break
415 else:
416 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
417 "internal-vld:id-ref={} is not present at vnfd:internal-"
418 "connection-point".format(vnf_params["member-vnf-index"],
419 icp_params["id-ref"]))
420
421 for vld_params in get_iterable(ns_params, "vld"):
422 if "ip-profile" in vld_params:
423 populate_dict(RO_ns_params, ("networks", vld_params["name"], "ip-profile"),
424 ip_profile_2_RO(vld_params["ip-profile"]))
425
426 if "wimAccountId" in vld_params and vld_params["wimAccountId"] is not None:
427 populate_dict(RO_ns_params, ("networks", vld_params["name"], "wim_account"),
428 wim_account_2_RO(vld_params["wimAccountId"])),
429 if vld_params.get("vim-network-name"):
430 RO_vld_sites = []
431 if isinstance(vld_params["vim-network-name"], dict):
432 for vim_account, vim_net in vld_params["vim-network-name"].items():
433 RO_vld_sites.append({
434 "netmap-use": vim_net,
435 "datacenter": vim_account_2_RO(vim_account)
436 })
437 else: # isinstance str
438 RO_vld_sites.append({"netmap-use": vld_params["vim-network-name"]})
439 if RO_vld_sites:
440 populate_dict(RO_ns_params, ("networks", vld_params["name"], "sites"), RO_vld_sites)
441 if vld_params.get("vim-network-id"):
442 RO_vld_sites = []
443 if isinstance(vld_params["vim-network-id"], dict):
444 for vim_account, vim_net in vld_params["vim-network-id"].items():
445 RO_vld_sites.append({
446 "netmap-use": vim_net,
447 "datacenter": vim_account_2_RO(vim_account)
448 })
449 else: # isinstance str
450 RO_vld_sites.append({"netmap-use": vld_params["vim-network-id"]})
451 if RO_vld_sites:
452 populate_dict(RO_ns_params, ("networks", vld_params["name"], "sites"), RO_vld_sites)
453 if vld_params.get("ns-net"):
454 if isinstance(vld_params["ns-net"], dict):
455 for vld_id, instance_scenario_id in vld_params["ns-net"].items():
456 RO_vld_ns_net = {"instance_scenario_id": instance_scenario_id, "osm_id": vld_id}
457 if RO_vld_ns_net:
458 populate_dict(RO_ns_params, ("networks", vld_params["name"], "use-network"), RO_vld_ns_net)
459 if "vnfd-connection-point-ref" in vld_params:
460 for cp_params in vld_params["vnfd-connection-point-ref"]:
461 # look for interface
462 for constituent_vnfd in nsd["constituent-vnfd"]:
463 if constituent_vnfd["member-vnf-index"] == cp_params["member-vnf-index-ref"]:
464 vnf_descriptor = vnfd_dict[constituent_vnfd["vnfd-id-ref"]]
465 break
466 else:
467 raise LcmException(
468 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={} "
469 "is not present at nsd:constituent-vnfd".format(cp_params["member-vnf-index-ref"]))
470 match_cp = False
471 for vdu_descriptor in vnf_descriptor["vdu"]:
472 for interface_descriptor in vdu_descriptor["interface"]:
473 if interface_descriptor.get("external-connection-point-ref") == \
474 cp_params["vnfd-connection-point-ref"]:
475 match_cp = True
476 break
477 if match_cp:
478 break
479 else:
480 raise LcmException(
481 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={}:"
482 "vnfd-connection-point-ref={} is not present at vnfd={}".format(
483 cp_params["member-vnf-index-ref"],
484 cp_params["vnfd-connection-point-ref"],
485 vnf_descriptor["id"]))
486 if cp_params.get("ip-address"):
487 populate_dict(RO_ns_params, ("vnfs", cp_params["member-vnf-index-ref"], "vdus",
488 vdu_descriptor["id"], "interfaces",
489 interface_descriptor["name"], "ip_address"),
490 cp_params["ip-address"])
491 if cp_params.get("mac-address"):
492 populate_dict(RO_ns_params, ("vnfs", cp_params["member-vnf-index-ref"], "vdus",
493 vdu_descriptor["id"], "interfaces",
494 interface_descriptor["name"], "mac_address"),
495 cp_params["mac-address"])
496 return RO_ns_params
497
498 def scale_vnfr(self, db_vnfr, vdu_create=None, vdu_delete=None):
499 # make a copy to do not change
500 vdu_create = copy(vdu_create)
501 vdu_delete = copy(vdu_delete)
502
503 vdurs = db_vnfr.get("vdur")
504 if vdurs is None:
505 vdurs = []
506 vdu_index = len(vdurs)
507 while vdu_index:
508 vdu_index -= 1
509 vdur = vdurs[vdu_index]
510 if vdur.get("pdu-type"):
511 continue
512 vdu_id_ref = vdur["vdu-id-ref"]
513 if vdu_create and vdu_create.get(vdu_id_ref):
514 for index in range(0, vdu_create[vdu_id_ref]):
515 vdur = deepcopy(vdur)
516 vdur["_id"] = str(uuid4())
517 vdur["count-index"] += 1
518 vdurs.insert(vdu_index+1+index, vdur)
519 del vdu_create[vdu_id_ref]
520 if vdu_delete and vdu_delete.get(vdu_id_ref):
521 del vdurs[vdu_index]
522 vdu_delete[vdu_id_ref] -= 1
523 if not vdu_delete[vdu_id_ref]:
524 del vdu_delete[vdu_id_ref]
525 # check all operations are done
526 if vdu_create or vdu_delete:
527 raise LcmException("Error scaling OUT VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
528 vdu_create))
529 if vdu_delete:
530 raise LcmException("Error scaling IN VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
531 vdu_delete))
532
533 vnfr_update = {"vdur": vdurs}
534 db_vnfr["vdur"] = vdurs
535 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
536
537 def ns_update_nsr(self, ns_update_nsr, db_nsr, nsr_desc_RO):
538 """
539 Updates database nsr with the RO info for the created vld
540 :param ns_update_nsr: dictionary to be filled with the updated info
541 :param db_nsr: content of db_nsr. This is also modified
542 :param nsr_desc_RO: nsr descriptor from RO
543 :return: Nothing, LcmException is raised on errors
544 """
545
546 for vld_index, vld in enumerate(get_iterable(db_nsr, "vld")):
547 for net_RO in get_iterable(nsr_desc_RO, "nets"):
548 if vld["id"] != net_RO.get("ns_net_osm_id"):
549 continue
550 vld["vim-id"] = net_RO.get("vim_net_id")
551 vld["name"] = net_RO.get("vim_name")
552 vld["status"] = net_RO.get("status")
553 vld["status-detailed"] = net_RO.get("error_msg")
554 ns_update_nsr["vld.{}".format(vld_index)] = vld
555 break
556 else:
557 raise LcmException("ns_update_nsr: Not found vld={} at RO info".format(vld["id"]))
558
559 def ns_update_vnfr(self, db_vnfrs, nsr_desc_RO):
560 """
561 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
562 :param db_vnfrs: dictionary with member-vnf-index: vnfr-content
563 :param nsr_desc_RO: nsr descriptor from RO
564 :return: Nothing, LcmException is raised on errors
565 """
566 for vnf_index, db_vnfr in db_vnfrs.items():
567 for vnf_RO in nsr_desc_RO["vnfs"]:
568 if vnf_RO["member_vnf_index"] != vnf_index:
569 continue
570 vnfr_update = {}
571 if vnf_RO.get("ip_address"):
572 db_vnfr["ip-address"] = vnfr_update["ip-address"] = vnf_RO["ip_address"].split(";")[0]
573 elif not db_vnfr.get("ip-address"):
574 raise LcmExceptionNoMgmtIP("ns member_vnf_index '{}' has no IP address".format(vnf_index))
575
576 for vdu_index, vdur in enumerate(get_iterable(db_vnfr, "vdur")):
577 vdur_RO_count_index = 0
578 if vdur.get("pdu-type"):
579 continue
580 for vdur_RO in get_iterable(vnf_RO, "vms"):
581 if vdur["vdu-id-ref"] != vdur_RO["vdu_osm_id"]:
582 continue
583 if vdur["count-index"] != vdur_RO_count_index:
584 vdur_RO_count_index += 1
585 continue
586 vdur["vim-id"] = vdur_RO.get("vim_vm_id")
587 if vdur_RO.get("ip_address"):
588 vdur["ip-address"] = vdur_RO["ip_address"].split(";")[0]
589 else:
590 vdur["ip-address"] = None
591 vdur["vdu-id-ref"] = vdur_RO.get("vdu_osm_id")
592 vdur["name"] = vdur_RO.get("vim_name")
593 vdur["status"] = vdur_RO.get("status")
594 vdur["status-detailed"] = vdur_RO.get("error_msg")
595 for ifacer in get_iterable(vdur, "interfaces"):
596 for interface_RO in get_iterable(vdur_RO, "interfaces"):
597 if ifacer["name"] == interface_RO.get("internal_name"):
598 ifacer["ip-address"] = interface_RO.get("ip_address")
599 ifacer["mac-address"] = interface_RO.get("mac_address")
600 break
601 else:
602 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} interface={} "
603 "at RO info".format(vnf_index, vdur["vdu-id-ref"], ifacer["name"]))
604 vnfr_update["vdur.{}".format(vdu_index)] = vdur
605 break
606 else:
607 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} count_index={} at "
608 "RO info".format(vnf_index, vdur["vdu-id-ref"], vdur["count-index"]))
609
610 for vld_index, vld in enumerate(get_iterable(db_vnfr, "vld")):
611 for net_RO in get_iterable(nsr_desc_RO, "nets"):
612 if vld["id"] != net_RO.get("vnf_net_osm_id"):
613 continue
614 vld["vim-id"] = net_RO.get("vim_net_id")
615 vld["name"] = net_RO.get("vim_name")
616 vld["status"] = net_RO.get("status")
617 vld["status-detailed"] = net_RO.get("error_msg")
618 vnfr_update["vld.{}".format(vld_index)] = vld
619 break
620 else:
621 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vld={} at RO info".format(
622 vnf_index, vld["id"]))
623
624 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
625 break
626
627 else:
628 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} at RO info".format(vnf_index))
629
630 async def instantiate(self, nsr_id, nslcmop_id):
631 logging_text = "Task ns={} instantiate={} ".format(nsr_id, nslcmop_id)
632 self.logger.debug(logging_text + "Enter")
633 # get all needed from database
634 start_deploy = time()
635 db_nsr = None
636 db_nslcmop = None
637 db_nsr_update = {"_admin.nslcmop": nslcmop_id}
638 db_nslcmop_update = {}
639 nslcmop_operation_state = None
640 db_vnfrs = {}
641 RO_descriptor_number = 0 # number of descriptors created at RO
642 vnf_index_2_RO_id = {} # map between vnfd/nsd id to the id used at RO
643 n2vc_info = {}
644 n2vc_key_list = [] # list of public keys to be injected as authorized to VMs
645 exc = None
646 try:
647 step = "Getting nslcmop={} from db".format(nslcmop_id)
648 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
649 step = "Getting nsr={} from db".format(nsr_id)
650 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
651 ns_params = db_nslcmop.get("operationParams")
652 nsd = db_nsr["nsd"]
653 nsr_name = db_nsr["name"] # TODO short-name??
654
655 # look if previous tasks in process
656 task_name, task_dependency = self.lcm_tasks.lookfor_related("ns", nsr_id, nslcmop_id)
657 if task_dependency:
658 step = db_nslcmop_update["detailed-status"] = \
659 "Waiting for related tasks to be completed: {}".format(task_name)
660 self.logger.debug(logging_text + step)
661 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
662 _, pending = await asyncio.wait(task_dependency, timeout=3600)
663 if pending:
664 raise LcmException("Timeout waiting related tasks to be completed")
665
666 step = "Getting vnfrs from db"
667 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
668 db_vnfds_ref = {}
669 db_vnfds = {}
670 db_vnfds_index = {}
671 for vnfr in db_vnfrs_list:
672 db_vnfrs[vnfr["member-vnf-index-ref"]] = vnfr
673 vnfd_id = vnfr["vnfd-id"]
674 vnfd_ref = vnfr["vnfd-ref"]
675 if vnfd_id not in db_vnfds:
676 step = "Getting vnfd={} id='{}' from db".format(vnfd_id, vnfd_ref)
677 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
678 db_vnfds_ref[vnfd_ref] = vnfd
679 db_vnfds[vnfd_id] = vnfd
680 db_vnfds_index[vnfr["member-vnf-index-ref"]] = db_vnfds[vnfd_id]
681
682 # Get or generates the _admin.deployed,VCA list
683 vca_deployed_list = None
684 vca_model_name = None
685 if db_nsr["_admin"].get("deployed"):
686 vca_deployed_list = db_nsr["_admin"]["deployed"].get("VCA")
687 vca_model_name = db_nsr["_admin"]["deployed"].get("VCA-model-name")
688 if vca_deployed_list is None:
689 vca_deployed_list = []
690 db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
691 populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
692 elif isinstance(vca_deployed_list, dict):
693 # maintain backward compatibility. Change a dict to list at database
694 vca_deployed_list = list(vca_deployed_list.values())
695 db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
696 populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
697
698 db_nsr_update["detailed-status"] = "creating"
699 db_nsr_update["operational-status"] = "init"
700 if not db_nsr["_admin"].get("deployed") or not db_nsr["_admin"]["deployed"].get("RO") or \
701 not db_nsr["_admin"]["deployed"]["RO"].get("vnfd"):
702 populate_dict(db_nsr, ("_admin", "deployed", "RO", "vnfd"), [])
703 db_nsr_update["_admin.deployed.RO.vnfd"] = []
704
705 # set state to INSTANTIATED. When instantiated NBI will not delete directly
706 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
707 self.update_db_2("nsrs", nsr_id, db_nsr_update)
708
709 # Deploy charms
710 # The parameters we'll need to deploy a charm
711 number_to_configure = 0
712
713 def deploy_charm(vnf_index, vdu_id, vdu_name, vdu_count_index, charm_params, n2vc_info, native_charm=False):
714 """An inner function to deploy the charm from either ns, vnf or vdu
715 For ns both vnf_index and vdu_id are None.
716 For vnf only vdu_id is None
717 For vdu both vnf_index and vdu_id contain a value
718 """
719 # if not charm_params.get("rw_mgmt_ip") and vnf_index: # if NS skip mgmt_ip checking
720 # raise LcmException("ns/vnfd/vdu has not management ip address to configure it")
721
722 machine_spec = {}
723 if native_charm:
724 machine_spec["username"] = charm_params.get("username"),
725 machine_spec["hostname"] = charm_params.get("rw_mgmt_ip")
726
727 # Note: The charm needs to exist on disk at the location
728 # specified by charm_path.
729 descriptor = vnfd if vnf_index else nsd
730 base_folder = descriptor["_admin"]["storage"]
731 storage_params = self.fs.get_params()
732 charm_path = "{}{}/{}/charms/{}".format(
733 storage_params["path"],
734 base_folder["folder"],
735 base_folder["pkg-dir"],
736 proxy_charm
737 )
738
739 # ns_name will be ignored in the current version of N2VC
740 # but will be implemented for the next point release.
741 model_name = nsr_id
742 vdu_id_text = (str(vdu_id) if vdu_id else "") + "-"
743 vnf_index_text = (str(vnf_index) if vnf_index else "") + "-"
744 application_name = self.n2vc.FormatApplicationName(nsr_name, vnf_index_text, vdu_id_text)
745
746 vca_index = len(vca_deployed_list)
747 # trunk name and add two char index at the end to ensure that it is unique. It is assumed no more than
748 # 26*26 charm in the same NS
749 application_name = application_name[0:48]
750 application_name += chr(97 + vca_index // 26) + chr(97 + vca_index % 26)
751 vca_deployed_ = {
752 "member-vnf-index": vnf_index,
753 "vdu_id": vdu_id,
754 "model": model_name,
755 "application": application_name,
756 "operational-status": "init",
757 "detailed-status": "",
758 "step": "initial-deploy",
759 "vnfd_id": vnfd_id,
760 "vdu_name": vdu_name,
761 "vdu_count_index": vdu_count_index,
762 }
763 vca_deployed_list.append(vca_deployed_)
764 db_nsr_update["_admin.deployed.VCA.{}".format(vca_index)] = vca_deployed_
765 self.update_db_2("nsrs", nsr_id, db_nsr_update)
766
767 self.logger.debug("Task create_ns={} Passing artifacts path '{}' for {}".format(nsr_id, charm_path,
768 proxy_charm))
769 if not n2vc_info:
770 n2vc_info["nsr_id"] = nsr_id
771 n2vc_info["nslcmop_id"] = nslcmop_id
772 n2vc_info["n2vc_event"] = asyncio.Event(loop=self.loop)
773 n2vc_info["lcmOperationType"] = "instantiate"
774 n2vc_info["deployed"] = vca_deployed_list
775 n2vc_info["db_update"] = db_nsr_update
776 task = asyncio.ensure_future(
777 self.n2vc.DeployCharms(
778 model_name, # The network service name
779 application_name, # The application name
780 descriptor, # The vnf/nsd descriptor
781 charm_path, # Path to charm
782 charm_params, # Runtime params, like mgmt ip
783 machine_spec, # for native charms only
784 self.n2vc_callback, # Callback for status changes
785 n2vc_info, # Callback parameter
786 None, # Callback parameter (task)
787 )
788 )
789 task.add_done_callback(functools.partial(self.n2vc_callback, model_name, application_name, None, None,
790 n2vc_info))
791 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "create_charm:" + application_name, task)
792
793 step = "Looking for needed vnfd to configure with proxy charm"
794 self.logger.debug(logging_text + step)
795
796 for c_vnf in get_iterable(nsd, "constituent-vnfd"):
797 vnfd_id = c_vnf["vnfd-id-ref"]
798 vnf_index = str(c_vnf["member-vnf-index"])
799 vnfd = db_vnfds_ref[vnfd_id]
800
801 # Get additional parameters
802 vnfr_params = {}
803 if db_vnfrs[vnf_index].get("additionalParamsForVnf"):
804 vnfr_params = db_vnfrs[vnf_index]["additionalParamsForVnf"].copy()
805 for k, v in vnfr_params.items():
806 if isinstance(v, str) and v.startswith("!!yaml "):
807 vnfr_params[k] = yaml.safe_load(v[7:])
808
809 step = "deploying proxy charms for configuration"
810 # Check if this VNF has a charm configuration
811 vnf_config = vnfd.get("vnf-configuration")
812 if vnf_config and vnf_config.get("juju"):
813 proxy_charm = vnf_config["juju"]["charm"]
814 if vnf_config["juju"].get("proxy") is False:
815 # native_charm, will be deployed after VM. Skip
816 proxy_charm = None
817
818 if proxy_charm:
819 if not vca_model_name:
820 step = "creating VCA model name '{}'".format(nsr_id)
821 self.logger.debug(logging_text + step)
822 await self.n2vc.CreateNetworkService(nsr_id)
823 vca_model_name = nsr_id
824 db_nsr_update["_admin.deployed.VCA-model-name"] = nsr_id
825 self.update_db_2("nsrs", nsr_id, db_nsr_update)
826 step = "deploying proxy charm to configure vnf {}".format(vnf_index)
827 vnfr_params["rw_mgmt_ip"] = db_vnfrs[vnf_index]["ip-address"]
828 charm_params = {
829 "user_values": vnfr_params,
830 "rw_mgmt_ip": db_vnfrs[vnf_index]["ip-address"],
831 "initial-config-primitive": {} # vnf_config.get('initial-config-primitive') or {}
832 }
833
834 # Login to the VCA. If there are multiple calls to login(),
835 # subsequent calls will be a nop and return immediately.
836 await self.n2vc.login()
837
838 deploy_charm(vnf_index, None, None, None, charm_params, n2vc_info)
839 number_to_configure += 1
840
841 # Deploy charms for each VDU that supports one.
842 for vdu_index, vdu in enumerate(get_iterable(vnfd, 'vdu')):
843 vdu_config = vdu.get('vdu-configuration')
844 proxy_charm = None
845
846 if vdu_config and vdu_config.get("juju"):
847 proxy_charm = vdu_config["juju"]["charm"]
848 if vdu_config["juju"].get("proxy") is False:
849 # native_charm, will be deployed after VM. Skip
850 proxy_charm = None
851
852 if proxy_charm:
853 if not vca_model_name:
854 step = "creating VCA model name"
855 await self.n2vc.CreateNetworkService(nsr_id)
856 vca_model_name = nsr_id
857 db_nsr_update["_admin.deployed.VCA-model-name"] = nsr_id
858 self.update_db_2("nsrs", nsr_id, db_nsr_update)
859 step = "deploying proxy charm to configure member_vnf_index={} vdu={}".format(vnf_index,
860 vdu["id"])
861 await self.n2vc.login()
862 vdur = db_vnfrs[vnf_index]["vdur"][vdu_index]
863 # TODO for the moment only first vdu_id contains a charm deployed
864 if vdur["vdu-id-ref"] != vdu["id"]:
865 raise LcmException("Mismatch vdur {}, vdu {} at index {} for member_vnf_index={}"
866 .format(vdur["vdu-id-ref"], vdu["id"], vdu_index, vnf_index))
867 vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
868 charm_params = {
869 "user_values": vnfr_params,
870 "rw_mgmt_ip": vdur["ip-address"],
871 "initial-config-primitive": {} # vdu_config.get('initial-config-primitive') or {}
872 }
873 deploy_charm(vnf_index, vdu["id"], vdur.get("name"), vdur["count-index"],
874 charm_params, n2vc_info)
875 number_to_configure += 1
876
877 # Check if this NS has a charm configuration
878
879 ns_config = nsd.get("ns-configuration")
880 if ns_config and ns_config.get("juju"):
881 proxy_charm = ns_config["juju"]["charm"]
882 if ns_config["juju"].get("proxy") is False:
883 # native_charm, will be deployed after VM. Skip
884 proxy_charm = None
885
886 if proxy_charm:
887 step = "deploying proxy charm to configure ns"
888 # TODO is NS magmt IP address needed?
889
890 # Get additional parameters
891 additional_params = {}
892 if db_nsr.get("additionalParamsForNs"):
893 additional_params = db_nsr["additionalParamsForNs"].copy()
894 for k, v in additional_params.items():
895 if isinstance(v, str) and v.startswith("!!yaml "):
896 additional_params[k] = yaml.safe_load(v[7:])
897
898 # additional_params["rw_mgmt_ip"] = db_nsr["ip-address"]
899 charm_params = {
900 "user_values": additional_params,
901 # "rw_mgmt_ip": db_nsr["ip-address"],
902 "initial-config-primitive": {} # ns_config.get('initial-config-primitive') or {}
903 }
904
905 # Login to the VCA. If there are multiple calls to login(),
906 # subsequent calls will be a nop and return immediately.
907 await self.n2vc.login()
908 deploy_charm(None, None, None, None, charm_params, n2vc_info)
909 number_to_configure += 1
910
911 db_nsr_update["operational-status"] = "running"
912
913 # Wait until all charms has reached blocked or active status
914 step = "waiting proxy charms to be ready"
915 if number_to_configure:
916 # wait until all charms are configured.
917 # steps are:
918 # initial-deploy
919 # get-ssh-public-key
920 # generate-ssh-key
921 # retry-get-ssh-public-key
922 # ssh-public-key-obtained
923 while time() <= start_deploy + self.total_deploy_timeout:
924 if db_nsr_update:
925 self.update_db_2("nsrs", nsr_id, db_nsr_update)
926 if db_nslcmop_update:
927 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
928
929 all_active = True
930 for vca_index, vca_deployed in enumerate(vca_deployed_list):
931 database_entry = "_admin.deployed.VCA.{}.".format(vca_index)
932 if vca_deployed["step"] == "initial-deploy":
933 if vca_deployed["operational-status"] in ("active", "blocked"):
934 step = "execute charm primitive get-ssh-public-key for member_vnf_index={} vdu_id={}" \
935 .format(vca_deployed["member-vnf-index"],
936 vca_deployed["vdu_id"])
937 self.logger.debug(logging_text + step)
938 primitive_id = await self.n2vc.ExecutePrimitive(
939 vca_deployed["model"],
940 vca_deployed["application"],
941 "get-ssh-public-key",
942 None,
943 )
944 vca_deployed["step"] = db_nsr_update[database_entry + "step"] = "get-ssh-public-key"
945 vca_deployed["primitive_id"] = db_nsr_update[database_entry + "primitive_id"] =\
946 primitive_id
947 db_nsr_update[database_entry + "operational-status"] =\
948 vca_deployed["operational-status"]
949 elif vca_deployed["step"] in ("get-ssh-public-key", "retry-get-ssh-public-key"):
950 primitive_id = vca_deployed["primitive_id"]
951 primitive_status = await self.n2vc.GetPrimitiveStatus(vca_deployed["model"],
952 primitive_id)
953 if primitive_status in ("completed", "failed"):
954 primitive_result = await self.n2vc.GetPrimitiveOutput(vca_deployed["model"],
955 primitive_id)
956 vca_deployed["primitive_id"] = db_nsr_update[database_entry + "primitive_id"] = None
957 if primitive_status == "completed" and isinstance(primitive_result, dict) and \
958 primitive_result.get("pubkey"):
959 ssh_public_key = primitive_result.get("pubkey")
960 vca_deployed["step"] = db_nsr_update[database_entry + "step"] =\
961 "ssh-public-key-obtained"
962 vca_deployed["ssh-public-key"] = db_nsr_update[database_entry + "ssh-public-key"] =\
963 ssh_public_key
964 n2vc_key_list.append(ssh_public_key)
965 step = "charm ssh-public-key for member_vnf_index={} vdu_id={} is '{}'".format(
966 vca_deployed["member-vnf-index"], vca_deployed["vdu_id"], ssh_public_key)
967 self.logger.debug(logging_text + step)
968 else: # primitive_status == "failed":
969 if vca_deployed["step"] == "get-ssh-public-key":
970 step = "execute charm primitive generate-ssh-public-key for member_vnf_index="\
971 "{} vdu_id={}".format(vca_deployed["member-vnf-index"],
972 vca_deployed["vdu_id"])
973 self.logger.debug(logging_text + step)
974 vca_deployed["step"] = db_nsr_update[database_entry + "step"] =\
975 "generate-ssh-key"
976 primitive_id = await self.n2vc.ExecutePrimitive(
977 vca_deployed["model"],
978 vca_deployed["application"],
979 "generate-ssh-key",
980 None,
981 )
982 vca_deployed["primitive_id"] = db_nsr_update[database_entry + "primitive_id"] =\
983 primitive_id
984 else: # failed for second time
985 raise LcmException(
986 "error executing primitive get-ssh-public-key: {}".format(primitive_result))
987
988 elif vca_deployed["step"] == "generate-ssh-key":
989 primitive_id = vca_deployed["primitive_id"]
990 primitive_status = await self.n2vc.GetPrimitiveStatus(vca_deployed["model"],
991 primitive_id)
992 if primitive_status in ("completed", "failed"):
993 primitive_result = await self.n2vc.GetPrimitiveOutput(vca_deployed["model"],
994 primitive_id)
995 vca_deployed["primitive_id"] = db_nsr_update[
996 database_entry + "primitive_id"] = None
997 if primitive_status == "completed":
998 step = "execute primitive get-ssh-public-key again for member_vnf_index={} "\
999 "vdu_id={}".format(vca_deployed["member-vnf-index"],
1000 vca_deployed["vdu_id"])
1001 self.logger.debug(logging_text + step)
1002 vca_deployed["step"] = db_nsr_update[database_entry + "step"] = \
1003 "retry-get-ssh-public-key"
1004 primitive_id = await self.n2vc.ExecutePrimitive(
1005 vca_deployed["model"],
1006 vca_deployed["application"],
1007 "get-ssh-public-key",
1008 None,
1009 )
1010 vca_deployed["primitive_id"] = db_nsr_update[database_entry + "primitive_id"] =\
1011 primitive_id
1012
1013 else: # primitive_status == "failed":
1014 raise LcmException("error executing primitive generate-ssh-key: {}"
1015 .format(primitive_result))
1016
1017 if vca_deployed["step"] != "ssh-public-key-obtained":
1018 all_active = False
1019
1020 if all_active:
1021 break
1022 await asyncio.sleep(5)
1023 else: # total_deploy_timeout
1024 raise LcmException("Timeout waiting charm to be initialized for member_vnf_index={} vdu_id={}"
1025 .format(vca_deployed["member-vnf-index"], vca_deployed["vdu_id"]))
1026
1027 # deploy RO
1028 RO = ROclient.ROClient(self.loop, **self.ro_config)
1029 # get vnfds, instantiate at RO
1030 for c_vnf in nsd.get("constituent-vnfd", ()):
1031 member_vnf_index = c_vnf["member-vnf-index"]
1032 vnfd = db_vnfds_ref[c_vnf['vnfd-id-ref']]
1033 vnfd_ref = vnfd["id"]
1034 step = db_nsr_update["detailed-status"] = "Creating vnfd='{}' member_vnf_index='{}' at RO".format(
1035 vnfd_ref, member_vnf_index)
1036 # self.logger.debug(logging_text + step)
1037 vnfd_id_RO = "{}.{}.{}".format(nsr_id, RO_descriptor_number, member_vnf_index[:23])
1038 vnf_index_2_RO_id[member_vnf_index] = vnfd_id_RO
1039 RO_descriptor_number += 1
1040
1041 # look position at deployed.RO.vnfd if not present it will be appended at the end
1042 for index, vnf_deployed in enumerate(db_nsr["_admin"]["deployed"]["RO"]["vnfd"]):
1043 if vnf_deployed["member-vnf-index"] == member_vnf_index:
1044 break
1045 else:
1046 index = len(db_nsr["_admin"]["deployed"]["RO"]["vnfd"])
1047 db_nsr["_admin"]["deployed"]["RO"]["vnfd"].append(None)
1048
1049 # look if present
1050 RO_update = {"member-vnf-index": member_vnf_index}
1051 vnfd_list = await RO.get_list("vnfd", filter_by={"osm_id": vnfd_id_RO})
1052 if vnfd_list:
1053 RO_update["id"] = vnfd_list[0]["uuid"]
1054 self.logger.debug(logging_text + "vnfd='{}' member_vnf_index='{}' exists at RO. Using RO_id={}".
1055 format(vnfd_ref, member_vnf_index, vnfd_list[0]["uuid"]))
1056 else:
1057 vnfd_RO = self.vnfd2RO(vnfd, vnfd_id_RO, db_vnfrs[c_vnf["member-vnf-index"]].
1058 get("additionalParamsForVnf"), nsr_id)
1059 desc = await RO.create("vnfd", descriptor=vnfd_RO)
1060 RO_update["id"] = desc["uuid"]
1061 self.logger.debug(logging_text + "vnfd='{}' member_vnf_index='{}' created at RO. RO_id={}".format(
1062 vnfd_ref, member_vnf_index, desc["uuid"]))
1063 db_nsr_update["_admin.deployed.RO.vnfd.{}".format(index)] = RO_update
1064 db_nsr["_admin"]["deployed"]["RO"]["vnfd"][index] = RO_update
1065 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1066
1067 # create nsd at RO
1068 nsd_ref = nsd["id"]
1069 step = db_nsr_update["detailed-status"] = "Creating nsd={} at RO".format(nsd_ref)
1070 # self.logger.debug(logging_text + step)
1071
1072 RO_osm_nsd_id = "{}.{}.{}".format(nsr_id, RO_descriptor_number, nsd_ref[:23])
1073 RO_descriptor_number += 1
1074 nsd_list = await RO.get_list("nsd", filter_by={"osm_id": RO_osm_nsd_id})
1075 if nsd_list:
1076 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = nsd_list[0]["uuid"]
1077 self.logger.debug(logging_text + "nsd={} exists at RO. Using RO_id={}".format(
1078 nsd_ref, RO_nsd_uuid))
1079 else:
1080 nsd_RO = deepcopy(nsd)
1081 nsd_RO["id"] = RO_osm_nsd_id
1082 nsd_RO.pop("_id", None)
1083 nsd_RO.pop("_admin", None)
1084 for c_vnf in nsd_RO.get("constituent-vnfd", ()):
1085 member_vnf_index = c_vnf["member-vnf-index"]
1086 c_vnf["vnfd-id-ref"] = vnf_index_2_RO_id[member_vnf_index]
1087 for c_vld in nsd_RO.get("vld", ()):
1088 for cp in c_vld.get("vnfd-connection-point-ref", ()):
1089 member_vnf_index = cp["member-vnf-index-ref"]
1090 cp["vnfd-id-ref"] = vnf_index_2_RO_id[member_vnf_index]
1091
1092 desc = await RO.create("nsd", descriptor=nsd_RO)
1093 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
1094 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = desc["uuid"]
1095 self.logger.debug(logging_text + "nsd={} created at RO. RO_id={}".format(nsd_ref, RO_nsd_uuid))
1096 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1097
1098 # Crate ns at RO
1099 # if present use it unless in error status
1100 RO_nsr_id = db_nsr["_admin"].get("deployed", {}).get("RO", {}).get("nsr_id")
1101 if RO_nsr_id:
1102 try:
1103 step = db_nsr_update["detailed-status"] = "Looking for existing ns at RO"
1104 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
1105 desc = await RO.show("ns", RO_nsr_id)
1106 except ROclient.ROClientException as e:
1107 if e.http_code != HTTPStatus.NOT_FOUND:
1108 raise
1109 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
1110 if RO_nsr_id:
1111 ns_status, ns_status_info = RO.check_ns_status(desc)
1112 db_nsr_update["_admin.deployed.RO.nsr_status"] = ns_status
1113 if ns_status == "ERROR":
1114 step = db_nsr_update["detailed-status"] = "Deleting ns at RO. RO_ns_id={}".format(RO_nsr_id)
1115 self.logger.debug(logging_text + step)
1116 await RO.delete("ns", RO_nsr_id)
1117 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
1118 if not RO_nsr_id:
1119 step = db_nsr_update["detailed-status"] = "Checking dependencies"
1120 # self.logger.debug(logging_text + step)
1121
1122 # check if VIM is creating and wait look if previous tasks in process
1123 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account", ns_params["vimAccountId"])
1124 if task_dependency:
1125 step = "Waiting for related tasks to be completed: {}".format(task_name)
1126 self.logger.debug(logging_text + step)
1127 await asyncio.wait(task_dependency, timeout=3600)
1128 if ns_params.get("vnf"):
1129 for vnf in ns_params["vnf"]:
1130 if "vimAccountId" in vnf:
1131 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account",
1132 vnf["vimAccountId"])
1133 if task_dependency:
1134 step = "Waiting for related tasks to be completed: {}".format(task_name)
1135 self.logger.debug(logging_text + step)
1136 await asyncio.wait(task_dependency, timeout=3600)
1137
1138 step = db_nsr_update["detailed-status"] = "Checking instantiation parameters"
1139
1140 # feature 1429. Add n2vc public key to needed VMs
1141 n2vc_key = await self.n2vc.GetPublicKey()
1142 n2vc_key_list.append(n2vc_key)
1143 RO_ns_params = self.ns_params_2_RO(ns_params, nsd, db_vnfds_ref, n2vc_key_list)
1144
1145 step = db_nsr_update["detailed-status"] = "Creating ns at RO"
1146 desc = await RO.create("ns", descriptor=RO_ns_params,
1147 name=db_nsr["name"],
1148 scenario=RO_nsd_uuid)
1149 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = desc["uuid"]
1150 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
1151 db_nsr_update["_admin.deployed.RO.nsr_status"] = "BUILD"
1152 self.logger.debug(logging_text + "ns created at RO. RO_id={}".format(desc["uuid"]))
1153 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1154
1155 # wait until NS is ready
1156 step = ns_status_detailed = detailed_status = "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id)
1157 detailed_status_old = None
1158 self.logger.debug(logging_text + step)
1159
1160 while time() <= start_deploy + self.total_deploy_timeout:
1161 desc = await RO.show("ns", RO_nsr_id)
1162 ns_status, ns_status_info = RO.check_ns_status(desc)
1163 db_nsr_update["_admin.deployed.RO.nsr_status"] = ns_status
1164 if ns_status == "ERROR":
1165 raise ROclient.ROClientException(ns_status_info)
1166 elif ns_status == "BUILD":
1167 detailed_status = ns_status_detailed + "; {}".format(ns_status_info)
1168 elif ns_status == "ACTIVE":
1169 step = detailed_status = "Waiting for management IP address reported by the VIM. Updating VNFRs"
1170 try:
1171 self.ns_update_vnfr(db_vnfrs, desc)
1172 break
1173 except LcmExceptionNoMgmtIP:
1174 pass
1175 else:
1176 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
1177 if detailed_status != detailed_status_old:
1178 detailed_status_old = db_nsr_update["detailed-status"] = detailed_status
1179 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1180 await asyncio.sleep(5, loop=self.loop)
1181 else: # total_deploy_timeout
1182 raise ROclient.ROClientException("Timeout waiting ns to be ready")
1183
1184 step = "Updating NSR"
1185 self.ns_update_nsr(db_nsr_update, db_nsr, desc)
1186
1187 db_nsr_update["operational-status"] = "running"
1188 db_nsr["detailed-status"] = "Configuring vnfr"
1189 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1190
1191 # Configure proxy charms once VMs are up
1192 for vca_index, vca_deployed in enumerate(vca_deployed_list):
1193 vnf_index = vca_deployed.get("member-vnf-index")
1194 vdu_id = vca_deployed.get("vdu_id")
1195 vdu_name = None
1196 vdu_count_index = None
1197
1198 step = "executing proxy charm initial primitives for member_vnf_index={} vdu_id={}".format(vnf_index,
1199 vdu_id)
1200 add_params = {}
1201 initial_config_primitive_list = []
1202 if vnf_index:
1203 if db_vnfrs[vnf_index].get("additionalParamsForVnf"):
1204 add_params = db_vnfrs[vnf_index]["additionalParamsForVnf"].copy()
1205 vnfd = db_vnfds_index[vnf_index]
1206
1207 if vdu_id:
1208 for vdu_index, vdu in enumerate(get_iterable(vnfd, 'vdu')):
1209 if vdu["id"] == vdu_id:
1210 initial_config_primitive_list = vdu['vdu-configuration'].get(
1211 'initial-config-primitive', [])
1212 break
1213 else:
1214 raise LcmException("Not found vdu_id={} at vnfd:vdu".format(vdu_id))
1215 vdur = db_vnfrs[vnf_index]["vdur"][vdu_index]
1216 # TODO for the moment only first vdu_id contains a charm deployed
1217 if vdur["vdu-id-ref"] != vdu["id"]:
1218 raise LcmException("Mismatch vdur {}, vdu {} at index {} for vnf {}"
1219 .format(vdur["vdu-id-ref"], vdu["id"], vdu_index, vnf_index))
1220 add_params["rw_mgmt_ip"] = vdur["ip-address"]
1221 else:
1222 add_params["rw_mgmt_ip"] = db_vnfrs[vnf_index]["ip-address"]
1223 initial_config_primitive_list = vnfd["vnf-configuration"].get('initial-config-primitive', [])
1224 else:
1225 if db_nsr.get("additionalParamsForNs"):
1226 add_params = db_nsr["additionalParamsForNs"].copy()
1227 for k, v in add_params.items():
1228 if isinstance(v, str) and v.startswith("!!yaml "):
1229 add_params[k] = yaml.safe_load(v[7:])
1230 add_params["rw_mgmt_ip"] = None
1231
1232 # add primitive verify-ssh-credentials to the list after config only when is a vnf or vdu charm
1233 initial_config_primitive_list = initial_config_primitive_list.copy()
1234 if initial_config_primitive_list and vnf_index:
1235 initial_config_primitive_list.insert(1, {"name": "verify-ssh-credentials", "parameter": []})
1236
1237 for initial_config_primitive in initial_config_primitive_list:
1238 primitive_params_ = self._map_primitive_params(initial_config_primitive, {}, add_params)
1239 self.logger.debug(logging_text + step + " primitive '{}' params '{}'"
1240 .format(initial_config_primitive["name"], primitive_params_))
1241 primitive_result, primitive_detail = await self._ns_execute_primitive(
1242 db_nsr["_admin"]["deployed"], vnf_index, vdu_id, vdu_name, vdu_count_index,
1243 initial_config_primitive["name"],
1244 primitive_params_,
1245 retries=10 if initial_config_primitive["name"] == "verify-ssh-credentials" else 0,
1246 retries_interval=30)
1247 if primitive_result != "COMPLETED":
1248 raise LcmException("charm error executing primitive {} for member_vnf_index={} vdu_id={}: '{}'"
1249 .format(initial_config_primitive["name"], vca_deployed["member-vnf-index"],
1250 vca_deployed["vdu_id"], primitive_detail))
1251
1252 # Deploy native charms
1253 step = "Looking for needed vnfd to configure with native charm"
1254 self.logger.debug(logging_text + step)
1255
1256 for c_vnf in get_iterable(nsd, "constituent-vnfd"):
1257 vnfd_id = c_vnf["vnfd-id-ref"]
1258 vnf_index = str(c_vnf["member-vnf-index"])
1259 vnfd = db_vnfds_ref[vnfd_id]
1260
1261 # Get additional parameters
1262 vnfr_params = {}
1263 if db_vnfrs[vnf_index].get("additionalParamsForVnf"):
1264 vnfr_params = db_vnfrs[vnf_index]["additionalParamsForVnf"].copy()
1265 for k, v in vnfr_params.items():
1266 if isinstance(v, str) and v.startswith("!!yaml "):
1267 vnfr_params[k] = yaml.safe_load(v[7:])
1268
1269 # Check if this VNF has a charm configuration
1270 vnf_config = vnfd.get("vnf-configuration")
1271 if vnf_config and vnf_config.get("juju"):
1272 native_charm = vnf_config["juju"].get("proxy") is False
1273
1274 if native_charm:
1275 if not vca_model_name:
1276 step = "creating VCA model name '{}'".format(nsr_id)
1277 self.logger.debug(logging_text + step)
1278 await self.n2vc.CreateNetworkService(nsr_id)
1279 vca_model_name = nsr_id
1280 db_nsr_update["_admin.deployed.VCA-model-name"] = nsr_id
1281 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1282 step = "deploying native charm for vnf_member_index={}".format(vnf_index)
1283 vnfr_params["rw_mgmt_ip"] = db_vnfrs[vnf_index]["ip-address"]
1284 charm_params = {
1285 "user_values": vnfr_params,
1286 "rw_mgmt_ip": db_vnfrs[vnf_index]["ip-address"],
1287 "initial-config-primitive": vnf_config.get('initial-config-primitive') or {},
1288 }
1289
1290 # get username
1291 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1292 # merged. Meanwhile let's get username from initial-config-primitive
1293 if vnf_config.get("initial-config-primitive"):
1294 for param in vnf_config["initial-config-primitive"][0].get("parameter", ()):
1295 if param["name"] == "ssh-username":
1296 charm_params["username"] = param["value"]
1297 if vnf_config.get("config-access") and vnf_config["config-access"].get("ssh-access"):
1298 if vnf_config["config-access"]["ssh-access"].get("required"):
1299 charm_params["username"] = vnf_config["config-access"]["ssh-access"].get("default-user")
1300
1301 # Login to the VCA. If there are multiple calls to login(),
1302 # subsequent calls will be a nop and return immediately.
1303 await self.n2vc.login()
1304
1305 deploy_charm(vnf_index, None, None, None, charm_params, n2vc_info, native_charm)
1306 number_to_configure += 1
1307
1308 # Deploy charms for each VDU that supports one.
1309 for vdu_index, vdu in enumerate(get_iterable(vnfd, 'vdu')):
1310 vdu_config = vdu.get('vdu-configuration')
1311 native_charm = False
1312
1313 if vdu_config and vdu_config.get("juju"):
1314 native_charm = vdu_config["juju"].get("proxy") is False
1315
1316 if native_charm:
1317 if not vca_model_name:
1318 step = "creating VCA model name"
1319 await self.n2vc.CreateNetworkService(nsr_id)
1320 vca_model_name = nsr_id
1321 db_nsr_update["_admin.deployed.VCA-model-name"] = nsr_id
1322 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1323 step = "deploying native charm for vnf_member_index={} vdu_id={}".format(vnf_index,
1324 vdu["id"])
1325 await self.n2vc.login()
1326 vdur = db_vnfrs[vnf_index]["vdur"][vdu_index]
1327 # TODO for the moment only first vdu_id contains a charm deployed
1328 if vdur["vdu-id-ref"] != vdu["id"]:
1329 raise LcmException("Mismatch vdur {}, vdu {} at index {} for vnf {}"
1330 .format(vdur["vdu-id-ref"], vdu["id"], vdu_index, vnf_index))
1331 vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
1332 charm_params = {
1333 "user_values": vnfr_params,
1334 "rw_mgmt_ip": vdur["ip-address"],
1335 "initial-config-primitive": vdu_config.get('initial-config-primitive') or {}
1336 }
1337
1338 # get username
1339 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1340 # merged. Meanwhile let's get username from initial-config-primitive
1341 if vdu_config.get("initial-config-primitive"):
1342 for param in vdu_config["initial-config-primitive"][0].get("parameter", ()):
1343 if param["name"] == "ssh-username":
1344 charm_params["username"] = param["value"]
1345 if vdu_config.get("config-access") and vdu_config["config-access"].get("ssh-access"):
1346 if vdu_config["config-access"]["ssh-access"].get("required"):
1347 charm_params["username"] = vdu_config["config-access"]["ssh-access"].get(
1348 "default-user")
1349
1350 deploy_charm(vnf_index, vdu["id"], vdur.get("name"), vdur["count-index"],
1351 charm_params, n2vc_info, native_charm)
1352 number_to_configure += 1
1353
1354 # Check if this NS has a charm configuration
1355
1356 ns_config = nsd.get("ns-configuration")
1357 if ns_config and ns_config.get("juju"):
1358 native_charm = ns_config["juju"].get("proxy") is False
1359
1360 if native_charm:
1361 step = "deploying native charm to configure ns"
1362 # TODO is NS magmt IP address needed?
1363
1364 # Get additional parameters
1365 additional_params = {}
1366 if db_nsr.get("additionalParamsForNs"):
1367 additional_params = db_nsr["additionalParamsForNs"].copy()
1368 for k, v in additional_params.items():
1369 if isinstance(v, str) and v.startswith("!!yaml "):
1370 additional_params[k] = yaml.safe_load(v[7:])
1371
1372 # additional_params["rw_mgmt_ip"] = db_nsr["ip-address"]
1373 charm_params = {
1374 "user_values": additional_params,
1375 "rw_mgmt_ip": db_nsr.get("ip-address"),
1376 "initial-config-primitive": ns_config.get('initial-config-primitive') or {}
1377 }
1378
1379 # get username
1380 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1381 # merged. Meanwhile let's get username from initial-config-primitive
1382 if ns_config.get("initial-config-primitive"):
1383 for param in ns_config["initial-config-primitive"][0].get("parameter", ()):
1384 if param["name"] == "ssh-username":
1385 charm_params["username"] = param["value"]
1386 if ns_config.get("config-access") and ns_config["config-access"].get("ssh-access"):
1387 if ns_config["config-access"]["ssh-access"].get("required"):
1388 charm_params["username"] = ns_config["config-access"]["ssh-access"].get("default-user")
1389
1390 # Login to the VCA. If there are multiple calls to login(),
1391 # subsequent calls will be a nop and return immediately.
1392 await self.n2vc.login()
1393 deploy_charm(None, None, None, None, charm_params, n2vc_info, native_charm)
1394 number_to_configure += 1
1395
1396 # waiting all charms are ok
1397 configuration_failed = False
1398 if number_to_configure:
1399 old_status = "configuring: init: {}".format(number_to_configure)
1400 db_nsr_update["config-status"] = old_status
1401 db_nsr_update["detailed-status"] = old_status
1402 db_nslcmop_update["detailed-status"] = old_status
1403
1404 # wait until all are configured.
1405 while time() <= start_deploy + self.total_deploy_timeout:
1406 if db_nsr_update:
1407 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1408 if db_nslcmop_update:
1409 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1410 # TODO add a fake task that set n2vc_event after some time
1411 await n2vc_info["n2vc_event"].wait()
1412 n2vc_info["n2vc_event"].clear()
1413 all_active = True
1414 status_map = {}
1415 n2vc_error_text = [] # contain text error list. If empty no one is in error status
1416 now = time()
1417 for vca_deployed in vca_deployed_list:
1418 vca_status = vca_deployed["operational-status"]
1419 if vca_status not in status_map:
1420 # Initialize it
1421 status_map[vca_status] = 0
1422 status_map[vca_status] += 1
1423
1424 if vca_status == "active":
1425 vca_deployed.pop("time_first_error", None)
1426 vca_deployed.pop("status_first_error", None)
1427 continue
1428
1429 all_active = False
1430 if vca_status in ("error", "blocked"):
1431 vca_deployed["detailed-status-error"] = vca_deployed["detailed-status"]
1432 # if not first time in this status error
1433 if not vca_deployed.get("time_first_error"):
1434 vca_deployed["time_first_error"] = now
1435 continue
1436 if vca_deployed.get("time_first_error") and \
1437 now <= vca_deployed["time_first_error"] + self.timeout_vca_on_error:
1438 n2vc_error_text.append("member_vnf_index={} vdu_id={} {}: {}"
1439 .format(vca_deployed["member-vnf-index"],
1440 vca_deployed["vdu_id"], vca_status,
1441 vca_deployed["detailed-status-error"]))
1442
1443 if all_active:
1444 break
1445 elif n2vc_error_text:
1446 db_nsr_update["config-status"] = "failed"
1447 error_text = "fail configuring " + ";".join(n2vc_error_text)
1448 db_nsr_update["detailed-status"] = error_text
1449 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED_TEMP"
1450 db_nslcmop_update["detailed-status"] = error_text
1451 db_nslcmop_update["statusEnteredTime"] = time()
1452 configuration_failed = True
1453 break
1454 else:
1455 cs = "configuring: "
1456 separator = ""
1457 for status, num in status_map.items():
1458 cs += separator + "{}: {}".format(status, num)
1459 separator = ", "
1460 if old_status != cs:
1461 db_nsr_update["config-status"] = cs
1462 db_nsr_update["detailed-status"] = cs
1463 db_nslcmop_update["detailed-status"] = cs
1464 old_status = cs
1465 else: # total_deploy_timeout
1466 raise LcmException("Timeout waiting ns to be configured")
1467
1468 if not configuration_failed:
1469 # all is done
1470 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
1471 db_nslcmop_update["statusEnteredTime"] = time()
1472 db_nslcmop_update["detailed-status"] = "done"
1473 db_nsr_update["config-status"] = "configured"
1474 db_nsr_update["detailed-status"] = "done"
1475
1476 return
1477
1478 except (ROclient.ROClientException, DbException, LcmException) as e:
1479 self.logger.error(logging_text + "Exit Exception while '{}': {}".format(step, e))
1480 exc = e
1481 except asyncio.CancelledError:
1482 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1483 exc = "Operation was cancelled"
1484 except Exception as e:
1485 exc = traceback.format_exc()
1486 self.logger.critical(logging_text + "Exit Exception {} while '{}': {}".format(type(e).__name__, step, e),
1487 exc_info=True)
1488 finally:
1489 if exc:
1490 if db_nsr:
1491 db_nsr_update["detailed-status"] = "ERROR {}: {}".format(step, exc)
1492 db_nsr_update["operational-status"] = "failed"
1493 if db_nslcmop:
1494 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
1495 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
1496 db_nslcmop_update["statusEnteredTime"] = time()
1497 try:
1498 if db_nsr:
1499 db_nsr_update["_admin.nslcmop"] = None
1500 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1501 if db_nslcmop_update:
1502 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1503 except DbException as e:
1504 self.logger.error(logging_text + "Cannot update database: {}".format(e))
1505 if nslcmop_operation_state:
1506 try:
1507 await self.msg.aiowrite("ns", "instantiated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
1508 "operationState": nslcmop_operation_state},
1509 loop=self.loop)
1510 except Exception as e:
1511 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1512
1513 self.logger.debug(logging_text + "Exit")
1514 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_instantiate")
1515
1516 async def _destroy_charm(self, model, application):
1517 """
1518 Order N2VC destroy a charm
1519 :param model:
1520 :param application:
1521 :return: True if charm does not exist. False if it exist
1522 """
1523 if not await self.n2vc.HasApplication(model, application):
1524 return True # Already removed
1525 await self.n2vc.RemoveCharms(model, application)
1526 return False
1527
1528 async def _wait_charm_destroyed(self, model, application, timeout):
1529 """
1530 Wait until charm does not exist
1531 :param model:
1532 :param application:
1533 :param timeout:
1534 :return: True if not exist, False if timeout
1535 """
1536 while True:
1537 if not await self.n2vc.HasApplication(model, application):
1538 return True
1539 if timeout < 0:
1540 return False
1541 await asyncio.sleep(10)
1542 timeout -= 10
1543
1544 # Check if this VNFD has a configured terminate action
1545 def _has_terminate_config_primitive(self, vnfd):
1546 vnf_config = vnfd.get("vnf-configuration")
1547 if vnf_config and vnf_config.get("terminate-config-primitive"):
1548 return True
1549 else:
1550 return False
1551
1552 # Get a numerically sorted list of the sequences for this VNFD's terminate action
1553 def _get_terminate_config_primitive_seq_list(self, vnfd):
1554 # No need to check for existing primitive twice, already done before
1555 vnf_config = vnfd.get("vnf-configuration")
1556 seq_list = vnf_config.get("terminate-config-primitive")
1557 # Get all 'seq' tags in seq_list, order sequences numerically, ascending.
1558 seq_list_sorted = sorted(seq_list, key=lambda x: int(x['seq']))
1559 return seq_list_sorted
1560
1561 @staticmethod
1562 def _create_nslcmop(nsr_id, operation, params):
1563 """
1564 Creates a ns-lcm-opp content to be stored at database.
1565 :param nsr_id: internal id of the instance
1566 :param operation: instantiate, terminate, scale, action, ...
1567 :param params: user parameters for the operation
1568 :return: dictionary following SOL005 format
1569 """
1570 # Raise exception if invalid arguments
1571 if not (nsr_id and operation and params):
1572 raise LcmException(
1573 "Parameters 'nsr_id', 'operation' and 'params' needed to create primitive not provided")
1574 now = time()
1575 _id = str(uuid4())
1576 nslcmop = {
1577 "id": _id,
1578 "_id": _id,
1579 # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1580 "operationState": "PROCESSING",
1581 "statusEnteredTime": now,
1582 "nsInstanceId": nsr_id,
1583 "lcmOperationType": operation,
1584 "startTime": now,
1585 "isAutomaticInvocation": False,
1586 "operationParams": params,
1587 "isCancelPending": False,
1588 "links": {
1589 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
1590 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
1591 }
1592 }
1593 return nslcmop
1594
1595 # Create a primitive with params from VNFD
1596 # - Called from terminate() before deleting instance
1597 # - Calls action() to execute the primitive
1598 async def _terminate_action(self, db_nslcmop, nslcmop_id, nsr_id):
1599 logging_text = "Task ns={} _terminate_action={} ".format(nsr_id, nslcmop_id)
1600 db_vnfds = {}
1601 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1602 # Loop over VNFRs
1603 for vnfr in db_vnfrs_list:
1604 vnfd_id = vnfr["vnfd-id"]
1605 vnf_index = vnfr["member-vnf-index-ref"]
1606 if vnfd_id not in db_vnfds:
1607 step = "Getting vnfd={} id='{}' from db".format(vnfd_id, vnfd_id)
1608 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
1609 db_vnfds[vnfd_id] = vnfd
1610 vnfd = db_vnfds[vnfd_id]
1611 if not self._has_terminate_config_primitive(vnfd):
1612 continue
1613 # Get the primitive's sorted sequence list
1614 seq_list = self._get_terminate_config_primitive_seq_list(vnfd)
1615 for seq in seq_list:
1616 # For each sequence in list, call terminate action
1617 step = "Calling terminate action for vnf_member_index={} primitive={}".format(
1618 vnf_index, seq.get("name"))
1619 self.logger.debug(logging_text + step)
1620 # Create the primitive for each sequence
1621 operation = "action"
1622 # primitive, i.e. "primitive": "touch"
1623 primitive = seq.get('name')
1624 primitive_params = {}
1625 params = {
1626 "member_vnf_index": vnf_index,
1627 "primitive": primitive,
1628 "primitive_params": primitive_params,
1629 }
1630 nslcmop_primitive = self._create_nslcmop(nsr_id, operation, params)
1631 # Get a copy of db_nslcmop 'admin' part
1632 db_nslcmop_action = {"_admin": deepcopy(db_nslcmop["_admin"])}
1633 # Update db_nslcmop with the primitive data
1634 db_nslcmop_action.update(nslcmop_primitive)
1635 # Create a new db entry for the created primitive, returns the new ID.
1636 # (The ID is normally obtained from Kafka.)
1637 nslcmop_terminate_action_id = self.db.create(
1638 "nslcmops", db_nslcmop_action)
1639 # Execute the primitive
1640 nslcmop_operation_state, nslcmop_operation_state_detail = await self.action(
1641 nsr_id, nslcmop_terminate_action_id)
1642 # Launch Exception if action() returns other than ['COMPLETED', 'PARTIALLY_COMPLETED']
1643 nslcmop_operation_states_ok = ['COMPLETED', 'PARTIALLY_COMPLETED']
1644 if nslcmop_operation_state not in nslcmop_operation_states_ok:
1645 raise LcmException(
1646 "terminate_primitive_action for vnf_member_index={}",
1647 " primitive={} fails with error {}".format(
1648 vnf_index, seq.get("name"), nslcmop_operation_state_detail))
1649
1650 async def terminate(self, nsr_id, nslcmop_id):
1651 logging_text = "Task ns={} terminate={} ".format(nsr_id, nslcmop_id)
1652 self.logger.debug(logging_text + "Enter")
1653 db_nsr = None
1654 db_nslcmop = None
1655 exc = None
1656 failed_detail = [] # annotates all failed error messages
1657 vca_time_destroy = None # time of where destroy charm order
1658 db_nsr_update = {"_admin.nslcmop": nslcmop_id}
1659 db_nslcmop_update = {}
1660 nslcmop_operation_state = None
1661 autoremove = False # autoremove after terminated
1662 try:
1663 step = "Getting nslcmop={} from db".format(nslcmop_id)
1664 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
1665 step = "Getting nsr={} from db".format(nsr_id)
1666 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1667 # nsd = db_nsr["nsd"]
1668 nsr_deployed = deepcopy(db_nsr["_admin"].get("deployed"))
1669 if db_nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
1670 return
1671 # #TODO check if VIM is creating and wait
1672 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
1673 # Call internal terminate action
1674 await self._terminate_action(db_nslcmop, nslcmop_id, nsr_id)
1675
1676 db_nsr_update["operational-status"] = "terminating"
1677 db_nsr_update["config-status"] = "terminating"
1678
1679 if nsr_deployed and nsr_deployed.get("VCA-model-name"):
1680 vca_model_name = nsr_deployed["VCA-model-name"]
1681 step = "deleting VCA model name '{}' and all charms".format(vca_model_name)
1682 self.logger.debug(logging_text + step)
1683 try:
1684 await self.n2vc.DestroyNetworkService(vca_model_name)
1685 except NetworkServiceDoesNotExist:
1686 pass
1687 db_nsr_update["_admin.deployed.VCA-model-name"] = None
1688 if nsr_deployed.get("VCA"):
1689 for vca_index in range(0, len(nsr_deployed["VCA"])):
1690 db_nsr_update["_admin.deployed.VCA.{}".format(vca_index)] = None
1691 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1692 # for backward compatibility if charm have been created with "default" model name delete one by one
1693 elif nsr_deployed and nsr_deployed.get("VCA"):
1694 try:
1695 step = "Scheduling configuration charms removing"
1696 db_nsr_update["detailed-status"] = "Deleting charms"
1697 self.logger.debug(logging_text + step)
1698 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1699 # for backward compatibility
1700 if isinstance(nsr_deployed["VCA"], dict):
1701 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
1702 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
1703 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1704
1705 for vca_index, vca_deployed in enumerate(nsr_deployed["VCA"]):
1706 if vca_deployed:
1707 if await self._destroy_charm(vca_deployed['model'], vca_deployed["application"]):
1708 vca_deployed.clear()
1709 db_nsr["_admin.deployed.VCA.{}".format(vca_index)] = None
1710 else:
1711 vca_time_destroy = time()
1712 except Exception as e:
1713 self.logger.debug(logging_text + "Failed while deleting charms: {}".format(e))
1714
1715 # remove from RO
1716 RO_fail = False
1717 RO = ROclient.ROClient(self.loop, **self.ro_config)
1718
1719 # Delete ns
1720 RO_nsr_id = RO_delete_action = None
1721 if nsr_deployed and nsr_deployed.get("RO"):
1722 RO_nsr_id = nsr_deployed["RO"].get("nsr_id")
1723 RO_delete_action = nsr_deployed["RO"].get("nsr_delete_action_id")
1724 try:
1725 if RO_nsr_id:
1726 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] = "Deleting ns at RO"
1727 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1728 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1729 self.logger.debug(logging_text + step)
1730 desc = await RO.delete("ns", RO_nsr_id)
1731 RO_delete_action = desc["action_id"]
1732 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = RO_delete_action
1733 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
1734 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
1735 if RO_delete_action:
1736 # wait until NS is deleted from VIM
1737 step = detailed_status = "Waiting ns deleted from VIM. RO_id={} RO_delete_action={}".\
1738 format(RO_nsr_id, RO_delete_action)
1739 detailed_status_old = None
1740 self.logger.debug(logging_text + step)
1741
1742 delete_timeout = 20 * 60 # 20 minutes
1743 while delete_timeout > 0:
1744 desc = await RO.show("ns", item_id_name=RO_nsr_id, extra_item="action",
1745 extra_item_id=RO_delete_action)
1746 ns_status, ns_status_info = RO.check_action_status(desc)
1747 if ns_status == "ERROR":
1748 raise ROclient.ROClientException(ns_status_info)
1749 elif ns_status == "BUILD":
1750 detailed_status = step + "; {}".format(ns_status_info)
1751 elif ns_status == "ACTIVE":
1752 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
1753 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
1754 break
1755 else:
1756 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
1757 if detailed_status != detailed_status_old:
1758 detailed_status_old = db_nslcmop_update["detailed-status"] = \
1759 db_nsr_update["detailed-status"] = detailed_status
1760 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1761 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1762 await asyncio.sleep(5, loop=self.loop)
1763 delete_timeout -= 5
1764 else: # delete_timeout <= 0:
1765 raise ROclient.ROClientException("Timeout waiting ns deleted from VIM")
1766
1767 except ROclient.ROClientException as e:
1768 if e.http_code == 404: # not found
1769 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
1770 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
1771 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
1772 self.logger.debug(logging_text + "RO_ns_id={} already deleted".format(RO_nsr_id))
1773 elif e.http_code == 409: # conflict
1774 failed_detail.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id, e))
1775 self.logger.debug(logging_text + failed_detail[-1])
1776 RO_fail = True
1777 else:
1778 failed_detail.append("RO_ns_id={} delete error: {}".format(RO_nsr_id, e))
1779 self.logger.error(logging_text + failed_detail[-1])
1780 RO_fail = True
1781
1782 # Delete nsd
1783 if not RO_fail and nsr_deployed and nsr_deployed.get("RO") and nsr_deployed["RO"].get("nsd_id"):
1784 RO_nsd_id = nsr_deployed["RO"]["nsd_id"]
1785 try:
1786 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
1787 "Deleting nsd at RO"
1788 await RO.delete("nsd", RO_nsd_id)
1789 self.logger.debug(logging_text + "RO_nsd_id={} deleted".format(RO_nsd_id))
1790 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
1791 except ROclient.ROClientException as e:
1792 if e.http_code == 404: # not found
1793 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
1794 self.logger.debug(logging_text + "RO_nsd_id={} already deleted".format(RO_nsd_id))
1795 elif e.http_code == 409: # conflict
1796 failed_detail.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id, e))
1797 self.logger.debug(logging_text + failed_detail[-1])
1798 RO_fail = True
1799 else:
1800 failed_detail.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id, e))
1801 self.logger.error(logging_text + failed_detail[-1])
1802 RO_fail = True
1803
1804 if not RO_fail and nsr_deployed and nsr_deployed.get("RO") and nsr_deployed["RO"].get("vnfd"):
1805 for index, vnf_deployed in enumerate(nsr_deployed["RO"]["vnfd"]):
1806 if not vnf_deployed or not vnf_deployed["id"]:
1807 continue
1808 try:
1809 RO_vnfd_id = vnf_deployed["id"]
1810 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
1811 "Deleting member_vnf_index={} RO_vnfd_id={} from RO".format(
1812 vnf_deployed["member-vnf-index"], RO_vnfd_id)
1813 await RO.delete("vnfd", RO_vnfd_id)
1814 self.logger.debug(logging_text + "RO_vnfd_id={} deleted".format(RO_vnfd_id))
1815 db_nsr_update["_admin.deployed.RO.vnfd.{}.id".format(index)] = None
1816 except ROclient.ROClientException as e:
1817 if e.http_code == 404: # not found
1818 db_nsr_update["_admin.deployed.RO.vnfd.{}.id".format(index)] = None
1819 self.logger.debug(logging_text + "RO_vnfd_id={} already deleted ".format(RO_vnfd_id))
1820 elif e.http_code == 409: # conflict
1821 failed_detail.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id, e))
1822 self.logger.debug(logging_text + failed_detail[-1])
1823 else:
1824 failed_detail.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id, e))
1825 self.logger.error(logging_text + failed_detail[-1])
1826
1827 # wait until charm deleted
1828 if vca_time_destroy:
1829 db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] = step = \
1830 "Waiting for deletion of configuration charms"
1831 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1832 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1833 for vca_index, vca_deployed in enumerate(nsr_deployed["VCA"]):
1834 if not vca_deployed:
1835 continue
1836 step = "Waiting for deletion of charm application_name={}".format(vca_deployed["application"])
1837 timeout = self.timeout_charm_delete - int(time() - vca_time_destroy)
1838 if not await self._wait_charm_destroyed(vca_deployed['model'], vca_deployed["application"],
1839 timeout):
1840 failed_detail.append("VCA[application_name={}] Deletion timeout".format(
1841 vca_deployed["application"]))
1842 else:
1843 db_nsr["_admin.deployed.VCA.{}".format(vca_index)] = None
1844
1845 if failed_detail:
1846 self.logger.error(logging_text + " ;".join(failed_detail))
1847 db_nsr_update["operational-status"] = "failed"
1848 db_nsr_update["detailed-status"] = "Deletion errors " + "; ".join(failed_detail)
1849 db_nslcmop_update["detailed-status"] = "; ".join(failed_detail)
1850 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
1851 db_nslcmop_update["statusEnteredTime"] = time()
1852 else:
1853 db_nsr_update["operational-status"] = "terminated"
1854 db_nsr_update["detailed-status"] = "Done"
1855 db_nsr_update["_admin.nsState"] = "NOT_INSTANTIATED"
1856 db_nslcmop_update["detailed-status"] = "Done"
1857 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
1858 db_nslcmop_update["statusEnteredTime"] = time()
1859 if db_nslcmop["operationParams"].get("autoremove"):
1860 autoremove = True
1861
1862 except (ROclient.ROClientException, DbException, LcmException) as e:
1863 self.logger.error(logging_text + "Exit Exception {}".format(e))
1864 exc = e
1865 except asyncio.CancelledError:
1866 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1867 exc = "Operation was cancelled"
1868 except Exception as e:
1869 exc = traceback.format_exc()
1870 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
1871 finally:
1872 if exc and db_nslcmop:
1873 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
1874 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
1875 db_nslcmop_update["statusEnteredTime"] = time()
1876 try:
1877 if db_nslcmop and db_nslcmop_update:
1878 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1879 if db_nsr:
1880 db_nsr_update["_admin.nslcmop"] = None
1881 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1882 except DbException as e:
1883 self.logger.error(logging_text + "Cannot update database: {}".format(e))
1884 if nslcmop_operation_state:
1885 try:
1886 await self.msg.aiowrite("ns", "terminated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
1887 "operationState": nslcmop_operation_state,
1888 "autoremove": autoremove},
1889 loop=self.loop)
1890 except Exception as e:
1891 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1892 self.logger.debug(logging_text + "Exit")
1893 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_terminate")
1894
1895 @staticmethod
1896 def _map_primitive_params(primitive_desc, params, instantiation_params):
1897 """
1898 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
1899 The default-value is used. If it is between < > it look for a value at instantiation_params
1900 :param primitive_desc: portion of VNFD/NSD that describes primitive
1901 :param params: Params provided by user
1902 :param instantiation_params: Instantiation params provided by user
1903 :return: a dictionary with the calculated params
1904 """
1905 calculated_params = {}
1906 for parameter in primitive_desc.get("parameter", ()):
1907 param_name = parameter["name"]
1908 if param_name in params:
1909 calculated_params[param_name] = params[param_name]
1910 elif "default-value" in parameter or "value" in parameter:
1911 if "value" in parameter:
1912 calculated_params[param_name] = parameter["value"]
1913 else:
1914 calculated_params[param_name] = parameter["default-value"]
1915 if isinstance(calculated_params[param_name], str) and calculated_params[param_name].startswith("<") \
1916 and calculated_params[param_name].endswith(">"):
1917 if calculated_params[param_name][1:-1] in instantiation_params:
1918 calculated_params[param_name] = instantiation_params[calculated_params[param_name][1:-1]]
1919 else:
1920 raise LcmException("Parameter {} needed to execute primitive {} not provided".
1921 format(parameter["default-value"], primitive_desc["name"]))
1922 else:
1923 raise LcmException("Parameter {} needed to execute primitive {} not provided".
1924 format(param_name, primitive_desc["name"]))
1925
1926 if isinstance(calculated_params[param_name], (dict, list, tuple)):
1927 calculated_params[param_name] = yaml.safe_dump(calculated_params[param_name], default_flow_style=True,
1928 width=256)
1929 elif isinstance(calculated_params[param_name], str) and calculated_params[param_name].startswith("!!yaml "):
1930 calculated_params[param_name] = calculated_params[param_name][7:]
1931 return calculated_params
1932
1933 async def _ns_execute_primitive(self, db_deployed, member_vnf_index, vdu_id, vdu_name, vdu_count_index,
1934 primitive, primitive_params, retries=0, retries_interval=30):
1935 start_primitive_time = time()
1936 try:
1937 for vca_deployed in db_deployed["VCA"]:
1938 if not vca_deployed:
1939 continue
1940 if member_vnf_index != vca_deployed["member-vnf-index"] or vdu_id != vca_deployed["vdu_id"]:
1941 continue
1942 if vdu_name and vdu_name != vca_deployed["vdu_name"]:
1943 continue
1944 if vdu_count_index and vdu_count_index != vca_deployed["vdu_count_index"]:
1945 continue
1946 break
1947 else:
1948 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} is not "
1949 "deployed".format(member_vnf_index, vdu_id, vdu_name, vdu_count_index))
1950 model_name = vca_deployed.get("model")
1951 application_name = vca_deployed.get("application")
1952 if not model_name or not application_name:
1953 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} has not "
1954 "model or application name" .format(member_vnf_index, vdu_id, vdu_name,
1955 vdu_count_index))
1956 # if vca_deployed["operational-status"] != "active":
1957 # raise LcmException("charm for member_vnf_index={} vdu_id={} operational_status={} not 'active'".format(
1958 # member_vnf_index, vdu_id, vca_deployed["operational-status"]))
1959 callback = None # self.n2vc_callback
1960 callback_args = () # [db_nsr, db_nslcmop, member_vnf_index, None]
1961 await self.n2vc.login()
1962 if primitive == "config":
1963 primitive_params = {"params": primitive_params}
1964 while retries >= 0:
1965 primitive_id = await self.n2vc.ExecutePrimitive(
1966 model_name,
1967 application_name,
1968 primitive,
1969 callback,
1970 *callback_args,
1971 **primitive_params
1972 )
1973 while time() - start_primitive_time < self.timeout_primitive:
1974 primitive_result_ = await self.n2vc.GetPrimitiveStatus(model_name, primitive_id)
1975 if primitive_result_ in ("completed", "failed"):
1976 primitive_result = "COMPLETED" if primitive_result_ == "completed" else "FAILED"
1977 detailed_result = await self.n2vc.GetPrimitiveOutput(model_name, primitive_id)
1978 break
1979 elif primitive_result_ is None and primitive == "config":
1980 primitive_result = "COMPLETED"
1981 detailed_result = None
1982 break
1983 else: # ("running", "pending", None):
1984 pass
1985 await asyncio.sleep(5)
1986 else:
1987 raise LcmException("timeout after {} seconds".format(self.timeout_primitive))
1988 if primitive_result == "COMPLETED":
1989 break
1990 retries -= 1
1991 if retries >= 0:
1992 await asyncio.sleep(retries_interval)
1993
1994 return primitive_result, detailed_result
1995 except (N2VCPrimitiveExecutionFailed, LcmException) as e:
1996 return "FAILED", str(e)
1997
1998 async def action(self, nsr_id, nslcmop_id):
1999 logging_text = "Task ns={} action={} ".format(nsr_id, nslcmop_id)
2000 self.logger.debug(logging_text + "Enter")
2001 # get all needed from database
2002 db_nsr = None
2003 db_nslcmop = None
2004 db_nsr_update = {"_admin.nslcmop": nslcmop_id}
2005 db_nslcmop_update = {}
2006 nslcmop_operation_state = None
2007 nslcmop_operation_state_detail = None
2008 exc = None
2009 try:
2010 step = "Getting information from database"
2011 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
2012 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2013
2014 nsr_deployed = db_nsr["_admin"].get("deployed")
2015 vnf_index = db_nslcmop["operationParams"].get("member_vnf_index")
2016 vdu_id = db_nslcmop["operationParams"].get("vdu_id")
2017 vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
2018 vdu_name = db_nslcmop["operationParams"].get("vdu_name")
2019
2020 if vnf_index:
2021 step = "Getting vnfr from database"
2022 db_vnfr = self.db.get_one("vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id})
2023 step = "Getting vnfd from database"
2024 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
2025 else:
2026 if db_nsr.get("nsd"):
2027 db_nsd = db_nsr.get("nsd") # TODO this will be removed
2028 else:
2029 step = "Getting nsd from database"
2030 db_nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
2031
2032 # look if previous tasks in process
2033 task_name, task_dependency = self.lcm_tasks.lookfor_related("ns", nsr_id, nslcmop_id)
2034 if task_dependency:
2035 step = db_nslcmop_update["detailed-status"] = \
2036 "Waiting for related tasks to be completed: {}".format(task_name)
2037 self.logger.debug(logging_text + step)
2038 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
2039 _, pending = await asyncio.wait(task_dependency, timeout=3600)
2040 if pending:
2041 raise LcmException("Timeout waiting related tasks to be completed")
2042
2043 # for backward compatibility
2044 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
2045 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
2046 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
2047 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2048
2049 primitive = db_nslcmop["operationParams"]["primitive"]
2050 primitive_params = db_nslcmop["operationParams"]["primitive_params"]
2051
2052 # look for primitive
2053 config_primitive_desc = None
2054 if vdu_id:
2055 for vdu in get_iterable(db_vnfd, "vdu"):
2056 if vdu_id == vdu["id"]:
2057 for config_primitive in vdu.get("vdu-configuration", {}).get("config-primitive", ()):
2058 if config_primitive["name"] == primitive:
2059 config_primitive_desc = config_primitive
2060 break
2061 elif vnf_index:
2062 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
2063 if config_primitive["name"] == primitive:
2064 config_primitive_desc = config_primitive
2065 break
2066 else:
2067 for config_primitive in db_nsd.get("ns-configuration", {}).get("config-primitive", ()):
2068 if config_primitive["name"] == primitive:
2069 config_primitive_desc = config_primitive
2070 break
2071
2072 if not config_primitive_desc:
2073 raise LcmException("Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".
2074 format(primitive))
2075
2076 desc_params = {}
2077 if vnf_index:
2078 if db_vnfr.get("additionalParamsForVnf"):
2079 desc_params.update(db_vnfr["additionalParamsForVnf"])
2080 else:
2081 if db_nsr.get("additionalParamsForVnf"):
2082 desc_params.update(db_nsr["additionalParamsForNs"])
2083
2084 # TODO check if ns is in a proper status
2085 result, result_detail = await self._ns_execute_primitive(
2086 nsr_deployed, vnf_index, vdu_id, vdu_name, vdu_count_index, primitive,
2087 self._map_primitive_params(config_primitive_desc, primitive_params, desc_params))
2088 db_nslcmop_update["detailed-status"] = nslcmop_operation_state_detail = result_detail
2089 db_nslcmop_update["operationState"] = nslcmop_operation_state = result
2090 db_nslcmop_update["statusEnteredTime"] = time()
2091 self.logger.debug(logging_text + " task Done with result {} {}".format(result, result_detail))
2092 return # database update is called inside finally
2093
2094 except (DbException, LcmException) as e:
2095 self.logger.error(logging_text + "Exit Exception {}".format(e))
2096 exc = e
2097 except asyncio.CancelledError:
2098 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
2099 exc = "Operation was cancelled"
2100 except Exception as e:
2101 exc = traceback.format_exc()
2102 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
2103 finally:
2104 if exc and db_nslcmop:
2105 db_nslcmop_update["detailed-status"] = nslcmop_operation_state_detail = \
2106 "FAILED {}: {}".format(step, exc)
2107 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
2108 db_nslcmop_update["statusEnteredTime"] = time()
2109 try:
2110 if db_nslcmop_update:
2111 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
2112 if db_nsr:
2113 db_nsr_update["_admin.nslcmop"] = None
2114 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2115 except DbException as e:
2116 self.logger.error(logging_text + "Cannot update database: {}".format(e))
2117 self.logger.debug(logging_text + "Exit")
2118 if nslcmop_operation_state:
2119 try:
2120 await self.msg.aiowrite("ns", "actioned", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
2121 "operationState": nslcmop_operation_state},
2122 loop=self.loop)
2123 except Exception as e:
2124 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
2125 self.logger.debug(logging_text + "Exit")
2126 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_action")
2127 return nslcmop_operation_state, nslcmop_operation_state_detail
2128
2129 async def scale(self, nsr_id, nslcmop_id):
2130 logging_text = "Task ns={} scale={} ".format(nsr_id, nslcmop_id)
2131 self.logger.debug(logging_text + "Enter")
2132 # get all needed from database
2133 db_nsr = None
2134 db_nslcmop = None
2135 db_nslcmop_update = {}
2136 nslcmop_operation_state = None
2137 db_nsr_update = {"_admin.nslcmop": nslcmop_id}
2138 exc = None
2139 # in case of error, indicates what part of scale was failed to put nsr at error status
2140 scale_process = None
2141 old_operational_status = ""
2142 old_config_status = ""
2143 vnfr_scaled = False
2144 try:
2145 # look if previous tasks in process
2146 task_name, task_dependency = self.lcm_tasks.lookfor_related("ns", nsr_id, nslcmop_id)
2147 if task_dependency:
2148 step = db_nslcmop_update["detailed-status"] = \
2149 "Waiting for related tasks to be completed: {}".format(task_name)
2150 self.logger.debug(logging_text + step)
2151 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
2152 _, pending = await asyncio.wait(task_dependency, timeout=3600)
2153 if pending:
2154 raise LcmException("Timeout waiting related tasks to be completed")
2155
2156 step = "Getting nslcmop from database"
2157 self.logger.debug(step + " after having waited for previous tasks to be completed")
2158 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
2159 step = "Getting nsr from database"
2160 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2161
2162 old_operational_status = db_nsr["operational-status"]
2163 old_config_status = db_nsr["config-status"]
2164 step = "Parsing scaling parameters"
2165 # self.logger.debug(step)
2166 db_nsr_update["operational-status"] = "scaling"
2167 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2168 nsr_deployed = db_nsr["_admin"].get("deployed")
2169 RO_nsr_id = nsr_deployed["RO"]["nsr_id"]
2170 vnf_index = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
2171 scaling_group = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
2172 scaling_type = db_nslcmop["operationParams"]["scaleVnfData"]["scaleVnfType"]
2173 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
2174
2175 # for backward compatibility
2176 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
2177 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
2178 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
2179 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2180
2181 step = "Getting vnfr from database"
2182 db_vnfr = self.db.get_one("vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id})
2183 step = "Getting vnfd from database"
2184 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
2185
2186 step = "Getting scaling-group-descriptor"
2187 for scaling_descriptor in db_vnfd["scaling-group-descriptor"]:
2188 if scaling_descriptor["name"] == scaling_group:
2189 break
2190 else:
2191 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
2192 "at vnfd:scaling-group-descriptor".format(scaling_group))
2193
2194 # cooldown_time = 0
2195 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
2196 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
2197 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
2198 # break
2199
2200 # TODO check if ns is in a proper status
2201 step = "Sending scale order to RO"
2202 nb_scale_op = 0
2203 if not db_nsr["_admin"].get("scaling-group"):
2204 self.update_db_2("nsrs", nsr_id, {"_admin.scaling-group": [{"name": scaling_group, "nb-scale-op": 0}]})
2205 admin_scale_index = 0
2206 else:
2207 for admin_scale_index, admin_scale_info in enumerate(db_nsr["_admin"]["scaling-group"]):
2208 if admin_scale_info["name"] == scaling_group:
2209 nb_scale_op = admin_scale_info.get("nb-scale-op", 0)
2210 break
2211 else: # not found, set index one plus last element and add new entry with the name
2212 admin_scale_index += 1
2213 db_nsr_update["_admin.scaling-group.{}.name".format(admin_scale_index)] = scaling_group
2214 RO_scaling_info = []
2215 vdu_scaling_info = {"scaling_group_name": scaling_group, "vdu": []}
2216 if scaling_type == "SCALE_OUT":
2217 # count if max-instance-count is reached
2218 if "max-instance-count" in scaling_descriptor and scaling_descriptor["max-instance-count"] is not None:
2219 max_instance_count = int(scaling_descriptor["max-instance-count"])
2220
2221 # self.logger.debug("MAX_INSTANCE_COUNT is {}".format(scaling_descriptor["max-instance-count"]))
2222 if nb_scale_op >= max_instance_count:
2223 raise LcmException("reached the limit of {} (max-instance-count) "
2224 "scaling-out operations for the "
2225 "scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group))
2226
2227 nb_scale_op += 1
2228 vdu_scaling_info["scaling_direction"] = "OUT"
2229 vdu_scaling_info["vdu-create"] = {}
2230 for vdu_scale_info in scaling_descriptor["vdu"]:
2231 RO_scaling_info.append({"osm_vdu_id": vdu_scale_info["vdu-id-ref"], "member-vnf-index": vnf_index,
2232 "type": "create", "count": vdu_scale_info.get("count", 1)})
2233 vdu_scaling_info["vdu-create"][vdu_scale_info["vdu-id-ref"]] = vdu_scale_info.get("count", 1)
2234
2235 elif scaling_type == "SCALE_IN":
2236 # count if min-instance-count is reached
2237 min_instance_count = 0
2238 if "min-instance-count" in scaling_descriptor and scaling_descriptor["min-instance-count"] is not None:
2239 min_instance_count = int(scaling_descriptor["min-instance-count"])
2240 if nb_scale_op <= min_instance_count:
2241 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
2242 "scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group))
2243 nb_scale_op -= 1
2244 vdu_scaling_info["scaling_direction"] = "IN"
2245 vdu_scaling_info["vdu-delete"] = {}
2246 for vdu_scale_info in scaling_descriptor["vdu"]:
2247 RO_scaling_info.append({"osm_vdu_id": vdu_scale_info["vdu-id-ref"], "member-vnf-index": vnf_index,
2248 "type": "delete", "count": vdu_scale_info.get("count", 1)})
2249 vdu_scaling_info["vdu-delete"][vdu_scale_info["vdu-id-ref"]] = vdu_scale_info.get("count", 1)
2250
2251 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
2252 vdu_create = vdu_scaling_info.get("vdu-create")
2253 vdu_delete = copy(vdu_scaling_info.get("vdu-delete"))
2254 if vdu_scaling_info["scaling_direction"] == "IN":
2255 for vdur in reversed(db_vnfr["vdur"]):
2256 if vdu_delete.get(vdur["vdu-id-ref"]):
2257 vdu_delete[vdur["vdu-id-ref"]] -= 1
2258 vdu_scaling_info["vdu"].append({
2259 "name": vdur["name"],
2260 "vdu_id": vdur["vdu-id-ref"],
2261 "interface": []
2262 })
2263 for interface in vdur["interfaces"]:
2264 vdu_scaling_info["vdu"][-1]["interface"].append({
2265 "name": interface["name"],
2266 "ip_address": interface["ip-address"],
2267 "mac_address": interface.get("mac-address"),
2268 })
2269 vdu_delete = vdu_scaling_info.pop("vdu-delete")
2270
2271 # execute primitive service PRE-SCALING
2272 step = "Executing pre-scale vnf-config-primitive"
2273 if scaling_descriptor.get("scaling-config-action"):
2274 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
2275 if scaling_config_action.get("trigger") and scaling_config_action["trigger"] == "pre-scale-in" \
2276 and scaling_type == "SCALE_IN":
2277 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
2278 step = db_nslcmop_update["detailed-status"] = \
2279 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive)
2280
2281 # look for primitive
2282 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
2283 if config_primitive["name"] == vnf_config_primitive:
2284 break
2285 else:
2286 raise LcmException(
2287 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
2288 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
2289 "primitive".format(scaling_group, config_primitive))
2290
2291 vnfr_params = {"VDU_SCALE_INFO": vdu_scaling_info}
2292 if db_vnfr.get("additionalParamsForVnf"):
2293 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
2294
2295 scale_process = "VCA"
2296 db_nsr_update["config-status"] = "configuring pre-scaling"
2297 result, result_detail = await self._ns_execute_primitive(
2298 nsr_deployed, vnf_index, None, None, None, vnf_config_primitive,
2299 self._map_primitive_params(config_primitive, {}, vnfr_params))
2300 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
2301 vnf_config_primitive, result, result_detail))
2302 if result == "FAILED":
2303 raise LcmException(result_detail)
2304 db_nsr_update["config-status"] = old_config_status
2305 scale_process = None
2306
2307 if RO_scaling_info:
2308 scale_process = "RO"
2309 RO = ROclient.ROClient(self.loop, **self.ro_config)
2310 RO_desc = await RO.create_action("ns", RO_nsr_id, {"vdu-scaling": RO_scaling_info})
2311 db_nsr_update["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index)] = nb_scale_op
2312 db_nsr_update["_admin.scaling-group.{}.time".format(admin_scale_index)] = time()
2313 # wait until ready
2314 RO_nslcmop_id = RO_desc["instance_action_id"]
2315 db_nslcmop_update["_admin.deploy.RO"] = RO_nslcmop_id
2316
2317 RO_task_done = False
2318 step = detailed_status = "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id)
2319 detailed_status_old = None
2320 self.logger.debug(logging_text + step)
2321
2322 deployment_timeout = 1 * 3600 # One hour
2323 while deployment_timeout > 0:
2324 if not RO_task_done:
2325 desc = await RO.show("ns", item_id_name=RO_nsr_id, extra_item="action",
2326 extra_item_id=RO_nslcmop_id)
2327 ns_status, ns_status_info = RO.check_action_status(desc)
2328 if ns_status == "ERROR":
2329 raise ROclient.ROClientException(ns_status_info)
2330 elif ns_status == "BUILD":
2331 detailed_status = step + "; {}".format(ns_status_info)
2332 elif ns_status == "ACTIVE":
2333 RO_task_done = True
2334 step = detailed_status = "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id)
2335 self.logger.debug(logging_text + step)
2336 else:
2337 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
2338 else:
2339 desc = await RO.show("ns", RO_nsr_id)
2340 ns_status, ns_status_info = RO.check_ns_status(desc)
2341 if ns_status == "ERROR":
2342 raise ROclient.ROClientException(ns_status_info)
2343 elif ns_status == "BUILD":
2344 detailed_status = step + "; {}".format(ns_status_info)
2345 elif ns_status == "ACTIVE":
2346 step = detailed_status = \
2347 "Waiting for management IP address reported by the VIM. Updating VNFRs"
2348 if not vnfr_scaled:
2349 self.scale_vnfr(db_vnfr, vdu_create=vdu_create, vdu_delete=vdu_delete)
2350 vnfr_scaled = True
2351 try:
2352 desc = await RO.show("ns", RO_nsr_id)
2353 # nsr_deployed["nsr_ip"] = RO.get_ns_vnf_info(desc)
2354 self.ns_update_vnfr({db_vnfr["member-vnf-index-ref"]: db_vnfr}, desc)
2355 break
2356 except LcmExceptionNoMgmtIP:
2357 pass
2358 else:
2359 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
2360 if detailed_status != detailed_status_old:
2361 detailed_status_old = db_nslcmop_update["detailed-status"] = detailed_status
2362 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
2363
2364 await asyncio.sleep(5, loop=self.loop)
2365 deployment_timeout -= 5
2366 if deployment_timeout <= 0:
2367 raise ROclient.ROClientException("Timeout waiting ns to be ready")
2368
2369 # update VDU_SCALING_INFO with the obtained ip_addresses
2370 if vdu_scaling_info["scaling_direction"] == "OUT":
2371 for vdur in reversed(db_vnfr["vdur"]):
2372 if vdu_scaling_info["vdu-create"].get(vdur["vdu-id-ref"]):
2373 vdu_scaling_info["vdu-create"][vdur["vdu-id-ref"]] -= 1
2374 vdu_scaling_info["vdu"].append({
2375 "name": vdur["name"],
2376 "vdu_id": vdur["vdu-id-ref"],
2377 "interface": []
2378 })
2379 for interface in vdur["interfaces"]:
2380 vdu_scaling_info["vdu"][-1]["interface"].append({
2381 "name": interface["name"],
2382 "ip_address": interface["ip-address"],
2383 "mac_address": interface.get("mac-address"),
2384 })
2385 del vdu_scaling_info["vdu-create"]
2386
2387 scale_process = None
2388 if db_nsr_update:
2389 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2390
2391 # execute primitive service POST-SCALING
2392 step = "Executing post-scale vnf-config-primitive"
2393 if scaling_descriptor.get("scaling-config-action"):
2394 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
2395 if scaling_config_action.get("trigger") and scaling_config_action["trigger"] == "post-scale-out" \
2396 and scaling_type == "SCALE_OUT":
2397 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
2398 step = db_nslcmop_update["detailed-status"] = \
2399 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive)
2400
2401 vnfr_params = {"VDU_SCALE_INFO": vdu_scaling_info}
2402 if db_vnfr.get("additionalParamsForVnf"):
2403 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
2404
2405 # look for primitive
2406 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
2407 if config_primitive["name"] == vnf_config_primitive:
2408 break
2409 else:
2410 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
2411 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
2412 "match any vnf-configuration:config-primitive".format(scaling_group,
2413 config_primitive))
2414 scale_process = "VCA"
2415 db_nsr_update["config-status"] = "configuring post-scaling"
2416
2417 result, result_detail = await self._ns_execute_primitive(
2418 nsr_deployed, vnf_index, None, None, None, vnf_config_primitive,
2419 self._map_primitive_params(config_primitive, {}, vnfr_params))
2420 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
2421 vnf_config_primitive, result, result_detail))
2422 if result == "FAILED":
2423 raise LcmException(result_detail)
2424 db_nsr_update["config-status"] = old_config_status
2425 scale_process = None
2426
2427 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
2428 db_nslcmop_update["statusEnteredTime"] = time()
2429 db_nslcmop_update["detailed-status"] = "done"
2430 db_nsr_update["detailed-status"] = "" # "scaled {} {}".format(scaling_group, scaling_type)
2431 db_nsr_update["operational-status"] = "running" if old_operational_status == "failed" \
2432 else old_operational_status
2433 db_nsr_update["config-status"] = old_config_status
2434 return
2435 except (ROclient.ROClientException, DbException, LcmException) as e:
2436 self.logger.error(logging_text + "Exit Exception {}".format(e))
2437 exc = e
2438 except asyncio.CancelledError:
2439 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
2440 exc = "Operation was cancelled"
2441 except Exception as e:
2442 exc = traceback.format_exc()
2443 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
2444 finally:
2445 if exc:
2446 if db_nslcmop:
2447 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
2448 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
2449 db_nslcmop_update["statusEnteredTime"] = time()
2450 if db_nsr:
2451 db_nsr_update["operational-status"] = old_operational_status
2452 db_nsr_update["config-status"] = old_config_status
2453 db_nsr_update["detailed-status"] = ""
2454 db_nsr_update["_admin.nslcmop"] = None
2455 if scale_process:
2456 if "VCA" in scale_process:
2457 db_nsr_update["config-status"] = "failed"
2458 if "RO" in scale_process:
2459 db_nsr_update["operational-status"] = "failed"
2460 db_nsr_update["detailed-status"] = "FAILED scaling nslcmop={} {}: {}".format(nslcmop_id, step,
2461 exc)
2462 try:
2463 if db_nslcmop and db_nslcmop_update:
2464 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
2465 if db_nsr:
2466 db_nsr_update["_admin.nslcmop"] = None
2467 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2468 except DbException as e:
2469 self.logger.error(logging_text + "Cannot update database: {}".format(e))
2470 if nslcmop_operation_state:
2471 try:
2472 await self.msg.aiowrite("ns", "scaled", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
2473 "operationState": nslcmop_operation_state},
2474 loop=self.loop)
2475 # if cooldown_time:
2476 # await asyncio.sleep(cooldown_time)
2477 # await self.msg.aiowrite("ns","scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
2478 except Exception as e:
2479 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
2480 self.logger.debug(logging_text + "Exit")
2481 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_scale")