2 # -*- coding: utf-8 -*-
7 import logging
.handlers
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
23 from collections
import OrderedDict
24 from copy
import deepcopy
25 from http
import HTTPStatus
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'
39 """utility for compare dot separate versions. Fills with zeros to proper number comparison"""
41 for point
in v
.split("."):
42 filled
.append(point
.zfill(8))
46 class LcmException(Exception):
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
61 self
.task_registry
= {
67 def register(self
, topic
, _id
, op_id
, task_name
, 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
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
}
82 self
.task_registry
[topic
][_id
][op_id
][task_name
] = task
83 # print("registering task", topic, _id, op_id, task_name, task)
85 def remove(self
, topic
, _id
, op_id
, task_name
=None):
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
94 if not self
.task_registry
[topic
].get(_id
) or not self
.task_registry
[topic
][_id
].get(op_id
):
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
]
107 def lookfor_related(self
, topic
, _id
, my_op_id
=None):
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
]):
114 if my_op_id
== op_id
:
115 my_op_id
= None # so that the next task is taken
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
)
122 return ", ".join(task_name_list
), task_list
124 def cancel(self
, topic
, _id
, target_op_id
=None, target_task_name
=None):
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
129 if not self
.task_registry
[topic
].get(_id
):
131 for op_id
in reversed(self
.task_registry
[topic
][_id
]):
132 if target_op_id
and target_op_id
!= op_id
:
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
:
140 # self.logger.debug("{} _id={} order_id={} task={} cancelled".format(topic, _id, op_id, task_name))
145 def __init__(self
, config_file
):
147 Init, Connect to database, filesystem storage, and messaging
148 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
155 self
.pings_not_received
= 1
157 # contains created tasks/futures to be able to cancel
158 self
.lcm_tasks
= TaskRegistry()
160 self
.logger
= logging
.getLogger('lcm')
162 config
= self
.read_config_file(config_file
)
165 "endpoint_url": "http://{}:{}/openmano".format(config
["RO"]["host"], config
["RO"]["port"]),
166 "tenant": config
.get("tenant", "osm"),
167 "logger_name": "lcm.ROclient",
171 self
.vca
= config
["VCA"] # TODO VCA
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
)
190 if config
["global"].get("loglevel"):
191 self
.logger
.setLevel(config
["global"]["loglevel"])
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
))
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'][''],
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
))
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"])
236 raise LcmException("Invalid configuration param '{}' at '[database]':'driver'".format(
237 config
["database"]["driver"]))
239 if config
["storage"]["driver"] == "local":
240 self
.fs
= fslocal
.FsLocal()
241 self
.fs
.fs_connect(config
["storage"])
243 raise LcmException("Invalid configuration param '{}' at '[storage]':'driver'".format(
244 config
["storage"]["driver"]))
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"])
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
))
259 async def check_RO_version(self
):
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
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
))
271 def update_db_2(self
, item
, _id
, _desc
):
273 Updates database with _desc information. Upon success _desc is cleared
282 self
.db
.set_one(item
, {"_id": _id
}, _desc
)
284 except DbException
as e
:
285 self
.logger
.error("Updating {} _id={} with '{}'. Error: {}".format(item
, _id
, _desc
, e
))
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")
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"]
305 raise LcmException("sdn-controller={} is not available. Not deployed at RO".format(
306 vim_content
["config"]["sdn-controller"]))
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)
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
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
)
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"]
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"
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
))
350 except (ROclient
.ROClientException
, DbException
) as e
:
351 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
353 except Exception as e
:
354 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
358 db_vim_update
["_admin.operationalState"] = "ERROR"
359 db_vim_update
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
361 self
.update_db_2("vim_accounts", vim_id
, db_vim_update
)
362 self
.lcm_tasks
.remove("vim_account", vim_id
, order_id
)
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")
373 step
= "Getting vim-id='{}' from db".format(vim_id
)
375 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_id
})
377 # look if previous tasks in process
378 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account", vim_id
, order_id
)
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)
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"]})
390 # look if previous tasks in process
391 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("sdn", db_sdn
["_id"])
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)
398 if db_sdn
.get("_admin") and db_sdn
["_admin"].get("deployed") and db_sdn
["_admin"]["deployed"].get(
400 RO_sdn_id
= db_sdn
["_admin"]["deployed"]["RO"]
402 raise LcmException("sdn-controller={} is not available. Not deployed at RO".format(
403 vim_content
["config"]["sdn-controller"]))
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)
419 vim_RO
["config"]["sdn-controller"] = RO_sdn_id
420 # TODO make a deep update of sdn-port-mapping
422 await RO
.edit("vim", RO_vim_id
, descriptor
=vim_RO
)
424 step
= "Editing vim-account at RO tenant"
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"):
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"
443 self
.logger
.debug(logging_text
+ "Exit Ok RO_vim_id={}".format(RO_vim_id
))
446 except (ROclient
.ROClientException
, DbException
) as e
:
447 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
449 except Exception as e
:
450 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
454 db_vim_update
["_admin.operationalState"] = "ERROR"
455 db_vim_update
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
457 self
.update_db_2("vim_accounts", vim_id
, db_vim_update
)
458 self
.lcm_tasks
.remove("vim_account", vim_id
, order_id
)
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")
466 step
= "Getting vim from db"
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"
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
))
481 step
= "Deleting vim from RO"
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
))
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")
496 except (ROclient
.ROClientException
, DbException
) as e
:
497 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
499 except Exception as e
:
500 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
503 self
.lcm_tasks
.remove("vim_account", vim_id
, order_id
)
505 db_vim_update
["_admin.operationalState"] = "ERROR"
506 db_vim_update
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
508 self
.update_db_2("vim_accounts", vim_id
, db_vim_update
)
509 self
.lcm_tasks
.remove("vim_account", vim_id
, order_id
)
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")
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
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
))
539 except (ROclient
.ROClientException
, DbException
) as e
:
540 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
542 except Exception as e
:
543 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
547 db_sdn_update
["_admin.operationalState"] = "ERROR"
548 db_sdn_update
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
550 self
.update_db_2("sdns", sdn_id
, db_sdn_update
)
551 self
.lcm_tasks
.remove("sdn", sdn_id
, order_id
)
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")
560 step
= "Getting sdn from db"
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)
574 await RO
.edit("sdn", RO_sdn_id
, descriptor
=sdn_RO
)
575 db_sdn_update
["_admin.operationalState"] = "ENABLED"
577 self
.logger
.debug(logging_text
+ "Exit Ok RO_sdn_id".format(RO_sdn_id
))
580 except (ROclient
.ROClientException
, DbException
) as e
:
581 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
583 except Exception as e
:
584 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
588 db_sdn
["_admin.operationalState"] = "ERROR"
589 db_sdn
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
591 self
.update_db_2("sdns", sdn_id
, db_sdn_update
)
592 self
.lcm_tasks
.remove("sdn", sdn_id
, order_id
)
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")
600 step
= "Getting sdn from db"
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"
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
))
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
))
621 except (ROclient
.ROClientException
, DbException
) as e
:
622 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
624 except Exception as e
:
625 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
629 db_sdn
["_admin.operationalState"] = "ERROR"
630 db_sdn
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
632 self
.update_db_2("sdns", sdn_id
, db_sdn_update
)
633 self
.lcm_tasks
.remove("sdn", sdn_id
, order_id
)
635 def vnfd2RO(self
, vnfd
, new_id
=None):
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
644 vnfd_RO
= deepcopy(vnfd
)
645 vnfd_RO
.pop("_id", None)
646 vnfd_RO
.pop("_admin", None)
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"]
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()
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)
670 except FsException
as e
:
671 raise LcmException("Error reading file at vnfd {}: {} ".format(vnfd
["_id"], e
))
676 def n2vc_callback(self
, model_name
, application_name
, status
, message
, n2vc_info
, task
=None):
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
690 :param message: detailed message error
691 :param n2vc_info dictionary with information shared with instantiate task. Contains:
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
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
,
710 vca_deployed
= deployed
.get(application_name
)
712 self
.logger
.error(logging_text
+ " Not present at nsr._admin.deployed.VCA")
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"
724 exc
= task
.exception()
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
)
732 self
.logger
.debug(logging_text
+ " task Done")
733 # task is Done, but callback is still ongoing. So ignore
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
)
744 self
.logger
.critical(logging_text
+ " Enter with bad parameters", exc_info
=True)
746 # wake up instantiate task
748 except Exception as e
:
749 self
.logger
.critical(logging_text
+ " Exception {}".format(e
), exc_info
=True)
751 def ns_params_2_RO(self
, ns_params
, nsd
, vnfd_dict
):
753 Creates a RO ns descriptor from OSM ns_instantite params
754 :param ns_params: OSM instantiate params
755 :return: The RO ns descriptor
759 def vim_account_2_RO(vim_account
):
760 if vim_account
in vim_2_RO
:
761 return vim_2_RO
[vim_account
]
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
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'])
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")
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"],
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"]]
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"]:
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"]:
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
)
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"]))
868 if not RO_vnf
["vdus"]:
870 if not RO_vnf
["networks"]:
871 del RO_vnf
["networks"]
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"]:
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
:
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
)
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"]:
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"]]
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"]))
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"]:
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"]))
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"]
923 cp_params
["member-vnf-index-ref"]: {
925 vdu_descriptor
["id"]: {
927 interface_descriptor
["name"]: RO_cp_params
933 deep_update(RO_ns_params
["vnfs"], RO_vnf_params
)
935 RO_ns_params
["networks"][vld_params
["name"]] = RO_vld
938 def ns_update_vnfr(self
, db_vnfrs
, nsr_desc_RO
):
940 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
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
:
949 db_vnfr
["ip-address"] = vnfr_update
["ip-address"] = vnf_RO
.get("ip_address")
951 for vdur_RO
in vnf_RO
.get("vms", ()):
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"),
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"),
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
)
974 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} at RO info".format(vnf_index
))
976 async def create_monitoring(self
, nsr_id
, vnf_member_index
, vnfd_desc
):
977 if not vnfd_desc
.get("scaling-group-descriptor"):
979 for scaling_group
in vnfd_desc
["scaling-group-descriptor"]:
980 scaling_policy_desc
= {}
983 "scaling_group_descriptor": {
984 "name": scaling_group
["name"],
985 "scaling_policy": scaling_policy_desc
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"),
998 if not scaling_criteria
.get("vnf-monitoring-param-ref"):
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
,
1010 scaling_policy_desc
["scaling_criteria"].append(scaling_criteria_desc
)
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"]))
1018 await self
.msg
.aiowrite("lcm_pm", "configure_scaling", scaling_desc
, self
.loop
)
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
1027 db_nslcmop_update
= {}
1028 nslcmop_operation_state
= None
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
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")
1041 nsr_name
= db_nsr
["name"] # TODO short-name??
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
})
1053 nsr_lcm
= db_nsr
["_admin"].get("deployed")
1055 nsr_lcm
= db_nsr
["_admin"]["deployed"] = {
1057 "RO": {"vnfd_id": {}, "nsd_id": None, "nsr_id": None, "nsr_status": "SCHEDULED"},
1061 db_nsr_update
["detailed-status"] = "creating"
1062 db_nsr_update
["operational-status"] = "init"
1064 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
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
1075 vnfd_list
= await RO
.get_list("vnfd", filter_by
={"osm_id": vnfd_id_RO
})
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"]))
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
)
1091 step
= db_nsr_update
["detailed-status"] = "Creating nsd={} at RO".format(nsd_id
)
1092 # self.logger.debug(logging_text + step)
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
})
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
))
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
)
1117 # if present use it unless in error status
1118 RO_nsr_id
= db_nsr
["_admin"].get("deployed", {}).get("RO", {}).get("nsr_id")
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
:
1127 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
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
1137 step
= db_nsr_update
["detailed-status"] = "Creating ns at RO"
1138 # self.logger.debug(logging_text + step)
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"])
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"])
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)
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
)
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"):
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")
1178 self
.update_db_2("vnfrs", vnfr
["_id"], vnfr_update
)
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
)
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"
1197 nsr_lcm
["nsr_ip"] = RO
.get_ns_vnf_info(desc
)
1199 except ROclient
.ROClientException
as e
:
1200 if e
.http_code
!= 409: # IP address is not ready return code is 409 CONFLICT
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")
1212 step
= "Updating VNFRs"
1213 self
.ns_update_vnfr(db_vnfrs
, desc
)
1215 db_nsr
["detailed-status"] = "Configuring vnfr"
1216 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1218 # The parameters we'll need to deploy a charm
1219 number_to_configure
= 0
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
1225 if not mgmt_ip_address
:
1226 raise LcmException("vnfd/vdu has not management ip address to configure it")
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!")
1234 # # await self.n2vc.login()
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"],
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
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"
1257 vdu_id_text
= vdu_id
1258 application_name
= self
.n2vc
.FormatApplicationName(
1263 if not nsr_lcm
.get("VCA"):
1265 nsr_lcm
["VCA"][application_name
] = db_nsr_update
["_admin.deployed.VCA.{}".format(application_name
)] = {
1266 "member-vnf-index": vnf_index
,
1268 "model": model_name
,
1269 "application": application_name
,
1270 "operational-status": "init",
1271 "detailed-status": "",
1274 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1276 self
.logger
.debug("Task create_ns={} Passing artifacts path '{}' for {}".format(nsr_id
, charm_path
,
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)
1298 task
.add_done_callback(functools
.partial(self
.n2vc_callback
, model_name
, application_name
, None, None,
1300 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "create_charm:" + application_name
, task
)
1302 step
= "Looking for needed vnfd to configure"
1303 self
.logger
.debug(logging_text
+ step
)
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
]
1310 # Check if this VNF has a charm configuration
1311 vnf_config
= vnfd
.get("vnf-configuration")
1313 if vnf_config
and vnf_config
.get("juju"):
1314 proxy_charm
= vnf_config
["juju"]["charm"]
1315 config_primitive
= None
1318 if 'initial-config-primitive' in vnf_config
:
1319 config_primitive
= vnf_config
['initial-config-primitive']
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
1328 # Deploy charms for each VDU that supports one.
1330 for vdu
in vnfd
['vdu']:
1331 vdu_config
= vdu
.get('vdu-configuration')
1333 config_primitive
= None
1335 if vdu_config
and vdu_config
.get("juju"):
1336 proxy_charm
= vdu_config
["juju"]["charm"]
1338 if 'initial-config-primitive' in vdu_config
:
1339 config_primitive
= vdu_config
['initial-config-primitive']
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
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
1357 # wait until all are configured.
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()
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
:
1372 status_map
[vca_status
] = 0
1373 status_map
[vca_status
] += 1
1375 if vca_status
!= "active":
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"]))
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
1395 cs
= "configuring: "
1397 for status
, num
in status_map
.items():
1398 cs
+= separator
+ "{}: {}".format(status
, num
)
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
1406 if not configuration_failed
:
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"
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"]])
1419 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
1420 self
.logger
.error(logging_text
+ "Exit Exception while '{}': {}".format(step
, 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
),
1432 db_nsr_update
["detailed-status"] = "ERROR {}: {}".format(step
, exc
)
1433 db_nsr_update
["operational-status"] = "failed"
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()
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
:
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
))
1449 self
.logger
.debug(logging_text
+ "Exit")
1450 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_instantiate")
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")
1458 failed_detail
= [] # annotates all failed error messages
1462 db_nslcmop_update
= {}
1463 nslcmop_operation_state
= None
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":
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"]
1478 db_nsr_update
["operational-status"] = "terminating"
1479 db_nsr_update
["config-status"] = "terminating"
1481 if nsr_lcm
and nsr_lcm
.get("VCA"):
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'],
1493 # self.n2vc_callback,
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
))
1509 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
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")
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
)
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":
1543 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
1544 await asyncio
.sleep(5, loop
=self
.loop
)
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")
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])
1562 failed_detail
.append("RO_ns_id={} delete error: {}".format(RO_nsr_id
, e
))
1563 self
.logger
.error(logging_text
+ failed_detail
[-1])
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"]
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])
1584 failed_detail
.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id
, e
))
1585 self
.logger
.error(logging_text
+ failed_detail
[-1])
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():
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])
1606 failed_detail
.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id
, e
))
1607 self
.logger
.error(logging_text
+ failed_detail
[-1])
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
))
1619 exc
= task
.exception()
1621 failed_detail
.append("VCA[{}] Deletion exception: {}".format(application_name
, exc
))
1623 db_nsr_update
["_admin.deployed.VCA.{}".format(application_name
)] = None
1625 # TODO Should it be cancelled?!!
1627 failed_detail
.append("VCA[{}] Deletion timeout".format(application_name
))
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")
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()
1652 except (ROclient
.ROClientException
, DbException
) as e
:
1653 self
.logger
.error(logging_text
+ "Exit Exception {}".format(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)
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
)
1669 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1670 if nslcmop_operation_state
:
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")
1679 async def _ns_execute_primitive(self
, db_deployed
, nsr_name
, member_vnf_index
, vdu_id
, primitive
, primitive_params
):
1681 vdu_id_text
= "vnfd"
1683 vdu_id_text
= vdu_id
1684 application_name
= self
.n2vc
.FormatApplicationName(
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
,
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(
1707 primitive
, callback
,
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)
1718 result
= "FAILED" # by default
1720 if task
.cancelled():
1721 result_detail
= "Task has been cancelled"
1723 exc
= task
.exception()
1725 result_detail
= str(exc
)
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"
1731 # TODO Should it be cancelled?!!
1733 result_detail
= "timeout"
1734 return result
, result_detail
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
1742 db_nslcmop_update
= {}
1743 nslcmop_operation_state
= None
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")
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
,
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
1765 except (DbException
, LcmException
) as e
:
1766 self
.logger
.error(logging_text
+ "Exit Exception {}".format(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)
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
:
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")
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
1797 db_nslcmop_update
= {}
1798 nslcmop_operation_state
= None
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")
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
:
1825 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
1826 "at vnfd:scaling-group-descriptor".format(scaling_group
))
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"):
1833 # TODO check if ns is in a proper status
1834 step
= "Sending scale order to RO"
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
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)
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)
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"],
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"),
1891 del vdu_scaling_info
["vdu-delete"]
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,
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
)
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
1932 RO_nslcmop_id
= RO_desc
["instance_action_id"]
1933 db_nslcmop_update
["_admin.deploy.RO"] = RO_nslcmop_id
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
)
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":
1952 step
= detailed_status
= "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id
)
1953 self
.logger
.debug(logging_text
+ step
)
1955 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
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"
1966 desc
= await RO
.show("ns", RO_nsr_id
)
1967 nsr_lcm
["nsr_ip"] = RO
.get_ns_vnf_info(desc
)
1969 except ROclient
.ROClientException
as e
:
1970 if e
.http_code
!= 409: # IP address is not ready return code is 409 CONFLICT
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
)
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")
1983 step
= "Updating VNFRs"
1984 self
.ns_update_vnfr({db_vnfr
["member-vnf-index-ref"]: db_vnfr
}, desc
)
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"],
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"),
2002 del vdu_scaling_info
["vdu-create"]
2005 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
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,
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
,
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
)
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"
2045 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
2046 self
.logger
.error(logging_text
+ "Exit Exception {}".format(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)
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()
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
)
2066 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2067 if nslcmop_operation_state
:
2069 await self
.msg
.aiowrite("ns", "scaled", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2070 "operationState": nslcmop_operation_state
})
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")
2079 async def test(self
, param
=None):
2080 self
.logger
.debug("Starting/Ending test task: {}".format(param
))
2082 async def kafka_ping(self
):
2083 self
.logger
.debug("Task kafka_ping Enter")
2084 consecutive_errors
= 0
2086 kafka_has_received
= False
2087 self
.pings_not_received
= 1
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
2101 except LcmException
:
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
))
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
)
2114 async def kafka_read(self
):
2115 self
.logger
.debug("Task kafka_read Enter")
2117 # future = asyncio.Future()
2118 consecutive_errors
= 0
2120 while consecutive_errors
< 10:
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
2129 if command
== "exit":
2132 elif command
.startswith("#"):
2134 elif command
== "echo":
2139 elif command
== "test":
2140 asyncio
.Task(self
.test(params
), loop
=self
.loop
)
2143 if topic
== "admin":
2144 if command
== "ping" and params
["to"] == "lcm" and params
["from"] == "lcm":
2145 self
.pings_not_received
= 0
2148 if command
== "instantiate":
2149 # self.logger.debug("Deploying NS {}".format(nsr_id))
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
)
2156 elif command
== "terminate":
2157 # self.logger.debug("Deleting NS {}".format(nsr_id))
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
)
2165 elif command
== "action":
2166 # self.logger.debug("Update NS {}".format(nsr_id))
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
)
2173 elif command
== "scale":
2174 # self.logger.debug("Update NS {}".format(nsr_id))
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
)
2181 elif command
== "show":
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
))
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"
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
)
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
)
2208 elif command
== "show":
2209 print("not implemented show with vim_account")
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
)
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
)
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
)
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
)
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
))
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
)
2243 # self.logger.debug("Task kafka_read terminating")
2244 self
.logger
.debug("Task kafka_read exit")
2247 self
.loop
= asyncio
.get_event_loop()
2250 self
.loop
.run_until_complete(self
.check_RO_version())
2252 self
.loop
.run_until_complete(asyncio
.gather(
2257 # self.logger.debug("Terminating cancelling creation tasks")
2258 # self.lcm_tasks.cancel("ALL", "create")
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)
2265 # self.lcm_tasks.cancel("ALL", "ALL")
2269 self
.db
.db_disconnect()
2271 self
.msg
.disconnect()
2273 self
.fs
.fs_disconnect()
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
2280 with
open(config_file
) as f
:
2282 for k
, v
in environ
.items():
2283 if not k
.startswith("OSMLCM_"):
2285 k_items
= k
.lower().split("_")
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()
2293 if k_items
[-1] == "port":
2294 c
[k_items
[-1]] = int(v
)
2297 except Exception as e
:
2298 self
.logger
.warn("skipping environ '{}' on exception '{}'".format(k
, e
))
2301 except Exception as e
:
2302 self
.logger
.critical("At config file '{}': {}".format(config_file
, e
))
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)")
2315 if __name__
== '__main__':
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="
2322 if o
in ("-h", "--help"):
2325 elif o
in ("-c", "--config"):
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":
2334 assert False, "Unhandled option"
2336 if not path
.isfile(config_file
):
2337 print("configuration file '{}' that not exist".format(config_file
), file=sys
.stderr
)
2340 for config_file
in (__file__
[:__file__
.rfind(".")] + ".cfg", "./lcm.cfg", "/etc/osm/lcm.cfg"):
2341 if path
.isfile(config_file
):
2344 print("No configuration file 'nbi.cfg' found neither at local folder nor at /etc/osm/", file=sys
.stderr
)
2346 lcm
= Lcm(config_file
)
2348 except (LcmException
, getopt
.GetoptError
) as e
:
2349 print(str(e
), file=sys
.stderr
)