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
import ROclient
21 from osm_lcm
.lcm_utils
import LcmException
, LcmBase
, populate_dict
, get_iterable
, deep_get
22 from osm_common
.dbbase
import DbException
24 from copy
import deepcopy
27 __author__
= "Felipe Vicens, Pol Alemany, Alfonso Tierno"
30 class NetsliceLcm(LcmBase
):
32 timeout_nsi_deploy
= 2 * 3600 # default global timeout for deployment a nsi
34 def __init__(self
, db
, msg
, fs
, lcm_tasks
, config
, loop
, ns
):
36 Init, Connect to database, filesystem storage, and messaging
37 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
41 self
.logger
= logging
.getLogger('lcm.netslice')
43 self
.lcm_tasks
= lcm_tasks
45 self
.ro_config
= config
["ro_config"]
46 self
.timeout
= config
["timeout"]
48 super().__init
__(db
, msg
, fs
, self
.logger
)
50 def nsi_update_nsir(self
, nsi_update_nsir
, db_nsir
, nsir_desc_RO
):
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
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"):
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
70 raise LcmException("ns_update_nsir: Not found vld={} at RO info".format(vld
["id"]))
72 async def instantiate(self
, nsir_id
, nsilcmop_id
):
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
:
79 logging_text
= "Task netslice={} instantiate={} ".format(nsir_id
, nsilcmop_id
)
80 self
.logger
.debug(logging_text
+ "Enter")
81 # get all needed from database
85 db_nsir_update
= {"_admin.nsilcmop": nsilcmop_id
}
86 db_nsilcmop_update
= {}
87 nsilcmop_operation_state
= None
89 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
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'])
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")
108 def vim_account_2_RO(vim_account
):
110 Translate a RO vim_account from OSM vim_account params
111 :param ns_params: OSM instantiate params
112 :return: The RO ns descriptor
114 if vim_account
in vim_2_RO
:
115 return vim_2_RO
[vim_account
]
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
125 async def netslice_scenario_create(self
, vld_item
, nsir_id
, db_nsir
, db_nsir_admin
, db_nsir_update
):
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
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")
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)
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
}
150 # Creating netslice-vld at RO
151 RO_nsir
= deep_get(db_nsir
, ("_admin", "deployed", "RO"), [])
153 if vld_id
in RO_nsir
:
154 db_nsir_update
["_admin.deployed.RO"] = RO_nsir
156 # If netslice-vld doesn't exists then create it
158 # TODO: Check VDU type in all descriptors finding SRIOV / PT
159 # Updating network names and datacenters from instantiation parameters for each VLD
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
)
167 if netslice_vld
.get("mgmt-network"):
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
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"]))
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
)
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
)
198 RO_vld_sites
.append({
199 "netmap-use": ip_vld
[vim_network_option
],
200 "datacenter": vim_account_2_RO(netslice_vld
["vimAccountId"])})
202 # Use default netslice vim-network-name from template
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"])})
212 populate_dict(RO_ns_params
, ("networks", netslice_vld
["name"], "use-network"), vld_shared
)
215 populate_dict(RO_ns_params
, ("networks", netslice_vld
["name"], "sites"), RO_vld_sites
)
217 RO_ns_params
["scenario"] = {"nets": [{"name": netslice_vld
["name"],
218 "external": mgmt_network
, "type": "bridge"}]}
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
)
227 def overwrite_nsd_params(self
, db_nsir
, nslcmop
):
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"]
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"]
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
269 # wait for any previous tasks in process
270 await self
.lcm_tasks
.waitfor_related_HA('nsi', 'nsilcmops', nsilcmop_id
)
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
})
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"]
282 timeout_nsi_deploy
= self
.timeout
.get("nsi_deploy", self
.timeout_nsi_deploy
)
284 # Empty list to keep track of network service records status in the netslice
285 nsir_admin
= db_nsir_admin
= db_nsir
.get("_admin")
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"
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
)
302 step
= "Instantiating netslice subnets"
303 db_nsir_update
["detailed-status"] = step
304 self
.update_db_2("nsis", nsir_id
, db_nsir_update
)
306 db_nsir
= self
.db
.get_one("nsis", {"_id": nsir_id
})
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)
315 # db_nsir_update["_admin.deployed.RO"] = db_nsir_update_RO
316 # self.update_db_2("nsis", nsir_id, db_nsir_update)
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
)
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
)
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
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"]:
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
})
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"]))
367 step
= "instantiating"
368 raise LcmException("; ".join(error_list
))
371 # TODO: future improvement due to synchronism -> await asyncio.wait(vca_task_list, timeout=300)
372 await asyncio
.sleep(5, loop
=self
.loop
)
374 else: # timeout_nsi_deploy reached:
375 raise LcmException("Timeout waiting nsi to be ready.")
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"
385 except (LcmException
, DbException
) as e
:
386 self
.logger
.error(logging_text
+ "Exit Exception while '{}': {}".format(step
, 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
),
398 db_nsir_update
["detailed-status"] = "ERROR {}: {}".format(step
, exc
)
399 db_nsir_update
["operational-status"] = "failed"
400 db_nsir_update
["config-status"] = "configured"
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()
407 db_nsir_update
["_admin.nsilcmop"] = None
408 self
.update_db_2("nsis", nsir_id
, db_nsir_update
)
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
:
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")
422 async def terminate(self
, nsir_id
, nsilcmop_id
):
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
:
429 logging_text
= "Task nsi={} terminate={} ".format(nsir_id
, nsilcmop_id
)
430 self
.logger
.debug(logging_text
+ "Enter")
434 db_nsir_update
= {"_admin.nsilcmop": nsilcmop_id
}
435 db_nsilcmop_update
= {}
436 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
438 failed_detail
= [] # annotates all failed error messages
439 nsilcmop_operation_state
= None
440 autoremove
= False # autoremove after terminated
442 # wait for any previous tasks in process
443 await self
.lcm_tasks
.waitfor_related_HA('nsi', 'nsilcmops', nsilcmop_id
)
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
})
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":
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
)
462 # Gets the list to keep track of network service records status in the netslice
463 nsrs_detailed_list
= []
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")
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
)
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"]
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
})
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
)
497 termination_timeout
= 2 * 3600 # Two hours
498 while termination_timeout
> 0:
499 # Check ns termination status
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"],
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"]:
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
})
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",
529 nsis_list
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
531 nss
.update({"instantiated": False})
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
))
539 await asyncio
.sleep(5, loop
=self
.loop
)
540 termination_timeout
-= 5
542 if termination_timeout
<= 0:
543 raise LcmException("Timeout waiting nsi to be terminated. nsi_id={}".format(nsir_id
))
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")
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
)
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])
572 failed_detail
.append("RO_ns_id={} delete error: {}".format(RO_nsir_id
, e
))
573 self
.logger
.error(logging_text
+ failed_detail
[-1])
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()
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"):
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"
598 except (LcmException
, DbException
) as e
:
599 self
.logger
.error(logging_text
+ "Exit Exception while '{}': {}".format(step
, 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
),
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"
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()
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
)
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
))
628 if nsilcmop_operation_state
:
630 await self
.msg
.aiowrite("nsi", "terminated", {"nsir_id": nsir_id
, "nsilcmop_id": nsilcmop_id
,
631 "operationState": nsilcmop_operation_state
,
632 "autoremove": autoremove
},
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")