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