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