bd83c12b88175add3506c05351a0cc641caeaa08
[osm/LCM.git] / osm_lcm / lcm.py
1 #!/usr/bin/python3
2 # -*- coding: utf-8 -*-
3
4 import asyncio
5 import yaml
6 import logging
7 import logging.handlers
8 import getopt
9 import functools
10 import sys
11 import traceback
12 import ROclient
13 # from osm_lcm import version as lcm_version, version_date as lcm_version_date, ROclient
14 from osm_common import dbmemory, dbmongo, fslocal, msglocal, msgkafka
15 from osm_common import version as common_version
16 from osm_common.dbbase import DbException, deep_update
17 from osm_common.fsbase import FsException
18 from osm_common.msgbase import MsgException
19 from os import environ, path
20 from n2vc.vnf import N2VC
21 from n2vc import version as N2VC_version
22
23 from collections import OrderedDict
24 from copy import deepcopy
25 from http import HTTPStatus
26 from time import time
27
28
29 __author__ = "Alfonso Tierno"
30 min_RO_version = [0, 5, 72]
31 # uncomment if LCM is installed as library and installed, and get them from __init__.py
32 lcm_version = '0.1.14'
33 lcm_version_date = '2018-09-11'
34
35
36 class LcmException(Exception):
37 pass
38
39
40 class TaskRegistry:
41 """
42 Implements a registry of task needed for later cancelation, look for related tasks that must be completed before
43 etc. It stores a four level dict
44 First level is the topic, ns, vim_account, sdn
45 Second level is the _id
46 Third level is the operation id
47 Fourth level is a descriptive name, the value is the task class
48 """
49
50 def __init__(self):
51 self.task_registry = {
52 "ns": {},
53 "vim_account": {},
54 "sdn": {},
55 }
56
57 def register(self, topic, _id, op_id, task_name, task):
58 """
59 Register a new task
60 :param topic: Can be "ns", "vim_account", "sdn"
61 :param _id: _id of the related item
62 :param op_id: id of the operation of the related item
63 :param task_name: Task descriptive name, as create, instantiate, terminate. Must be unique in this op_id
64 :param task: Task class
65 :return: none
66 """
67 if _id not in self.task_registry[topic]:
68 self.task_registry[topic][_id] = OrderedDict()
69 if op_id not in self.task_registry[topic][_id]:
70 self.task_registry[topic][_id][op_id] = {task_name: task}
71 else:
72 self.task_registry[topic][_id][op_id][task_name] = task
73 # print("registering task", topic, _id, op_id, task_name, task)
74
75 def remove(self, topic, _id, op_id, task_name=None):
76 """
77 When task is ended, it should removed. It ignores missing tasks
78 :param topic: Can be "ns", "vim_account", "sdn"
79 :param _id: _id of the related item
80 :param op_id: id of the operation of the related item
81 :param task_name: Task descriptive name. If note it deletes all
82 :return:
83 """
84 if not self.task_registry[topic].get(_id) or not self.task_registry[topic][_id].get(op_id):
85 return
86 if not task_name:
87 # print("deleting tasks", topic, _id, op_id, self.task_registry[topic][_id][op_id])
88 del self.task_registry[topic][_id][op_id]
89 elif task_name in self.task_registry[topic][_id][op_id]:
90 # print("deleting tasks", topic, _id, op_id, task_name, self.task_registry[topic][_id][op_id][task_name])
91 del self.task_registry[topic][_id][op_id][task_name]
92 if not self.task_registry[topic][_id][op_id]:
93 del self.task_registry[topic][_id][op_id]
94 if not self.task_registry[topic][_id]:
95 del self.task_registry[topic][_id]
96
97 def lookfor_related(self, topic, _id, my_op_id=None):
98 task_list = []
99 task_name_list = []
100 if _id not in self.task_registry[topic]:
101 return "", task_name_list
102 for op_id in reversed(self.task_registry[topic][_id]):
103 if my_op_id:
104 if my_op_id == op_id:
105 my_op_id = None # so that the next task is taken
106 continue
107
108 for task_name, task in self.task_registry[topic][_id][op_id].items():
109 task_list.append(task)
110 task_name_list.append(task_name)
111 break
112 return ", ".join(task_name_list), task_list
113
114 def cancel(self, topic, _id, target_op_id=None, target_task_name=None):
115 """
116 Cancel all active tasks of a concrete ns, vim_account, sdn identified for _id. If op_id is supplied only this is
117 cancelled, and the same with task_name
118 """
119 if not self.task_registry[topic].get(_id):
120 return
121 for op_id in reversed(self.task_registry[topic][_id]):
122 if target_op_id and target_op_id != op_id:
123 continue
124 for task_name, task in self.task_registry[topic][_id][op_id].items():
125 if target_task_name and target_task_name != task_name:
126 continue
127 # result =
128 task.cancel()
129 # if result:
130 # self.logger.debug("{} _id={} order_id={} task={} cancelled".format(topic, _id, op_id, task_name))
131
132
133 class Lcm:
134
135 def __init__(self, config_file):
136 """
137 Init, Connect to database, filesystem storage, and messaging
138 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
139 :return: None
140 """
141
142 self.db = None
143 self.msg = None
144 self.fs = None
145 self.pings_not_received = 1
146
147 # contains created tasks/futures to be able to cancel
148 self.lcm_tasks = TaskRegistry()
149 # logging
150 self.logger = logging.getLogger('lcm')
151 # load configuration
152 config = self.read_config_file(config_file)
153 self.config = config
154 self.ro_config = {
155 "endpoint_url": "http://{}:{}/openmano".format(config["RO"]["host"], config["RO"]["port"]),
156 "tenant": config.get("tenant", "osm"),
157 "logger_name": "lcm.ROclient",
158 "loglevel": "ERROR",
159 }
160
161 self.vca = config["VCA"] # TODO VCA
162 self.loop = None
163
164 # logging
165 log_format_simple = "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
166 log_formatter_simple = logging.Formatter(log_format_simple, datefmt='%Y-%m-%dT%H:%M:%S')
167 config["database"]["logger_name"] = "lcm.db"
168 config["storage"]["logger_name"] = "lcm.fs"
169 config["message"]["logger_name"] = "lcm.msg"
170 if config["global"].get("logfile"):
171 file_handler = logging.handlers.RotatingFileHandler(config["global"]["logfile"],
172 maxBytes=100e6, backupCount=9, delay=0)
173 file_handler.setFormatter(log_formatter_simple)
174 self.logger.addHandler(file_handler)
175 if not config["global"].get("nologging"):
176 str_handler = logging.StreamHandler()
177 str_handler.setFormatter(log_formatter_simple)
178 self.logger.addHandler(str_handler)
179
180 if config["global"].get("loglevel"):
181 self.logger.setLevel(config["global"]["loglevel"])
182
183 # logging other modules
184 for k1, logname in {"message": "lcm.msg", "database": "lcm.db", "storage": "lcm.fs"}.items():
185 config[k1]["logger_name"] = logname
186 logger_module = logging.getLogger(logname)
187 if config[k1].get("logfile"):
188 file_handler = logging.handlers.RotatingFileHandler(config[k1]["logfile"],
189 maxBytes=100e6, backupCount=9, delay=0)
190 file_handler.setFormatter(log_formatter_simple)
191 logger_module.addHandler(file_handler)
192 if config[k1].get("loglevel"):
193 logger_module.setLevel(config[k1]["loglevel"])
194 self.logger.critical("starting osm/lcm version {} {}".format(lcm_version, lcm_version_date))
195 self.n2vc = N2VC(
196 log=self.logger,
197 server=config['VCA']['host'],
198 port=config['VCA']['port'],
199 user=config['VCA']['user'],
200 secret=config['VCA']['secret'],
201 # TODO: This should point to the base folder where charms are stored,
202 # if there is a common one (like object storage). Otherwise, leave
203 # it unset and pass it via DeployCharms
204 # artifacts=config['VCA'][''],
205 artifacts=None,
206 )
207 # check version of N2VC
208 # TODO enhance with int conversion or from distutils.version import LooseVersion
209 # or with list(map(int, version.split(".")))
210 if N2VC_version < "0.0.2":
211 raise LcmException("Not compatible osm/N2VC version '{}'. Needed '0.0.2' or higher".format(N2VC_version))
212 if common_version < "0.1.7":
213 raise LcmException("Not compatible osm/common version '{}'. Needed '0.1.7' or higher".format(
214 common_version))
215
216 try:
217 # TODO check database version
218 if config["database"]["driver"] == "mongo":
219 self.db = dbmongo.DbMongo()
220 self.db.db_connect(config["database"])
221 elif config["database"]["driver"] == "memory":
222 self.db = dbmemory.DbMemory()
223 self.db.db_connect(config["database"])
224 else:
225 raise LcmException("Invalid configuration param '{}' at '[database]':'driver'".format(
226 config["database"]["driver"]))
227
228 if config["storage"]["driver"] == "local":
229 self.fs = fslocal.FsLocal()
230 self.fs.fs_connect(config["storage"])
231 else:
232 raise LcmException("Invalid configuration param '{}' at '[storage]':'driver'".format(
233 config["storage"]["driver"]))
234
235 if config["message"]["driver"] == "local":
236 self.msg = msglocal.MsgLocal()
237 self.msg.connect(config["message"])
238 elif config["message"]["driver"] == "kafka":
239 self.msg = msgkafka.MsgKafka()
240 self.msg.connect(config["message"])
241 else:
242 raise LcmException("Invalid configuration param '{}' at '[message]':'driver'".format(
243 config["storage"]["driver"]))
244 except (DbException, FsException, MsgException) as e:
245 self.logger.critical(str(e), exc_info=True)
246 raise LcmException(str(e))
247
248 async def check_RO_version(self):
249 try:
250 RO = ROclient.ROClient(self.loop, **self.ro_config)
251 RO_version = await RO.get_version()
252 if RO_version < min_RO_version:
253 raise LcmException("Not compatible osm/RO version '{}.{}.{}'. Needed '{}.{}.{}' or higher".format(
254 *RO_version, *min_RO_version
255 ))
256 except ROclient.ROClientException as e:
257 self.logger.critical("Error while conneting to osm/RO " + str(e), exc_info=True)
258 raise LcmException(str(e))
259
260 def update_db_2(self, item, _id, _desc):
261 """
262 Updates database with _desc information. Upon success _desc is cleared
263 :param item:
264 :param _id:
265 :param _desc:
266 :return:
267 """
268 if not _desc:
269 return
270 try:
271 self.db.set_one(item, {"_id": _id}, _desc)
272 _desc.clear()
273 except DbException as e:
274 self.logger.error("Updating {} _id={} with '{}'. Error: {}".format(item, _id, _desc, e))
275
276 async def vim_create(self, vim_content, order_id):
277 vim_id = vim_content["_id"]
278 logging_text = "Task vim_create={} ".format(vim_id)
279 self.logger.debug(logging_text + "Enter")
280 db_vim = None
281 db_vim_update = {}
282 exc = None
283 RO_sdn_id = None
284 try:
285 step = "Getting vim-id='{}' from db".format(vim_id)
286 db_vim = self.db.get_one("vim_accounts", {"_id": vim_id})
287 db_vim_update["_admin.deployed.RO"] = None
288 if vim_content.get("config") and vim_content["config"].get("sdn-controller"):
289 step = "Getting sdn-controller-id='{}' from db".format(vim_content["config"]["sdn-controller"])
290 db_sdn = self.db.get_one("sdns", {"_id": vim_content["config"]["sdn-controller"]})
291 if db_sdn.get("_admin") and db_sdn["_admin"].get("deployed") and db_sdn["_admin"]["deployed"].get("RO"):
292 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
293 else:
294 raise LcmException("sdn-controller={} is not available. Not deployed at RO".format(
295 vim_content["config"]["sdn-controller"]))
296
297 step = "Creating vim at RO"
298 db_vim_update["_admin.detailed-status"] = step
299 self.update_db_2("vim_accounts", vim_id, db_vim_update)
300 RO = ROclient.ROClient(self.loop, **self.ro_config)
301 vim_RO = deepcopy(vim_content)
302 vim_RO.pop("_id", None)
303 vim_RO.pop("_admin", None)
304 vim_RO.pop("schema_version", None)
305 vim_RO.pop("schema_type", None)
306 vim_RO.pop("vim_tenant_name", None)
307 vim_RO["type"] = vim_RO.pop("vim_type")
308 vim_RO.pop("vim_user", None)
309 vim_RO.pop("vim_password", None)
310 if RO_sdn_id:
311 vim_RO["config"]["sdn-controller"] = RO_sdn_id
312 desc = await RO.create("vim", descriptor=vim_RO)
313 RO_vim_id = desc["uuid"]
314 db_vim_update["_admin.deployed.RO"] = RO_vim_id
315
316 step = "Creating vim_account at RO"
317 db_vim_update["_admin.detailed-status"] = step
318 self.update_db_2("vim_accounts", vim_id, db_vim_update)
319
320 vim_account_RO = {"vim_tenant_name": vim_content["vim_tenant_name"],
321 "vim_username": vim_content["vim_user"],
322 "vim_password": vim_content["vim_password"]
323 }
324 if vim_RO.get("config"):
325 vim_account_RO["config"] = vim_RO["config"]
326 if "sdn-controller" in vim_account_RO["config"]:
327 del vim_account_RO["config"]["sdn-controller"]
328 if "sdn-port-mapping" in vim_account_RO["config"]:
329 del vim_account_RO["config"]["sdn-port-mapping"]
330 desc = await RO.attach_datacenter(RO_vim_id, descriptor=vim_account_RO)
331 db_vim_update["_admin.deployed.RO-account"] = desc["uuid"]
332 db_vim_update["_admin.operationalState"] = "ENABLED"
333 db_vim_update["_admin.detailed-status"] = "Done"
334
335 # await asyncio.sleep(15) # TODO remove. This is for test
336 self.logger.debug(logging_text + "Exit Ok RO_vim_id={}".format(RO_vim_id))
337 return
338
339 except (ROclient.ROClientException, DbException) as e:
340 self.logger.error(logging_text + "Exit Exception {}".format(e))
341 exc = e
342 except Exception as e:
343 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
344 exc = e
345 finally:
346 if exc and db_vim:
347 db_vim_update["_admin.operationalState"] = "ERROR"
348 db_vim_update["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
349 if db_vim_update:
350 self.update_db_2("vim_accounts", vim_id, db_vim_update)
351 self.lcm_tasks.remove("vim_account", vim_id, order_id)
352
353 async def vim_edit(self, vim_content, order_id):
354 vim_id = vim_content["_id"]
355 logging_text = "Task vim_edit={} ".format(vim_id)
356 self.logger.debug(logging_text + "Enter")
357 db_vim = None
358 exc = None
359 RO_sdn_id = None
360 RO_vim_id = None
361 db_vim_update = {}
362 step = "Getting vim-id='{}' from db".format(vim_id)
363 try:
364 db_vim = self.db.get_one("vim_accounts", {"_id": vim_id})
365
366 # look if previous tasks in process
367 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account", vim_id, order_id)
368 if task_dependency:
369 step = "Waiting for related tasks to be completed: {}".format(task_name)
370 self.logger.debug(logging_text + step)
371 # TODO write this to database
372 await asyncio.wait(task_dependency, timeout=3600)
373
374 if db_vim.get("_admin") and db_vim["_admin"].get("deployed") and db_vim["_admin"]["deployed"].get("RO"):
375 if vim_content.get("config") and vim_content["config"].get("sdn-controller"):
376 step = "Getting sdn-controller-id='{}' from db".format(vim_content["config"]["sdn-controller"])
377 db_sdn = self.db.get_one("sdns", {"_id": vim_content["config"]["sdn-controller"]})
378
379 # look if previous tasks in process
380 task_name, task_dependency = self.lcm_tasks.lookfor_related("sdn", db_sdn["_id"])
381 if task_dependency:
382 step = "Waiting for related tasks to be completed: {}".format(task_name)
383 self.logger.debug(logging_text + step)
384 # TODO write this to database
385 await asyncio.wait(task_dependency, timeout=3600)
386
387 if db_sdn.get("_admin") and db_sdn["_admin"].get("deployed") and db_sdn["_admin"]["deployed"].get(
388 "RO"):
389 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
390 else:
391 raise LcmException("sdn-controller={} is not available. Not deployed at RO".format(
392 vim_content["config"]["sdn-controller"]))
393
394 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
395 step = "Editing vim at RO"
396 RO = ROclient.ROClient(self.loop, **self.ro_config)
397 vim_RO = deepcopy(vim_content)
398 vim_RO.pop("_id", None)
399 vim_RO.pop("_admin", None)
400 vim_RO.pop("schema_version", None)
401 vim_RO.pop("schema_type", None)
402 vim_RO.pop("vim_tenant_name", None)
403 if "vim_type" in vim_RO:
404 vim_RO["type"] = vim_RO.pop("vim_type")
405 vim_RO.pop("vim_user", None)
406 vim_RO.pop("vim_password", None)
407 if RO_sdn_id:
408 vim_RO["config"]["sdn-controller"] = RO_sdn_id
409 # TODO make a deep update of sdn-port-mapping
410 if vim_RO:
411 await RO.edit("vim", RO_vim_id, descriptor=vim_RO)
412
413 step = "Editing vim-account at RO tenant"
414 vim_account_RO = {}
415 if "config" in vim_content:
416 if "sdn-controller" in vim_content["config"]:
417 del vim_content["config"]["sdn-controller"]
418 if "sdn-port-mapping" in vim_content["config"]:
419 del vim_content["config"]["sdn-port-mapping"]
420 if not vim_content["config"]:
421 del vim_content["config"]
422 for k in ("vim_tenant_name", "vim_password", "config"):
423 if k in vim_content:
424 vim_account_RO[k] = vim_content[k]
425 if "vim_user" in vim_content:
426 vim_content["vim_username"] = vim_content["vim_user"]
427 # vim_account must be edited always even if empty in order to ensure changes are translated to RO
428 # vim_thread. RO will remove and relaunch a new thread for this vim_account
429 await RO.edit("vim_account", RO_vim_id, descriptor=vim_account_RO)
430 db_vim_update["_admin.operationalState"] = "ENABLED"
431
432 self.logger.debug(logging_text + "Exit Ok RO_vim_id={}".format(RO_vim_id))
433 return
434
435 except (ROclient.ROClientException, DbException) as e:
436 self.logger.error(logging_text + "Exit Exception {}".format(e))
437 exc = e
438 except Exception as e:
439 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
440 exc = e
441 finally:
442 if exc and db_vim:
443 db_vim_update["_admin.operationalState"] = "ERROR"
444 db_vim_update["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
445 if db_vim_update:
446 self.update_db_2("vim_accounts", vim_id, db_vim_update)
447 self.lcm_tasks.remove("vim_account", vim_id, order_id)
448
449 async def vim_delete(self, vim_id, order_id):
450 logging_text = "Task vim_delete={} ".format(vim_id)
451 self.logger.debug(logging_text + "Enter")
452 db_vim = None
453 db_vim_update = {}
454 exc = None
455 step = "Getting vim from db"
456 try:
457 db_vim = self.db.get_one("vim_accounts", {"_id": vim_id})
458 if db_vim.get("_admin") and db_vim["_admin"].get("deployed") and db_vim["_admin"]["deployed"].get("RO"):
459 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
460 RO = ROclient.ROClient(self.loop, **self.ro_config)
461 step = "Detaching vim from RO tenant"
462 try:
463 await RO.detach_datacenter(RO_vim_id)
464 except ROclient.ROClientException as e:
465 if e.http_code == 404: # not found
466 self.logger.debug(logging_text + "RO_vim_id={} already detached".format(RO_vim_id))
467 else:
468 raise
469
470 step = "Deleting vim from RO"
471 try:
472 await RO.delete("vim", RO_vim_id)
473 except ROclient.ROClientException as e:
474 if e.http_code == 404: # not found
475 self.logger.debug(logging_text + "RO_vim_id={} already deleted".format(RO_vim_id))
476 else:
477 raise
478 else:
479 # nothing to delete
480 self.logger.error(logging_text + "Nohing to remove at RO")
481 self.db.del_one("vim_accounts", {"_id": vim_id})
482 self.logger.debug(logging_text + "Exit Ok")
483 return
484
485 except (ROclient.ROClientException, DbException) as e:
486 self.logger.error(logging_text + "Exit Exception {}".format(e))
487 exc = e
488 except Exception as e:
489 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
490 exc = e
491 finally:
492 self.lcm_tasks.remove("vim_account", vim_id, order_id)
493 if exc and db_vim:
494 db_vim_update["_admin.operationalState"] = "ERROR"
495 db_vim_update["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
496 if db_vim_update:
497 self.update_db_2("vim_accounts", vim_id, db_vim_update)
498 self.lcm_tasks.remove("vim_account", vim_id, order_id)
499
500 async def sdn_create(self, sdn_content, order_id):
501 sdn_id = sdn_content["_id"]
502 logging_text = "Task sdn_create={} ".format(sdn_id)
503 self.logger.debug(logging_text + "Enter")
504 db_sdn = None
505 db_sdn_update = {}
506 RO_sdn_id = None
507 exc = None
508 try:
509 step = "Getting sdn from db"
510 db_sdn = self.db.get_one("sdns", {"_id": sdn_id})
511 db_sdn_update["_admin.deployed.RO"] = None
512
513 step = "Creating sdn at RO"
514 RO = ROclient.ROClient(self.loop, **self.ro_config)
515 sdn_RO = deepcopy(sdn_content)
516 sdn_RO.pop("_id", None)
517 sdn_RO.pop("_admin", None)
518 sdn_RO.pop("schema_version", None)
519 sdn_RO.pop("schema_type", None)
520 sdn_RO.pop("description", None)
521 desc = await RO.create("sdn", descriptor=sdn_RO)
522 RO_sdn_id = desc["uuid"]
523 db_sdn_update["_admin.deployed.RO"] = RO_sdn_id
524 db_sdn_update["_admin.operationalState"] = "ENABLED"
525 self.logger.debug(logging_text + "Exit Ok RO_sdn_id={}".format(RO_sdn_id))
526 return
527
528 except (ROclient.ROClientException, DbException) as e:
529 self.logger.error(logging_text + "Exit Exception {}".format(e))
530 exc = e
531 except Exception as e:
532 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
533 exc = e
534 finally:
535 if exc and db_sdn:
536 db_sdn_update["_admin.operationalState"] = "ERROR"
537 db_sdn_update["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
538 if db_sdn_update:
539 self.update_db_2("sdns", sdn_id, db_sdn_update)
540 self.lcm_tasks.remove("sdn", sdn_id, order_id)
541
542 async def sdn_edit(self, sdn_content, order_id):
543 sdn_id = sdn_content["_id"]
544 logging_text = "Task sdn_edit={} ".format(sdn_id)
545 self.logger.debug(logging_text + "Enter")
546 db_sdn = None
547 db_sdn_update = {}
548 exc = None
549 step = "Getting sdn from db"
550 try:
551 db_sdn = self.db.get_one("sdns", {"_id": sdn_id})
552 if db_sdn.get("_admin") and db_sdn["_admin"].get("deployed") and db_sdn["_admin"]["deployed"].get("RO"):
553 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
554 RO = ROclient.ROClient(self.loop, **self.ro_config)
555 step = "Editing sdn at RO"
556 sdn_RO = deepcopy(sdn_content)
557 sdn_RO.pop("_id", None)
558 sdn_RO.pop("_admin", None)
559 sdn_RO.pop("schema_version", None)
560 sdn_RO.pop("schema_type", None)
561 sdn_RO.pop("description", None)
562 if sdn_RO:
563 await RO.edit("sdn", RO_sdn_id, descriptor=sdn_RO)
564 db_sdn_update["_admin.operationalState"] = "ENABLED"
565
566 self.logger.debug(logging_text + "Exit Ok RO_sdn_id".format(RO_sdn_id))
567 return
568
569 except (ROclient.ROClientException, DbException) as e:
570 self.logger.error(logging_text + "Exit Exception {}".format(e))
571 exc = e
572 except Exception as e:
573 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
574 exc = e
575 finally:
576 if exc and db_sdn:
577 db_sdn["_admin.operationalState"] = "ERROR"
578 db_sdn["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
579 if db_sdn_update:
580 self.update_db_2("sdns", sdn_id, db_sdn_update)
581 self.lcm_tasks.remove("sdn", sdn_id, order_id)
582
583 async def sdn_delete(self, sdn_id, order_id):
584 logging_text = "Task sdn_delete={} ".format(sdn_id)
585 self.logger.debug(logging_text + "Enter")
586 db_sdn = None
587 db_sdn_update = {}
588 exc = None
589 step = "Getting sdn from db"
590 try:
591 db_sdn = self.db.get_one("sdns", {"_id": sdn_id})
592 if db_sdn.get("_admin") and db_sdn["_admin"].get("deployed") and db_sdn["_admin"]["deployed"].get("RO"):
593 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
594 RO = ROclient.ROClient(self.loop, **self.ro_config)
595 step = "Deleting sdn from RO"
596 try:
597 await RO.delete("sdn", RO_sdn_id)
598 except ROclient.ROClientException as e:
599 if e.http_code == 404: # not found
600 self.logger.debug(logging_text + "RO_sdn_id={} already deleted".format(RO_sdn_id))
601 else:
602 raise
603 else:
604 # nothing to delete
605 self.logger.error(logging_text + "Skipping. There is not RO information at database")
606 self.db.del_one("sdns", {"_id": sdn_id})
607 self.logger.debug("sdn_delete task sdn_id={} Exit Ok".format(sdn_id))
608 return
609
610 except (ROclient.ROClientException, DbException) as e:
611 self.logger.error(logging_text + "Exit Exception {}".format(e))
612 exc = e
613 except Exception as e:
614 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
615 exc = e
616 finally:
617 if exc and db_sdn:
618 db_sdn["_admin.operationalState"] = "ERROR"
619 db_sdn["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
620 if db_sdn_update:
621 self.update_db_2("sdns", sdn_id, db_sdn_update)
622 self.lcm_tasks.remove("sdn", sdn_id, order_id)
623
624 def vnfd2RO(self, vnfd, new_id=None):
625 """
626 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
627 :param vnfd: input vnfd
628 :param new_id: overrides vnf id if provided
629 :return: copy of vnfd
630 """
631 ci_file = None
632 try:
633 vnfd_RO = deepcopy(vnfd)
634 vnfd_RO.pop("_id", None)
635 vnfd_RO.pop("_admin", None)
636 if new_id:
637 vnfd_RO["id"] = new_id
638 for vdu in vnfd_RO["vdu"]:
639 if "cloud-init-file" in vdu:
640 base_folder = vnfd["_admin"]["storage"]
641 clout_init_file = "{}/{}/cloud_init/{}".format(
642 base_folder["folder"],
643 base_folder["pkg-dir"],
644 vdu["cloud-init-file"]
645 )
646 ci_file = self.fs.file_open(clout_init_file, "r")
647 # TODO: detect if binary or text. Propose to read as binary and try to decode to utf8. If fails
648 # convert to base 64 or similar
649 clout_init_content = ci_file.read()
650 ci_file.close()
651 ci_file = None
652 vdu.pop("cloud-init-file", None)
653 vdu["cloud-init"] = clout_init_content
654 # remnove unused by RO configuration, monitoring, scaling
655 vnfd_RO.pop("vnf-configuration", None)
656 vnfd_RO.pop("monitoring-param", None)
657 vnfd_RO.pop("scaling-group-descriptor", None)
658 return vnfd_RO
659 except FsException as e:
660 raise LcmException("Error reading file at vnfd {}: {} ".format(vnfd["_id"], e))
661 finally:
662 if ci_file:
663 ci_file.close()
664
665 def n2vc_callback(self, model_name, application_name, status, message, db_nsr, db_nslcmop, task=None):
666 """
667 Callback both for charm status change and task completion
668 :param model_name: Charm model name
669 :param application_name: Charm application name
670 :param status: Can be
671 - blocked: The unit needs manual intervention
672 - maintenance: The unit is actively deploying/configuring
673 - waiting: The unit is waiting for another charm to be ready
674 - active: The unit is deployed, configured, and ready
675 - error: The charm has failed and needs attention.
676 - terminated: The charm has been destroyed
677 - removing,
678 - removed
679 :param message: detailed message error
680 :param db_nsr: nsr database content
681 :param db_nslcmop: nslcmop database content
682 :param task: None for charm status change, or task for completion task callback
683 :return:
684 """
685 nsr_id = None
686 nslcmop_id = None
687 db_nsr_update = {}
688 db_nslcmop_update = {}
689 try:
690 nsr_id = db_nsr["_id"]
691 nsr_lcm = db_nsr["_admin"]["deployed"]
692 nslcmop_id = db_nslcmop["_id"]
693 ns_operation = db_nslcmop["lcmOperationType"]
694 logging_text = "Task ns={} {}={} [n2vc_callback] application={}".format(nsr_id, ns_operation, nslcmop_id,
695 application_name)
696 vca_deployed = nsr_lcm["VCA"].get(application_name)
697 if not vca_deployed:
698 self.logger.error(logging_text + " Not present at nsr._admin.deployed.VCA")
699 return
700
701 if task:
702 if task.cancelled():
703 self.logger.debug(logging_text + " task Cancelled")
704 # TODO update db_nslcmop
705 return
706
707 if task.done():
708 exc = task.exception()
709 if exc:
710 self.logger.error(logging_text + " task Exception={}".format(exc))
711 if ns_operation in ("instantiate", "terminate"):
712 vca_deployed['operational-status'] = "error"
713 db_nsr_update["_admin.deployed.VCA.{}.operational-status".format(application_name)] = \
714 "error"
715 vca_deployed['detailed-status'] = str(exc)
716 db_nsr_update[
717 "_admin.deployed.VCA.{}.detailed-status".format(application_name)] = str(exc)
718 elif ns_operation == "action":
719 db_nslcmop_update["operationState"] = "FAILED"
720 db_nslcmop_update["detailed-status"] = str(exc)
721 db_nslcmop_update["statusEnteredTime"] = time()
722 return
723
724 else:
725 self.logger.debug(logging_text + " task Done")
726 # TODO revise with Adam if action is finished and ok when task is done
727 if ns_operation == "action":
728 db_nslcmop_update["operationState"] = "COMPLETED"
729 db_nslcmop_update["detailed-status"] = "Done"
730 db_nslcmop_update["statusEnteredTime"] = time()
731 # task is Done, but callback is still ongoing. So ignore
732 return
733 elif status:
734 self.logger.debug(logging_text + " Enter status={}".format(status))
735 if vca_deployed['operational-status'] == status:
736 return # same status, ignore
737 vca_deployed['operational-status'] = status
738 db_nsr_update["_admin.deployed.VCA.{}.operational-status".format(application_name)] = status
739 vca_deployed['detailed-status'] = str(message)
740 db_nsr_update["_admin.deployed.VCA.{}.detailed-status".format(application_name)] = str(message)
741 else:
742 self.logger.critical(logging_text + " Enter with bad parameters", exc_info=True)
743 return
744
745 all_active = True
746 status_map = {}
747 n2vc_error_text = [] # contain text error list. If empty no one is in error status
748 for _, vca_info in nsr_lcm["VCA"].items():
749 vca_status = vca_info["operational-status"]
750 if vca_status not in status_map:
751 # Initialize it
752 status_map[vca_status] = 0
753 status_map[vca_status] += 1
754
755 if vca_status != "active":
756 all_active = False
757 if vca_status in ("error", "blocked"):
758 n2vc_error_text.append("member_vnf_index={} vdu_id={} {}: {}".format(vca_info["member-vnf-index"],
759 vca_info["vdu_id"], vca_status,
760 vca_info["detailed-status"]))
761
762 if all_active:
763 self.logger.debug(logging_text + " All active")
764 db_nsr_update["config-status"] = "configured"
765 db_nsr_update["detailed-status"] = "done"
766 db_nslcmop_update["operationState"] = "COMPLETED"
767 db_nslcmop_update["detailed-status"] = "Done"
768 db_nslcmop_update["statusEnteredTime"] = time()
769 elif n2vc_error_text:
770 db_nsr_update["config-status"] = "failed"
771 error_text = "fail configuring " + ";".join(n2vc_error_text)
772 db_nsr_update["detailed-status"] = error_text
773 db_nslcmop_update["operationState"] = "FAILED_TEMP"
774 db_nslcmop_update["detailed-status"] = error_text
775 db_nslcmop_update["statusEnteredTime"] = time()
776 else:
777 cs = "configuring: "
778 separator = ""
779 for status, num in status_map.items():
780 cs += separator + "{}: {}".format(status, num)
781 separator = ", "
782 db_nsr_update["config-status"] = cs
783 db_nsr_update["detailed-status"] = cs
784 db_nslcmop_update["detailed-status"] = cs
785
786 except Exception as e:
787 self.logger.critical(logging_text + " Exception {}".format(e), exc_info=True)
788 finally:
789 try:
790 if db_nslcmop_update:
791 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
792 if db_nsr_update:
793 self.update_db_2("nsrs", nsr_id, db_nsr_update)
794 except Exception as e:
795 self.logger.critical(logging_text + " Update database Exception {}".format(e), exc_info=True)
796
797 def ns_params_2_RO(self, ns_params, nsd, vnfd_dict):
798 """
799 Creates a RO ns descriptor from OSM ns_instantite params
800 :param ns_params: OSM instantiate params
801 :return: The RO ns descriptor
802 """
803 vim_2_RO = {}
804
805 def vim_account_2_RO(vim_account):
806 if vim_account in vim_2_RO:
807 return vim_2_RO[vim_account]
808
809 db_vim = self.db.get_one("vim_accounts", {"_id": vim_account})
810 if db_vim["_admin"]["operationalState"] != "ENABLED":
811 raise LcmException("VIM={} is not available. operationalState={}".format(
812 vim_account, db_vim["_admin"]["operationalState"]))
813 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
814 vim_2_RO[vim_account] = RO_vim_id
815 return RO_vim_id
816
817 def ip_profile_2_RO(ip_profile):
818 RO_ip_profile = deepcopy((ip_profile))
819 if "dns-server" in RO_ip_profile:
820 if isinstance(RO_ip_profile["dns-server"], list):
821 RO_ip_profile["dns-address"] = []
822 for ds in RO_ip_profile.pop("dns-server"):
823 RO_ip_profile["dns-address"].append(ds['address'])
824 else:
825 RO_ip_profile["dns-address"] = RO_ip_profile.pop("dns-server")
826 if RO_ip_profile.get("ip-version") == "ipv4":
827 RO_ip_profile["ip-version"] = "IPv4"
828 if RO_ip_profile.get("ip-version") == "ipv6":
829 RO_ip_profile["ip-version"] = "IPv6"
830 if "dhcp-params" in RO_ip_profile:
831 RO_ip_profile["dhcp"] = RO_ip_profile.pop("dhcp-params")
832 return RO_ip_profile
833
834 if not ns_params:
835 return None
836 RO_ns_params = {
837 # "name": ns_params["nsName"],
838 # "description": ns_params.get("nsDescription"),
839 "datacenter": vim_account_2_RO(ns_params["vimAccountId"]),
840 # "scenario": ns_params["nsdId"],
841 "vnfs": {},
842 "networks": {},
843 }
844 if ns_params.get("ssh-authorized-key"):
845 RO_ns_params["cloud-config"] = {"key-pairs": ns_params["ssh-authorized-key"]}
846 if ns_params.get("vnf"):
847 for vnf_params in ns_params["vnf"]:
848 for constituent_vnfd in nsd["constituent-vnfd"]:
849 if constituent_vnfd["member-vnf-index"] == vnf_params["member-vnf-index"]:
850 vnf_descriptor = vnfd_dict[constituent_vnfd["vnfd-id-ref"]]
851 break
852 else:
853 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index={} is not present at nsd:"
854 "constituent-vnfd".format(vnf_params["member-vnf-index"]))
855 RO_vnf = {"vdus": {}, "networks": {}}
856 if vnf_params.get("vimAccountId"):
857 RO_vnf["datacenter"] = vim_account_2_RO(vnf_params["vimAccountId"])
858 if vnf_params.get("vdu"):
859 for vdu_params in vnf_params["vdu"]:
860 RO_vnf["vdus"][vdu_params["id"]] = {}
861 if vdu_params.get("volume"):
862 RO_vnf["vdus"][vdu_params["id"]]["devices"] = {}
863 for volume_params in vdu_params["volume"]:
864 RO_vnf["vdus"][vdu_params["id"]]["devices"][volume_params["name"]] = {}
865 if volume_params.get("vim-volume-id"):
866 RO_vnf["vdus"][vdu_params["id"]]["devices"][volume_params["name"]]["vim_id"] = \
867 volume_params["vim-volume-id"]
868 if vdu_params.get("interface"):
869 RO_vnf["vdus"][vdu_params["id"]]["interfaces"] = {}
870 for interface_params in vdu_params["interface"]:
871 RO_interface = {}
872 RO_vnf["vdus"][vdu_params["id"]]["interfaces"][interface_params["name"]] = RO_interface
873 if interface_params.get("ip-address"):
874 RO_interface["ip_address"] = interface_params["ip-address"]
875 if interface_params.get("mac-address"):
876 RO_interface["mac_address"] = interface_params["mac-address"]
877 if interface_params.get("floating-ip-required"):
878 RO_interface["floating-ip"] = interface_params["floating-ip-required"]
879 if vnf_params.get("internal-vld"):
880 for internal_vld_params in vnf_params["internal-vld"]:
881 RO_vnf["networks"][internal_vld_params["name"]] = {}
882 if internal_vld_params.get("vim-network-name"):
883 RO_vnf["networks"][internal_vld_params["name"]]["vim-network-name"] = \
884 internal_vld_params["vim-network-name"]
885 if internal_vld_params.get("ip-profile"):
886 RO_vnf["networks"][internal_vld_params["name"]]["ip-profile"] = \
887 ip_profile_2_RO(internal_vld_params["ip-profile"])
888 if internal_vld_params.get("internal-connection-point"):
889 for icp_params in internal_vld_params["internal-connection-point"]:
890 # look for interface
891 iface_found = False
892 for vdu_descriptor in vnf_descriptor["vdu"]:
893 for vdu_interface in vdu_descriptor["interface"]:
894 if vdu_interface.get("internal-connection-point-ref") == icp_params["id-ref"]:
895 RO_interface_update = {}
896 if icp_params.get("ip-address"):
897 RO_interface_update["ip_address"] = icp_params["ip-address"]
898 if icp_params.get("mac-address"):
899 RO_interface_update["mac_address"] = icp_params["mac-address"]
900 if RO_interface_update:
901 RO_vnf_update = {"vdus": {vdu_descriptor["id"]: {
902 "interfaces": {vdu_interface["name"]: RO_interface_update}}}}
903 deep_update(RO_vnf, RO_vnf_update)
904 iface_found = True
905 break
906 if iface_found:
907 break
908 else:
909 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
910 "internal-vld:id-ref={} is not present at vnfd:internal-"
911 "connection-point".format(vnf_params["member-vnf-index"],
912 icp_params["id-ref"]))
913
914 if not RO_vnf["vdus"]:
915 del RO_vnf["vdus"]
916 if not RO_vnf["networks"]:
917 del RO_vnf["networks"]
918 if RO_vnf:
919 RO_ns_params["vnfs"][vnf_params["member-vnf-index"]] = RO_vnf
920 if ns_params.get("vld"):
921 for vld_params in ns_params["vld"]:
922 RO_vld = {}
923 if "ip-profile" in vld_params:
924 RO_vld["ip-profile"] = ip_profile_2_RO(vld_params["ip-profile"])
925 if "vim-network-name" in vld_params:
926 RO_vld["sites"] = []
927 if isinstance(vld_params["vim-network-name"], dict):
928 for vim_account, vim_net in vld_params["vim-network-name"].items():
929 RO_vld["sites"].append({
930 "netmap-use": vim_net,
931 "datacenter": vim_account_2_RO(vim_account)
932 })
933 else: # isinstance str
934 RO_vld["sites"].append({"netmap-use": vld_params["vim-network-name"]})
935 if "vnfd-connection-point-ref" in vld_params:
936 for cp_params in vld_params["vnfd-connection-point-ref"]:
937 # look for interface
938 for constituent_vnfd in nsd["constituent-vnfd"]:
939 if constituent_vnfd["member-vnf-index"] == cp_params["member-vnf-index-ref"]:
940 vnf_descriptor = vnfd_dict[constituent_vnfd["vnfd-id-ref"]]
941 break
942 else:
943 raise LcmException(
944 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={} "
945 "is not present at nsd:constituent-vnfd".format(cp_params["member-vnf-index-ref"]))
946 match_cp = False
947 for vdu_descriptor in vnf_descriptor["vdu"]:
948 for interface_descriptor in vdu_descriptor["interface"]:
949 if interface_descriptor.get("external-connection-point-ref") == \
950 cp_params["vnfd-connection-point-ref"]:
951 match_cp = True
952 break
953 if match_cp:
954 break
955 else:
956 raise LcmException(
957 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={}:"
958 "vnfd-connection-point-ref={} is not present at vnfd={}".format(
959 cp_params["member-vnf-index-ref"],
960 cp_params["vnfd-connection-point-ref"],
961 vnf_descriptor["id"]))
962 RO_cp_params = {}
963 if cp_params.get("ip-address"):
964 RO_cp_params["ip_address"] = cp_params["ip-address"]
965 if cp_params.get("mac-address"):
966 RO_cp_params["mac_address"] = cp_params["mac-address"]
967 if RO_cp_params:
968 RO_vnf_params = {
969 cp_params["member-vnf-index-ref"]: {
970 "vdus": {
971 vdu_descriptor["id"]: {
972 "interfaces": {
973 interface_descriptor["name"]: RO_cp_params
974 }
975 }
976 }
977 }
978 }
979 deep_update(RO_ns_params["vnfs"], RO_vnf_params)
980 if RO_vld:
981 RO_ns_params["networks"][vld_params["name"]] = RO_vld
982 return RO_ns_params
983
984 def ns_update_vnfr(self, db_vnfrs, nsr_desc_RO):
985 """
986 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
987 :param db_vnfrs:
988 :param nsr_desc_RO:
989 :return:
990 """
991 for vnf_index, db_vnfr in db_vnfrs.items():
992 for vnf_RO in nsr_desc_RO["vnfs"]:
993 if vnf_RO["member_vnf_index"] == vnf_index:
994 vnfr_update = {}
995 db_vnfr["ip-address"] = vnfr_update["ip-address"] = vnf_RO.get("ip_address")
996 vdur_list = []
997 for vdur_RO in vnf_RO.get("vms", ()):
998 vdur = {
999 "vim-id": vdur_RO.get("vim_vm_id"),
1000 "ip-address": vdur_RO.get("ip_address"),
1001 "vdu-id-ref": vdur_RO.get("vdu_osm_id"),
1002 "name": vdur_RO.get("vim_name"),
1003 "status": vdur_RO.get("status"),
1004 "status-detailed": vdur_RO.get("error_msg"),
1005 "interfaces": []
1006 }
1007
1008 for interface_RO in vdur_RO.get("interfaces", ()):
1009 vdur["interfaces"].append({
1010 "ip-address": interface_RO.get("ip_address"),
1011 "mac-address": interface_RO.get("mac_address"),
1012 "name": interface_RO.get("external_name"),
1013 })
1014 vdur_list.append(vdur)
1015 db_vnfr["vdur"] = vnfr_update["vdur"] = vdur_list
1016 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
1017 break
1018
1019 else:
1020 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} at RO info".format(vnf_index))
1021
1022 async def create_monitoring(self, nsr_id, vnf_member_index, vnfd_desc):
1023 if not vnfd_desc.get("scaling-group-descriptor"):
1024 return
1025 for scaling_group in vnfd_desc["scaling-group-descriptor"]:
1026 scaling_policy_desc = {}
1027 scaling_desc = {
1028 "ns_id": nsr_id,
1029 "scaling_group_descriptor": {
1030 "name": scaling_group["name"],
1031 "scaling_policy": scaling_policy_desc
1032 }
1033 }
1034 for scaling_policy in scaling_group.get("scaling-policy"):
1035 scaling_policy_desc["scale_in_operation_type"] = scaling_policy_desc["scale_out_operation_type"] = \
1036 scaling_policy["scaling-type"]
1037 scaling_policy_desc["threshold_time"] = scaling_policy["threshold-time"]
1038 scaling_policy_desc["cooldown_time"] = scaling_policy["cooldown-time"]
1039 scaling_policy_desc["scaling_criteria"] = []
1040 for scaling_criteria in scaling_policy.get("scaling-criteria"):
1041 scaling_criteria_desc = {"scale_in_threshold": scaling_criteria.get("scale-in-threshold"),
1042 "scale_out_threshold": scaling_criteria.get("scale-out-threshold"),
1043 }
1044 if not scaling_criteria.get("vnf-monitoring-param-ref"):
1045 continue
1046 for monitoring_param in vnfd_desc.get("monitoring-param", ()):
1047 if monitoring_param["id"] == scaling_criteria["vnf-monitoring-param-ref"]:
1048 scaling_criteria_desc["monitoring_param"] = {
1049 "id": monitoring_param["id"],
1050 "name": monitoring_param["name"],
1051 "aggregation_type": monitoring_param.get("aggregation-type"),
1052 "vdu_name": monitoring_param.get("vdu-ref"),
1053 "vnf_member_index": vnf_member_index,
1054 }
1055
1056 scaling_policy_desc["scaling_criteria"].append(scaling_criteria_desc)
1057 break
1058 else:
1059 self.logger.error(
1060 "Task ns={} member_vnf_index={} Invalid vnfd vnf-monitoring-param-ref={} not in "
1061 "monitoring-param list".format(nsr_id, vnf_member_index,
1062 scaling_criteria["vnf-monitoring-param-ref"]))
1063
1064 await self.msg.aiowrite("lcm_pm", "configure_scaling", scaling_desc, self.loop)
1065
1066 async def ns_instantiate(self, nsr_id, nslcmop_id):
1067 logging_text = "Task ns={} instantiate={} ".format(nsr_id, nslcmop_id)
1068 self.logger.debug(logging_text + "Enter")
1069 # get all needed from database
1070 db_nsr = None
1071 db_nslcmop = None
1072 db_nsr_update = {}
1073 db_nslcmop_update = {}
1074 db_vnfrs = {}
1075 RO_descriptor_number = 0 # number of descriptors created at RO
1076 descriptor_id_2_RO = {} # map between vnfd/nsd id to the id used at RO
1077 exc = None
1078 try:
1079 step = "Getting nslcmop={} from db".format(nslcmop_id)
1080 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
1081 step = "Getting nsr={} from db".format(nsr_id)
1082 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1083 ns_params = db_nsr.get("instantiate_params")
1084 nsd = db_nsr["nsd"]
1085 nsr_name = db_nsr["name"] # TODO short-name??
1086 needed_vnfd = {}
1087 vnfr_filter = {"nsr-id-ref": nsr_id, "member-vnf-index-ref": None}
1088 for c_vnf in nsd["constituent-vnfd"]:
1089 vnfd_id = c_vnf["vnfd-id-ref"]
1090 vnfr_filter["member-vnf-index-ref"] = c_vnf["member-vnf-index"]
1091 step = "Getting vnfr={} of nsr={} from db".format(c_vnf["member-vnf-index"], nsr_id)
1092 db_vnfrs[c_vnf["member-vnf-index"]] = self.db.get_one("vnfrs", vnfr_filter)
1093 if vnfd_id not in needed_vnfd:
1094 step = "Getting vnfd={} from db".format(vnfd_id)
1095 needed_vnfd[vnfd_id] = self.db.get_one("vnfds", {"id": vnfd_id})
1096
1097 nsr_lcm = db_nsr["_admin"].get("deployed")
1098 if not nsr_lcm:
1099 nsr_lcm = db_nsr["_admin"]["deployed"] = {
1100 "id": nsr_id,
1101 "RO": {"vnfd_id": {}, "nsd_id": None, "nsr_id": None, "nsr_status": "SCHEDULED"},
1102 "nsr_ip": {},
1103 "VCA": {},
1104 }
1105 db_nsr_update["detailed-status"] = "creating"
1106 db_nsr_update["operational-status"] = "init"
1107
1108 RO = ROclient.ROClient(self.loop, **self.ro_config)
1109
1110 # get vnfds, instantiate at RO
1111 for vnfd_id, vnfd in needed_vnfd.items():
1112 step = db_nsr_update["detailed-status"] = "Creating vnfd={} at RO".format(vnfd_id)
1113 # self.logger.debug(logging_text + step)
1114 vnfd_id_RO = "{}.{}.{}".format(nsr_id, RO_descriptor_number, vnfd_id[:23])
1115 descriptor_id_2_RO[vnfd_id] = vnfd_id_RO
1116 RO_descriptor_number += 1
1117
1118 # look if present
1119 vnfd_list = await RO.get_list("vnfd", filter_by={"osm_id": vnfd_id_RO})
1120 if vnfd_list:
1121 db_nsr_update["_admin.deployed.RO.vnfd_id.{}".format(vnfd_id)] = vnfd_list[0]["uuid"]
1122 self.logger.debug(logging_text + "vnfd={} exists at RO. Using RO_id={}".format(
1123 vnfd_id, vnfd_list[0]["uuid"]))
1124 else:
1125 vnfd_RO = self.vnfd2RO(vnfd, vnfd_id_RO)
1126 desc = await RO.create("vnfd", descriptor=vnfd_RO)
1127 db_nsr_update["_admin.deployed.RO.vnfd_id.{}".format(vnfd_id)] = desc["uuid"]
1128 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
1129 self.logger.debug(logging_text + "vnfd={} created at RO. RO_id={}".format(
1130 vnfd_id, desc["uuid"]))
1131 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1132
1133 # create nsd at RO
1134 nsd_id = nsd["id"]
1135 step = db_nsr_update["detailed-status"] = "Creating nsd={} at RO".format(nsd_id)
1136 # self.logger.debug(logging_text + step)
1137
1138 RO_osm_nsd_id = "{}.{}.{}".format(nsr_id, RO_descriptor_number, nsd_id[:23])
1139 descriptor_id_2_RO[nsd_id] = RO_osm_nsd_id
1140 RO_descriptor_number += 1
1141 nsd_list = await RO.get_list("nsd", filter_by={"osm_id": RO_osm_nsd_id})
1142 if nsd_list:
1143 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = nsd_list[0]["uuid"]
1144 self.logger.debug(logging_text + "nsd={} exists at RO. Using RO_id={}".format(
1145 nsd_id, RO_nsd_uuid))
1146 else:
1147 nsd_RO = deepcopy(nsd)
1148 nsd_RO["id"] = RO_osm_nsd_id
1149 nsd_RO.pop("_id", None)
1150 nsd_RO.pop("_admin", None)
1151 for c_vnf in nsd_RO["constituent-vnfd"]:
1152 vnfd_id = c_vnf["vnfd-id-ref"]
1153 c_vnf["vnfd-id-ref"] = descriptor_id_2_RO[vnfd_id]
1154 desc = await RO.create("nsd", descriptor=nsd_RO)
1155 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
1156 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = desc["uuid"]
1157 self.logger.debug(logging_text + "nsd={} created at RO. RO_id={}".format(nsd_id, RO_nsd_uuid))
1158 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1159
1160 # Crate ns at RO
1161 # if present use it unless in error status
1162 RO_nsr_id = db_nsr["_admin"].get("deployed", {}).get("RO", {}).get("nsr_id")
1163 if RO_nsr_id:
1164 try:
1165 step = db_nsr_update["detailed-status"] = "Looking for existing ns at RO"
1166 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
1167 desc = await RO.show("ns", RO_nsr_id)
1168 except ROclient.ROClientException as e:
1169 if e.http_code != HTTPStatus.NOT_FOUND:
1170 raise
1171 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
1172 if RO_nsr_id:
1173 ns_status, ns_status_info = RO.check_ns_status(desc)
1174 db_nsr_update["_admin.deployed.RO.nsr_status"] = ns_status
1175 if ns_status == "ERROR":
1176 step = db_nsr_update["detailed-status"] = "Deleting ns at RO. RO_ns_id={}".format(RO_nsr_id)
1177 self.logger.debug(logging_text + step)
1178 await RO.delete("ns", RO_nsr_id)
1179 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
1180 if not RO_nsr_id:
1181 step = db_nsr_update["detailed-status"] = "Creating ns at RO"
1182 # self.logger.debug(logging_text + step)
1183
1184 # check if VIM is creating and wait look if previous tasks in process
1185 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account", ns_params["vimAccountId"])
1186 if task_dependency:
1187 step = "Waiting for related tasks to be completed: {}".format(task_name)
1188 self.logger.debug(logging_text + step)
1189 await asyncio.wait(task_dependency, timeout=3600)
1190 if ns_params.get("vnf"):
1191 for vnf in ns_params["vnf"]:
1192 if "vimAccountId" in vnf:
1193 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account",
1194 vnf["vimAccountId"])
1195 if task_dependency:
1196 step = "Waiting for related tasks to be completed: {}".format(task_name)
1197 self.logger.debug(logging_text + step)
1198 await asyncio.wait(task_dependency, timeout=3600)
1199
1200 RO_ns_params = self.ns_params_2_RO(ns_params, nsd, needed_vnfd)
1201 desc = await RO.create("ns", descriptor=RO_ns_params,
1202 name=db_nsr["name"],
1203 scenario=RO_nsd_uuid)
1204 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = desc["uuid"]
1205 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
1206 db_nsr_update["_admin.deployed.RO.nsr_status"] = "BUILD"
1207 self.logger.debug(logging_text + "ns created at RO. RO_id={}".format(desc["uuid"]))
1208 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1209
1210 # update VNFR vimAccount
1211 step = "Updating VNFR vimAcccount"
1212 for vnf_index, vnfr in db_vnfrs.items():
1213 if vnfr.get("vim-account-id"):
1214 continue
1215 vnfr_update = {"vim-account-id": db_nsr["instantiate_params"]["vimAccountId"]}
1216 if db_nsr["instantiate_params"].get("vnf"):
1217 for vnf_params in db_nsr["instantiate_params"]["vnf"]:
1218 if vnf_params.get("member-vnf-index") == vnf_index:
1219 if vnf_params.get("vimAccountId"):
1220 vnfr_update["vim-account-id"] = vnf_params.get("vimAccountId")
1221 break
1222 self.update_db_2("vnfrs", vnfr["_id"], vnfr_update)
1223
1224 # wait until NS is ready
1225 step = ns_status_detailed = detailed_status = "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id)
1226 detailed_status_old = None
1227 self.logger.debug(logging_text + step)
1228
1229 deployment_timeout = 2 * 3600 # Two hours
1230 while deployment_timeout > 0:
1231 desc = await RO.show("ns", RO_nsr_id)
1232 ns_status, ns_status_info = RO.check_ns_status(desc)
1233 db_nsr_update["admin.deployed.RO.nsr_status"] = ns_status
1234 if ns_status == "ERROR":
1235 raise ROclient.ROClientException(ns_status_info)
1236 elif ns_status == "BUILD":
1237 detailed_status = ns_status_detailed + "; {}".format(ns_status_info)
1238 elif ns_status == "ACTIVE":
1239 step = detailed_status = "Waiting for management IP address reported by the VIM"
1240 try:
1241 nsr_lcm["nsr_ip"] = RO.get_ns_vnf_info(desc)
1242 break
1243 except ROclient.ROClientException as e:
1244 if e.http_code != 409: # IP address is not ready return code is 409 CONFLICT
1245 raise e
1246 else:
1247 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
1248 if detailed_status != detailed_status_old:
1249 detailed_status_old = db_nsr_update["detailed-status"] = detailed_status
1250 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1251 await asyncio.sleep(5, loop=self.loop)
1252 deployment_timeout -= 5
1253 if deployment_timeout <= 0:
1254 raise ROclient.ROClientException("Timeout waiting ns to be ready")
1255
1256 step = "Updating VNFRs"
1257 self.ns_update_vnfr(db_vnfrs, desc)
1258
1259 db_nsr["detailed-status"] = "Configuring vnfr"
1260 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1261
1262 # The parameters we'll need to deploy a charm
1263 number_to_configure = 0
1264
1265 def deploy(vnf_index, vdu_id, mgmt_ip_address, config_primitive=None):
1266 """An inner function to deploy the charm from either vnf or vdu
1267 vnf_index is mandatory. vdu_id can be None for a vnf configuration or the id for vdu configuration
1268 """
1269 if not mgmt_ip_address:
1270 raise LcmException("vnfd/vdu has not management ip address to configure it")
1271 # Login to the VCA.
1272 # if number_to_configure == 0:
1273 # self.logger.debug("Logging into N2VC...")
1274 # task = asyncio.ensure_future(self.n2vc.login())
1275 # yield from asyncio.wait_for(task, 30.0)
1276 # self.logger.debug("Logged into N2VC!")
1277
1278 # # await self.n2vc.login()
1279
1280 # Note: The charm needs to exist on disk at the location
1281 # specified by charm_path.
1282 base_folder = vnfd["_admin"]["storage"]
1283 storage_params = self.fs.get_params()
1284 charm_path = "{}{}/{}/charms/{}".format(
1285 storage_params["path"],
1286 base_folder["folder"],
1287 base_folder["pkg-dir"],
1288 proxy_charm
1289 )
1290
1291 # Setup the runtime parameters for this VNF
1292 params = {'rw_mgmt_ip': mgmt_ip_address}
1293 if config_primitive:
1294 params["initial-config-primitive"] = config_primitive
1295
1296 # ns_name will be ignored in the current version of N2VC
1297 # but will be implemented for the next point release.
1298 model_name = 'default'
1299 vdu_id_text = "vnfd"
1300 if vdu_id:
1301 vdu_id_text = vdu_id
1302 application_name = self.n2vc.FormatApplicationName(
1303 nsr_name,
1304 vnf_index,
1305 vdu_id_text
1306 )
1307 if not nsr_lcm.get("VCA"):
1308 nsr_lcm["VCA"] = {}
1309 nsr_lcm["VCA"][application_name] = db_nsr_update["_admin.deployed.VCA.{}".format(application_name)] = {
1310 "member-vnf-index": vnf_index,
1311 "vdu_id": vdu_id,
1312 "model": model_name,
1313 "application": application_name,
1314 "operational-status": "init",
1315 "detailed-status": "",
1316 "vnfd_id": vnfd_id,
1317 }
1318 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1319
1320 self.logger.debug("Task create_ns={} Passing artifacts path '{}' for {}".format(nsr_id, charm_path,
1321 proxy_charm))
1322 task = asyncio.ensure_future(
1323 self.n2vc.DeployCharms(
1324 model_name, # The network service name
1325 application_name, # The application name
1326 vnfd, # The vnf descriptor
1327 charm_path, # Path to charm
1328 params, # Runtime params, like mgmt ip
1329 {}, # for native charms only
1330 self.n2vc_callback, # Callback for status changes
1331 db_nsr, # Callback parameter
1332 db_nslcmop,
1333 None, # Callback parameter (task)
1334 )
1335 )
1336 task.add_done_callback(functools.partial(self.n2vc_callback, model_name, application_name, None, None,
1337 db_nsr, db_nslcmop))
1338 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "create_charm:" + application_name, task)
1339
1340 step = "Looking for needed vnfd to configure"
1341 self.logger.debug(logging_text + step)
1342
1343 for c_vnf in nsd["constituent-vnfd"]:
1344 vnfd_id = c_vnf["vnfd-id-ref"]
1345 vnf_index = str(c_vnf["member-vnf-index"])
1346 vnfd = needed_vnfd[vnfd_id]
1347
1348 # Check if this VNF has a charm configuration
1349 vnf_config = vnfd.get("vnf-configuration")
1350
1351 if vnf_config and vnf_config.get("juju"):
1352 proxy_charm = vnf_config["juju"]["charm"]
1353 config_primitive = None
1354
1355 if proxy_charm:
1356 if 'initial-config-primitive' in vnf_config:
1357 config_primitive = vnf_config['initial-config-primitive']
1358
1359 # Login to the VCA. If there are multiple calls to login(),
1360 # subsequent calls will be a nop and return immediately.
1361 step = "connecting to N2VC to configure vnf {}".format(vnf_index)
1362 await self.n2vc.login()
1363 deploy(vnf_index, None, db_vnfrs[vnf_index]["ip-address"], config_primitive)
1364 number_to_configure += 1
1365
1366 # Deploy charms for each VDU that supports one.
1367 vdu_index = 0
1368 for vdu in vnfd['vdu']:
1369 vdu_config = vdu.get('vdu-configuration')
1370 proxy_charm = None
1371 config_primitive = None
1372
1373 if vdu_config and vdu_config.get("juju"):
1374 proxy_charm = vdu_config["juju"]["charm"]
1375
1376 if 'initial-config-primitive' in vdu_config:
1377 config_primitive = vdu_config['initial-config-primitive']
1378
1379 if proxy_charm:
1380 step = "connecting to N2VC to configure vdu {} from vnf {}".format(vdu["id"], vnf_index)
1381 await self.n2vc.login()
1382 deploy(vnf_index, vdu["id"], db_vnfrs[vnf_index]["vdur"][vdu_index]["ip-address"],
1383 config_primitive)
1384 number_to_configure += 1
1385 vdu_index += 1
1386
1387 if number_to_configure:
1388 db_nsr_update["config-status"] = "configuring"
1389 db_nsr_update["operational-status"] = "running"
1390 db_nsr_update["detailed-status"] = "configuring: init: {}".format(number_to_configure)
1391 db_nslcmop_update["detailed-status"] = "configuring: init: {}".format(number_to_configure)
1392 else:
1393 db_nslcmop_update["operationState"] = "COMPLETED"
1394 db_nslcmop_update["statusEnteredTime"] = time()
1395 db_nslcmop_update["detailed-status"] = "done"
1396 db_nsr_update["config-status"] = "configured"
1397 db_nsr_update["detailed-status"] = "done"
1398 db_nsr_update["operational-status"] = "running"
1399 step = "Sending monitoring parameters to PM"
1400 # for c_vnf in nsd["constituent-vnfd"]:
1401 # await self.create_monitoring(nsr_id, c_vnf["member-vnf-index"], needed_vnfd[c_vnf["vnfd-id-ref"]])
1402 try:
1403 await self.msg.aiowrite("ns", "instantiated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
1404 except Exception as e:
1405 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1406
1407 self.logger.debug(logging_text + "Exit")
1408 return
1409
1410 except (ROclient.ROClientException, DbException, LcmException) as e:
1411 self.logger.error(logging_text + "Exit Exception while '{}': {}".format(step, e))
1412 exc = e
1413 except asyncio.CancelledError:
1414 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1415 exc = "Operation was cancelled"
1416 except Exception as e:
1417 exc = traceback.format_exc()
1418 self.logger.critical(logging_text + "Exit Exception {} while '{}': {}".format(type(e).__name__, step, e),
1419 exc_info=True)
1420 finally:
1421 if exc:
1422 if db_nsr:
1423 db_nsr_update["detailed-status"] = "ERROR {}: {}".format(step, exc)
1424 db_nsr_update["operational-status"] = "failed"
1425 if db_nslcmop:
1426 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
1427 db_nslcmop_update["operationState"] = "FAILED"
1428 db_nslcmop_update["statusEnteredTime"] = time()
1429 if db_nsr_update:
1430 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1431 if db_nslcmop_update:
1432 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1433 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_instantiate")
1434
1435 async def ns_terminate(self, nsr_id, nslcmop_id):
1436 logging_text = "Task ns={} terminate={} ".format(nsr_id, nslcmop_id)
1437 self.logger.debug(logging_text + "Enter")
1438 db_nsr = None
1439 db_nslcmop = None
1440 exc = None
1441 failed_detail = [] # annotates all failed error messages
1442 vca_task_list = []
1443 vca_task_dict = {}
1444 db_nsr_update = {}
1445 db_nslcmop_update = {}
1446 try:
1447 step = "Getting nslcmop={} from db".format(nslcmop_id)
1448 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
1449 step = "Getting nsr={} from db".format(nsr_id)
1450 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1451 # nsd = db_nsr["nsd"]
1452 nsr_lcm = deepcopy(db_nsr["_admin"].get("deployed"))
1453 if db_nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
1454 return
1455 # TODO ALF remove
1456 # db_vim = self.db.get_one("vim_accounts", {"_id": db_nsr["datacenter"]})
1457 # #TODO check if VIM is creating and wait
1458 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
1459
1460 db_nsr_update["operational-status"] = "terminating"
1461 db_nsr_update["config-status"] = "terminating"
1462
1463 if nsr_lcm and nsr_lcm.get("VCA"):
1464 try:
1465 step = "Scheduling configuration charms removing"
1466 db_nsr_update["detailed-status"] = "Deleting charms"
1467 self.logger.debug(logging_text + step)
1468 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1469 for application_name, deploy_info in nsr_lcm["VCA"].items():
1470 if deploy_info: # TODO it would be desirable having a and deploy_info.get("deployed"):
1471 task = asyncio.ensure_future(
1472 self.n2vc.RemoveCharms(
1473 deploy_info['model'],
1474 application_name,
1475 # self.n2vc_callback,
1476 # db_nsr,
1477 # db_nslcmop,
1478 )
1479 )
1480 vca_task_list.append(task)
1481 vca_task_dict[application_name] = task
1482 # task.add_done_callback(functools.partial(self.n2vc_callback, deploy_info['model'],
1483 # deploy_info['application'], None, db_nsr,
1484 # db_nslcmop, vnf_index))
1485 self.lcm_ns_tasks[nsr_id][nslcmop_id]["delete_charm:" + application_name] = task
1486 except Exception as e:
1487 self.logger.debug(logging_text + "Failed while deleting charms: {}".format(e))
1488
1489 # remove from RO
1490 RO_fail = False
1491 RO = ROclient.ROClient(self.loop, **self.ro_config)
1492
1493 # Delete ns
1494 RO_nsr_id = RO_delete_action = None
1495 if nsr_lcm and nsr_lcm.get("RO"):
1496 RO_nsr_id = nsr_lcm["RO"].get("nsr_id")
1497 RO_delete_action = nsr_lcm["RO"].get("nsr_delete_action_id")
1498 try:
1499 if RO_nsr_id:
1500 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] = "Deleting ns at RO"
1501 self.logger.debug(logging_text + step)
1502 desc = await RO.delete("ns", RO_nsr_id)
1503 RO_delete_action = desc["action_id"]
1504 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = RO_delete_action
1505 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
1506 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
1507 if RO_delete_action:
1508 # wait until NS is deleted from VIM
1509 step = detailed_status = "Waiting ns deleted from VIM. RO_id={}".format(RO_nsr_id)
1510 detailed_status_old = None
1511 self.logger.debug(logging_text + step)
1512
1513 delete_timeout = 20 * 60 # 20 minutes
1514 while delete_timeout > 0:
1515 desc = await RO.show("ns", item_id_name=RO_nsr_id, extra_item="action",
1516 extra_item_id=RO_delete_action)
1517 ns_status, ns_status_info = RO.check_action_status(desc)
1518 if ns_status == "ERROR":
1519 raise ROclient.ROClientException(ns_status_info)
1520 elif ns_status == "BUILD":
1521 detailed_status = step + "; {}".format(ns_status_info)
1522 elif ns_status == "ACTIVE":
1523 break
1524 else:
1525 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
1526 await asyncio.sleep(5, loop=self.loop)
1527 delete_timeout -= 5
1528 if detailed_status != detailed_status_old:
1529 detailed_status_old = db_nslcmop_update["detailed-status"] = detailed_status
1530 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1531 else: # delete_timeout <= 0:
1532 raise ROclient.ROClientException("Timeout waiting ns deleted from VIM")
1533
1534 except ROclient.ROClientException as e:
1535 if e.http_code == 404: # not found
1536 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
1537 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
1538 self.logger.debug(logging_text + "RO_ns_id={} already deleted".format(RO_nsr_id))
1539 elif e.http_code == 409: # conflict
1540 failed_detail.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id, e))
1541 self.logger.debug(logging_text + failed_detail[-1])
1542 RO_fail = True
1543 else:
1544 failed_detail.append("RO_ns_id={} delete error: {}".format(RO_nsr_id, e))
1545 self.logger.error(logging_text + failed_detail[-1])
1546 RO_fail = True
1547
1548 # Delete nsd
1549 if not RO_fail and nsr_lcm and nsr_lcm.get("RO") and nsr_lcm["RO"].get("nsd_id"):
1550 RO_nsd_id = nsr_lcm["RO"]["nsd_id"]
1551 try:
1552 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
1553 "Deleting nsd at RO"
1554 await RO.delete("nsd", RO_nsd_id)
1555 self.logger.debug(logging_text + "RO_nsd_id={} deleted".format(RO_nsd_id))
1556 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
1557 except ROclient.ROClientException as e:
1558 if e.http_code == 404: # not found
1559 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
1560 self.logger.debug(logging_text + "RO_nsd_id={} already deleted".format(RO_nsd_id))
1561 elif e.http_code == 409: # conflict
1562 failed_detail.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id, e))
1563 self.logger.debug(logging_text + failed_detail[-1])
1564 RO_fail = True
1565 else:
1566 failed_detail.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id, e))
1567 self.logger.error(logging_text + failed_detail[-1])
1568 RO_fail = True
1569
1570 if not RO_fail and nsr_lcm and nsr_lcm.get("RO") and nsr_lcm["RO"].get("vnfd_id"):
1571 for vnf_id, RO_vnfd_id in nsr_lcm["RO"]["vnfd_id"].items():
1572 if not RO_vnfd_id:
1573 continue
1574 try:
1575 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
1576 "Deleting vnfd={} at RO".format(vnf_id)
1577 await RO.delete("vnfd", RO_vnfd_id)
1578 self.logger.debug(logging_text + "RO_vnfd_id={} deleted".format(RO_vnfd_id))
1579 db_nsr_update["_admin.deployed.RO.vnfd_id.{}".format(vnf_id)] = None
1580 except ROclient.ROClientException as e:
1581 if e.http_code == 404: # not found
1582 db_nsr_update["_admin.deployed.RO.vnfd_id.{}".format(vnf_id)] = None
1583 self.logger.debug(logging_text + "RO_vnfd_id={} already deleted ".format(RO_vnfd_id))
1584 elif e.http_code == 409: # conflict
1585 failed_detail.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id, e))
1586 self.logger.debug(logging_text + failed_detail[-1])
1587 else:
1588 failed_detail.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id, e))
1589 self.logger.error(logging_text + failed_detail[-1])
1590
1591 if vca_task_list:
1592 db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
1593 "Waiting for deletion of configuration charms"
1594 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1595 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1596 await asyncio.wait(vca_task_list, timeout=300)
1597 for application_name, task in vca_task_dict.items():
1598 if task.cancelled():
1599 failed_detail.append("VCA[{}] Deletion has been cancelled".format(application_name))
1600 elif task.done():
1601 exc = task.exception()
1602 if exc:
1603 failed_detail.append("VCA[{}] Deletion exception: {}".format(application_name, exc))
1604 else:
1605 db_nsr_update["_admin.deployed.VCA.{}".format(application_name)] = None
1606 else: # timeout
1607 # TODO Should it be cancelled?!!
1608 task.cancel()
1609 failed_detail.append("VCA[{}] Deletion timeout".format(application_name))
1610
1611 if failed_detail:
1612 self.logger.error(logging_text + " ;".join(failed_detail))
1613 db_nsr_update["operational-status"] = "failed"
1614 db_nsr_update["detailed-status"] = "Deletion errors " + "; ".join(failed_detail)
1615 db_nslcmop_update["detailed-status"] = "; ".join(failed_detail)
1616 db_nslcmop_update["operationState"] = "FAILED"
1617 db_nslcmop_update["statusEnteredTime"] = time()
1618 elif db_nslcmop["operationParams"].get("autoremove"):
1619 self.db.del_one("nsrs", {"_id": nsr_id})
1620 db_nsr_update.clear()
1621 self.db.del_list("nslcmops", {"nsInstanceId": nsr_id})
1622 db_nslcmop_update.clear()
1623 self.db.del_list("vnfrs", {"nsr-id-ref": nsr_id})
1624 self.logger.debug(logging_text + "Delete from database")
1625 else:
1626 db_nsr_update["operational-status"] = "terminated"
1627 db_nsr_update["detailed-status"] = "Done"
1628 db_nsr_update["_admin.nsState"] = "NOT_INSTANTIATED"
1629 db_nslcmop_update["detailed-status"] = "Done"
1630 db_nslcmop_update["operationState"] = "COMPLETED"
1631 db_nslcmop_update["statusEnteredTime"] = time()
1632 try:
1633 await self.msg.aiowrite("ns", "terminated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
1634 except Exception as e:
1635 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1636 self.logger.debug(logging_text + "Exit")
1637
1638 except (ROclient.ROClientException, DbException) as e:
1639 self.logger.error(logging_text + "Exit Exception {}".format(e))
1640 exc = e
1641 except asyncio.CancelledError:
1642 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1643 exc = "Operation was cancelled"
1644 except Exception as e:
1645 exc = traceback.format_exc()
1646 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
1647 finally:
1648 if exc and db_nslcmop:
1649 db_nslcmop_update = {
1650 "detailed-status": "FAILED {}: {}".format(step, exc),
1651 "operationState": "FAILED",
1652 "statusEnteredTime": time(),
1653 }
1654 if db_nslcmop_update:
1655 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1656 if db_nsr_update:
1657 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1658 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_terminate")
1659
1660 async def _ns_execute_primitive(self, db_deployed, nsr_name, member_vnf_index, vdu_id, primitive, primitive_params):
1661
1662 vdu_id_text = "vnfd"
1663 if vdu_id:
1664 vdu_id_text = vdu_id
1665 application_name = self.n2vc.FormatApplicationName(
1666 nsr_name,
1667 member_vnf_index,
1668 vdu_id_text
1669 )
1670 vca_deployed = db_deployed["VCA"].get(application_name)
1671 if not vca_deployed:
1672 raise LcmException("charm for member_vnf_index={} vdu_id={} is not deployed".format(member_vnf_index,
1673 vdu_id))
1674 model_name = vca_deployed.get("model")
1675 application_name = vca_deployed.get("application")
1676 if not model_name or not application_name:
1677 raise LcmException("charm for member_vnf_index={} is not properly deployed".format(member_vnf_index))
1678 if vca_deployed["operational-status"] != "active":
1679 raise LcmException("charm for member_vnf_index={} operational_status={} not 'active'".format(
1680 member_vnf_index, vca_deployed["operational-status"]))
1681 callback = None # self.n2vc_callback
1682 callback_args = () # [db_nsr, db_nslcmop, member_vnf_index, None]
1683 await self.n2vc.login()
1684 task = asyncio.ensure_future(
1685 self.n2vc.ExecutePrimitive(
1686 model_name,
1687 application_name,
1688 primitive, callback,
1689 *callback_args,
1690 **primitive_params
1691 )
1692 )
1693 # task.add_done_callback(functools.partial(self.n2vc_callback, model_name, application_name, None,
1694 # db_nsr, db_nslcmop, member_vnf_index))
1695 # self.lcm_ns_tasks[nsr_id][nslcmop_id]["action: " + primitive] = task
1696 # wait until completed with timeout
1697 await asyncio.wait((task,), timeout=600)
1698
1699 result = "FAILED" # by default
1700 result_detail = ""
1701 if task.cancelled():
1702 result_detail = "Task has been cancelled"
1703 elif task.done():
1704 exc = task.exception()
1705 if exc:
1706 result_detail = str(exc)
1707 else:
1708 # TODO revise with Adam if action is finished and ok when task is done or callback is needed
1709 result = "COMPLETED"
1710 result_detail = "Done"
1711 else: # timeout
1712 # TODO Should it be cancelled?!!
1713 task.cancel()
1714 result_detail = "timeout"
1715 return result, result_detail
1716
1717 async def ns_action(self, nsr_id, nslcmop_id):
1718 logging_text = "Task ns={} action={} ".format(nsr_id, nslcmop_id)
1719 self.logger.debug(logging_text + "Enter")
1720 # get all needed from database
1721 db_nsr = None
1722 db_nslcmop = None
1723 db_nslcmop_update = None
1724 exc = None
1725 try:
1726 step = "Getting information from database"
1727 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
1728 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1729 nsr_lcm = db_nsr["_admin"].get("deployed")
1730 nsr_name = db_nsr["name"]
1731 vnf_index = db_nslcmop["operationParams"]["member_vnf_index"]
1732 vdu_id = db_nslcmop["operationParams"].get("vdu_id")
1733
1734 # TODO check if ns is in a proper status
1735 primitive = db_nslcmop["operationParams"]["primitive"]
1736 primitive_params = db_nslcmop["operationParams"]["primitive_params"]
1737 result, result_detail = await self._ns_execute_primitive(nsr_lcm, nsr_name, vnf_index, vdu_id, primitive,
1738 primitive_params)
1739 db_nslcmop_update = {
1740 "detailed-status": result_detail,
1741 "operationState": result,
1742 "statusEnteredTime": time()
1743 }
1744 self.logger.debug(logging_text + " task Done with result {} {}".format(result, result_detail))
1745 return # database update is called inside finally
1746
1747 except (DbException, LcmException) as e:
1748 self.logger.error(logging_text + "Exit Exception {}".format(e))
1749 exc = e
1750 except asyncio.CancelledError:
1751 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1752 exc = "Operation was cancelled"
1753 except Exception as e:
1754 exc = traceback.format_exc()
1755 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
1756 finally:
1757 if exc and db_nslcmop:
1758 db_nslcmop_update = {
1759 "detailed-status": "FAILED {}: {}".format(step, exc),
1760 "operationState": "FAILED",
1761 "statusEnteredTime": time(),
1762 }
1763 if db_nslcmop_update:
1764 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1765 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_action")
1766
1767 async def ns_scale(self, nsr_id, nslcmop_id):
1768 logging_text = "Task ns={} scale={} ".format(nsr_id, nslcmop_id)
1769 self.logger.debug(logging_text + "Enter")
1770 # get all needed from database
1771 db_nsr = None
1772 db_nslcmop = None
1773 db_nslcmop_update = {}
1774 db_nsr_update = {}
1775 exc = None
1776 try:
1777 step = "Getting nslcmop from database"
1778 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
1779 step = "Getting nsr from database"
1780 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1781 step = "Parsing scaling parameters"
1782 db_nsr_update["operational-status"] = "scaling"
1783 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1784 nsr_lcm = db_nsr["_admin"].get("deployed")
1785 RO_nsr_id = nsr_lcm["RO"]["nsr_id"]
1786 vnf_index = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
1787 scaling_group = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1788 scaling_type = db_nslcmop["operationParams"]["scaleVnfData"]["scaleVnfType"]
1789 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
1790
1791 step = "Getting vnfr from database"
1792 db_vnfr = self.db.get_one("vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id})
1793 step = "Getting vnfd from database"
1794 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
1795 step = "Getting scaling-group-descriptor"
1796 for scaling_descriptor in db_vnfd["scaling-group-descriptor"]:
1797 if scaling_descriptor["name"] == scaling_group:
1798 break
1799 else:
1800 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
1801 "at vnfd:scaling-group-descriptor".format(scaling_group))
1802 # cooldown_time = 0
1803 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
1804 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
1805 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
1806 # break
1807
1808 # TODO check if ns is in a proper status
1809 step = "Sending scale order to RO"
1810 nb_scale_op = 0
1811 if not db_nsr["_admin"].get("scaling-group"):
1812 self.update_db_2("nsrs", nsr_id, {"_admin.scaling-group": [{"name": scaling_group, "nb-scale-op": 0}]})
1813 admin_scale_index = 0
1814 else:
1815 for admin_scale_index, admin_scale_info in enumerate(db_nsr["_admin"]["scaling-group"]):
1816 if admin_scale_info["name"] == scaling_group:
1817 nb_scale_op = admin_scale_info.get("nb-scale-op", 0)
1818 break
1819 RO_scaling_info = []
1820 vdu_scaling_info = {"scaling_group_name": scaling_group, "vdu": []}
1821 if scaling_type == "SCALE_OUT":
1822 # count if max-instance-count is reached
1823 if "max-instance-count" in scaling_descriptor and scaling_descriptor["max-instance-count"] is not None:
1824 max_instance_count = int(scaling_descriptor["max-instance-count"])
1825 if nb_scale_op >= max_instance_count:
1826 raise LcmException("reached the limit of {} (max-instance-count) scaling-out operations for the"
1827 " scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group))
1828 nb_scale_op = nb_scale_op + 1
1829 vdu_scaling_info["scaling_direction"] = "OUT"
1830 vdu_scaling_info["vdu-create"] = {}
1831 for vdu_scale_info in scaling_descriptor["vdu"]:
1832 RO_scaling_info.append({"osm_vdu_id": vdu_scale_info["vdu-id-ref"], "member-vnf-index": vnf_index,
1833 "type": "create", "count": vdu_scale_info.get("count", 1)})
1834 vdu_scaling_info["vdu-create"][vdu_scale_info["vdu-id-ref"]] = vdu_scale_info.get("count", 1)
1835 elif scaling_type == "SCALE_IN":
1836 # count if min-instance-count is reached
1837 if "min-instance-count" in scaling_descriptor and scaling_descriptor["min-instance-count"] is not None:
1838 min_instance_count = int(scaling_descriptor["min-instance-count"])
1839 if nb_scale_op <= min_instance_count:
1840 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
1841 "scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group))
1842 nb_scale_op = nb_scale_op - 1
1843 vdu_scaling_info["scaling_direction"] = "IN"
1844 vdu_scaling_info["vdu-delete"] = {}
1845 for vdu_scale_info in scaling_descriptor["vdu"]:
1846 RO_scaling_info.append({"osm_vdu_id": vdu_scale_info["vdu-id-ref"], "member-vnf-index": vnf_index,
1847 "type": "delete", "count": vdu_scale_info.get("count", 1)})
1848 vdu_scaling_info["vdu-delete"][vdu_scale_info["vdu-id-ref"]] = vdu_scale_info.get("count", 1)
1849
1850 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
1851 if vdu_scaling_info["scaling_direction"] == "IN":
1852 for vdur in reversed(db_vnfr["vdur"]):
1853 if vdu_scaling_info["vdu-delete"].get(vdur["vdu-id-ref"]):
1854 vdu_scaling_info["vdu-delete"][vdur["vdu-id-ref"]] -= 1
1855 vdu_scaling_info["vdu"].append({
1856 "name": vdur["name"],
1857 "vdu_id": vdur["vdu-id-ref"],
1858 "interface": []
1859 })
1860 for interface in vdur["interfaces"]:
1861 vdu_scaling_info["vdu"][-1]["interface"].append({
1862 "name": interface["name"],
1863 "ip_address": interface["ip-address"],
1864 "mac_address": interface.get("mac-address"),
1865 })
1866 del vdu_scaling_info["vdu-delete"]
1867
1868 # execute primitive service PRE-SCALING
1869 step = "Executing pre-scale vnf-config-primitive"
1870 if scaling_descriptor.get("scaling-config-action"):
1871 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
1872 if scaling_config_action.get("trigger") and scaling_config_action["trigger"] == "pre-scale-in" \
1873 and scaling_type == "SCALE_IN":
1874 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
1875 step = db_nslcmop_update["detailed-status"] = \
1876 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive)
1877 # look for primitive
1878 primitive_params = {}
1879 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
1880 if config_primitive["name"] == vnf_config_primitive:
1881 for parameter in config_primitive.get("parameter", ()):
1882 if 'default-value' in parameter and \
1883 parameter['default-value'] == "<VDU_SCALE_INFO>":
1884 primitive_params[parameter["name"]] = yaml.safe_dump(vdu_scaling_info,
1885 default_flow_style=True,
1886 width=256)
1887 break
1888 else:
1889 raise LcmException(
1890 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
1891 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-cnfiguration:config-"
1892 "primitive".format(scaling_group, config_primitive))
1893 result, result_detail = await self._ns_execute_primitive(nsr_lcm, vnf_index,
1894 vnf_config_primitive, primitive_params)
1895 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
1896 vnf_config_primitive, result, result_detail))
1897 if result == "FAILED":
1898 raise LcmException(result_detail)
1899
1900 if RO_scaling_info:
1901 RO = ROclient.ROClient(self.loop, **self.ro_config)
1902 RO_desc = await RO.create_action("ns", RO_nsr_id, {"vdu-scaling": RO_scaling_info})
1903 db_nsr_update["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index)] = nb_scale_op
1904 db_nsr_update["_admin.scaling-group.{}.time".format(admin_scale_index)] = time()
1905 # TODO mark db_nsr_update as scaling
1906 # wait until ready
1907 RO_nslcmop_id = RO_desc["instance_action_id"]
1908 db_nslcmop_update["_admin.deploy.RO"] = RO_nslcmop_id
1909
1910 RO_task_done = False
1911 step = detailed_status = "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id)
1912 detailed_status_old = None
1913 self.logger.debug(logging_text + step)
1914
1915 deployment_timeout = 1 * 3600 # One hours
1916 while deployment_timeout > 0:
1917 if not RO_task_done:
1918 desc = await RO.show("ns", item_id_name=RO_nsr_id, extra_item="action",
1919 extra_item_id=RO_nslcmop_id)
1920 ns_status, ns_status_info = RO.check_action_status(desc)
1921 if ns_status == "ERROR":
1922 raise ROclient.ROClientException(ns_status_info)
1923 elif ns_status == "BUILD":
1924 detailed_status = step + "; {}".format(ns_status_info)
1925 elif ns_status == "ACTIVE":
1926 RO_task_done = True
1927 step = detailed_status = "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id)
1928 self.logger.debug(logging_text + step)
1929 else:
1930 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
1931 else:
1932 desc = await RO.show("ns", RO_nsr_id)
1933 ns_status, ns_status_info = RO.check_ns_status(desc)
1934 if ns_status == "ERROR":
1935 raise ROclient.ROClientException(ns_status_info)
1936 elif ns_status == "BUILD":
1937 detailed_status = step + "; {}".format(ns_status_info)
1938 elif ns_status == "ACTIVE":
1939 step = detailed_status = "Waiting for management IP address reported by the VIM"
1940 try:
1941 desc = await RO.show("ns", RO_nsr_id)
1942 nsr_lcm["nsr_ip"] = RO.get_ns_vnf_info(desc)
1943 break
1944 except ROclient.ROClientException as e:
1945 if e.http_code != 409: # IP address is not ready return code is 409 CONFLICT
1946 raise e
1947 else:
1948 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
1949 if detailed_status != detailed_status_old:
1950 detailed_status_old = db_nslcmop_update["detailed-status"] = detailed_status
1951 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1952
1953 await asyncio.sleep(5, loop=self.loop)
1954 deployment_timeout -= 5
1955 if deployment_timeout <= 0:
1956 raise ROclient.ROClientException("Timeout waiting ns to be ready")
1957
1958 step = "Updating VNFRs"
1959 self.ns_update_vnfr({db_vnfr["member-vnf-index-ref"]: db_vnfr}, desc)
1960
1961 # update VDU_SCALING_INFO with the obtained ip_addresses
1962 if vdu_scaling_info["scaling_direction"] == "OUT":
1963 for vdur in reversed(db_vnfr["vdur"]):
1964 if vdu_scaling_info["vdu-create"].get(vdur["vdu-id-ref"]):
1965 vdu_scaling_info["vdu-create"][vdur["vdu-id-ref"]] -= 1
1966 vdu_scaling_info["vdu"].append({
1967 "name": vdur["name"],
1968 "vdu_id": vdur["vdu-id-ref"],
1969 "interface": []
1970 })
1971 for interface in vdur["interfaces"]:
1972 vdu_scaling_info["vdu"][-1]["interface"].append({
1973 "name": interface["name"],
1974 "ip_address": interface["ip-address"],
1975 "mac_address": interface.get("mac-address"),
1976 })
1977 del vdu_scaling_info["vdu-create"]
1978
1979 if db_nsr_update:
1980 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1981
1982 # execute primitive service POST-SCALING
1983 step = "Executing post-scale vnf-config-primitive"
1984 if scaling_descriptor.get("scaling-config-action"):
1985 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
1986 if scaling_config_action.get("trigger") and scaling_config_action["trigger"] == "post-scale-out" \
1987 and scaling_type == "SCALE_OUT":
1988 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
1989 step = db_nslcmop_update["detailed-status"] = \
1990 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive)
1991 # look for primitive
1992 primitive_params = {}
1993 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
1994 if config_primitive["name"] == vnf_config_primitive:
1995 for parameter in config_primitive.get("parameter", ()):
1996 if 'default-value' in parameter and \
1997 parameter['default-value'] == "<VDU_SCALE_INFO>":
1998 primitive_params[parameter["name"]] = yaml.safe_dump(vdu_scaling_info,
1999 default_flow_style=True,
2000 width=256)
2001 break
2002 else:
2003 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
2004 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
2005 "match any vnf-cnfiguration:config-primitive".format(scaling_group,
2006 config_primitive))
2007 result, result_detail = await self._ns_execute_primitive(nsr_lcm, vnf_index,
2008 vnf_config_primitive, primitive_params)
2009 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
2010 vnf_config_primitive, result, result_detail))
2011 if result == "FAILED":
2012 raise LcmException(result_detail)
2013
2014 db_nslcmop_update["operationState"] = "COMPLETED"
2015 db_nslcmop_update["statusEnteredTime"] = time()
2016 db_nslcmop_update["detailed-status"] = "done"
2017 db_nsr_update["detailed-status"] = "done"
2018 db_nsr_update["operational-status"] = "running"
2019 try:
2020 await self.msg.aiowrite("ns", "scaled", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
2021 # if cooldown_time:
2022 # await asyncio.sleep(cooldown_time)
2023 # await self.msg.aiowrite("ns", "scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
2024 except Exception as e:
2025 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
2026 self.logger.debug(logging_text + "Exit Ok")
2027 return
2028 except (ROclient.ROClientException, DbException, LcmException) as e:
2029 self.logger.error(logging_text + "Exit Exception {}".format(e))
2030 exc = e
2031 except asyncio.CancelledError:
2032 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
2033 exc = "Operation was cancelled"
2034 except Exception as e:
2035 exc = traceback.format_exc()
2036 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
2037 finally:
2038 if exc:
2039 if db_nslcmop:
2040 db_nslcmop_update = {
2041 "detailed-status": "FAILED {}: {}".format(step, exc),
2042 "operationState": "FAILED",
2043 "statusEnteredTime": time(),
2044 }
2045 if db_nsr:
2046 db_nsr_update["operational-status"] = "FAILED {}: {}".format(step, exc),
2047 db_nsr_update["detailed-status"] = "failed"
2048 if db_nslcmop_update:
2049 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
2050 if db_nsr_update:
2051 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2052 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_scale")
2053
2054 async def test(self, param=None):
2055 self.logger.debug("Starting/Ending test task: {}".format(param))
2056
2057 async def kafka_ping(self):
2058 self.logger.debug("Task kafka_ping Enter")
2059 consecutive_errors = 0
2060 first_start = True
2061 kafka_has_received = False
2062 self.pings_not_received = 1
2063 while True:
2064 try:
2065 await self.msg.aiowrite("admin", "ping", {"from": "lcm", "to": "lcm"}, self.loop)
2066 # time between pings are low when it is not received and at starting
2067 wait_time = 5 if not kafka_has_received else 120
2068 if not self.pings_not_received:
2069 kafka_has_received = True
2070 self.pings_not_received += 1
2071 await asyncio.sleep(wait_time, loop=self.loop)
2072 if self.pings_not_received > 10:
2073 raise LcmException("It is not receiving pings from Kafka bus")
2074 consecutive_errors = 0
2075 first_start = False
2076 except LcmException:
2077 raise
2078 except Exception as e:
2079 # if not first_start is the first time after starting. So leave more time and wait
2080 # to allow kafka starts
2081 if consecutive_errors == 8 if not first_start else 30:
2082 self.logger.error("Task kafka_read task exit error too many errors. Exception: {}".format(e))
2083 raise
2084 consecutive_errors += 1
2085 self.logger.error("Task kafka_read retrying after Exception {}".format(e))
2086 wait_time = 1 if not first_start else 5
2087 await asyncio.sleep(wait_time, loop=self.loop)
2088
2089 async def kafka_read(self):
2090 self.logger.debug("Task kafka_read Enter")
2091 order_id = 1
2092 # future = asyncio.Future()
2093 consecutive_errors = 0
2094 first_start = True
2095 while consecutive_errors < 10:
2096 try:
2097 topics = ("admin", "ns", "vim_account", "sdn")
2098 topic, command, params = await self.msg.aioread(topics, self.loop)
2099 if topic != "admin" and command != "ping":
2100 self.logger.debug("Task kafka_read receives {} {}: {}".format(topic, command, params))
2101 consecutive_errors = 0
2102 first_start = False
2103 order_id += 1
2104 if command == "exit":
2105 print("Bye!")
2106 break
2107 elif command.startswith("#"):
2108 continue
2109 elif command == "echo":
2110 # just for test
2111 print(params)
2112 sys.stdout.flush()
2113 continue
2114 elif command == "test":
2115 asyncio.Task(self.test(params), loop=self.loop)
2116 continue
2117
2118 if topic == "admin":
2119 if command == "ping" and params["to"] == "lcm" and params["from"] == "lcm":
2120 self.pings_not_received = 0
2121 continue
2122 elif topic == "ns":
2123 if command == "instantiate":
2124 # self.logger.debug("Deploying NS {}".format(nsr_id))
2125 nslcmop = params
2126 nslcmop_id = nslcmop["_id"]
2127 nsr_id = nslcmop["nsInstanceId"]
2128 task = asyncio.ensure_future(self.ns_instantiate(nsr_id, nslcmop_id))
2129 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_instantiate", task)
2130 continue
2131 elif command == "terminate":
2132 # self.logger.debug("Deleting NS {}".format(nsr_id))
2133 nslcmop = params
2134 nslcmop_id = nslcmop["_id"]
2135 nsr_id = nslcmop["nsInstanceId"]
2136 self.lcm_tasks.cancel(topic, nsr_id)
2137 task = asyncio.ensure_future(self.ns_terminate(nsr_id, nslcmop_id))
2138 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_terminate", task)
2139 continue
2140 elif command == "action":
2141 # self.logger.debug("Update NS {}".format(nsr_id))
2142 nslcmop = params
2143 nslcmop_id = nslcmop["_id"]
2144 nsr_id = nslcmop["nsInstanceId"]
2145 task = asyncio.ensure_future(self.ns_action(nsr_id, nslcmop_id))
2146 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_action", task)
2147 continue
2148 elif command == "scale":
2149 # self.logger.debug("Update NS {}".format(nsr_id))
2150 nslcmop = params
2151 nslcmop_id = nslcmop["_id"]
2152 nsr_id = nslcmop["nsInstanceId"]
2153 task = asyncio.ensure_future(self.ns_scale(nsr_id, nslcmop_id))
2154 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_scale", task)
2155 continue
2156 elif command == "show":
2157 try:
2158 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2159 print("nsr:\n _id={}\n operational-status: {}\n config-status: {}"
2160 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
2161 "".format(nsr_id, db_nsr["operational-status"], db_nsr["config-status"],
2162 db_nsr["detailed-status"],
2163 db_nsr["_admin"]["deployed"], self.lcm_ns_tasks.get(nsr_id)))
2164 except Exception as e:
2165 print("nsr {} not found: {}".format(nsr_id, e))
2166 sys.stdout.flush()
2167 continue
2168 elif command == "deleted":
2169 continue # TODO cleaning of task just in case should be done
2170 elif command in ("terminated", "instantiated", "scaled", "actioned"): # "scaled-cooldown-time"
2171 continue
2172 elif topic == "vim_account":
2173 vim_id = params["_id"]
2174 if command == "create":
2175 task = asyncio.ensure_future(self.vim_create(params, order_id))
2176 self.lcm_tasks.register("vim_account", vim_id, order_id, "vim_create", task)
2177 continue
2178 elif command == "delete":
2179 self.lcm_tasks.cancel(topic, vim_id)
2180 task = asyncio.ensure_future(self.vim_delete(vim_id, order_id))
2181 self.lcm_tasks.register("vim_account", vim_id, order_id, "vim_delete", task)
2182 continue
2183 elif command == "show":
2184 print("not implemented show with vim_account")
2185 sys.stdout.flush()
2186 continue
2187 elif command == "edit":
2188 task = asyncio.ensure_future(self.vim_edit(params, order_id))
2189 self.lcm_tasks.register("vim_account", vim_id, order_id, "vim_edit", task)
2190 continue
2191 elif topic == "sdn":
2192 _sdn_id = params["_id"]
2193 if command == "create":
2194 task = asyncio.ensure_future(self.sdn_create(params, order_id))
2195 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_create", task)
2196 continue
2197 elif command == "delete":
2198 self.lcm_tasks.cancel(topic, _sdn_id)
2199 task = asyncio.ensure_future(self.sdn_delete(_sdn_id, order_id))
2200 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_delete", task)
2201 continue
2202 elif command == "edit":
2203 task = asyncio.ensure_future(self.sdn_edit(params, order_id))
2204 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_edit", task)
2205 continue
2206 self.logger.critical("unknown topic {} and command '{}'".format(topic, command))
2207 except Exception as e:
2208 # if not first_start is the first time after starting. So leave more time and wait
2209 # to allow kafka starts
2210 if consecutive_errors == 8 if not first_start else 30:
2211 self.logger.error("Task kafka_read task exit error too many errors. Exception: {}".format(e))
2212 raise
2213 consecutive_errors += 1
2214 self.logger.error("Task kafka_read retrying after Exception {}".format(e))
2215 wait_time = 2 if not first_start else 5
2216 await asyncio.sleep(wait_time, loop=self.loop)
2217
2218 # self.logger.debug("Task kafka_read terminating")
2219 self.logger.debug("Task kafka_read exit")
2220
2221 def start(self):
2222 self.loop = asyncio.get_event_loop()
2223
2224 # check RO version
2225 self.loop.run_until_complete(self.check_RO_version())
2226
2227 self.loop.run_until_complete(asyncio.gather(
2228 self.kafka_read(),
2229 self.kafka_ping()
2230 ))
2231 # TODO
2232 # self.logger.debug("Terminating cancelling creation tasks")
2233 # self.lcm_tasks.cancel("ALL", "create")
2234 # timeout = 200
2235 # while self.is_pending_tasks():
2236 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
2237 # await asyncio.sleep(2, loop=self.loop)
2238 # timeout -= 2
2239 # if not timeout:
2240 # self.lcm_tasks.cancel("ALL", "ALL")
2241 self.loop.close()
2242 self.loop = None
2243 if self.db:
2244 self.db.db_disconnect()
2245 if self.msg:
2246 self.msg.disconnect()
2247 if self.fs:
2248 self.fs.fs_disconnect()
2249
2250 def read_config_file(self, config_file):
2251 # TODO make a [ini] + yaml inside parser
2252 # the configparser library is not suitable, because it does not admit comments at the end of line,
2253 # and not parse integer or boolean
2254 try:
2255 with open(config_file) as f:
2256 conf = yaml.load(f)
2257 for k, v in environ.items():
2258 if not k.startswith("OSMLCM_"):
2259 continue
2260 k_items = k.lower().split("_")
2261 c = conf
2262 try:
2263 for k_item in k_items[1:-1]:
2264 if k_item in ("ro", "vca"):
2265 # put in capital letter
2266 k_item = k_item.upper()
2267 c = c[k_item]
2268 if k_items[-1] == "port":
2269 c[k_items[-1]] = int(v)
2270 else:
2271 c[k_items[-1]] = v
2272 except Exception as e:
2273 self.logger.warn("skipping environ '{}' on exception '{}'".format(k, e))
2274
2275 return conf
2276 except Exception as e:
2277 self.logger.critical("At config file '{}': {}".format(config_file, e))
2278 exit(1)
2279
2280
2281 def usage():
2282 print("""Usage: {} [options]
2283 -c|--config [configuration_file]: loads the configuration file (default: ./nbi.cfg)
2284 -h|--help: shows this help
2285 """.format(sys.argv[0]))
2286 # --log-socket-host HOST: send logs to this host")
2287 # --log-socket-port PORT: send logs using this port (default: 9022)")
2288
2289
2290 if __name__ == '__main__':
2291 try:
2292 # load parameters and configuration
2293 opts, args = getopt.getopt(sys.argv[1:], "hc:", ["config=", "help"])
2294 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
2295 config_file = None
2296 for o, a in opts:
2297 if o in ("-h", "--help"):
2298 usage()
2299 sys.exit()
2300 elif o in ("-c", "--config"):
2301 config_file = a
2302 # elif o == "--log-socket-port":
2303 # log_socket_port = a
2304 # elif o == "--log-socket-host":
2305 # log_socket_host = a
2306 # elif o == "--log-file":
2307 # log_file = a
2308 else:
2309 assert False, "Unhandled option"
2310 if config_file:
2311 if not path.isfile(config_file):
2312 print("configuration file '{}' that not exist".format(config_file), file=sys.stderr)
2313 exit(1)
2314 else:
2315 for config_file in (__file__[:__file__.rfind(".")] + ".cfg", "./lcm.cfg", "/etc/osm/lcm.cfg"):
2316 if path.isfile(config_file):
2317 break
2318 else:
2319 print("No configuration file 'nbi.cfg' found neither at local folder nor at /etc/osm/", file=sys.stderr)
2320 exit(1)
2321 lcm = Lcm(config_file)
2322 lcm.start()
2323 except (LcmException, getopt.GetoptError) as e:
2324 print(str(e), file=sys.stderr)
2325 # usage()
2326 exit(1)