blob: d2843048bd82cca0a1a75fa7b7c32848433b3ba8 [file] [log] [blame]
Felipe Vicensc2033f22018-11-15 15:09:58 +01001# -*- coding: utf-8 -*-
tierno8069ce52019-08-28 15:34:33 +00002##
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##
Felipe Vicensc2033f22018-11-15 15:09:58 +010015
16import asyncio
17import logging
18import logging.handlers
19import traceback
tierno8069ce52019-08-28 15:34:33 +000020from osm_lcm.ns import populate_dict as populate_dict
21from osm_lcm import ROclient, ns
22from osm_lcm.lcm_utils import LcmException, LcmBase
Felipe Vicensc2033f22018-11-15 15:09:58 +010023from osm_common.dbbase import DbException
24from time import time
Felipe Vicens6559b4a2018-12-01 04:40:48 +010025from copy import deepcopy
26
Felipe Vicensc2033f22018-11-15 15:09:58 +010027
28__author__ = "Felipe Vicens, Pol Alemany, Alfonso Tierno"
29
30
Felipe Vicens6559b4a2018-12-01 04:40:48 +010031def get_iterable(in_dict, in_key):
32 """
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
37 """
38 if not in_dict.get(in_key):
39 return ()
40 return in_dict[in_key]
41
42
Felipe Vicensc2033f22018-11-15 15:09:58 +010043class NetsliceLcm(LcmBase):
44
Felipe Vicens6559b4a2018-12-01 04:40:48 +010045 total_deploy_timeout = 2 * 3600 # global timeout for deployment
46
Felipe Vicensc2033f22018-11-15 15:09:58 +010047 def __init__(self, db, msg, fs, lcm_tasks, ro_config, vca_config, loop):
48 """
49 Init, Connect to database, filesystem storage, and messaging
50 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
51 :return: None
52 """
53 # logging
54 self.logger = logging.getLogger('lcm.netslice')
55 self.loop = loop
56 self.lcm_tasks = lcm_tasks
57 self.ns = ns.NsLcm(db, msg, fs, lcm_tasks, ro_config, vca_config, loop)
Felipe Vicens6559b4a2018-12-01 04:40:48 +010058 self.ro_config = ro_config
Felipe Vicensc2033f22018-11-15 15:09:58 +010059
60 super().__init__(db, msg, fs, self.logger)
61
Felipe Vicens0f389ce2019-01-12 12:20:11 +010062 def nsi_update_nsir(self, nsi_update_nsir, db_nsir, nsir_desc_RO):
63 """
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
69 """
70
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"):
74 continue
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
80 break
81 else:
82 raise LcmException("ns_update_nsir: Not found vld={} at RO info".format(vld["id"]))
83
Felipe Vicensc2033f22018-11-15 15:09:58 +010084 async def instantiate(self, nsir_id, nsilcmop_id):
kuused124bfe2019-06-18 12:09:24 +020085
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:
89 return
90
Felipe Vicensc2033f22018-11-15 15:09:58 +010091 logging_text = "Task netslice={} instantiate={} ".format(nsir_id, nsilcmop_id)
92 self.logger.debug(logging_text + "Enter")
93 # get all needed from database
Felipe Vicens0f389ce2019-01-12 12:20:11 +010094 exc = None
Felipe Vicensc2033f22018-11-15 15:09:58 +010095 db_nsir = None
96 db_nsilcmop = None
97 db_nsir_update = {"_admin.nsilcmop": nsilcmop_id}
98 db_nsilcmop_update = {}
99 nsilcmop_operation_state = None
Felipe Vicens6559b4a2018-12-01 04:40:48 +0100100 vim_2_RO = {}
101 RO = ROclient.ROClient(self.loop, **self.ro_config)
Felipe Vicens720b07a2019-01-31 02:32:09 +0100102
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'])
110 else:
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")
118 return RO_ip_profile
Felipe Vicens6559b4a2018-12-01 04:40:48 +0100119
120 def vim_account_2_RO(vim_account):
121 """
122 Translate a RO vim_account from OSM vim_account params
123 :param ns_params: OSM instantiate params
124 :return: The RO ns descriptor
125 """
126 if vim_account in vim_2_RO:
127 return vim_2_RO[vim_account]
128
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
135 return RO_vim_id
136
Felipe Vicens720b07a2019-01-31 02:32:09 +0100137 async def netslice_scenario_create(self, vld_item, nsir_id, db_nsir, db_nsir_admin, db_nsir_update):
138 """
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
142 """
143 ip_vld = None
144 mgmt_network = False
145 RO_vld_sites = []
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")
150
151 vld_shared = None
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)
155 if shared_nsi:
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}
159 break
160 break
161
162 # Creating netslice-vld at RO
163 RO_nsir = db_nsir["_admin"].get("deployed", {}).get("RO", [])
164
165 if vld_id in RO_nsir:
166 db_nsir_update["_admin.deployed.RO"] = RO_nsir
167
168 # If netslice-vld doesn't exists then create it
169 else:
170 # TODO: Check VDU type in all descriptors finding SRIOV / PT
171 # Updating network names and datacenters from instantiation parameters for each VLD
172 RO_ns_params = {}
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)
178
179 if netslice_vld.get("mgmt-network"):
180 mgmt_network = True
181
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
185 if ip_vld:
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"]))
193
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)
202 })
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)
208 })
209 else:
210 RO_vld_sites.append({
211 "netmap-use": ip_vld[vim_network_option],
212 "datacenter": vim_account_2_RO(netslice_vld["vimAccountId"])})
213
214 # Use default netslice vim-network-name from template
215 else:
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"])})
222
223 if vld_shared:
224 populate_dict(RO_ns_params, ("networks", netslice_vld["name"], "use-network"), vld_shared)
225
226 if RO_vld_sites:
227 populate_dict(RO_ns_params, ("networks", netslice_vld["name"], "sites"), RO_vld_sites)
228
229 RO_ns_params["scenario"] = {"nets": [{"name": netslice_vld["name"],
230 "external": mgmt_network, "type": "bridge"}]}
231
232 # self.logger.debug(logging_text + step)
Felipe Vicens720b07a2019-01-31 02:32:09 +0100233 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)
kuused124bfe2019-06-18 12:09:24 +0200238
Felipe Vicens720b07a2019-01-31 02:32:09 +0100239 def overwrite_nsd_params(self, db_nsir, nslcmop):
240 RO_list = []
241 vld_op_list = []
242 vld = None
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"]
250
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"]
269 nslcmop_vld = {}
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
Felipe Vicensb0e5fe42019-12-05 10:30:38 +0100277 self.update_db_2("nslcmops", nslcmop["_id"], {"operationParams.vld": vld_op_list})
Felipe Vicens720b07a2019-01-31 02:32:09 +0100278 return nsr_id, nslcmop
279
Felipe Vicensc2033f22018-11-15 15:09:58 +0100280 try:
kuused124bfe2019-06-18 12:09:24 +0200281 # wait for any previous tasks in process
282 await self.lcm_tasks.waitfor_related_HA('nsi', 'nsilcmops', nsilcmop_id)
283
Felipe Vicensc2033f22018-11-15 15:09:58 +0100284 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})
Felipe Vicens720b07a2019-01-31 02:32:09 +0100288
Felipe Vicensc2033f22018-11-15 15:09:58 +0100289 # Empty list to keep track of network service records status in the netslice
Felipe Vicens720b07a2019-01-31 02:32:09 +0100290 nsir_admin = db_nsir_admin = db_nsir.get("_admin")
Felipe Vicensc2033f22018-11-15 15:09:58 +0100291
Felipe Vicensb0e5fe42019-12-05 10:30:38 +0100292 step = "Creating slice operational-status init"
Felipe Vicensc2033f22018-11-15 15:09:58 +0100293 # Slice status Creating
294 db_nsir_update["detailed-status"] = "creating"
295 db_nsir_update["operational-status"] = "init"
kuused124bfe2019-06-18 12:09:24 +0200296 self.update_db_2("nsis", nsir_id, db_nsir_update)
297
Felipe Vicensb0e5fe42019-12-05 10:30:38 +0100298 step = "Creating netslice VLDs before NS instantiation"
Felipe Vicens0f389ce2019-01-12 12:20:11 +0100299 # Creating netslice VLDs networking before NS instantiation
Felipe Vicensb0e5fe42019-12-05 10:30:38 +0100300 db_nsir_update["detailed-status"] = "Creating netslice-vld at RO"
301 self.update_db_2("nsis", nsir_id, db_nsir_update)
Felipe Vicens720b07a2019-01-31 02:32:09 +0100302 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)
kuused124bfe2019-06-18 12:09:24 +0200306
Felipe Vicensb0e5fe42019-12-05 10:30:38 +0100307 step = "Creating netslice subnets at RO"
Felipe Vicens720b07a2019-01-31 02:32:09 +0100308 db_nsir_update["detailed-status"] = "Creating netslice subnets at RO"
kuused124bfe2019-06-18 12:09:24 +0200309 self.update_db_2("nsis", nsir_id, db_nsir_update)
Felipe Vicens0f389ce2019-01-12 12:20:11 +0100310
Felipe Vicens720b07a2019-01-31 02:32:09 +0100311 db_nsir = self.db.get_one("nsis", {"_id": nsir_id})
Felipe Vicens0f389ce2019-01-12 12:20:11 +0100312
Felipe Vicens720b07a2019-01-31 02:32:09 +0100313 # 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:
kuused124bfe2019-06-18 12:09:24 +0200317 # await netslice_scenario_check(self, netslice_scenario["netslice_scenario_id"],
Felipe Vicens720b07a2019-01-31 02:32:09 +0100318 # nsir_id, db_nsir_update_RO)
kuused124bfe2019-06-18 12:09:24 +0200319
Felipe Vicens720b07a2019-01-31 02:32:09 +0100320 # db_nsir_update["_admin.deployed.RO"] = db_nsir_update_RO
321 # self.update_db_2("nsis", nsir_id, db_nsir_update)
Felipe Vicens6559b4a2018-12-01 04:40:48 +0100322
Felipe Vicensc2033f22018-11-15 15:09:58 +0100323 # Iterate over the network services operation ids to instantiate NSs
Felipe Vicens720b07a2019-01-31 02:32:09 +0100324 # TODO: (future improvement) look another way check the tasks instead of keep asking
Felipe Vicensc2033f22018-11-15 15:09:58 +0100325 # -> 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)
Felipe Vicensb0e5fe42019-12-05 10:30:38 +0100327 step = "Instantiating Netslice Subnets"
Felipe Vicens0f389ce2019-01-12 12:20:11 +0100328 db_nsir = self.db.get_one("nsis", {"_id": nsir_id})
Felipe Vicensc2033f22018-11-15 15:09:58 +0100329 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})
Felipe Vicens720b07a2019-01-31 02:32:09 +0100332 # 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)
Felipe Vicensc2033f22018-11-15 15:09:58 +0100335 task = asyncio.ensure_future(self.ns.instantiate(nsr_id, nslcmop_id))
336 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_instantiate", task)
kuused124bfe2019-06-18 12:09:24 +0200337
Felipe Vicensc2033f22018-11-15 15:09:58 +0100338 # 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)
kuused124bfe2019-06-18 12:09:24 +0200342
Felipe Vicensc2033f22018-11-15 15:09:58 +0100343 # 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
347 nsi_ready = True
Felipe Vicens720b07a2019-01-31 02:32:09 +0100348 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 = []
Felipe Vicensc2033f22018-11-15 15:09:58 +0100352 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
Felipe Vicens720b07a2019-01-31 02:32:09 +0100356 for nss in nsrs_detailed_list:
357 if nss["nsrId"] == nslcmop["nsInstanceId"]:
358 nss.update({"nsrId": nslcmop["nsInstanceId"], "status": nslcmop["operationState"],
359 "detailed-status":
360 nsir_status_detailed + "; {}".format(nslcmop.get("detailed-status")),
361 "instantiated": True})
362 nsrs_detailed_list_new.append(nss)
Felipe Vicensb0e5fe42019-12-05 10:30:38 +0100363 if status not in ["COMPLETED", "PARTIALLY_COMPLETED", "FAILED", "FAILED_TEMP"]:
Felipe Vicensc2033f22018-11-15 15:09:58 +0100364 nsi_ready = False
365
Felipe Vicens720b07a2019-01-31 02:32:09 +0100366 if nsrs_detailed_list_new != nsrs_detailed_list_old:
Felipe Vicens720b07a2019-01-31 02:32:09 +0100367 nsrs_detailed_list_old = nsrs_detailed_list_new
Felipe Vicensb0e5fe42019-12-05 10:30:38 +0100368 self.update_db_2("nsis", nsir_id, {"_admin.nsrs-detailed-list": nsrs_detailed_list_new})
Felipe Vicensc2033f22018-11-15 15:09:58 +0100369
370 if nsi_ready:
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))
375 break
Felipe Vicensb0e5fe42019-12-05 10:30:38 +0100376
Felipe Vicensc2033f22018-11-15 15:09:58 +0100377 # 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
Felipe Vicensb0e5fe42019-12-05 10:30:38 +0100380
Felipe Vicensc2033f22018-11-15 15:09:58 +0100381 if deployment_timeout <= 0:
382 raise LcmException("Timeout waiting nsi to be ready. nsi_id={}".format(nsir_id))
383
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"
390 return
391
392 except (LcmException, DbException) as e:
393 self.logger.error(logging_text + "Exit Exception while '{}': {}".format(step, e))
394 exc = 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),
401 exc_info=True)
402 finally:
403 if exc:
404 if db_nsir:
405 db_nsir_update["detailed-status"] = "ERROR {}: {}".format(step, exc)
406 db_nsir_update["operational-status"] = "failed"
407 if db_nsilcmop:
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()
tiernobaa51102018-12-14 13:16:18 +0000411 try:
412 if db_nsir:
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)
416 if db_nsilcmop:
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))
Felipe Vicensc2033f22018-11-15 15:09:58 +0100420 if nsilcmop_operation_state:
421 try:
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")
428
429 async def terminate(self, nsir_id, nsilcmop_id):
kuused124bfe2019-06-18 12:09:24 +0200430
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:
434 return
435
Felipe Vicensc2033f22018-11-15 15:09:58 +0100436 logging_text = "Task nsi={} terminate={} ".format(nsir_id, nsilcmop_id)
437 self.logger.debug(logging_text + "Enter")
kuused124bfe2019-06-18 12:09:24 +0200438 exc = None
Felipe Vicensc2033f22018-11-15 15:09:58 +0100439 db_nsir = None
440 db_nsilcmop = None
441 db_nsir_update = {"_admin.nsilcmop": nsilcmop_id}
442 db_nsilcmop_update = {}
Felipe Vicens6559b4a2018-12-01 04:40:48 +0100443 RO = ROclient.ROClient(self.loop, **self.ro_config)
Felipe Vicens720b07a2019-01-31 02:32:09 +0100444 nsir_deployed = None
Felipe Vicens6559b4a2018-12-01 04:40:48 +0100445 failed_detail = [] # annotates all failed error messages
Felipe Vicensc2033f22018-11-15 15:09:58 +0100446 nsilcmop_operation_state = None
tiernoc2564fe2019-01-28 16:18:56 +0000447 autoremove = False # autoremove after terminated
Felipe Vicensc2033f22018-11-15 15:09:58 +0100448 try:
kuused124bfe2019-06-18 12:09:24 +0200449 # wait for any previous tasks in process
450 await self.lcm_tasks.waitfor_related_HA('nsi', 'nsilcmops', nsilcmop_id)
451
Felipe Vicensc2033f22018-11-15 15:09:58 +0100452 step = "Getting nsir={} from db".format(nsir_id)
453 db_nsir = self.db.get_one("nsis", {"_id": nsir_id})
Felipe Vicens720b07a2019-01-31 02:32:09 +0100454 nsir_deployed = deepcopy(db_nsir["_admin"].get("deployed"))
Felipe Vicensc2033f22018-11-15 15:09:58 +0100455 step = "Getting nsilcmop={} from db".format(nsilcmop_id)
456 db_nsilcmop = self.db.get_one("nsilcmops", {"_id": nsilcmop_id})
kuused124bfe2019-06-18 12:09:24 +0200457
Felipe Vicensc2033f22018-11-15 15:09:58 +0100458 # 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":
461 return
462
463 # Slice status Terminating
464 db_nsir_update["operational-status"] = "terminating"
465 db_nsir_update["config-status"] = "terminating"
Felipe Vicens720b07a2019-01-31 02:32:09 +0100466 db_nsir_update["detailed-status"] = "Terminating Netslice subnets"
Felipe Vicensc2033f22018-11-15 15:09:58 +0100467 self.update_db_2("nsis", nsir_id, db_nsir_update)
468
Felipe Vicensc2033f22018-11-15 15:09:58 +0100469 # Gets the list to keep track of network service records status in the netslice
kuused124bfe2019-06-18 12:09:24 +0200470 nsrs_detailed_list = []
Felipe Vicensc2033f22018-11-15 15:09:58 +0100471
472 # Iterate over the network services operation ids to terminate NSs
kuused124bfe2019-06-18 12:09:24 +0200473 # TODO: (future improvement) look another way check the tasks instead of keep asking
Felipe Vicensc2033f22018-11-15 15:09:58 +0100474 # -> 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)
Felipe Vicensb0e5fe42019-12-05 10:30:38 +0100476 step = "Terminating Netslice Subnets"
Felipe Vicensc2033f22018-11-15 15:09:58 +0100477 nslcmop_ids = db_nsilcmop["operationParams"].get("nslcmops_ids")
Felipe Vicens720b07a2019-01-31 02:32:09 +0100478 nslcmop_new = []
Felipe Vicensc2033f22018-11-15 15:09:58 +0100479 for nslcmop_id in nslcmop_ids:
480 nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
481 nsr_id = nslcmop["operationParams"].get("nsInstanceId")
Felipe Vicens720b07a2019-01-31 02:32:09 +0100482 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)
488 else:
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"]
494 break
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})
Felipe Vicensc2033f22018-11-15 15:09:58 +0100498
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)
kuused124bfe2019-06-18 12:09:24 +0200503
Felipe Vicensc2033f22018-11-15 15:09:58 +0100504 termination_timeout = 2 * 3600 # Two hours
505 while termination_timeout > 0:
506 # Check ns termination status
507 nsi_ready = True
Felipe Vicens720b07a2019-01-31 02:32:09 +0100508 db_nsir = self.db.get_one("nsis", {"_id": nsir_id})
Felipe Vicens720b07a2019-01-31 02:32:09 +0100509 nsrs_detailed_list = db_nsir["_admin"].get("nsrs-detailed-list")
510 nsrs_detailed_list_new = []
Felipe Vicensc2033f22018-11-15 15:09:58 +0100511 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
Felipe Vicens720b07a2019-01-31 02:32:09 +0100515 for nss in nsrs_detailed_list:
516 if nss["nsrId"] == nslcmop["nsInstanceId"]:
517 nss.update({"nsrId": nslcmop["nsInstanceId"], "status": nslcmop["operationState"],
518 "detailed-status":
519 nsir_status_detailed + "; {}".format(nslcmop.get("detailed-status"))})
520 nsrs_detailed_list_new.append(nss)
Felipe Vicensc2033f22018-11-15 15:09:58 +0100521 if status not in ["COMPLETED", "PARTIALLY_COMPLETED", "FAILED", "FAILED_TEMP"]:
522 nsi_ready = False
523
Felipe Vicens720b07a2019-01-31 02:32:09 +0100524 if nsrs_detailed_list_new != nsrs_detailed_list_old:
Felipe Vicens720b07a2019-01-31 02:32:09 +0100525 nsrs_detailed_list_old = nsrs_detailed_list_new
Felipe Vicensb0e5fe42019-12-05 10:30:38 +0100526 self.update_db_2("nsis", nsir_id, {"_admin.nsrs-detailed-list": nsrs_detailed_list_new})
527
Felipe Vicensc2033f22018-11-15 15:09:58 +0100528 if nsi_ready:
Felipe Vicens720b07a2019-01-31 02:32:09 +0100529 # Check if it is the last used nss and mark isinstantiate: False
530 db_nsir = self.db.get_one("nsis", {"_id": nsir_id})
Felipe Vicens720b07a2019-01-31 02:32:09 +0100531 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",
535 "_id.ne": nsir_id}
536 nsis_list = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
537 if not nsis_list:
538 nss.update({"instantiated": False})
Felipe Vicens720b07a2019-01-31 02:32:09 +0100539
Felipe Vicensc2033f22018-11-15 15:09:58 +0100540 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))
544 break
545
546 await asyncio.sleep(5, loop=self.loop)
547 termination_timeout -= 5
548
549 if termination_timeout <= 0:
550 raise LcmException("Timeout waiting nsi to be terminated. nsi_id={}".format(nsir_id))
551
Felipe Vicens720b07a2019-01-31 02:32:09 +0100552 # Delete netslice-vlds
Felipe Vicens6559b4a2018-12-01 04:40:48 +0100553 RO_nsir_id = RO_delete_action = None
Felipe Vicens720b07a2019-01-31 02:32:09 +0100554 for nsir_deployed_RO in get_iterable(nsir_deployed, "RO"):
555 RO_nsir_id = nsir_deployed_RO.get("netslice_scenario_id")
556 try:
557 step = db_nsir_update["detailed-status"] = "Deleting netslice-vld at RO"
558 db_nsilcmop_update["detailed-status"] = "Deleting netslice-vld at RO"
Felipe Vicens6559b4a2018-12-01 04:40:48 +0100559 self.logger.debug(logging_text + step)
560 desc = await RO.delete("ns", RO_nsir_id)
561 RO_delete_action = desc["action_id"]
Felipe Vicens720b07a2019-01-31 02:32:09 +0100562 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)
566 if RO_delete_action:
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])
578 else:
579 failed_detail.append("RO_ns_id={} delete error: {}".format(RO_nsir_id, e))
580 self.logger.error(logging_text + failed_detail[-1])
Felipe Vicens6559b4a2018-12-01 04:40:48 +0100581
Felipe Vicens720b07a2019-01-31 02:32:09 +0100582 if failed_detail:
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()
Felipe Vicens6559b4a2018-12-01 04:40:48 +0100589 else:
Felipe Vicens720b07a2019-01-31 02:32:09 +0100590 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"):
596 autoremove = True
Felipe Vicens6559b4a2018-12-01 04:40:48 +0100597
Felipe Vicens720b07a2019-01-31 02:32:09 +0100598 db_nsir_update["detailed-status"] = "done"
Felipe Vicensc2033f22018-11-15 15:09:58 +0100599 db_nsir_update["operational-status"] = "terminated"
Felipe Vicens720b07a2019-01-31 02:32:09 +0100600 db_nsir_update["config-status"] = "terminated"
Felipe Vicensc2033f22018-11-15 15:09:58 +0100601 db_nsilcmop_update["statusEnteredTime"] = time()
602 db_nsilcmop_update["detailed-status"] = "done"
603 return
604
605 except (LcmException, DbException) as e:
606 self.logger.error(logging_text + "Exit Exception while '{}': {}".format(step, e))
607 exc = 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),
614 exc_info=True)
615 finally:
616 if exc:
617 if db_nsir:
Felipe Vicens720b07a2019-01-31 02:32:09 +0100618 db_nsir_update["_admin.deployed"] = nsir_deployed
Felipe Vicensc2033f22018-11-15 15:09:58 +0100619 db_nsir_update["detailed-status"] = "ERROR {}: {}".format(step, exc)
620 db_nsir_update["operational-status"] = "failed"
621 if db_nsilcmop:
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()
tiernobaa51102018-12-14 13:16:18 +0000625 try:
626 if db_nsir:
Felipe Vicens720b07a2019-01-31 02:32:09 +0100627 db_nsir_update["_admin.deployed"] = nsir_deployed
tiernobaa51102018-12-14 13:16:18 +0000628 db_nsir_update["_admin.nsilcmop"] = None
tiernobaa51102018-12-14 13:16:18 +0000629 self.update_db_2("nsis", nsir_id, db_nsir_update)
630 if db_nsilcmop:
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))
Felipe Vicensc2033f22018-11-15 15:09:58 +0100634
635 if nsilcmop_operation_state:
636 try:
637 await self.msg.aiowrite("nsi", "terminated", {"nsir_id": nsir_id, "nsilcmop_id": nsilcmop_id,
tiernoc2564fe2019-01-28 16:18:56 +0000638 "operationState": nsilcmop_operation_state,
639 "autoremove": autoremove},
640 loop=self.loop)
Felipe Vicensc2033f22018-11-15 15:09:58 +0100641 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")