bug559 use of encrypt/decrypt methods
[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 instantiate(self, nsr_id, nslcmop_id):
398 logging_text = "Task ns={} instantiate={} ".format(nsr_id, nslcmop_id)
399 self.logger.debug(logging_text + "Enter")
400 # get all needed from database
401 db_nsr = None
402 db_nslcmop = None
403 db_nsr_update = {"_admin.nslcmop": nslcmop_id}
404 db_nslcmop_update = {}
405 nslcmop_operation_state = None
406 db_vnfrs = {}
407 RO_descriptor_number = 0 # number of descriptors created at RO
408 descriptor_id_2_RO = {} # map between vnfd/nsd id to the id used at RO
409 n2vc_info = {}
410 exc = None
411 try:
412 step = "Getting nslcmop={} from db".format(nslcmop_id)
413 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
414 step = "Getting nsr={} from db".format(nsr_id)
415 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
416 ns_params = db_nsr.get("instantiate_params")
417 nsd = db_nsr["nsd"]
418 nsr_name = db_nsr["name"] # TODO short-name??
419
420 # look if previous tasks in process
421 task_name, task_dependency = self.lcm_tasks.lookfor_related("ns", nsr_id, nslcmop_id)
422 if task_dependency:
423 step = db_nslcmop_update["detailed-status"] = \
424 "Waiting for related tasks to be completed: {}".format(task_name)
425 self.logger.debug(logging_text + step)
426 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
427 _, pending = await asyncio.wait(task_dependency, timeout=3600)
428 if pending:
429 raise LcmException("Timeout waiting related tasks to be completed")
430
431 needed_vnfd = {}
432 vnfr_filter = {"nsr-id-ref": nsr_id, "member-vnf-index-ref": None}
433 for c_vnf in nsd["constituent-vnfd"]:
434 vnfd_id = c_vnf["vnfd-id-ref"]
435 vnfr_filter["member-vnf-index-ref"] = c_vnf["member-vnf-index"]
436 step = "Getting vnfr={} of nsr={} from db".format(c_vnf["member-vnf-index"], nsr_id)
437 db_vnfrs[c_vnf["member-vnf-index"]] = self.db.get_one("vnfrs", vnfr_filter)
438 if vnfd_id not in needed_vnfd:
439 step = "Getting vnfd={} from db".format(vnfd_id)
440 needed_vnfd[vnfd_id] = self.db.get_one("vnfds", {"id": vnfd_id})
441
442 nsr_lcm = db_nsr["_admin"].get("deployed")
443 if not nsr_lcm:
444 nsr_lcm = db_nsr["_admin"]["deployed"] = {
445 "id": nsr_id,
446 "RO": {"vnfd_id": {}, "nsd_id": None, "nsr_id": None, "nsr_status": "SCHEDULED"},
447 "nsr_ip": {},
448 "VCA": {},
449 }
450 db_nsr_update["detailed-status"] = "creating"
451 db_nsr_update["operational-status"] = "init"
452
453 RO = ROclient.ROClient(self.loop, **self.ro_config)
454
455 # get vnfds, instantiate at RO
456 for vnfd_id, vnfd in needed_vnfd.items():
457 step = db_nsr_update["detailed-status"] = "Creating vnfd={} at RO".format(vnfd_id)
458 # self.logger.debug(logging_text + step)
459 vnfd_id_RO = "{}.{}.{}".format(nsr_id, RO_descriptor_number, vnfd_id[:23])
460 descriptor_id_2_RO[vnfd_id] = vnfd_id_RO
461 RO_descriptor_number += 1
462
463 # look if present
464 vnfd_list = await RO.get_list("vnfd", filter_by={"osm_id": vnfd_id_RO})
465 if vnfd_list:
466 db_nsr_update["_admin.deployed.RO.vnfd_id.{}".format(vnfd_id)] = vnfd_list[0]["uuid"]
467 self.logger.debug(logging_text + "vnfd={} exists at RO. Using RO_id={}".format(
468 vnfd_id, vnfd_list[0]["uuid"]))
469 else:
470 vnfd_RO = self.vnfd2RO(vnfd, vnfd_id_RO)
471 desc = await RO.create("vnfd", descriptor=vnfd_RO)
472 db_nsr_update["_admin.deployed.RO.vnfd_id.{}".format(vnfd_id)] = desc["uuid"]
473 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
474 self.logger.debug(logging_text + "vnfd={} created at RO. RO_id={}".format(
475 vnfd_id, desc["uuid"]))
476 self.update_db_2("nsrs", nsr_id, db_nsr_update)
477
478 # create nsd at RO
479 nsd_id = nsd["id"]
480 step = db_nsr_update["detailed-status"] = "Creating nsd={} at RO".format(nsd_id)
481 # self.logger.debug(logging_text + step)
482
483 RO_osm_nsd_id = "{}.{}.{}".format(nsr_id, RO_descriptor_number, nsd_id[:23])
484 descriptor_id_2_RO[nsd_id] = RO_osm_nsd_id
485 RO_descriptor_number += 1
486 nsd_list = await RO.get_list("nsd", filter_by={"osm_id": RO_osm_nsd_id})
487 if nsd_list:
488 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = nsd_list[0]["uuid"]
489 self.logger.debug(logging_text + "nsd={} exists at RO. Using RO_id={}".format(
490 nsd_id, RO_nsd_uuid))
491 else:
492 nsd_RO = deepcopy(nsd)
493 nsd_RO["id"] = RO_osm_nsd_id
494 nsd_RO.pop("_id", None)
495 nsd_RO.pop("_admin", None)
496 for c_vnf in nsd_RO["constituent-vnfd"]:
497 vnfd_id = c_vnf["vnfd-id-ref"]
498 c_vnf["vnfd-id-ref"] = descriptor_id_2_RO[vnfd_id]
499 desc = await RO.create("nsd", descriptor=nsd_RO)
500 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
501 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = desc["uuid"]
502 self.logger.debug(logging_text + "nsd={} created at RO. RO_id={}".format(nsd_id, RO_nsd_uuid))
503 self.update_db_2("nsrs", nsr_id, db_nsr_update)
504
505 # Crate ns at RO
506 # if present use it unless in error status
507 RO_nsr_id = db_nsr["_admin"].get("deployed", {}).get("RO", {}).get("nsr_id")
508 if RO_nsr_id:
509 try:
510 step = db_nsr_update["detailed-status"] = "Looking for existing ns at RO"
511 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
512 desc = await RO.show("ns", RO_nsr_id)
513 except ROclient.ROClientException as e:
514 if e.http_code != HTTPStatus.NOT_FOUND:
515 raise
516 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
517 if RO_nsr_id:
518 ns_status, ns_status_info = RO.check_ns_status(desc)
519 db_nsr_update["_admin.deployed.RO.nsr_status"] = ns_status
520 if ns_status == "ERROR":
521 step = db_nsr_update["detailed-status"] = "Deleting ns at RO. RO_ns_id={}".format(RO_nsr_id)
522 self.logger.debug(logging_text + step)
523 await RO.delete("ns", RO_nsr_id)
524 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
525 if not RO_nsr_id:
526 step = db_nsr_update["detailed-status"] = "Checking dependencies"
527 # self.logger.debug(logging_text + step)
528
529 # check if VIM is creating and wait look if previous tasks in process
530 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account", ns_params["vimAccountId"])
531 if task_dependency:
532 step = "Waiting for related tasks to be completed: {}".format(task_name)
533 self.logger.debug(logging_text + step)
534 await asyncio.wait(task_dependency, timeout=3600)
535 if ns_params.get("vnf"):
536 for vnf in ns_params["vnf"]:
537 if "vimAccountId" in vnf:
538 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account",
539 vnf["vimAccountId"])
540 if task_dependency:
541 step = "Waiting for related tasks to be completed: {}".format(task_name)
542 self.logger.debug(logging_text + step)
543 await asyncio.wait(task_dependency, timeout=3600)
544
545 step = db_nsr_update["detailed-status"] = "Checking instantiation parameters"
546 RO_ns_params = self.ns_params_2_RO(ns_params, nsd, needed_vnfd)
547 step = db_nsr_update["detailed-status"] = "Creating ns at RO"
548 desc = await RO.create("ns", descriptor=RO_ns_params,
549 name=db_nsr["name"],
550 scenario=RO_nsd_uuid)
551 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = desc["uuid"]
552 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
553 db_nsr_update["_admin.deployed.RO.nsr_status"] = "BUILD"
554 self.logger.debug(logging_text + "ns created at RO. RO_id={}".format(desc["uuid"]))
555 self.update_db_2("nsrs", nsr_id, db_nsr_update)
556
557 # update VNFR vimAccount
558 step = "Updating VNFR vimAcccount"
559 for vnf_index, vnfr in db_vnfrs.items():
560 if vnfr.get("vim-account-id"):
561 continue
562 vnfr_update = {"vim-account-id": db_nsr["instantiate_params"]["vimAccountId"]}
563 if db_nsr["instantiate_params"].get("vnf"):
564 for vnf_params in db_nsr["instantiate_params"]["vnf"]:
565 if vnf_params.get("member-vnf-index") == vnf_index:
566 if vnf_params.get("vimAccountId"):
567 vnfr_update["vim-account-id"] = vnf_params.get("vimAccountId")
568 break
569 self.update_db_2("vnfrs", vnfr["_id"], vnfr_update)
570
571 # wait until NS is ready
572 step = ns_status_detailed = detailed_status = "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id)
573 detailed_status_old = None
574 self.logger.debug(logging_text + step)
575
576 deployment_timeout = 2 * 3600 # Two hours
577 while deployment_timeout > 0:
578 desc = await RO.show("ns", RO_nsr_id)
579 ns_status, ns_status_info = RO.check_ns_status(desc)
580 db_nsr_update["admin.deployed.RO.nsr_status"] = ns_status
581 if ns_status == "ERROR":
582 raise ROclient.ROClientException(ns_status_info)
583 elif ns_status == "BUILD":
584 detailed_status = ns_status_detailed + "; {}".format(ns_status_info)
585 elif ns_status == "ACTIVE":
586 step = detailed_status = "Waiting for management IP address reported by the VIM"
587 try:
588 nsr_lcm["nsr_ip"] = RO.get_ns_vnf_info(desc)
589 break
590 except ROclient.ROClientException as e:
591 if e.http_code != 409: # IP address is not ready return code is 409 CONFLICT
592 raise e
593 else:
594 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
595 if detailed_status != detailed_status_old:
596 detailed_status_old = db_nsr_update["detailed-status"] = detailed_status
597 self.update_db_2("nsrs", nsr_id, db_nsr_update)
598 await asyncio.sleep(5, loop=self.loop)
599 deployment_timeout -= 5
600 if deployment_timeout <= 0:
601 raise ROclient.ROClientException("Timeout waiting ns to be ready")
602
603 step = "Updating VNFRs"
604 self.ns_update_vnfr(db_vnfrs, desc)
605
606 db_nsr["detailed-status"] = "Configuring vnfr"
607 self.update_db_2("nsrs", nsr_id, db_nsr_update)
608
609 # The parameters we'll need to deploy a charm
610 number_to_configure = 0
611
612 def deploy(vnf_index, vdu_id, mgmt_ip_address, n2vc_info, config_primitive=None):
613 """An inner function to deploy the charm from either vnf or vdu
614 vnf_index is mandatory. vdu_id can be None for a vnf configuration or the id for vdu configuration
615 """
616 if not mgmt_ip_address:
617 raise LcmException("vnfd/vdu has not management ip address to configure it")
618 # Login to the VCA.
619 # if number_to_configure == 0:
620 # self.logger.debug("Logging into N2VC...")
621 # task = asyncio.ensure_future(self.n2vc.login())
622 # yield from asyncio.wait_for(task, 30.0)
623 # self.logger.debug("Logged into N2VC!")
624
625 # # await self.n2vc.login()
626
627 # Note: The charm needs to exist on disk at the location
628 # specified by charm_path.
629 base_folder = vnfd["_admin"]["storage"]
630 storage_params = self.fs.get_params()
631 charm_path = "{}{}/{}/charms/{}".format(
632 storage_params["path"],
633 base_folder["folder"],
634 base_folder["pkg-dir"],
635 proxy_charm
636 )
637
638 # Setup the runtime parameters for this VNF
639 params = {'rw_mgmt_ip': mgmt_ip_address}
640 if config_primitive:
641 params["initial-config-primitive"] = config_primitive
642
643 # ns_name will be ignored in the current version of N2VC
644 # but will be implemented for the next point release.
645 model_name = 'default'
646 vdu_id_text = "vnfd"
647 if vdu_id:
648 vdu_id_text = vdu_id
649 application_name = self.n2vc.FormatApplicationName(
650 nsr_name,
651 vnf_index,
652 vdu_id_text
653 )
654 if not nsr_lcm.get("VCA"):
655 nsr_lcm["VCA"] = {}
656 nsr_lcm["VCA"][application_name] = db_nsr_update["_admin.deployed.VCA.{}".format(application_name)] = {
657 "member-vnf-index": vnf_index,
658 "vdu_id": vdu_id,
659 "model": model_name,
660 "application": application_name,
661 "operational-status": "init",
662 "detailed-status": "",
663 "vnfd_id": vnfd_id,
664 }
665 self.update_db_2("nsrs", nsr_id, db_nsr_update)
666
667 self.logger.debug("Task create_ns={} Passing artifacts path '{}' for {}".format(nsr_id, charm_path,
668 proxy_charm))
669 if not n2vc_info:
670 n2vc_info["nsr_id"] = nsr_id
671 n2vc_info["nslcmop_id"] = nslcmop_id
672 n2vc_info["n2vc_event"] = asyncio.Event(loop=self.loop)
673 n2vc_info["lcmOperationType"] = "instantiate"
674 n2vc_info["deployed"] = nsr_lcm["VCA"]
675 n2vc_info["db_update"] = db_nsr_update
676 task = asyncio.ensure_future(
677 self.n2vc.DeployCharms(
678 model_name, # The network service name
679 application_name, # The application name
680 vnfd, # The vnf descriptor
681 charm_path, # Path to charm
682 params, # Runtime params, like mgmt ip
683 {}, # for native charms only
684 self.n2vc_callback, # Callback for status changes
685 n2vc_info, # Callback parameter
686 None, # Callback parameter (task)
687 )
688 )
689 task.add_done_callback(functools.partial(self.n2vc_callback, model_name, application_name, None, None,
690 n2vc_info))
691 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "create_charm:" + application_name, task)
692
693 step = "Looking for needed vnfd to configure"
694 self.logger.debug(logging_text + step)
695
696 for c_vnf in nsd["constituent-vnfd"]:
697 vnfd_id = c_vnf["vnfd-id-ref"]
698 vnf_index = str(c_vnf["member-vnf-index"])
699 vnfd = needed_vnfd[vnfd_id]
700
701 # Check if this VNF has a charm configuration
702 vnf_config = vnfd.get("vnf-configuration")
703
704 if vnf_config and vnf_config.get("juju"):
705 proxy_charm = vnf_config["juju"]["charm"]
706 config_primitive = None
707
708 if proxy_charm:
709 if 'initial-config-primitive' in vnf_config:
710 config_primitive = vnf_config['initial-config-primitive']
711
712 # Login to the VCA. If there are multiple calls to login(),
713 # subsequent calls will be a nop and return immediately.
714 step = "connecting to N2VC to configure vnf {}".format(vnf_index)
715 await self.n2vc.login()
716 deploy(vnf_index, None, db_vnfrs[vnf_index]["ip-address"], n2vc_info, config_primitive)
717 number_to_configure += 1
718
719 # Deploy charms for each VDU that supports one.
720 vdu_index = 0
721 for vdu in vnfd['vdu']:
722 vdu_config = vdu.get('vdu-configuration')
723 proxy_charm = None
724 config_primitive = None
725
726 if vdu_config and vdu_config.get("juju"):
727 proxy_charm = vdu_config["juju"]["charm"]
728
729 if 'initial-config-primitive' in vdu_config:
730 config_primitive = vdu_config['initial-config-primitive']
731
732 if proxy_charm:
733 step = "connecting to N2VC to configure vdu {} from vnf {}".format(vdu["id"], vnf_index)
734 await self.n2vc.login()
735 deploy(vnf_index, vdu["id"], db_vnfrs[vnf_index]["vdur"][vdu_index]["ip-address"],
736 n2vc_info, config_primitive)
737 number_to_configure += 1
738 vdu_index += 1
739
740 db_nsr_update["operational-status"] = "running"
741 configuration_failed = False
742 if number_to_configure:
743 old_status = "configuring: init: {}".format(number_to_configure)
744 db_nsr_update["config-status"] = old_status
745 db_nsr_update["detailed-status"] = old_status
746 db_nslcmop_update["detailed-status"] = old_status
747
748 # wait until all are configured.
749 while True:
750 if db_nsr_update:
751 self.update_db_2("nsrs", nsr_id, db_nsr_update)
752 if db_nslcmop_update:
753 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
754 await n2vc_info["n2vc_event"].wait()
755 n2vc_info["n2vc_event"].clear()
756 all_active = True
757 status_map = {}
758 n2vc_error_text = [] # contain text error list. If empty no one is in error status
759 for _, vca_info in nsr_lcm["VCA"].items():
760 vca_status = vca_info["operational-status"]
761 if vca_status not in status_map:
762 # Initialize it
763 status_map[vca_status] = 0
764 status_map[vca_status] += 1
765
766 if vca_status != "active":
767 all_active = False
768 if vca_status in ("error", "blocked"):
769 n2vc_error_text.append(
770 "member_vnf_index={} vdu_id={} {}: {}".format(vca_info["member-vnf-index"],
771 vca_info["vdu_id"], vca_status,
772 vca_info["detailed-status"]))
773
774 if all_active:
775 break
776 elif n2vc_error_text:
777 db_nsr_update["config-status"] = "failed"
778 error_text = "fail configuring " + ";".join(n2vc_error_text)
779 db_nsr_update["detailed-status"] = error_text
780 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED_TEMP"
781 db_nslcmop_update["detailed-status"] = error_text
782 db_nslcmop_update["statusEnteredTime"] = time()
783 configuration_failed = True
784 break
785 else:
786 cs = "configuring: "
787 separator = ""
788 for status, num in status_map.items():
789 cs += separator + "{}: {}".format(status, num)
790 separator = ", "
791 if old_status != cs:
792 db_nsr_update["config-status"] = cs
793 db_nsr_update["detailed-status"] = cs
794 db_nslcmop_update["detailed-status"] = cs
795 old_status = cs
796
797 if not configuration_failed:
798 # all is done
799 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
800 db_nslcmop_update["statusEnteredTime"] = time()
801 db_nslcmop_update["detailed-status"] = "done"
802 db_nsr_update["config-status"] = "configured"
803 db_nsr_update["detailed-status"] = "done"
804
805 return
806
807 except (ROclient.ROClientException, DbException, LcmException) as e:
808 self.logger.error(logging_text + "Exit Exception while '{}': {}".format(step, e))
809 exc = e
810 except asyncio.CancelledError:
811 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
812 exc = "Operation was cancelled"
813 except Exception as e:
814 exc = traceback.format_exc()
815 self.logger.critical(logging_text + "Exit Exception {} while '{}': {}".format(type(e).__name__, step, e),
816 exc_info=True)
817 finally:
818 if exc:
819 if db_nsr:
820 db_nsr_update["detailed-status"] = "ERROR {}: {}".format(step, exc)
821 db_nsr_update["operational-status"] = "failed"
822 if db_nslcmop:
823 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
824 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
825 db_nslcmop_update["statusEnteredTime"] = time()
826 if db_nsr:
827 db_nsr_update["_admin.nslcmop"] = None
828 self.update_db_2("nsrs", nsr_id, db_nsr_update)
829 if db_nslcmop_update:
830 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
831 if nslcmop_operation_state:
832 try:
833 await self.msg.aiowrite("ns", "instantiated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
834 "operationState": nslcmop_operation_state})
835 except Exception as e:
836 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
837
838 self.logger.debug(logging_text + "Exit")
839 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_instantiate")
840
841 async def terminate(self, nsr_id, nslcmop_id):
842 logging_text = "Task ns={} terminate={} ".format(nsr_id, nslcmop_id)
843 self.logger.debug(logging_text + "Enter")
844 db_nsr = None
845 db_nslcmop = None
846 exc = None
847 failed_detail = [] # annotates all failed error messages
848 vca_task_list = []
849 vca_task_dict = {}
850 db_nsr_update = {"_admin.nslcmop": nslcmop_id}
851 db_nslcmop_update = {}
852 nslcmop_operation_state = None
853 try:
854 step = "Getting nslcmop={} from db".format(nslcmop_id)
855 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
856 step = "Getting nsr={} from db".format(nsr_id)
857 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
858 # nsd = db_nsr["nsd"]
859 nsr_lcm = deepcopy(db_nsr["_admin"].get("deployed"))
860 if db_nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
861 return
862 # TODO ALF remove
863 # db_vim = self.db.get_one("vim_accounts", {"_id": db_nsr["datacenter"]})
864 # #TODO check if VIM is creating and wait
865 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
866
867 db_nsr_update["operational-status"] = "terminating"
868 db_nsr_update["config-status"] = "terminating"
869
870 if nsr_lcm and nsr_lcm.get("VCA"):
871 try:
872 step = "Scheduling configuration charms removing"
873 db_nsr_update["detailed-status"] = "Deleting charms"
874 self.logger.debug(logging_text + step)
875 self.update_db_2("nsrs", nsr_id, db_nsr_update)
876 for application_name, deploy_info in nsr_lcm["VCA"].items():
877 if deploy_info: # TODO it would be desirable having a and deploy_info.get("deployed"):
878 task = asyncio.ensure_future(
879 self.n2vc.RemoveCharms(
880 deploy_info['model'],
881 application_name,
882 # self.n2vc_callback,
883 # db_nsr,
884 # db_nslcmop,
885 )
886 )
887 vca_task_list.append(task)
888 vca_task_dict[application_name] = task
889 # task.add_done_callback(functools.partial(self.n2vc_callback, deploy_info['model'],
890 # deploy_info['application'], None, db_nsr,
891 # db_nslcmop, vnf_index))
892 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "delete_charm:" + application_name, task)
893 except Exception as e:
894 self.logger.debug(logging_text + "Failed while deleting charms: {}".format(e))
895
896 # remove from RO
897 RO_fail = False
898 RO = ROclient.ROClient(self.loop, **self.ro_config)
899
900 # Delete ns
901 RO_nsr_id = RO_delete_action = None
902 if nsr_lcm and nsr_lcm.get("RO"):
903 RO_nsr_id = nsr_lcm["RO"].get("nsr_id")
904 RO_delete_action = nsr_lcm["RO"].get("nsr_delete_action_id")
905 try:
906 if RO_nsr_id:
907 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] = "Deleting ns at RO"
908 self.logger.debug(logging_text + step)
909 desc = await RO.delete("ns", RO_nsr_id)
910 RO_delete_action = desc["action_id"]
911 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = RO_delete_action
912 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
913 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
914 if RO_delete_action:
915 # wait until NS is deleted from VIM
916 step = detailed_status = "Waiting ns deleted from VIM. RO_id={}".format(RO_nsr_id)
917 detailed_status_old = None
918 self.logger.debug(logging_text + step)
919
920 delete_timeout = 20 * 60 # 20 minutes
921 while delete_timeout > 0:
922 desc = await RO.show("ns", item_id_name=RO_nsr_id, extra_item="action",
923 extra_item_id=RO_delete_action)
924 ns_status, ns_status_info = RO.check_action_status(desc)
925 if ns_status == "ERROR":
926 raise ROclient.ROClientException(ns_status_info)
927 elif ns_status == "BUILD":
928 detailed_status = step + "; {}".format(ns_status_info)
929 elif ns_status == "ACTIVE":
930 break
931 else:
932 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
933 await asyncio.sleep(5, loop=self.loop)
934 delete_timeout -= 5
935 if detailed_status != detailed_status_old:
936 detailed_status_old = db_nslcmop_update["detailed-status"] = detailed_status
937 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
938 else: # delete_timeout <= 0:
939 raise ROclient.ROClientException("Timeout waiting ns deleted from VIM")
940
941 except ROclient.ROClientException as e:
942 if e.http_code == 404: # not found
943 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
944 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
945 self.logger.debug(logging_text + "RO_ns_id={} already deleted".format(RO_nsr_id))
946 elif e.http_code == 409: # conflict
947 failed_detail.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id, e))
948 self.logger.debug(logging_text + failed_detail[-1])
949 RO_fail = True
950 else:
951 failed_detail.append("RO_ns_id={} delete error: {}".format(RO_nsr_id, e))
952 self.logger.error(logging_text + failed_detail[-1])
953 RO_fail = True
954
955 # Delete nsd
956 if not RO_fail and nsr_lcm and nsr_lcm.get("RO") and nsr_lcm["RO"].get("nsd_id"):
957 RO_nsd_id = nsr_lcm["RO"]["nsd_id"]
958 try:
959 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
960 "Deleting nsd at RO"
961 await RO.delete("nsd", RO_nsd_id)
962 self.logger.debug(logging_text + "RO_nsd_id={} deleted".format(RO_nsd_id))
963 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
964 except ROclient.ROClientException as e:
965 if e.http_code == 404: # not found
966 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
967 self.logger.debug(logging_text + "RO_nsd_id={} already deleted".format(RO_nsd_id))
968 elif e.http_code == 409: # conflict
969 failed_detail.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id, e))
970 self.logger.debug(logging_text + failed_detail[-1])
971 RO_fail = True
972 else:
973 failed_detail.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id, e))
974 self.logger.error(logging_text + failed_detail[-1])
975 RO_fail = True
976
977 if not RO_fail and nsr_lcm and nsr_lcm.get("RO") and nsr_lcm["RO"].get("vnfd_id"):
978 for vnf_id, RO_vnfd_id in nsr_lcm["RO"]["vnfd_id"].items():
979 if not RO_vnfd_id:
980 continue
981 try:
982 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
983 "Deleting vnfd={} at RO".format(vnf_id)
984 await RO.delete("vnfd", RO_vnfd_id)
985 self.logger.debug(logging_text + "RO_vnfd_id={} deleted".format(RO_vnfd_id))
986 db_nsr_update["_admin.deployed.RO.vnfd_id.{}".format(vnf_id)] = None
987 except ROclient.ROClientException as e:
988 if e.http_code == 404: # not found
989 db_nsr_update["_admin.deployed.RO.vnfd_id.{}".format(vnf_id)] = None
990 self.logger.debug(logging_text + "RO_vnfd_id={} already deleted ".format(RO_vnfd_id))
991 elif e.http_code == 409: # conflict
992 failed_detail.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id, e))
993 self.logger.debug(logging_text + failed_detail[-1])
994 else:
995 failed_detail.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id, e))
996 self.logger.error(logging_text + failed_detail[-1])
997
998 if vca_task_list:
999 db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
1000 "Waiting for deletion of configuration charms"
1001 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1002 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1003 await asyncio.wait(vca_task_list, timeout=300)
1004 for application_name, task in vca_task_dict.items():
1005 if task.cancelled():
1006 failed_detail.append("VCA[{}] Deletion has been cancelled".format(application_name))
1007 elif task.done():
1008 exc = task.exception()
1009 if exc:
1010 failed_detail.append("VCA[{}] Deletion exception: {}".format(application_name, exc))
1011 else:
1012 db_nsr_update["_admin.deployed.VCA.{}".format(application_name)] = None
1013 else: # timeout
1014 # TODO Should it be cancelled?!!
1015 task.cancel()
1016 failed_detail.append("VCA[{}] Deletion timeout".format(application_name))
1017
1018 if failed_detail:
1019 self.logger.error(logging_text + " ;".join(failed_detail))
1020 db_nsr_update["operational-status"] = "failed"
1021 db_nsr_update["detailed-status"] = "Deletion errors " + "; ".join(failed_detail)
1022 db_nslcmop_update["detailed-status"] = "; ".join(failed_detail)
1023 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
1024 db_nslcmop_update["statusEnteredTime"] = time()
1025 elif db_nslcmop["operationParams"].get("autoremove"):
1026 self.db.del_one("nsrs", {"_id": nsr_id})
1027 db_nsr_update.clear()
1028 self.db.del_list("nslcmops", {"nsInstanceId": nsr_id})
1029 nslcmop_operation_state = "COMPLETED"
1030 db_nslcmop_update.clear()
1031 self.db.del_list("vnfrs", {"nsr-id-ref": nsr_id})
1032 self.logger.debug(logging_text + "Delete from database")
1033 else:
1034 db_nsr_update["operational-status"] = "terminated"
1035 db_nsr_update["detailed-status"] = "Done"
1036 db_nsr_update["_admin.nsState"] = "NOT_INSTANTIATED"
1037 db_nslcmop_update["detailed-status"] = "Done"
1038 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
1039 db_nslcmop_update["statusEnteredTime"] = time()
1040
1041 except (ROclient.ROClientException, DbException) as e:
1042 self.logger.error(logging_text + "Exit Exception {}".format(e))
1043 exc = e
1044 except asyncio.CancelledError:
1045 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1046 exc = "Operation was cancelled"
1047 except Exception as e:
1048 exc = traceback.format_exc()
1049 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
1050 finally:
1051 if exc and db_nslcmop:
1052 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
1053 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
1054 db_nslcmop_update["statusEnteredTime"] = time()
1055 if db_nslcmop_update:
1056 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1057 if db_nsr:
1058 db_nsr_update["_admin.nslcmop"] = None
1059 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1060 if nslcmop_operation_state:
1061 try:
1062 await self.msg.aiowrite("ns", "terminated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
1063 "operationState": nslcmop_operation_state})
1064 except Exception as e:
1065 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1066 self.logger.debug(logging_text + "Exit")
1067 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_terminate")
1068
1069 async def _ns_execute_primitive(self, db_deployed, nsr_name, member_vnf_index, vdu_id, primitive, primitive_params):
1070
1071 vdu_id_text = "vnfd"
1072 if vdu_id:
1073 vdu_id_text = vdu_id
1074 application_name = self.n2vc.FormatApplicationName(
1075 nsr_name,
1076 member_vnf_index,
1077 vdu_id_text
1078 )
1079 vca_deployed = db_deployed["VCA"].get(application_name)
1080 if not vca_deployed:
1081 raise LcmException("charm for member_vnf_index={} vdu_id={} is not deployed".format(member_vnf_index,
1082 vdu_id))
1083 model_name = vca_deployed.get("model")
1084 application_name = vca_deployed.get("application")
1085 if not model_name or not application_name:
1086 raise LcmException("charm for member_vnf_index={} is not properly deployed".format(member_vnf_index))
1087 if vca_deployed["operational-status"] != "active":
1088 raise LcmException("charm for member_vnf_index={} operational_status={} not 'active'".format(
1089 member_vnf_index, vca_deployed["operational-status"]))
1090 callback = None # self.n2vc_callback
1091 callback_args = () # [db_nsr, db_nslcmop, member_vnf_index, None]
1092 await self.n2vc.login()
1093 task = asyncio.ensure_future(
1094 self.n2vc.ExecutePrimitive(
1095 model_name,
1096 application_name,
1097 primitive, callback,
1098 *callback_args,
1099 **primitive_params
1100 )
1101 )
1102 # task.add_done_callback(functools.partial(self.n2vc_callback, model_name, application_name, None,
1103 # db_nsr, db_nslcmop, member_vnf_index))
1104 # self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "action:" + primitive, task)
1105 # wait until completed with timeout
1106 await asyncio.wait((task,), timeout=600)
1107
1108 result = "FAILED" # by default
1109 result_detail = ""
1110 if task.cancelled():
1111 result_detail = "Task has been cancelled"
1112 elif task.done():
1113 exc = task.exception()
1114 if exc:
1115 result_detail = str(exc)
1116 else:
1117 # TODO revise with Adam if action is finished and ok when task is done or callback is needed
1118 result = "COMPLETED"
1119 result_detail = "Done"
1120 else: # timeout
1121 # TODO Should it be cancelled?!!
1122 task.cancel()
1123 result_detail = "timeout"
1124 return result, result_detail
1125
1126 async def action(self, nsr_id, nslcmop_id):
1127 logging_text = "Task ns={} action={} ".format(nsr_id, nslcmop_id)
1128 self.logger.debug(logging_text + "Enter")
1129 # get all needed from database
1130 db_nsr = None
1131 db_nslcmop = None
1132 db_nsr_update = {"_admin.nslcmop": nslcmop_id}
1133 db_nslcmop_update = {}
1134 nslcmop_operation_state = None
1135 exc = None
1136 try:
1137 step = "Getting information from database"
1138 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
1139 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1140 nsr_lcm = db_nsr["_admin"].get("deployed")
1141 nsr_name = db_nsr["name"]
1142 vnf_index = db_nslcmop["operationParams"]["member_vnf_index"]
1143 vdu_id = db_nslcmop["operationParams"].get("vdu_id")
1144
1145 # look if previous tasks in process
1146 task_name, task_dependency = self.lcm_tasks.lookfor_related("ns", nsr_id, nslcmop_id)
1147 if task_dependency:
1148 step = db_nslcmop_update["detailed-status"] = \
1149 "Waiting for related tasks to be completed: {}".format(task_name)
1150 self.logger.debug(logging_text + step)
1151 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1152 _, pending = await asyncio.wait(task_dependency, timeout=3600)
1153 if pending:
1154 raise LcmException("Timeout waiting related tasks to be completed")
1155
1156 # TODO check if ns is in a proper status
1157 primitive = db_nslcmop["operationParams"]["primitive"]
1158 primitive_params = db_nslcmop["operationParams"]["primitive_params"]
1159 result, result_detail = await self._ns_execute_primitive(nsr_lcm, nsr_name, vnf_index, vdu_id, primitive,
1160 primitive_params)
1161 db_nslcmop_update["detailed-status"] = result_detail
1162 db_nslcmop_update["operationState"] = nslcmop_operation_state = result
1163 db_nslcmop_update["statusEnteredTime"] = time()
1164 self.logger.debug(logging_text + " task Done with result {} {}".format(result, result_detail))
1165 return # database update is called inside finally
1166
1167 except (DbException, LcmException) as e:
1168 self.logger.error(logging_text + "Exit Exception {}".format(e))
1169 exc = e
1170 except asyncio.CancelledError:
1171 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1172 exc = "Operation was cancelled"
1173 except Exception as e:
1174 exc = traceback.format_exc()
1175 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
1176 finally:
1177 if exc and db_nslcmop:
1178 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
1179 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
1180 db_nslcmop_update["statusEnteredTime"] = time()
1181 if db_nslcmop_update:
1182 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1183 if db_nsr:
1184 db_nsr_update["_admin.nslcmop"] = None
1185 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1186 self.logger.debug(logging_text + "Exit")
1187 if nslcmop_operation_state:
1188 try:
1189 await self.msg.aiowrite("ns", "actioned", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
1190 "operationState": nslcmop_operation_state})
1191 except Exception as e:
1192 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1193 self.logger.debug(logging_text + "Exit")
1194 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_action")
1195
1196 async def scale(self, nsr_id, nslcmop_id):
1197 logging_text = "Task ns={} scale={} ".format(nsr_id, nslcmop_id)
1198 self.logger.debug(logging_text + "Enter")
1199 # get all needed from database
1200 db_nsr = None
1201 db_nslcmop = None
1202 db_nslcmop_update = {}
1203 nslcmop_operation_state = None
1204 db_nsr_update = {"_admin.nslcmop": nslcmop_id}
1205 exc = None
1206 # in case of error, indicates what part of scale was failed to put nsr at error status
1207 scale_process = None
1208 old_operational_status = ""
1209 old_config_status = ""
1210 try:
1211 step = "Getting nslcmop from database"
1212 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
1213 step = "Getting nsr from database"
1214 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1215 old_operational_status = db_nsr["operational-status"]
1216 old_config_status = db_nsr["config-status"]
1217
1218 # look if previous tasks in process
1219 task_name, task_dependency = self.lcm_tasks.lookfor_related("ns", nsr_id, nslcmop_id)
1220 if task_dependency:
1221 step = db_nslcmop_update["detailed-status"] = \
1222 "Waiting for related tasks to be completed: {}".format(task_name)
1223 self.logger.debug(logging_text + step)
1224 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1225 _, pending = await asyncio.wait(task_dependency, timeout=3600)
1226 if pending:
1227 raise LcmException("Timeout waiting related tasks to be completed")
1228
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 else: # not found, set index one plus last element and add new entry with the name
1268 admin_scale_index += 1
1269 db_nsr_update["_admin.scaling-group.{}.name".format(admin_scale_index)] = scaling_group
1270 RO_scaling_info = []
1271 vdu_scaling_info = {"scaling_group_name": scaling_group, "vdu": []}
1272 if scaling_type == "SCALE_OUT":
1273 # count if max-instance-count is reached
1274 if "max-instance-count" in scaling_descriptor and scaling_descriptor["max-instance-count"] is not None:
1275 max_instance_count = int(scaling_descriptor["max-instance-count"])
1276 if nb_scale_op >= max_instance_count:
1277 raise LcmException("reached the limit of {} (max-instance-count) scaling-out operations for the"
1278 " scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group))
1279 nb_scale_op = nb_scale_op + 1
1280 vdu_scaling_info["scaling_direction"] = "OUT"
1281 vdu_scaling_info["vdu-create"] = {}
1282 for vdu_scale_info in scaling_descriptor["vdu"]:
1283 RO_scaling_info.append({"osm_vdu_id": vdu_scale_info["vdu-id-ref"], "member-vnf-index": vnf_index,
1284 "type": "create", "count": vdu_scale_info.get("count", 1)})
1285 vdu_scaling_info["vdu-create"][vdu_scale_info["vdu-id-ref"]] = vdu_scale_info.get("count", 1)
1286 elif scaling_type == "SCALE_IN":
1287 # count if min-instance-count is reached
1288 if "min-instance-count" in scaling_descriptor and scaling_descriptor["min-instance-count"] is not None:
1289 min_instance_count = int(scaling_descriptor["min-instance-count"])
1290 if nb_scale_op <= min_instance_count:
1291 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
1292 "scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group))
1293 nb_scale_op = nb_scale_op - 1
1294 vdu_scaling_info["scaling_direction"] = "IN"
1295 vdu_scaling_info["vdu-delete"] = {}
1296 for vdu_scale_info in scaling_descriptor["vdu"]:
1297 RO_scaling_info.append({"osm_vdu_id": vdu_scale_info["vdu-id-ref"], "member-vnf-index": vnf_index,
1298 "type": "delete", "count": vdu_scale_info.get("count", 1)})
1299 vdu_scaling_info["vdu-delete"][vdu_scale_info["vdu-id-ref"]] = vdu_scale_info.get("count", 1)
1300
1301 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
1302 if vdu_scaling_info["scaling_direction"] == "IN":
1303 for vdur in reversed(db_vnfr["vdur"]):
1304 if vdu_scaling_info["vdu-delete"].get(vdur["vdu-id-ref"]):
1305 vdu_scaling_info["vdu-delete"][vdur["vdu-id-ref"]] -= 1
1306 vdu_scaling_info["vdu"].append({
1307 "name": vdur["name"],
1308 "vdu_id": vdur["vdu-id-ref"],
1309 "interface": []
1310 })
1311 for interface in vdur["interfaces"]:
1312 vdu_scaling_info["vdu"][-1]["interface"].append({
1313 "name": interface["name"],
1314 "ip_address": interface["ip-address"],
1315 "mac_address": interface.get("mac-address"),
1316 })
1317 del vdu_scaling_info["vdu-delete"]
1318
1319 # execute primitive service PRE-SCALING
1320 step = "Executing pre-scale vnf-config-primitive"
1321 if scaling_descriptor.get("scaling-config-action"):
1322 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
1323 if scaling_config_action.get("trigger") and scaling_config_action["trigger"] == "pre-scale-in" \
1324 and scaling_type == "SCALE_IN":
1325 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
1326 step = db_nslcmop_update["detailed-status"] = \
1327 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive)
1328 # look for primitive
1329 primitive_params = {}
1330 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
1331 if config_primitive["name"] == vnf_config_primitive:
1332 for parameter in config_primitive.get("parameter", ()):
1333 if 'default-value' in parameter and \
1334 parameter['default-value'] == "<VDU_SCALE_INFO>":
1335 primitive_params[parameter["name"]] = yaml.safe_dump(vdu_scaling_info,
1336 default_flow_style=True,
1337 width=256)
1338 break
1339 else:
1340 raise LcmException(
1341 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
1342 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-cnfiguration:config-"
1343 "primitive".format(scaling_group, config_primitive))
1344 scale_process = "VCA"
1345 db_nsr_update["config-status"] = "configuring pre-scaling"
1346 result, result_detail = await self._ns_execute_primitive(nsr_lcm, vnf_index,
1347 vnf_config_primitive, primitive_params)
1348 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
1349 vnf_config_primitive, result, result_detail))
1350 if result == "FAILED":
1351 raise LcmException(result_detail)
1352 db_nsr_update["config-status"] = old_config_status
1353 scale_process = None
1354
1355 if RO_scaling_info:
1356 scale_process = "RO"
1357 RO = ROclient.ROClient(self.loop, **self.ro_config)
1358 RO_desc = await RO.create_action("ns", RO_nsr_id, {"vdu-scaling": RO_scaling_info})
1359 db_nsr_update["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index)] = nb_scale_op
1360 db_nsr_update["_admin.scaling-group.{}.time".format(admin_scale_index)] = time()
1361 # wait until ready
1362 RO_nslcmop_id = RO_desc["instance_action_id"]
1363 db_nslcmop_update["_admin.deploy.RO"] = RO_nslcmop_id
1364
1365 RO_task_done = False
1366 step = detailed_status = "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id)
1367 detailed_status_old = None
1368 self.logger.debug(logging_text + step)
1369
1370 deployment_timeout = 1 * 3600 # One hour
1371 while deployment_timeout > 0:
1372 if not RO_task_done:
1373 desc = await RO.show("ns", item_id_name=RO_nsr_id, extra_item="action",
1374 extra_item_id=RO_nslcmop_id)
1375 ns_status, ns_status_info = RO.check_action_status(desc)
1376 if ns_status == "ERROR":
1377 raise ROclient.ROClientException(ns_status_info)
1378 elif ns_status == "BUILD":
1379 detailed_status = step + "; {}".format(ns_status_info)
1380 elif ns_status == "ACTIVE":
1381 RO_task_done = True
1382 step = detailed_status = "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id)
1383 self.logger.debug(logging_text + step)
1384 else:
1385 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
1386 else:
1387 desc = await RO.show("ns", RO_nsr_id)
1388 ns_status, ns_status_info = RO.check_ns_status(desc)
1389 if ns_status == "ERROR":
1390 raise ROclient.ROClientException(ns_status_info)
1391 elif ns_status == "BUILD":
1392 detailed_status = step + "; {}".format(ns_status_info)
1393 elif ns_status == "ACTIVE":
1394 step = detailed_status = "Waiting for management IP address reported by the VIM"
1395 try:
1396 desc = await RO.show("ns", RO_nsr_id)
1397 nsr_lcm["nsr_ip"] = RO.get_ns_vnf_info(desc)
1398 break
1399 except ROclient.ROClientException as e:
1400 if e.http_code != 409: # IP address is not ready return code is 409 CONFLICT
1401 raise e
1402 else:
1403 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
1404 if detailed_status != detailed_status_old:
1405 detailed_status_old = db_nslcmop_update["detailed-status"] = detailed_status
1406 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1407
1408 await asyncio.sleep(5, loop=self.loop)
1409 deployment_timeout -= 5
1410 if deployment_timeout <= 0:
1411 raise ROclient.ROClientException("Timeout waiting ns to be ready")
1412
1413 step = "Updating VNFRs"
1414 self.ns_update_vnfr({db_vnfr["member-vnf-index-ref"]: db_vnfr}, desc)
1415
1416 # update VDU_SCALING_INFO with the obtained ip_addresses
1417 if vdu_scaling_info["scaling_direction"] == "OUT":
1418 for vdur in reversed(db_vnfr["vdur"]):
1419 if vdu_scaling_info["vdu-create"].get(vdur["vdu-id-ref"]):
1420 vdu_scaling_info["vdu-create"][vdur["vdu-id-ref"]] -= 1
1421 vdu_scaling_info["vdu"].append({
1422 "name": vdur["name"],
1423 "vdu_id": vdur["vdu-id-ref"],
1424 "interface": []
1425 })
1426 for interface in vdur["interfaces"]:
1427 vdu_scaling_info["vdu"][-1]["interface"].append({
1428 "name": interface["name"],
1429 "ip_address": interface["ip-address"],
1430 "mac_address": interface.get("mac-address"),
1431 })
1432 del vdu_scaling_info["vdu-create"]
1433
1434 scale_process = None
1435 if db_nsr_update:
1436 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1437
1438 # execute primitive service POST-SCALING
1439 step = "Executing post-scale vnf-config-primitive"
1440 if scaling_descriptor.get("scaling-config-action"):
1441 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
1442 if scaling_config_action.get("trigger") and scaling_config_action["trigger"] == "post-scale-out" \
1443 and scaling_type == "SCALE_OUT":
1444 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
1445 step = db_nslcmop_update["detailed-status"] = \
1446 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive)
1447 # look for primitive
1448 primitive_params = {}
1449 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
1450 if config_primitive["name"] == vnf_config_primitive:
1451 for parameter in config_primitive.get("parameter", ()):
1452 if 'default-value' in parameter and \
1453 parameter['default-value'] == "<VDU_SCALE_INFO>":
1454 primitive_params[parameter["name"]] = yaml.safe_dump(vdu_scaling_info,
1455 default_flow_style=True,
1456 width=256)
1457 break
1458 else:
1459 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
1460 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
1461 "match any vnf-configuration:config-primitive".format(scaling_group,
1462 config_primitive))
1463 scale_process = "VCA"
1464 db_nsr_update["config-status"] = "configuring post-scaling"
1465
1466 result, result_detail = await self._ns_execute_primitive(nsr_lcm, vnf_index,
1467 vnf_config_primitive, primitive_params)
1468 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
1469 vnf_config_primitive, result, result_detail))
1470 if result == "FAILED":
1471 raise LcmException(result_detail)
1472 db_nsr_update["config-status"] = old_config_status
1473 scale_process = None
1474
1475 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
1476 db_nslcmop_update["statusEnteredTime"] = time()
1477 db_nslcmop_update["detailed-status"] = "done"
1478 db_nsr_update["detailed-status"] = "" # "scaled {} {}".format(scaling_group, scaling_type)
1479 db_nsr_update["operational-status"] = old_operational_status
1480 db_nsr_update["config-status"] = old_config_status
1481 return
1482 except (ROclient.ROClientException, DbException, LcmException) as e:
1483 self.logger.error(logging_text + "Exit Exception {}".format(e))
1484 exc = e
1485 except asyncio.CancelledError:
1486 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1487 exc = "Operation was cancelled"
1488 except Exception as e:
1489 exc = traceback.format_exc()
1490 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
1491 finally:
1492 if exc:
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 if db_nsr:
1498 db_nsr_update["operational-status"] = old_operational_status
1499 db_nsr_update["config-status"] = old_config_status
1500 db_nsr_update["detailed-status"] = ""
1501 db_nsr_update["_admin.nslcmop"] = None
1502 if scale_process:
1503 if "VCA" in scale_process:
1504 db_nsr_update["config-status"] = "failed"
1505 if "RO" in scale_process:
1506 db_nsr_update["operational-status"] = "failed"
1507 db_nsr_update["detailed-status"] = "FAILED scaling nslcmop={} {}: {}".format(nslcmop_id, step,
1508 exc)
1509 if db_nslcmop_update:
1510 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1511 if db_nsr:
1512 db_nsr_update["_admin.nslcmop"] = None
1513 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1514 if nslcmop_operation_state:
1515 try:
1516 await self.msg.aiowrite("ns", "scaled", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
1517 "operationState": nslcmop_operation_state})
1518 # if cooldown_time:
1519 # await asyncio.sleep(cooldown_time)
1520 # await self.msg.aiowrite("ns","scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
1521 except Exception as e:
1522 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1523 self.logger.debug(logging_text + "Exit")
1524 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_scale")