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