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