da428d1205bd150744316319aa3587acd960ded6
[osm/LCM.git] / osm_lcm / netslice.py
1 # -*- coding: utf-8 -*-
2
3 import asyncio
4 import logging
5 import logging.handlers
6 import traceback
7 import ns
8 from ns import populate_dict as populate_dict
9 import ROclient
10 from lcm_utils import LcmException, LcmBase
11 from osm_common.dbbase import DbException
12 from time import time
13 from copy import deepcopy
14
15
16 __author__ = "Felipe Vicens, Pol Alemany, Alfonso Tierno"
17
18
19 def get_iterable(in_dict, in_key):
20 """
21 Similar to <dict>.get(), but if value is None, False, ..., An empty tuple is returned instead
22 :param in_dict: a dictionary
23 :param in_key: the key to look for at in_dict
24 :return: in_dict[in_var] or () if it is None or not present
25 """
26 if not in_dict.get(in_key):
27 return ()
28 return in_dict[in_key]
29
30
31 class NetsliceLcm(LcmBase):
32
33 total_deploy_timeout = 2 * 3600 # global timeout for deployment
34
35 def __init__(self, db, msg, fs, lcm_tasks, ro_config, vca_config, loop):
36 """
37 Init, Connect to database, filesystem storage, and messaging
38 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
39 :return: None
40 """
41 # logging
42 self.logger = logging.getLogger('lcm.netslice')
43 self.loop = loop
44 self.lcm_tasks = lcm_tasks
45 self.ns = ns.NsLcm(db, msg, fs, lcm_tasks, ro_config, vca_config, loop)
46 self.ro_config = ro_config
47
48 super().__init__(db, msg, fs, self.logger)
49
50 def nsi_update_nsir(self, nsi_update_nsir, db_nsir, nsir_desc_RO):
51 """
52 Updates database nsir with the RO info for the created vld
53 :param nsi_update_nsir: dictionary to be filled with the updated info
54 :param db_nsir: content of db_nsir. This is also modified
55 :param nsir_desc_RO: nsir descriptor from RO
56 :return: Nothing, LcmException is raised on errors
57 """
58
59 for vld_index, vld in enumerate(get_iterable(db_nsir, "vld")):
60 for net_RO in get_iterable(nsir_desc_RO, "nets"):
61 if vld["id"] != net_RO.get("ns_net_osm_id"):
62 continue
63 vld["vim-id"] = net_RO.get("vim_net_id")
64 vld["name"] = net_RO.get("vim_name")
65 vld["status"] = net_RO.get("status")
66 vld["status-detailed"] = net_RO.get("error_msg")
67 nsi_update_nsir["vld.{}".format(vld_index)] = vld
68 break
69 else:
70 raise LcmException("ns_update_nsir: Not found vld={} at RO info".format(vld["id"]))
71
72 async def instantiate(self, nsir_id, nsilcmop_id):
73
74 # Try to lock HA task here
75 task_is_locked_by_me = self.lcm_tasks.lock_HA('nsi', 'nsilcmops', nsilcmop_id)
76 if not task_is_locked_by_me:
77 return
78
79 logging_text = "Task netslice={} instantiate={} ".format(nsir_id, nsilcmop_id)
80 self.logger.debug(logging_text + "Enter")
81 # get all needed from database
82 exc = None
83 db_nsir = None
84 db_nsilcmop = None
85 db_nsir_update = {"_admin.nsilcmop": nsilcmop_id}
86 db_nsilcmop_update = {}
87 nsilcmop_operation_state = None
88 vim_2_RO = {}
89 RO = ROclient.ROClient(self.loop, **self.ro_config)
90
91 def ip_profile_2_RO(ip_profile):
92 RO_ip_profile = deepcopy((ip_profile))
93 if "dns-server" in RO_ip_profile:
94 if isinstance(RO_ip_profile["dns-server"], list):
95 RO_ip_profile["dns-address"] = []
96 for ds in RO_ip_profile.pop("dns-server"):
97 RO_ip_profile["dns-address"].append(ds['address'])
98 else:
99 RO_ip_profile["dns-address"] = RO_ip_profile.pop("dns-server")
100 if RO_ip_profile.get("ip-version") == "ipv4":
101 RO_ip_profile["ip-version"] = "IPv4"
102 if RO_ip_profile.get("ip-version") == "ipv6":
103 RO_ip_profile["ip-version"] = "IPv6"
104 if "dhcp-params" in RO_ip_profile:
105 RO_ip_profile["dhcp"] = RO_ip_profile.pop("dhcp-params")
106 return RO_ip_profile
107
108 def vim_account_2_RO(vim_account):
109 """
110 Translate a RO vim_account from OSM vim_account params
111 :param ns_params: OSM instantiate params
112 :return: The RO ns descriptor
113 """
114 if vim_account in vim_2_RO:
115 return vim_2_RO[vim_account]
116
117 db_vim = self.db.get_one("vim_accounts", {"_id": vim_account})
118 if db_vim["_admin"]["operationalState"] != "ENABLED":
119 raise LcmException("VIM={} is not available. operationalState={}".format(
120 vim_account, db_vim["_admin"]["operationalState"]))
121 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
122 vim_2_RO[vim_account] = RO_vim_id
123 return RO_vim_id
124
125 async def netslice_scenario_create(self, vld_item, nsir_id, db_nsir, db_nsir_admin, db_nsir_update):
126 """
127 Create a network slice VLD through RO Scenario
128 :param vld_id The VLD id inside nsir to be created
129 :param nsir_id The nsir id
130 """
131 ip_vld = None
132 mgmt_network = False
133 RO_vld_sites = []
134 vld_id = vld_item["id"]
135 netslice_vld = vld_item
136 # logging_text = "Task netslice={} instantiate_vld={} ".format(nsir_id, vld_id)
137 # self.logger.debug(logging_text + "Enter")
138
139 vld_shared = None
140 for shared_nsrs_item in get_iterable(vld_item, "shared-nsrs-list"):
141 _filter = {"_id.ne": nsir_id, "_admin.nsrs-detailed-list.ANYINDEX.nsrId": shared_nsrs_item}
142 shared_nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
143 if shared_nsi:
144 for vlds in get_iterable(shared_nsi["_admin"]["deployed"], "RO"):
145 if vld_id == vlds["vld_id"]:
146 vld_shared = {"instance_scenario_id": vlds["netslice_scenario_id"], "osm_id": vld_id}
147 break
148 break
149
150 # Creating netslice-vld at RO
151 RO_nsir = db_nsir["_admin"].get("deployed", {}).get("RO", [])
152
153 if vld_id in RO_nsir:
154 db_nsir_update["_admin.deployed.RO"] = RO_nsir
155
156 # If netslice-vld doesn't exists then create it
157 else:
158 # TODO: Check VDU type in all descriptors finding SRIOV / PT
159 # Updating network names and datacenters from instantiation parameters for each VLD
160 RO_ns_params = {}
161 RO_ns_params["name"] = netslice_vld["name"]
162 RO_ns_params["datacenter"] = vim_account_2_RO(db_nsir["instantiation_parameters"]["vimAccountId"])
163 for instantiation_params_vld in get_iterable(db_nsir["instantiation_parameters"], "netslice-vld"):
164 if instantiation_params_vld.get("name") == netslice_vld["name"]:
165 ip_vld = deepcopy(instantiation_params_vld)
166
167 if netslice_vld.get("mgmt-network"):
168 mgmt_network = True
169
170 # Creating scenario if vim-network-name / vim-network-id are present as instantiation parameter
171 # Use vim-network-id instantiation parameter
172 vim_network_option = None
173 if ip_vld:
174 if ip_vld.get("vim-network-id"):
175 vim_network_option = "vim-network-id"
176 elif ip_vld.get("vim-network-name"):
177 vim_network_option = "vim-network-name"
178 if ip_vld.get("ip-profile"):
179 populate_dict(RO_ns_params, ("networks", netslice_vld["name"], "ip-profile"),
180 ip_profile_2_RO(ip_vld["ip-profile"]))
181
182 if vim_network_option:
183 if ip_vld.get(vim_network_option):
184 if isinstance(ip_vld.get(vim_network_option), list):
185 for vim_net_id in ip_vld.get(vim_network_option):
186 for vim_account, vim_net in vim_net_id.items():
187 RO_vld_sites.append({
188 "netmap-use": vim_net,
189 "datacenter": vim_account_2_RO(vim_account)
190 })
191 elif isinstance(ip_vld.get(vim_network_option), dict):
192 for vim_account, vim_net in ip_vld.get(vim_network_option).items():
193 RO_vld_sites.append({
194 "netmap-use": vim_net,
195 "datacenter": vim_account_2_RO(vim_account)
196 })
197 else:
198 RO_vld_sites.append({
199 "netmap-use": ip_vld[vim_network_option],
200 "datacenter": vim_account_2_RO(netslice_vld["vimAccountId"])})
201
202 # Use default netslice vim-network-name from template
203 else:
204 for nss_conn_point_ref in get_iterable(netslice_vld, "nss-connection-point-ref"):
205 if nss_conn_point_ref.get("vimAccountId"):
206 if nss_conn_point_ref["vimAccountId"] != netslice_vld["vimAccountId"]:
207 RO_vld_sites.append({
208 "netmap-create": None,
209 "datacenter": vim_account_2_RO(nss_conn_point_ref["vimAccountId"])})
210
211 if vld_shared:
212 populate_dict(RO_ns_params, ("networks", netslice_vld["name"], "use-network"), vld_shared)
213
214 if RO_vld_sites:
215 populate_dict(RO_ns_params, ("networks", netslice_vld["name"], "sites"), RO_vld_sites)
216
217 RO_ns_params["scenario"] = {"nets": [{"name": netslice_vld["name"],
218 "external": mgmt_network, "type": "bridge"}]}
219
220 # self.logger.debug(logging_text + step)
221 db_nsir_update["detailed-status"] = "Creating netslice-vld at RO"
222 desc = await RO.create("ns", descriptor=RO_ns_params)
223 db_nsir_update_RO = {}
224 db_nsir_update_RO["netslice_scenario_id"] = desc["uuid"]
225 db_nsir_update_RO["vld_id"] = RO_ns_params["name"]
226 db_nsir_update["_admin.deployed.RO"].append(db_nsir_update_RO)
227
228 def overwrite_nsd_params(self, db_nsir, nslcmop):
229 RO_list = []
230 vld_op_list = []
231 vld = None
232 nsr_id = nslcmop.get("nsInstanceId")
233 # Overwrite instantiation parameters in netslice runtime
234 if db_nsir.get("_admin"):
235 if db_nsir["_admin"].get("deployed"):
236 db_admin_deployed_nsir = db_nsir["_admin"].get("deployed")
237 if db_admin_deployed_nsir.get("RO"):
238 RO_list = db_admin_deployed_nsir["RO"]
239
240 for RO_item in RO_list:
241 for netslice_vld in get_iterable(db_nsir["_admin"], "netslice-vld"):
242 # if is equal vld of _admin with vld of netslice-vld then go for the CPs
243 if RO_item.get("vld_id") == netslice_vld.get("id"):
244 # Search the cp of netslice-vld that match with nst:netslice-subnet
245 for nss_cp_item in get_iterable(netslice_vld, "nss-connection-point-ref"):
246 # Search the netslice-subnet of nst that match
247 for nss in get_iterable(db_nsir["_admin"], "netslice-subnet"):
248 # Compare nss-ref equal nss from nst
249 if nss_cp_item["nss-ref"] == nss["nss-id"]:
250 db_nsds = self.db.get_one("nsds", {"_id": nss["nsdId"]})
251 # Go for nsd, and search the CP that match with nst:CP to get vld-id-ref
252 for cp_nsd in db_nsds["connection-point"]:
253 if cp_nsd["name"] == nss_cp_item["nsd-connection-point-ref"]:
254 if nslcmop.get("operationParams"):
255 if nslcmop["operationParams"].get("nsName") == nss["nsName"]:
256 vld_id = RO_item["vld_id"]
257 netslice_scenario_id = RO_item["netslice_scenario_id"]
258 nslcmop_vld = {}
259 nslcmop_vld["ns-net"] = {vld_id: netslice_scenario_id}
260 nslcmop_vld["name"] = cp_nsd["vld-id-ref"]
261 for vld in get_iterable(nslcmop["operationParams"], "vld"):
262 if vld["name"] == cp_nsd["vld-id-ref"]:
263 nslcmop_vld.update(vld)
264 vld_op_list.append(nslcmop_vld)
265 nslcmop["operationParams"]["vld"] = vld_op_list
266 self.update_db_2("nslcmops", nslcmop["_id"], nslcmop)
267 return nsr_id, nslcmop
268
269 try:
270 # wait for any previous tasks in process
271 await self.lcm_tasks.waitfor_related_HA('nsi', 'nsilcmops', nsilcmop_id)
272
273 step = "Getting nsir={} from db".format(nsir_id)
274 db_nsir = self.db.get_one("nsis", {"_id": nsir_id})
275 step = "Getting nsilcmop={} from db".format(nsilcmop_id)
276 db_nsilcmop = self.db.get_one("nsilcmops", {"_id": nsilcmop_id})
277
278 # Empty list to keep track of network service records status in the netslice
279 nsir_admin = db_nsir_admin = db_nsir.get("_admin")
280
281 # Slice status Creating
282 db_nsir_update["detailed-status"] = "creating"
283 db_nsir_update["operational-status"] = "init"
284 self.update_db_2("nsis", nsir_id, db_nsir_update)
285
286 # Creating netslice VLDs networking before NS instantiation
287 db_nsir_update["_admin.deployed.RO"] = db_nsir_admin["deployed"]["RO"]
288 for vld_item in get_iterable(nsir_admin, "netslice-vld"):
289 await netslice_scenario_create(self, vld_item, nsir_id, db_nsir, db_nsir_admin, db_nsir_update)
290 self.update_db_2("nsis", nsir_id, db_nsir_update)
291
292 db_nsir_update["detailed-status"] = "Creating netslice subnets at RO"
293 self.update_db_2("nsis", nsir_id, db_nsir_update)
294
295 db_nsir = self.db.get_one("nsis", {"_id": nsir_id})
296
297 # Check status of the VLDs and wait for creation
298 # netslice_scenarios = db_nsir["_admin"]["deployed"]["RO"]
299 # db_nsir_update_RO = deepcopy(netslice_scenarios)
300 # for netslice_scenario in netslice_scenarios:
301 # await netslice_scenario_check(self, netslice_scenario["netslice_scenario_id"],
302 # nsir_id, db_nsir_update_RO)
303
304 # db_nsir_update["_admin.deployed.RO"] = db_nsir_update_RO
305 # self.update_db_2("nsis", nsir_id, db_nsir_update)
306
307 # Iterate over the network services operation ids to instantiate NSs
308 # TODO: (future improvement) look another way check the tasks instead of keep asking
309 # -> https://docs.python.org/3/library/asyncio-task.html#waiting-primitives
310 # steps: declare ns_tasks, add task when terminate is called, await asyncio.wait(vca_task_list, timeout=300)
311 db_nsir = self.db.get_one("nsis", {"_id": nsir_id})
312 nslcmop_ids = db_nsilcmop["operationParams"].get("nslcmops_ids")
313 for nslcmop_id in nslcmop_ids:
314 nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
315 # Overwriting netslice-vld vim-net-id to ns
316 nsr_id, nslcmop = overwrite_nsd_params(self, db_nsir, nslcmop)
317 step = "Launching ns={} instantiate={} task".format(nsr_id, nslcmop_id)
318 task = asyncio.ensure_future(self.ns.instantiate(nsr_id, nslcmop_id))
319 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_instantiate", task)
320
321 # Wait until Network Slice is ready
322 step = nsir_status_detailed = " Waiting nsi ready. nsi_id={}".format(nsir_id)
323 nsrs_detailed_list_old = None
324 self.logger.debug(logging_text + step)
325
326 # TODO: substitute while for await (all task to be done or not)
327 deployment_timeout = 2 * 3600 # Two hours
328 while deployment_timeout > 0:
329 # Check ns instantiation status
330 nsi_ready = True
331 nsir = self.db.get_one("nsis", {"_id": nsir_id})
332 nsir_admin = nsir["_admin"]
333 nsrs_detailed_list = nsir["_admin"]["nsrs-detailed-list"]
334 nsrs_detailed_list_new = []
335 for nslcmop_item in nslcmop_ids:
336 nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_item})
337 status = nslcmop.get("operationState")
338 # TODO: (future improvement) other possible status: ROLLING_BACK,ROLLED_BACK
339 for nss in nsrs_detailed_list:
340 if nss["nsrId"] == nslcmop["nsInstanceId"]:
341 nss.update({"nsrId": nslcmop["nsInstanceId"], "status": nslcmop["operationState"],
342 "detailed-status":
343 nsir_status_detailed + "; {}".format(nslcmop.get("detailed-status")),
344 "instantiated": True})
345 nsrs_detailed_list_new.append(nss)
346 if status not in ["COMPLETED", "PARTIALLY_COMPLETED", "FAILED", "FAILED_TEMP"]:
347 nsi_ready = False
348
349 if nsrs_detailed_list_new != nsrs_detailed_list_old:
350 nsir_admin["nsrs-detailed-list"] = nsrs_detailed_list_new
351 nsrs_detailed_list_old = nsrs_detailed_list_new
352 db_nsir_update["_admin"] = nsir_admin
353 self.update_db_2("nsis", nsir_id, db_nsir_update)
354
355 if nsi_ready:
356 step = "Network Slice Instance is ready. nsi_id={}".format(nsir_id)
357 for items in nsrs_detailed_list:
358 if "FAILED" in items.values():
359 raise LcmException("Error deploying NSI: {}".format(nsir_id))
360 break
361
362 # TODO: future improvement due to synchronism -> await asyncio.wait(vca_task_list, timeout=300)
363 await asyncio.sleep(5, loop=self.loop)
364 deployment_timeout -= 5
365
366 if deployment_timeout <= 0:
367 raise LcmException("Timeout waiting nsi to be ready. nsi_id={}".format(nsir_id))
368
369 db_nsir_update["operational-status"] = "running"
370 db_nsir_update["detailed-status"] = "done"
371 db_nsir_update["config-status"] = "configured"
372 db_nsilcmop_update["operationState"] = nsilcmop_operation_state = "COMPLETED"
373 db_nsilcmop_update["statusEnteredTime"] = time()
374 db_nsilcmop_update["detailed-status"] = "done"
375 return
376
377 except (LcmException, DbException) as e:
378 self.logger.error(logging_text + "Exit Exception while '{}': {}".format(step, e))
379 exc = e
380 except asyncio.CancelledError:
381 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
382 exc = "Operation was cancelled"
383 except Exception as e:
384 exc = traceback.format_exc()
385 self.logger.critical(logging_text + "Exit Exception {} while '{}': {}".format(type(e).__name__, step, e),
386 exc_info=True)
387 finally:
388 if exc:
389 if db_nsir:
390 db_nsir_update["detailed-status"] = "ERROR {}: {}".format(step, exc)
391 db_nsir_update["operational-status"] = "failed"
392 if db_nsilcmop:
393 db_nsilcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
394 db_nsilcmop_update["operationState"] = nsilcmop_operation_state = "FAILED"
395 db_nsilcmop_update["statusEnteredTime"] = time()
396 try:
397 if db_nsir:
398 db_nsir_update["_admin.nsiState"] = "INSTANTIATED"
399 db_nsir_update["_admin.nsilcmop"] = None
400 self.update_db_2("nsis", nsir_id, db_nsir_update)
401 if db_nsilcmop:
402 self.update_db_2("nsilcmops", nsilcmop_id, db_nsilcmop_update)
403 except DbException as e:
404 self.logger.error(logging_text + "Cannot update database: {}".format(e))
405 if nsilcmop_operation_state:
406 try:
407 await self.msg.aiowrite("nsi", "instantiated", {"nsir_id": nsir_id, "nsilcmop_id": nsilcmop_id,
408 "operationState": nsilcmop_operation_state})
409 except Exception as e:
410 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
411 self.logger.debug(logging_text + "Exit")
412 self.lcm_tasks.remove("nsi", nsir_id, nsilcmop_id, "nsi_instantiate")
413
414 async def terminate(self, nsir_id, nsilcmop_id):
415
416 # Try to lock HA task here
417 task_is_locked_by_me = self.lcm_tasks.lock_HA('nsi', 'nsilcmops', nsilcmop_id)
418 if not task_is_locked_by_me:
419 return
420
421 logging_text = "Task nsi={} terminate={} ".format(nsir_id, nsilcmop_id)
422 self.logger.debug(logging_text + "Enter")
423 exc = None
424 db_nsir = None
425 db_nsilcmop = None
426 db_nsir_update = {"_admin.nsilcmop": nsilcmop_id}
427 db_nsilcmop_update = {}
428 RO = ROclient.ROClient(self.loop, **self.ro_config)
429 nsir_deployed = None
430 failed_detail = [] # annotates all failed error messages
431 nsilcmop_operation_state = None
432 autoremove = False # autoremove after terminated
433 try:
434 # wait for any previous tasks in process
435 await self.lcm_tasks.waitfor_related_HA('nsi', 'nsilcmops', nsilcmop_id)
436
437 step = "Getting nsir={} from db".format(nsir_id)
438 db_nsir = self.db.get_one("nsis", {"_id": nsir_id})
439 nsir_deployed = deepcopy(db_nsir["_admin"].get("deployed"))
440 step = "Getting nsilcmop={} from db".format(nsilcmop_id)
441 db_nsilcmop = self.db.get_one("nsilcmops", {"_id": nsilcmop_id})
442
443 # TODO: Check if makes sense check the nsiState=NOT_INSTANTIATED when terminate
444 # CASE: Instance was terminated but there is a second request to terminate the instance
445 if db_nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED":
446 return
447
448 # Slice status Terminating
449 db_nsir_update["operational-status"] = "terminating"
450 db_nsir_update["config-status"] = "terminating"
451 db_nsir_update["detailed-status"] = "Terminating Netslice subnets"
452 self.update_db_2("nsis", nsir_id, db_nsir_update)
453
454 # Gets the list to keep track of network service records status in the netslice
455 nsir_admin = db_nsir["_admin"]
456 nsrs_detailed_list = []
457
458 # Iterate over the network services operation ids to terminate NSs
459 # TODO: (future improvement) look another way check the tasks instead of keep asking
460 # -> https://docs.python.org/3/library/asyncio-task.html#waiting-primitives
461 # steps: declare ns_tasks, add task when terminate is called, await asyncio.wait(vca_task_list, timeout=300)
462 nslcmop_ids = db_nsilcmop["operationParams"].get("nslcmops_ids")
463 nslcmop_new = []
464 for nslcmop_id in nslcmop_ids:
465 nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
466 nsr_id = nslcmop["operationParams"].get("nsInstanceId")
467 nss_in_use = self.db.get_list("nsis", {"_admin.netslice-vld.ANYINDEX.shared-nsrs-list": nsr_id,
468 "operational-status": {"$nin": ["terminated", "failed"]}})
469 if len(nss_in_use) < 2:
470 task = asyncio.ensure_future(self.ns.terminate(nsr_id, nslcmop_id))
471 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_instantiate", task)
472 nslcmop_new.append(nslcmop_id)
473 else:
474 # Update shared nslcmop shared with active nsi
475 netsliceInstanceId = db_nsir["_id"]
476 for nsis_item in nss_in_use:
477 if db_nsir["_id"] != nsis_item["_id"]:
478 netsliceInstanceId = nsis_item["_id"]
479 break
480 self.db.set_one("nslcmops", {"_id": nslcmop_id},
481 {"operationParams.netsliceInstanceId": netsliceInstanceId})
482 self.db.set_one("nsilcmops", {"_id": nsilcmop_id}, {"operationParams.nslcmops_ids": nslcmop_new})
483
484 # Wait until Network Slice is terminated
485 step = nsir_status_detailed = " Waiting nsi terminated. nsi_id={}".format(nsir_id)
486 nsrs_detailed_list_old = None
487 self.logger.debug(logging_text + step)
488
489 termination_timeout = 2 * 3600 # Two hours
490 while termination_timeout > 0:
491 # Check ns termination status
492 nsi_ready = True
493 db_nsir = self.db.get_one("nsis", {"_id": nsir_id})
494 nsir_admin = db_nsir["_admin"]
495 nsrs_detailed_list = db_nsir["_admin"].get("nsrs-detailed-list")
496 nsrs_detailed_list_new = []
497 for nslcmop_item in nslcmop_ids:
498 nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_item})
499 status = nslcmop["operationState"]
500 # TODO: (future improvement) other possible status: ROLLING_BACK,ROLLED_BACK
501 for nss in nsrs_detailed_list:
502 if nss["nsrId"] == nslcmop["nsInstanceId"]:
503 nss.update({"nsrId": nslcmop["nsInstanceId"], "status": nslcmop["operationState"],
504 "detailed-status":
505 nsir_status_detailed + "; {}".format(nslcmop.get("detailed-status"))})
506 nsrs_detailed_list_new.append(nss)
507 if status not in ["COMPLETED", "PARTIALLY_COMPLETED", "FAILED", "FAILED_TEMP"]:
508 nsi_ready = False
509
510 if nsrs_detailed_list_new != nsrs_detailed_list_old:
511 nsir_admin["nsrs-detailed-list"] = nsrs_detailed_list_new
512 nsrs_detailed_list_old = nsrs_detailed_list_new
513 db_nsir_update["_admin"] = nsir_admin
514 self.update_db_2("nsis", nsir_id, db_nsir_update)
515
516 if nsi_ready:
517 # Check if it is the last used nss and mark isinstantiate: False
518 db_nsir = self.db.get_one("nsis", {"_id": nsir_id})
519 nsir_admin = db_nsir["_admin"]
520 nsrs_detailed_list = db_nsir["_admin"].get("nsrs-detailed-list")
521 for nss in nsrs_detailed_list:
522 _filter = {"_admin.nsrs-detailed-list.ANYINDEX.nsrId": nss["nsrId"],
523 "operational-status.ne": "terminated",
524 "_id.ne": nsir_id}
525 nsis_list = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
526 if not nsis_list:
527 nss.update({"instantiated": False})
528 db_nsir_update["_admin"] = nsir_admin
529 self.update_db_2("nsis", nsir_id, db_nsir_update)
530
531 step = "Network Slice Instance is terminated. nsi_id={}".format(nsir_id)
532 for items in nsrs_detailed_list:
533 if "FAILED" in items.values():
534 raise LcmException("Error terminating NSI: {}".format(nsir_id))
535 break
536
537 await asyncio.sleep(5, loop=self.loop)
538 termination_timeout -= 5
539
540 if termination_timeout <= 0:
541 raise LcmException("Timeout waiting nsi to be terminated. nsi_id={}".format(nsir_id))
542
543 # Delete netslice-vlds
544 RO_nsir_id = RO_delete_action = None
545 for nsir_deployed_RO in get_iterable(nsir_deployed, "RO"):
546 RO_nsir_id = nsir_deployed_RO.get("netslice_scenario_id")
547 try:
548 step = db_nsir_update["detailed-status"] = "Deleting netslice-vld at RO"
549 db_nsilcmop_update["detailed-status"] = "Deleting netslice-vld at RO"
550 self.logger.debug(logging_text + step)
551 desc = await RO.delete("ns", RO_nsir_id)
552 RO_delete_action = desc["action_id"]
553 nsir_deployed_RO["vld_delete_action_id"] = RO_delete_action
554 nsir_deployed_RO["vld_status"] = "DELETING"
555 db_nsir_update["_admin.deployed"] = nsir_deployed
556 self.update_db_2("nsis", nsir_id, db_nsir_update)
557 if RO_delete_action:
558 # wait until NS is deleted from VIM
559 step = "Waiting ns deleted from VIM. RO_id={}".format(RO_nsir_id)
560 self.logger.debug(logging_text + step)
561 except ROclient.ROClientException as e:
562 if e.http_code == 404: # not found
563 nsir_deployed_RO["vld_id"] = None
564 nsir_deployed_RO["vld_status"] = "DELETED"
565 self.logger.debug(logging_text + "RO_ns_id={} already deleted".format(RO_nsir_id))
566 elif e.http_code == 409: # conflict
567 failed_detail.append("RO_ns_id={} delete conflict: {}".format(RO_nsir_id, e))
568 self.logger.debug(logging_text + failed_detail[-1])
569 else:
570 failed_detail.append("RO_ns_id={} delete error: {}".format(RO_nsir_id, e))
571 self.logger.error(logging_text + failed_detail[-1])
572
573 if failed_detail:
574 self.logger.error(logging_text + " ;".join(failed_detail))
575 db_nsir_update["operational-status"] = "failed"
576 db_nsir_update["detailed-status"] = "Deletion errors " + "; ".join(failed_detail)
577 db_nsilcmop_update["detailed-status"] = "; ".join(failed_detail)
578 db_nsilcmop_update["operationState"] = nsilcmop_operation_state = "FAILED"
579 db_nsilcmop_update["statusEnteredTime"] = time()
580 else:
581 db_nsir_update["operational-status"] = "terminating"
582 db_nsir_update["config-status"] = "terminating"
583 db_nsir_update["_admin.nsiState"] = "NOT_INSTANTIATED"
584 db_nsilcmop_update["operationState"] = nsilcmop_operation_state = "COMPLETED"
585 db_nsilcmop_update["statusEnteredTime"] = time()
586 if db_nsilcmop["operationParams"].get("autoremove"):
587 autoremove = True
588
589 db_nsir_update["detailed-status"] = "done"
590 db_nsir_update["operational-status"] = "terminated"
591 db_nsir_update["config-status"] = "terminated"
592 db_nsilcmop_update["statusEnteredTime"] = time()
593 db_nsilcmop_update["detailed-status"] = "done"
594 return
595
596 except (LcmException, DbException) as e:
597 self.logger.error(logging_text + "Exit Exception while '{}': {}".format(step, e))
598 exc = e
599 except asyncio.CancelledError:
600 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
601 exc = "Operation was cancelled"
602 except Exception as e:
603 exc = traceback.format_exc()
604 self.logger.critical(logging_text + "Exit Exception {} while '{}': {}".format(type(e).__name__, step, e),
605 exc_info=True)
606 finally:
607 if exc:
608 if db_nsir:
609 db_nsir_update["_admin.deployed"] = nsir_deployed
610 db_nsir_update["detailed-status"] = "ERROR {}: {}".format(step, exc)
611 db_nsir_update["operational-status"] = "failed"
612 if db_nsilcmop:
613 db_nsilcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
614 db_nsilcmop_update["operationState"] = nsilcmop_operation_state = "FAILED"
615 db_nsilcmop_update["statusEnteredTime"] = time()
616 try:
617 if db_nsir:
618 db_nsir_update["_admin.deployed"] = nsir_deployed
619 db_nsir_update["_admin.nsilcmop"] = None
620 self.update_db_2("nsis", nsir_id, db_nsir_update)
621 if db_nsilcmop:
622 self.update_db_2("nsilcmops", nsilcmop_id, db_nsilcmop_update)
623 except DbException as e:
624 self.logger.error(logging_text + "Cannot update database: {}".format(e))
625
626 if nsilcmop_operation_state:
627 try:
628 await self.msg.aiowrite("nsi", "terminated", {"nsir_id": nsir_id, "nsilcmop_id": nsilcmop_id,
629 "operationState": nsilcmop_operation_state,
630 "autoremove": autoremove},
631 loop=self.loop)
632 except Exception as e:
633 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
634 self.logger.debug(logging_text + "Exit")
635 self.lcm_tasks.remove("nsi", nsir_id, nsilcmop_id, "nsi_terminate")