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
15 from osm_common
import dbmongo
16 from osm_common
import fslocal
17 from osm_common
import msglocal
18 from osm_common
import msgkafka
19 from osm_common
.dbbase
import DbException
20 from osm_common
.fsbase
import FsException
21 from osm_common
.msgbase
import MsgException
22 from os
import environ
, path
23 from n2vc
.vnf
import N2VC
24 from n2vc
import version
as N2VC_version
26 from collections
import OrderedDict
27 from copy
import deepcopy
28 from http
import HTTPStatus
32 __author__
= "Alfonso Tierno"
33 min_RO_version
= [0, 5, 72]
36 class LcmException(Exception):
42 Implements a registry of task needed for later cancelation, look for related tasks that must be completed before
43 etc. It stores a four level dict
44 First level is the topic, ns, vim_account, sdn
45 Second level is the _id
46 Third level is the operation id
47 Fourth level is a descriptive name, the value is the task class
51 self
.task_registry
= {
57 def register(self
, topic
, _id
, op_id
, task_name
, task
):
60 :param topic: Can be "ns", "vim_account", "sdn"
61 :param _id: _id of the related item
62 :param op_id: id of the operation of the related item
63 :param task_name: Task descriptive name, as create, instantiate, terminate. Must be unique in this op_id
64 :param task: Task class
67 if _id
not in self
.task_registry
[topic
]:
68 self
.task_registry
[topic
][_id
] = OrderedDict()
69 if op_id
not in self
.task_registry
[topic
][_id
]:
70 self
.task_registry
[topic
][_id
][op_id
] = {task_name
: task
}
72 self
.task_registry
[topic
][_id
][op_id
][task_name
] = task
73 # print("registering task", topic, _id, op_id, task_name, task)
75 def remove(self
, topic
, _id
, op_id
, task_name
=None):
77 When task is ended, it should removed. It ignores missing tasks
78 :param topic: Can be "ns", "vim_account", "sdn"
79 :param _id: _id of the related item
80 :param op_id: id of the operation of the related item
81 :param task_name: Task descriptive name. If note it deletes all
84 if not self
.task_registry
[topic
].get(_id
) or not self
.task_registry
[topic
][_id
].get(op_id
):
87 # print("deleting tasks", topic, _id, op_id, self.task_registry[topic][_id][op_id])
88 del self
.task_registry
[topic
][_id
][op_id
]
89 elif task_name
in self
.task_registry
[topic
][_id
][op_id
]:
90 # print("deleting tasks", topic, _id, op_id, task_name, self.task_registry[topic][_id][op_id][task_name])
91 del self
.task_registry
[topic
][_id
][op_id
][task_name
]
92 if not self
.task_registry
[topic
][_id
][op_id
]:
93 del self
.task_registry
[topic
][_id
][op_id
]
94 if not self
.task_registry
[topic
][_id
]:
95 del self
.task_registry
[topic
][_id
]
97 def lookfor_related(self
, topic
, _id
, my_op_id
=None):
100 if _id
not in self
.task_registry
[topic
]:
101 return "", task_name_list
102 for op_id
in reversed(self
.task_registry
[topic
][_id
]):
104 if my_op_id
== op_id
:
105 my_op_id
= None # so that the next task is taken
108 for task_name
, task
in self
.task_registry
[topic
][_id
][op_id
].items():
109 task_list
.append(task
)
110 task_name_list
.append(task_name
)
112 return ", ".join(task_name_list
), task_list
114 def cancel(self
, topic
, _id
, target_op_id
=None, target_task_name
=None):
116 Cancel all active tasks of a concrete ns, vim_account, sdn identified for _id. If op_id is supplied only this is
117 cancelled, and the same with task_name
119 if not self
.task_registry
[topic
].get(_id
):
121 for op_id
in reversed(self
.task_registry
[topic
][_id
]):
122 if target_op_id
and target_op_id
!= op_id
:
124 for task_name
, task
in self
.task_registry
[topic
][_id
][op_id
].items():
125 if target_task_name
and target_task_name
!= task_name
:
127 result
= task
.cancel()
129 self
.logger
.debug("{} _id={} order_id={} task={} cancelled".format(topic
, _id
, op_id
, task_name
))
134 def __init__(self
, config_file
):
136 Init, Connect to database, filesystem storage, and messaging
137 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
144 self
.pings_not_received
= 1
146 # contains created tasks/futures to be able to cancel
147 self
.lcm_tasks
= TaskRegistry()
149 self
.logger
= logging
.getLogger('lcm')
151 config
= self
.read_config_file(config_file
)
154 "endpoint_url": "http://{}:{}/openmano".format(config
["RO"]["host"], config
["RO"]["port"]),
155 "tenant": config
.get("tenant", "osm"),
156 "logger_name": "lcm.ROclient",
160 self
.vca
= config
["VCA"] # TODO VCA
164 log_format_simple
= "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
165 log_formatter_simple
= logging
.Formatter(log_format_simple
, datefmt
='%Y-%m-%dT%H:%M:%S')
166 config
["database"]["logger_name"] = "lcm.db"
167 config
["storage"]["logger_name"] = "lcm.fs"
168 config
["message"]["logger_name"] = "lcm.msg"
169 if "logfile" in config
["global"]:
170 file_handler
= logging
.handlers
.RotatingFileHandler(config
["global"]["logfile"],
171 maxBytes
=100e6
, backupCount
=9, delay
=0)
172 file_handler
.setFormatter(log_formatter_simple
)
173 self
.logger
.addHandler(file_handler
)
175 str_handler
= logging
.StreamHandler()
176 str_handler
.setFormatter(log_formatter_simple
)
177 self
.logger
.addHandler(str_handler
)
179 if config
["global"].get("loglevel"):
180 self
.logger
.setLevel(config
["global"]["loglevel"])
182 # logging other modules
183 for k1
, logname
in {"message": "lcm.msg", "database": "lcm.db", "storage": "lcm.fs"}.items():
184 config
[k1
]["logger_name"] = logname
185 logger_module
= logging
.getLogger(logname
)
186 if "logfile" in config
[k1
]:
187 file_handler
= logging
.handlers
.RotatingFileHandler(config
[k1
]["logfile"],
188 maxBytes
=100e6
, backupCount
=9, delay
=0)
189 file_handler
.setFormatter(log_formatter_simple
)
190 logger_module
.addHandler(file_handler
)
191 if "loglevel" in config
[k1
]:
192 logger_module
.setLevel(config
[k1
]["loglevel"])
193 # self.logger.critical("starting osm/lcm version {} {}".format(lcm_version, lcm_version_date))
196 server
=config
['VCA']['host'],
197 port
=config
['VCA']['port'],
198 user
=config
['VCA']['user'],
199 secret
=config
['VCA']['secret'],
200 # TODO: This should point to the base folder where charms are stored,
201 # if there is a common one (like object storage). Otherwise, leave
202 # it unset and pass it via DeployCharms
203 # artifacts=config['VCA'][''],
206 # check version of N2VC
207 # TODO enhance with int conversion or from distutils.version import LooseVersion
208 # or with list(map(int, version.split(".")))
209 if N2VC_version
< "0.0.2":
210 raise LcmException("Not compatible osm/N2VC version '{}'. Needed '0.0.2' or higher".format(N2VC_version
))
213 # TODO check database version
214 if config
["database"]["driver"] == "mongo":
215 self
.db
= dbmongo
.DbMongo()
216 self
.db
.db_connect(config
["database"])
217 elif config
["database"]["driver"] == "memory":
218 self
.db
= dbmemory
.DbMemory()
219 self
.db
.db_connect(config
["database"])
221 raise LcmException("Invalid configuration param '{}' at '[database]':'driver'".format(
222 config
["database"]["driver"]))
224 if config
["storage"]["driver"] == "local":
225 self
.fs
= fslocal
.FsLocal()
226 self
.fs
.fs_connect(config
["storage"])
228 raise LcmException("Invalid configuration param '{}' at '[storage]':'driver'".format(
229 config
["storage"]["driver"]))
231 if config
["message"]["driver"] == "local":
232 self
.msg
= msglocal
.MsgLocal()
233 self
.msg
.connect(config
["message"])
234 elif config
["message"]["driver"] == "kafka":
235 self
.msg
= msgkafka
.MsgKafka()
236 self
.msg
.connect(config
["message"])
238 raise LcmException("Invalid configuration param '{}' at '[message]':'driver'".format(
239 config
["storage"]["driver"]))
240 except (DbException
, FsException
, MsgException
) as e
:
241 self
.logger
.critical(str(e
), exc_info
=True)
242 raise LcmException(str(e
))
244 async def check_RO_version(self
):
246 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
247 RO_version
= await RO
.get_version()
248 if RO_version
< min_RO_version
:
249 raise LcmException("Not compatible osm/RO version '{}.{}.{}'. Needed '{}.{}.{}' or higher".format(
250 *RO_version
, *min_RO_version
252 except ROclient
.ROClientException
as e
:
253 self
.logger
.critical("Error while conneting to osm/RO " + str(e
), exc_info
=True)
254 raise LcmException(str(e
))
256 def update_db_2(self
, item
, _id
, _desc
):
258 Updates database with _desc information. Upon success _desc is cleared
267 self
.db
.set_one(item
, {"_id": _id
}, _desc
)
269 except DbException
as e
:
270 self
.logger
.error("Updating {} _id={} with '{}'. Error: {}".format(item
, _id
, _desc
, e
))
272 async def vim_create(self
, vim_content
, order_id
):
273 vim_id
= vim_content
["_id"]
274 logging_text
= "Task vim_create={} ".format(vim_id
)
275 self
.logger
.debug(logging_text
+ "Enter")
281 step
= "Getting vim-id='{}' from db".format(vim_id
)
282 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_id
})
283 db_vim_update
["_admin.deployed.RO"] = None
284 if vim_content
.get("config") and vim_content
["config"].get("sdn-controller"):
285 step
= "Getting sdn-controller-id='{}' from db".format(vim_content
["config"]["sdn-controller"])
286 db_sdn
= self
.db
.get_one("sdns", {"_id": vim_content
["config"]["sdn-controller"]})
287 if db_sdn
.get("_admin") and db_sdn
["_admin"].get("deployed") and db_sdn
["_admin"]["deployed"].get("RO"):
288 RO_sdn_id
= db_sdn
["_admin"]["deployed"]["RO"]
290 raise LcmException("sdn-controller={} is not available. Not deployed at RO".format(
291 vim_content
["config"]["sdn-controller"]))
293 step
= "Creating vim at RO"
294 db_vim_update
["_admin.detailed-status"] = step
295 self
.update_db_2("vim_accounts", vim_id
, db_vim_update
)
296 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
297 vim_RO
= deepcopy(vim_content
)
298 vim_RO
.pop("_id", None)
299 vim_RO
.pop("_admin", None)
300 vim_RO
.pop("schema_version", None)
301 vim_RO
.pop("schema_type", None)
302 vim_RO
.pop("vim_tenant_name", None)
303 vim_RO
["type"] = vim_RO
.pop("vim_type")
304 vim_RO
.pop("vim_user", None)
305 vim_RO
.pop("vim_password", None)
307 vim_RO
["config"]["sdn-controller"] = RO_sdn_id
308 desc
= await RO
.create("vim", descriptor
=vim_RO
)
309 RO_vim_id
= desc
["uuid"]
310 db_vim_update
["_admin.deployed.RO"] = RO_vim_id
312 step
= "Creating vim_account at RO"
313 db_vim_update
["_admin.detailed-status"] = step
314 self
.update_db_2("vim_accounts", vim_id
, db_vim_update
)
316 vim_account_RO
= {"vim_tenant_name": vim_content
["vim_tenant_name"],
317 "vim_username": vim_content
["vim_user"],
318 "vim_password": vim_content
["vim_password"]
320 if vim_RO
.get("config"):
321 vim_account_RO
["config"] = vim_RO
["config"]
322 if "sdn-controller" in vim_account_RO
["config"]:
323 del vim_account_RO
["config"]["sdn-controller"]
324 if "sdn-port-mapping" in vim_account_RO
["config"]:
325 del vim_account_RO
["config"]["sdn-port-mapping"]
326 desc
= await RO
.attach_datacenter(RO_vim_id
, descriptor
=vim_account_RO
)
327 db_vim_update
["_admin.deployed.RO-account"] = desc
["uuid"]
328 db_vim_update
["_admin.operationalState"] = "ENABLED"
329 db_vim_update
["_admin.detailed-status"] = "Done"
331 # await asyncio.sleep(15) # TODO remove. This is for test
332 self
.logger
.debug(logging_text
+ "Exit Ok RO_vim_id={}".format(RO_vim_id
))
335 except (ROclient
.ROClientException
, DbException
) as e
:
336 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
338 except Exception as e
:
339 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
343 db_vim_update
["_admin.operationalState"] = "ERROR"
344 db_vim_update
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
346 self
.update_db_2("vim_accounts", vim_id
, db_vim_update
)
347 self
.lcm_tasks
.remove("vim_account", vim_id
, order_id
)
349 async def vim_edit(self
, vim_content
, order_id
):
350 vim_id
= vim_content
["_id"]
351 logging_text
= "Task vim_edit={} ".format(vim_id
)
352 self
.logger
.debug(logging_text
+ "Enter")
358 step
= "Getting vim-id='{}' from db".format(vim_id
)
360 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_id
})
362 # look if previous tasks in process
363 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account", vim_id
, order_id
)
365 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
366 self
.logger
.debug(logging_text
+ step
)
367 # TODO write this to database
368 await asyncio
.wait(task_dependency
, timeout
=3600)
370 if db_vim
.get("_admin") and db_vim
["_admin"].get("deployed") and db_vim
["_admin"]["deployed"].get("RO"):
371 if vim_content
.get("config") and vim_content
["config"].get("sdn-controller"):
372 step
= "Getting sdn-controller-id='{}' from db".format(vim_content
["config"]["sdn-controller"])
373 db_sdn
= self
.db
.get_one("sdns", {"_id": vim_content
["config"]["sdn-controller"]})
375 # look if previous tasks in process
376 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("sdn", db_sdn
["_id"])
378 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
379 self
.logger
.debug(logging_text
+ step
)
380 # TODO write this to database
381 await asyncio
.wait(task_dependency
, timeout
=3600)
383 if db_sdn
.get("_admin") and db_sdn
["_admin"].get("deployed") and db_sdn
["_admin"]["deployed"].get(
385 RO_sdn_id
= db_sdn
["_admin"]["deployed"]["RO"]
387 raise LcmException("sdn-controller={} is not available. Not deployed at RO".format(
388 vim_content
["config"]["sdn-controller"]))
390 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
391 step
= "Editing vim at RO"
392 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
393 vim_RO
= deepcopy(vim_content
)
394 vim_RO
.pop("_id", None)
395 vim_RO
.pop("_admin", None)
396 vim_RO
.pop("schema_version", None)
397 vim_RO
.pop("schema_type", None)
398 vim_RO
.pop("vim_tenant_name", None)
399 if "vim_type" in vim_RO
:
400 vim_RO
["type"] = vim_RO
.pop("vim_type")
401 vim_RO
.pop("vim_user", None)
402 vim_RO
.pop("vim_password", None)
404 vim_RO
["config"]["sdn-controller"] = RO_sdn_id
405 # TODO make a deep update of sdn-port-mapping
407 await RO
.edit("vim", RO_vim_id
, descriptor
=vim_RO
)
409 step
= "Editing vim-account at RO tenant"
411 if "config" in vim_content
:
412 if "sdn-controller" in vim_content
["config"]:
413 del vim_content
["config"]["sdn-controller"]
414 if "sdn-port-mapping" in vim_content
["config"]:
415 del vim_content
["config"]["sdn-port-mapping"]
416 if not vim_content
["config"]:
417 del vim_content
["config"]
418 for k
in ("vim_tenant_name", "vim_password", "config"):
420 vim_account_RO
[k
] = vim_content
[k
]
421 if "vim_user" in vim_content
:
422 vim_content
["vim_username"] = vim_content
["vim_user"]
423 # vim_account must be edited always even if empty in order to ensure changes are translated to RO
424 # vim_thread. RO will remove and relaunch a new thread for this vim_account
425 await RO
.edit("vim_account", RO_vim_id
, descriptor
=vim_account_RO
)
426 db_vim_update
["_admin.operationalState"] = "ENABLED"
428 self
.logger
.debug(logging_text
+ "Exit Ok RO_vim_id={}".format(RO_vim_id
))
431 except (ROclient
.ROClientException
, DbException
) as e
:
432 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
434 except Exception as e
:
435 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
439 db_vim_update
["_admin.operationalState"] = "ERROR"
440 db_vim_update
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
442 self
.update_db_2("vim_accounts", vim_id
, db_vim_update
)
443 self
.lcm_tasks
.remove("vim_account", vim_id
, order_id
)
445 async def vim_delete(self
, vim_id
, order_id
):
446 logging_text
= "Task vim_delete={} ".format(vim_id
)
447 self
.logger
.debug(logging_text
+ "Enter")
451 step
= "Getting vim from db"
453 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_id
})
454 if db_vim
.get("_admin") and db_vim
["_admin"].get("deployed") and db_vim
["_admin"]["deployed"].get("RO"):
455 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
456 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
457 step
= "Detaching vim from RO tenant"
459 await RO
.detach_datacenter(RO_vim_id
)
460 except ROclient
.ROClientException
as e
:
461 if e
.http_code
== 404: # not found
462 self
.logger
.debug(logging_text
+ "RO_vim_id={} already detached".format(RO_vim_id
))
466 step
= "Deleting vim from RO"
468 await RO
.delete("vim", RO_vim_id
)
469 except ROclient
.ROClientException
as e
:
470 if e
.http_code
== 404: # not found
471 self
.logger
.debug(logging_text
+ "RO_vim_id={} already deleted".format(RO_vim_id
))
476 self
.logger
.error(logging_text
+ "Nohing to remove at RO")
477 self
.db
.del_one("vim_accounts", {"_id": vim_id
})
478 self
.logger
.debug(logging_text
+ "Exit Ok")
481 except (ROclient
.ROClientException
, DbException
) as e
:
482 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
484 except Exception as e
:
485 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
488 self
.lcm_tasks
.remove("vim_account", vim_id
, order_id
)
490 db_vim_update
["_admin.operationalState"] = "ERROR"
491 db_vim_update
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
493 self
.update_db_2("vim_accounts", vim_id
, db_vim_update
)
494 self
.lcm_tasks
.remove("vim_account", vim_id
, order_id
)
496 async def sdn_create(self
, sdn_content
, order_id
):
497 sdn_id
= sdn_content
["_id"]
498 logging_text
= "Task sdn_create={} ".format(sdn_id
)
499 self
.logger
.debug(logging_text
+ "Enter")
505 step
= "Getting sdn from db"
506 db_sdn
= self
.db
.get_one("sdns", {"_id": sdn_id
})
507 db_sdn_update
["_admin.deployed.RO"] = None
509 step
= "Creating sdn at RO"
510 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
511 sdn_RO
= deepcopy(sdn_content
)
512 sdn_RO
.pop("_id", None)
513 sdn_RO
.pop("_admin", None)
514 sdn_RO
.pop("schema_version", None)
515 sdn_RO
.pop("schema_type", None)
516 sdn_RO
.pop("description", None)
517 desc
= await RO
.create("sdn", descriptor
=sdn_RO
)
518 RO_sdn_id
= desc
["uuid"]
519 db_sdn_update
["_admin.deployed.RO"] = RO_sdn_id
520 db_sdn_update
["_admin.operationalState"] = "ENABLED"
521 self
.logger
.debug(logging_text
+ "Exit Ok RO_sdn_id={}".format(RO_sdn_id
))
524 except (ROclient
.ROClientException
, DbException
) as e
:
525 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
527 except Exception as e
:
528 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
532 db_sdn_update
["_admin.operationalState"] = "ERROR"
533 db_sdn_update
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
535 self
.update_db_2("sdns", sdn_id
, db_sdn_update
)
536 self
.lcm_tasks
.remove("sdn", sdn_id
, order_id
)
538 async def sdn_edit(self
, sdn_content
, order_id
):
539 sdn_id
= sdn_content
["_id"]
540 logging_text
= "Task sdn_edit={} ".format(sdn_id
)
541 self
.logger
.debug(logging_text
+ "Enter")
545 step
= "Getting sdn from db"
547 db_sdn
= self
.db
.get_one("sdns", {"_id": sdn_id
})
548 if db_sdn
.get("_admin") and db_sdn
["_admin"].get("deployed") and db_sdn
["_admin"]["deployed"].get("RO"):
549 RO_sdn_id
= db_sdn
["_admin"]["deployed"]["RO"]
550 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
551 step
= "Editing sdn at RO"
552 sdn_RO
= deepcopy(sdn_content
)
553 sdn_RO
.pop("_id", None)
554 sdn_RO
.pop("_admin", None)
555 sdn_RO
.pop("schema_version", None)
556 sdn_RO
.pop("schema_type", None)
557 sdn_RO
.pop("description", None)
559 await RO
.edit("sdn", RO_sdn_id
, descriptor
=sdn_RO
)
560 db_sdn_update
["_admin.operationalState"] = "ENABLED"
562 self
.logger
.debug(logging_text
+ "Exit Ok RO_sdn_id".format(RO_sdn_id
))
565 except (ROclient
.ROClientException
, DbException
) as e
:
566 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
568 except Exception as e
:
569 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
573 db_sdn
["_admin.operationalState"] = "ERROR"
574 db_sdn
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
576 self
.update_db_2("sdns", sdn_id
, db_sdn_update
)
577 self
.lcm_tasks
.remove("sdn", sdn_id
, order_id
)
579 async def sdn_delete(self
, sdn_id
, order_id
):
580 logging_text
= "Task sdn_delete={} ".format(sdn_id
)
581 self
.logger
.debug(logging_text
+ "Enter")
585 step
= "Getting sdn from db"
587 db_sdn
= self
.db
.get_one("sdns", {"_id": sdn_id
})
588 if db_sdn
.get("_admin") and db_sdn
["_admin"].get("deployed") and db_sdn
["_admin"]["deployed"].get("RO"):
589 RO_sdn_id
= db_sdn
["_admin"]["deployed"]["RO"]
590 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
591 step
= "Deleting sdn from RO"
593 await RO
.delete("sdn", RO_sdn_id
)
594 except ROclient
.ROClientException
as e
:
595 if e
.http_code
== 404: # not found
596 self
.logger
.debug(logging_text
+ "RO_sdn_id={} already deleted".format(RO_sdn_id
))
601 self
.logger
.error(logging_text
+ "Skipping. There is not RO information at database")
602 self
.db
.del_one("sdns", {"_id": sdn_id
})
603 self
.logger
.debug("sdn_delete task sdn_id={} Exit Ok".format(sdn_id
))
606 except (ROclient
.ROClientException
, DbException
) as e
:
607 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
609 except Exception as e
:
610 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
614 db_sdn
["_admin.operationalState"] = "ERROR"
615 db_sdn
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
617 self
.update_db_2("sdns", sdn_id
, db_sdn_update
)
618 self
.lcm_tasks
.remove("sdn", sdn_id
, order_id
)
620 def vnfd2RO(self
, vnfd
, new_id
=None):
622 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
623 :param vnfd: input vnfd
624 :param new_id: overrides vnf id if provided
625 :return: copy of vnfd
629 vnfd_RO
= deepcopy(vnfd
)
630 vnfd_RO
.pop("_id", None)
631 vnfd_RO
.pop("_admin", None)
633 vnfd_RO
["id"] = new_id
634 for vdu
in vnfd_RO
["vdu"]:
635 if "cloud-init-file" in vdu
:
636 base_folder
= vnfd
["_admin"]["storage"]
637 clout_init_file
= "{}/{}/cloud_init/{}".format(
638 base_folder
["folder"],
639 base_folder
["pkg-dir"],
640 vdu
["cloud-init-file"]
642 ci_file
= self
.fs
.file_open(clout_init_file
, "r")
643 # TODO: detect if binary or text. Propose to read as binary and try to decode to utf8. If fails
644 # convert to base 64 or similar
645 clout_init_content
= ci_file
.read()
648 vdu
.pop("cloud-init-file", None)
649 vdu
["cloud-init"] = clout_init_content
650 # remnove unused by RO configuration, monitoring, scaling
651 vnfd_RO
.pop("vnf-configuration", None)
652 vnfd_RO
.pop("monitoring-param", None)
653 vnfd_RO
.pop("scaling-group-descriptor", None)
655 except FsException
as e
:
656 raise LcmException("Error reading file at vnfd {}: {} ".format(vnfd
["_id"], e
))
661 def n2vc_callback(self
, model_name
, application_name
, status
, message
, db_nsr
, db_nslcmop
, task
=None):
663 Callback both for charm status change and task completion
664 :param model_name: Charm model name
665 :param application_name: Charm application name
666 :param status: Can be
667 - blocked: The unit needs manual intervention
668 - maintenance: The unit is actively deploying/configuring
669 - waiting: The unit is waiting for another charm to be ready
670 - active: The unit is deployed, configured, and ready
671 - error: The charm has failed and needs attention.
672 - terminated: The charm has been destroyed
675 :param message: detailed message error
676 :param db_nsr: nsr database content
677 :param db_nslcmop: nslcmop database content
678 :param task: None for charm status change, or task for completion task callback
684 db_nslcmop_update
= {}
686 nsr_id
= db_nsr
["_id"]
687 nsr_lcm
= db_nsr
["_admin"]["deployed"]
688 nslcmop_id
= db_nslcmop
["_id"]
689 ns_operation
= db_nslcmop
["lcmOperationType"]
690 logging_text
= "Task ns={} {}={} [n2vc_callback] application={}".format(nsr_id
, ns_operation
, nslcmop_id
,
692 vca_deployed
= nsr_lcm
["VCA"].get(application_name
)
694 self
.logger
.error(logging_text
+ " Not present at nsr._admin.deployed.VCA")
699 self
.logger
.debug(logging_text
+ " task Cancelled")
700 # TODO update db_nslcmop
704 exc
= task
.exception()
706 self
.logger
.error(logging_text
+ " task Exception={}".format(exc
))
707 if ns_operation
in ("instantiate", "terminate"):
708 vca_deployed
['operational-status'] = "error"
709 db_nsr_update
["_admin.deployed.VCA.{}.operational-status".format(application_name
)] = \
711 vca_deployed
['detailed-status'] = str(exc
)
713 "_admin.deployed.VCA.{}.detailed-status".format(application_name
)] = str(exc
)
714 elif ns_operation
== "action":
715 db_nslcmop_update
["operationState"] = "FAILED"
716 db_nslcmop_update
["detailed-status"] = str(exc
)
717 db_nslcmop_update
["statusEnteredTime"] = time()
721 self
.logger
.debug(logging_text
+ " task Done")
722 # TODO revise with Adam if action is finished and ok when task is done
723 if ns_operation
== "action":
724 db_nslcmop_update
["operationState"] = "COMPLETED"
725 db_nslcmop_update
["detailed-status"] = "Done"
726 db_nslcmop_update
["statusEnteredTime"] = time()
727 # task is Done, but callback is still ongoing. So ignore
730 self
.logger
.debug(logging_text
+ " Enter status={}".format(status
))
731 if vca_deployed
['operational-status'] == status
:
732 return # same status, ignore
733 vca_deployed
['operational-status'] = status
734 db_nsr_update
["_admin.deployed.VCA.{}.operational-status".format(application_name
)] = status
735 vca_deployed
['detailed-status'] = str(message
)
736 db_nsr_update
["_admin.deployed.VCA.{}.detailed-status".format(application_name
)] = str(message
)
738 self
.logger
.critical(logging_text
+ " Enter with bad parameters", exc_info
=True)
743 n2vc_error_text
= [] # contain text error list. If empty no one is in error status
744 for _
, vca_info
in nsr_lcm
["VCA"].items():
745 vca_status
= vca_info
["operational-status"]
746 if vca_status
not in status_map
:
748 status_map
[vca_status
] = 0
749 status_map
[vca_status
] += 1
751 if vca_status
!= "active":
753 if vca_status
in ("error", "blocked"):
754 n2vc_error_text
.append("member_vnf_index={} vdu_id={} {}: {}".format(vca_info
["member-vnf-index"],
755 vca_info
["vdu_id"], vca_status
,
756 vca_info
["detailed-status"]))
759 self
.logger
.debug(logging_text
+ " All active")
760 db_nsr_update
["config-status"] = "configured"
761 db_nsr_update
["detailed-status"] = "done"
762 db_nslcmop_update
["operationState"] = "COMPLETED"
763 db_nslcmop_update
["detailed-status"] = "Done"
764 db_nslcmop_update
["statusEnteredTime"] = time()
765 elif n2vc_error_text
:
766 db_nsr_update
["config-status"] = "failed"
767 error_text
= "fail configuring " + ";".join(n2vc_error_text
)
768 db_nsr_update
["detailed-status"] = error_text
769 db_nslcmop_update
["operationState"] = "FAILED_TEMP"
770 db_nslcmop_update
["detailed-status"] = error_text
771 db_nslcmop_update
["statusEnteredTime"] = time()
775 for status
, num
in status_map
.items():
776 cs
+= separator
+ "{}: {}".format(status
, num
)
778 db_nsr_update
["config-status"] = cs
779 db_nsr_update
["detailed-status"] = cs
780 db_nslcmop_update
["detailed-status"] = cs
782 except Exception as e
:
783 self
.logger
.critical(logging_text
+ " Exception {}".format(e
), exc_info
=True)
786 if db_nslcmop_update
:
787 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
789 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
790 except Exception as e
:
791 self
.logger
.critical(logging_text
+ " Update database Exception {}".format(e
), exc_info
=True)
793 def ns_params_2_RO(self
, ns_params
, nsd
, vnfd_dict
):
795 Creates a RO ns descriptor from OSM ns_instantite params
796 :param ns_params: OSM instantiate params
797 :return: The RO ns descriptor
801 def vim_account_2_RO(vim_account
):
802 if vim_account
in vim_2_RO
:
803 return vim_2_RO
[vim_account
]
805 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_account
})
806 if db_vim
["_admin"]["operationalState"] != "ENABLED":
807 raise LcmException("VIM={} is not available. operationalState={}".format(
808 vim_account
, db_vim
["_admin"]["operationalState"]))
809 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
810 vim_2_RO
[vim_account
] = RO_vim_id
813 def ip_profile_2_RO(ip_profile
):
814 RO_ip_profile
= deepcopy((ip_profile
))
815 if "dns-server" in RO_ip_profile
:
816 RO_ip_profile
["dns-address"] = RO_ip_profile
.pop("dns-server")
817 if RO_ip_profile
.get("ip-version") == "ipv4":
818 RO_ip_profile
["ip-version"] = "IPv4"
819 if RO_ip_profile
.get("ip-version") == "ipv6":
820 RO_ip_profile
["ip-version"] = "IPv6"
821 if "dhcp-params" in RO_ip_profile
:
822 RO_ip_profile
["dhcp"] = RO_ip_profile
.pop("dhcp-params")
828 # "name": ns_params["nsName"],
829 # "description": ns_params.get("nsDescription"),
830 "datacenter": vim_account_2_RO(ns_params
["vimAccountId"]),
831 # "scenario": ns_params["nsdId"],
835 if ns_params
.get("ssh-authorized-key"):
836 RO_ns_params
["cloud-config"] = {"key-pairs": ns_params
["ssh-authorized-key"]}
837 if ns_params
.get("vnf"):
838 for vnf_params
in ns_params
["vnf"]:
839 for constituent_vnfd
in nsd
["constituent-vnfd"]:
840 if constituent_vnfd
["member-vnf-index"] == vnf_params
["member-vnf-index"]:
841 vnf_descriptor
= vnfd_dict
[constituent_vnfd
["vnfd-id-ref"]]
844 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index={} is not present at nsd:"
845 "constituent-vnfd".format(vnf_params
["member-vnf-index"]))
846 RO_vnf
= {"vdus": {}, "networks": {}}
847 if vnf_params
.get("vimAccountId"):
848 RO_vnf
["datacenter"] = vim_account_2_RO(vnf_params
["vimAccountId"])
849 if vnf_params
.get("vdu"):
850 for vdu_params
in vnf_params
["vdu"]:
851 RO_vnf
["vdus"][vdu_params
["id"]] = {}
852 if vdu_params
.get("volume"):
853 RO_vnf
["vdus"][vdu_params
["id"]]["devices"] = {}
854 for volume_params
in vdu_params
["volume"]:
855 RO_vnf
["vdus"][vdu_params
["id"]]["devices"][volume_params
["name"]] = {}
856 if volume_params
.get("vim-volume-id"):
857 RO_vnf
["vdus"][vdu_params
["id"]]["devices"][volume_params
["name"]]["vim_id"] = \
858 volume_params
["vim-volume-id"]
859 if vdu_params
.get("interface"):
860 RO_vnf
["vdus"][vdu_params
["id"]]["interfaces"] = {}
861 for interface_params
in vdu_params
["interface"]:
863 RO_vnf
["vdus"][vdu_params
["id"]]["interfaces"][interface_params
["name"]] = RO_interface
864 if interface_params
.get("ip-address"):
865 RO_interface
["ip_address"] = interface_params
["ip-address"]
866 if interface_params
.get("mac-address"):
867 RO_interface
["mac_address"] = interface_params
["mac-address"]
868 if interface_params
.get("floating-ip-required"):
869 RO_interface
["floating-ip"] = interface_params
["floating-ip-required"]
870 if vnf_params
.get("internal-vld"):
871 for internal_vld_params
in vnf_params
["internal-vld"]:
872 RO_vnf
["networks"][internal_vld_params
["name"]] = {}
873 if internal_vld_params
.get("vim-network-name"):
874 RO_vnf
["networks"][internal_vld_params
["name"]]["vim-network-name"] = \
875 internal_vld_params
["vim-network-name"]
876 if internal_vld_params
.get("ip-profile"):
877 RO_vnf
["networks"][internal_vld_params
["name"]]["ip-profile"] = \
878 ip_profile_2_RO(internal_vld_params
["ip-profile"])
879 if internal_vld_params
.get("internal-connection-point"):
880 for icp_params
in internal_vld_params
["internal-connection-point"]:
883 for vdu_descriptor
in vnf_descriptor
["vdu"]:
884 for vdu_interface
in vdu_descriptor
["interface"]:
885 if vdu_interface
.get("internal-connection-point-ref") == icp_params
["id-ref"]:
886 if vdu_descriptor
["id"] not in RO_vnf
["vdus"]:
887 RO_vnf
["vdus"][vdu_descriptor
["id"]] = {}
888 if "interfaces" not in RO_vnf
["vdus"][vdu_descriptor
["id"]]:
889 RO_vnf
["vdus"][vdu_descriptor
["id"]]["interfaces"] = {}
890 RO_ifaces
= RO_vnf
["vdus"][vdu_descriptor
["id"]]["interfaces"]
891 if vdu_interface
["name"] not in RO_ifaces
:
892 RO_ifaces
[vdu_interface
["name"]] = {}
894 RO_ifaces
[vdu_interface
["name"]]["ip_address"] = icp_params
["ip-address"]
900 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
901 "internal-vld:id-ref={} is not present at vnfd:internal-"
902 "connection-point".format(vnf_params
["member-vnf-index"],
903 icp_params
["id-ref"]))
905 if not RO_vnf
["vdus"]:
907 if not RO_vnf
["networks"]:
908 del RO_vnf
["networks"]
910 RO_ns_params
["vnfs"][vnf_params
["member-vnf-index"]] = RO_vnf
911 if ns_params
.get("vld"):
912 for vld_params
in ns_params
["vld"]:
914 if "ip-profile" in vld_params
:
915 RO_vld
["ip-profile"] = ip_profile_2_RO(vld_params
["ip-profile"])
916 if "vim-network-name" in vld_params
:
918 if isinstance(vld_params
["vim-network-name"], dict):
919 for vim_account
, vim_net
in vld_params
["vim-network-name"].items():
920 RO_vld
["sites"].append({
921 "netmap-use": vim_net
,
922 "datacenter": vim_account_2_RO(vim_account
)
924 else: # isinstance str
925 RO_vld
["sites"].append({"netmap-use": vld_params
["vim-network-name"]})
927 RO_ns_params
["networks"][vld_params
["name"]] = RO_vld
930 def ns_update_vnfr(self
, db_vnfrs
, nsr_desc_RO
):
932 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
937 for vnf_index
, db_vnfr
in db_vnfrs
.items():
938 for vnf_RO
in nsr_desc_RO
["vnfs"]:
939 if vnf_RO
["member_vnf_index"] == vnf_index
:
941 db_vnfr
["ip-address"] = vnfr_update
["ip-address"] = vnf_RO
.get("ip_address")
943 for vdur_RO
in vnf_RO
.get("vms", ()):
945 "vim-id": vdur_RO
.get("vim_vm_id"),
946 "ip-address": vdur_RO
.get("ip_address"),
947 "vdu-id-ref": vdur_RO
.get("vdu_osm_id"),
948 "name": vdur_RO
.get("vim_name"),
949 "status": vdur_RO
.get("status"),
950 "status-detailed": vdur_RO
.get("error_msg"),
954 for interface_RO
in vdur_RO
.get("interfaces", ()):
955 vdur
["interfaces"].append({
956 "ip-address": interface_RO
.get("ip_address"),
957 "mac-address": interface_RO
.get("mac_address"),
958 "name": interface_RO
.get("external_name"),
960 vdur_list
.append(vdur
)
961 db_vnfr
["vdur"] = vnfr_update
["vdur"] = vdur_list
962 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
966 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} at RO info".format(vnf_index
))
968 async def create_monitoring(self
, nsr_id
, vnf_member_index
, vnfd_desc
):
969 if not vnfd_desc
.get("scaling-group-descriptor"):
971 for scaling_group
in vnfd_desc
["scaling-group-descriptor"]:
972 scaling_policy_desc
= {}
975 "scaling_group_descriptor": {
976 "name": scaling_group
["name"],
977 "scaling_policy": scaling_policy_desc
980 for scaling_policy
in scaling_group
.get("scaling-policy"):
981 scaling_policy_desc
["scale_in_operation_type"] = scaling_policy_desc
["scale_out_operation_type"] = \
982 scaling_policy
["scaling-type"]
983 scaling_policy_desc
["threshold_time"] = scaling_policy
["threshold-time"]
984 scaling_policy_desc
["cooldown_time"] = scaling_policy
["cooldown-time"]
985 scaling_policy_desc
["scaling_criteria"] = []
986 for scaling_criteria
in scaling_policy
.get("scaling-criteria"):
987 scaling_criteria_desc
= {"scale_in_threshold": scaling_criteria
.get("scale-in-threshold"),
988 "scale_out_threshold": scaling_criteria
.get("scale-out-threshold"),
990 if not scaling_criteria
.get("vnf-monitoring-param-ref"):
992 for monitoring_param
in vnfd_desc
.get("monitoring-param", ()):
993 if monitoring_param
["id"] == scaling_criteria
["vnf-monitoring-param-ref"]:
994 scaling_criteria_desc
["monitoring_param"] = {
995 "id": monitoring_param
["id"],
996 "name": monitoring_param
["name"],
997 "aggregation_type": monitoring_param
.get("aggregation-type"),
998 "vdu_name": monitoring_param
.get("vdu-ref"),
999 "vnf_member_index": vnf_member_index
,
1002 scaling_policy_desc
["scaling_criteria"].append(scaling_criteria_desc
)
1006 "Task ns={} member_vnf_index={} Invalid vnfd vnf-monitoring-param-ref={} not in "
1007 "monitoring-param list".format(nsr_id
, vnf_member_index
,
1008 scaling_criteria
["vnf-monitoring-param-ref"]))
1010 await self
.msg
.aiowrite("lcm_pm", "configure_scaling", scaling_desc
, self
.loop
)
1012 async def ns_instantiate(self
, nsr_id
, nslcmop_id
):
1013 logging_text
= "Task ns={} instantiate={} ".format(nsr_id
, nslcmop_id
)
1014 self
.logger
.debug(logging_text
+ "Enter")
1015 # get all needed from database
1019 db_nslcmop_update
= {}
1021 RO_descriptor_number
= 0 # number of descriptors created at RO
1022 descriptor_id_2_RO
= {} # map between vnfd/nsd id to the id used at RO
1025 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
1026 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1027 step
= "Getting nsr={} from db".format(nsr_id
)
1028 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1029 ns_params
= db_nsr
.get("instantiate_params")
1031 nsr_name
= db_nsr
["name"] # TODO short-name??
1033 vnfr_filter
= {"nsr-id-ref": nsr_id
, "member-vnf-index-ref": None}
1034 for c_vnf
in nsd
["constituent-vnfd"]:
1035 vnfd_id
= c_vnf
["vnfd-id-ref"]
1036 vnfr_filter
["member-vnf-index-ref"] = c_vnf
["member-vnf-index"]
1037 step
= "Getting vnfr={} of nsr={} from db".format(c_vnf
["member-vnf-index"], nsr_id
)
1038 db_vnfrs
[c_vnf
["member-vnf-index"]] = self
.db
.get_one("vnfrs", vnfr_filter
)
1039 if vnfd_id
not in needed_vnfd
:
1040 step
= "Getting vnfd={} from db".format(vnfd_id
)
1041 needed_vnfd
[vnfd_id
] = self
.db
.get_one("vnfds", {"id": vnfd_id
})
1043 nsr_lcm
= db_nsr
["_admin"].get("deployed")
1045 nsr_lcm
= db_nsr
["_admin"]["deployed"] = {
1047 "RO": {"vnfd_id": {}, "nsd_id": None, "nsr_id": None, "nsr_status": "SCHEDULED"},
1051 db_nsr_update
["detailed-status"] = "creating"
1052 db_nsr_update
["operational-status"] = "init"
1054 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
1056 # get vnfds, instantiate at RO
1057 for vnfd_id
, vnfd
in needed_vnfd
.items():
1058 step
= db_nsr_update
["detailed-status"] = "Creating vnfd={} at RO".format(vnfd_id
)
1059 # self.logger.debug(logging_text + step)
1060 vnfd_id_RO
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, vnfd_id
[:23])
1061 descriptor_id_2_RO
[vnfd_id
] = vnfd_id_RO
1062 RO_descriptor_number
+= 1
1065 vnfd_list
= await RO
.get_list("vnfd", filter_by
={"osm_id": vnfd_id_RO
})
1067 db_nsr_update
["_admin.deployed.RO.vnfd_id.{}".format(vnfd_id
)] = vnfd_list
[0]["uuid"]
1068 self
.logger
.debug(logging_text
+ "vnfd={} exists at RO. Using RO_id={}".format(
1069 vnfd_id
, vnfd_list
[0]["uuid"]))
1071 vnfd_RO
= self
.vnfd2RO(vnfd
, vnfd_id_RO
)
1072 desc
= await RO
.create("vnfd", descriptor
=vnfd_RO
)
1073 db_nsr_update
["_admin.deployed.RO.vnfd_id.{}".format(vnfd_id
)] = desc
["uuid"]
1074 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1075 self
.logger
.debug(logging_text
+ "vnfd={} created at RO. RO_id={}".format(
1076 vnfd_id
, desc
["uuid"]))
1077 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1081 step
= db_nsr_update
["detailed-status"] = "Creating nsd={} at RO".format(nsd_id
)
1082 # self.logger.debug(logging_text + step)
1084 RO_osm_nsd_id
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, nsd_id
[:23])
1085 descriptor_id_2_RO
[nsd_id
] = RO_osm_nsd_id
1086 RO_descriptor_number
+= 1
1087 nsd_list
= await RO
.get_list("nsd", filter_by
={"osm_id": RO_osm_nsd_id
})
1089 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= nsd_list
[0]["uuid"]
1090 self
.logger
.debug(logging_text
+ "nsd={} exists at RO. Using RO_id={}".format(
1091 nsd_id
, RO_nsd_uuid
))
1093 nsd_RO
= deepcopy(nsd
)
1094 nsd_RO
["id"] = RO_osm_nsd_id
1095 nsd_RO
.pop("_id", None)
1096 nsd_RO
.pop("_admin", None)
1097 for c_vnf
in nsd_RO
["constituent-vnfd"]:
1098 vnfd_id
= c_vnf
["vnfd-id-ref"]
1099 c_vnf
["vnfd-id-ref"] = descriptor_id_2_RO
[vnfd_id
]
1100 desc
= await RO
.create("nsd", descriptor
=nsd_RO
)
1101 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1102 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= desc
["uuid"]
1103 self
.logger
.debug(logging_text
+ "nsd={} created at RO. RO_id={}".format(nsd_id
, RO_nsd_uuid
))
1104 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1107 # if present use it unless in error status
1108 RO_nsr_id
= db_nsr
["_admin"].get("deployed", {}).get("RO", {}).get("nsr_id")
1111 step
= db_nsr_update
["detailed-status"] = "Looking for existing ns at RO"
1112 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
1113 desc
= await RO
.show("ns", RO_nsr_id
)
1114 except ROclient
.ROClientException
as e
:
1115 if e
.http_code
!= HTTPStatus
.NOT_FOUND
:
1117 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1119 ns_status
, ns_status_info
= RO
.check_ns_status(desc
)
1120 db_nsr_update
["_admin.deployed.RO.nsr_status"] = ns_status
1121 if ns_status
== "ERROR":
1122 step
= db_nsr_update
["detailed-status"] = "Deleting ns at RO. RO_ns_id={}".format(RO_nsr_id
)
1123 self
.logger
.debug(logging_text
+ step
)
1124 await RO
.delete("ns", RO_nsr_id
)
1125 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1127 step
= db_nsr_update
["detailed-status"] = "Creating ns at RO"
1128 # self.logger.debug(logging_text + step)
1130 # check if VIM is creating and wait look if previous tasks in process
1131 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account", ns_params
["vimAccountId"])
1133 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
1134 self
.logger
.debug(logging_text
+ step
)
1135 await asyncio
.wait(task_dependency
, timeout
=3600)
1136 if ns_params
.get("vnf"):
1137 for vnf
in ns_params
["vnf"]:
1138 if "vimAccountId" in vnf
:
1139 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account",
1140 vnf
["vimAccountId"])
1142 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
1143 self
.logger
.debug(logging_text
+ step
)
1144 await asyncio
.wait(task_dependency
, timeout
=3600)
1146 RO_ns_params
= self
.ns_params_2_RO(ns_params
, nsd
, needed_vnfd
)
1147 desc
= await RO
.create("ns", descriptor
=RO_ns_params
,
1148 name
=db_nsr
["name"],
1149 scenario
=RO_nsd_uuid
)
1150 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = desc
["uuid"]
1151 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1152 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "BUILD"
1153 self
.logger
.debug(logging_text
+ "ns created at RO. RO_id={}".format(desc
["uuid"]))
1154 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1156 # update VNFR vimAccount
1157 step
= "Updating VNFR vimAcccount"
1158 for vnf_index
, vnfr
in db_vnfrs
.items():
1159 if vnfr
.get("vim-account-id"):
1161 vnfr_update
= {"vim-account-id": db_nsr
["instantiate_params"]["vimAccountId"]}
1162 if db_nsr
["instantiate_params"].get("vnf"):
1163 for vnf_params
in db_nsr
["instantiate_params"]["vnf"]:
1164 if vnf_params
.get("member-vnf-index") == vnf_index
:
1165 if vnf_params
.get("vimAccountId"):
1166 vnfr_update
["vim-account-id"] = vnf_params
.get("vimAccountId")
1168 self
.update_db_2("vnfrs", vnfr
["_id"], vnfr_update
)
1170 # wait until NS is ready
1171 step
= ns_status_detailed
= detailed_status
= "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id
)
1172 detailed_status_old
= None
1173 self
.logger
.debug(logging_text
+ step
)
1175 deployment_timeout
= 2 * 3600 # Two hours
1176 while deployment_timeout
> 0:
1177 desc
= await RO
.show("ns", RO_nsr_id
)
1178 ns_status
, ns_status_info
= RO
.check_ns_status(desc
)
1179 db_nsr_update
["admin.deployed.RO.nsr_status"] = ns_status
1180 if ns_status
== "ERROR":
1181 raise ROclient
.ROClientException(ns_status_info
)
1182 elif ns_status
== "BUILD":
1183 detailed_status
= ns_status_detailed
+ "; {}".format(ns_status_info
)
1184 elif ns_status
== "ACTIVE":
1185 step
= detailed_status
= "Waiting for management IP address reported by the VIM"
1187 nsr_lcm
["nsr_ip"] = RO
.get_ns_vnf_info(desc
)
1189 except ROclient
.ROClientException
as e
:
1190 if e
.http_code
!= 409: # IP address is not ready return code is 409 CONFLICT
1193 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
1194 if detailed_status
!= detailed_status_old
:
1195 detailed_status_old
= db_nsr_update
["detailed-status"] = detailed_status
1196 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1197 await asyncio
.sleep(5, loop
=self
.loop
)
1198 deployment_timeout
-= 5
1199 if deployment_timeout
<= 0:
1200 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
1202 step
= "Updating VNFRs"
1203 self
.ns_update_vnfr(db_vnfrs
, desc
)
1205 db_nsr
["detailed-status"] = "Configuring vnfr"
1206 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1208 # The parameters we'll need to deploy a charm
1209 number_to_configure
= 0
1211 def deploy(vnf_index
, vdu_id
, mgmt_ip_address
, config_primitive
=None):
1212 """An inner function to deploy the charm from either vnf or vdu
1213 vnf_index is mandatory. vdu_id can be None for a vnf configuration or the id for vdu configuration
1215 if not mgmt_ip_address
:
1216 raise LcmException("vnfd/vdu has not management ip address to configure it")
1218 # if number_to_configure == 0:
1219 # self.logger.debug("Logging into N2VC...")
1220 # task = asyncio.ensure_future(self.n2vc.login())
1221 # yield from asyncio.wait_for(task, 30.0)
1222 # self.logger.debug("Logged into N2VC!")
1224 # # await self.n2vc.login()
1226 # Note: The charm needs to exist on disk at the location
1227 # specified by charm_path.
1228 base_folder
= vnfd
["_admin"]["storage"]
1229 storage_params
= self
.fs
.get_params()
1230 charm_path
= "{}{}/{}/charms/{}".format(
1231 storage_params
["path"],
1232 base_folder
["folder"],
1233 base_folder
["pkg-dir"],
1237 # Setup the runtime parameters for this VNF
1238 params
= {'rw_mgmt_ip': mgmt_ip_address
}
1239 if config_primitive
:
1240 params
["initial-config-primitive"] = config_primitive
1242 # ns_name will be ignored in the current version of N2VC
1243 # but will be implemented for the next point release.
1244 model_name
= 'default'
1245 vdu_id_text
= "vnfd"
1247 vdu_id_text
= vdu_id
1248 application_name
= self
.n2vc
.FormatApplicationName(
1253 if not nsr_lcm
.get("VCA"):
1255 nsr_lcm
["VCA"][application_name
] = db_nsr_update
["_admin.deployed.VCA.{}".format(application_name
)] = {
1256 "member-vnf-index": vnf_index
,
1258 "model": model_name
,
1259 "application": application_name
,
1260 "operational-status": "init",
1261 "detailed-status": "",
1264 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1266 self
.logger
.debug("Task create_ns={} Passing artifacts path '{}' for {}".format(nsr_id
, charm_path
,
1268 task
= asyncio
.ensure_future(
1269 self
.n2vc
.DeployCharms(
1270 model_name
, # The network service name
1271 application_name
, # The application name
1272 vnfd
, # The vnf descriptor
1273 charm_path
, # Path to charm
1274 params
, # Runtime params, like mgmt ip
1275 {}, # for native charms only
1276 self
.n2vc_callback
, # Callback for status changes
1277 db_nsr
, # Callback parameter
1279 None, # Callback parameter (task)
1282 task
.add_done_callback(functools
.partial(self
.n2vc_callback
, model_name
, application_name
, None, None,
1283 db_nsr
, db_nslcmop
))
1284 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "create_charm:" + application_name
, task
)
1286 step
= "Looking for needed vnfd to configure"
1287 self
.logger
.debug(logging_text
+ step
)
1289 for c_vnf
in nsd
["constituent-vnfd"]:
1290 vnfd_id
= c_vnf
["vnfd-id-ref"]
1291 vnf_index
= str(c_vnf
["member-vnf-index"])
1292 vnfd
= needed_vnfd
[vnfd_id
]
1294 # Check if this VNF has a charm configuration
1295 vnf_config
= vnfd
.get("vnf-configuration")
1297 if vnf_config
and vnf_config
.get("juju"):
1298 proxy_charm
= vnf_config
["juju"]["charm"]
1299 config_primitive
= None
1302 if 'initial-config-primitive' in vnf_config
:
1303 config_primitive
= vnf_config
['initial-config-primitive']
1305 # Login to the VCA. If there are multiple calls to login(),
1306 # subsequent calls will be a nop and return immediately.
1307 step
= "connecting to N2VC to configure vnf {}".format(vnf_index
)
1308 await self
.n2vc
.login()
1309 deploy(vnf_index
, None, db_vnfrs
[vnf_index
]["ip-address"], config_primitive
)
1310 number_to_configure
+= 1
1312 # Deploy charms for each VDU that supports one.
1314 for vdu
in vnfd
['vdu']:
1315 vdu_config
= vdu
.get('vdu-configuration')
1317 config_primitive
= None
1319 if vdu_config
and vdu_config
.get("juju"):
1320 proxy_charm
= vdu_config
["juju"]["charm"]
1322 if 'initial-config-primitive' in vdu_config
:
1323 config_primitive
= vdu_config
['initial-config-primitive']
1326 step
= "connecting to N2VC to configure vdu {} from vnf {}".format(vdu
["id"], vnf_index
)
1327 await self
.n2vc
.login()
1328 deploy(vnf_index
, vdu
["id"], db_vnfrs
[vnf_index
]["vdur"][vdu_index
]["ip-address"],
1330 number_to_configure
+= 1
1333 if number_to_configure
:
1334 db_nsr_update
["config-status"] = "configuring"
1335 db_nsr_update
["operational-status"] = "running"
1336 db_nsr_update
["detailed-status"] = "configuring: init: {}".format(number_to_configure
)
1337 db_nslcmop_update
["detailed-status"] = "configuring: init: {}".format(number_to_configure
)
1339 db_nslcmop_update
["operationState"] = "COMPLETED"
1340 db_nslcmop_update
["statusEnteredTime"] = time()
1341 db_nslcmop_update
["detailed-status"] = "done"
1342 db_nsr_update
["config-status"] = "configured"
1343 db_nsr_update
["detailed-status"] = "done"
1344 db_nsr_update
["operational-status"] = "running"
1345 step
= "Sending monitoring parameters to PM"
1346 # for c_vnf in nsd["constituent-vnfd"]:
1347 # await self.create_monitoring(nsr_id, c_vnf["member-vnf-index"], needed_vnfd[c_vnf["vnfd-id-ref"]])
1349 await self
.msg
.aiowrite("ns", "instantiated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
})
1350 except Exception as e
:
1351 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1353 self
.logger
.debug(logging_text
+ "Exit")
1356 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
1357 self
.logger
.error(logging_text
+ "Exit Exception while '{}': {}".format(step
, e
))
1359 except asyncio
.CancelledError
:
1360 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1361 exc
= "Operation was cancelled"
1362 except Exception as e
:
1363 exc
= traceback
.format_exc()
1364 self
.logger
.critical(logging_text
+ "Exit Exception {} while '{}': {}".format(type(e
).__name
__, step
, e
),
1369 db_nsr_update
["detailed-status"] = "ERROR {}: {}".format(step
, exc
)
1370 db_nsr_update
["operational-status"] = "failed"
1372 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
1373 db_nslcmop_update
["operationState"] = "FAILED"
1374 db_nslcmop_update
["statusEnteredTime"] = time()
1376 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1377 if db_nslcmop_update
:
1378 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1379 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_instantiate")
1381 async def ns_terminate(self
, nsr_id
, nslcmop_id
):
1382 logging_text
= "Task ns={} terminate={} ".format(nsr_id
, nslcmop_id
)
1383 self
.logger
.debug(logging_text
+ "Enter")
1387 failed_detail
= [] # annotates all failed error messages
1391 db_nslcmop_update
= {}
1393 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
1394 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1395 step
= "Getting nsr={} from db".format(nsr_id
)
1396 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1397 # nsd = db_nsr["nsd"]
1398 nsr_lcm
= deepcopy(db_nsr
["_admin"].get("deployed"))
1399 if db_nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
1402 # db_vim = self.db.get_one("vim_accounts", {"_id": db_nsr["datacenter"]})
1403 # #TODO check if VIM is creating and wait
1404 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
1406 db_nsr_update
["operational-status"] = "terminating"
1407 db_nsr_update
["config-status"] = "terminating"
1409 if nsr_lcm
and nsr_lcm
.get("VCA"):
1411 step
= "Scheduling configuration charms removing"
1412 db_nsr_update
["detailed-status"] = "Deleting charms"
1413 self
.logger
.debug(logging_text
+ step
)
1414 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1415 for application_name
, deploy_info
in nsr_lcm
["VCA"].items():
1416 if deploy_info
: # TODO it would be desirable having a and deploy_info.get("deployed"):
1417 task
= asyncio
.ensure_future(
1418 self
.n2vc
.RemoveCharms(
1419 deploy_info
['model'],
1421 # self.n2vc_callback,
1426 vca_task_list
.append(task
)
1427 vca_task_dict
[application_name
] = task
1428 # task.add_done_callback(functools.partial(self.n2vc_callback, deploy_info['model'],
1429 # deploy_info['application'], None, db_nsr,
1430 # db_nslcmop, vnf_index))
1431 self
.lcm_ns_tasks
[nsr_id
][nslcmop_id
]["delete_charm:" + application_name
] = task
1432 except Exception as e
:
1433 self
.logger
.debug(logging_text
+ "Failed while deleting charms: {}".format(e
))
1437 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
1439 if nsr_lcm
and nsr_lcm
.get("RO") and nsr_lcm
["RO"].get("nsr_id"):
1440 RO_nsr_id
= nsr_lcm
["RO"]["nsr_id"]
1442 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] = "Deleting ns at RO"
1443 self
.logger
.debug(logging_text
+ step
)
1444 await RO
.delete("ns", RO_nsr_id
)
1445 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1446 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
1447 except ROclient
.ROClientException
as e
:
1448 if e
.http_code
== 404: # not found
1449 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1450 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
1451 self
.logger
.debug(logging_text
+ "RO_ns_id={} already deleted".format(RO_nsr_id
))
1452 elif e
.http_code
== 409: # conflict
1453 failed_detail
.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id
, e
))
1454 self
.logger
.debug(logging_text
+ failed_detail
[-1])
1457 failed_detail
.append("RO_ns_id={} delete error: {}".format(RO_nsr_id
, e
))
1458 self
.logger
.error(logging_text
+ failed_detail
[-1])
1462 if not RO_fail
and nsr_lcm
and nsr_lcm
.get("RO") and nsr_lcm
["RO"].get("nsd_id"):
1463 RO_nsd_id
= nsr_lcm
["RO"]["nsd_id"]
1465 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
1466 "Deleting nsd at RO"
1467 await RO
.delete("nsd", RO_nsd_id
)
1468 self
.logger
.debug(logging_text
+ "RO_nsd_id={} deleted".format(RO_nsd_id
))
1469 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
1470 except ROclient
.ROClientException
as e
:
1471 if e
.http_code
== 404: # not found
1472 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
1473 self
.logger
.debug(logging_text
+ "RO_nsd_id={} already deleted".format(RO_nsd_id
))
1474 elif e
.http_code
== 409: # conflict
1475 failed_detail
.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id
, e
))
1476 self
.logger
.debug(logging_text
+ failed_detail
[-1])
1479 failed_detail
.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id
, e
))
1480 self
.logger
.error(logging_text
+ failed_detail
[-1])
1483 if not RO_fail
and nsr_lcm
and nsr_lcm
.get("RO") and nsr_lcm
["RO"].get("vnfd_id"):
1484 for vnf_id
, RO_vnfd_id
in nsr_lcm
["RO"]["vnfd_id"].items():
1488 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
1489 "Deleting vnfd={} at RO".format(vnf_id
)
1490 await RO
.delete("vnfd", RO_vnfd_id
)
1491 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} deleted".format(RO_vnfd_id
))
1492 db_nsr_update
["_admin.deployed.RO.vnfd_id.{}".format(vnf_id
)] = None
1493 except ROclient
.ROClientException
as e
:
1494 if e
.http_code
== 404: # not found
1495 db_nsr_update
["_admin.deployed.RO.vnfd_id.{}".format(vnf_id
)] = None
1496 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} already deleted ".format(RO_vnfd_id
))
1497 elif e
.http_code
== 409: # conflict
1498 failed_detail
.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id
, e
))
1499 self
.logger
.debug(logging_text
+ failed_detail
[-1])
1501 failed_detail
.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id
, e
))
1502 self
.logger
.error(logging_text
+ failed_detail
[-1])
1505 db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
1506 "Waiting for deletion of configuration charms"
1507 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1508 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1509 await asyncio
.wait(vca_task_list
, timeout
=300)
1510 for application_name
, task
in vca_task_dict
.items():
1511 if task
.cancelled():
1512 failed_detail
.append("VCA[{}] Deletion has been cancelled".format(application_name
))
1514 exc
= task
.exception()
1516 failed_detail
.append("VCA[{}] Deletion exception: {}".format(application_name
, exc
))
1518 db_nsr_update
["_admin.deployed.VCA.{}".format(application_name
)] = None
1520 # TODO Should it be cancelled?!!
1522 failed_detail
.append("VCA[{}] Deletion timeout".format(application_name
))
1525 self
.logger
.error(logging_text
+ " ;".join(failed_detail
))
1526 db_nsr_update
["operational-status"] = "failed"
1527 db_nsr_update
["detailed-status"] = "Deletion errors " + "; ".join(failed_detail
)
1528 db_nslcmop_update
["detailed-status"] = "; ".join(failed_detail
)
1529 db_nslcmop_update
["operationState"] = "FAILED"
1530 db_nslcmop_update
["statusEnteredTime"] = time()
1531 elif db_nslcmop
["operationParams"].get("autoremove"):
1532 self
.db
.del_one("nsrs", {"_id": nsr_id
})
1533 db_nsr_update
.clear()
1534 self
.db
.del_list("nslcmops", {"nsInstanceId": nsr_id
})
1535 db_nslcmop_update
.clear()
1536 self
.db
.del_list("vnfrs", {"nsr-id-ref": nsr_id
})
1537 self
.logger
.debug(logging_text
+ "Delete from database")
1539 db_nsr_update
["operational-status"] = "terminated"
1540 db_nsr_update
["detailed-status"] = "Done"
1541 db_nsr_update
["_admin.nsState"] = "NOT_INSTANTIATED"
1542 db_nslcmop_update
["detailed-status"] = "Done"
1543 db_nslcmop_update
["operationState"] = "COMPLETED"
1544 db_nslcmop_update
["statusEnteredTime"] = time()
1546 await self
.msg
.aiowrite("ns", "terminated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
})
1547 except Exception as e
:
1548 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1549 self
.logger
.debug(logging_text
+ "Exit")
1551 except (ROclient
.ROClientException
, DbException
) as e
:
1552 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
1554 except asyncio
.CancelledError
:
1555 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1556 exc
= "Operation was cancelled"
1557 except Exception as e
:
1558 exc
= traceback
.format_exc()
1559 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
1561 if exc
and db_nslcmop
:
1562 db_nslcmop_update
= {
1563 "detailed-status": "FAILED {}: {}".format(step
, exc
),
1564 "operationState": "FAILED",
1565 "statusEnteredTime": time(),
1567 if db_nslcmop_update
:
1568 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1570 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1571 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_terminate")
1573 async def _ns_execute_primitive(self
, db_deployed
, nsr_name
, member_vnf_index
, vdu_id
, primitive
, primitive_params
):
1575 vdu_id_text
= "vnfd"
1577 vdu_id_text
= vdu_id
1578 application_name
= self
.n2vc
.FormatApplicationName(
1583 vca_deployed
= db_deployed
["VCA"].get(application_name
)
1584 if not vca_deployed
:
1585 raise LcmException("charm for member_vnf_index={} vdu_id={} is not deployed".format(member_vnf_index
,
1587 model_name
= vca_deployed
.get("model")
1588 application_name
= vca_deployed
.get("application")
1589 if not model_name
or not application_name
:
1590 raise LcmException("charm for member_vnf_index={} is not properly deployed".format(member_vnf_index
))
1591 if vca_deployed
["operational-status"] != "active":
1592 raise LcmException("charm for member_vnf_index={} operational_status={} not 'active'".format(
1593 member_vnf_index
, vca_deployed
["operational-status"]))
1594 callback
= None # self.n2vc_callback
1595 callback_args
= () # [db_nsr, db_nslcmop, member_vnf_index, None]
1596 await self
.n2vc
.login()
1597 task
= asyncio
.ensure_future(
1598 self
.n2vc
.ExecutePrimitive(
1601 primitive
, callback
,
1606 # task.add_done_callback(functools.partial(self.n2vc_callback, model_name, application_name, None,
1607 # db_nsr, db_nslcmop, member_vnf_index))
1608 # self.lcm_ns_tasks[nsr_id][nslcmop_id]["action: " + primitive] = task
1609 # wait until completed with timeout
1610 await asyncio
.wait((task
,), timeout
=600)
1612 result
= "FAILED" # by default
1614 if task
.cancelled():
1615 result_detail
= "Task has been cancelled"
1617 exc
= task
.exception()
1619 result_detail
= str(exc
)
1621 # TODO revise with Adam if action is finished and ok when task is done or callback is needed
1622 result
= "COMPLETED"
1623 result_detail
= "Done"
1625 # TODO Should it be cancelled?!!
1627 result_detail
= "timeout"
1628 return result
, result_detail
1630 async def ns_action(self
, nsr_id
, nslcmop_id
):
1631 logging_text
= "Task ns={} action={} ".format(nsr_id
, nslcmop_id
)
1632 self
.logger
.debug(logging_text
+ "Enter")
1633 # get all needed from database
1636 db_nslcmop_update
= None
1639 step
= "Getting information from database"
1640 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1641 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1642 nsr_lcm
= db_nsr
["_admin"].get("deployed")
1643 nsr_name
= db_nsr
["name"]
1644 vnf_index
= db_nslcmop
["operationParams"]["member_vnf_index"]
1645 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
1647 # TODO check if ns is in a proper status
1648 primitive
= db_nslcmop
["operationParams"]["primitive"]
1649 primitive_params
= db_nslcmop
["operationParams"]["primitive_params"]
1650 result
, result_detail
= await self
._ns
_execute
_primitive
(nsr_lcm
, nsr_name
, vnf_index
, vdu_id
, primitive
,
1652 db_nslcmop_update
= {
1653 "detailed-status": result_detail
,
1654 "operationState": result
,
1655 "statusEnteredTime": time()
1657 self
.logger
.debug(logging_text
+ " task Done with result {} {}".format(result
, result_detail
))
1658 return # database update is called inside finally
1660 except (DbException
, LcmException
) as e
:
1661 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
1663 except asyncio
.CancelledError
:
1664 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1665 exc
= "Operation was cancelled"
1666 except Exception as e
:
1667 exc
= traceback
.format_exc()
1668 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
1670 if exc
and db_nslcmop
:
1671 db_nslcmop_update
= {
1672 "detailed-status": "FAILED {}: {}".format(step
, exc
),
1673 "operationState": "FAILED",
1674 "statusEnteredTime": time(),
1676 if db_nslcmop_update
:
1677 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1678 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_action")
1680 async def ns_scale(self
, nsr_id
, nslcmop_id
):
1681 logging_text
= "Task ns={} scale={} ".format(nsr_id
, nslcmop_id
)
1682 self
.logger
.debug(logging_text
+ "Enter")
1683 # get all needed from database
1686 db_nslcmop_update
= {}
1690 step
= "Getting nslcmop from database"
1691 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1692 step
= "Getting nsr from database"
1693 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1694 step
= "Parsing scaling parameters"
1695 db_nsr_update
["operational-status"] = "scaling"
1696 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1697 nsr_lcm
= db_nsr
["_admin"].get("deployed")
1698 RO_nsr_id
= nsr_lcm
["RO"]["nsr_id"]
1699 vnf_index
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
1700 scaling_group
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1701 scaling_type
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleVnfType"]
1702 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
1704 step
= "Getting vnfr from database"
1705 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
1706 step
= "Getting vnfd from database"
1707 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
1708 step
= "Getting scaling-group-descriptor"
1709 for scaling_descriptor
in db_vnfd
["scaling-group-descriptor"]:
1710 if scaling_descriptor
["name"] == scaling_group
:
1713 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
1714 "at vnfd:scaling-group-descriptor".format(scaling_group
))
1716 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
1717 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
1718 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
1721 # TODO check if ns is in a proper status
1722 step
= "Sending scale order to RO"
1724 if not db_nsr
["_admin"].get("scaling-group"):
1725 self
.update_db_2("nsrs", nsr_id
, {"_admin.scaling-group": [{"name": scaling_group
, "nb-scale-op": 0}]})
1726 admin_scale_index
= 0
1728 for admin_scale_index
, admin_scale_info
in enumerate(db_nsr
["_admin"]["scaling-group"]):
1729 if admin_scale_info
["name"] == scaling_group
:
1730 nb_scale_op
= admin_scale_info
.get("nb-scale-op", 0)
1732 RO_scaling_info
= []
1733 vdu_scaling_info
= {"scaling_group_name": scaling_group
, "vdu": []}
1734 if scaling_type
== "SCALE_OUT":
1735 # count if max-instance-count is reached
1736 if "max-instance-count" in scaling_descriptor
and scaling_descriptor
["max-instance-count"] is not None:
1737 max_instance_count
= int(scaling_descriptor
["max-instance-count"])
1738 if nb_scale_op
>= max_instance_count
:
1739 raise LcmException("reached the limit of {} (max-instance-count) scaling-out operations for the"
1740 " scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
1741 nb_scale_op
= nb_scale_op
+ 1
1742 vdu_scaling_info
["scaling_direction"] = "OUT"
1743 vdu_scaling_info
["vdu-create"] = {}
1744 for vdu_scale_info
in scaling_descriptor
["vdu"]:
1745 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
1746 "type": "create", "count": vdu_scale_info
.get("count", 1)})
1747 vdu_scaling_info
["vdu-create"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
1748 elif scaling_type
== "SCALE_IN":
1749 # count if min-instance-count is reached
1750 if "min-instance-count" in scaling_descriptor
and scaling_descriptor
["min-instance-count"] is not None:
1751 min_instance_count
= int(scaling_descriptor
["min-instance-count"])
1752 if nb_scale_op
<= min_instance_count
:
1753 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
1754 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
1755 nb_scale_op
= nb_scale_op
- 1
1756 vdu_scaling_info
["scaling_direction"] = "IN"
1757 vdu_scaling_info
["vdu-delete"] = {}
1758 for vdu_scale_info
in scaling_descriptor
["vdu"]:
1759 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
1760 "type": "delete", "count": vdu_scale_info
.get("count", 1)})
1761 vdu_scaling_info
["vdu-delete"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
1763 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
1764 if vdu_scaling_info
["scaling_direction"] == "IN":
1765 for vdur
in reversed(db_vnfr
["vdur"]):
1766 if vdu_scaling_info
["vdu-delete"].get(vdur
["vdu-id-ref"]):
1767 vdu_scaling_info
["vdu-delete"][vdur
["vdu-id-ref"]] -= 1
1768 vdu_scaling_info
["vdu"].append({
1769 "name": vdur
["name"],
1770 "vdu_id": vdur
["vdu-id-ref"],
1773 for interface
in vdur
["interfaces"]:
1774 vdu_scaling_info
["vdu"][-1]["interface"].append({
1775 "name": interface
["name"],
1776 "ip_address": interface
["ip-address"],
1777 "mac_address": interface
.get("mac-address"),
1779 del vdu_scaling_info
["vdu-delete"]
1781 # execute primitive service PRE-SCALING
1782 step
= "Executing pre-scale vnf-config-primitive"
1783 if scaling_descriptor
.get("scaling-config-action"):
1784 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
1785 if scaling_config_action
.get("trigger") and scaling_config_action
["trigger"] == "pre-scale-in" \
1786 and scaling_type
== "SCALE_IN":
1787 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
1788 step
= db_nslcmop_update
["detailed-status"] = \
1789 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive
)
1790 # look for primitive
1791 primitive_params
= {}
1792 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
1793 if config_primitive
["name"] == vnf_config_primitive
:
1794 for parameter
in config_primitive
.get("parameter", ()):
1795 if 'default-value' in parameter
and \
1796 parameter
['default-value'] == "<VDU_SCALE_INFO>":
1797 primitive_params
[parameter
["name"]] = yaml
.safe_dump(vdu_scaling_info
,
1798 default_flow_style
=True,
1803 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
1804 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-cnfiguration:config-"
1805 "primitive".format(scaling_group
, config_primitive
))
1806 result
, result_detail
= await self
._ns
_execute
_primitive
(nsr_lcm
, vnf_index
,
1807 vnf_config_primitive
, primitive_params
)
1808 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
1809 vnf_config_primitive
, result
, result_detail
))
1810 if result
== "FAILED":
1811 raise LcmException(result_detail
)
1814 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
1815 RO_desc
= await RO
.create_action("ns", RO_nsr_id
, {"vdu-scaling": RO_scaling_info
})
1816 db_nsr_update
["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index
)] = nb_scale_op
1817 db_nsr_update
["_admin.scaling-group.{}.time".format(admin_scale_index
)] = time()
1818 # TODO mark db_nsr_update as scaling
1820 RO_nslcmop_id
= RO_desc
["instance_action_id"]
1821 db_nslcmop_update
["_admin.deploy.RO"] = RO_nslcmop_id
1823 RO_task_done
= False
1824 step
= detailed_status
= "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id
)
1825 detailed_status_old
= None
1826 self
.logger
.debug(logging_text
+ step
)
1828 deployment_timeout
= 1 * 3600 # One hours
1829 while deployment_timeout
> 0:
1830 if not RO_task_done
:
1831 desc
= await RO
.show("ns", item_id_name
=RO_nsr_id
, extra_item
="action",
1832 extra_item_id
=RO_nslcmop_id
)
1833 ns_status
, ns_status_info
= RO
.check_action_status(desc
)
1834 if ns_status
== "ERROR":
1835 raise ROclient
.ROClientException(ns_status_info
)
1836 elif ns_status
== "BUILD":
1837 detailed_status
= step
+ "; {}".format(ns_status_info
)
1838 elif ns_status
== "ACTIVE":
1840 step
= detailed_status
= "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id
)
1841 self
.logger
.debug(logging_text
+ step
)
1843 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
1845 desc
= await RO
.show("ns", RO_nsr_id
)
1846 ns_status
, ns_status_info
= RO
.check_ns_status(desc
)
1847 if ns_status
== "ERROR":
1848 raise ROclient
.ROClientException(ns_status_info
)
1849 elif ns_status
== "BUILD":
1850 detailed_status
= step
+ "; {}".format(ns_status_info
)
1851 elif ns_status
== "ACTIVE":
1852 step
= detailed_status
= "Waiting for management IP address reported by the VIM"
1854 desc
= await RO
.show("ns", RO_nsr_id
)
1855 nsr_lcm
["nsr_ip"] = RO
.get_ns_vnf_info(desc
)
1857 except ROclient
.ROClientException
as e
:
1858 if e
.http_code
!= 409: # IP address is not ready return code is 409 CONFLICT
1861 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
1862 if detailed_status
!= detailed_status_old
:
1863 detailed_status_old
= db_nslcmop_update
["detailed-status"] = detailed_status
1864 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1866 await asyncio
.sleep(5, loop
=self
.loop
)
1867 deployment_timeout
-= 5
1868 if deployment_timeout
<= 0:
1869 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
1871 step
= "Updating VNFRs"
1872 self
.ns_update_vnfr({db_vnfr
["member-vnf-index-ref"]: db_vnfr
}, desc
)
1874 # update VDU_SCALING_INFO with the obtained ip_addresses
1875 if vdu_scaling_info
["scaling_direction"] == "OUT":
1876 for vdur
in reversed(db_vnfr
["vdur"]):
1877 if vdu_scaling_info
["vdu-create"].get(vdur
["vdu-id-ref"]):
1878 vdu_scaling_info
["vdu-create"][vdur
["vdu-id-ref"]] -= 1
1879 vdu_scaling_info
["vdu"].append({
1880 "name": vdur
["name"],
1881 "vdu_id": vdur
["vdu-id-ref"],
1884 for interface
in vdur
["interfaces"]:
1885 vdu_scaling_info
["vdu"][-1]["interface"].append({
1886 "name": interface
["name"],
1887 "ip_address": interface
["ip-address"],
1888 "mac_address": interface
.get("mac-address"),
1890 del vdu_scaling_info
["vdu-create"]
1893 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1895 # execute primitive service POST-SCALING
1896 step
= "Executing post-scale vnf-config-primitive"
1897 if scaling_descriptor
.get("scaling-config-action"):
1898 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
1899 if scaling_config_action
.get("trigger") and scaling_config_action
["trigger"] == "post-scale-out" \
1900 and scaling_type
== "SCALE_OUT":
1901 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
1902 step
= db_nslcmop_update
["detailed-status"] = \
1903 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive
)
1904 # look for primitive
1905 primitive_params
= {}
1906 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
1907 if config_primitive
["name"] == vnf_config_primitive
:
1908 for parameter
in config_primitive
.get("parameter", ()):
1909 if 'default-value' in parameter
and \
1910 parameter
['default-value'] == "<VDU_SCALE_INFO>":
1911 primitive_params
[parameter
["name"]] = yaml
.safe_dump(vdu_scaling_info
,
1912 default_flow_style
=True,
1916 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
1917 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
1918 "match any vnf-cnfiguration:config-primitive".format(scaling_group
,
1920 result
, result_detail
= await self
._ns
_execute
_primitive
(nsr_lcm
, vnf_index
,
1921 vnf_config_primitive
, primitive_params
)
1922 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
1923 vnf_config_primitive
, result
, result_detail
))
1924 if result
== "FAILED":
1925 raise LcmException(result_detail
)
1927 db_nslcmop_update
["operationState"] = "COMPLETED"
1928 db_nslcmop_update
["statusEnteredTime"] = time()
1929 db_nslcmop_update
["detailed-status"] = "done"
1930 db_nsr_update
["detailed-status"] = "done"
1931 db_nsr_update
["operational-status"] = "running"
1933 await self
.msg
.aiowrite("ns", "scaled", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
})
1935 # await asyncio.sleep(cooldown_time)
1936 # await self.msg.aiowrite("ns", "scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
1937 except Exception as e
:
1938 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1939 self
.logger
.debug(logging_text
+ "Exit Ok")
1941 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
1942 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
1944 except asyncio
.CancelledError
:
1945 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1946 exc
= "Operation was cancelled"
1947 except Exception as e
:
1948 exc
= traceback
.format_exc()
1949 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
1953 db_nslcmop_update
= {
1954 "detailed-status": "FAILED {}: {}".format(step
, exc
),
1955 "operationState": "FAILED",
1956 "statusEnteredTime": time(),
1959 db_nsr_update
["operational-status"] = "FAILED {}: {}".format(step
, exc
),
1960 db_nsr_update
["detailed-status"] = "failed"
1961 if db_nslcmop_update
:
1962 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1964 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1965 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_scale")
1967 async def test(self
, param
=None):
1968 self
.logger
.debug("Starting/Ending test task: {}".format(param
))
1970 async def kafka_ping(self
):
1971 self
.logger
.debug("Task kafka_ping Enter")
1972 consecutive_errors
= 0
1974 kafka_has_received
= False
1975 self
.pings_not_received
= 1
1978 await self
.msg
.aiowrite("admin", "ping", {"from": "lcm", "to": "lcm"}, self
.loop
)
1979 # time between pings are low when it is not received and at starting
1980 wait_time
= 5 if not kafka_has_received
else 120
1981 if not self
.pings_not_received
:
1982 kafka_has_received
= True
1983 self
.pings_not_received
+= 1
1984 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
1985 if self
.pings_not_received
> 10:
1986 raise LcmException("It is not receiving pings from Kafka bus")
1987 consecutive_errors
= 0
1989 except LcmException
:
1991 except Exception as e
:
1992 # if not first_start is the first time after starting. So leave more time and wait
1993 # to allow kafka starts
1994 if consecutive_errors
== 8 if not first_start
else 30:
1995 self
.logger
.error("Task kafka_read task exit error too many errors. Exception: {}".format(e
))
1997 consecutive_errors
+= 1
1998 self
.logger
.error("Task kafka_read retrying after Exception {}".format(e
))
1999 wait_time
= 1 if not first_start
else 5
2000 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
2002 async def kafka_read(self
):
2003 self
.logger
.debug("Task kafka_read Enter")
2005 # future = asyncio.Future()
2006 consecutive_errors
= 0
2008 while consecutive_errors
< 10:
2010 topics
= ("admin", "ns", "vim_account", "sdn")
2011 topic
, command
, params
= await self
.msg
.aioread(topics
, self
.loop
)
2012 if topic
!= "admin" and command
!= "ping":
2013 self
.logger
.debug("Task kafka_read receives {} {}: {}".format(topic
, command
, params
))
2014 consecutive_errors
= 0
2017 if command
== "exit":
2020 elif command
.startswith("#"):
2022 elif command
== "echo":
2027 elif command
== "test":
2028 asyncio
.Task(self
.test(params
), loop
=self
.loop
)
2031 if topic
== "admin":
2032 if command
== "ping" and params
["to"] == "lcm" and params
["from"] == "lcm":
2033 self
.pings_not_received
= 0
2036 if command
== "instantiate":
2037 # self.logger.debug("Deploying NS {}".format(nsr_id))
2039 nslcmop_id
= nslcmop
["_id"]
2040 nsr_id
= nslcmop
["nsInstanceId"]
2041 task
= asyncio
.ensure_future(self
.ns_instantiate(nsr_id
, nslcmop_id
))
2042 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_instantiate", task
)
2044 elif command
== "terminate":
2045 # self.logger.debug("Deleting NS {}".format(nsr_id))
2047 nslcmop_id
= nslcmop
["_id"]
2048 nsr_id
= nslcmop
["nsInstanceId"]
2049 self
.lcm_tasks
.cancel(topic
, nsr_id
)
2050 task
= asyncio
.ensure_future(self
.ns_terminate(nsr_id
, nslcmop_id
))
2051 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_terminate", task
)
2053 elif command
== "action":
2054 # self.logger.debug("Update NS {}".format(nsr_id))
2056 nslcmop_id
= nslcmop
["_id"]
2057 nsr_id
= nslcmop
["nsInstanceId"]
2058 task
= asyncio
.ensure_future(self
.ns_action(nsr_id
, nslcmop_id
))
2059 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_action", task
)
2061 elif command
== "scale":
2062 # self.logger.debug("Update NS {}".format(nsr_id))
2064 nslcmop_id
= nslcmop
["_id"]
2065 nsr_id
= nslcmop
["nsInstanceId"]
2066 task
= asyncio
.ensure_future(self
.ns_scale(nsr_id
, nslcmop_id
))
2067 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_scale", task
)
2069 elif command
== "show":
2071 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2072 print("nsr:\n _id={}\n operational-status: {}\n config-status: {}"
2073 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
2074 "".format(nsr_id
, db_nsr
["operational-status"], db_nsr
["config-status"],
2075 db_nsr
["detailed-status"],
2076 db_nsr
["_admin"]["deployed"], self
.lcm_ns_tasks
.get(nsr_id
)))
2077 except Exception as e
:
2078 print("nsr {} not found: {}".format(nsr_id
, e
))
2081 elif command
== "deleted":
2082 continue # TODO cleaning of task just in case should be done
2083 elif command
in ("terminated", "instantiated", "scaled", "actioned"): # "scaled-cooldown-time"
2085 elif topic
== "vim_account":
2086 vim_id
= params
["_id"]
2087 if command
== "create":
2088 task
= asyncio
.ensure_future(self
.vim_create(params
, order_id
))
2089 self
.lcm_tasks
.register("vim_account", vim_id
, order_id
, "vim_create", task
)
2091 elif command
== "delete":
2092 self
.lcm_tasks
.cancel(topic
, vim_id
)
2093 task
= asyncio
.ensure_future(self
.vim_delete(vim_id
, order_id
))
2094 self
.lcm_tasks
.register("vim_account", vim_id
, order_id
, "vim_delete", task
)
2096 elif command
== "show":
2097 print("not implemented show with vim_account")
2100 elif command
== "edit":
2101 task
= asyncio
.ensure_future(self
.vim_edit(params
, order_id
))
2102 self
.lcm_tasks
.register("vim_account", vim_id
, order_id
, "vim_edit", task
)
2104 elif topic
== "sdn":
2105 _sdn_id
= params
["_id"]
2106 if command
== "create":
2107 task
= asyncio
.ensure_future(self
.sdn_create(params
, order_id
))
2108 self
.lcm_tasks
.register("sdn", _sdn_id
, order_id
, "sdn_create", task
)
2110 elif command
== "delete":
2111 self
.lcm_tasks
.cancel(topic
, _sdn_id
)
2112 task
= asyncio
.ensure_future(self
.sdn_delete(_sdn_id
, order_id
))
2113 self
.lcm_tasks
.register("sdn", _sdn_id
, order_id
, "sdn_delete", task
)
2115 elif command
== "edit":
2116 task
= asyncio
.ensure_future(self
.sdn_edit(params
, order_id
))
2117 self
.lcm_tasks
.register("sdn", _sdn_id
, order_id
, "sdn_edit", task
)
2119 self
.logger
.critical("unknown topic {} and command '{}'".format(topic
, command
))
2120 except Exception as e
:
2121 # if not first_start is the first time after starting. So leave more time and wait
2122 # to allow kafka starts
2123 if consecutive_errors
== 8 if not first_start
else 30:
2124 self
.logger
.error("Task kafka_read task exit error too many errors. Exception: {}".format(e
))
2126 consecutive_errors
+= 1
2127 self
.logger
.error("Task kafka_read retrying after Exception {}".format(e
))
2128 wait_time
= 2 if not first_start
else 5
2129 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
2131 # self.logger.debug("Task kafka_read terminating")
2132 self
.logger
.debug("Task kafka_read exit")
2135 self
.loop
= asyncio
.get_event_loop()
2138 self
.loop
.run_until_complete(self
.check_RO_version())
2140 self
.loop
.run_until_complete(asyncio
.gather(
2145 # self.logger.debug("Terminating cancelling creation tasks")
2146 # self.lcm_tasks.cancel("ALL", "create")
2148 # while self.is_pending_tasks():
2149 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
2150 # await asyncio.sleep(2, loop=self.loop)
2153 # self.lcm_tasks.cancel("ALL", "ALL")
2157 self
.db
.db_disconnect()
2159 self
.msg
.disconnect()
2161 self
.fs
.fs_disconnect()
2163 def read_config_file(self
, config_file
):
2164 # TODO make a [ini] + yaml inside parser
2165 # the configparser library is not suitable, because it does not admit comments at the end of line,
2166 # and not parse integer or boolean
2168 with
open(config_file
) as f
:
2170 for k
, v
in environ
.items():
2171 if not k
.startswith("OSMLCM_"):
2173 k_items
= k
.lower().split("_")
2176 for k_item
in k_items
[1:-1]:
2177 if k_item
in ("ro", "vca"):
2178 # put in capital letter
2179 k_item
= k_item
.upper()
2181 if k_items
[-1] == "port":
2182 c
[k_items
[-1]] = int(v
)
2185 except Exception as e
:
2186 self
.logger
.warn("skipping environ '{}' on exception '{}'".format(k
, e
))
2189 except Exception as e
:
2190 self
.logger
.critical("At config file '{}': {}".format(config_file
, e
))
2195 print("""Usage: {} [options]
2196 -c|--config [configuration_file]: loads the configuration file (default: ./nbi.cfg)
2197 -h|--help: shows this help
2198 """.format(sys
.argv
[0]))
2199 # --log-socket-host HOST: send logs to this host")
2200 # --log-socket-port PORT: send logs using this port (default: 9022)")
2203 if __name__
== '__main__':
2205 # load parameters and configuration
2206 opts
, args
= getopt
.getopt(sys
.argv
[1:], "hc:", ["config=", "help"])
2207 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
2210 if o
in ("-h", "--help"):
2213 elif o
in ("-c", "--config"):
2215 # elif o == "--log-socket-port":
2216 # log_socket_port = a
2217 # elif o == "--log-socket-host":
2218 # log_socket_host = a
2219 # elif o == "--log-file":
2222 assert False, "Unhandled option"
2224 if not path
.isfile(config_file
):
2225 print("configuration file '{}' that not exist".format(config_file
), file=sys
.stderr
)
2228 for config_file
in (__file__
[:__file__
.rfind(".")] + ".cfg", "./lcm.cfg", "/etc/osm/lcm.cfg"):
2229 if path
.isfile(config_file
):
2232 print("No configuration file 'nbi.cfg' found neither at local folder nor at /etc/osm/", file=sys
.stderr
)
2234 lcm
= Lcm(config_file
)
2236 except (LcmException
, getopt
.GetoptError
) as e
:
2237 print(str(e
), file=sys
.stderr
)