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]
34 # uncomment if LCM is installed as library and installed, and get them from __init__.py
35 lcm_version
= '0.1.12'
36 lcm_version_date
= '2018-08-23'
39 class LcmException(Exception):
45 Implements a registry of task needed for later cancelation, look for related tasks that must be completed before
46 etc. It stores a four level dict
47 First level is the topic, ns, vim_account, sdn
48 Second level is the _id
49 Third level is the operation id
50 Fourth level is a descriptive name, the value is the task class
54 self
.task_registry
= {
60 def register(self
, topic
, _id
, op_id
, task_name
, task
):
63 :param topic: Can be "ns", "vim_account", "sdn"
64 :param _id: _id of the related item
65 :param op_id: id of the operation of the related item
66 :param task_name: Task descriptive name, as create, instantiate, terminate. Must be unique in this op_id
67 :param task: Task class
70 if _id
not in self
.task_registry
[topic
]:
71 self
.task_registry
[topic
][_id
] = OrderedDict()
72 if op_id
not in self
.task_registry
[topic
][_id
]:
73 self
.task_registry
[topic
][_id
][op_id
] = {task_name
: task
}
75 self
.task_registry
[topic
][_id
][op_id
][task_name
] = task
76 # print("registering task", topic, _id, op_id, task_name, task)
78 def remove(self
, topic
, _id
, op_id
, task_name
=None):
80 When task is ended, it should removed. It ignores missing tasks
81 :param topic: Can be "ns", "vim_account", "sdn"
82 :param _id: _id of the related item
83 :param op_id: id of the operation of the related item
84 :param task_name: Task descriptive name. If note it deletes all
87 if not self
.task_registry
[topic
].get(_id
) or not self
.task_registry
[topic
][_id
].get(op_id
):
90 # print("deleting tasks", topic, _id, op_id, self.task_registry[topic][_id][op_id])
91 del self
.task_registry
[topic
][_id
][op_id
]
92 elif task_name
in self
.task_registry
[topic
][_id
][op_id
]:
93 # print("deleting tasks", topic, _id, op_id, task_name, self.task_registry[topic][_id][op_id][task_name])
94 del self
.task_registry
[topic
][_id
][op_id
][task_name
]
95 if not self
.task_registry
[topic
][_id
][op_id
]:
96 del self
.task_registry
[topic
][_id
][op_id
]
97 if not self
.task_registry
[topic
][_id
]:
98 del self
.task_registry
[topic
][_id
]
100 def lookfor_related(self
, topic
, _id
, my_op_id
=None):
103 if _id
not in self
.task_registry
[topic
]:
104 return "", task_name_list
105 for op_id
in reversed(self
.task_registry
[topic
][_id
]):
107 if my_op_id
== op_id
:
108 my_op_id
= None # so that the next task is taken
111 for task_name
, task
in self
.task_registry
[topic
][_id
][op_id
].items():
112 task_list
.append(task
)
113 task_name_list
.append(task_name
)
115 return ", ".join(task_name_list
), task_list
117 def cancel(self
, topic
, _id
, target_op_id
=None, target_task_name
=None):
119 Cancel all active tasks of a concrete ns, vim_account, sdn identified for _id. If op_id is supplied only this is
120 cancelled, and the same with task_name
122 if not self
.task_registry
[topic
].get(_id
):
124 for op_id
in reversed(self
.task_registry
[topic
][_id
]):
125 if target_op_id
and target_op_id
!= op_id
:
127 for task_name
, task
in self
.task_registry
[topic
][_id
][op_id
].items():
128 if target_task_name
and target_task_name
!= task_name
:
130 result
= task
.cancel()
132 self
.logger
.debug("{} _id={} order_id={} task={} cancelled".format(topic
, _id
, op_id
, task_name
))
137 def __init__(self
, config_file
):
139 Init, Connect to database, filesystem storage, and messaging
140 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
147 self
.pings_not_received
= 1
149 # contains created tasks/futures to be able to cancel
150 self
.lcm_tasks
= TaskRegistry()
152 self
.logger
= logging
.getLogger('lcm')
154 config
= self
.read_config_file(config_file
)
157 "endpoint_url": "http://{}:{}/openmano".format(config
["RO"]["host"], config
["RO"]["port"]),
158 "tenant": config
.get("tenant", "osm"),
159 "logger_name": "lcm.ROclient",
163 self
.vca
= config
["VCA"] # TODO VCA
167 log_format_simple
= "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
168 log_formatter_simple
= logging
.Formatter(log_format_simple
, datefmt
='%Y-%m-%dT%H:%M:%S')
169 config
["database"]["logger_name"] = "lcm.db"
170 config
["storage"]["logger_name"] = "lcm.fs"
171 config
["message"]["logger_name"] = "lcm.msg"
172 if config
["global"].get("logfile"):
173 file_handler
= logging
.handlers
.RotatingFileHandler(config
["global"]["logfile"],
174 maxBytes
=100e6
, backupCount
=9, delay
=0)
175 file_handler
.setFormatter(log_formatter_simple
)
176 self
.logger
.addHandler(file_handler
)
177 if not config
["global"].get("nologging"):
178 str_handler
= logging
.StreamHandler()
179 str_handler
.setFormatter(log_formatter_simple
)
180 self
.logger
.addHandler(str_handler
)
182 if config
["global"].get("loglevel"):
183 self
.logger
.setLevel(config
["global"]["loglevel"])
185 # logging other modules
186 for k1
, logname
in {"message": "lcm.msg", "database": "lcm.db", "storage": "lcm.fs"}.items():
187 config
[k1
]["logger_name"] = logname
188 logger_module
= logging
.getLogger(logname
)
189 if config
[k1
].get("logfile"):
190 file_handler
= logging
.handlers
.RotatingFileHandler(config
[k1
]["logfile"],
191 maxBytes
=100e6
, backupCount
=9, delay
=0)
192 file_handler
.setFormatter(log_formatter_simple
)
193 logger_module
.addHandler(file_handler
)
194 if config
[k1
].get("loglevel"):
195 logger_module
.setLevel(config
[k1
]["loglevel"])
196 self
.logger
.critical("starting osm/lcm version {} {}".format(lcm_version
, lcm_version_date
))
199 server
=config
['VCA']['host'],
200 port
=config
['VCA']['port'],
201 user
=config
['VCA']['user'],
202 secret
=config
['VCA']['secret'],
203 # TODO: This should point to the base folder where charms are stored,
204 # if there is a common one (like object storage). Otherwise, leave
205 # it unset and pass it via DeployCharms
206 # artifacts=config['VCA'][''],
209 # check version of N2VC
210 # TODO enhance with int conversion or from distutils.version import LooseVersion
211 # or with list(map(int, version.split(".")))
212 if N2VC_version
< "0.0.2":
213 raise LcmException("Not compatible osm/N2VC version '{}'. Needed '0.0.2' or higher".format(N2VC_version
))
216 # TODO check database version
217 if config
["database"]["driver"] == "mongo":
218 self
.db
= dbmongo
.DbMongo()
219 self
.db
.db_connect(config
["database"])
220 elif config
["database"]["driver"] == "memory":
221 self
.db
= dbmemory
.DbMemory()
222 self
.db
.db_connect(config
["database"])
224 raise LcmException("Invalid configuration param '{}' at '[database]':'driver'".format(
225 config
["database"]["driver"]))
227 if config
["storage"]["driver"] == "local":
228 self
.fs
= fslocal
.FsLocal()
229 self
.fs
.fs_connect(config
["storage"])
231 raise LcmException("Invalid configuration param '{}' at '[storage]':'driver'".format(
232 config
["storage"]["driver"]))
234 if config
["message"]["driver"] == "local":
235 self
.msg
= msglocal
.MsgLocal()
236 self
.msg
.connect(config
["message"])
237 elif config
["message"]["driver"] == "kafka":
238 self
.msg
= msgkafka
.MsgKafka()
239 self
.msg
.connect(config
["message"])
241 raise LcmException("Invalid configuration param '{}' at '[message]':'driver'".format(
242 config
["storage"]["driver"]))
243 except (DbException
, FsException
, MsgException
) as e
:
244 self
.logger
.critical(str(e
), exc_info
=True)
245 raise LcmException(str(e
))
247 async def check_RO_version(self
):
249 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
250 RO_version
= await RO
.get_version()
251 if RO_version
< min_RO_version
:
252 raise LcmException("Not compatible osm/RO version '{}.{}.{}'. Needed '{}.{}.{}' or higher".format(
253 *RO_version
, *min_RO_version
255 except ROclient
.ROClientException
as e
:
256 self
.logger
.critical("Error while conneting to osm/RO " + str(e
), exc_info
=True)
257 raise LcmException(str(e
))
259 def update_db_2(self
, item
, _id
, _desc
):
261 Updates database with _desc information. Upon success _desc is cleared
270 self
.db
.set_one(item
, {"_id": _id
}, _desc
)
272 except DbException
as e
:
273 self
.logger
.error("Updating {} _id={} with '{}'. Error: {}".format(item
, _id
, _desc
, e
))
275 async def vim_create(self
, vim_content
, order_id
):
276 vim_id
= vim_content
["_id"]
277 logging_text
= "Task vim_create={} ".format(vim_id
)
278 self
.logger
.debug(logging_text
+ "Enter")
284 step
= "Getting vim-id='{}' from db".format(vim_id
)
285 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_id
})
286 db_vim_update
["_admin.deployed.RO"] = None
287 if vim_content
.get("config") and vim_content
["config"].get("sdn-controller"):
288 step
= "Getting sdn-controller-id='{}' from db".format(vim_content
["config"]["sdn-controller"])
289 db_sdn
= self
.db
.get_one("sdns", {"_id": vim_content
["config"]["sdn-controller"]})
290 if db_sdn
.get("_admin") and db_sdn
["_admin"].get("deployed") and db_sdn
["_admin"]["deployed"].get("RO"):
291 RO_sdn_id
= db_sdn
["_admin"]["deployed"]["RO"]
293 raise LcmException("sdn-controller={} is not available. Not deployed at RO".format(
294 vim_content
["config"]["sdn-controller"]))
296 step
= "Creating vim at RO"
297 db_vim_update
["_admin.detailed-status"] = step
298 self
.update_db_2("vim_accounts", vim_id
, db_vim_update
)
299 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
300 vim_RO
= deepcopy(vim_content
)
301 vim_RO
.pop("_id", None)
302 vim_RO
.pop("_admin", None)
303 vim_RO
.pop("schema_version", None)
304 vim_RO
.pop("schema_type", None)
305 vim_RO
.pop("vim_tenant_name", None)
306 vim_RO
["type"] = vim_RO
.pop("vim_type")
307 vim_RO
.pop("vim_user", None)
308 vim_RO
.pop("vim_password", None)
310 vim_RO
["config"]["sdn-controller"] = RO_sdn_id
311 desc
= await RO
.create("vim", descriptor
=vim_RO
)
312 RO_vim_id
= desc
["uuid"]
313 db_vim_update
["_admin.deployed.RO"] = RO_vim_id
315 step
= "Creating vim_account at RO"
316 db_vim_update
["_admin.detailed-status"] = step
317 self
.update_db_2("vim_accounts", vim_id
, db_vim_update
)
319 vim_account_RO
= {"vim_tenant_name": vim_content
["vim_tenant_name"],
320 "vim_username": vim_content
["vim_user"],
321 "vim_password": vim_content
["vim_password"]
323 if vim_RO
.get("config"):
324 vim_account_RO
["config"] = vim_RO
["config"]
325 if "sdn-controller" in vim_account_RO
["config"]:
326 del vim_account_RO
["config"]["sdn-controller"]
327 if "sdn-port-mapping" in vim_account_RO
["config"]:
328 del vim_account_RO
["config"]["sdn-port-mapping"]
329 desc
= await RO
.attach_datacenter(RO_vim_id
, descriptor
=vim_account_RO
)
330 db_vim_update
["_admin.deployed.RO-account"] = desc
["uuid"]
331 db_vim_update
["_admin.operationalState"] = "ENABLED"
332 db_vim_update
["_admin.detailed-status"] = "Done"
334 # await asyncio.sleep(15) # TODO remove. This is for test
335 self
.logger
.debug(logging_text
+ "Exit Ok RO_vim_id={}".format(RO_vim_id
))
338 except (ROclient
.ROClientException
, DbException
) as e
:
339 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
341 except Exception as e
:
342 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
346 db_vim_update
["_admin.operationalState"] = "ERROR"
347 db_vim_update
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
349 self
.update_db_2("vim_accounts", vim_id
, db_vim_update
)
350 self
.lcm_tasks
.remove("vim_account", vim_id
, order_id
)
352 async def vim_edit(self
, vim_content
, order_id
):
353 vim_id
= vim_content
["_id"]
354 logging_text
= "Task vim_edit={} ".format(vim_id
)
355 self
.logger
.debug(logging_text
+ "Enter")
361 step
= "Getting vim-id='{}' from db".format(vim_id
)
363 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_id
})
365 # look if previous tasks in process
366 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account", vim_id
, order_id
)
368 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
369 self
.logger
.debug(logging_text
+ step
)
370 # TODO write this to database
371 await asyncio
.wait(task_dependency
, timeout
=3600)
373 if db_vim
.get("_admin") and db_vim
["_admin"].get("deployed") and db_vim
["_admin"]["deployed"].get("RO"):
374 if vim_content
.get("config") and vim_content
["config"].get("sdn-controller"):
375 step
= "Getting sdn-controller-id='{}' from db".format(vim_content
["config"]["sdn-controller"])
376 db_sdn
= self
.db
.get_one("sdns", {"_id": vim_content
["config"]["sdn-controller"]})
378 # look if previous tasks in process
379 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("sdn", db_sdn
["_id"])
381 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
382 self
.logger
.debug(logging_text
+ step
)
383 # TODO write this to database
384 await asyncio
.wait(task_dependency
, timeout
=3600)
386 if db_sdn
.get("_admin") and db_sdn
["_admin"].get("deployed") and db_sdn
["_admin"]["deployed"].get(
388 RO_sdn_id
= db_sdn
["_admin"]["deployed"]["RO"]
390 raise LcmException("sdn-controller={} is not available. Not deployed at RO".format(
391 vim_content
["config"]["sdn-controller"]))
393 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
394 step
= "Editing vim at RO"
395 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
396 vim_RO
= deepcopy(vim_content
)
397 vim_RO
.pop("_id", None)
398 vim_RO
.pop("_admin", None)
399 vim_RO
.pop("schema_version", None)
400 vim_RO
.pop("schema_type", None)
401 vim_RO
.pop("vim_tenant_name", None)
402 if "vim_type" in vim_RO
:
403 vim_RO
["type"] = vim_RO
.pop("vim_type")
404 vim_RO
.pop("vim_user", None)
405 vim_RO
.pop("vim_password", None)
407 vim_RO
["config"]["sdn-controller"] = RO_sdn_id
408 # TODO make a deep update of sdn-port-mapping
410 await RO
.edit("vim", RO_vim_id
, descriptor
=vim_RO
)
412 step
= "Editing vim-account at RO tenant"
414 if "config" in vim_content
:
415 if "sdn-controller" in vim_content
["config"]:
416 del vim_content
["config"]["sdn-controller"]
417 if "sdn-port-mapping" in vim_content
["config"]:
418 del vim_content
["config"]["sdn-port-mapping"]
419 if not vim_content
["config"]:
420 del vim_content
["config"]
421 for k
in ("vim_tenant_name", "vim_password", "config"):
423 vim_account_RO
[k
] = vim_content
[k
]
424 if "vim_user" in vim_content
:
425 vim_content
["vim_username"] = vim_content
["vim_user"]
426 # vim_account must be edited always even if empty in order to ensure changes are translated to RO
427 # vim_thread. RO will remove and relaunch a new thread for this vim_account
428 await RO
.edit("vim_account", RO_vim_id
, descriptor
=vim_account_RO
)
429 db_vim_update
["_admin.operationalState"] = "ENABLED"
431 self
.logger
.debug(logging_text
+ "Exit Ok RO_vim_id={}".format(RO_vim_id
))
434 except (ROclient
.ROClientException
, DbException
) as e
:
435 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
437 except Exception as e
:
438 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
442 db_vim_update
["_admin.operationalState"] = "ERROR"
443 db_vim_update
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
445 self
.update_db_2("vim_accounts", vim_id
, db_vim_update
)
446 self
.lcm_tasks
.remove("vim_account", vim_id
, order_id
)
448 async def vim_delete(self
, vim_id
, order_id
):
449 logging_text
= "Task vim_delete={} ".format(vim_id
)
450 self
.logger
.debug(logging_text
+ "Enter")
454 step
= "Getting vim from db"
456 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_id
})
457 if db_vim
.get("_admin") and db_vim
["_admin"].get("deployed") and db_vim
["_admin"]["deployed"].get("RO"):
458 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
459 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
460 step
= "Detaching vim from RO tenant"
462 await RO
.detach_datacenter(RO_vim_id
)
463 except ROclient
.ROClientException
as e
:
464 if e
.http_code
== 404: # not found
465 self
.logger
.debug(logging_text
+ "RO_vim_id={} already detached".format(RO_vim_id
))
469 step
= "Deleting vim from RO"
471 await RO
.delete("vim", RO_vim_id
)
472 except ROclient
.ROClientException
as e
:
473 if e
.http_code
== 404: # not found
474 self
.logger
.debug(logging_text
+ "RO_vim_id={} already deleted".format(RO_vim_id
))
479 self
.logger
.error(logging_text
+ "Nohing to remove at RO")
480 self
.db
.del_one("vim_accounts", {"_id": vim_id
})
481 self
.logger
.debug(logging_text
+ "Exit Ok")
484 except (ROclient
.ROClientException
, DbException
) as e
:
485 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
487 except Exception as e
:
488 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
491 self
.lcm_tasks
.remove("vim_account", vim_id
, order_id
)
493 db_vim_update
["_admin.operationalState"] = "ERROR"
494 db_vim_update
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
496 self
.update_db_2("vim_accounts", vim_id
, db_vim_update
)
497 self
.lcm_tasks
.remove("vim_account", vim_id
, order_id
)
499 async def sdn_create(self
, sdn_content
, order_id
):
500 sdn_id
= sdn_content
["_id"]
501 logging_text
= "Task sdn_create={} ".format(sdn_id
)
502 self
.logger
.debug(logging_text
+ "Enter")
508 step
= "Getting sdn from db"
509 db_sdn
= self
.db
.get_one("sdns", {"_id": sdn_id
})
510 db_sdn_update
["_admin.deployed.RO"] = None
512 step
= "Creating sdn at RO"
513 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
514 sdn_RO
= deepcopy(sdn_content
)
515 sdn_RO
.pop("_id", None)
516 sdn_RO
.pop("_admin", None)
517 sdn_RO
.pop("schema_version", None)
518 sdn_RO
.pop("schema_type", None)
519 sdn_RO
.pop("description", None)
520 desc
= await RO
.create("sdn", descriptor
=sdn_RO
)
521 RO_sdn_id
= desc
["uuid"]
522 db_sdn_update
["_admin.deployed.RO"] = RO_sdn_id
523 db_sdn_update
["_admin.operationalState"] = "ENABLED"
524 self
.logger
.debug(logging_text
+ "Exit Ok RO_sdn_id={}".format(RO_sdn_id
))
527 except (ROclient
.ROClientException
, DbException
) as e
:
528 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
530 except Exception as e
:
531 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
535 db_sdn_update
["_admin.operationalState"] = "ERROR"
536 db_sdn_update
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
538 self
.update_db_2("sdns", sdn_id
, db_sdn_update
)
539 self
.lcm_tasks
.remove("sdn", sdn_id
, order_id
)
541 async def sdn_edit(self
, sdn_content
, order_id
):
542 sdn_id
= sdn_content
["_id"]
543 logging_text
= "Task sdn_edit={} ".format(sdn_id
)
544 self
.logger
.debug(logging_text
+ "Enter")
548 step
= "Getting sdn from db"
550 db_sdn
= self
.db
.get_one("sdns", {"_id": sdn_id
})
551 if db_sdn
.get("_admin") and db_sdn
["_admin"].get("deployed") and db_sdn
["_admin"]["deployed"].get("RO"):
552 RO_sdn_id
= db_sdn
["_admin"]["deployed"]["RO"]
553 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
554 step
= "Editing sdn at RO"
555 sdn_RO
= deepcopy(sdn_content
)
556 sdn_RO
.pop("_id", None)
557 sdn_RO
.pop("_admin", None)
558 sdn_RO
.pop("schema_version", None)
559 sdn_RO
.pop("schema_type", None)
560 sdn_RO
.pop("description", None)
562 await RO
.edit("sdn", RO_sdn_id
, descriptor
=sdn_RO
)
563 db_sdn_update
["_admin.operationalState"] = "ENABLED"
565 self
.logger
.debug(logging_text
+ "Exit Ok RO_sdn_id".format(RO_sdn_id
))
568 except (ROclient
.ROClientException
, DbException
) as e
:
569 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
571 except Exception as e
:
572 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
576 db_sdn
["_admin.operationalState"] = "ERROR"
577 db_sdn
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
579 self
.update_db_2("sdns", sdn_id
, db_sdn_update
)
580 self
.lcm_tasks
.remove("sdn", sdn_id
, order_id
)
582 async def sdn_delete(self
, sdn_id
, order_id
):
583 logging_text
= "Task sdn_delete={} ".format(sdn_id
)
584 self
.logger
.debug(logging_text
+ "Enter")
588 step
= "Getting sdn from db"
590 db_sdn
= self
.db
.get_one("sdns", {"_id": sdn_id
})
591 if db_sdn
.get("_admin") and db_sdn
["_admin"].get("deployed") and db_sdn
["_admin"]["deployed"].get("RO"):
592 RO_sdn_id
= db_sdn
["_admin"]["deployed"]["RO"]
593 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
594 step
= "Deleting sdn from RO"
596 await RO
.delete("sdn", RO_sdn_id
)
597 except ROclient
.ROClientException
as e
:
598 if e
.http_code
== 404: # not found
599 self
.logger
.debug(logging_text
+ "RO_sdn_id={} already deleted".format(RO_sdn_id
))
604 self
.logger
.error(logging_text
+ "Skipping. There is not RO information at database")
605 self
.db
.del_one("sdns", {"_id": sdn_id
})
606 self
.logger
.debug("sdn_delete task sdn_id={} Exit Ok".format(sdn_id
))
609 except (ROclient
.ROClientException
, DbException
) as e
:
610 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
612 except Exception as e
:
613 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
617 db_sdn
["_admin.operationalState"] = "ERROR"
618 db_sdn
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
620 self
.update_db_2("sdns", sdn_id
, db_sdn_update
)
621 self
.lcm_tasks
.remove("sdn", sdn_id
, order_id
)
623 def vnfd2RO(self
, vnfd
, new_id
=None):
625 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
626 :param vnfd: input vnfd
627 :param new_id: overrides vnf id if provided
628 :return: copy of vnfd
632 vnfd_RO
= deepcopy(vnfd
)
633 vnfd_RO
.pop("_id", None)
634 vnfd_RO
.pop("_admin", None)
636 vnfd_RO
["id"] = new_id
637 for vdu
in vnfd_RO
["vdu"]:
638 if "cloud-init-file" in vdu
:
639 base_folder
= vnfd
["_admin"]["storage"]
640 clout_init_file
= "{}/{}/cloud_init/{}".format(
641 base_folder
["folder"],
642 base_folder
["pkg-dir"],
643 vdu
["cloud-init-file"]
645 ci_file
= self
.fs
.file_open(clout_init_file
, "r")
646 # TODO: detect if binary or text. Propose to read as binary and try to decode to utf8. If fails
647 # convert to base 64 or similar
648 clout_init_content
= ci_file
.read()
651 vdu
.pop("cloud-init-file", None)
652 vdu
["cloud-init"] = clout_init_content
653 # remnove unused by RO configuration, monitoring, scaling
654 vnfd_RO
.pop("vnf-configuration", None)
655 vnfd_RO
.pop("monitoring-param", None)
656 vnfd_RO
.pop("scaling-group-descriptor", None)
658 except FsException
as e
:
659 raise LcmException("Error reading file at vnfd {}: {} ".format(vnfd
["_id"], e
))
664 def n2vc_callback(self
, model_name
, application_name
, status
, message
, db_nsr
, db_nslcmop
, task
=None):
666 Callback both for charm status change and task completion
667 :param model_name: Charm model name
668 :param application_name: Charm application name
669 :param status: Can be
670 - blocked: The unit needs manual intervention
671 - maintenance: The unit is actively deploying/configuring
672 - waiting: The unit is waiting for another charm to be ready
673 - active: The unit is deployed, configured, and ready
674 - error: The charm has failed and needs attention.
675 - terminated: The charm has been destroyed
678 :param message: detailed message error
679 :param db_nsr: nsr database content
680 :param db_nslcmop: nslcmop database content
681 :param task: None for charm status change, or task for completion task callback
687 db_nslcmop_update
= {}
689 nsr_id
= db_nsr
["_id"]
690 nsr_lcm
= db_nsr
["_admin"]["deployed"]
691 nslcmop_id
= db_nslcmop
["_id"]
692 ns_operation
= db_nslcmop
["lcmOperationType"]
693 logging_text
= "Task ns={} {}={} [n2vc_callback] application={}".format(nsr_id
, ns_operation
, nslcmop_id
,
695 vca_deployed
= nsr_lcm
["VCA"].get(application_name
)
697 self
.logger
.error(logging_text
+ " Not present at nsr._admin.deployed.VCA")
702 self
.logger
.debug(logging_text
+ " task Cancelled")
703 # TODO update db_nslcmop
707 exc
= task
.exception()
709 self
.logger
.error(logging_text
+ " task Exception={}".format(exc
))
710 if ns_operation
in ("instantiate", "terminate"):
711 vca_deployed
['operational-status'] = "error"
712 db_nsr_update
["_admin.deployed.VCA.{}.operational-status".format(application_name
)] = \
714 vca_deployed
['detailed-status'] = str(exc
)
716 "_admin.deployed.VCA.{}.detailed-status".format(application_name
)] = str(exc
)
717 elif ns_operation
== "action":
718 db_nslcmop_update
["operationState"] = "FAILED"
719 db_nslcmop_update
["detailed-status"] = str(exc
)
720 db_nslcmop_update
["statusEnteredTime"] = time()
724 self
.logger
.debug(logging_text
+ " task Done")
725 # TODO revise with Adam if action is finished and ok when task is done
726 if ns_operation
== "action":
727 db_nslcmop_update
["operationState"] = "COMPLETED"
728 db_nslcmop_update
["detailed-status"] = "Done"
729 db_nslcmop_update
["statusEnteredTime"] = time()
730 # task is Done, but callback is still ongoing. So ignore
733 self
.logger
.debug(logging_text
+ " Enter status={}".format(status
))
734 if vca_deployed
['operational-status'] == status
:
735 return # same status, ignore
736 vca_deployed
['operational-status'] = status
737 db_nsr_update
["_admin.deployed.VCA.{}.operational-status".format(application_name
)] = status
738 vca_deployed
['detailed-status'] = str(message
)
739 db_nsr_update
["_admin.deployed.VCA.{}.detailed-status".format(application_name
)] = str(message
)
741 self
.logger
.critical(logging_text
+ " Enter with bad parameters", exc_info
=True)
746 n2vc_error_text
= [] # contain text error list. If empty no one is in error status
747 for _
, vca_info
in nsr_lcm
["VCA"].items():
748 vca_status
= vca_info
["operational-status"]
749 if vca_status
not in status_map
:
751 status_map
[vca_status
] = 0
752 status_map
[vca_status
] += 1
754 if vca_status
!= "active":
756 if vca_status
in ("error", "blocked"):
757 n2vc_error_text
.append("member_vnf_index={} vdu_id={} {}: {}".format(vca_info
["member-vnf-index"],
758 vca_info
["vdu_id"], vca_status
,
759 vca_info
["detailed-status"]))
762 self
.logger
.debug(logging_text
+ " All active")
763 db_nsr_update
["config-status"] = "configured"
764 db_nsr_update
["detailed-status"] = "done"
765 db_nslcmop_update
["operationState"] = "COMPLETED"
766 db_nslcmop_update
["detailed-status"] = "Done"
767 db_nslcmop_update
["statusEnteredTime"] = time()
768 elif n2vc_error_text
:
769 db_nsr_update
["config-status"] = "failed"
770 error_text
= "fail configuring " + ";".join(n2vc_error_text
)
771 db_nsr_update
["detailed-status"] = error_text
772 db_nslcmop_update
["operationState"] = "FAILED_TEMP"
773 db_nslcmop_update
["detailed-status"] = error_text
774 db_nslcmop_update
["statusEnteredTime"] = time()
778 for status
, num
in status_map
.items():
779 cs
+= separator
+ "{}: {}".format(status
, num
)
781 db_nsr_update
["config-status"] = cs
782 db_nsr_update
["detailed-status"] = cs
783 db_nslcmop_update
["detailed-status"] = cs
785 except Exception as e
:
786 self
.logger
.critical(logging_text
+ " Exception {}".format(e
), exc_info
=True)
789 if db_nslcmop_update
:
790 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
792 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
793 except Exception as e
:
794 self
.logger
.critical(logging_text
+ " Update database Exception {}".format(e
), exc_info
=True)
796 def ns_params_2_RO(self
, ns_params
, nsd
, vnfd_dict
):
798 Creates a RO ns descriptor from OSM ns_instantite params
799 :param ns_params: OSM instantiate params
800 :return: The RO ns descriptor
804 def vim_account_2_RO(vim_account
):
805 if vim_account
in vim_2_RO
:
806 return vim_2_RO
[vim_account
]
808 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_account
})
809 if db_vim
["_admin"]["operationalState"] != "ENABLED":
810 raise LcmException("VIM={} is not available. operationalState={}".format(
811 vim_account
, db_vim
["_admin"]["operationalState"]))
812 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
813 vim_2_RO
[vim_account
] = RO_vim_id
816 def ip_profile_2_RO(ip_profile
):
817 RO_ip_profile
= deepcopy((ip_profile
))
818 if "dns-server" in RO_ip_profile
:
819 RO_ip_profile
["dns-address"] = RO_ip_profile
.pop("dns-server")
820 if RO_ip_profile
.get("ip-version") == "ipv4":
821 RO_ip_profile
["ip-version"] = "IPv4"
822 if RO_ip_profile
.get("ip-version") == "ipv6":
823 RO_ip_profile
["ip-version"] = "IPv6"
824 if "dhcp-params" in RO_ip_profile
:
825 RO_ip_profile
["dhcp"] = RO_ip_profile
.pop("dhcp-params")
831 # "name": ns_params["nsName"],
832 # "description": ns_params.get("nsDescription"),
833 "datacenter": vim_account_2_RO(ns_params
["vimAccountId"]),
834 # "scenario": ns_params["nsdId"],
838 if ns_params
.get("ssh-authorized-key"):
839 RO_ns_params
["cloud-config"] = {"key-pairs": ns_params
["ssh-authorized-key"]}
840 if ns_params
.get("vnf"):
841 for vnf_params
in ns_params
["vnf"]:
842 for constituent_vnfd
in nsd
["constituent-vnfd"]:
843 if constituent_vnfd
["member-vnf-index"] == vnf_params
["member-vnf-index"]:
844 vnf_descriptor
= vnfd_dict
[constituent_vnfd
["vnfd-id-ref"]]
847 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index={} is not present at nsd:"
848 "constituent-vnfd".format(vnf_params
["member-vnf-index"]))
849 RO_vnf
= {"vdus": {}, "networks": {}}
850 if vnf_params
.get("vimAccountId"):
851 RO_vnf
["datacenter"] = vim_account_2_RO(vnf_params
["vimAccountId"])
852 if vnf_params
.get("vdu"):
853 for vdu_params
in vnf_params
["vdu"]:
854 RO_vnf
["vdus"][vdu_params
["id"]] = {}
855 if vdu_params
.get("volume"):
856 RO_vnf
["vdus"][vdu_params
["id"]]["devices"] = {}
857 for volume_params
in vdu_params
["volume"]:
858 RO_vnf
["vdus"][vdu_params
["id"]]["devices"][volume_params
["name"]] = {}
859 if volume_params
.get("vim-volume-id"):
860 RO_vnf
["vdus"][vdu_params
["id"]]["devices"][volume_params
["name"]]["vim_id"] = \
861 volume_params
["vim-volume-id"]
862 if vdu_params
.get("interface"):
863 RO_vnf
["vdus"][vdu_params
["id"]]["interfaces"] = {}
864 for interface_params
in vdu_params
["interface"]:
866 RO_vnf
["vdus"][vdu_params
["id"]]["interfaces"][interface_params
["name"]] = RO_interface
867 if interface_params
.get("ip-address"):
868 RO_interface
["ip_address"] = interface_params
["ip-address"]
869 if interface_params
.get("mac-address"):
870 RO_interface
["mac_address"] = interface_params
["mac-address"]
871 if interface_params
.get("floating-ip-required"):
872 RO_interface
["floating-ip"] = interface_params
["floating-ip-required"]
873 if vnf_params
.get("internal-vld"):
874 for internal_vld_params
in vnf_params
["internal-vld"]:
875 RO_vnf
["networks"][internal_vld_params
["name"]] = {}
876 if internal_vld_params
.get("vim-network-name"):
877 RO_vnf
["networks"][internal_vld_params
["name"]]["vim-network-name"] = \
878 internal_vld_params
["vim-network-name"]
879 if internal_vld_params
.get("ip-profile"):
880 RO_vnf
["networks"][internal_vld_params
["name"]]["ip-profile"] = \
881 ip_profile_2_RO(internal_vld_params
["ip-profile"])
882 if internal_vld_params
.get("internal-connection-point"):
883 for icp_params
in internal_vld_params
["internal-connection-point"]:
886 for vdu_descriptor
in vnf_descriptor
["vdu"]:
887 for vdu_interface
in vdu_descriptor
["interface"]:
888 if vdu_interface
.get("internal-connection-point-ref") == icp_params
["id-ref"]:
889 if vdu_descriptor
["id"] not in RO_vnf
["vdus"]:
890 RO_vnf
["vdus"][vdu_descriptor
["id"]] = {}
891 if "interfaces" not in RO_vnf
["vdus"][vdu_descriptor
["id"]]:
892 RO_vnf
["vdus"][vdu_descriptor
["id"]]["interfaces"] = {}
893 RO_ifaces
= RO_vnf
["vdus"][vdu_descriptor
["id"]]["interfaces"]
894 if vdu_interface
["name"] not in RO_ifaces
:
895 RO_ifaces
[vdu_interface
["name"]] = {}
897 RO_ifaces
[vdu_interface
["name"]]["ip_address"] = icp_params
["ip-address"]
903 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
904 "internal-vld:id-ref={} is not present at vnfd:internal-"
905 "connection-point".format(vnf_params
["member-vnf-index"],
906 icp_params
["id-ref"]))
908 if not RO_vnf
["vdus"]:
910 if not RO_vnf
["networks"]:
911 del RO_vnf
["networks"]
913 RO_ns_params
["vnfs"][vnf_params
["member-vnf-index"]] = RO_vnf
914 if ns_params
.get("vld"):
915 for vld_params
in ns_params
["vld"]:
917 if "ip-profile" in vld_params
:
918 RO_vld
["ip-profile"] = ip_profile_2_RO(vld_params
["ip-profile"])
919 if "vim-network-name" in vld_params
:
921 if isinstance(vld_params
["vim-network-name"], dict):
922 for vim_account
, vim_net
in vld_params
["vim-network-name"].items():
923 RO_vld
["sites"].append({
924 "netmap-use": vim_net
,
925 "datacenter": vim_account_2_RO(vim_account
)
927 else: # isinstance str
928 RO_vld
["sites"].append({"netmap-use": vld_params
["vim-network-name"]})
930 RO_ns_params
["networks"][vld_params
["name"]] = RO_vld
933 def ns_update_vnfr(self
, db_vnfrs
, nsr_desc_RO
):
935 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
940 for vnf_index
, db_vnfr
in db_vnfrs
.items():
941 for vnf_RO
in nsr_desc_RO
["vnfs"]:
942 if vnf_RO
["member_vnf_index"] == vnf_index
:
944 db_vnfr
["ip-address"] = vnfr_update
["ip-address"] = vnf_RO
.get("ip_address")
946 for vdur_RO
in vnf_RO
.get("vms", ()):
948 "vim-id": vdur_RO
.get("vim_vm_id"),
949 "ip-address": vdur_RO
.get("ip_address"),
950 "vdu-id-ref": vdur_RO
.get("vdu_osm_id"),
951 "name": vdur_RO
.get("vim_name"),
952 "status": vdur_RO
.get("status"),
953 "status-detailed": vdur_RO
.get("error_msg"),
957 for interface_RO
in vdur_RO
.get("interfaces", ()):
958 vdur
["interfaces"].append({
959 "ip-address": interface_RO
.get("ip_address"),
960 "mac-address": interface_RO
.get("mac_address"),
961 "name": interface_RO
.get("external_name"),
963 vdur_list
.append(vdur
)
964 db_vnfr
["vdur"] = vnfr_update
["vdur"] = vdur_list
965 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
969 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} at RO info".format(vnf_index
))
971 async def create_monitoring(self
, nsr_id
, vnf_member_index
, vnfd_desc
):
972 if not vnfd_desc
.get("scaling-group-descriptor"):
974 for scaling_group
in vnfd_desc
["scaling-group-descriptor"]:
975 scaling_policy_desc
= {}
978 "scaling_group_descriptor": {
979 "name": scaling_group
["name"],
980 "scaling_policy": scaling_policy_desc
983 for scaling_policy
in scaling_group
.get("scaling-policy"):
984 scaling_policy_desc
["scale_in_operation_type"] = scaling_policy_desc
["scale_out_operation_type"] = \
985 scaling_policy
["scaling-type"]
986 scaling_policy_desc
["threshold_time"] = scaling_policy
["threshold-time"]
987 scaling_policy_desc
["cooldown_time"] = scaling_policy
["cooldown-time"]
988 scaling_policy_desc
["scaling_criteria"] = []
989 for scaling_criteria
in scaling_policy
.get("scaling-criteria"):
990 scaling_criteria_desc
= {"scale_in_threshold": scaling_criteria
.get("scale-in-threshold"),
991 "scale_out_threshold": scaling_criteria
.get("scale-out-threshold"),
993 if not scaling_criteria
.get("vnf-monitoring-param-ref"):
995 for monitoring_param
in vnfd_desc
.get("monitoring-param", ()):
996 if monitoring_param
["id"] == scaling_criteria
["vnf-monitoring-param-ref"]:
997 scaling_criteria_desc
["monitoring_param"] = {
998 "id": monitoring_param
["id"],
999 "name": monitoring_param
["name"],
1000 "aggregation_type": monitoring_param
.get("aggregation-type"),
1001 "vdu_name": monitoring_param
.get("vdu-ref"),
1002 "vnf_member_index": vnf_member_index
,
1005 scaling_policy_desc
["scaling_criteria"].append(scaling_criteria_desc
)
1009 "Task ns={} member_vnf_index={} Invalid vnfd vnf-monitoring-param-ref={} not in "
1010 "monitoring-param list".format(nsr_id
, vnf_member_index
,
1011 scaling_criteria
["vnf-monitoring-param-ref"]))
1013 await self
.msg
.aiowrite("lcm_pm", "configure_scaling", scaling_desc
, self
.loop
)
1015 async def ns_instantiate(self
, nsr_id
, nslcmop_id
):
1016 logging_text
= "Task ns={} instantiate={} ".format(nsr_id
, nslcmop_id
)
1017 self
.logger
.debug(logging_text
+ "Enter")
1018 # get all needed from database
1022 db_nslcmop_update
= {}
1024 RO_descriptor_number
= 0 # number of descriptors created at RO
1025 descriptor_id_2_RO
= {} # map between vnfd/nsd id to the id used at RO
1028 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
1029 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1030 step
= "Getting nsr={} from db".format(nsr_id
)
1031 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1032 ns_params
= db_nsr
.get("instantiate_params")
1034 nsr_name
= db_nsr
["name"] # TODO short-name??
1036 vnfr_filter
= {"nsr-id-ref": nsr_id
, "member-vnf-index-ref": None}
1037 for c_vnf
in nsd
["constituent-vnfd"]:
1038 vnfd_id
= c_vnf
["vnfd-id-ref"]
1039 vnfr_filter
["member-vnf-index-ref"] = c_vnf
["member-vnf-index"]
1040 step
= "Getting vnfr={} of nsr={} from db".format(c_vnf
["member-vnf-index"], nsr_id
)
1041 db_vnfrs
[c_vnf
["member-vnf-index"]] = self
.db
.get_one("vnfrs", vnfr_filter
)
1042 if vnfd_id
not in needed_vnfd
:
1043 step
= "Getting vnfd={} from db".format(vnfd_id
)
1044 needed_vnfd
[vnfd_id
] = self
.db
.get_one("vnfds", {"id": vnfd_id
})
1046 nsr_lcm
= db_nsr
["_admin"].get("deployed")
1048 nsr_lcm
= db_nsr
["_admin"]["deployed"] = {
1050 "RO": {"vnfd_id": {}, "nsd_id": None, "nsr_id": None, "nsr_status": "SCHEDULED"},
1054 db_nsr_update
["detailed-status"] = "creating"
1055 db_nsr_update
["operational-status"] = "init"
1057 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
1059 # get vnfds, instantiate at RO
1060 for vnfd_id
, vnfd
in needed_vnfd
.items():
1061 step
= db_nsr_update
["detailed-status"] = "Creating vnfd={} at RO".format(vnfd_id
)
1062 # self.logger.debug(logging_text + step)
1063 vnfd_id_RO
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, vnfd_id
[:23])
1064 descriptor_id_2_RO
[vnfd_id
] = vnfd_id_RO
1065 RO_descriptor_number
+= 1
1068 vnfd_list
= await RO
.get_list("vnfd", filter_by
={"osm_id": vnfd_id_RO
})
1070 db_nsr_update
["_admin.deployed.RO.vnfd_id.{}".format(vnfd_id
)] = vnfd_list
[0]["uuid"]
1071 self
.logger
.debug(logging_text
+ "vnfd={} exists at RO. Using RO_id={}".format(
1072 vnfd_id
, vnfd_list
[0]["uuid"]))
1074 vnfd_RO
= self
.vnfd2RO(vnfd
, vnfd_id_RO
)
1075 desc
= await RO
.create("vnfd", descriptor
=vnfd_RO
)
1076 db_nsr_update
["_admin.deployed.RO.vnfd_id.{}".format(vnfd_id
)] = desc
["uuid"]
1077 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1078 self
.logger
.debug(logging_text
+ "vnfd={} created at RO. RO_id={}".format(
1079 vnfd_id
, desc
["uuid"]))
1080 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1084 step
= db_nsr_update
["detailed-status"] = "Creating nsd={} at RO".format(nsd_id
)
1085 # self.logger.debug(logging_text + step)
1087 RO_osm_nsd_id
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, nsd_id
[:23])
1088 descriptor_id_2_RO
[nsd_id
] = RO_osm_nsd_id
1089 RO_descriptor_number
+= 1
1090 nsd_list
= await RO
.get_list("nsd", filter_by
={"osm_id": RO_osm_nsd_id
})
1092 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= nsd_list
[0]["uuid"]
1093 self
.logger
.debug(logging_text
+ "nsd={} exists at RO. Using RO_id={}".format(
1094 nsd_id
, RO_nsd_uuid
))
1096 nsd_RO
= deepcopy(nsd
)
1097 nsd_RO
["id"] = RO_osm_nsd_id
1098 nsd_RO
.pop("_id", None)
1099 nsd_RO
.pop("_admin", None)
1100 for c_vnf
in nsd_RO
["constituent-vnfd"]:
1101 vnfd_id
= c_vnf
["vnfd-id-ref"]
1102 c_vnf
["vnfd-id-ref"] = descriptor_id_2_RO
[vnfd_id
]
1103 desc
= await RO
.create("nsd", descriptor
=nsd_RO
)
1104 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1105 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= desc
["uuid"]
1106 self
.logger
.debug(logging_text
+ "nsd={} created at RO. RO_id={}".format(nsd_id
, RO_nsd_uuid
))
1107 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1110 # if present use it unless in error status
1111 RO_nsr_id
= db_nsr
["_admin"].get("deployed", {}).get("RO", {}).get("nsr_id")
1114 step
= db_nsr_update
["detailed-status"] = "Looking for existing ns at RO"
1115 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
1116 desc
= await RO
.show("ns", RO_nsr_id
)
1117 except ROclient
.ROClientException
as e
:
1118 if e
.http_code
!= HTTPStatus
.NOT_FOUND
:
1120 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1122 ns_status
, ns_status_info
= RO
.check_ns_status(desc
)
1123 db_nsr_update
["_admin.deployed.RO.nsr_status"] = ns_status
1124 if ns_status
== "ERROR":
1125 step
= db_nsr_update
["detailed-status"] = "Deleting ns at RO. RO_ns_id={}".format(RO_nsr_id
)
1126 self
.logger
.debug(logging_text
+ step
)
1127 await RO
.delete("ns", RO_nsr_id
)
1128 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1130 step
= db_nsr_update
["detailed-status"] = "Creating ns at RO"
1131 # self.logger.debug(logging_text + step)
1133 # check if VIM is creating and wait look if previous tasks in process
1134 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account", ns_params
["vimAccountId"])
1136 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
1137 self
.logger
.debug(logging_text
+ step
)
1138 await asyncio
.wait(task_dependency
, timeout
=3600)
1139 if ns_params
.get("vnf"):
1140 for vnf
in ns_params
["vnf"]:
1141 if "vimAccountId" in vnf
:
1142 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account",
1143 vnf
["vimAccountId"])
1145 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
1146 self
.logger
.debug(logging_text
+ step
)
1147 await asyncio
.wait(task_dependency
, timeout
=3600)
1149 RO_ns_params
= self
.ns_params_2_RO(ns_params
, nsd
, needed_vnfd
)
1150 desc
= await RO
.create("ns", descriptor
=RO_ns_params
,
1151 name
=db_nsr
["name"],
1152 scenario
=RO_nsd_uuid
)
1153 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = desc
["uuid"]
1154 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1155 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "BUILD"
1156 self
.logger
.debug(logging_text
+ "ns created at RO. RO_id={}".format(desc
["uuid"]))
1157 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1159 # update VNFR vimAccount
1160 step
= "Updating VNFR vimAcccount"
1161 for vnf_index
, vnfr
in db_vnfrs
.items():
1162 if vnfr
.get("vim-account-id"):
1164 vnfr_update
= {"vim-account-id": db_nsr
["instantiate_params"]["vimAccountId"]}
1165 if db_nsr
["instantiate_params"].get("vnf"):
1166 for vnf_params
in db_nsr
["instantiate_params"]["vnf"]:
1167 if vnf_params
.get("member-vnf-index") == vnf_index
:
1168 if vnf_params
.get("vimAccountId"):
1169 vnfr_update
["vim-account-id"] = vnf_params
.get("vimAccountId")
1171 self
.update_db_2("vnfrs", vnfr
["_id"], vnfr_update
)
1173 # wait until NS is ready
1174 step
= ns_status_detailed
= detailed_status
= "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id
)
1175 detailed_status_old
= None
1176 self
.logger
.debug(logging_text
+ step
)
1178 deployment_timeout
= 2 * 3600 # Two hours
1179 while deployment_timeout
> 0:
1180 desc
= await RO
.show("ns", RO_nsr_id
)
1181 ns_status
, ns_status_info
= RO
.check_ns_status(desc
)
1182 db_nsr_update
["admin.deployed.RO.nsr_status"] = ns_status
1183 if ns_status
== "ERROR":
1184 raise ROclient
.ROClientException(ns_status_info
)
1185 elif ns_status
== "BUILD":
1186 detailed_status
= ns_status_detailed
+ "; {}".format(ns_status_info
)
1187 elif ns_status
== "ACTIVE":
1188 step
= detailed_status
= "Waiting for management IP address reported by the VIM"
1190 nsr_lcm
["nsr_ip"] = RO
.get_ns_vnf_info(desc
)
1192 except ROclient
.ROClientException
as e
:
1193 if e
.http_code
!= 409: # IP address is not ready return code is 409 CONFLICT
1196 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
1197 if detailed_status
!= detailed_status_old
:
1198 detailed_status_old
= db_nsr_update
["detailed-status"] = detailed_status
1199 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1200 await asyncio
.sleep(5, loop
=self
.loop
)
1201 deployment_timeout
-= 5
1202 if deployment_timeout
<= 0:
1203 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
1205 step
= "Updating VNFRs"
1206 self
.ns_update_vnfr(db_vnfrs
, desc
)
1208 db_nsr
["detailed-status"] = "Configuring vnfr"
1209 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1211 # The parameters we'll need to deploy a charm
1212 number_to_configure
= 0
1214 def deploy(vnf_index
, vdu_id
, mgmt_ip_address
, config_primitive
=None):
1215 """An inner function to deploy the charm from either vnf or vdu
1216 vnf_index is mandatory. vdu_id can be None for a vnf configuration or the id for vdu configuration
1218 if not mgmt_ip_address
:
1219 raise LcmException("vnfd/vdu has not management ip address to configure it")
1221 # if number_to_configure == 0:
1222 # self.logger.debug("Logging into N2VC...")
1223 # task = asyncio.ensure_future(self.n2vc.login())
1224 # yield from asyncio.wait_for(task, 30.0)
1225 # self.logger.debug("Logged into N2VC!")
1227 # # await self.n2vc.login()
1229 # Note: The charm needs to exist on disk at the location
1230 # specified by charm_path.
1231 base_folder
= vnfd
["_admin"]["storage"]
1232 storage_params
= self
.fs
.get_params()
1233 charm_path
= "{}{}/{}/charms/{}".format(
1234 storage_params
["path"],
1235 base_folder
["folder"],
1236 base_folder
["pkg-dir"],
1240 # Setup the runtime parameters for this VNF
1241 params
= {'rw_mgmt_ip': mgmt_ip_address
}
1242 if config_primitive
:
1243 params
["initial-config-primitive"] = config_primitive
1245 # ns_name will be ignored in the current version of N2VC
1246 # but will be implemented for the next point release.
1247 model_name
= 'default'
1248 vdu_id_text
= "vnfd"
1250 vdu_id_text
= vdu_id
1251 application_name
= self
.n2vc
.FormatApplicationName(
1256 if not nsr_lcm
.get("VCA"):
1258 nsr_lcm
["VCA"][application_name
] = db_nsr_update
["_admin.deployed.VCA.{}".format(application_name
)] = {
1259 "member-vnf-index": vnf_index
,
1261 "model": model_name
,
1262 "application": application_name
,
1263 "operational-status": "init",
1264 "detailed-status": "",
1267 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1269 self
.logger
.debug("Task create_ns={} Passing artifacts path '{}' for {}".format(nsr_id
, charm_path
,
1271 task
= asyncio
.ensure_future(
1272 self
.n2vc
.DeployCharms(
1273 model_name
, # The network service name
1274 application_name
, # The application name
1275 vnfd
, # The vnf descriptor
1276 charm_path
, # Path to charm
1277 params
, # Runtime params, like mgmt ip
1278 {}, # for native charms only
1279 self
.n2vc_callback
, # Callback for status changes
1280 db_nsr
, # Callback parameter
1282 None, # Callback parameter (task)
1285 task
.add_done_callback(functools
.partial(self
.n2vc_callback
, model_name
, application_name
, None, None,
1286 db_nsr
, db_nslcmop
))
1287 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "create_charm:" + application_name
, task
)
1289 step
= "Looking for needed vnfd to configure"
1290 self
.logger
.debug(logging_text
+ step
)
1292 for c_vnf
in nsd
["constituent-vnfd"]:
1293 vnfd_id
= c_vnf
["vnfd-id-ref"]
1294 vnf_index
= str(c_vnf
["member-vnf-index"])
1295 vnfd
= needed_vnfd
[vnfd_id
]
1297 # Check if this VNF has a charm configuration
1298 vnf_config
= vnfd
.get("vnf-configuration")
1300 if vnf_config
and vnf_config
.get("juju"):
1301 proxy_charm
= vnf_config
["juju"]["charm"]
1302 config_primitive
= None
1305 if 'initial-config-primitive' in vnf_config
:
1306 config_primitive
= vnf_config
['initial-config-primitive']
1308 # Login to the VCA. If there are multiple calls to login(),
1309 # subsequent calls will be a nop and return immediately.
1310 step
= "connecting to N2VC to configure vnf {}".format(vnf_index
)
1311 await self
.n2vc
.login()
1312 deploy(vnf_index
, None, db_vnfrs
[vnf_index
]["ip-address"], config_primitive
)
1313 number_to_configure
+= 1
1315 # Deploy charms for each VDU that supports one.
1317 for vdu
in vnfd
['vdu']:
1318 vdu_config
= vdu
.get('vdu-configuration')
1320 config_primitive
= None
1322 if vdu_config
and vdu_config
.get("juju"):
1323 proxy_charm
= vdu_config
["juju"]["charm"]
1325 if 'initial-config-primitive' in vdu_config
:
1326 config_primitive
= vdu_config
['initial-config-primitive']
1329 step
= "connecting to N2VC to configure vdu {} from vnf {}".format(vdu
["id"], vnf_index
)
1330 await self
.n2vc
.login()
1331 deploy(vnf_index
, vdu
["id"], db_vnfrs
[vnf_index
]["vdur"][vdu_index
]["ip-address"],
1333 number_to_configure
+= 1
1336 if number_to_configure
:
1337 db_nsr_update
["config-status"] = "configuring"
1338 db_nsr_update
["operational-status"] = "running"
1339 db_nsr_update
["detailed-status"] = "configuring: init: {}".format(number_to_configure
)
1340 db_nslcmop_update
["detailed-status"] = "configuring: init: {}".format(number_to_configure
)
1342 db_nslcmop_update
["operationState"] = "COMPLETED"
1343 db_nslcmop_update
["statusEnteredTime"] = time()
1344 db_nslcmop_update
["detailed-status"] = "done"
1345 db_nsr_update
["config-status"] = "configured"
1346 db_nsr_update
["detailed-status"] = "done"
1347 db_nsr_update
["operational-status"] = "running"
1348 step
= "Sending monitoring parameters to PM"
1349 # for c_vnf in nsd["constituent-vnfd"]:
1350 # await self.create_monitoring(nsr_id, c_vnf["member-vnf-index"], needed_vnfd[c_vnf["vnfd-id-ref"]])
1352 await self
.msg
.aiowrite("ns", "instantiated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
})
1353 except Exception as e
:
1354 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1356 self
.logger
.debug(logging_text
+ "Exit")
1359 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
1360 self
.logger
.error(logging_text
+ "Exit Exception while '{}': {}".format(step
, e
))
1362 except asyncio
.CancelledError
:
1363 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1364 exc
= "Operation was cancelled"
1365 except Exception as e
:
1366 exc
= traceback
.format_exc()
1367 self
.logger
.critical(logging_text
+ "Exit Exception {} while '{}': {}".format(type(e
).__name
__, step
, e
),
1372 db_nsr_update
["detailed-status"] = "ERROR {}: {}".format(step
, exc
)
1373 db_nsr_update
["operational-status"] = "failed"
1375 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
1376 db_nslcmop_update
["operationState"] = "FAILED"
1377 db_nslcmop_update
["statusEnteredTime"] = time()
1379 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1380 if db_nslcmop_update
:
1381 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1382 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_instantiate")
1384 async def ns_terminate(self
, nsr_id
, nslcmop_id
):
1385 logging_text
= "Task ns={} terminate={} ".format(nsr_id
, nslcmop_id
)
1386 self
.logger
.debug(logging_text
+ "Enter")
1390 failed_detail
= [] # annotates all failed error messages
1394 db_nslcmop_update
= {}
1396 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
1397 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1398 step
= "Getting nsr={} from db".format(nsr_id
)
1399 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1400 # nsd = db_nsr["nsd"]
1401 nsr_lcm
= deepcopy(db_nsr
["_admin"].get("deployed"))
1402 if db_nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
1405 # db_vim = self.db.get_one("vim_accounts", {"_id": db_nsr["datacenter"]})
1406 # #TODO check if VIM is creating and wait
1407 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
1409 db_nsr_update
["operational-status"] = "terminating"
1410 db_nsr_update
["config-status"] = "terminating"
1412 if nsr_lcm
and nsr_lcm
.get("VCA"):
1414 step
= "Scheduling configuration charms removing"
1415 db_nsr_update
["detailed-status"] = "Deleting charms"
1416 self
.logger
.debug(logging_text
+ step
)
1417 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1418 for application_name
, deploy_info
in nsr_lcm
["VCA"].items():
1419 if deploy_info
: # TODO it would be desirable having a and deploy_info.get("deployed"):
1420 task
= asyncio
.ensure_future(
1421 self
.n2vc
.RemoveCharms(
1422 deploy_info
['model'],
1424 # self.n2vc_callback,
1429 vca_task_list
.append(task
)
1430 vca_task_dict
[application_name
] = task
1431 # task.add_done_callback(functools.partial(self.n2vc_callback, deploy_info['model'],
1432 # deploy_info['application'], None, db_nsr,
1433 # db_nslcmop, vnf_index))
1434 self
.lcm_ns_tasks
[nsr_id
][nslcmop_id
]["delete_charm:" + application_name
] = task
1435 except Exception as e
:
1436 self
.logger
.debug(logging_text
+ "Failed while deleting charms: {}".format(e
))
1440 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
1442 if nsr_lcm
and nsr_lcm
.get("RO") and nsr_lcm
["RO"].get("nsr_id"):
1443 RO_nsr_id
= nsr_lcm
["RO"]["nsr_id"]
1445 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] = "Deleting ns at RO"
1446 self
.logger
.debug(logging_text
+ step
)
1447 await RO
.delete("ns", RO_nsr_id
)
1448 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1449 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
1450 except ROclient
.ROClientException
as e
:
1451 if e
.http_code
== 404: # not found
1452 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1453 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
1454 self
.logger
.debug(logging_text
+ "RO_ns_id={} already deleted".format(RO_nsr_id
))
1455 elif e
.http_code
== 409: # conflict
1456 failed_detail
.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id
, e
))
1457 self
.logger
.debug(logging_text
+ failed_detail
[-1])
1460 failed_detail
.append("RO_ns_id={} delete error: {}".format(RO_nsr_id
, e
))
1461 self
.logger
.error(logging_text
+ failed_detail
[-1])
1465 if not RO_fail
and nsr_lcm
and nsr_lcm
.get("RO") and nsr_lcm
["RO"].get("nsd_id"):
1466 RO_nsd_id
= nsr_lcm
["RO"]["nsd_id"]
1468 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
1469 "Deleting nsd at RO"
1470 await RO
.delete("nsd", RO_nsd_id
)
1471 self
.logger
.debug(logging_text
+ "RO_nsd_id={} deleted".format(RO_nsd_id
))
1472 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
1473 except ROclient
.ROClientException
as e
:
1474 if e
.http_code
== 404: # not found
1475 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
1476 self
.logger
.debug(logging_text
+ "RO_nsd_id={} already deleted".format(RO_nsd_id
))
1477 elif e
.http_code
== 409: # conflict
1478 failed_detail
.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id
, e
))
1479 self
.logger
.debug(logging_text
+ failed_detail
[-1])
1482 failed_detail
.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id
, e
))
1483 self
.logger
.error(logging_text
+ failed_detail
[-1])
1486 if not RO_fail
and nsr_lcm
and nsr_lcm
.get("RO") and nsr_lcm
["RO"].get("vnfd_id"):
1487 for vnf_id
, RO_vnfd_id
in nsr_lcm
["RO"]["vnfd_id"].items():
1491 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
1492 "Deleting vnfd={} at RO".format(vnf_id
)
1493 await RO
.delete("vnfd", RO_vnfd_id
)
1494 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} deleted".format(RO_vnfd_id
))
1495 db_nsr_update
["_admin.deployed.RO.vnfd_id.{}".format(vnf_id
)] = None
1496 except ROclient
.ROClientException
as e
:
1497 if e
.http_code
== 404: # not found
1498 db_nsr_update
["_admin.deployed.RO.vnfd_id.{}".format(vnf_id
)] = None
1499 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} already deleted ".format(RO_vnfd_id
))
1500 elif e
.http_code
== 409: # conflict
1501 failed_detail
.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id
, e
))
1502 self
.logger
.debug(logging_text
+ failed_detail
[-1])
1504 failed_detail
.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id
, e
))
1505 self
.logger
.error(logging_text
+ failed_detail
[-1])
1508 db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
1509 "Waiting for deletion of configuration charms"
1510 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1511 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1512 await asyncio
.wait(vca_task_list
, timeout
=300)
1513 for application_name
, task
in vca_task_dict
.items():
1514 if task
.cancelled():
1515 failed_detail
.append("VCA[{}] Deletion has been cancelled".format(application_name
))
1517 exc
= task
.exception()
1519 failed_detail
.append("VCA[{}] Deletion exception: {}".format(application_name
, exc
))
1521 db_nsr_update
["_admin.deployed.VCA.{}".format(application_name
)] = None
1523 # TODO Should it be cancelled?!!
1525 failed_detail
.append("VCA[{}] Deletion timeout".format(application_name
))
1528 self
.logger
.error(logging_text
+ " ;".join(failed_detail
))
1529 db_nsr_update
["operational-status"] = "failed"
1530 db_nsr_update
["detailed-status"] = "Deletion errors " + "; ".join(failed_detail
)
1531 db_nslcmop_update
["detailed-status"] = "; ".join(failed_detail
)
1532 db_nslcmop_update
["operationState"] = "FAILED"
1533 db_nslcmop_update
["statusEnteredTime"] = time()
1534 elif db_nslcmop
["operationParams"].get("autoremove"):
1535 self
.db
.del_one("nsrs", {"_id": nsr_id
})
1536 db_nsr_update
.clear()
1537 self
.db
.del_list("nslcmops", {"nsInstanceId": nsr_id
})
1538 db_nslcmop_update
.clear()
1539 self
.db
.del_list("vnfrs", {"nsr-id-ref": nsr_id
})
1540 self
.logger
.debug(logging_text
+ "Delete from database")
1542 db_nsr_update
["operational-status"] = "terminated"
1543 db_nsr_update
["detailed-status"] = "Done"
1544 db_nsr_update
["_admin.nsState"] = "NOT_INSTANTIATED"
1545 db_nslcmop_update
["detailed-status"] = "Done"
1546 db_nslcmop_update
["operationState"] = "COMPLETED"
1547 db_nslcmop_update
["statusEnteredTime"] = time()
1549 await self
.msg
.aiowrite("ns", "terminated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
})
1550 except Exception as e
:
1551 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1552 self
.logger
.debug(logging_text
+ "Exit")
1554 except (ROclient
.ROClientException
, DbException
) as e
:
1555 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
1557 except asyncio
.CancelledError
:
1558 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1559 exc
= "Operation was cancelled"
1560 except Exception as e
:
1561 exc
= traceback
.format_exc()
1562 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
1564 if exc
and db_nslcmop
:
1565 db_nslcmop_update
= {
1566 "detailed-status": "FAILED {}: {}".format(step
, exc
),
1567 "operationState": "FAILED",
1568 "statusEnteredTime": time(),
1570 if db_nslcmop_update
:
1571 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1573 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1574 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_terminate")
1576 async def _ns_execute_primitive(self
, db_deployed
, nsr_name
, member_vnf_index
, vdu_id
, primitive
, primitive_params
):
1578 vdu_id_text
= "vnfd"
1580 vdu_id_text
= vdu_id
1581 application_name
= self
.n2vc
.FormatApplicationName(
1586 vca_deployed
= db_deployed
["VCA"].get(application_name
)
1587 if not vca_deployed
:
1588 raise LcmException("charm for member_vnf_index={} vdu_id={} is not deployed".format(member_vnf_index
,
1590 model_name
= vca_deployed
.get("model")
1591 application_name
= vca_deployed
.get("application")
1592 if not model_name
or not application_name
:
1593 raise LcmException("charm for member_vnf_index={} is not properly deployed".format(member_vnf_index
))
1594 if vca_deployed
["operational-status"] != "active":
1595 raise LcmException("charm for member_vnf_index={} operational_status={} not 'active'".format(
1596 member_vnf_index
, vca_deployed
["operational-status"]))
1597 callback
= None # self.n2vc_callback
1598 callback_args
= () # [db_nsr, db_nslcmop, member_vnf_index, None]
1599 await self
.n2vc
.login()
1600 task
= asyncio
.ensure_future(
1601 self
.n2vc
.ExecutePrimitive(
1604 primitive
, callback
,
1609 # task.add_done_callback(functools.partial(self.n2vc_callback, model_name, application_name, None,
1610 # db_nsr, db_nslcmop, member_vnf_index))
1611 # self.lcm_ns_tasks[nsr_id][nslcmop_id]["action: " + primitive] = task
1612 # wait until completed with timeout
1613 await asyncio
.wait((task
,), timeout
=600)
1615 result
= "FAILED" # by default
1617 if task
.cancelled():
1618 result_detail
= "Task has been cancelled"
1620 exc
= task
.exception()
1622 result_detail
= str(exc
)
1624 # TODO revise with Adam if action is finished and ok when task is done or callback is needed
1625 result
= "COMPLETED"
1626 result_detail
= "Done"
1628 # TODO Should it be cancelled?!!
1630 result_detail
= "timeout"
1631 return result
, result_detail
1633 async def ns_action(self
, nsr_id
, nslcmop_id
):
1634 logging_text
= "Task ns={} action={} ".format(nsr_id
, nslcmop_id
)
1635 self
.logger
.debug(logging_text
+ "Enter")
1636 # get all needed from database
1639 db_nslcmop_update
= None
1642 step
= "Getting information from database"
1643 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1644 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1645 nsr_lcm
= db_nsr
["_admin"].get("deployed")
1646 nsr_name
= db_nsr
["name"]
1647 vnf_index
= db_nslcmop
["operationParams"]["member_vnf_index"]
1648 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
1650 # TODO check if ns is in a proper status
1651 primitive
= db_nslcmop
["operationParams"]["primitive"]
1652 primitive_params
= db_nslcmop
["operationParams"]["primitive_params"]
1653 result
, result_detail
= await self
._ns
_execute
_primitive
(nsr_lcm
, nsr_name
, vnf_index
, vdu_id
, primitive
,
1655 db_nslcmop_update
= {
1656 "detailed-status": result_detail
,
1657 "operationState": result
,
1658 "statusEnteredTime": time()
1660 self
.logger
.debug(logging_text
+ " task Done with result {} {}".format(result
, result_detail
))
1661 return # database update is called inside finally
1663 except (DbException
, LcmException
) as e
:
1664 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
1666 except asyncio
.CancelledError
:
1667 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1668 exc
= "Operation was cancelled"
1669 except Exception as e
:
1670 exc
= traceback
.format_exc()
1671 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
1673 if exc
and db_nslcmop
:
1674 db_nslcmop_update
= {
1675 "detailed-status": "FAILED {}: {}".format(step
, exc
),
1676 "operationState": "FAILED",
1677 "statusEnteredTime": time(),
1679 if db_nslcmop_update
:
1680 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1681 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_action")
1683 async def ns_scale(self
, nsr_id
, nslcmop_id
):
1684 logging_text
= "Task ns={} scale={} ".format(nsr_id
, nslcmop_id
)
1685 self
.logger
.debug(logging_text
+ "Enter")
1686 # get all needed from database
1689 db_nslcmop_update
= {}
1693 step
= "Getting nslcmop from database"
1694 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1695 step
= "Getting nsr from database"
1696 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1697 step
= "Parsing scaling parameters"
1698 db_nsr_update
["operational-status"] = "scaling"
1699 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1700 nsr_lcm
= db_nsr
["_admin"].get("deployed")
1701 RO_nsr_id
= nsr_lcm
["RO"]["nsr_id"]
1702 vnf_index
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
1703 scaling_group
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1704 scaling_type
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleVnfType"]
1705 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
1707 step
= "Getting vnfr from database"
1708 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
1709 step
= "Getting vnfd from database"
1710 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
1711 step
= "Getting scaling-group-descriptor"
1712 for scaling_descriptor
in db_vnfd
["scaling-group-descriptor"]:
1713 if scaling_descriptor
["name"] == scaling_group
:
1716 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
1717 "at vnfd:scaling-group-descriptor".format(scaling_group
))
1719 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
1720 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
1721 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
1724 # TODO check if ns is in a proper status
1725 step
= "Sending scale order to RO"
1727 if not db_nsr
["_admin"].get("scaling-group"):
1728 self
.update_db_2("nsrs", nsr_id
, {"_admin.scaling-group": [{"name": scaling_group
, "nb-scale-op": 0}]})
1729 admin_scale_index
= 0
1731 for admin_scale_index
, admin_scale_info
in enumerate(db_nsr
["_admin"]["scaling-group"]):
1732 if admin_scale_info
["name"] == scaling_group
:
1733 nb_scale_op
= admin_scale_info
.get("nb-scale-op", 0)
1735 RO_scaling_info
= []
1736 vdu_scaling_info
= {"scaling_group_name": scaling_group
, "vdu": []}
1737 if scaling_type
== "SCALE_OUT":
1738 # count if max-instance-count is reached
1739 if "max-instance-count" in scaling_descriptor
and scaling_descriptor
["max-instance-count"] is not None:
1740 max_instance_count
= int(scaling_descriptor
["max-instance-count"])
1741 if nb_scale_op
>= max_instance_count
:
1742 raise LcmException("reached the limit of {} (max-instance-count) scaling-out operations for the"
1743 " scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
1744 nb_scale_op
= nb_scale_op
+ 1
1745 vdu_scaling_info
["scaling_direction"] = "OUT"
1746 vdu_scaling_info
["vdu-create"] = {}
1747 for vdu_scale_info
in scaling_descriptor
["vdu"]:
1748 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
1749 "type": "create", "count": vdu_scale_info
.get("count", 1)})
1750 vdu_scaling_info
["vdu-create"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
1751 elif scaling_type
== "SCALE_IN":
1752 # count if min-instance-count is reached
1753 if "min-instance-count" in scaling_descriptor
and scaling_descriptor
["min-instance-count"] is not None:
1754 min_instance_count
= int(scaling_descriptor
["min-instance-count"])
1755 if nb_scale_op
<= min_instance_count
:
1756 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
1757 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
1758 nb_scale_op
= nb_scale_op
- 1
1759 vdu_scaling_info
["scaling_direction"] = "IN"
1760 vdu_scaling_info
["vdu-delete"] = {}
1761 for vdu_scale_info
in scaling_descriptor
["vdu"]:
1762 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
1763 "type": "delete", "count": vdu_scale_info
.get("count", 1)})
1764 vdu_scaling_info
["vdu-delete"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
1766 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
1767 if vdu_scaling_info
["scaling_direction"] == "IN":
1768 for vdur
in reversed(db_vnfr
["vdur"]):
1769 if vdu_scaling_info
["vdu-delete"].get(vdur
["vdu-id-ref"]):
1770 vdu_scaling_info
["vdu-delete"][vdur
["vdu-id-ref"]] -= 1
1771 vdu_scaling_info
["vdu"].append({
1772 "name": vdur
["name"],
1773 "vdu_id": vdur
["vdu-id-ref"],
1776 for interface
in vdur
["interfaces"]:
1777 vdu_scaling_info
["vdu"][-1]["interface"].append({
1778 "name": interface
["name"],
1779 "ip_address": interface
["ip-address"],
1780 "mac_address": interface
.get("mac-address"),
1782 del vdu_scaling_info
["vdu-delete"]
1784 # execute primitive service PRE-SCALING
1785 step
= "Executing pre-scale vnf-config-primitive"
1786 if scaling_descriptor
.get("scaling-config-action"):
1787 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
1788 if scaling_config_action
.get("trigger") and scaling_config_action
["trigger"] == "pre-scale-in" \
1789 and scaling_type
== "SCALE_IN":
1790 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
1791 step
= db_nslcmop_update
["detailed-status"] = \
1792 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive
)
1793 # look for primitive
1794 primitive_params
= {}
1795 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
1796 if config_primitive
["name"] == vnf_config_primitive
:
1797 for parameter
in config_primitive
.get("parameter", ()):
1798 if 'default-value' in parameter
and \
1799 parameter
['default-value'] == "<VDU_SCALE_INFO>":
1800 primitive_params
[parameter
["name"]] = yaml
.safe_dump(vdu_scaling_info
,
1801 default_flow_style
=True,
1806 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
1807 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-cnfiguration:config-"
1808 "primitive".format(scaling_group
, config_primitive
))
1809 result
, result_detail
= await self
._ns
_execute
_primitive
(nsr_lcm
, vnf_index
,
1810 vnf_config_primitive
, primitive_params
)
1811 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
1812 vnf_config_primitive
, result
, result_detail
))
1813 if result
== "FAILED":
1814 raise LcmException(result_detail
)
1817 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
1818 RO_desc
= await RO
.create_action("ns", RO_nsr_id
, {"vdu-scaling": RO_scaling_info
})
1819 db_nsr_update
["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index
)] = nb_scale_op
1820 db_nsr_update
["_admin.scaling-group.{}.time".format(admin_scale_index
)] = time()
1821 # TODO mark db_nsr_update as scaling
1823 RO_nslcmop_id
= RO_desc
["instance_action_id"]
1824 db_nslcmop_update
["_admin.deploy.RO"] = RO_nslcmop_id
1826 RO_task_done
= False
1827 step
= detailed_status
= "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id
)
1828 detailed_status_old
= None
1829 self
.logger
.debug(logging_text
+ step
)
1831 deployment_timeout
= 1 * 3600 # One hours
1832 while deployment_timeout
> 0:
1833 if not RO_task_done
:
1834 desc
= await RO
.show("ns", item_id_name
=RO_nsr_id
, extra_item
="action",
1835 extra_item_id
=RO_nslcmop_id
)
1836 ns_status
, ns_status_info
= RO
.check_action_status(desc
)
1837 if ns_status
== "ERROR":
1838 raise ROclient
.ROClientException(ns_status_info
)
1839 elif ns_status
== "BUILD":
1840 detailed_status
= step
+ "; {}".format(ns_status_info
)
1841 elif ns_status
== "ACTIVE":
1843 step
= detailed_status
= "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id
)
1844 self
.logger
.debug(logging_text
+ step
)
1846 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
1848 desc
= await RO
.show("ns", RO_nsr_id
)
1849 ns_status
, ns_status_info
= RO
.check_ns_status(desc
)
1850 if ns_status
== "ERROR":
1851 raise ROclient
.ROClientException(ns_status_info
)
1852 elif ns_status
== "BUILD":
1853 detailed_status
= step
+ "; {}".format(ns_status_info
)
1854 elif ns_status
== "ACTIVE":
1855 step
= detailed_status
= "Waiting for management IP address reported by the VIM"
1857 desc
= await RO
.show("ns", RO_nsr_id
)
1858 nsr_lcm
["nsr_ip"] = RO
.get_ns_vnf_info(desc
)
1860 except ROclient
.ROClientException
as e
:
1861 if e
.http_code
!= 409: # IP address is not ready return code is 409 CONFLICT
1864 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
1865 if detailed_status
!= detailed_status_old
:
1866 detailed_status_old
= db_nslcmop_update
["detailed-status"] = detailed_status
1867 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1869 await asyncio
.sleep(5, loop
=self
.loop
)
1870 deployment_timeout
-= 5
1871 if deployment_timeout
<= 0:
1872 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
1874 step
= "Updating VNFRs"
1875 self
.ns_update_vnfr({db_vnfr
["member-vnf-index-ref"]: db_vnfr
}, desc
)
1877 # update VDU_SCALING_INFO with the obtained ip_addresses
1878 if vdu_scaling_info
["scaling_direction"] == "OUT":
1879 for vdur
in reversed(db_vnfr
["vdur"]):
1880 if vdu_scaling_info
["vdu-create"].get(vdur
["vdu-id-ref"]):
1881 vdu_scaling_info
["vdu-create"][vdur
["vdu-id-ref"]] -= 1
1882 vdu_scaling_info
["vdu"].append({
1883 "name": vdur
["name"],
1884 "vdu_id": vdur
["vdu-id-ref"],
1887 for interface
in vdur
["interfaces"]:
1888 vdu_scaling_info
["vdu"][-1]["interface"].append({
1889 "name": interface
["name"],
1890 "ip_address": interface
["ip-address"],
1891 "mac_address": interface
.get("mac-address"),
1893 del vdu_scaling_info
["vdu-create"]
1896 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1898 # execute primitive service POST-SCALING
1899 step
= "Executing post-scale vnf-config-primitive"
1900 if scaling_descriptor
.get("scaling-config-action"):
1901 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
1902 if scaling_config_action
.get("trigger") and scaling_config_action
["trigger"] == "post-scale-out" \
1903 and scaling_type
== "SCALE_OUT":
1904 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
1905 step
= db_nslcmop_update
["detailed-status"] = \
1906 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive
)
1907 # look for primitive
1908 primitive_params
= {}
1909 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
1910 if config_primitive
["name"] == vnf_config_primitive
:
1911 for parameter
in config_primitive
.get("parameter", ()):
1912 if 'default-value' in parameter
and \
1913 parameter
['default-value'] == "<VDU_SCALE_INFO>":
1914 primitive_params
[parameter
["name"]] = yaml
.safe_dump(vdu_scaling_info
,
1915 default_flow_style
=True,
1919 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
1920 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
1921 "match any vnf-cnfiguration:config-primitive".format(scaling_group
,
1923 result
, result_detail
= await self
._ns
_execute
_primitive
(nsr_lcm
, vnf_index
,
1924 vnf_config_primitive
, primitive_params
)
1925 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
1926 vnf_config_primitive
, result
, result_detail
))
1927 if result
== "FAILED":
1928 raise LcmException(result_detail
)
1930 db_nslcmop_update
["operationState"] = "COMPLETED"
1931 db_nslcmop_update
["statusEnteredTime"] = time()
1932 db_nslcmop_update
["detailed-status"] = "done"
1933 db_nsr_update
["detailed-status"] = "done"
1934 db_nsr_update
["operational-status"] = "running"
1936 await self
.msg
.aiowrite("ns", "scaled", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
})
1938 # await asyncio.sleep(cooldown_time)
1939 # await self.msg.aiowrite("ns", "scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
1940 except Exception as e
:
1941 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1942 self
.logger
.debug(logging_text
+ "Exit Ok")
1944 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
1945 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
1947 except asyncio
.CancelledError
:
1948 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1949 exc
= "Operation was cancelled"
1950 except Exception as e
:
1951 exc
= traceback
.format_exc()
1952 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
1956 db_nslcmop_update
= {
1957 "detailed-status": "FAILED {}: {}".format(step
, exc
),
1958 "operationState": "FAILED",
1959 "statusEnteredTime": time(),
1962 db_nsr_update
["operational-status"] = "FAILED {}: {}".format(step
, exc
),
1963 db_nsr_update
["detailed-status"] = "failed"
1964 if db_nslcmop_update
:
1965 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1967 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1968 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_scale")
1970 async def test(self
, param
=None):
1971 self
.logger
.debug("Starting/Ending test task: {}".format(param
))
1973 async def kafka_ping(self
):
1974 self
.logger
.debug("Task kafka_ping Enter")
1975 consecutive_errors
= 0
1977 kafka_has_received
= False
1978 self
.pings_not_received
= 1
1981 await self
.msg
.aiowrite("admin", "ping", {"from": "lcm", "to": "lcm"}, self
.loop
)
1982 # time between pings are low when it is not received and at starting
1983 wait_time
= 5 if not kafka_has_received
else 120
1984 if not self
.pings_not_received
:
1985 kafka_has_received
= True
1986 self
.pings_not_received
+= 1
1987 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
1988 if self
.pings_not_received
> 10:
1989 raise LcmException("It is not receiving pings from Kafka bus")
1990 consecutive_errors
= 0
1992 except LcmException
:
1994 except Exception as e
:
1995 # if not first_start is the first time after starting. So leave more time and wait
1996 # to allow kafka starts
1997 if consecutive_errors
== 8 if not first_start
else 30:
1998 self
.logger
.error("Task kafka_read task exit error too many errors. Exception: {}".format(e
))
2000 consecutive_errors
+= 1
2001 self
.logger
.error("Task kafka_read retrying after Exception {}".format(e
))
2002 wait_time
= 1 if not first_start
else 5
2003 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
2005 async def kafka_read(self
):
2006 self
.logger
.debug("Task kafka_read Enter")
2008 # future = asyncio.Future()
2009 consecutive_errors
= 0
2011 while consecutive_errors
< 10:
2013 topics
= ("admin", "ns", "vim_account", "sdn")
2014 topic
, command
, params
= await self
.msg
.aioread(topics
, self
.loop
)
2015 if topic
!= "admin" and command
!= "ping":
2016 self
.logger
.debug("Task kafka_read receives {} {}: {}".format(topic
, command
, params
))
2017 consecutive_errors
= 0
2020 if command
== "exit":
2023 elif command
.startswith("#"):
2025 elif command
== "echo":
2030 elif command
== "test":
2031 asyncio
.Task(self
.test(params
), loop
=self
.loop
)
2034 if topic
== "admin":
2035 if command
== "ping" and params
["to"] == "lcm" and params
["from"] == "lcm":
2036 self
.pings_not_received
= 0
2039 if command
== "instantiate":
2040 # self.logger.debug("Deploying NS {}".format(nsr_id))
2042 nslcmop_id
= nslcmop
["_id"]
2043 nsr_id
= nslcmop
["nsInstanceId"]
2044 task
= asyncio
.ensure_future(self
.ns_instantiate(nsr_id
, nslcmop_id
))
2045 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_instantiate", task
)
2047 elif command
== "terminate":
2048 # self.logger.debug("Deleting NS {}".format(nsr_id))
2050 nslcmop_id
= nslcmop
["_id"]
2051 nsr_id
= nslcmop
["nsInstanceId"]
2052 self
.lcm_tasks
.cancel(topic
, nsr_id
)
2053 task
= asyncio
.ensure_future(self
.ns_terminate(nsr_id
, nslcmop_id
))
2054 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_terminate", task
)
2056 elif command
== "action":
2057 # self.logger.debug("Update NS {}".format(nsr_id))
2059 nslcmop_id
= nslcmop
["_id"]
2060 nsr_id
= nslcmop
["nsInstanceId"]
2061 task
= asyncio
.ensure_future(self
.ns_action(nsr_id
, nslcmop_id
))
2062 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_action", task
)
2064 elif command
== "scale":
2065 # self.logger.debug("Update NS {}".format(nsr_id))
2067 nslcmop_id
= nslcmop
["_id"]
2068 nsr_id
= nslcmop
["nsInstanceId"]
2069 task
= asyncio
.ensure_future(self
.ns_scale(nsr_id
, nslcmop_id
))
2070 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_scale", task
)
2072 elif command
== "show":
2074 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2075 print("nsr:\n _id={}\n operational-status: {}\n config-status: {}"
2076 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
2077 "".format(nsr_id
, db_nsr
["operational-status"], db_nsr
["config-status"],
2078 db_nsr
["detailed-status"],
2079 db_nsr
["_admin"]["deployed"], self
.lcm_ns_tasks
.get(nsr_id
)))
2080 except Exception as e
:
2081 print("nsr {} not found: {}".format(nsr_id
, e
))
2084 elif command
== "deleted":
2085 continue # TODO cleaning of task just in case should be done
2086 elif command
in ("terminated", "instantiated", "scaled", "actioned"): # "scaled-cooldown-time"
2088 elif topic
== "vim_account":
2089 vim_id
= params
["_id"]
2090 if command
== "create":
2091 task
= asyncio
.ensure_future(self
.vim_create(params
, order_id
))
2092 self
.lcm_tasks
.register("vim_account", vim_id
, order_id
, "vim_create", task
)
2094 elif command
== "delete":
2095 self
.lcm_tasks
.cancel(topic
, vim_id
)
2096 task
= asyncio
.ensure_future(self
.vim_delete(vim_id
, order_id
))
2097 self
.lcm_tasks
.register("vim_account", vim_id
, order_id
, "vim_delete", task
)
2099 elif command
== "show":
2100 print("not implemented show with vim_account")
2103 elif command
== "edit":
2104 task
= asyncio
.ensure_future(self
.vim_edit(params
, order_id
))
2105 self
.lcm_tasks
.register("vim_account", vim_id
, order_id
, "vim_edit", task
)
2107 elif topic
== "sdn":
2108 _sdn_id
= params
["_id"]
2109 if command
== "create":
2110 task
= asyncio
.ensure_future(self
.sdn_create(params
, order_id
))
2111 self
.lcm_tasks
.register("sdn", _sdn_id
, order_id
, "sdn_create", task
)
2113 elif command
== "delete":
2114 self
.lcm_tasks
.cancel(topic
, _sdn_id
)
2115 task
= asyncio
.ensure_future(self
.sdn_delete(_sdn_id
, order_id
))
2116 self
.lcm_tasks
.register("sdn", _sdn_id
, order_id
, "sdn_delete", task
)
2118 elif command
== "edit":
2119 task
= asyncio
.ensure_future(self
.sdn_edit(params
, order_id
))
2120 self
.lcm_tasks
.register("sdn", _sdn_id
, order_id
, "sdn_edit", task
)
2122 self
.logger
.critical("unknown topic {} and command '{}'".format(topic
, command
))
2123 except Exception as e
:
2124 # if not first_start is the first time after starting. So leave more time and wait
2125 # to allow kafka starts
2126 if consecutive_errors
== 8 if not first_start
else 30:
2127 self
.logger
.error("Task kafka_read task exit error too many errors. Exception: {}".format(e
))
2129 consecutive_errors
+= 1
2130 self
.logger
.error("Task kafka_read retrying after Exception {}".format(e
))
2131 wait_time
= 2 if not first_start
else 5
2132 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
2134 # self.logger.debug("Task kafka_read terminating")
2135 self
.logger
.debug("Task kafka_read exit")
2138 self
.loop
= asyncio
.get_event_loop()
2141 self
.loop
.run_until_complete(self
.check_RO_version())
2143 self
.loop
.run_until_complete(asyncio
.gather(
2148 # self.logger.debug("Terminating cancelling creation tasks")
2149 # self.lcm_tasks.cancel("ALL", "create")
2151 # while self.is_pending_tasks():
2152 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
2153 # await asyncio.sleep(2, loop=self.loop)
2156 # self.lcm_tasks.cancel("ALL", "ALL")
2160 self
.db
.db_disconnect()
2162 self
.msg
.disconnect()
2164 self
.fs
.fs_disconnect()
2166 def read_config_file(self
, config_file
):
2167 # TODO make a [ini] + yaml inside parser
2168 # the configparser library is not suitable, because it does not admit comments at the end of line,
2169 # and not parse integer or boolean
2171 with
open(config_file
) as f
:
2173 for k
, v
in environ
.items():
2174 if not k
.startswith("OSMLCM_"):
2176 k_items
= k
.lower().split("_")
2179 for k_item
in k_items
[1:-1]:
2180 if k_item
in ("ro", "vca"):
2181 # put in capital letter
2182 k_item
= k_item
.upper()
2184 if k_items
[-1] == "port":
2185 c
[k_items
[-1]] = int(v
)
2188 except Exception as e
:
2189 self
.logger
.warn("skipping environ '{}' on exception '{}'".format(k
, e
))
2192 except Exception as e
:
2193 self
.logger
.critical("At config file '{}': {}".format(config_file
, e
))
2198 print("""Usage: {} [options]
2199 -c|--config [configuration_file]: loads the configuration file (default: ./nbi.cfg)
2200 -h|--help: shows this help
2201 """.format(sys
.argv
[0]))
2202 # --log-socket-host HOST: send logs to this host")
2203 # --log-socket-port PORT: send logs using this port (default: 9022)")
2206 if __name__
== '__main__':
2208 # load parameters and configuration
2209 opts
, args
= getopt
.getopt(sys
.argv
[1:], "hc:", ["config=", "help"])
2210 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
2213 if o
in ("-h", "--help"):
2216 elif o
in ("-c", "--config"):
2218 # elif o == "--log-socket-port":
2219 # log_socket_port = a
2220 # elif o == "--log-socket-host":
2221 # log_socket_host = a
2222 # elif o == "--log-file":
2225 assert False, "Unhandled option"
2227 if not path
.isfile(config_file
):
2228 print("configuration file '{}' that not exist".format(config_file
), file=sys
.stderr
)
2231 for config_file
in (__file__
[:__file__
.rfind(".")] + ".cfg", "./lcm.cfg", "/etc/osm/lcm.cfg"):
2232 if path
.isfile(config_file
):
2235 print("No configuration file 'nbi.cfg' found neither at local folder nor at /etc/osm/", file=sys
.stderr
)
2237 lcm
= Lcm(config_file
)
2239 except (LcmException
, getopt
.GetoptError
) as e
:
2240 print(str(e
), file=sys
.stderr
)