c5aef180dd29fd555256c1b55f293e217fa6827e
[osm/LCM.git] / osm_lcm / ns.py
1 #!/usr/bin/python3
2 # -*- coding: utf-8 -*-
3
4 import asyncio
5 import yaml
6 import logging
7 import logging.handlers
8 import functools
9 import traceback
10
11 import ROclient
12 from lcm_utils import LcmException, LcmBase
13
14 from osm_common.dbbase import DbException, deep_update
15 from osm_common.fsbase import FsException
16 from n2vc.vnf import N2VC
17
18 from copy import deepcopy
19 from http import HTTPStatus
20 from time import time
21
22
23 __author__ = "Alfonso Tierno"
24
25
26 class NsLcm(LcmBase):
27
28 def __init__(self, db, msg, fs, lcm_tasks, ro_config, vca_config, loop):
29 """
30 Init, Connect to database, filesystem storage, and messaging
31 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
32 :return: None
33 """
34 # logging
35 self.logger = logging.getLogger('lcm.ns')
36 self.loop = loop
37 self.lcm_tasks = lcm_tasks
38
39 super().__init__(db, msg, fs, self.logger)
40
41 self.ro_config = ro_config
42
43 self.n2vc = N2VC(
44 log=self.logger,
45 server=vca_config['host'],
46 port=vca_config['port'],
47 user=vca_config['user'],
48 secret=vca_config['secret'],
49 # TODO: This should point to the base folder where charms are stored,
50 # if there is a common one (like object storage). Otherwise, leave
51 # it unset and pass it via DeployCharms
52 # artifacts=vca_config[''],
53 artifacts=None,
54 )
55
56 def vnfd2RO(self, vnfd, new_id=None):
57 """
58 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
59 :param vnfd: input vnfd
60 :param new_id: overrides vnf id if provided
61 :return: copy of vnfd
62 """
63 ci_file = None
64 try:
65 vnfd_RO = deepcopy(vnfd)
66 vnfd_RO.pop("_id", None)
67 vnfd_RO.pop("_admin", None)
68 if new_id:
69 vnfd_RO["id"] = new_id
70 for vdu in vnfd_RO["vdu"]:
71 if "cloud-init-file" in vdu:
72 base_folder = vnfd["_admin"]["storage"]
73 clout_init_file = "{}/{}/cloud_init/{}".format(
74 base_folder["folder"],
75 base_folder["pkg-dir"],
76 vdu["cloud-init-file"]
77 )
78 ci_file = self.fs.file_open(clout_init_file, "r")
79 # TODO: detect if binary or text. Propose to read as binary and try to decode to utf8. If fails
80 # convert to base 64 or similar
81 clout_init_content = ci_file.read()
82 ci_file.close()
83 ci_file = None
84 vdu.pop("cloud-init-file", None)
85 vdu["cloud-init"] = clout_init_content
86 # remnove unused by RO configuration, monitoring, scaling
87 vnfd_RO.pop("vnf-configuration", None)
88 vnfd_RO.pop("monitoring-param", None)
89 vnfd_RO.pop("scaling-group-descriptor", None)
90 return vnfd_RO
91 except FsException as e:
92 raise LcmException("Error reading file at vnfd {}: {} ".format(vnfd["_id"], e))
93 finally:
94 if ci_file:
95 ci_file.close()
96
97 def n2vc_callback(self, model_name, application_name, status, message, n2vc_info, task=None):
98 """
99 Callback both for charm status change and task completion
100 :param model_name: Charm model name
101 :param application_name: Charm application name
102 :param status: Can be
103 - blocked: The unit needs manual intervention
104 - maintenance: The unit is actively deploying/configuring
105 - waiting: The unit is waiting for another charm to be ready
106 - active: The unit is deployed, configured, and ready
107 - error: The charm has failed and needs attention.
108 - terminated: The charm has been destroyed
109 - removing,
110 - removed
111 :param message: detailed message error
112 :param n2vc_info dictionary with information shared with instantiate task. Contains:
113 nsr_id:
114 nslcmop_id:
115 lcmOperationType: currently "instantiate"
116 deployed: dictionary with {<application>: {operational-status: <status>, detailed-status: <text>}}
117 db_update: dictionary to be filled with the changes to be wrote to database with format key.key.key: value
118 n2vc_event: event used to notify instantiation task that some change has been produced
119 :param task: None for charm status change, or task for completion task callback
120 :return:
121 """
122 try:
123 nsr_id = n2vc_info["nsr_id"]
124 deployed = n2vc_info["deployed"]
125 db_nsr_update = n2vc_info["db_update"]
126 nslcmop_id = n2vc_info["nslcmop_id"]
127 ns_operation = n2vc_info["lcmOperationType"]
128 n2vc_event = n2vc_info["n2vc_event"]
129 logging_text = "Task ns={} {}={} [n2vc_callback] application={}".format(nsr_id, ns_operation, nslcmop_id,
130 application_name)
131 vca_deployed = deployed.get(application_name)
132 if not vca_deployed:
133 self.logger.error(logging_text + " Not present at nsr._admin.deployed.VCA")
134 return
135
136 if task:
137 if task.cancelled():
138 self.logger.debug(logging_text + " task Cancelled")
139 vca_deployed['operational-status'] = "error"
140 db_nsr_update["_admin.deployed.VCA.{}.operational-status".format(application_name)] = "error"
141 vca_deployed['detailed-status'] = "Task Cancelled"
142 db_nsr_update["_admin.deployed.VCA.{}.detailed-status".format(application_name)] = "Task Cancelled"
143
144 elif task.done():
145 exc = task.exception()
146 if exc:
147 self.logger.error(logging_text + " task Exception={}".format(exc))
148 vca_deployed['operational-status'] = "error"
149 db_nsr_update["_admin.deployed.VCA.{}.operational-status".format(application_name)] = "error"
150 vca_deployed['detailed-status'] = str(exc)
151 db_nsr_update["_admin.deployed.VCA.{}.detailed-status".format(application_name)] = str(exc)
152 else:
153 self.logger.debug(logging_text + " task Done")
154 # task is Done, but callback is still ongoing. So ignore
155 return
156 elif status:
157 self.logger.debug(logging_text + " Enter status={}".format(status))
158 if vca_deployed['operational-status'] == status:
159 return # same status, ignore
160 vca_deployed['operational-status'] = status
161 db_nsr_update["_admin.deployed.VCA.{}.operational-status".format(application_name)] = status
162 vca_deployed['detailed-status'] = str(message)
163 db_nsr_update["_admin.deployed.VCA.{}.detailed-status".format(application_name)] = str(message)
164 else:
165 self.logger.critical(logging_text + " Enter with bad parameters", exc_info=True)
166 return
167 # wake up instantiate task
168 n2vc_event.set()
169 except Exception as e:
170 self.logger.critical(logging_text + " Exception {}".format(e), exc_info=True)
171
172 def ns_params_2_RO(self, ns_params, nsd, vnfd_dict):
173 """
174 Creates a RO ns descriptor from OSM ns_instantite params
175 :param ns_params: OSM instantiate params
176 :return: The RO ns descriptor
177 """
178 vim_2_RO = {}
179
180 def vim_account_2_RO(vim_account):
181 if vim_account in vim_2_RO:
182 return vim_2_RO[vim_account]
183
184 db_vim = self.db.get_one("vim_accounts", {"_id": vim_account})
185 if db_vim["_admin"]["operationalState"] != "ENABLED":
186 raise LcmException("VIM={} is not available. operationalState={}".format(
187 vim_account, db_vim["_admin"]["operationalState"]))
188 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
189 vim_2_RO[vim_account] = RO_vim_id
190 return RO_vim_id
191
192 def ip_profile_2_RO(ip_profile):
193 RO_ip_profile = deepcopy((ip_profile))
194 if "dns-server" in RO_ip_profile:
195 if isinstance(RO_ip_profile["dns-server"], list):
196 RO_ip_profile["dns-address"] = []
197 for ds in RO_ip_profile.pop("dns-server"):
198 RO_ip_profile["dns-address"].append(ds['address'])
199 else:
200 RO_ip_profile["dns-address"] = RO_ip_profile.pop("dns-server")
201 if RO_ip_profile.get("ip-version") == "ipv4":
202 RO_ip_profile["ip-version"] = "IPv4"
203 if RO_ip_profile.get("ip-version") == "ipv6":
204 RO_ip_profile["ip-version"] = "IPv6"
205 if "dhcp-params" in RO_ip_profile:
206 RO_ip_profile["dhcp"] = RO_ip_profile.pop("dhcp-params")
207 return RO_ip_profile
208
209 if not ns_params:
210 return None
211 RO_ns_params = {
212 # "name": ns_params["nsName"],
213 # "description": ns_params.get("nsDescription"),
214 "datacenter": vim_account_2_RO(ns_params["vimAccountId"]),
215 # "scenario": ns_params["nsdId"],
216 "vnfs": {},
217 "networks": {},
218 }
219 if ns_params.get("ssh-authorized-key"):
220 RO_ns_params["cloud-config"] = {"key-pairs": ns_params["ssh-authorized-key"]}
221 if ns_params.get("vnf"):
222 for vnf_params in ns_params["vnf"]:
223 for constituent_vnfd in nsd["constituent-vnfd"]:
224 if constituent_vnfd["member-vnf-index"] == vnf_params["member-vnf-index"]:
225 vnf_descriptor = vnfd_dict[constituent_vnfd["vnfd-id-ref"]]
226 break
227 else:
228 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index={} is not present at nsd:"
229 "constituent-vnfd".format(vnf_params["member-vnf-index"]))
230 RO_vnf = {"vdus": {}, "networks": {}}
231 if vnf_params.get("vimAccountId"):
232 RO_vnf["datacenter"] = vim_account_2_RO(vnf_params["vimAccountId"])
233 if vnf_params.get("vdu"):
234 for vdu_params in vnf_params["vdu"]:
235 RO_vnf["vdus"][vdu_params["id"]] = {}
236 if vdu_params.get("volume"):
237 RO_vnf["vdus"][vdu_params["id"]]["devices"] = {}
238 for volume_params in vdu_params["volume"]:
239 RO_vnf["vdus"][vdu_params["id"]]["devices"][volume_params["name"]] = {}
240 if volume_params.get("vim-volume-id"):
241 RO_vnf["vdus"][vdu_params["id"]]["devices"][volume_params["name"]]["vim_id"] = \
242 volume_params["vim-volume-id"]
243 if vdu_params.get("interface"):
244 RO_vnf["vdus"][vdu_params["id"]]["interfaces"] = {}
245 for interface_params in vdu_params["interface"]:
246 RO_interface = {}
247 RO_vnf["vdus"][vdu_params["id"]]["interfaces"][interface_params["name"]] = RO_interface
248 if interface_params.get("ip-address"):
249 RO_interface["ip_address"] = interface_params["ip-address"]
250 if interface_params.get("mac-address"):
251 RO_interface["mac_address"] = interface_params["mac-address"]
252 if interface_params.get("floating-ip-required"):
253 RO_interface["floating-ip"] = interface_params["floating-ip-required"]
254 if vnf_params.get("internal-vld"):
255 for internal_vld_params in vnf_params["internal-vld"]:
256 RO_vnf["networks"][internal_vld_params["name"]] = {}
257 if internal_vld_params.get("vim-network-name"):
258 RO_vnf["networks"][internal_vld_params["name"]]["vim-network-name"] = \
259 internal_vld_params["vim-network-name"]
260 if internal_vld_params.get("ip-profile"):
261 RO_vnf["networks"][internal_vld_params["name"]]["ip-profile"] = \
262 ip_profile_2_RO(internal_vld_params["ip-profile"])
263 if internal_vld_params.get("internal-connection-point"):
264 for icp_params in internal_vld_params["internal-connection-point"]:
265 # look for interface
266 iface_found = False
267 for vdu_descriptor in vnf_descriptor["vdu"]:
268 for vdu_interface in vdu_descriptor["interface"]:
269 if vdu_interface.get("internal-connection-point-ref") == icp_params["id-ref"]:
270 RO_interface_update = {}
271 if icp_params.get("ip-address"):
272 RO_interface_update["ip_address"] = icp_params["ip-address"]
273 if icp_params.get("mac-address"):
274 RO_interface_update["mac_address"] = icp_params["mac-address"]
275 if RO_interface_update:
276 RO_vnf_update = {"vdus": {vdu_descriptor["id"]: {
277 "interfaces": {vdu_interface["name"]: RO_interface_update}}}}
278 deep_update(RO_vnf, RO_vnf_update)
279 iface_found = True
280 break
281 if iface_found:
282 break
283 else:
284 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
285 "internal-vld:id-ref={} is not present at vnfd:internal-"
286 "connection-point".format(vnf_params["member-vnf-index"],
287 icp_params["id-ref"]))
288
289 if not RO_vnf["vdus"]:
290 del RO_vnf["vdus"]
291 if not RO_vnf["networks"]:
292 del RO_vnf["networks"]
293 if RO_vnf:
294 RO_ns_params["vnfs"][vnf_params["member-vnf-index"]] = RO_vnf
295 if ns_params.get("vld"):
296 for vld_params in ns_params["vld"]:
297 RO_vld = {}
298 if "ip-profile" in vld_params:
299 RO_vld["ip-profile"] = ip_profile_2_RO(vld_params["ip-profile"])
300 if "vim-network-name" in vld_params:
301 RO_vld["sites"] = []
302 if isinstance(vld_params["vim-network-name"], dict):
303 for vim_account, vim_net in vld_params["vim-network-name"].items():
304 RO_vld["sites"].append({
305 "netmap-use": vim_net,
306 "datacenter": vim_account_2_RO(vim_account)
307 })
308 else: # isinstance str
309 RO_vld["sites"].append({"netmap-use": vld_params["vim-network-name"]})
310 if "vnfd-connection-point-ref" in vld_params:
311 for cp_params in vld_params["vnfd-connection-point-ref"]:
312 # look for interface
313 for constituent_vnfd in nsd["constituent-vnfd"]:
314 if constituent_vnfd["member-vnf-index"] == cp_params["member-vnf-index-ref"]:
315 vnf_descriptor = vnfd_dict[constituent_vnfd["vnfd-id-ref"]]
316 break
317 else:
318 raise LcmException(
319 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={} "
320 "is not present at nsd:constituent-vnfd".format(cp_params["member-vnf-index-ref"]))
321 match_cp = False
322 for vdu_descriptor in vnf_descriptor["vdu"]:
323 for interface_descriptor in vdu_descriptor["interface"]:
324 if interface_descriptor.get("external-connection-point-ref") == \
325 cp_params["vnfd-connection-point-ref"]:
326 match_cp = True
327 break
328 if match_cp:
329 break
330 else:
331 raise LcmException(
332 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={}:"
333 "vnfd-connection-point-ref={} is not present at vnfd={}".format(
334 cp_params["member-vnf-index-ref"],
335 cp_params["vnfd-connection-point-ref"],
336 vnf_descriptor["id"]))
337 RO_cp_params = {}
338 if cp_params.get("ip-address"):
339 RO_cp_params["ip_address"] = cp_params["ip-address"]
340 if cp_params.get("mac-address"):
341 RO_cp_params["mac_address"] = cp_params["mac-address"]
342 if RO_cp_params:
343 RO_vnf_params = {
344 cp_params["member-vnf-index-ref"]: {
345 "vdus": {
346 vdu_descriptor["id"]: {
347 "interfaces": {
348 interface_descriptor["name"]: RO_cp_params
349 }
350 }
351 }
352 }
353 }
354 deep_update(RO_ns_params["vnfs"], RO_vnf_params)
355 if RO_vld:
356 RO_ns_params["networks"][vld_params["name"]] = RO_vld
357 return RO_ns_params
358
359 def ns_update_vnfr(self, db_vnfrs, nsr_desc_RO):
360 """
361 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
362 :param db_vnfrs:
363 :param nsr_desc_RO:
364 :return:
365 """
366 for vnf_index, db_vnfr in db_vnfrs.items():
367 for vnf_RO in nsr_desc_RO["vnfs"]:
368 if vnf_RO["member_vnf_index"] == vnf_index:
369 vnfr_update = {}
370 db_vnfr["ip-address"] = vnfr_update["ip-address"] = vnf_RO.get("ip_address")
371 vdur_list = []
372 for vdur_RO in vnf_RO.get("vms", ()):
373 vdur = {
374 "vim-id": vdur_RO.get("vim_vm_id"),
375 "ip-address": vdur_RO.get("ip_address"),
376 "vdu-id-ref": vdur_RO.get("vdu_osm_id"),
377 "name": vdur_RO.get("vim_name"),
378 "status": vdur_RO.get("status"),
379 "status-detailed": vdur_RO.get("error_msg"),
380 "interfaces": []
381 }
382
383 for interface_RO in vdur_RO.get("interfaces", ()):
384 vdur["interfaces"].append({
385 "ip-address": interface_RO.get("ip_address"),
386 "mac-address": interface_RO.get("mac_address"),
387 "name": interface_RO.get("internal_name"),
388 })
389 vdur_list.append(vdur)
390 db_vnfr["vdur"] = vnfr_update["vdur"] = vdur_list
391 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
392 break
393
394 else:
395 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} at RO info".format(vnf_index))
396
397 async def create_monitoring(self, nsr_id, vnf_member_index, vnfd_desc):
398 if not vnfd_desc.get("scaling-group-descriptor"):
399 return
400 for scaling_group in vnfd_desc["scaling-group-descriptor"]:
401 scaling_policy_desc = {}
402 scaling_desc = {
403 "ns_id": nsr_id,
404 "scaling_group_descriptor": {
405 "name": scaling_group["name"],
406 "scaling_policy": scaling_policy_desc
407 }
408 }
409 for scaling_policy in scaling_group.get("scaling-policy"):
410 scaling_policy_desc["scale_in_operation_type"] = scaling_policy_desc["scale_out_operation_type"] = \
411 scaling_policy["scaling-type"]
412 scaling_policy_desc["threshold_time"] = scaling_policy["threshold-time"]
413 scaling_policy_desc["cooldown_time"] = scaling_policy["cooldown-time"]
414 scaling_policy_desc["scaling_criteria"] = []
415 for scaling_criteria in scaling_policy.get("scaling-criteria"):
416 scaling_criteria_desc = {"scale_in_threshold": scaling_criteria.get("scale-in-threshold"),
417 "scale_out_threshold": scaling_criteria.get("scale-out-threshold"),
418 }
419 if not scaling_criteria.get("vnf-monitoring-param-ref"):
420 continue
421 for monitoring_param in vnfd_desc.get("monitoring-param", ()):
422 if monitoring_param["id"] == scaling_criteria["vnf-monitoring-param-ref"]:
423 scaling_criteria_desc["monitoring_param"] = {
424 "id": monitoring_param["id"],
425 "name": monitoring_param["name"],
426 "aggregation_type": monitoring_param.get("aggregation-type"),
427 "vdu_name": monitoring_param.get("vdu-ref"),
428 "vnf_member_index": vnf_member_index,
429 }
430
431 scaling_policy_desc["scaling_criteria"].append(scaling_criteria_desc)
432 break
433 else:
434 self.logger.error(
435 "Task ns={} member_vnf_index={} Invalid vnfd vnf-monitoring-param-ref={} not in "
436 "monitoring-param list".format(nsr_id, vnf_member_index,
437 scaling_criteria["vnf-monitoring-param-ref"]))
438
439 await self.msg.aiowrite("lcm_pm", "configure_scaling", scaling_desc, self.loop)
440
441 async def instantiate(self, nsr_id, nslcmop_id):
442 logging_text = "Task ns={} instantiate={} ".format(nsr_id, nslcmop_id)
443 self.logger.debug(logging_text + "Enter")
444 # get all needed from database
445 db_nsr = None
446 db_nslcmop = None
447 db_nsr_update = {}
448 db_nslcmop_update = {}
449 nslcmop_operation_state = None
450 db_vnfrs = {}
451 RO_descriptor_number = 0 # number of descriptors created at RO
452 descriptor_id_2_RO = {} # map between vnfd/nsd id to the id used at RO
453 n2vc_info = {}
454 exc = None
455 try:
456 step = "Getting nslcmop={} from db".format(nslcmop_id)
457 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
458 step = "Getting nsr={} from db".format(nsr_id)
459 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
460 ns_params = db_nsr.get("instantiate_params")
461 nsd = db_nsr["nsd"]
462 nsr_name = db_nsr["name"] # TODO short-name??
463 needed_vnfd = {}
464 vnfr_filter = {"nsr-id-ref": nsr_id, "member-vnf-index-ref": None}
465 for c_vnf in nsd["constituent-vnfd"]:
466 vnfd_id = c_vnf["vnfd-id-ref"]
467 vnfr_filter["member-vnf-index-ref"] = c_vnf["member-vnf-index"]
468 step = "Getting vnfr={} of nsr={} from db".format(c_vnf["member-vnf-index"], nsr_id)
469 db_vnfrs[c_vnf["member-vnf-index"]] = self.db.get_one("vnfrs", vnfr_filter)
470 if vnfd_id not in needed_vnfd:
471 step = "Getting vnfd={} from db".format(vnfd_id)
472 needed_vnfd[vnfd_id] = self.db.get_one("vnfds", {"id": vnfd_id})
473
474 nsr_lcm = db_nsr["_admin"].get("deployed")
475 if not nsr_lcm:
476 nsr_lcm = db_nsr["_admin"]["deployed"] = {
477 "id": nsr_id,
478 "RO": {"vnfd_id": {}, "nsd_id": None, "nsr_id": None, "nsr_status": "SCHEDULED"},
479 "nsr_ip": {},
480 "VCA": {},
481 }
482 db_nsr_update["detailed-status"] = "creating"
483 db_nsr_update["operational-status"] = "init"
484
485 RO = ROclient.ROClient(self.loop, **self.ro_config)
486
487 # get vnfds, instantiate at RO
488 for vnfd_id, vnfd in needed_vnfd.items():
489 step = db_nsr_update["detailed-status"] = "Creating vnfd={} at RO".format(vnfd_id)
490 # self.logger.debug(logging_text + step)
491 vnfd_id_RO = "{}.{}.{}".format(nsr_id, RO_descriptor_number, vnfd_id[:23])
492 descriptor_id_2_RO[vnfd_id] = vnfd_id_RO
493 RO_descriptor_number += 1
494
495 # look if present
496 vnfd_list = await RO.get_list("vnfd", filter_by={"osm_id": vnfd_id_RO})
497 if vnfd_list:
498 db_nsr_update["_admin.deployed.RO.vnfd_id.{}".format(vnfd_id)] = vnfd_list[0]["uuid"]
499 self.logger.debug(logging_text + "vnfd={} exists at RO. Using RO_id={}".format(
500 vnfd_id, vnfd_list[0]["uuid"]))
501 else:
502 vnfd_RO = self.vnfd2RO(vnfd, vnfd_id_RO)
503 desc = await RO.create("vnfd", descriptor=vnfd_RO)
504 db_nsr_update["_admin.deployed.RO.vnfd_id.{}".format(vnfd_id)] = desc["uuid"]
505 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
506 self.logger.debug(logging_text + "vnfd={} created at RO. RO_id={}".format(
507 vnfd_id, desc["uuid"]))
508 self.update_db_2("nsrs", nsr_id, db_nsr_update)
509
510 # create nsd at RO
511 nsd_id = nsd["id"]
512 step = db_nsr_update["detailed-status"] = "Creating nsd={} at RO".format(nsd_id)
513 # self.logger.debug(logging_text + step)
514
515 RO_osm_nsd_id = "{}.{}.{}".format(nsr_id, RO_descriptor_number, nsd_id[:23])
516 descriptor_id_2_RO[nsd_id] = RO_osm_nsd_id
517 RO_descriptor_number += 1
518 nsd_list = await RO.get_list("nsd", filter_by={"osm_id": RO_osm_nsd_id})
519 if nsd_list:
520 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = nsd_list[0]["uuid"]
521 self.logger.debug(logging_text + "nsd={} exists at RO. Using RO_id={}".format(
522 nsd_id, RO_nsd_uuid))
523 else:
524 nsd_RO = deepcopy(nsd)
525 nsd_RO["id"] = RO_osm_nsd_id
526 nsd_RO.pop("_id", None)
527 nsd_RO.pop("_admin", None)
528 for c_vnf in nsd_RO["constituent-vnfd"]:
529 vnfd_id = c_vnf["vnfd-id-ref"]
530 c_vnf["vnfd-id-ref"] = descriptor_id_2_RO[vnfd_id]
531 desc = await RO.create("nsd", descriptor=nsd_RO)
532 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
533 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = desc["uuid"]
534 self.logger.debug(logging_text + "nsd={} created at RO. RO_id={}".format(nsd_id, RO_nsd_uuid))
535 self.update_db_2("nsrs", nsr_id, db_nsr_update)
536
537 # Crate ns at RO
538 # if present use it unless in error status
539 RO_nsr_id = db_nsr["_admin"].get("deployed", {}).get("RO", {}).get("nsr_id")
540 if RO_nsr_id:
541 try:
542 step = db_nsr_update["detailed-status"] = "Looking for existing ns at RO"
543 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
544 desc = await RO.show("ns", RO_nsr_id)
545 except ROclient.ROClientException as e:
546 if e.http_code != HTTPStatus.NOT_FOUND:
547 raise
548 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
549 if RO_nsr_id:
550 ns_status, ns_status_info = RO.check_ns_status(desc)
551 db_nsr_update["_admin.deployed.RO.nsr_status"] = ns_status
552 if ns_status == "ERROR":
553 step = db_nsr_update["detailed-status"] = "Deleting ns at RO. RO_ns_id={}".format(RO_nsr_id)
554 self.logger.debug(logging_text + step)
555 await RO.delete("ns", RO_nsr_id)
556 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
557 if not RO_nsr_id:
558 step = db_nsr_update["detailed-status"] = "Checking dependencies"
559 # self.logger.debug(logging_text + step)
560
561 # check if VIM is creating and wait look if previous tasks in process
562 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account", ns_params["vimAccountId"])
563 if task_dependency:
564 step = "Waiting for related tasks to be completed: {}".format(task_name)
565 self.logger.debug(logging_text + step)
566 await asyncio.wait(task_dependency, timeout=3600)
567 if ns_params.get("vnf"):
568 for vnf in ns_params["vnf"]:
569 if "vimAccountId" in vnf:
570 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account",
571 vnf["vimAccountId"])
572 if task_dependency:
573 step = "Waiting for related tasks to be completed: {}".format(task_name)
574 self.logger.debug(logging_text + step)
575 await asyncio.wait(task_dependency, timeout=3600)
576
577 step = db_nsr_update["detailed-status"] = "Checking instantiation parameters"
578 RO_ns_params = self.ns_params_2_RO(ns_params, nsd, needed_vnfd)
579 step = db_nsr_update["detailed-status"] = "Creating ns at RO"
580 desc = await RO.create("ns", descriptor=RO_ns_params,
581 name=db_nsr["name"],
582 scenario=RO_nsd_uuid)
583 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = desc["uuid"]
584 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
585 db_nsr_update["_admin.deployed.RO.nsr_status"] = "BUILD"
586 self.logger.debug(logging_text + "ns created at RO. RO_id={}".format(desc["uuid"]))
587 self.update_db_2("nsrs", nsr_id, db_nsr_update)
588
589 # update VNFR vimAccount
590 step = "Updating VNFR vimAcccount"
591 for vnf_index, vnfr in db_vnfrs.items():
592 if vnfr.get("vim-account-id"):
593 continue
594 vnfr_update = {"vim-account-id": db_nsr["instantiate_params"]["vimAccountId"]}
595 if db_nsr["instantiate_params"].get("vnf"):
596 for vnf_params in db_nsr["instantiate_params"]["vnf"]:
597 if vnf_params.get("member-vnf-index") == vnf_index:
598 if vnf_params.get("vimAccountId"):
599 vnfr_update["vim-account-id"] = vnf_params.get("vimAccountId")
600 break
601 self.update_db_2("vnfrs", vnfr["_id"], vnfr_update)
602
603 # wait until NS is ready
604 step = ns_status_detailed = detailed_status = "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id)
605 detailed_status_old = None
606 self.logger.debug(logging_text + step)
607
608 deployment_timeout = 2 * 3600 # Two hours
609 while deployment_timeout > 0:
610 desc = await RO.show("ns", RO_nsr_id)
611 ns_status, ns_status_info = RO.check_ns_status(desc)
612 db_nsr_update["admin.deployed.RO.nsr_status"] = ns_status
613 if ns_status == "ERROR":
614 raise ROclient.ROClientException(ns_status_info)
615 elif ns_status == "BUILD":
616 detailed_status = ns_status_detailed + "; {}".format(ns_status_info)
617 elif ns_status == "ACTIVE":
618 step = detailed_status = "Waiting for management IP address reported by the VIM"
619 try:
620 nsr_lcm["nsr_ip"] = RO.get_ns_vnf_info(desc)
621 break
622 except ROclient.ROClientException as e:
623 if e.http_code != 409: # IP address is not ready return code is 409 CONFLICT
624 raise e
625 else:
626 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
627 if detailed_status != detailed_status_old:
628 detailed_status_old = db_nsr_update["detailed-status"] = detailed_status
629 self.update_db_2("nsrs", nsr_id, db_nsr_update)
630 await asyncio.sleep(5, loop=self.loop)
631 deployment_timeout -= 5
632 if deployment_timeout <= 0:
633 raise ROclient.ROClientException("Timeout waiting ns to be ready")
634
635 step = "Updating VNFRs"
636 self.ns_update_vnfr(db_vnfrs, desc)
637
638 db_nsr["detailed-status"] = "Configuring vnfr"
639 self.update_db_2("nsrs", nsr_id, db_nsr_update)
640
641 # The parameters we'll need to deploy a charm
642 number_to_configure = 0
643
644 def deploy(vnf_index, vdu_id, mgmt_ip_address, n2vc_info, config_primitive=None):
645 """An inner function to deploy the charm from either vnf or vdu
646 vnf_index is mandatory. vdu_id can be None for a vnf configuration or the id for vdu configuration
647 """
648 if not mgmt_ip_address:
649 raise LcmException("vnfd/vdu has not management ip address to configure it")
650 # Login to the VCA.
651 # if number_to_configure == 0:
652 # self.logger.debug("Logging into N2VC...")
653 # task = asyncio.ensure_future(self.n2vc.login())
654 # yield from asyncio.wait_for(task, 30.0)
655 # self.logger.debug("Logged into N2VC!")
656
657 # # await self.n2vc.login()
658
659 # Note: The charm needs to exist on disk at the location
660 # specified by charm_path.
661 base_folder = vnfd["_admin"]["storage"]
662 storage_params = self.fs.get_params()
663 charm_path = "{}{}/{}/charms/{}".format(
664 storage_params["path"],
665 base_folder["folder"],
666 base_folder["pkg-dir"],
667 proxy_charm
668 )
669
670 # Setup the runtime parameters for this VNF
671 params = {'rw_mgmt_ip': mgmt_ip_address}
672 if config_primitive:
673 params["initial-config-primitive"] = config_primitive
674
675 # ns_name will be ignored in the current version of N2VC
676 # but will be implemented for the next point release.
677 model_name = 'default'
678 vdu_id_text = "vnfd"
679 if vdu_id:
680 vdu_id_text = vdu_id
681 application_name = self.n2vc.FormatApplicationName(
682 nsr_name,
683 vnf_index,
684 vdu_id_text
685 )
686 if not nsr_lcm.get("VCA"):
687 nsr_lcm["VCA"] = {}
688 nsr_lcm["VCA"][application_name] = db_nsr_update["_admin.deployed.VCA.{}".format(application_name)] = {
689 "member-vnf-index": vnf_index,
690 "vdu_id": vdu_id,
691 "model": model_name,
692 "application": application_name,
693 "operational-status": "init",
694 "detailed-status": "",
695 "vnfd_id": vnfd_id,
696 }
697 self.update_db_2("nsrs", nsr_id, db_nsr_update)
698
699 self.logger.debug("Task create_ns={} Passing artifacts path '{}' for {}".format(nsr_id, charm_path,
700 proxy_charm))
701 if not n2vc_info:
702 n2vc_info["nsr_id"] = nsr_id
703 n2vc_info["nslcmop_id"] = nslcmop_id
704 n2vc_info["n2vc_event"] = asyncio.Event(loop=self.loop)
705 n2vc_info["lcmOperationType"] = "instantiate"
706 n2vc_info["deployed"] = nsr_lcm["VCA"]
707 n2vc_info["db_update"] = db_nsr_update
708 task = asyncio.ensure_future(
709 self.n2vc.DeployCharms(
710 model_name, # The network service name
711 application_name, # The application name
712 vnfd, # The vnf descriptor
713 charm_path, # Path to charm
714 params, # Runtime params, like mgmt ip
715 {}, # for native charms only
716 self.n2vc_callback, # Callback for status changes
717 n2vc_info, # Callback parameter
718 None, # Callback parameter (task)
719 )
720 )
721 task.add_done_callback(functools.partial(self.n2vc_callback, model_name, application_name, None, None,
722 n2vc_info))
723 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "create_charm:" + application_name, task)
724
725 step = "Looking for needed vnfd to configure"
726 self.logger.debug(logging_text + step)
727
728 for c_vnf in nsd["constituent-vnfd"]:
729 vnfd_id = c_vnf["vnfd-id-ref"]
730 vnf_index = str(c_vnf["member-vnf-index"])
731 vnfd = needed_vnfd[vnfd_id]
732
733 # Check if this VNF has a charm configuration
734 vnf_config = vnfd.get("vnf-configuration")
735
736 if vnf_config and vnf_config.get("juju"):
737 proxy_charm = vnf_config["juju"]["charm"]
738 config_primitive = None
739
740 if proxy_charm:
741 if 'initial-config-primitive' in vnf_config:
742 config_primitive = vnf_config['initial-config-primitive']
743
744 # Login to the VCA. If there are multiple calls to login(),
745 # subsequent calls will be a nop and return immediately.
746 step = "connecting to N2VC to configure vnf {}".format(vnf_index)
747 await self.n2vc.login()
748 deploy(vnf_index, None, db_vnfrs[vnf_index]["ip-address"], n2vc_info, config_primitive)
749 number_to_configure += 1
750
751 # Deploy charms for each VDU that supports one.
752 vdu_index = 0
753 for vdu in vnfd['vdu']:
754 vdu_config = vdu.get('vdu-configuration')
755 proxy_charm = None
756 config_primitive = None
757
758 if vdu_config and vdu_config.get("juju"):
759 proxy_charm = vdu_config["juju"]["charm"]
760
761 if 'initial-config-primitive' in vdu_config:
762 config_primitive = vdu_config['initial-config-primitive']
763
764 if proxy_charm:
765 step = "connecting to N2VC to configure vdu {} from vnf {}".format(vdu["id"], vnf_index)
766 await self.n2vc.login()
767 deploy(vnf_index, vdu["id"], db_vnfrs[vnf_index]["vdur"][vdu_index]["ip-address"],
768 n2vc_info, config_primitive)
769 number_to_configure += 1
770 vdu_index += 1
771
772 db_nsr_update["operational-status"] = "running"
773 configuration_failed = False
774 if number_to_configure:
775 old_status = "configuring: init: {}".format(number_to_configure)
776 db_nsr_update["config-status"] = old_status
777 db_nsr_update["detailed-status"] = old_status
778 db_nslcmop_update["detailed-status"] = old_status
779
780 # wait until all are configured.
781 while True:
782 if db_nsr_update:
783 self.update_db_2("nsrs", nsr_id, db_nsr_update)
784 if db_nslcmop_update:
785 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
786 await n2vc_info["n2vc_event"].wait()
787 n2vc_info["n2vc_event"].clear()
788 all_active = True
789 status_map = {}
790 n2vc_error_text = [] # contain text error list. If empty no one is in error status
791 for _, vca_info in nsr_lcm["VCA"].items():
792 vca_status = vca_info["operational-status"]
793 if vca_status not in status_map:
794 # Initialize it
795 status_map[vca_status] = 0
796 status_map[vca_status] += 1
797
798 if vca_status != "active":
799 all_active = False
800 if vca_status in ("error", "blocked"):
801 n2vc_error_text.append(
802 "member_vnf_index={} vdu_id={} {}: {}".format(vca_info["member-vnf-index"],
803 vca_info["vdu_id"], vca_status,
804 vca_info["detailed-status"]))
805
806 if all_active:
807 break
808 elif n2vc_error_text:
809 db_nsr_update["config-status"] = "failed"
810 error_text = "fail configuring " + ";".join(n2vc_error_text)
811 db_nsr_update["detailed-status"] = error_text
812 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED_TEMP"
813 db_nslcmop_update["detailed-status"] = error_text
814 db_nslcmop_update["statusEnteredTime"] = time()
815 configuration_failed = True
816 break
817 else:
818 cs = "configuring: "
819 separator = ""
820 for status, num in status_map.items():
821 cs += separator + "{}: {}".format(status, num)
822 separator = ", "
823 if old_status != cs:
824 db_nsr_update["config-status"] = cs
825 db_nsr_update["detailed-status"] = cs
826 db_nslcmop_update["detailed-status"] = cs
827 old_status = cs
828
829 if not configuration_failed:
830 # all is done
831 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
832 db_nslcmop_update["statusEnteredTime"] = time()
833 db_nslcmop_update["detailed-status"] = "done"
834 db_nsr_update["config-status"] = "configured"
835 db_nsr_update["detailed-status"] = "done"
836
837 # step = "Sending monitoring parameters to PM"
838 # for c_vnf in nsd["constituent-vnfd"]:
839 # await self.create_monitoring(nsr_id, c_vnf["member-vnf-index"], needed_vnfd[c_vnf["vnfd-id-ref"]])
840 return
841
842 except (ROclient.ROClientException, DbException, LcmException) as e:
843 self.logger.error(logging_text + "Exit Exception while '{}': {}".format(step, e))
844 exc = e
845 except asyncio.CancelledError:
846 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
847 exc = "Operation was cancelled"
848 except Exception as e:
849 exc = traceback.format_exc()
850 self.logger.critical(logging_text + "Exit Exception {} while '{}': {}".format(type(e).__name__, step, e),
851 exc_info=True)
852 finally:
853 if exc:
854 if db_nsr:
855 db_nsr_update["detailed-status"] = "ERROR {}: {}".format(step, exc)
856 db_nsr_update["operational-status"] = "failed"
857 if db_nslcmop:
858 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
859 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
860 db_nslcmop_update["statusEnteredTime"] = time()
861 if db_nsr_update:
862 self.update_db_2("nsrs", nsr_id, db_nsr_update)
863 if db_nslcmop_update:
864 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
865 if nslcmop_operation_state:
866 try:
867 await self.msg.aiowrite("ns", "instantiated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
868 "operationState": nslcmop_operation_state})
869 except Exception as e:
870 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
871
872 self.logger.debug(logging_text + "Exit")
873 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_instantiate")
874
875 async def terminate(self, nsr_id, nslcmop_id):
876 logging_text = "Task ns={} terminate={} ".format(nsr_id, nslcmop_id)
877 self.logger.debug(logging_text + "Enter")
878 db_nsr = None
879 db_nslcmop = None
880 exc = None
881 failed_detail = [] # annotates all failed error messages
882 vca_task_list = []
883 vca_task_dict = {}
884 db_nsr_update = {}
885 db_nslcmop_update = {}
886 nslcmop_operation_state = None
887 try:
888 step = "Getting nslcmop={} from db".format(nslcmop_id)
889 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
890 step = "Getting nsr={} from db".format(nsr_id)
891 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
892 # nsd = db_nsr["nsd"]
893 nsr_lcm = deepcopy(db_nsr["_admin"].get("deployed"))
894 if db_nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
895 return
896 # TODO ALF remove
897 # db_vim = self.db.get_one("vim_accounts", {"_id": db_nsr["datacenter"]})
898 # #TODO check if VIM is creating and wait
899 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
900
901 db_nsr_update["operational-status"] = "terminating"
902 db_nsr_update["config-status"] = "terminating"
903
904 if nsr_lcm and nsr_lcm.get("VCA"):
905 try:
906 step = "Scheduling configuration charms removing"
907 db_nsr_update["detailed-status"] = "Deleting charms"
908 self.logger.debug(logging_text + step)
909 self.update_db_2("nsrs", nsr_id, db_nsr_update)
910 for application_name, deploy_info in nsr_lcm["VCA"].items():
911 if deploy_info: # TODO it would be desirable having a and deploy_info.get("deployed"):
912 task = asyncio.ensure_future(
913 self.n2vc.RemoveCharms(
914 deploy_info['model'],
915 application_name,
916 # self.n2vc_callback,
917 # db_nsr,
918 # db_nslcmop,
919 )
920 )
921 vca_task_list.append(task)
922 vca_task_dict[application_name] = task
923 # task.add_done_callback(functools.partial(self.n2vc_callback, deploy_info['model'],
924 # deploy_info['application'], None, db_nsr,
925 # db_nslcmop, vnf_index))
926 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "delete_charm:" + application_name, task)
927 except Exception as e:
928 self.logger.debug(logging_text + "Failed while deleting charms: {}".format(e))
929
930 # remove from RO
931 RO_fail = False
932 RO = ROclient.ROClient(self.loop, **self.ro_config)
933
934 # Delete ns
935 RO_nsr_id = RO_delete_action = None
936 if nsr_lcm and nsr_lcm.get("RO"):
937 RO_nsr_id = nsr_lcm["RO"].get("nsr_id")
938 RO_delete_action = nsr_lcm["RO"].get("nsr_delete_action_id")
939 try:
940 if RO_nsr_id:
941 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] = "Deleting ns at RO"
942 self.logger.debug(logging_text + step)
943 desc = await RO.delete("ns", RO_nsr_id)
944 RO_delete_action = desc["action_id"]
945 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = RO_delete_action
946 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
947 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
948 if RO_delete_action:
949 # wait until NS is deleted from VIM
950 step = detailed_status = "Waiting ns deleted from VIM. RO_id={}".format(RO_nsr_id)
951 detailed_status_old = None
952 self.logger.debug(logging_text + step)
953
954 delete_timeout = 20 * 60 # 20 minutes
955 while delete_timeout > 0:
956 desc = await RO.show("ns", item_id_name=RO_nsr_id, extra_item="action",
957 extra_item_id=RO_delete_action)
958 ns_status, ns_status_info = RO.check_action_status(desc)
959 if ns_status == "ERROR":
960 raise ROclient.ROClientException(ns_status_info)
961 elif ns_status == "BUILD":
962 detailed_status = step + "; {}".format(ns_status_info)
963 elif ns_status == "ACTIVE":
964 break
965 else:
966 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
967 await asyncio.sleep(5, loop=self.loop)
968 delete_timeout -= 5
969 if detailed_status != detailed_status_old:
970 detailed_status_old = db_nslcmop_update["detailed-status"] = detailed_status
971 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
972 else: # delete_timeout <= 0:
973 raise ROclient.ROClientException("Timeout waiting ns deleted from VIM")
974
975 except ROclient.ROClientException as e:
976 if e.http_code == 404: # not found
977 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
978 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
979 self.logger.debug(logging_text + "RO_ns_id={} already deleted".format(RO_nsr_id))
980 elif e.http_code == 409: # conflict
981 failed_detail.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id, e))
982 self.logger.debug(logging_text + failed_detail[-1])
983 RO_fail = True
984 else:
985 failed_detail.append("RO_ns_id={} delete error: {}".format(RO_nsr_id, e))
986 self.logger.error(logging_text + failed_detail[-1])
987 RO_fail = True
988
989 # Delete nsd
990 if not RO_fail and nsr_lcm and nsr_lcm.get("RO") and nsr_lcm["RO"].get("nsd_id"):
991 RO_nsd_id = nsr_lcm["RO"]["nsd_id"]
992 try:
993 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
994 "Deleting nsd at RO"
995 await RO.delete("nsd", RO_nsd_id)
996 self.logger.debug(logging_text + "RO_nsd_id={} deleted".format(RO_nsd_id))
997 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
998 except ROclient.ROClientException as e:
999 if e.http_code == 404: # not found
1000 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
1001 self.logger.debug(logging_text + "RO_nsd_id={} already deleted".format(RO_nsd_id))
1002 elif e.http_code == 409: # conflict
1003 failed_detail.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id, e))
1004 self.logger.debug(logging_text + failed_detail[-1])
1005 RO_fail = True
1006 else:
1007 failed_detail.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id, e))
1008 self.logger.error(logging_text + failed_detail[-1])
1009 RO_fail = True
1010
1011 if not RO_fail and nsr_lcm and nsr_lcm.get("RO") and nsr_lcm["RO"].get("vnfd_id"):
1012 for vnf_id, RO_vnfd_id in nsr_lcm["RO"]["vnfd_id"].items():
1013 if not RO_vnfd_id:
1014 continue
1015 try:
1016 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
1017 "Deleting vnfd={} at RO".format(vnf_id)
1018 await RO.delete("vnfd", RO_vnfd_id)
1019 self.logger.debug(logging_text + "RO_vnfd_id={} deleted".format(RO_vnfd_id))
1020 db_nsr_update["_admin.deployed.RO.vnfd_id.{}".format(vnf_id)] = None
1021 except ROclient.ROClientException as e:
1022 if e.http_code == 404: # not found
1023 db_nsr_update["_admin.deployed.RO.vnfd_id.{}".format(vnf_id)] = None
1024 self.logger.debug(logging_text + "RO_vnfd_id={} already deleted ".format(RO_vnfd_id))
1025 elif e.http_code == 409: # conflict
1026 failed_detail.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id, e))
1027 self.logger.debug(logging_text + failed_detail[-1])
1028 else:
1029 failed_detail.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id, e))
1030 self.logger.error(logging_text + failed_detail[-1])
1031
1032 if vca_task_list:
1033 db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
1034 "Waiting for deletion of configuration charms"
1035 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1036 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1037 await asyncio.wait(vca_task_list, timeout=300)
1038 for application_name, task in vca_task_dict.items():
1039 if task.cancelled():
1040 failed_detail.append("VCA[{}] Deletion has been cancelled".format(application_name))
1041 elif task.done():
1042 exc = task.exception()
1043 if exc:
1044 failed_detail.append("VCA[{}] Deletion exception: {}".format(application_name, exc))
1045 else:
1046 db_nsr_update["_admin.deployed.VCA.{}".format(application_name)] = None
1047 else: # timeout
1048 # TODO Should it be cancelled?!!
1049 task.cancel()
1050 failed_detail.append("VCA[{}] Deletion timeout".format(application_name))
1051
1052 if failed_detail:
1053 self.logger.error(logging_text + " ;".join(failed_detail))
1054 db_nsr_update["operational-status"] = "failed"
1055 db_nsr_update["detailed-status"] = "Deletion errors " + "; ".join(failed_detail)
1056 db_nslcmop_update["detailed-status"] = "; ".join(failed_detail)
1057 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
1058 db_nslcmop_update["statusEnteredTime"] = time()
1059 elif db_nslcmop["operationParams"].get("autoremove"):
1060 self.db.del_one("nsrs", {"_id": nsr_id})
1061 db_nsr_update.clear()
1062 self.db.del_list("nslcmops", {"nsInstanceId": nsr_id})
1063 nslcmop_operation_state = "COMPLETED"
1064 db_nslcmop_update.clear()
1065 self.db.del_list("vnfrs", {"nsr-id-ref": nsr_id})
1066 self.logger.debug(logging_text + "Delete from database")
1067 else:
1068 db_nsr_update["operational-status"] = "terminated"
1069 db_nsr_update["detailed-status"] = "Done"
1070 db_nsr_update["_admin.nsState"] = "NOT_INSTANTIATED"
1071 db_nslcmop_update["detailed-status"] = "Done"
1072 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
1073 db_nslcmop_update["statusEnteredTime"] = time()
1074
1075 except (ROclient.ROClientException, DbException) as e:
1076 self.logger.error(logging_text + "Exit Exception {}".format(e))
1077 exc = e
1078 except asyncio.CancelledError:
1079 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1080 exc = "Operation was cancelled"
1081 except Exception as e:
1082 exc = traceback.format_exc()
1083 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
1084 finally:
1085 if exc and db_nslcmop:
1086 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
1087 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
1088 db_nslcmop_update["statusEnteredTime"] = time()
1089 if db_nslcmop_update:
1090 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1091 if db_nsr_update:
1092 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1093 if nslcmop_operation_state:
1094 try:
1095 await self.msg.aiowrite("ns", "terminated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
1096 "operationState": nslcmop_operation_state})
1097 except Exception as e:
1098 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1099 self.logger.debug(logging_text + "Exit")
1100 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_terminate")
1101
1102 async def _ns_execute_primitive(self, db_deployed, nsr_name, member_vnf_index, vdu_id, primitive, primitive_params):
1103
1104 vdu_id_text = "vnfd"
1105 if vdu_id:
1106 vdu_id_text = vdu_id
1107 application_name = self.n2vc.FormatApplicationName(
1108 nsr_name,
1109 member_vnf_index,
1110 vdu_id_text
1111 )
1112 vca_deployed = db_deployed["VCA"].get(application_name)
1113 if not vca_deployed:
1114 raise LcmException("charm for member_vnf_index={} vdu_id={} is not deployed".format(member_vnf_index,
1115 vdu_id))
1116 model_name = vca_deployed.get("model")
1117 application_name = vca_deployed.get("application")
1118 if not model_name or not application_name:
1119 raise LcmException("charm for member_vnf_index={} is not properly deployed".format(member_vnf_index))
1120 if vca_deployed["operational-status"] != "active":
1121 raise LcmException("charm for member_vnf_index={} operational_status={} not 'active'".format(
1122 member_vnf_index, vca_deployed["operational-status"]))
1123 callback = None # self.n2vc_callback
1124 callback_args = () # [db_nsr, db_nslcmop, member_vnf_index, None]
1125 await self.n2vc.login()
1126 task = asyncio.ensure_future(
1127 self.n2vc.ExecutePrimitive(
1128 model_name,
1129 application_name,
1130 primitive, callback,
1131 *callback_args,
1132 **primitive_params
1133 )
1134 )
1135 # task.add_done_callback(functools.partial(self.n2vc_callback, model_name, application_name, None,
1136 # db_nsr, db_nslcmop, member_vnf_index))
1137 # self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "action:" + primitive, task)
1138 # wait until completed with timeout
1139 await asyncio.wait((task,), timeout=600)
1140
1141 result = "FAILED" # by default
1142 result_detail = ""
1143 if task.cancelled():
1144 result_detail = "Task has been cancelled"
1145 elif task.done():
1146 exc = task.exception()
1147 if exc:
1148 result_detail = str(exc)
1149 else:
1150 # TODO revise with Adam if action is finished and ok when task is done or callback is needed
1151 result = "COMPLETED"
1152 result_detail = "Done"
1153 else: # timeout
1154 # TODO Should it be cancelled?!!
1155 task.cancel()
1156 result_detail = "timeout"
1157 return result, result_detail
1158
1159 async def action(self, nsr_id, nslcmop_id):
1160 logging_text = "Task ns={} action={} ".format(nsr_id, nslcmop_id)
1161 self.logger.debug(logging_text + "Enter")
1162 # get all needed from database
1163 db_nsr = None
1164 db_nslcmop = None
1165 db_nslcmop_update = {}
1166 nslcmop_operation_state = None
1167 exc = None
1168 try:
1169 step = "Getting information from database"
1170 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
1171 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1172 nsr_lcm = db_nsr["_admin"].get("deployed")
1173 nsr_name = db_nsr["name"]
1174 vnf_index = db_nslcmop["operationParams"]["member_vnf_index"]
1175 vdu_id = db_nslcmop["operationParams"].get("vdu_id")
1176
1177 # TODO check if ns is in a proper status
1178 primitive = db_nslcmop["operationParams"]["primitive"]
1179 primitive_params = db_nslcmop["operationParams"]["primitive_params"]
1180 result, result_detail = await self._ns_execute_primitive(nsr_lcm, nsr_name, vnf_index, vdu_id, primitive,
1181 primitive_params)
1182 db_nslcmop_update["detailed-status"] = result_detail
1183 db_nslcmop_update["operationState"] = nslcmop_operation_state = result
1184 db_nslcmop_update["statusEnteredTime"] = time()
1185 self.logger.debug(logging_text + " task Done with result {} {}".format(result, result_detail))
1186 return # database update is called inside finally
1187
1188 except (DbException, LcmException) as e:
1189 self.logger.error(logging_text + "Exit Exception {}".format(e))
1190 exc = e
1191 except asyncio.CancelledError:
1192 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1193 exc = "Operation was cancelled"
1194 except Exception as e:
1195 exc = traceback.format_exc()
1196 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
1197 finally:
1198 if exc and db_nslcmop:
1199 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
1200 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
1201 db_nslcmop_update["statusEnteredTime"] = time()
1202 if db_nslcmop_update:
1203 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1204 self.logger.debug(logging_text + "Exit")
1205 if nslcmop_operation_state:
1206 try:
1207 await self.msg.aiowrite("ns", "actioned", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
1208 "operationState": nslcmop_operation_state})
1209 except Exception as e:
1210 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1211 self.logger.debug(logging_text + "Exit")
1212 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_action")
1213
1214 async def scale(self, nsr_id, nslcmop_id):
1215 logging_text = "Task ns={} scale={} ".format(nsr_id, nslcmop_id)
1216 self.logger.debug(logging_text + "Enter")
1217 # get all needed from database
1218 db_nsr = None
1219 db_nslcmop = None
1220 db_nslcmop_update = {}
1221 nslcmop_operation_state = None
1222 db_nsr_update = {}
1223 exc = None
1224 try:
1225 step = "Getting nslcmop from database"
1226 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
1227 step = "Getting nsr from database"
1228 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1229 step = "Parsing scaling parameters"
1230 db_nsr_update["operational-status"] = "scaling"
1231 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1232 nsr_lcm = db_nsr["_admin"].get("deployed")
1233 RO_nsr_id = nsr_lcm["RO"]["nsr_id"]
1234 vnf_index = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
1235 scaling_group = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1236 scaling_type = db_nslcmop["operationParams"]["scaleVnfData"]["scaleVnfType"]
1237 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
1238
1239 step = "Getting vnfr from database"
1240 db_vnfr = self.db.get_one("vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id})
1241 step = "Getting vnfd from database"
1242 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
1243 step = "Getting scaling-group-descriptor"
1244 for scaling_descriptor in db_vnfd["scaling-group-descriptor"]:
1245 if scaling_descriptor["name"] == scaling_group:
1246 break
1247 else:
1248 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
1249 "at vnfd:scaling-group-descriptor".format(scaling_group))
1250 # cooldown_time = 0
1251 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
1252 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
1253 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
1254 # break
1255
1256 # TODO check if ns is in a proper status
1257 step = "Sending scale order to RO"
1258 nb_scale_op = 0
1259 if not db_nsr["_admin"].get("scaling-group"):
1260 self.update_db_2("nsrs", nsr_id, {"_admin.scaling-group": [{"name": scaling_group, "nb-scale-op": 0}]})
1261 admin_scale_index = 0
1262 else:
1263 for admin_scale_index, admin_scale_info in enumerate(db_nsr["_admin"]["scaling-group"]):
1264 if admin_scale_info["name"] == scaling_group:
1265 nb_scale_op = admin_scale_info.get("nb-scale-op", 0)
1266 break
1267 RO_scaling_info = []
1268 vdu_scaling_info = {"scaling_group_name": scaling_group, "vdu": []}
1269 if scaling_type == "SCALE_OUT":
1270 # count if max-instance-count is reached
1271 if "max-instance-count" in scaling_descriptor and scaling_descriptor["max-instance-count"] is not None:
1272 max_instance_count = int(scaling_descriptor["max-instance-count"])
1273 if nb_scale_op >= max_instance_count:
1274 raise LcmException("reached the limit of {} (max-instance-count) scaling-out operations for the"
1275 " scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group))
1276 nb_scale_op = nb_scale_op + 1
1277 vdu_scaling_info["scaling_direction"] = "OUT"
1278 vdu_scaling_info["vdu-create"] = {}
1279 for vdu_scale_info in scaling_descriptor["vdu"]:
1280 RO_scaling_info.append({"osm_vdu_id": vdu_scale_info["vdu-id-ref"], "member-vnf-index": vnf_index,
1281 "type": "create", "count": vdu_scale_info.get("count", 1)})
1282 vdu_scaling_info["vdu-create"][vdu_scale_info["vdu-id-ref"]] = vdu_scale_info.get("count", 1)
1283 elif scaling_type == "SCALE_IN":
1284 # count if min-instance-count is reached
1285 if "min-instance-count" in scaling_descriptor and scaling_descriptor["min-instance-count"] is not None:
1286 min_instance_count = int(scaling_descriptor["min-instance-count"])
1287 if nb_scale_op <= min_instance_count:
1288 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
1289 "scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group))
1290 nb_scale_op = nb_scale_op - 1
1291 vdu_scaling_info["scaling_direction"] = "IN"
1292 vdu_scaling_info["vdu-delete"] = {}
1293 for vdu_scale_info in scaling_descriptor["vdu"]:
1294 RO_scaling_info.append({"osm_vdu_id": vdu_scale_info["vdu-id-ref"], "member-vnf-index": vnf_index,
1295 "type": "delete", "count": vdu_scale_info.get("count", 1)})
1296 vdu_scaling_info["vdu-delete"][vdu_scale_info["vdu-id-ref"]] = vdu_scale_info.get("count", 1)
1297
1298 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
1299 if vdu_scaling_info["scaling_direction"] == "IN":
1300 for vdur in reversed(db_vnfr["vdur"]):
1301 if vdu_scaling_info["vdu-delete"].get(vdur["vdu-id-ref"]):
1302 vdu_scaling_info["vdu-delete"][vdur["vdu-id-ref"]] -= 1
1303 vdu_scaling_info["vdu"].append({
1304 "name": vdur["name"],
1305 "vdu_id": vdur["vdu-id-ref"],
1306 "interface": []
1307 })
1308 for interface in vdur["interfaces"]:
1309 vdu_scaling_info["vdu"][-1]["interface"].append({
1310 "name": interface["name"],
1311 "ip_address": interface["ip-address"],
1312 "mac_address": interface.get("mac-address"),
1313 })
1314 del vdu_scaling_info["vdu-delete"]
1315
1316 # execute primitive service PRE-SCALING
1317 step = "Executing pre-scale vnf-config-primitive"
1318 if scaling_descriptor.get("scaling-config-action"):
1319 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
1320 if scaling_config_action.get("trigger") and scaling_config_action["trigger"] == "pre-scale-in" \
1321 and scaling_type == "SCALE_IN":
1322 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
1323 step = db_nslcmop_update["detailed-status"] = \
1324 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive)
1325 # look for primitive
1326 primitive_params = {}
1327 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
1328 if config_primitive["name"] == vnf_config_primitive:
1329 for parameter in config_primitive.get("parameter", ()):
1330 if 'default-value' in parameter and \
1331 parameter['default-value'] == "<VDU_SCALE_INFO>":
1332 primitive_params[parameter["name"]] = yaml.safe_dump(vdu_scaling_info,
1333 default_flow_style=True,
1334 width=256)
1335 break
1336 else:
1337 raise LcmException(
1338 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
1339 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-cnfiguration:config-"
1340 "primitive".format(scaling_group, config_primitive))
1341 result, result_detail = await self._ns_execute_primitive(nsr_lcm, vnf_index,
1342 vnf_config_primitive, primitive_params)
1343 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
1344 vnf_config_primitive, result, result_detail))
1345 if result == "FAILED":
1346 raise LcmException(result_detail)
1347
1348 if RO_scaling_info:
1349 RO = ROclient.ROClient(self.loop, **self.ro_config)
1350 RO_desc = await RO.create_action("ns", RO_nsr_id, {"vdu-scaling": RO_scaling_info})
1351 db_nsr_update["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index)] = nb_scale_op
1352 db_nsr_update["_admin.scaling-group.{}.time".format(admin_scale_index)] = time()
1353 # TODO mark db_nsr_update as scaling
1354 # wait until ready
1355 RO_nslcmop_id = RO_desc["instance_action_id"]
1356 db_nslcmop_update["_admin.deploy.RO"] = RO_nslcmop_id
1357
1358 RO_task_done = False
1359 step = detailed_status = "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id)
1360 detailed_status_old = None
1361 self.logger.debug(logging_text + step)
1362
1363 deployment_timeout = 1 * 3600 # One hours
1364 while deployment_timeout > 0:
1365 if not RO_task_done:
1366 desc = await RO.show("ns", item_id_name=RO_nsr_id, extra_item="action",
1367 extra_item_id=RO_nslcmop_id)
1368 ns_status, ns_status_info = RO.check_action_status(desc)
1369 if ns_status == "ERROR":
1370 raise ROclient.ROClientException(ns_status_info)
1371 elif ns_status == "BUILD":
1372 detailed_status = step + "; {}".format(ns_status_info)
1373 elif ns_status == "ACTIVE":
1374 RO_task_done = True
1375 step = detailed_status = "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id)
1376 self.logger.debug(logging_text + step)
1377 else:
1378 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
1379 else:
1380 desc = await RO.show("ns", RO_nsr_id)
1381 ns_status, ns_status_info = RO.check_ns_status(desc)
1382 if ns_status == "ERROR":
1383 raise ROclient.ROClientException(ns_status_info)
1384 elif ns_status == "BUILD":
1385 detailed_status = step + "; {}".format(ns_status_info)
1386 elif ns_status == "ACTIVE":
1387 step = detailed_status = "Waiting for management IP address reported by the VIM"
1388 try:
1389 desc = await RO.show("ns", RO_nsr_id)
1390 nsr_lcm["nsr_ip"] = RO.get_ns_vnf_info(desc)
1391 break
1392 except ROclient.ROClientException as e:
1393 if e.http_code != 409: # IP address is not ready return code is 409 CONFLICT
1394 raise e
1395 else:
1396 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
1397 if detailed_status != detailed_status_old:
1398 detailed_status_old = db_nslcmop_update["detailed-status"] = detailed_status
1399 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1400
1401 await asyncio.sleep(5, loop=self.loop)
1402 deployment_timeout -= 5
1403 if deployment_timeout <= 0:
1404 raise ROclient.ROClientException("Timeout waiting ns to be ready")
1405
1406 step = "Updating VNFRs"
1407 self.ns_update_vnfr({db_vnfr["member-vnf-index-ref"]: db_vnfr}, desc)
1408
1409 # update VDU_SCALING_INFO with the obtained ip_addresses
1410 if vdu_scaling_info["scaling_direction"] == "OUT":
1411 for vdur in reversed(db_vnfr["vdur"]):
1412 if vdu_scaling_info["vdu-create"].get(vdur["vdu-id-ref"]):
1413 vdu_scaling_info["vdu-create"][vdur["vdu-id-ref"]] -= 1
1414 vdu_scaling_info["vdu"].append({
1415 "name": vdur["name"],
1416 "vdu_id": vdur["vdu-id-ref"],
1417 "interface": []
1418 })
1419 for interface in vdur["interfaces"]:
1420 vdu_scaling_info["vdu"][-1]["interface"].append({
1421 "name": interface["name"],
1422 "ip_address": interface["ip-address"],
1423 "mac_address": interface.get("mac-address"),
1424 })
1425 del vdu_scaling_info["vdu-create"]
1426
1427 if db_nsr_update:
1428 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1429
1430 # execute primitive service POST-SCALING
1431 step = "Executing post-scale vnf-config-primitive"
1432 if scaling_descriptor.get("scaling-config-action"):
1433 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
1434 if scaling_config_action.get("trigger") and scaling_config_action["trigger"] == "post-scale-out" \
1435 and scaling_type == "SCALE_OUT":
1436 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
1437 step = db_nslcmop_update["detailed-status"] = \
1438 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive)
1439 # look for primitive
1440 primitive_params = {}
1441 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
1442 if config_primitive["name"] == vnf_config_primitive:
1443 for parameter in config_primitive.get("parameter", ()):
1444 if 'default-value' in parameter and \
1445 parameter['default-value'] == "<VDU_SCALE_INFO>":
1446 primitive_params[parameter["name"]] = yaml.safe_dump(vdu_scaling_info,
1447 default_flow_style=True,
1448 width=256)
1449 break
1450 else:
1451 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
1452 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
1453 "match any vnf-cnfiguration:config-primitive".format(scaling_group,
1454 config_primitive))
1455 result, result_detail = await self._ns_execute_primitive(nsr_lcm, vnf_index,
1456 vnf_config_primitive, primitive_params)
1457 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
1458 vnf_config_primitive, result, result_detail))
1459 if result == "FAILED":
1460 raise LcmException(result_detail)
1461
1462 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
1463 db_nslcmop_update["statusEnteredTime"] = time()
1464 db_nslcmop_update["detailed-status"] = "done"
1465 db_nsr_update["detailed-status"] = "done"
1466 db_nsr_update["operational-status"] = "running"
1467 return
1468 except (ROclient.ROClientException, DbException, LcmException) as e:
1469 self.logger.error(logging_text + "Exit Exception {}".format(e))
1470 exc = e
1471 except asyncio.CancelledError:
1472 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1473 exc = "Operation was cancelled"
1474 except Exception as e:
1475 exc = traceback.format_exc()
1476 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
1477 finally:
1478 if exc:
1479 if db_nslcmop:
1480 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
1481 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
1482 db_nslcmop_update["statusEnteredTime"] = time()
1483 if db_nsr:
1484 db_nsr_update["operational-status"] = "FAILED {}: {}".format(step, exc),
1485 db_nsr_update["detailed-status"] = "failed"
1486 if db_nslcmop_update:
1487 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1488 if db_nsr_update:
1489 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1490 if nslcmop_operation_state:
1491 try:
1492 await self.msg.aiowrite("ns", "scaled", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
1493 "operationState": nslcmop_operation_state})
1494 # if cooldown_time:
1495 # await asyncio.sleep(cooldown_time)
1496 # await self.msg.aiowrite("ns","scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
1497 except Exception as e:
1498 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1499 self.logger.debug(logging_text + "Exit")
1500 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_scale")