Fix bug 533 passing DNS addresses to the RO
[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 if isinstance(RO_ip_profile["dns-server"], list):
821 RO_ip_profile["dns-address"] = []
822 for ds in RO_ip_profile.pop("dns-server"):
823 RO_ip_profile["dns-address"].append(ds['address'])
824 else:
825 RO_ip_profile["dns-address"] = RO_ip_profile.pop("dns-server")
826 if RO_ip_profile.get("ip-version") == "ipv4":
827 RO_ip_profile["ip-version"] = "IPv4"
828 if RO_ip_profile.get("ip-version") == "ipv6":
829 RO_ip_profile["ip-version"] = "IPv6"
830 if "dhcp-params" in RO_ip_profile:
831 RO_ip_profile["dhcp"] = RO_ip_profile.pop("dhcp-params")
832 return RO_ip_profile
833
834 if not ns_params:
835 return None
836 RO_ns_params = {
837 # "name": ns_params["nsName"],
838 # "description": ns_params.get("nsDescription"),
839 "datacenter": vim_account_2_RO(ns_params["vimAccountId"]),
840 # "scenario": ns_params["nsdId"],
841 "vnfs": {},
842 "networks": {},
843 }
844 if ns_params.get("ssh-authorized-key"):
845 RO_ns_params["cloud-config"] = {"key-pairs": ns_params["ssh-authorized-key"]}
846 if ns_params.get("vnf"):
847 for vnf_params in ns_params["vnf"]:
848 for constituent_vnfd in nsd["constituent-vnfd"]:
849 if constituent_vnfd["member-vnf-index"] == vnf_params["member-vnf-index"]:
850 vnf_descriptor = vnfd_dict[constituent_vnfd["vnfd-id-ref"]]
851 break
852 else:
853 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index={} is not present at nsd:"
854 "constituent-vnfd".format(vnf_params["member-vnf-index"]))
855 RO_vnf = {"vdus": {}, "networks": {}}
856 if vnf_params.get("vimAccountId"):
857 RO_vnf["datacenter"] = vim_account_2_RO(vnf_params["vimAccountId"])
858 if vnf_params.get("vdu"):
859 for vdu_params in vnf_params["vdu"]:
860 RO_vnf["vdus"][vdu_params["id"]] = {}
861 if vdu_params.get("volume"):
862 RO_vnf["vdus"][vdu_params["id"]]["devices"] = {}
863 for volume_params in vdu_params["volume"]:
864 RO_vnf["vdus"][vdu_params["id"]]["devices"][volume_params["name"]] = {}
865 if volume_params.get("vim-volume-id"):
866 RO_vnf["vdus"][vdu_params["id"]]["devices"][volume_params["name"]]["vim_id"] = \
867 volume_params["vim-volume-id"]
868 if vdu_params.get("interface"):
869 RO_vnf["vdus"][vdu_params["id"]]["interfaces"] = {}
870 for interface_params in vdu_params["interface"]:
871 RO_interface = {}
872 RO_vnf["vdus"][vdu_params["id"]]["interfaces"][interface_params["name"]] = RO_interface
873 if interface_params.get("ip-address"):
874 RO_interface["ip_address"] = interface_params["ip-address"]
875 if interface_params.get("mac-address"):
876 RO_interface["mac_address"] = interface_params["mac-address"]
877 if interface_params.get("floating-ip-required"):
878 RO_interface["floating-ip"] = interface_params["floating-ip-required"]
879 if vnf_params.get("internal-vld"):
880 for internal_vld_params in vnf_params["internal-vld"]:
881 RO_vnf["networks"][internal_vld_params["name"]] = {}
882 if internal_vld_params.get("vim-network-name"):
883 RO_vnf["networks"][internal_vld_params["name"]]["vim-network-name"] = \
884 internal_vld_params["vim-network-name"]
885 if internal_vld_params.get("ip-profile"):
886 RO_vnf["networks"][internal_vld_params["name"]]["ip-profile"] = \
887 ip_profile_2_RO(internal_vld_params["ip-profile"])
888 if internal_vld_params.get("internal-connection-point"):
889 for icp_params in internal_vld_params["internal-connection-point"]:
890 # look for interface
891 iface_found = False
892 for vdu_descriptor in vnf_descriptor["vdu"]:
893 for vdu_interface in vdu_descriptor["interface"]:
894 if vdu_interface.get("internal-connection-point-ref") == icp_params["id-ref"]:
895 if vdu_descriptor["id"] not in RO_vnf["vdus"]:
896 RO_vnf["vdus"][vdu_descriptor["id"]] = {}
897 if "interfaces" not in RO_vnf["vdus"][vdu_descriptor["id"]]:
898 RO_vnf["vdus"][vdu_descriptor["id"]]["interfaces"] = {}
899 RO_ifaces = RO_vnf["vdus"][vdu_descriptor["id"]]["interfaces"]
900 if vdu_interface["name"] not in RO_ifaces:
901 RO_ifaces[vdu_interface["name"]] = {}
902
903 RO_ifaces[vdu_interface["name"]]["ip_address"] = icp_params["ip-address"]
904 iface_found = True
905 break
906 if iface_found:
907 break
908 else:
909 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
910 "internal-vld:id-ref={} is not present at vnfd:internal-"
911 "connection-point".format(vnf_params["member-vnf-index"],
912 icp_params["id-ref"]))
913
914 if not RO_vnf["vdus"]:
915 del RO_vnf["vdus"]
916 if not RO_vnf["networks"]:
917 del RO_vnf["networks"]
918 if RO_vnf:
919 RO_ns_params["vnfs"][vnf_params["member-vnf-index"]] = RO_vnf
920 if ns_params.get("vld"):
921 for vld_params in ns_params["vld"]:
922 RO_vld = {}
923 if "ip-profile" in vld_params:
924 RO_vld["ip-profile"] = ip_profile_2_RO(vld_params["ip-profile"])
925 if "vim-network-name" in vld_params:
926 RO_vld["sites"] = []
927 if isinstance(vld_params["vim-network-name"], dict):
928 for vim_account, vim_net in vld_params["vim-network-name"].items():
929 RO_vld["sites"].append({
930 "netmap-use": vim_net,
931 "datacenter": vim_account_2_RO(vim_account)
932 })
933 else: # isinstance str
934 RO_vld["sites"].append({"netmap-use": vld_params["vim-network-name"]})
935 if RO_vld:
936 RO_ns_params["networks"][vld_params["name"]] = RO_vld
937 return RO_ns_params
938
939 def ns_update_vnfr(self, db_vnfrs, nsr_desc_RO):
940 """
941 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
942 :param db_vnfrs:
943 :param nsr_desc_RO:
944 :return:
945 """
946 for vnf_index, db_vnfr in db_vnfrs.items():
947 for vnf_RO in nsr_desc_RO["vnfs"]:
948 if vnf_RO["member_vnf_index"] == vnf_index:
949 vnfr_update = {}
950 db_vnfr["ip-address"] = vnfr_update["ip-address"] = vnf_RO.get("ip_address")
951 vdur_list = []
952 for vdur_RO in vnf_RO.get("vms", ()):
953 vdur = {
954 "vim-id": vdur_RO.get("vim_vm_id"),
955 "ip-address": vdur_RO.get("ip_address"),
956 "vdu-id-ref": vdur_RO.get("vdu_osm_id"),
957 "name": vdur_RO.get("vim_name"),
958 "status": vdur_RO.get("status"),
959 "status-detailed": vdur_RO.get("error_msg"),
960 "interfaces": []
961 }
962
963 for interface_RO in vdur_RO.get("interfaces", ()):
964 vdur["interfaces"].append({
965 "ip-address": interface_RO.get("ip_address"),
966 "mac-address": interface_RO.get("mac_address"),
967 "name": interface_RO.get("external_name"),
968 })
969 vdur_list.append(vdur)
970 db_vnfr["vdur"] = vnfr_update["vdur"] = vdur_list
971 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
972 break
973
974 else:
975 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} at RO info".format(vnf_index))
976
977 async def create_monitoring(self, nsr_id, vnf_member_index, vnfd_desc):
978 if not vnfd_desc.get("scaling-group-descriptor"):
979 return
980 for scaling_group in vnfd_desc["scaling-group-descriptor"]:
981 scaling_policy_desc = {}
982 scaling_desc = {
983 "ns_id": nsr_id,
984 "scaling_group_descriptor": {
985 "name": scaling_group["name"],
986 "scaling_policy": scaling_policy_desc
987 }
988 }
989 for scaling_policy in scaling_group.get("scaling-policy"):
990 scaling_policy_desc["scale_in_operation_type"] = scaling_policy_desc["scale_out_operation_type"] = \
991 scaling_policy["scaling-type"]
992 scaling_policy_desc["threshold_time"] = scaling_policy["threshold-time"]
993 scaling_policy_desc["cooldown_time"] = scaling_policy["cooldown-time"]
994 scaling_policy_desc["scaling_criteria"] = []
995 for scaling_criteria in scaling_policy.get("scaling-criteria"):
996 scaling_criteria_desc = {"scale_in_threshold": scaling_criteria.get("scale-in-threshold"),
997 "scale_out_threshold": scaling_criteria.get("scale-out-threshold"),
998 }
999 if not scaling_criteria.get("vnf-monitoring-param-ref"):
1000 continue
1001 for monitoring_param in vnfd_desc.get("monitoring-param", ()):
1002 if monitoring_param["id"] == scaling_criteria["vnf-monitoring-param-ref"]:
1003 scaling_criteria_desc["monitoring_param"] = {
1004 "id": monitoring_param["id"],
1005 "name": monitoring_param["name"],
1006 "aggregation_type": monitoring_param.get("aggregation-type"),
1007 "vdu_name": monitoring_param.get("vdu-ref"),
1008 "vnf_member_index": vnf_member_index,
1009 }
1010
1011 scaling_policy_desc["scaling_criteria"].append(scaling_criteria_desc)
1012 break
1013 else:
1014 self.logger.error(
1015 "Task ns={} member_vnf_index={} Invalid vnfd vnf-monitoring-param-ref={} not in "
1016 "monitoring-param list".format(nsr_id, vnf_member_index,
1017 scaling_criteria["vnf-monitoring-param-ref"]))
1018
1019 await self.msg.aiowrite("lcm_pm", "configure_scaling", scaling_desc, self.loop)
1020
1021 async def ns_instantiate(self, nsr_id, nslcmop_id):
1022 logging_text = "Task ns={} instantiate={} ".format(nsr_id, nslcmop_id)
1023 self.logger.debug(logging_text + "Enter")
1024 # get all needed from database
1025 db_nsr = None
1026 db_nslcmop = None
1027 db_nsr_update = {}
1028 db_nslcmop_update = {}
1029 db_vnfrs = {}
1030 RO_descriptor_number = 0 # number of descriptors created at RO
1031 descriptor_id_2_RO = {} # map between vnfd/nsd id to the id used at RO
1032 exc = None
1033 try:
1034 step = "Getting nslcmop={} from db".format(nslcmop_id)
1035 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
1036 step = "Getting nsr={} from db".format(nsr_id)
1037 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1038 ns_params = db_nsr.get("instantiate_params")
1039 nsd = db_nsr["nsd"]
1040 nsr_name = db_nsr["name"] # TODO short-name??
1041 needed_vnfd = {}
1042 vnfr_filter = {"nsr-id-ref": nsr_id, "member-vnf-index-ref": None}
1043 for c_vnf in nsd["constituent-vnfd"]:
1044 vnfd_id = c_vnf["vnfd-id-ref"]
1045 vnfr_filter["member-vnf-index-ref"] = c_vnf["member-vnf-index"]
1046 step = "Getting vnfr={} of nsr={} from db".format(c_vnf["member-vnf-index"], nsr_id)
1047 db_vnfrs[c_vnf["member-vnf-index"]] = self.db.get_one("vnfrs", vnfr_filter)
1048 if vnfd_id not in needed_vnfd:
1049 step = "Getting vnfd={} from db".format(vnfd_id)
1050 needed_vnfd[vnfd_id] = self.db.get_one("vnfds", {"id": vnfd_id})
1051
1052 nsr_lcm = db_nsr["_admin"].get("deployed")
1053 if not nsr_lcm:
1054 nsr_lcm = db_nsr["_admin"]["deployed"] = {
1055 "id": nsr_id,
1056 "RO": {"vnfd_id": {}, "nsd_id": None, "nsr_id": None, "nsr_status": "SCHEDULED"},
1057 "nsr_ip": {},
1058 "VCA": {},
1059 }
1060 db_nsr_update["detailed-status"] = "creating"
1061 db_nsr_update["operational-status"] = "init"
1062
1063 RO = ROclient.ROClient(self.loop, **self.ro_config)
1064
1065 # get vnfds, instantiate at RO
1066 for vnfd_id, vnfd in needed_vnfd.items():
1067 step = db_nsr_update["detailed-status"] = "Creating vnfd={} at RO".format(vnfd_id)
1068 # self.logger.debug(logging_text + step)
1069 vnfd_id_RO = "{}.{}.{}".format(nsr_id, RO_descriptor_number, vnfd_id[:23])
1070 descriptor_id_2_RO[vnfd_id] = vnfd_id_RO
1071 RO_descriptor_number += 1
1072
1073 # look if present
1074 vnfd_list = await RO.get_list("vnfd", filter_by={"osm_id": vnfd_id_RO})
1075 if vnfd_list:
1076 db_nsr_update["_admin.deployed.RO.vnfd_id.{}".format(vnfd_id)] = vnfd_list[0]["uuid"]
1077 self.logger.debug(logging_text + "vnfd={} exists at RO. Using RO_id={}".format(
1078 vnfd_id, vnfd_list[0]["uuid"]))
1079 else:
1080 vnfd_RO = self.vnfd2RO(vnfd, vnfd_id_RO)
1081 desc = await RO.create("vnfd", descriptor=vnfd_RO)
1082 db_nsr_update["_admin.deployed.RO.vnfd_id.{}".format(vnfd_id)] = desc["uuid"]
1083 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
1084 self.logger.debug(logging_text + "vnfd={} created at RO. RO_id={}".format(
1085 vnfd_id, desc["uuid"]))
1086 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1087
1088 # create nsd at RO
1089 nsd_id = nsd["id"]
1090 step = db_nsr_update["detailed-status"] = "Creating nsd={} at RO".format(nsd_id)
1091 # self.logger.debug(logging_text + step)
1092
1093 RO_osm_nsd_id = "{}.{}.{}".format(nsr_id, RO_descriptor_number, nsd_id[:23])
1094 descriptor_id_2_RO[nsd_id] = RO_osm_nsd_id
1095 RO_descriptor_number += 1
1096 nsd_list = await RO.get_list("nsd", filter_by={"osm_id": RO_osm_nsd_id})
1097 if nsd_list:
1098 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = nsd_list[0]["uuid"]
1099 self.logger.debug(logging_text + "nsd={} exists at RO. Using RO_id={}".format(
1100 nsd_id, RO_nsd_uuid))
1101 else:
1102 nsd_RO = deepcopy(nsd)
1103 nsd_RO["id"] = RO_osm_nsd_id
1104 nsd_RO.pop("_id", None)
1105 nsd_RO.pop("_admin", None)
1106 for c_vnf in nsd_RO["constituent-vnfd"]:
1107 vnfd_id = c_vnf["vnfd-id-ref"]
1108 c_vnf["vnfd-id-ref"] = descriptor_id_2_RO[vnfd_id]
1109 desc = await RO.create("nsd", descriptor=nsd_RO)
1110 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
1111 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = desc["uuid"]
1112 self.logger.debug(logging_text + "nsd={} created at RO. RO_id={}".format(nsd_id, RO_nsd_uuid))
1113 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1114
1115 # Crate ns at RO
1116 # if present use it unless in error status
1117 RO_nsr_id = db_nsr["_admin"].get("deployed", {}).get("RO", {}).get("nsr_id")
1118 if RO_nsr_id:
1119 try:
1120 step = db_nsr_update["detailed-status"] = "Looking for existing ns at RO"
1121 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
1122 desc = await RO.show("ns", RO_nsr_id)
1123 except ROclient.ROClientException as e:
1124 if e.http_code != HTTPStatus.NOT_FOUND:
1125 raise
1126 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
1127 if RO_nsr_id:
1128 ns_status, ns_status_info = RO.check_ns_status(desc)
1129 db_nsr_update["_admin.deployed.RO.nsr_status"] = ns_status
1130 if ns_status == "ERROR":
1131 step = db_nsr_update["detailed-status"] = "Deleting ns at RO. RO_ns_id={}".format(RO_nsr_id)
1132 self.logger.debug(logging_text + step)
1133 await RO.delete("ns", RO_nsr_id)
1134 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
1135 if not RO_nsr_id:
1136 step = db_nsr_update["detailed-status"] = "Creating ns at RO"
1137 # self.logger.debug(logging_text + step)
1138
1139 # check if VIM is creating and wait look if previous tasks in process
1140 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account", ns_params["vimAccountId"])
1141 if task_dependency:
1142 step = "Waiting for related tasks to be completed: {}".format(task_name)
1143 self.logger.debug(logging_text + step)
1144 await asyncio.wait(task_dependency, timeout=3600)
1145 if ns_params.get("vnf"):
1146 for vnf in ns_params["vnf"]:
1147 if "vimAccountId" in vnf:
1148 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account",
1149 vnf["vimAccountId"])
1150 if task_dependency:
1151 step = "Waiting for related tasks to be completed: {}".format(task_name)
1152 self.logger.debug(logging_text + step)
1153 await asyncio.wait(task_dependency, timeout=3600)
1154
1155 RO_ns_params = self.ns_params_2_RO(ns_params, nsd, needed_vnfd)
1156 desc = await RO.create("ns", descriptor=RO_ns_params,
1157 name=db_nsr["name"],
1158 scenario=RO_nsd_uuid)
1159 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = desc["uuid"]
1160 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
1161 db_nsr_update["_admin.deployed.RO.nsr_status"] = "BUILD"
1162 self.logger.debug(logging_text + "ns created at RO. RO_id={}".format(desc["uuid"]))
1163 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1164
1165 # update VNFR vimAccount
1166 step = "Updating VNFR vimAcccount"
1167 for vnf_index, vnfr in db_vnfrs.items():
1168 if vnfr.get("vim-account-id"):
1169 continue
1170 vnfr_update = {"vim-account-id": db_nsr["instantiate_params"]["vimAccountId"]}
1171 if db_nsr["instantiate_params"].get("vnf"):
1172 for vnf_params in db_nsr["instantiate_params"]["vnf"]:
1173 if vnf_params.get("member-vnf-index") == vnf_index:
1174 if vnf_params.get("vimAccountId"):
1175 vnfr_update["vim-account-id"] = vnf_params.get("vimAccountId")
1176 break
1177 self.update_db_2("vnfrs", vnfr["_id"], vnfr_update)
1178
1179 # wait until NS is ready
1180 step = ns_status_detailed = detailed_status = "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id)
1181 detailed_status_old = None
1182 self.logger.debug(logging_text + step)
1183
1184 deployment_timeout = 2 * 3600 # Two hours
1185 while deployment_timeout > 0:
1186 desc = await RO.show("ns", RO_nsr_id)
1187 ns_status, ns_status_info = RO.check_ns_status(desc)
1188 db_nsr_update["admin.deployed.RO.nsr_status"] = ns_status
1189 if ns_status == "ERROR":
1190 raise ROclient.ROClientException(ns_status_info)
1191 elif ns_status == "BUILD":
1192 detailed_status = ns_status_detailed + "; {}".format(ns_status_info)
1193 elif ns_status == "ACTIVE":
1194 step = detailed_status = "Waiting for management IP address reported by the VIM"
1195 try:
1196 nsr_lcm["nsr_ip"] = RO.get_ns_vnf_info(desc)
1197 break
1198 except ROclient.ROClientException as e:
1199 if e.http_code != 409: # IP address is not ready return code is 409 CONFLICT
1200 raise e
1201 else:
1202 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
1203 if detailed_status != detailed_status_old:
1204 detailed_status_old = db_nsr_update["detailed-status"] = detailed_status
1205 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1206 await asyncio.sleep(5, loop=self.loop)
1207 deployment_timeout -= 5
1208 if deployment_timeout <= 0:
1209 raise ROclient.ROClientException("Timeout waiting ns to be ready")
1210
1211 step = "Updating VNFRs"
1212 self.ns_update_vnfr(db_vnfrs, desc)
1213
1214 db_nsr["detailed-status"] = "Configuring vnfr"
1215 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1216
1217 # The parameters we'll need to deploy a charm
1218 number_to_configure = 0
1219
1220 def deploy(vnf_index, vdu_id, mgmt_ip_address, config_primitive=None):
1221 """An inner function to deploy the charm from either vnf or vdu
1222 vnf_index is mandatory. vdu_id can be None for a vnf configuration or the id for vdu configuration
1223 """
1224 if not mgmt_ip_address:
1225 raise LcmException("vnfd/vdu has not management ip address to configure it")
1226 # Login to the VCA.
1227 # if number_to_configure == 0:
1228 # self.logger.debug("Logging into N2VC...")
1229 # task = asyncio.ensure_future(self.n2vc.login())
1230 # yield from asyncio.wait_for(task, 30.0)
1231 # self.logger.debug("Logged into N2VC!")
1232
1233 # # await self.n2vc.login()
1234
1235 # Note: The charm needs to exist on disk at the location
1236 # specified by charm_path.
1237 base_folder = vnfd["_admin"]["storage"]
1238 storage_params = self.fs.get_params()
1239 charm_path = "{}{}/{}/charms/{}".format(
1240 storage_params["path"],
1241 base_folder["folder"],
1242 base_folder["pkg-dir"],
1243 proxy_charm
1244 )
1245
1246 # Setup the runtime parameters for this VNF
1247 params = {'rw_mgmt_ip': mgmt_ip_address}
1248 if config_primitive:
1249 params["initial-config-primitive"] = config_primitive
1250
1251 # ns_name will be ignored in the current version of N2VC
1252 # but will be implemented for the next point release.
1253 model_name = 'default'
1254 vdu_id_text = "vnfd"
1255 if vdu_id:
1256 vdu_id_text = vdu_id
1257 application_name = self.n2vc.FormatApplicationName(
1258 nsr_name,
1259 vnf_index,
1260 vdu_id_text
1261 )
1262 if not nsr_lcm.get("VCA"):
1263 nsr_lcm["VCA"] = {}
1264 nsr_lcm["VCA"][application_name] = db_nsr_update["_admin.deployed.VCA.{}".format(application_name)] = {
1265 "member-vnf-index": vnf_index,
1266 "vdu_id": vdu_id,
1267 "model": model_name,
1268 "application": application_name,
1269 "operational-status": "init",
1270 "detailed-status": "",
1271 "vnfd_id": vnfd_id,
1272 }
1273 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1274
1275 self.logger.debug("Task create_ns={} Passing artifacts path '{}' for {}".format(nsr_id, charm_path,
1276 proxy_charm))
1277 task = asyncio.ensure_future(
1278 self.n2vc.DeployCharms(
1279 model_name, # The network service name
1280 application_name, # The application name
1281 vnfd, # The vnf descriptor
1282 charm_path, # Path to charm
1283 params, # Runtime params, like mgmt ip
1284 {}, # for native charms only
1285 self.n2vc_callback, # Callback for status changes
1286 db_nsr, # Callback parameter
1287 db_nslcmop,
1288 None, # Callback parameter (task)
1289 )
1290 )
1291 task.add_done_callback(functools.partial(self.n2vc_callback, model_name, application_name, None, None,
1292 db_nsr, db_nslcmop))
1293 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "create_charm:" + application_name, task)
1294
1295 step = "Looking for needed vnfd to configure"
1296 self.logger.debug(logging_text + step)
1297
1298 for c_vnf in nsd["constituent-vnfd"]:
1299 vnfd_id = c_vnf["vnfd-id-ref"]
1300 vnf_index = str(c_vnf["member-vnf-index"])
1301 vnfd = needed_vnfd[vnfd_id]
1302
1303 # Check if this VNF has a charm configuration
1304 vnf_config = vnfd.get("vnf-configuration")
1305
1306 if vnf_config and vnf_config.get("juju"):
1307 proxy_charm = vnf_config["juju"]["charm"]
1308 config_primitive = None
1309
1310 if proxy_charm:
1311 if 'initial-config-primitive' in vnf_config:
1312 config_primitive = vnf_config['initial-config-primitive']
1313
1314 # Login to the VCA. If there are multiple calls to login(),
1315 # subsequent calls will be a nop and return immediately.
1316 step = "connecting to N2VC to configure vnf {}".format(vnf_index)
1317 await self.n2vc.login()
1318 deploy(vnf_index, None, db_vnfrs[vnf_index]["ip-address"], config_primitive)
1319 number_to_configure += 1
1320
1321 # Deploy charms for each VDU that supports one.
1322 vdu_index = 0
1323 for vdu in vnfd['vdu']:
1324 vdu_config = vdu.get('vdu-configuration')
1325 proxy_charm = None
1326 config_primitive = None
1327
1328 if vdu_config and vdu_config.get("juju"):
1329 proxy_charm = vdu_config["juju"]["charm"]
1330
1331 if 'initial-config-primitive' in vdu_config:
1332 config_primitive = vdu_config['initial-config-primitive']
1333
1334 if proxy_charm:
1335 step = "connecting to N2VC to configure vdu {} from vnf {}".format(vdu["id"], vnf_index)
1336 await self.n2vc.login()
1337 deploy(vnf_index, vdu["id"], db_vnfrs[vnf_index]["vdur"][vdu_index]["ip-address"],
1338 config_primitive)
1339 number_to_configure += 1
1340 vdu_index += 1
1341
1342 if number_to_configure:
1343 db_nsr_update["config-status"] = "configuring"
1344 db_nsr_update["operational-status"] = "running"
1345 db_nsr_update["detailed-status"] = "configuring: init: {}".format(number_to_configure)
1346 db_nslcmop_update["detailed-status"] = "configuring: init: {}".format(number_to_configure)
1347 else:
1348 db_nslcmop_update["operationState"] = "COMPLETED"
1349 db_nslcmop_update["statusEnteredTime"] = time()
1350 db_nslcmop_update["detailed-status"] = "done"
1351 db_nsr_update["config-status"] = "configured"
1352 db_nsr_update["detailed-status"] = "done"
1353 db_nsr_update["operational-status"] = "running"
1354 step = "Sending monitoring parameters to PM"
1355 # for c_vnf in nsd["constituent-vnfd"]:
1356 # await self.create_monitoring(nsr_id, c_vnf["member-vnf-index"], needed_vnfd[c_vnf["vnfd-id-ref"]])
1357 try:
1358 await self.msg.aiowrite("ns", "instantiated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
1359 except Exception as e:
1360 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1361
1362 self.logger.debug(logging_text + "Exit")
1363 return
1364
1365 except (ROclient.ROClientException, DbException, LcmException) as e:
1366 self.logger.error(logging_text + "Exit Exception while '{}': {}".format(step, e))
1367 exc = e
1368 except asyncio.CancelledError:
1369 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1370 exc = "Operation was cancelled"
1371 except Exception as e:
1372 exc = traceback.format_exc()
1373 self.logger.critical(logging_text + "Exit Exception {} while '{}': {}".format(type(e).__name__, step, e),
1374 exc_info=True)
1375 finally:
1376 if exc:
1377 if db_nsr:
1378 db_nsr_update["detailed-status"] = "ERROR {}: {}".format(step, exc)
1379 db_nsr_update["operational-status"] = "failed"
1380 if db_nslcmop:
1381 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
1382 db_nslcmop_update["operationState"] = "FAILED"
1383 db_nslcmop_update["statusEnteredTime"] = time()
1384 if db_nsr_update:
1385 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1386 if db_nslcmop_update:
1387 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1388 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_instantiate")
1389
1390 async def ns_terminate(self, nsr_id, nslcmop_id):
1391 logging_text = "Task ns={} terminate={} ".format(nsr_id, nslcmop_id)
1392 self.logger.debug(logging_text + "Enter")
1393 db_nsr = None
1394 db_nslcmop = None
1395 exc = None
1396 failed_detail = [] # annotates all failed error messages
1397 vca_task_list = []
1398 vca_task_dict = {}
1399 db_nsr_update = {}
1400 db_nslcmop_update = {}
1401 try:
1402 step = "Getting nslcmop={} from db".format(nslcmop_id)
1403 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
1404 step = "Getting nsr={} from db".format(nsr_id)
1405 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1406 # nsd = db_nsr["nsd"]
1407 nsr_lcm = deepcopy(db_nsr["_admin"].get("deployed"))
1408 if db_nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
1409 return
1410 # TODO ALF remove
1411 # db_vim = self.db.get_one("vim_accounts", {"_id": db_nsr["datacenter"]})
1412 # #TODO check if VIM is creating and wait
1413 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
1414
1415 db_nsr_update["operational-status"] = "terminating"
1416 db_nsr_update["config-status"] = "terminating"
1417
1418 if nsr_lcm and nsr_lcm.get("VCA"):
1419 try:
1420 step = "Scheduling configuration charms removing"
1421 db_nsr_update["detailed-status"] = "Deleting charms"
1422 self.logger.debug(logging_text + step)
1423 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1424 for application_name, deploy_info in nsr_lcm["VCA"].items():
1425 if deploy_info: # TODO it would be desirable having a and deploy_info.get("deployed"):
1426 task = asyncio.ensure_future(
1427 self.n2vc.RemoveCharms(
1428 deploy_info['model'],
1429 application_name,
1430 # self.n2vc_callback,
1431 # db_nsr,
1432 # db_nslcmop,
1433 )
1434 )
1435 vca_task_list.append(task)
1436 vca_task_dict[application_name] = task
1437 # task.add_done_callback(functools.partial(self.n2vc_callback, deploy_info['model'],
1438 # deploy_info['application'], None, db_nsr,
1439 # db_nslcmop, vnf_index))
1440 self.lcm_ns_tasks[nsr_id][nslcmop_id]["delete_charm:" + application_name] = task
1441 except Exception as e:
1442 self.logger.debug(logging_text + "Failed while deleting charms: {}".format(e))
1443
1444 # remove from RO
1445 RO_fail = False
1446 RO = ROclient.ROClient(self.loop, **self.ro_config)
1447
1448 # Delete ns
1449 RO_nsr_id = RO_delete_action = None
1450 if nsr_lcm and nsr_lcm.get("RO"):
1451 RO_nsr_id = nsr_lcm["RO"].get("nsr_id")
1452 RO_delete_action = nsr_lcm["RO"].get("nsr_delete_action_id")
1453 try:
1454 if RO_nsr_id:
1455 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] = "Deleting ns at RO"
1456 self.logger.debug(logging_text + step)
1457 desc = await RO.delete("ns", RO_nsr_id)
1458 RO_delete_action = desc["action_id"]
1459 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = RO_delete_action
1460 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
1461 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
1462 if RO_delete_action:
1463 # wait until NS is deleted from VIM
1464 step = detailed_status = "Waiting ns deleted from VIM. RO_id={}".format(RO_nsr_id)
1465 detailed_status_old = None
1466 self.logger.debug(logging_text + step)
1467
1468 delete_timeout = 20 * 60 # 20 minutes
1469 while delete_timeout > 0:
1470 desc = await RO.show("ns", item_id_name=RO_nsr_id, extra_item="action",
1471 extra_item_id=RO_delete_action)
1472 ns_status, ns_status_info = RO.check_action_status(desc)
1473 if ns_status == "ERROR":
1474 raise ROclient.ROClientException(ns_status_info)
1475 elif ns_status == "BUILD":
1476 detailed_status = step + "; {}".format(ns_status_info)
1477 elif ns_status == "ACTIVE":
1478 break
1479 else:
1480 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
1481 await asyncio.sleep(5, loop=self.loop)
1482 delete_timeout -= 5
1483 if detailed_status != detailed_status_old:
1484 detailed_status_old = db_nslcmop_update["detailed-status"] = detailed_status
1485 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1486 else: # delete_timeout <= 0:
1487 raise ROclient.ROClientException("Timeout waiting ns deleted from VIM")
1488
1489 except ROclient.ROClientException as e:
1490 if e.http_code == 404: # not found
1491 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
1492 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
1493 self.logger.debug(logging_text + "RO_ns_id={} already deleted".format(RO_nsr_id))
1494 elif e.http_code == 409: # conflict
1495 failed_detail.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id, e))
1496 self.logger.debug(logging_text + failed_detail[-1])
1497 RO_fail = True
1498 else:
1499 failed_detail.append("RO_ns_id={} delete error: {}".format(RO_nsr_id, e))
1500 self.logger.error(logging_text + failed_detail[-1])
1501 RO_fail = True
1502
1503 # Delete nsd
1504 if not RO_fail and nsr_lcm and nsr_lcm.get("RO") and nsr_lcm["RO"].get("nsd_id"):
1505 RO_nsd_id = nsr_lcm["RO"]["nsd_id"]
1506 try:
1507 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
1508 "Deleting nsd at RO"
1509 await RO.delete("nsd", RO_nsd_id)
1510 self.logger.debug(logging_text + "RO_nsd_id={} deleted".format(RO_nsd_id))
1511 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
1512 except ROclient.ROClientException as e:
1513 if e.http_code == 404: # not found
1514 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
1515 self.logger.debug(logging_text + "RO_nsd_id={} already deleted".format(RO_nsd_id))
1516 elif e.http_code == 409: # conflict
1517 failed_detail.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id, e))
1518 self.logger.debug(logging_text + failed_detail[-1])
1519 RO_fail = True
1520 else:
1521 failed_detail.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id, e))
1522 self.logger.error(logging_text + failed_detail[-1])
1523 RO_fail = True
1524
1525 if not RO_fail and nsr_lcm and nsr_lcm.get("RO") and nsr_lcm["RO"].get("vnfd_id"):
1526 for vnf_id, RO_vnfd_id in nsr_lcm["RO"]["vnfd_id"].items():
1527 if not RO_vnfd_id:
1528 continue
1529 try:
1530 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
1531 "Deleting vnfd={} at RO".format(vnf_id)
1532 await RO.delete("vnfd", RO_vnfd_id)
1533 self.logger.debug(logging_text + "RO_vnfd_id={} deleted".format(RO_vnfd_id))
1534 db_nsr_update["_admin.deployed.RO.vnfd_id.{}".format(vnf_id)] = None
1535 except ROclient.ROClientException as e:
1536 if e.http_code == 404: # not found
1537 db_nsr_update["_admin.deployed.RO.vnfd_id.{}".format(vnf_id)] = None
1538 self.logger.debug(logging_text + "RO_vnfd_id={} already deleted ".format(RO_vnfd_id))
1539 elif e.http_code == 409: # conflict
1540 failed_detail.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id, e))
1541 self.logger.debug(logging_text + failed_detail[-1])
1542 else:
1543 failed_detail.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id, e))
1544 self.logger.error(logging_text + failed_detail[-1])
1545
1546 if vca_task_list:
1547 db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
1548 "Waiting for deletion of configuration charms"
1549 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1550 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1551 await asyncio.wait(vca_task_list, timeout=300)
1552 for application_name, task in vca_task_dict.items():
1553 if task.cancelled():
1554 failed_detail.append("VCA[{}] Deletion has been cancelled".format(application_name))
1555 elif task.done():
1556 exc = task.exception()
1557 if exc:
1558 failed_detail.append("VCA[{}] Deletion exception: {}".format(application_name, exc))
1559 else:
1560 db_nsr_update["_admin.deployed.VCA.{}".format(application_name)] = None
1561 else: # timeout
1562 # TODO Should it be cancelled?!!
1563 task.cancel()
1564 failed_detail.append("VCA[{}] Deletion timeout".format(application_name))
1565
1566 if failed_detail:
1567 self.logger.error(logging_text + " ;".join(failed_detail))
1568 db_nsr_update["operational-status"] = "failed"
1569 db_nsr_update["detailed-status"] = "Deletion errors " + "; ".join(failed_detail)
1570 db_nslcmop_update["detailed-status"] = "; ".join(failed_detail)
1571 db_nslcmop_update["operationState"] = "FAILED"
1572 db_nslcmop_update["statusEnteredTime"] = time()
1573 elif db_nslcmop["operationParams"].get("autoremove"):
1574 self.db.del_one("nsrs", {"_id": nsr_id})
1575 db_nsr_update.clear()
1576 self.db.del_list("nslcmops", {"nsInstanceId": nsr_id})
1577 db_nslcmop_update.clear()
1578 self.db.del_list("vnfrs", {"nsr-id-ref": nsr_id})
1579 self.logger.debug(logging_text + "Delete from database")
1580 else:
1581 db_nsr_update["operational-status"] = "terminated"
1582 db_nsr_update["detailed-status"] = "Done"
1583 db_nsr_update["_admin.nsState"] = "NOT_INSTANTIATED"
1584 db_nslcmop_update["detailed-status"] = "Done"
1585 db_nslcmop_update["operationState"] = "COMPLETED"
1586 db_nslcmop_update["statusEnteredTime"] = time()
1587 try:
1588 await self.msg.aiowrite("ns", "terminated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
1589 except Exception as e:
1590 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1591 self.logger.debug(logging_text + "Exit")
1592
1593 except (ROclient.ROClientException, DbException) as e:
1594 self.logger.error(logging_text + "Exit Exception {}".format(e))
1595 exc = e
1596 except asyncio.CancelledError:
1597 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1598 exc = "Operation was cancelled"
1599 except Exception as e:
1600 exc = traceback.format_exc()
1601 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
1602 finally:
1603 if exc and db_nslcmop:
1604 db_nslcmop_update = {
1605 "detailed-status": "FAILED {}: {}".format(step, exc),
1606 "operationState": "FAILED",
1607 "statusEnteredTime": time(),
1608 }
1609 if db_nslcmop_update:
1610 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1611 if db_nsr_update:
1612 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1613 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_terminate")
1614
1615 async def _ns_execute_primitive(self, db_deployed, nsr_name, member_vnf_index, vdu_id, primitive, primitive_params):
1616
1617 vdu_id_text = "vnfd"
1618 if vdu_id:
1619 vdu_id_text = vdu_id
1620 application_name = self.n2vc.FormatApplicationName(
1621 nsr_name,
1622 member_vnf_index,
1623 vdu_id_text
1624 )
1625 vca_deployed = db_deployed["VCA"].get(application_name)
1626 if not vca_deployed:
1627 raise LcmException("charm for member_vnf_index={} vdu_id={} is not deployed".format(member_vnf_index,
1628 vdu_id))
1629 model_name = vca_deployed.get("model")
1630 application_name = vca_deployed.get("application")
1631 if not model_name or not application_name:
1632 raise LcmException("charm for member_vnf_index={} is not properly deployed".format(member_vnf_index))
1633 if vca_deployed["operational-status"] != "active":
1634 raise LcmException("charm for member_vnf_index={} operational_status={} not 'active'".format(
1635 member_vnf_index, vca_deployed["operational-status"]))
1636 callback = None # self.n2vc_callback
1637 callback_args = () # [db_nsr, db_nslcmop, member_vnf_index, None]
1638 await self.n2vc.login()
1639 task = asyncio.ensure_future(
1640 self.n2vc.ExecutePrimitive(
1641 model_name,
1642 application_name,
1643 primitive, callback,
1644 *callback_args,
1645 **primitive_params
1646 )
1647 )
1648 # task.add_done_callback(functools.partial(self.n2vc_callback, model_name, application_name, None,
1649 # db_nsr, db_nslcmop, member_vnf_index))
1650 # self.lcm_ns_tasks[nsr_id][nslcmop_id]["action: " + primitive] = task
1651 # wait until completed with timeout
1652 await asyncio.wait((task,), timeout=600)
1653
1654 result = "FAILED" # by default
1655 result_detail = ""
1656 if task.cancelled():
1657 result_detail = "Task has been cancelled"
1658 elif task.done():
1659 exc = task.exception()
1660 if exc:
1661 result_detail = str(exc)
1662 else:
1663 # TODO revise with Adam if action is finished and ok when task is done or callback is needed
1664 result = "COMPLETED"
1665 result_detail = "Done"
1666 else: # timeout
1667 # TODO Should it be cancelled?!!
1668 task.cancel()
1669 result_detail = "timeout"
1670 return result, result_detail
1671
1672 async def ns_action(self, nsr_id, nslcmop_id):
1673 logging_text = "Task ns={} action={} ".format(nsr_id, nslcmop_id)
1674 self.logger.debug(logging_text + "Enter")
1675 # get all needed from database
1676 db_nsr = None
1677 db_nslcmop = None
1678 db_nslcmop_update = None
1679 exc = None
1680 try:
1681 step = "Getting information from database"
1682 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
1683 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1684 nsr_lcm = db_nsr["_admin"].get("deployed")
1685 nsr_name = db_nsr["name"]
1686 vnf_index = db_nslcmop["operationParams"]["member_vnf_index"]
1687 vdu_id = db_nslcmop["operationParams"].get("vdu_id")
1688
1689 # TODO check if ns is in a proper status
1690 primitive = db_nslcmop["operationParams"]["primitive"]
1691 primitive_params = db_nslcmop["operationParams"]["primitive_params"]
1692 result, result_detail = await self._ns_execute_primitive(nsr_lcm, nsr_name, vnf_index, vdu_id, primitive,
1693 primitive_params)
1694 db_nslcmop_update = {
1695 "detailed-status": result_detail,
1696 "operationState": result,
1697 "statusEnteredTime": time()
1698 }
1699 self.logger.debug(logging_text + " task Done with result {} {}".format(result, result_detail))
1700 return # database update is called inside finally
1701
1702 except (DbException, LcmException) as e:
1703 self.logger.error(logging_text + "Exit Exception {}".format(e))
1704 exc = e
1705 except asyncio.CancelledError:
1706 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1707 exc = "Operation was cancelled"
1708 except Exception as e:
1709 exc = traceback.format_exc()
1710 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
1711 finally:
1712 if exc and db_nslcmop:
1713 db_nslcmop_update = {
1714 "detailed-status": "FAILED {}: {}".format(step, exc),
1715 "operationState": "FAILED",
1716 "statusEnteredTime": time(),
1717 }
1718 if db_nslcmop_update:
1719 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1720 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_action")
1721
1722 async def ns_scale(self, nsr_id, nslcmop_id):
1723 logging_text = "Task ns={} scale={} ".format(nsr_id, nslcmop_id)
1724 self.logger.debug(logging_text + "Enter")
1725 # get all needed from database
1726 db_nsr = None
1727 db_nslcmop = None
1728 db_nslcmop_update = {}
1729 db_nsr_update = {}
1730 exc = None
1731 try:
1732 step = "Getting nslcmop from database"
1733 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
1734 step = "Getting nsr from database"
1735 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1736 step = "Parsing scaling parameters"
1737 db_nsr_update["operational-status"] = "scaling"
1738 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1739 nsr_lcm = db_nsr["_admin"].get("deployed")
1740 RO_nsr_id = nsr_lcm["RO"]["nsr_id"]
1741 vnf_index = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
1742 scaling_group = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1743 scaling_type = db_nslcmop["operationParams"]["scaleVnfData"]["scaleVnfType"]
1744 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
1745
1746 step = "Getting vnfr from database"
1747 db_vnfr = self.db.get_one("vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id})
1748 step = "Getting vnfd from database"
1749 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
1750 step = "Getting scaling-group-descriptor"
1751 for scaling_descriptor in db_vnfd["scaling-group-descriptor"]:
1752 if scaling_descriptor["name"] == scaling_group:
1753 break
1754 else:
1755 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
1756 "at vnfd:scaling-group-descriptor".format(scaling_group))
1757 # cooldown_time = 0
1758 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
1759 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
1760 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
1761 # break
1762
1763 # TODO check if ns is in a proper status
1764 step = "Sending scale order to RO"
1765 nb_scale_op = 0
1766 if not db_nsr["_admin"].get("scaling-group"):
1767 self.update_db_2("nsrs", nsr_id, {"_admin.scaling-group": [{"name": scaling_group, "nb-scale-op": 0}]})
1768 admin_scale_index = 0
1769 else:
1770 for admin_scale_index, admin_scale_info in enumerate(db_nsr["_admin"]["scaling-group"]):
1771 if admin_scale_info["name"] == scaling_group:
1772 nb_scale_op = admin_scale_info.get("nb-scale-op", 0)
1773 break
1774 RO_scaling_info = []
1775 vdu_scaling_info = {"scaling_group_name": scaling_group, "vdu": []}
1776 if scaling_type == "SCALE_OUT":
1777 # count if max-instance-count is reached
1778 if "max-instance-count" in scaling_descriptor and scaling_descriptor["max-instance-count"] is not None:
1779 max_instance_count = int(scaling_descriptor["max-instance-count"])
1780 if nb_scale_op >= max_instance_count:
1781 raise LcmException("reached the limit of {} (max-instance-count) scaling-out operations for the"
1782 " scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group))
1783 nb_scale_op = nb_scale_op + 1
1784 vdu_scaling_info["scaling_direction"] = "OUT"
1785 vdu_scaling_info["vdu-create"] = {}
1786 for vdu_scale_info in scaling_descriptor["vdu"]:
1787 RO_scaling_info.append({"osm_vdu_id": vdu_scale_info["vdu-id-ref"], "member-vnf-index": vnf_index,
1788 "type": "create", "count": vdu_scale_info.get("count", 1)})
1789 vdu_scaling_info["vdu-create"][vdu_scale_info["vdu-id-ref"]] = vdu_scale_info.get("count", 1)
1790 elif scaling_type == "SCALE_IN":
1791 # count if min-instance-count is reached
1792 if "min-instance-count" in scaling_descriptor and scaling_descriptor["min-instance-count"] is not None:
1793 min_instance_count = int(scaling_descriptor["min-instance-count"])
1794 if nb_scale_op <= min_instance_count:
1795 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
1796 "scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group))
1797 nb_scale_op = nb_scale_op - 1
1798 vdu_scaling_info["scaling_direction"] = "IN"
1799 vdu_scaling_info["vdu-delete"] = {}
1800 for vdu_scale_info in scaling_descriptor["vdu"]:
1801 RO_scaling_info.append({"osm_vdu_id": vdu_scale_info["vdu-id-ref"], "member-vnf-index": vnf_index,
1802 "type": "delete", "count": vdu_scale_info.get("count", 1)})
1803 vdu_scaling_info["vdu-delete"][vdu_scale_info["vdu-id-ref"]] = vdu_scale_info.get("count", 1)
1804
1805 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
1806 if vdu_scaling_info["scaling_direction"] == "IN":
1807 for vdur in reversed(db_vnfr["vdur"]):
1808 if vdu_scaling_info["vdu-delete"].get(vdur["vdu-id-ref"]):
1809 vdu_scaling_info["vdu-delete"][vdur["vdu-id-ref"]] -= 1
1810 vdu_scaling_info["vdu"].append({
1811 "name": vdur["name"],
1812 "vdu_id": vdur["vdu-id-ref"],
1813 "interface": []
1814 })
1815 for interface in vdur["interfaces"]:
1816 vdu_scaling_info["vdu"][-1]["interface"].append({
1817 "name": interface["name"],
1818 "ip_address": interface["ip-address"],
1819 "mac_address": interface.get("mac-address"),
1820 })
1821 del vdu_scaling_info["vdu-delete"]
1822
1823 # execute primitive service PRE-SCALING
1824 step = "Executing pre-scale vnf-config-primitive"
1825 if scaling_descriptor.get("scaling-config-action"):
1826 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
1827 if scaling_config_action.get("trigger") and scaling_config_action["trigger"] == "pre-scale-in" \
1828 and scaling_type == "SCALE_IN":
1829 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
1830 step = db_nslcmop_update["detailed-status"] = \
1831 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive)
1832 # look for primitive
1833 primitive_params = {}
1834 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
1835 if config_primitive["name"] == vnf_config_primitive:
1836 for parameter in config_primitive.get("parameter", ()):
1837 if 'default-value' in parameter and \
1838 parameter['default-value'] == "<VDU_SCALE_INFO>":
1839 primitive_params[parameter["name"]] = yaml.safe_dump(vdu_scaling_info,
1840 default_flow_style=True,
1841 width=256)
1842 break
1843 else:
1844 raise LcmException(
1845 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
1846 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-cnfiguration:config-"
1847 "primitive".format(scaling_group, config_primitive))
1848 result, result_detail = await self._ns_execute_primitive(nsr_lcm, vnf_index,
1849 vnf_config_primitive, primitive_params)
1850 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
1851 vnf_config_primitive, result, result_detail))
1852 if result == "FAILED":
1853 raise LcmException(result_detail)
1854
1855 if RO_scaling_info:
1856 RO = ROclient.ROClient(self.loop, **self.ro_config)
1857 RO_desc = await RO.create_action("ns", RO_nsr_id, {"vdu-scaling": RO_scaling_info})
1858 db_nsr_update["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index)] = nb_scale_op
1859 db_nsr_update["_admin.scaling-group.{}.time".format(admin_scale_index)] = time()
1860 # TODO mark db_nsr_update as scaling
1861 # wait until ready
1862 RO_nslcmop_id = RO_desc["instance_action_id"]
1863 db_nslcmop_update["_admin.deploy.RO"] = RO_nslcmop_id
1864
1865 RO_task_done = False
1866 step = detailed_status = "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id)
1867 detailed_status_old = None
1868 self.logger.debug(logging_text + step)
1869
1870 deployment_timeout = 1 * 3600 # One hours
1871 while deployment_timeout > 0:
1872 if not RO_task_done:
1873 desc = await RO.show("ns", item_id_name=RO_nsr_id, extra_item="action",
1874 extra_item_id=RO_nslcmop_id)
1875 ns_status, ns_status_info = RO.check_action_status(desc)
1876 if ns_status == "ERROR":
1877 raise ROclient.ROClientException(ns_status_info)
1878 elif ns_status == "BUILD":
1879 detailed_status = step + "; {}".format(ns_status_info)
1880 elif ns_status == "ACTIVE":
1881 RO_task_done = True
1882 step = detailed_status = "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id)
1883 self.logger.debug(logging_text + step)
1884 else:
1885 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
1886 else:
1887 desc = await RO.show("ns", RO_nsr_id)
1888 ns_status, ns_status_info = RO.check_ns_status(desc)
1889 if ns_status == "ERROR":
1890 raise ROclient.ROClientException(ns_status_info)
1891 elif ns_status == "BUILD":
1892 detailed_status = step + "; {}".format(ns_status_info)
1893 elif ns_status == "ACTIVE":
1894 step = detailed_status = "Waiting for management IP address reported by the VIM"
1895 try:
1896 desc = await RO.show("ns", RO_nsr_id)
1897 nsr_lcm["nsr_ip"] = RO.get_ns_vnf_info(desc)
1898 break
1899 except ROclient.ROClientException as e:
1900 if e.http_code != 409: # IP address is not ready return code is 409 CONFLICT
1901 raise e
1902 else:
1903 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
1904 if detailed_status != detailed_status_old:
1905 detailed_status_old = db_nslcmop_update["detailed-status"] = detailed_status
1906 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1907
1908 await asyncio.sleep(5, loop=self.loop)
1909 deployment_timeout -= 5
1910 if deployment_timeout <= 0:
1911 raise ROclient.ROClientException("Timeout waiting ns to be ready")
1912
1913 step = "Updating VNFRs"
1914 self.ns_update_vnfr({db_vnfr["member-vnf-index-ref"]: db_vnfr}, desc)
1915
1916 # update VDU_SCALING_INFO with the obtained ip_addresses
1917 if vdu_scaling_info["scaling_direction"] == "OUT":
1918 for vdur in reversed(db_vnfr["vdur"]):
1919 if vdu_scaling_info["vdu-create"].get(vdur["vdu-id-ref"]):
1920 vdu_scaling_info["vdu-create"][vdur["vdu-id-ref"]] -= 1
1921 vdu_scaling_info["vdu"].append({
1922 "name": vdur["name"],
1923 "vdu_id": vdur["vdu-id-ref"],
1924 "interface": []
1925 })
1926 for interface in vdur["interfaces"]:
1927 vdu_scaling_info["vdu"][-1]["interface"].append({
1928 "name": interface["name"],
1929 "ip_address": interface["ip-address"],
1930 "mac_address": interface.get("mac-address"),
1931 })
1932 del vdu_scaling_info["vdu-create"]
1933
1934 if db_nsr_update:
1935 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1936
1937 # execute primitive service POST-SCALING
1938 step = "Executing post-scale vnf-config-primitive"
1939 if scaling_descriptor.get("scaling-config-action"):
1940 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
1941 if scaling_config_action.get("trigger") and scaling_config_action["trigger"] == "post-scale-out" \
1942 and scaling_type == "SCALE_OUT":
1943 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
1944 step = db_nslcmop_update["detailed-status"] = \
1945 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive)
1946 # look for primitive
1947 primitive_params = {}
1948 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
1949 if config_primitive["name"] == vnf_config_primitive:
1950 for parameter in config_primitive.get("parameter", ()):
1951 if 'default-value' in parameter and \
1952 parameter['default-value'] == "<VDU_SCALE_INFO>":
1953 primitive_params[parameter["name"]] = yaml.safe_dump(vdu_scaling_info,
1954 default_flow_style=True,
1955 width=256)
1956 break
1957 else:
1958 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
1959 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
1960 "match any vnf-cnfiguration:config-primitive".format(scaling_group,
1961 config_primitive))
1962 result, result_detail = await self._ns_execute_primitive(nsr_lcm, vnf_index,
1963 vnf_config_primitive, primitive_params)
1964 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
1965 vnf_config_primitive, result, result_detail))
1966 if result == "FAILED":
1967 raise LcmException(result_detail)
1968
1969 db_nslcmop_update["operationState"] = "COMPLETED"
1970 db_nslcmop_update["statusEnteredTime"] = time()
1971 db_nslcmop_update["detailed-status"] = "done"
1972 db_nsr_update["detailed-status"] = "done"
1973 db_nsr_update["operational-status"] = "running"
1974 try:
1975 await self.msg.aiowrite("ns", "scaled", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
1976 # if cooldown_time:
1977 # await asyncio.sleep(cooldown_time)
1978 # await self.msg.aiowrite("ns", "scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
1979 except Exception as e:
1980 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1981 self.logger.debug(logging_text + "Exit Ok")
1982 return
1983 except (ROclient.ROClientException, DbException, LcmException) as e:
1984 self.logger.error(logging_text + "Exit Exception {}".format(e))
1985 exc = e
1986 except asyncio.CancelledError:
1987 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1988 exc = "Operation was cancelled"
1989 except Exception as e:
1990 exc = traceback.format_exc()
1991 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
1992 finally:
1993 if exc:
1994 if db_nslcmop:
1995 db_nslcmop_update = {
1996 "detailed-status": "FAILED {}: {}".format(step, exc),
1997 "operationState": "FAILED",
1998 "statusEnteredTime": time(),
1999 }
2000 if db_nsr:
2001 db_nsr_update["operational-status"] = "FAILED {}: {}".format(step, exc),
2002 db_nsr_update["detailed-status"] = "failed"
2003 if db_nslcmop_update:
2004 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
2005 if db_nsr_update:
2006 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2007 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_scale")
2008
2009 async def test(self, param=None):
2010 self.logger.debug("Starting/Ending test task: {}".format(param))
2011
2012 async def kafka_ping(self):
2013 self.logger.debug("Task kafka_ping Enter")
2014 consecutive_errors = 0
2015 first_start = True
2016 kafka_has_received = False
2017 self.pings_not_received = 1
2018 while True:
2019 try:
2020 await self.msg.aiowrite("admin", "ping", {"from": "lcm", "to": "lcm"}, self.loop)
2021 # time between pings are low when it is not received and at starting
2022 wait_time = 5 if not kafka_has_received else 120
2023 if not self.pings_not_received:
2024 kafka_has_received = True
2025 self.pings_not_received += 1
2026 await asyncio.sleep(wait_time, loop=self.loop)
2027 if self.pings_not_received > 10:
2028 raise LcmException("It is not receiving pings from Kafka bus")
2029 consecutive_errors = 0
2030 first_start = False
2031 except LcmException:
2032 raise
2033 except Exception as e:
2034 # if not first_start is the first time after starting. So leave more time and wait
2035 # to allow kafka starts
2036 if consecutive_errors == 8 if not first_start else 30:
2037 self.logger.error("Task kafka_read task exit error too many errors. Exception: {}".format(e))
2038 raise
2039 consecutive_errors += 1
2040 self.logger.error("Task kafka_read retrying after Exception {}".format(e))
2041 wait_time = 1 if not first_start else 5
2042 await asyncio.sleep(wait_time, loop=self.loop)
2043
2044 async def kafka_read(self):
2045 self.logger.debug("Task kafka_read Enter")
2046 order_id = 1
2047 # future = asyncio.Future()
2048 consecutive_errors = 0
2049 first_start = True
2050 while consecutive_errors < 10:
2051 try:
2052 topics = ("admin", "ns", "vim_account", "sdn")
2053 topic, command, params = await self.msg.aioread(topics, self.loop)
2054 if topic != "admin" and command != "ping":
2055 self.logger.debug("Task kafka_read receives {} {}: {}".format(topic, command, params))
2056 consecutive_errors = 0
2057 first_start = False
2058 order_id += 1
2059 if command == "exit":
2060 print("Bye!")
2061 break
2062 elif command.startswith("#"):
2063 continue
2064 elif command == "echo":
2065 # just for test
2066 print(params)
2067 sys.stdout.flush()
2068 continue
2069 elif command == "test":
2070 asyncio.Task(self.test(params), loop=self.loop)
2071 continue
2072
2073 if topic == "admin":
2074 if command == "ping" and params["to"] == "lcm" and params["from"] == "lcm":
2075 self.pings_not_received = 0
2076 continue
2077 elif topic == "ns":
2078 if command == "instantiate":
2079 # self.logger.debug("Deploying NS {}".format(nsr_id))
2080 nslcmop = params
2081 nslcmop_id = nslcmop["_id"]
2082 nsr_id = nslcmop["nsInstanceId"]
2083 task = asyncio.ensure_future(self.ns_instantiate(nsr_id, nslcmop_id))
2084 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_instantiate", task)
2085 continue
2086 elif command == "terminate":
2087 # self.logger.debug("Deleting NS {}".format(nsr_id))
2088 nslcmop = params
2089 nslcmop_id = nslcmop["_id"]
2090 nsr_id = nslcmop["nsInstanceId"]
2091 self.lcm_tasks.cancel(topic, nsr_id)
2092 task = asyncio.ensure_future(self.ns_terminate(nsr_id, nslcmop_id))
2093 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_terminate", task)
2094 continue
2095 elif command == "action":
2096 # self.logger.debug("Update NS {}".format(nsr_id))
2097 nslcmop = params
2098 nslcmop_id = nslcmop["_id"]
2099 nsr_id = nslcmop["nsInstanceId"]
2100 task = asyncio.ensure_future(self.ns_action(nsr_id, nslcmop_id))
2101 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_action", task)
2102 continue
2103 elif command == "scale":
2104 # self.logger.debug("Update NS {}".format(nsr_id))
2105 nslcmop = params
2106 nslcmop_id = nslcmop["_id"]
2107 nsr_id = nslcmop["nsInstanceId"]
2108 task = asyncio.ensure_future(self.ns_scale(nsr_id, nslcmop_id))
2109 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_scale", task)
2110 continue
2111 elif command == "show":
2112 try:
2113 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2114 print("nsr:\n _id={}\n operational-status: {}\n config-status: {}"
2115 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
2116 "".format(nsr_id, db_nsr["operational-status"], db_nsr["config-status"],
2117 db_nsr["detailed-status"],
2118 db_nsr["_admin"]["deployed"], self.lcm_ns_tasks.get(nsr_id)))
2119 except Exception as e:
2120 print("nsr {} not found: {}".format(nsr_id, e))
2121 sys.stdout.flush()
2122 continue
2123 elif command == "deleted":
2124 continue # TODO cleaning of task just in case should be done
2125 elif command in ("terminated", "instantiated", "scaled", "actioned"): # "scaled-cooldown-time"
2126 continue
2127 elif topic == "vim_account":
2128 vim_id = params["_id"]
2129 if command == "create":
2130 task = asyncio.ensure_future(self.vim_create(params, order_id))
2131 self.lcm_tasks.register("vim_account", vim_id, order_id, "vim_create", task)
2132 continue
2133 elif command == "delete":
2134 self.lcm_tasks.cancel(topic, vim_id)
2135 task = asyncio.ensure_future(self.vim_delete(vim_id, order_id))
2136 self.lcm_tasks.register("vim_account", vim_id, order_id, "vim_delete", task)
2137 continue
2138 elif command == "show":
2139 print("not implemented show with vim_account")
2140 sys.stdout.flush()
2141 continue
2142 elif command == "edit":
2143 task = asyncio.ensure_future(self.vim_edit(params, order_id))
2144 self.lcm_tasks.register("vim_account", vim_id, order_id, "vim_edit", task)
2145 continue
2146 elif topic == "sdn":
2147 _sdn_id = params["_id"]
2148 if command == "create":
2149 task = asyncio.ensure_future(self.sdn_create(params, order_id))
2150 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_create", task)
2151 continue
2152 elif command == "delete":
2153 self.lcm_tasks.cancel(topic, _sdn_id)
2154 task = asyncio.ensure_future(self.sdn_delete(_sdn_id, order_id))
2155 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_delete", task)
2156 continue
2157 elif command == "edit":
2158 task = asyncio.ensure_future(self.sdn_edit(params, order_id))
2159 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_edit", task)
2160 continue
2161 self.logger.critical("unknown topic {} and command '{}'".format(topic, command))
2162 except Exception as e:
2163 # if not first_start is the first time after starting. So leave more time and wait
2164 # to allow kafka starts
2165 if consecutive_errors == 8 if not first_start else 30:
2166 self.logger.error("Task kafka_read task exit error too many errors. Exception: {}".format(e))
2167 raise
2168 consecutive_errors += 1
2169 self.logger.error("Task kafka_read retrying after Exception {}".format(e))
2170 wait_time = 2 if not first_start else 5
2171 await asyncio.sleep(wait_time, loop=self.loop)
2172
2173 # self.logger.debug("Task kafka_read terminating")
2174 self.logger.debug("Task kafka_read exit")
2175
2176 def start(self):
2177 self.loop = asyncio.get_event_loop()
2178
2179 # check RO version
2180 self.loop.run_until_complete(self.check_RO_version())
2181
2182 self.loop.run_until_complete(asyncio.gather(
2183 self.kafka_read(),
2184 self.kafka_ping()
2185 ))
2186 # TODO
2187 # self.logger.debug("Terminating cancelling creation tasks")
2188 # self.lcm_tasks.cancel("ALL", "create")
2189 # timeout = 200
2190 # while self.is_pending_tasks():
2191 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
2192 # await asyncio.sleep(2, loop=self.loop)
2193 # timeout -= 2
2194 # if not timeout:
2195 # self.lcm_tasks.cancel("ALL", "ALL")
2196 self.loop.close()
2197 self.loop = None
2198 if self.db:
2199 self.db.db_disconnect()
2200 if self.msg:
2201 self.msg.disconnect()
2202 if self.fs:
2203 self.fs.fs_disconnect()
2204
2205 def read_config_file(self, config_file):
2206 # TODO make a [ini] + yaml inside parser
2207 # the configparser library is not suitable, because it does not admit comments at the end of line,
2208 # and not parse integer or boolean
2209 try:
2210 with open(config_file) as f:
2211 conf = yaml.load(f)
2212 for k, v in environ.items():
2213 if not k.startswith("OSMLCM_"):
2214 continue
2215 k_items = k.lower().split("_")
2216 c = conf
2217 try:
2218 for k_item in k_items[1:-1]:
2219 if k_item in ("ro", "vca"):
2220 # put in capital letter
2221 k_item = k_item.upper()
2222 c = c[k_item]
2223 if k_items[-1] == "port":
2224 c[k_items[-1]] = int(v)
2225 else:
2226 c[k_items[-1]] = v
2227 except Exception as e:
2228 self.logger.warn("skipping environ '{}' on exception '{}'".format(k, e))
2229
2230 return conf
2231 except Exception as e:
2232 self.logger.critical("At config file '{}': {}".format(config_file, e))
2233 exit(1)
2234
2235
2236 def usage():
2237 print("""Usage: {} [options]
2238 -c|--config [configuration_file]: loads the configuration file (default: ./nbi.cfg)
2239 -h|--help: shows this help
2240 """.format(sys.argv[0]))
2241 # --log-socket-host HOST: send logs to this host")
2242 # --log-socket-port PORT: send logs using this port (default: 9022)")
2243
2244
2245 if __name__ == '__main__':
2246 try:
2247 # load parameters and configuration
2248 opts, args = getopt.getopt(sys.argv[1:], "hc:", ["config=", "help"])
2249 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
2250 config_file = None
2251 for o, a in opts:
2252 if o in ("-h", "--help"):
2253 usage()
2254 sys.exit()
2255 elif o in ("-c", "--config"):
2256 config_file = a
2257 # elif o == "--log-socket-port":
2258 # log_socket_port = a
2259 # elif o == "--log-socket-host":
2260 # log_socket_host = a
2261 # elif o == "--log-file":
2262 # log_file = a
2263 else:
2264 assert False, "Unhandled option"
2265 if config_file:
2266 if not path.isfile(config_file):
2267 print("configuration file '{}' that not exist".format(config_file), file=sys.stderr)
2268 exit(1)
2269 else:
2270 for config_file in (__file__[:__file__.rfind(".")] + ".cfg", "./lcm.cfg", "/etc/osm/lcm.cfg"):
2271 if path.isfile(config_file):
2272 break
2273 else:
2274 print("No configuration file 'nbi.cfg' found neither at local folder nor at /etc/osm/", file=sys.stderr)
2275 exit(1)
2276 lcm = Lcm(config_file)
2277 lcm.start()
2278 except (LcmException, getopt.GetoptError) as e:
2279 print(str(e), file=sys.stderr)
2280 # usage()
2281 exit(1)