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