fix 1102 Mark nsiState to INSTANTIATE at beginning
[osm/LCM.git] / osm_lcm / netslice.py
1 # -*- coding: utf-8 -*-
2 ##
3 # Licensed under the Apache License, Version 2.0 (the "License"); you may
4 # not use this file except in compliance with the License. You may obtain
5 # a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations
13 # under the License.
14 ##
15
16 import asyncio
17 import logging
18 import logging.handlers
19 import traceback
20 from osm_lcm import ROclient
21 from osm_lcm.lcm_utils import LcmException, LcmBase, populate_dict, get_iterable, deep_get
22 from osm_common.dbbase import DbException
23 from time import time
24 from copy import deepcopy
25
26
27 __author__ = "Felipe Vicens, Pol Alemany, Alfonso Tierno"
28
29
30 class NetsliceLcm(LcmBase):
31
32 timeout_nsi_deploy = 2 * 3600 # default global timeout for deployment a nsi
33
34 def __init__(self, db, msg, fs, lcm_tasks, config, loop, ns):
35 """
36 Init, Connect to database, filesystem storage, and messaging
37 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
38 :return: None
39 """
40 # logging
41 self.logger = logging.getLogger('lcm.netslice')
42 self.loop = loop
43 self.lcm_tasks = lcm_tasks
44 self.ns = ns
45 self.ro_config = config["ro_config"]
46 self.timeout = config["timeout"]
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 = deep_get(db_nsir, ("_admin", "deployed", "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 desc = await RO.create("ns", descriptor=RO_ns_params)
222 db_nsir_update_RO = {}
223 db_nsir_update_RO["netslice_scenario_id"] = desc["uuid"]
224 db_nsir_update_RO["vld_id"] = RO_ns_params["name"]
225 db_nsir_update["_admin.deployed.RO"].append(db_nsir_update_RO)
226
227 def overwrite_nsd_params(self, db_nsir, nslcmop):
228 RO_list = []
229 vld_op_list = []
230 vld = None
231 nsr_id = nslcmop.get("nsInstanceId")
232 # Overwrite instantiation parameters in netslice runtime
233 if db_nsir.get("_admin"):
234 if db_nsir["_admin"].get("deployed"):
235 db_admin_deployed_nsir = db_nsir["_admin"].get("deployed")
236 if db_admin_deployed_nsir.get("RO"):
237 RO_list = db_admin_deployed_nsir["RO"]
238
239 for RO_item in RO_list:
240 for netslice_vld in get_iterable(db_nsir["_admin"], "netslice-vld"):
241 # if is equal vld of _admin with vld of netslice-vld then go for the CPs
242 if RO_item.get("vld_id") == netslice_vld.get("id"):
243 # Search the cp of netslice-vld that match with nst:netslice-subnet
244 for nss_cp_item in get_iterable(netslice_vld, "nss-connection-point-ref"):
245 # Search the netslice-subnet of nst that match
246 for nss in get_iterable(db_nsir["_admin"], "netslice-subnet"):
247 # Compare nss-ref equal nss from nst
248 if nss_cp_item["nss-ref"] == nss["nss-id"]:
249 db_nsds = self.db.get_one("nsds", {"_id": nss["nsdId"]})
250 # Go for nsd, and search the CP that match with nst:CP to get vld-id-ref
251 for cp_nsd in db_nsds.get("connection-point", ()):
252 if cp_nsd["name"] == nss_cp_item["nsd-connection-point-ref"]:
253 if nslcmop.get("operationParams"):
254 if nslcmop["operationParams"].get("nsName") == nss["nsName"]:
255 vld_id = RO_item["vld_id"]
256 netslice_scenario_id = RO_item["netslice_scenario_id"]
257 nslcmop_vld = {}
258 nslcmop_vld["ns-net"] = {vld_id: netslice_scenario_id}
259 nslcmop_vld["name"] = cp_nsd["vld-id-ref"]
260 for vld in get_iterable(nslcmop["operationParams"], "vld"):
261 if vld["name"] == cp_nsd["vld-id-ref"]:
262 nslcmop_vld.update(vld)
263 vld_op_list.append(nslcmop_vld)
264 nslcmop["operationParams"]["vld"] = vld_op_list
265 self.update_db_2("nslcmops", nslcmop["_id"], {"operationParams.vld": vld_op_list})
266 return nsr_id, nslcmop
267
268 try:
269 # wait for any previous tasks in process
270 await self.lcm_tasks.waitfor_related_HA('nsi', 'nsilcmops', nsilcmop_id)
271
272 step = "Getting nsir={} from db".format(nsir_id)
273 db_nsir = self.db.get_one("nsis", {"_id": nsir_id})
274 step = "Getting nsilcmop={} from db".format(nsilcmop_id)
275 db_nsilcmop = self.db.get_one("nsilcmops", {"_id": nsilcmop_id})
276
277 start_deploy = time()
278 nsi_params = db_nsilcmop.get("operationParams")
279 if nsi_params and nsi_params.get("timeout_nsi_deploy"):
280 timeout_nsi_deploy = nsi_params["timeout_nsi_deploy"]
281 else:
282 timeout_nsi_deploy = self.timeout.get("nsi_deploy", self.timeout_nsi_deploy)
283
284 # Empty list to keep track of network service records status in the netslice
285 nsir_admin = db_nsir_admin = db_nsir.get("_admin")
286
287 step = "Creating slice operational-status init"
288 # Slice status Creating
289 db_nsir_update["detailed-status"] = "creating"
290 db_nsir_update["operational-status"] = "init"
291 db_nsir_update["_admin.nsiState"] = "INSTANTIATED"
292
293 step = "Instantiating netslice VLDs before NS instantiation"
294 # Creating netslice VLDs networking before NS instantiation
295 db_nsir_update["detailed-status"] = step
296 self.update_db_2("nsis", nsir_id, db_nsir_update)
297 db_nsir_update["_admin.deployed.RO"] = db_nsir_admin["deployed"]["RO"]
298 for vld_item in get_iterable(nsir_admin, "netslice-vld"):
299 await netslice_scenario_create(self, vld_item, nsir_id, db_nsir, db_nsir_admin, db_nsir_update)
300 self.update_db_2("nsis", nsir_id, db_nsir_update)
301
302 step = "Instantiating netslice subnets"
303 db_nsir_update["detailed-status"] = step
304 self.update_db_2("nsis", nsir_id, db_nsir_update)
305
306 db_nsir = self.db.get_one("nsis", {"_id": nsir_id})
307
308 # Check status of the VLDs and wait for creation
309 # netslice_scenarios = db_nsir["_admin"]["deployed"]["RO"]
310 # db_nsir_update_RO = deepcopy(netslice_scenarios)
311 # for netslice_scenario in netslice_scenarios:
312 # await netslice_scenario_check(self, netslice_scenario["netslice_scenario_id"],
313 # nsir_id, db_nsir_update_RO)
314
315 # db_nsir_update["_admin.deployed.RO"] = db_nsir_update_RO
316 # self.update_db_2("nsis", nsir_id, db_nsir_update)
317
318 # Iterate over the network services operation ids to instantiate NSs
319 step = "Instantiating Netslice Subnets"
320 db_nsir = self.db.get_one("nsis", {"_id": nsir_id})
321 nslcmop_ids = db_nsilcmop["operationParams"].get("nslcmops_ids")
322 for nslcmop_id in nslcmop_ids:
323 nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
324 # Overwriting netslice-vld vim-net-id to ns
325 nsr_id, nslcmop = overwrite_nsd_params(self, db_nsir, nslcmop)
326 step = "Launching ns={} instantiate={} task".format(nsr_id, nslcmop_id)
327 task = asyncio.ensure_future(self.ns.instantiate(nsr_id, nslcmop_id))
328 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_instantiate", task)
329
330 # Wait until Network Slice is ready
331 step = " Waiting nsi ready."
332 nsrs_detailed_list_old = None
333 self.logger.debug(logging_text + step)
334
335 # For HA, it is checked from database, as the ns operation may be managed by other LCM worker
336 while time() <= start_deploy + timeout_nsi_deploy:
337 # Check ns instantiation status
338 nsi_ready = True
339 nsir = self.db.get_one("nsis", {"_id": nsir_id})
340 nsrs_detailed_list = nsir["_admin"]["nsrs-detailed-list"]
341 nsrs_detailed_list_new = []
342 for nslcmop_item in nslcmop_ids:
343 nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_item})
344 status = nslcmop.get("operationState")
345 # TODO: (future improvement) other possible status: ROLLING_BACK,ROLLED_BACK
346 for nss in nsrs_detailed_list:
347 if nss["nsrId"] == nslcmop["nsInstanceId"]:
348 nss.update({"nsrId": nslcmop["nsInstanceId"], "status": nslcmop["operationState"],
349 "detailed-status": nslcmop.get("detailed-status"),
350 "instantiated": True})
351 nsrs_detailed_list_new.append(nss)
352 if status not in ["COMPLETED", "PARTIALLY_COMPLETED", "FAILED", "FAILED_TEMP"]:
353 nsi_ready = False
354
355 if nsrs_detailed_list_new != nsrs_detailed_list_old:
356 nsrs_detailed_list_old = nsrs_detailed_list_new
357 self.update_db_2("nsis", nsir_id, {"_admin.nsrs-detailed-list": nsrs_detailed_list_new})
358
359 if nsi_ready:
360 error_list = []
361 step = "Network Slice Instance instantiated"
362 for nss in nsrs_detailed_list:
363 if nss["status"] in ("FAILED", "FAILED_TEMP"):
364 error_list.append("NS {} {}: {}".format(nss["nsrId"], nss["status"],
365 nss["detailed-status"]))
366 if error_list:
367 step = "instantiating"
368 raise LcmException("; ".join(error_list))
369 break
370
371 # TODO: future improvement due to synchronism -> await asyncio.wait(vca_task_list, timeout=300)
372 await asyncio.sleep(5, loop=self.loop)
373
374 else: # timeout_nsi_deploy reached:
375 raise LcmException("Timeout waiting nsi to be ready.")
376
377 db_nsir_update["operational-status"] = "running"
378 db_nsir_update["detailed-status"] = "done"
379 db_nsir_update["config-status"] = "configured"
380 db_nsilcmop_update["operationState"] = nsilcmop_operation_state = "COMPLETED"
381 db_nsilcmop_update["statusEnteredTime"] = time()
382 db_nsilcmop_update["detailed-status"] = "done"
383 return
384
385 except (LcmException, DbException) as e:
386 self.logger.error(logging_text + "Exit Exception while '{}': {}".format(step, e))
387 exc = e
388 except asyncio.CancelledError:
389 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
390 exc = "Operation was cancelled"
391 except Exception as e:
392 exc = traceback.format_exc()
393 self.logger.critical(logging_text + "Exit Exception {} while '{}': {}".format(type(e).__name__, step, e),
394 exc_info=True)
395 finally:
396 if exc:
397 if db_nsir:
398 db_nsir_update["detailed-status"] = "ERROR {}: {}".format(step, exc)
399 db_nsir_update["operational-status"] = "failed"
400 db_nsir_update["config-status"] = "configured"
401 if db_nsilcmop:
402 db_nsilcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
403 db_nsilcmop_update["operationState"] = nsilcmop_operation_state = "FAILED"
404 db_nsilcmop_update["statusEnteredTime"] = time()
405 try:
406 if db_nsir:
407 db_nsir_update["_admin.nsilcmop"] = None
408 self.update_db_2("nsis", nsir_id, db_nsir_update)
409 if db_nsilcmop:
410 self.update_db_2("nsilcmops", nsilcmop_id, db_nsilcmop_update)
411 except DbException as e:
412 self.logger.error(logging_text + "Cannot update database: {}".format(e))
413 if nsilcmop_operation_state:
414 try:
415 await self.msg.aiowrite("nsi", "instantiated", {"nsir_id": nsir_id, "nsilcmop_id": nsilcmop_id,
416 "operationState": nsilcmop_operation_state})
417 except Exception as e:
418 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
419 self.logger.debug(logging_text + "Exit")
420 self.lcm_tasks.remove("nsi", nsir_id, nsilcmop_id, "nsi_instantiate")
421
422 async def terminate(self, nsir_id, nsilcmop_id):
423
424 # Try to lock HA task here
425 task_is_locked_by_me = self.lcm_tasks.lock_HA('nsi', 'nsilcmops', nsilcmop_id)
426 if not task_is_locked_by_me:
427 return
428
429 logging_text = "Task nsi={} terminate={} ".format(nsir_id, nsilcmop_id)
430 self.logger.debug(logging_text + "Enter")
431 exc = None
432 db_nsir = None
433 db_nsilcmop = None
434 db_nsir_update = {"_admin.nsilcmop": nsilcmop_id}
435 db_nsilcmop_update = {}
436 RO = ROclient.ROClient(self.loop, **self.ro_config)
437 nsir_deployed = None
438 failed_detail = [] # annotates all failed error messages
439 nsilcmop_operation_state = None
440 autoremove = False # autoremove after terminated
441 try:
442 # wait for any previous tasks in process
443 await self.lcm_tasks.waitfor_related_HA('nsi', 'nsilcmops', nsilcmop_id)
444
445 step = "Getting nsir={} from db".format(nsir_id)
446 db_nsir = self.db.get_one("nsis", {"_id": nsir_id})
447 nsir_deployed = deepcopy(db_nsir["_admin"].get("deployed"))
448 step = "Getting nsilcmop={} from db".format(nsilcmop_id)
449 db_nsilcmop = self.db.get_one("nsilcmops", {"_id": nsilcmop_id})
450
451 # TODO: Check if makes sense check the nsiState=NOT_INSTANTIATED when terminate
452 # CASE: Instance was terminated but there is a second request to terminate the instance
453 if db_nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED":
454 return
455
456 # Slice status Terminating
457 db_nsir_update["operational-status"] = "terminating"
458 db_nsir_update["config-status"] = "terminating"
459 db_nsir_update["detailed-status"] = "Terminating Netslice subnets"
460 self.update_db_2("nsis", nsir_id, db_nsir_update)
461
462 # Gets the list to keep track of network service records status in the netslice
463 nsrs_detailed_list = []
464
465 # Iterate over the network services operation ids to terminate NSs
466 # TODO: (future improvement) look another way check the tasks instead of keep asking
467 # -> https://docs.python.org/3/library/asyncio-task.html#waiting-primitives
468 # steps: declare ns_tasks, add task when terminate is called, await asyncio.wait(vca_task_list, timeout=300)
469 step = "Terminating Netslice Subnets"
470 nslcmop_ids = db_nsilcmop["operationParams"].get("nslcmops_ids")
471 nslcmop_new = []
472 for nslcmop_id in nslcmop_ids:
473 nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
474 nsr_id = nslcmop["operationParams"].get("nsInstanceId")
475 nss_in_use = self.db.get_list("nsis", {"_admin.netslice-vld.ANYINDEX.shared-nsrs-list": nsr_id,
476 "operational-status": {"$nin": ["terminated", "failed"]}})
477 if len(nss_in_use) < 2:
478 task = asyncio.ensure_future(self.ns.terminate(nsr_id, nslcmop_id))
479 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_instantiate", task)
480 nslcmop_new.append(nslcmop_id)
481 else:
482 # Update shared nslcmop shared with active nsi
483 netsliceInstanceId = db_nsir["_id"]
484 for nsis_item in nss_in_use:
485 if db_nsir["_id"] != nsis_item["_id"]:
486 netsliceInstanceId = nsis_item["_id"]
487 break
488 self.db.set_one("nslcmops", {"_id": nslcmop_id},
489 {"operationParams.netsliceInstanceId": netsliceInstanceId})
490 self.db.set_one("nsilcmops", {"_id": nsilcmop_id}, {"operationParams.nslcmops_ids": nslcmop_new})
491
492 # Wait until Network Slice is terminated
493 step = nsir_status_detailed = " Waiting nsi terminated. nsi_id={}".format(nsir_id)
494 nsrs_detailed_list_old = None
495 self.logger.debug(logging_text + step)
496
497 termination_timeout = 2 * 3600 # Two hours
498 while termination_timeout > 0:
499 # Check ns termination status
500 nsi_ready = True
501 db_nsir = self.db.get_one("nsis", {"_id": nsir_id})
502 nsrs_detailed_list = db_nsir["_admin"].get("nsrs-detailed-list")
503 nsrs_detailed_list_new = []
504 for nslcmop_item in nslcmop_ids:
505 nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_item})
506 status = nslcmop["operationState"]
507 # TODO: (future improvement) other possible status: ROLLING_BACK,ROLLED_BACK
508 for nss in nsrs_detailed_list:
509 if nss["nsrId"] == nslcmop["nsInstanceId"]:
510 nss.update({"nsrId": nslcmop["nsInstanceId"], "status": nslcmop["operationState"],
511 "detailed-status":
512 nsir_status_detailed + "; {}".format(nslcmop.get("detailed-status"))})
513 nsrs_detailed_list_new.append(nss)
514 if status not in ["COMPLETED", "PARTIALLY_COMPLETED", "FAILED", "FAILED_TEMP"]:
515 nsi_ready = False
516
517 if nsrs_detailed_list_new != nsrs_detailed_list_old:
518 nsrs_detailed_list_old = nsrs_detailed_list_new
519 self.update_db_2("nsis", nsir_id, {"_admin.nsrs-detailed-list": nsrs_detailed_list_new})
520
521 if nsi_ready:
522 # Check if it is the last used nss and mark isinstantiate: False
523 db_nsir = self.db.get_one("nsis", {"_id": nsir_id})
524 nsrs_detailed_list = db_nsir["_admin"].get("nsrs-detailed-list")
525 for nss in nsrs_detailed_list:
526 _filter = {"_admin.nsrs-detailed-list.ANYINDEX.nsrId": nss["nsrId"],
527 "operational-status.ne": "terminated",
528 "_id.ne": nsir_id}
529 nsis_list = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
530 if not nsis_list:
531 nss.update({"instantiated": False})
532
533 step = "Network Slice Instance is terminated. nsi_id={}".format(nsir_id)
534 for items in nsrs_detailed_list:
535 if "FAILED" in items.values():
536 raise LcmException("Error terminating NSI: {}".format(nsir_id))
537 break
538
539 await asyncio.sleep(5, loop=self.loop)
540 termination_timeout -= 5
541
542 if termination_timeout <= 0:
543 raise LcmException("Timeout waiting nsi to be terminated. nsi_id={}".format(nsir_id))
544
545 # Delete netslice-vlds
546 RO_nsir_id = RO_delete_action = None
547 for nsir_deployed_RO in get_iterable(nsir_deployed, "RO"):
548 RO_nsir_id = nsir_deployed_RO.get("netslice_scenario_id")
549 try:
550 step = db_nsir_update["detailed-status"] = "Deleting netslice-vld at RO"
551 db_nsilcmop_update["detailed-status"] = "Deleting netslice-vld at RO"
552 self.logger.debug(logging_text + step)
553 desc = await RO.delete("ns", RO_nsir_id)
554 RO_delete_action = desc["action_id"]
555 nsir_deployed_RO["vld_delete_action_id"] = RO_delete_action
556 nsir_deployed_RO["vld_status"] = "DELETING"
557 db_nsir_update["_admin.deployed"] = nsir_deployed
558 self.update_db_2("nsis", nsir_id, db_nsir_update)
559 if RO_delete_action:
560 # wait until NS is deleted from VIM
561 step = "Waiting ns deleted from VIM. RO_id={}".format(RO_nsir_id)
562 self.logger.debug(logging_text + step)
563 except ROclient.ROClientException as e:
564 if e.http_code == 404: # not found
565 nsir_deployed_RO["vld_id"] = None
566 nsir_deployed_RO["vld_status"] = "DELETED"
567 self.logger.debug(logging_text + "RO_ns_id={} already deleted".format(RO_nsir_id))
568 elif e.http_code == 409: # conflict
569 failed_detail.append("RO_ns_id={} delete conflict: {}".format(RO_nsir_id, e))
570 self.logger.debug(logging_text + failed_detail[-1])
571 else:
572 failed_detail.append("RO_ns_id={} delete error: {}".format(RO_nsir_id, e))
573 self.logger.error(logging_text + failed_detail[-1])
574
575 if failed_detail:
576 self.logger.error(logging_text + " ;".join(failed_detail))
577 db_nsir_update["operational-status"] = "failed"
578 db_nsir_update["detailed-status"] = "Deletion errors " + "; ".join(failed_detail)
579 db_nsilcmop_update["detailed-status"] = "; ".join(failed_detail)
580 db_nsilcmop_update["operationState"] = nsilcmop_operation_state = "FAILED"
581 db_nsilcmop_update["statusEnteredTime"] = time()
582 else:
583 db_nsir_update["operational-status"] = "terminating"
584 db_nsir_update["config-status"] = "terminating"
585 db_nsir_update["_admin.nsiState"] = "NOT_INSTANTIATED"
586 db_nsilcmop_update["operationState"] = nsilcmop_operation_state = "COMPLETED"
587 db_nsilcmop_update["statusEnteredTime"] = time()
588 if db_nsilcmop["operationParams"].get("autoremove"):
589 autoremove = True
590
591 db_nsir_update["detailed-status"] = "done"
592 db_nsir_update["operational-status"] = "terminated"
593 db_nsir_update["config-status"] = "terminated"
594 db_nsilcmop_update["statusEnteredTime"] = time()
595 db_nsilcmop_update["detailed-status"] = "done"
596 return
597
598 except (LcmException, DbException) as e:
599 self.logger.error(logging_text + "Exit Exception while '{}': {}".format(step, e))
600 exc = e
601 except asyncio.CancelledError:
602 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
603 exc = "Operation was cancelled"
604 except Exception as e:
605 exc = traceback.format_exc()
606 self.logger.critical(logging_text + "Exit Exception {} while '{}': {}".format(type(e).__name__, step, e),
607 exc_info=True)
608 finally:
609 if exc:
610 if db_nsir:
611 db_nsir_update["_admin.deployed"] = nsir_deployed
612 db_nsir_update["detailed-status"] = "ERROR {}: {}".format(step, exc)
613 db_nsir_update["operational-status"] = "failed"
614 if db_nsilcmop:
615 db_nsilcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
616 db_nsilcmop_update["operationState"] = nsilcmop_operation_state = "FAILED"
617 db_nsilcmop_update["statusEnteredTime"] = time()
618 try:
619 if db_nsir:
620 db_nsir_update["_admin.deployed"] = nsir_deployed
621 db_nsir_update["_admin.nsilcmop"] = None
622 self.update_db_2("nsis", nsir_id, db_nsir_update)
623 if db_nsilcmop:
624 self.update_db_2("nsilcmops", nsilcmop_id, db_nsilcmop_update)
625 except DbException as e:
626 self.logger.error(logging_text + "Cannot update database: {}".format(e))
627
628 if nsilcmop_operation_state:
629 try:
630 await self.msg.aiowrite("nsi", "terminated", {"nsir_id": nsir_id, "nsilcmop_id": nsilcmop_id,
631 "operationState": nsilcmop_operation_state,
632 "autoremove": autoremove},
633 loop=self.loop)
634 except Exception as e:
635 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
636 self.logger.debug(logging_text + "Exit")
637 self.lcm_tasks.remove("nsi", nsir_id, nsilcmop_id, "nsi_terminate")