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