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