2 # -*- coding: utf-8 -*-
8 import logging
.handlers
13 from osm_common
import dbmemory
14 from osm_common
import dbmongo
15 from osm_common
import fslocal
16 from osm_common
import msglocal
17 from osm_common
import msgkafka
18 from osm_common
.dbbase
import DbException
19 from osm_common
.fsbase
import FsException
20 from osm_common
.msgbase
import MsgException
21 from os
import environ
, path
22 from n2vc
.vnf
import N2VC
23 from n2vc
import version
as N2VC_version
25 from collections
import OrderedDict
26 from copy
import deepcopy
27 from http
import HTTPStatus
31 __author__
= "Alfonso Tierno"
32 min_RO_version
= [0, 5, 72]
35 class LcmException(Exception):
41 Implements a registry of task needed for later cancelation, look for related tasks that must be completed before
42 etc. It stores a four level dict
43 First level is the topic, ns, vim_account, sdn
44 Second level is the _id
45 Third level is the operation id
46 Fourth level is a descriptive name, the value is the task class
50 self
.task_registry
= {
56 def register(self
, topic
, _id
, op_id
, task_name
, task
):
59 :param topic: Can be "ns", "vim_account", "sdn"
60 :param _id: _id of the related item
61 :param op_id: id of the operation of the related item
62 :param task_name: Task descriptive name, as create, instantiate, terminate. Must be unique in this op_id
63 :param task: Task class
66 if _id
not in self
.task_registry
[topic
]:
67 self
.task_registry
[topic
][_id
] = OrderedDict()
68 if op_id
not in self
.task_registry
[topic
][_id
]:
69 self
.task_registry
[topic
][_id
][op_id
] = {task_name
: task
}
71 self
.task_registry
[topic
][_id
][op_id
][task_name
] = task
72 # print("registering task", topic, _id, op_id, task_name, task)
74 def remove(self
, topic
, _id
, op_id
, task_name
=None):
76 When task is ended, it should removed. It ignores missing tasks
77 :param topic: Can be "ns", "vim_account", "sdn"
78 :param _id: _id of the related item
79 :param op_id: id of the operation of the related item
80 :param task_name: Task descriptive name. If note it deletes all
83 if not self
.task_registry
[topic
].get(_id
) or not self
.task_registry
[topic
][_id
].get(op_id
):
86 # print("deleting tasks", topic, _id, op_id, self.task_registry[topic][_id][op_id])
87 del self
.task_registry
[topic
][_id
][op_id
]
88 elif task_name
in self
.task_registry
[topic
][_id
][op_id
]:
89 # print("deleting tasks", topic, _id, op_id, task_name, self.task_registry[topic][_id][op_id][task_name])
90 del self
.task_registry
[topic
][_id
][op_id
][task_name
]
91 if not self
.task_registry
[topic
][_id
][op_id
]:
92 del self
.task_registry
[topic
][_id
][op_id
]
93 if not self
.task_registry
[topic
][_id
]:
94 del self
.task_registry
[topic
][_id
]
96 def lookfor_related(self
, topic
, _id
, my_op_id
=None):
99 if _id
not in self
.task_registry
[topic
]:
100 return "", task_name_list
101 for op_id
in reversed(self
.task_registry
[topic
][_id
]):
103 if my_op_id
== op_id
:
104 my_op_id
= None # so that the next task is taken
107 for task_name
, task
in self
.task_registry
[topic
][_id
][op_id
].items():
108 task_list
.append(task
)
109 task_name_list
.append(task_name
)
111 return ", ".join(task_name_list
), task_list
113 def cancel(self
, topic
, _id
, target_op_id
=None, target_task_name
=None):
115 Cancel all active tasks of a concrete ns, vim_account, sdn identified for _id. If op_id is supplied only this is
116 cancelled, and the same with task_name
118 if not self
.task_registry
[topic
].get(_id
):
120 for op_id
in reversed(self
.task_registry
[topic
][_id
]):
121 if target_op_id
and target_op_id
!= op_id
:
123 for task_name
, task
in self
.task_registry
[topic
][_id
][op_id
].items():
124 if target_task_name
and target_task_name
!= task_name
:
126 result
= task
.cancel()
128 self
.logger
.debug("{} _id={} order_id={} task={} cancelled".format(topic
, _id
, op_id
, task_name
))
133 def __init__(self
, config_file
):
135 Init, Connect to database, filesystem storage, and messaging
136 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
143 self
.pings_not_received
= 1
145 # contains created tasks/futures to be able to cancel
146 self
.lcm_tasks
= TaskRegistry()
148 self
.logger
= logging
.getLogger('lcm')
150 config
= self
.read_config_file(config_file
)
153 "endpoint_url": "http://{}:{}/openmano".format(config
["RO"]["host"], config
["RO"]["port"]),
154 "tenant": config
.get("tenant", "osm"),
155 "logger_name": "lcm.ROclient",
159 self
.vca
= config
["VCA"] # TODO VCA
163 log_format_simple
= "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
164 log_formatter_simple
= logging
.Formatter(log_format_simple
, datefmt
='%Y-%m-%dT%H:%M:%S')
165 config
["database"]["logger_name"] = "lcm.db"
166 config
["storage"]["logger_name"] = "lcm.fs"
167 config
["message"]["logger_name"] = "lcm.msg"
168 if "logfile" in config
["global"]:
169 file_handler
= logging
.handlers
.RotatingFileHandler(config
["global"]["logfile"],
170 maxBytes
=100e6
, backupCount
=9, delay
=0)
171 file_handler
.setFormatter(log_formatter_simple
)
172 self
.logger
.addHandler(file_handler
)
174 str_handler
= logging
.StreamHandler()
175 str_handler
.setFormatter(log_formatter_simple
)
176 self
.logger
.addHandler(str_handler
)
178 if config
["global"].get("loglevel"):
179 self
.logger
.setLevel(config
["global"]["loglevel"])
181 # logging other modules
182 for k1
, logname
in {"message": "lcm.msg", "database": "lcm.db", "storage": "lcm.fs"}.items():
183 config
[k1
]["logger_name"] = logname
184 logger_module
= logging
.getLogger(logname
)
185 if "logfile" in config
[k1
]:
186 file_handler
= logging
.handlers
.RotatingFileHandler(config
[k1
]["logfile"],
187 maxBytes
=100e6
, backupCount
=9, delay
=0)
188 file_handler
.setFormatter(log_formatter_simple
)
189 logger_module
.addHandler(file_handler
)
190 if "loglevel" in config
[k1
]:
191 logger_module
.setLevel(config
[k1
]["loglevel"])
195 server
=config
['VCA']['host'],
196 port
=config
['VCA']['port'],
197 user
=config
['VCA']['user'],
198 secret
=config
['VCA']['secret'],
199 # TODO: This should point to the base folder where charms are stored,
200 # if there is a common one (like object storage). Otherwise, leave
201 # it unset and pass it via DeployCharms
202 # artifacts=config['VCA'][''],
205 # check version of N2VC
206 # TODO enhance with int conversion or from distutils.version import LooseVersion
207 # or with list(map(int, version.split(".")))
208 if N2VC_version
< "0.0.2":
209 raise LcmException("Not compatible osm/N2VC version '{}'. Needed '0.0.2' or higher".format(N2VC_version
))
212 # TODO check database version
213 if config
["database"]["driver"] == "mongo":
214 self
.db
= dbmongo
.DbMongo()
215 self
.db
.db_connect(config
["database"])
216 elif config
["database"]["driver"] == "memory":
217 self
.db
= dbmemory
.DbMemory()
218 self
.db
.db_connect(config
["database"])
220 raise LcmException("Invalid configuration param '{}' at '[database]':'driver'".format(
221 config
["database"]["driver"]))
223 if config
["storage"]["driver"] == "local":
224 self
.fs
= fslocal
.FsLocal()
225 self
.fs
.fs_connect(config
["storage"])
227 raise LcmException("Invalid configuration param '{}' at '[storage]':'driver'".format(
228 config
["storage"]["driver"]))
230 if config
["message"]["driver"] == "local":
231 self
.msg
= msglocal
.MsgLocal()
232 self
.msg
.connect(config
["message"])
233 elif config
["message"]["driver"] == "kafka":
234 self
.msg
= msgkafka
.MsgKafka()
235 self
.msg
.connect(config
["message"])
237 raise LcmException("Invalid configuration param '{}' at '[message]':'driver'".format(
238 config
["storage"]["driver"]))
239 except (DbException
, FsException
, MsgException
) as e
:
240 self
.logger
.critical(str(e
), exc_info
=True)
241 raise LcmException(str(e
))
243 async def check_RO_version(self
):
245 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
246 RO_version
= await RO
.get_version()
247 if RO_version
< min_RO_version
:
248 raise LcmException("Not compatible osm/RO version '{}.{}.{}'. Needed '{}.{}.{}' or higher".format(
249 *RO_version
, *min_RO_version
251 except ROclient
.ROClientException
as e
:
252 self
.logger
.critical("Error while conneting to osm/RO " + str(e
), exc_info
=True)
253 raise LcmException(str(e
))
255 def update_db_2(self
, item
, _id
, _desc
):
257 Updates database with _desc information. Upon success _desc is cleared
266 self
.db
.set_one(item
, {"_id": _id
}, _desc
)
268 except DbException
as e
:
269 self
.logger
.error("Updating {} _id={} with '{}'. Error: {}".format(item
, _id
, _desc
, e
))
271 async def vim_create(self
, vim_content
, order_id
):
272 vim_id
= vim_content
["_id"]
273 logging_text
= "Task vim_create={} ".format(vim_id
)
274 self
.logger
.debug(logging_text
+ "Enter")
280 step
= "Getting vim-id='{}' from db".format(vim_id
)
281 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_id
})
282 db_vim_update
["_admin.deployed.RO"] = None
283 if vim_content
.get("config") and vim_content
["config"].get("sdn-controller"):
284 step
= "Getting sdn-controller-id='{}' from db".format(vim_content
["config"]["sdn-controller"])
285 db_sdn
= self
.db
.get_one("sdns", {"_id": vim_content
["config"]["sdn-controller"]})
286 if db_sdn
.get("_admin") and db_sdn
["_admin"].get("deployed") and db_sdn
["_admin"]["deployed"].get("RO"):
287 RO_sdn_id
= db_sdn
["_admin"]["deployed"]["RO"]
289 raise LcmException("sdn-controller={} is not available. Not deployed at RO".format(
290 vim_content
["config"]["sdn-controller"]))
292 step
= "Creating vim at RO"
293 db_vim_update
["_admin.detailed-status"] = step
294 self
.update_db_2("vim_accounts", vim_id
, db_vim_update
)
295 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
296 vim_RO
= deepcopy(vim_content
)
297 vim_RO
.pop("_id", None)
298 vim_RO
.pop("_admin", None)
299 vim_RO
.pop("schema_version", None)
300 vim_RO
.pop("schema_type", None)
301 vim_RO
.pop("vim_tenant_name", None)
302 vim_RO
["type"] = vim_RO
.pop("vim_type")
303 vim_RO
.pop("vim_user", None)
304 vim_RO
.pop("vim_password", None)
306 vim_RO
["config"]["sdn-controller"] = RO_sdn_id
307 desc
= await RO
.create("vim", descriptor
=vim_RO
)
308 RO_vim_id
= desc
["uuid"]
309 db_vim_update
["_admin.deployed.RO"] = RO_vim_id
311 step
= "Creating vim_account at RO"
312 db_vim_update
["_admin.detailed-status"] = step
313 self
.update_db_2("vim_accounts", vim_id
, db_vim_update
)
315 vim_account_RO
= {"vim_tenant_name": vim_content
["vim_tenant_name"],
316 "vim_username": vim_content
["vim_user"],
317 "vim_password": vim_content
["vim_password"]
319 if vim_RO
.get("config"):
320 vim_account_RO
["config"] = vim_RO
["config"]
321 if "sdn-controller" in vim_account_RO
["config"]:
322 del vim_account_RO
["config"]["sdn-controller"]
323 if "sdn-port-mapping" in vim_account_RO
["config"]:
324 del vim_account_RO
["config"]["sdn-port-mapping"]
325 desc
= await RO
.attach_datacenter(RO_vim_id
, descriptor
=vim_account_RO
)
326 db_vim_update
["_admin.deployed.RO-account"] = desc
["uuid"]
327 db_vim_update
["_admin.operationalState"] = "ENABLED"
328 db_vim_update
["_admin.detailed-status"] = "Done"
330 # await asyncio.sleep(15) # TODO remove. This is for test
331 self
.logger
.debug(logging_text
+ "Exit Ok RO_vim_id={}".format(RO_vim_id
))
334 except (ROclient
.ROClientException
, DbException
) as e
:
335 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
337 except Exception as e
:
338 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
342 db_vim_update
["_admin.operationalState"] = "ERROR"
343 db_vim_update
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
345 self
.update_db_2("vim_accounts", vim_id
, db_vim_update
)
346 self
.lcm_tasks
.remove("vim_account", vim_id
, order_id
)
348 async def vim_edit(self
, vim_content
, order_id
):
349 vim_id
= vim_content
["_id"]
350 logging_text
= "Task vim_edit={} ".format(vim_id
)
351 self
.logger
.debug(logging_text
+ "Enter")
357 step
= "Getting vim-id='{}' from db".format(vim_id
)
359 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_id
})
361 # look if previous tasks in process
362 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account", vim_id
, order_id
)
364 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
365 self
.logger
.debug(logging_text
+ step
)
366 # TODO write this to database
367 await asyncio
.wait(task_dependency
, timeout
=3600)
369 if db_vim
.get("_admin") and db_vim
["_admin"].get("deployed") and db_vim
["_admin"]["deployed"].get("RO"):
370 if vim_content
.get("config") and vim_content
["config"].get("sdn-controller"):
371 step
= "Getting sdn-controller-id='{}' from db".format(vim_content
["config"]["sdn-controller"])
372 db_sdn
= self
.db
.get_one("sdns", {"_id": vim_content
["config"]["sdn-controller"]})
374 # look if previous tasks in process
375 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("sdn", db_sdn
["_id"])
377 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
378 self
.logger
.debug(logging_text
+ step
)
379 # TODO write this to database
380 await asyncio
.wait(task_dependency
, timeout
=3600)
382 if db_sdn
.get("_admin") and db_sdn
["_admin"].get("deployed") and db_sdn
["_admin"]["deployed"].get(
384 RO_sdn_id
= db_sdn
["_admin"]["deployed"]["RO"]
386 raise LcmException("sdn-controller={} is not available. Not deployed at RO".format(
387 vim_content
["config"]["sdn-controller"]))
389 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
390 step
= "Editing vim at RO"
391 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
392 vim_RO
= deepcopy(vim_content
)
393 vim_RO
.pop("_id", None)
394 vim_RO
.pop("_admin", None)
395 vim_RO
.pop("schema_version", None)
396 vim_RO
.pop("schema_type", None)
397 vim_RO
.pop("vim_tenant_name", None)
398 if "vim_type" in vim_RO
:
399 vim_RO
["type"] = vim_RO
.pop("vim_type")
400 vim_RO
.pop("vim_user", None)
401 vim_RO
.pop("vim_password", None)
403 vim_RO
["config"]["sdn-controller"] = RO_sdn_id
404 # TODO make a deep update of sdn-port-mapping
406 await RO
.edit("vim", RO_vim_id
, descriptor
=vim_RO
)
408 step
= "Editing vim-account at RO tenant"
410 if "config" in vim_content
:
411 if "sdn-controller" in vim_content
["config"]:
412 del vim_content
["config"]["sdn-controller"]
413 if "sdn-port-mapping" in vim_content
["config"]:
414 del vim_content
["config"]["sdn-port-mapping"]
415 if not vim_content
["config"]:
416 del vim_content
["config"]
417 for k
in ("vim_tenant_name", "vim_password", "config"):
419 vim_account_RO
[k
] = vim_content
[k
]
420 if "vim_user" in vim_content
:
421 vim_content
["vim_username"] = vim_content
["vim_user"]
422 # vim_account must be edited always even if empty in order to ensure changes are translated to RO
423 # vim_thread. RO will remove and relaunch a new thread for this vim_account
424 await RO
.edit("vim_account", RO_vim_id
, descriptor
=vim_account_RO
)
425 db_vim_update
["_admin.operationalState"] = "ENABLED"
427 self
.logger
.debug(logging_text
+ "Exit Ok RO_vim_id={}".format(RO_vim_id
))
430 except (ROclient
.ROClientException
, DbException
) as e
:
431 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
433 except Exception as e
:
434 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
438 db_vim_update
["_admin.operationalState"] = "ERROR"
439 db_vim_update
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
441 self
.update_db_2("vim_accounts", vim_id
, db_vim_update
)
442 self
.lcm_tasks
.remove("vim_account", vim_id
, order_id
)
444 async def vim_delete(self
, vim_id
, order_id
):
445 logging_text
= "Task vim_delete={} ".format(vim_id
)
446 self
.logger
.debug(logging_text
+ "Enter")
450 step
= "Getting vim from db"
452 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_id
})
453 if db_vim
.get("_admin") and db_vim
["_admin"].get("deployed") and db_vim
["_admin"]["deployed"].get("RO"):
454 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
455 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
456 step
= "Detaching vim from RO tenant"
458 await RO
.detach_datacenter(RO_vim_id
)
459 except ROclient
.ROClientException
as e
:
460 if e
.http_code
== 404: # not found
461 self
.logger
.debug(logging_text
+ "RO_vim_id={} already detached".format(RO_vim_id
))
465 step
= "Deleting vim from RO"
467 await RO
.delete("vim", RO_vim_id
)
468 except ROclient
.ROClientException
as e
:
469 if e
.http_code
== 404: # not found
470 self
.logger
.debug(logging_text
+ "RO_vim_id={} already deleted".format(RO_vim_id
))
475 self
.logger
.error(logging_text
+ "Nohing to remove at RO")
476 self
.db
.del_one("vim_accounts", {"_id": vim_id
})
477 self
.logger
.debug(logging_text
+ "Exit Ok")
480 except (ROclient
.ROClientException
, DbException
) as e
:
481 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
483 except Exception as e
:
484 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
487 self
.lcm_tasks
.remove("vim_account", vim_id
, order_id
)
489 db_vim_update
["_admin.operationalState"] = "ERROR"
490 db_vim_update
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
492 self
.update_db_2("vim_accounts", vim_id
, db_vim_update
)
493 self
.lcm_tasks
.remove("vim_account", vim_id
, order_id
)
495 async def sdn_create(self
, sdn_content
, order_id
):
496 sdn_id
= sdn_content
["_id"]
497 logging_text
= "Task sdn_create={} ".format(sdn_id
)
498 self
.logger
.debug(logging_text
+ "Enter")
504 step
= "Getting sdn from db"
505 db_sdn
= self
.db
.get_one("sdns", {"_id": sdn_id
})
506 db_sdn_update
["_admin.deployed.RO"] = None
508 step
= "Creating sdn at RO"
509 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
510 sdn_RO
= deepcopy(sdn_content
)
511 sdn_RO
.pop("_id", None)
512 sdn_RO
.pop("_admin", None)
513 sdn_RO
.pop("schema_version", None)
514 sdn_RO
.pop("schema_type", None)
515 sdn_RO
.pop("description", None)
516 desc
= await RO
.create("sdn", descriptor
=sdn_RO
)
517 RO_sdn_id
= desc
["uuid"]
518 db_sdn_update
["_admin.deployed.RO"] = RO_sdn_id
519 db_sdn_update
["_admin.operationalState"] = "ENABLED"
520 self
.logger
.debug(logging_text
+ "Exit Ok RO_sdn_id={}".format(RO_sdn_id
))
523 except (ROclient
.ROClientException
, DbException
) as e
:
524 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
526 except Exception as e
:
527 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
531 db_sdn_update
["_admin.operationalState"] = "ERROR"
532 db_sdn_update
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
534 self
.update_db_2("sdns", sdn_id
, db_sdn_update
)
535 self
.lcm_tasks
.remove("sdn", sdn_id
, order_id
)
537 async def sdn_edit(self
, sdn_content
, order_id
):
538 sdn_id
= sdn_content
["_id"]
539 logging_text
= "Task sdn_edit={} ".format(sdn_id
)
540 self
.logger
.debug(logging_text
+ "Enter")
544 step
= "Getting sdn from db"
546 db_sdn
= self
.db
.get_one("sdns", {"_id": sdn_id
})
547 if db_sdn
.get("_admin") and db_sdn
["_admin"].get("deployed") and db_sdn
["_admin"]["deployed"].get("RO"):
548 RO_sdn_id
= db_sdn
["_admin"]["deployed"]["RO"]
549 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
550 step
= "Editing sdn at RO"
551 sdn_RO
= deepcopy(sdn_content
)
552 sdn_RO
.pop("_id", None)
553 sdn_RO
.pop("_admin", None)
554 sdn_RO
.pop("schema_version", None)
555 sdn_RO
.pop("schema_type", None)
556 sdn_RO
.pop("description", None)
558 await RO
.edit("sdn", RO_sdn_id
, descriptor
=sdn_RO
)
559 db_sdn_update
["_admin.operationalState"] = "ENABLED"
561 self
.logger
.debug(logging_text
+ "Exit Ok RO_sdn_id".format(RO_sdn_id
))
564 except (ROclient
.ROClientException
, DbException
) as e
:
565 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
567 except Exception as e
:
568 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
572 db_sdn
["_admin.operationalState"] = "ERROR"
573 db_sdn
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
575 self
.update_db_2("sdns", sdn_id
, db_sdn_update
)
576 self
.lcm_tasks
.remove("sdn", sdn_id
, order_id
)
578 async def sdn_delete(self
, sdn_id
, order_id
):
579 logging_text
= "Task sdn_delete={} ".format(sdn_id
)
580 self
.logger
.debug(logging_text
+ "Enter")
584 step
= "Getting sdn from db"
586 db_sdn
= self
.db
.get_one("sdns", {"_id": sdn_id
})
587 if db_sdn
.get("_admin") and db_sdn
["_admin"].get("deployed") and db_sdn
["_admin"]["deployed"].get("RO"):
588 RO_sdn_id
= db_sdn
["_admin"]["deployed"]["RO"]
589 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
590 step
= "Deleting sdn from RO"
592 await RO
.delete("sdn", RO_sdn_id
)
593 except ROclient
.ROClientException
as e
:
594 if e
.http_code
== 404: # not found
595 self
.logger
.debug(logging_text
+ "RO_sdn_id={} already deleted".format(RO_sdn_id
))
600 self
.logger
.error(logging_text
+ "Skipping. There is not RO information at database")
601 self
.db
.del_one("sdns", {"_id": sdn_id
})
602 self
.logger
.debug("sdn_delete task sdn_id={} Exit Ok".format(sdn_id
))
605 except (ROclient
.ROClientException
, DbException
) as e
:
606 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
608 except Exception as e
:
609 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
613 db_sdn
["_admin.operationalState"] = "ERROR"
614 db_sdn
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
616 self
.update_db_2("sdns", sdn_id
, db_sdn_update
)
617 self
.lcm_tasks
.remove("sdn", sdn_id
, order_id
)
619 def vnfd2RO(self
, vnfd
, new_id
=None):
621 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
622 :param vnfd: input vnfd
623 :param new_id: overrides vnf id if provided
624 :return: copy of vnfd
628 vnfd_RO
= deepcopy(vnfd
)
629 vnfd_RO
.pop("_id", None)
630 vnfd_RO
.pop("_admin", None)
632 vnfd_RO
["id"] = new_id
633 for vdu
in vnfd_RO
["vdu"]:
634 if "cloud-init-file" in vdu
:
635 base_folder
= vnfd
["_admin"]["storage"]
636 clout_init_file
= "{}/{}/cloud_init/{}".format(
637 base_folder
["folder"],
638 base_folder
["pkg-dir"],
639 vdu
["cloud-init-file"]
641 ci_file
= self
.fs
.file_open(clout_init_file
, "r")
642 # TODO: detect if binary or text. Propose to read as binary and try to decode to utf8. If fails
643 # convert to base 64 or similar
644 clout_init_content
= ci_file
.read()
647 vdu
.pop("cloud-init-file", None)
648 vdu
["cloud-init"] = clout_init_content
649 # remnove unused by RO configuration, monitoring, scaling
650 vnfd_RO
.pop("vnf-configuration", None)
651 vnfd_RO
.pop("monitoring-param", None)
652 vnfd_RO
.pop("scaling-group-descriptor", None)
654 except FsException
as e
:
655 raise LcmException("Error reading file at vnfd {}: {} ".format(vnfd
["_id"], e
))
660 def n2vc_callback(self
, model_name
, application_name
, status
, message
, db_nsr
, db_nslcmop
, member_vnf_index
,
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 member_vnf_index: NSD member-vnf-index
679 :param task: None for charm status change, or task for completion task callback
685 db_nslcmop_update
= {}
687 nsr_id
= db_nsr
["_id"]
688 nslcmop_id
= db_nslcmop
["_id"]
689 nsr_lcm
= db_nsr
["_admin"]["deployed"]
690 ns_operation
= db_nslcmop
["lcmOperationType"]
691 logging_text
= "Task ns={} {}={} [n2vc_callback] vnf_index={}".format(nsr_id
, ns_operation
, nslcmop_id
,
696 self
.logger
.debug(logging_text
+ " task Cancelled")
697 # TODO update db_nslcmop
701 exc
= task
.exception()
703 self
.logger
.error(logging_text
+ " task Exception={}".format(exc
))
704 if ns_operation
in ("instantiate", "terminate"):
705 nsr_lcm
["VCA"][member_vnf_index
]['operational-status'] = "error"
706 db_nsr_update
["_admin.deployed.VCA.{}.operational-status".format(member_vnf_index
)] = \
708 nsr_lcm
["VCA"][member_vnf_index
]['detailed-status'] = str(exc
)
710 "_admin.deployed.VCA.{}.detailed-status".format(member_vnf_index
)] = str(exc
)
711 elif ns_operation
== "action":
712 db_nslcmop_update
["operationState"] = "FAILED"
713 db_nslcmop_update
["detailed-status"] = str(exc
)
714 db_nslcmop_update
["statusEnteredTime"] = time()
718 self
.logger
.debug(logging_text
+ " task Done")
719 # TODO revise with Adam if action is finished and ok when task is done
720 if ns_operation
== "action":
721 db_nslcmop_update
["operationState"] = "COMPLETED"
722 db_nslcmop_update
["detailed-status"] = "Done"
723 db_nslcmop_update
["statusEnteredTime"] = time()
724 # task is Done, but callback is still ongoing. So ignore
727 self
.logger
.debug(logging_text
+ " Enter status={}".format(status
))
728 if nsr_lcm
["VCA"][member_vnf_index
]['operational-status'] == status
:
729 return # same status, ignore
730 nsr_lcm
["VCA"][member_vnf_index
]['operational-status'] = status
731 db_nsr_update
["_admin.deployed.VCA.{}.operational-status".format(member_vnf_index
)] = status
732 nsr_lcm
["VCA"][member_vnf_index
]['detailed-status'] = str(message
)
733 db_nsr_update
["_admin.deployed.VCA.{}.detailed-status".format(member_vnf_index
)] = str(message
)
735 self
.logger
.critical(logging_text
+ " Enter with bad parameters", exc_info
=True)
740 n2vc_error_text
= [] # contain text error list. If empty no one is in error status
741 for vnf_index
, vca_info
in nsr_lcm
["VCA"].items():
742 vca_status
= vca_info
["operational-status"]
743 if vca_status
not in status_map
:
745 status_map
[vca_status
] = 0
746 status_map
[vca_status
] += 1
748 if vca_status
!= "active":
750 if vca_status
in ("error", "blocked"):
751 n2vc_error_text
.append("member_vnf_index={} {}: {}".format(member_vnf_index
, vca_status
,
752 vca_info
["detailed-status"]))
755 self
.logger
.debug("[n2vc_callback] ns_instantiate={} vnf_index={} All active".format(nsr_id
,
757 db_nsr_update
["config-status"] = "configured"
758 db_nsr_update
["detailed-status"] = "done"
759 db_nslcmop_update
["operationState"] = "COMPLETED"
760 db_nslcmop_update
["detailed-status"] = "Done"
761 db_nslcmop_update
["statusEnteredTime"] = time()
762 elif n2vc_error_text
:
763 db_nsr_update
["config-status"] = "failed"
764 error_text
= "fail configuring " + ";".join(n2vc_error_text
)
765 db_nsr_update
["detailed-status"] = error_text
766 db_nslcmop_update
["operationState"] = "FAILED_TEMP"
767 db_nslcmop_update
["detailed-status"] = error_text
768 db_nslcmop_update
["statusEnteredTime"] = time()
772 for status
, num
in status_map
.items():
773 cs
+= separator
+ "{}: {}".format(status
, num
)
775 db_nsr_update
["config-status"] = cs
776 db_nsr_update
["detailed-status"] = cs
777 db_nslcmop_update
["detailed-status"] = cs
779 except Exception as e
:
780 self
.logger
.critical("[n2vc_callback] vnf_index={} Exception {}".format(member_vnf_index
, e
), exc_info
=True)
783 if db_nslcmop_update
:
784 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
786 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
787 except Exception as e
:
788 self
.logger
.critical("[n2vc_callback] vnf_index={} Update database Exception {}".format(
789 member_vnf_index
, e
), exc_info
=True)
791 def ns_params_2_RO(self
, ns_params
, nsd
, vnfd_dict
):
793 Creates a RO ns descriptor from OSM ns_instantite params
794 :param ns_params: OSM instantiate params
795 :return: The RO ns descriptor
799 def vim_account_2_RO(vim_account
):
800 if vim_account
in vim_2_RO
:
801 return vim_2_RO
[vim_account
]
803 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_account
})
804 if db_vim
["_admin"]["operationalState"] != "ENABLED":
805 raise LcmException("VIM={} is not available. operationalState={}".format(
806 vim_account
, db_vim
["_admin"]["operationalState"]))
807 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
808 vim_2_RO
[vim_account
] = RO_vim_id
811 def ip_profile_2_RO(ip_profile
):
812 RO_ip_profile
= deepcopy((ip_profile
))
813 if "dns-server" in RO_ip_profile
:
814 RO_ip_profile
["dns-address"] = RO_ip_profile
.pop("dns-server")
815 if RO_ip_profile
.get("ip-version") == "ipv4":
816 RO_ip_profile
["ip-version"] = "IPv4"
817 if RO_ip_profile
.get("ip-version") == "ipv6":
818 RO_ip_profile
["ip-version"] = "IPv6"
819 if "dhcp-params" in RO_ip_profile
:
820 RO_ip_profile
["dhcp"] = RO_ip_profile
.pop("dhcp-params")
826 # "name": ns_params["nsName"],
827 # "description": ns_params.get("nsDescription"),
828 "datacenter": vim_account_2_RO(ns_params
["vimAccountId"]),
829 # "scenario": ns_params["nsdId"],
833 if ns_params
.get("ssh-authorized-key"):
834 RO_ns_params
["cloud-config"] = {"key-pairs": ns_params
["ssh-authorized-key"]}
835 if ns_params
.get("vnf"):
836 for vnf_params
in ns_params
["vnf"]:
837 for constituent_vnfd
in nsd
["constituent-vnfd"]:
838 if constituent_vnfd
["member-vnf-index"] == vnf_params
["member-vnf-index"]:
839 vnf_descriptor
= vnfd_dict
[constituent_vnfd
["vnfd-id-ref"]]
842 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index={} is not present at nsd:"
843 "constituent-vnfd".format(vnf_params
["member-vnf-index"]))
844 RO_vnf
= {"vdus": {}, "networks": {}}
845 if vnf_params
.get("vimAccountId"):
846 RO_vnf
["datacenter"] = vim_account_2_RO(vnf_params
["vimAccountId"])
847 if vnf_params
.get("vdu"):
848 for vdu_params
in vnf_params
["vdu"]:
849 RO_vnf
["vdus"][vdu_params
["id"]] = {}
850 if vdu_params
.get("volume"):
851 RO_vnf
["vdus"][vdu_params
["id"]]["devices"] = {}
852 for volume_params
in vdu_params
["volume"]:
853 RO_vnf
["vdus"][vdu_params
["id"]]["devices"][volume_params
["name"]] = {}
854 if volume_params
.get("vim-volume-id"):
855 RO_vnf
["vdus"][vdu_params
["id"]]["devices"][volume_params
["name"]]["vim_id"] = \
856 volume_params
["vim-volume-id"]
857 if vdu_params
.get("interface"):
858 RO_vnf
["vdus"][vdu_params
["id"]]["interfaces"] = {}
859 for interface_params
in vdu_params
["interface"]:
861 RO_vnf
["vdus"][vdu_params
["id"]]["interfaces"][interface_params
["name"]] = RO_interface
862 if interface_params
.get("ip-address"):
863 RO_interface
["ip_address"] = interface_params
["ip-address"]
864 if interface_params
.get("mac-address"):
865 RO_interface
["mac_address"] = interface_params
["mac-address"]
866 if interface_params
.get("floating-ip-required"):
867 RO_interface
["floating-ip"] = interface_params
["floating-ip-required"]
868 if vnf_params
.get("internal-vld"):
869 for internal_vld_params
in vnf_params
["internal-vld"]:
870 RO_vnf
["networks"][internal_vld_params
["name"]] = {}
871 if internal_vld_params
.get("vim-network-name"):
872 RO_vnf
["networks"][internal_vld_params
["name"]]["vim-network-name"] = \
873 internal_vld_params
["vim-network-name"]
874 if internal_vld_params
.get("ip-profile"):
875 RO_vnf
["networks"][internal_vld_params
["name"]]["ip-profile"] = \
876 ip_profile_2_RO(internal_vld_params
["ip-profile"])
877 if internal_vld_params
.get("internal-connection-point"):
878 for icp_params
in internal_vld_params
["internal-connection-point"]:
881 for vdu_descriptor
in vnf_descriptor
["vdu"]:
882 for vdu_interface
in vdu_descriptor
["interface"]:
883 if vdu_interface
.get("internal-connection-point-ref") == icp_params
["id-ref"]:
884 if vdu_descriptor
["id"] not in RO_vnf
["vdus"]:
885 RO_vnf
["vdus"][vdu_descriptor
["id"]] = {}
886 if "interfaces" not in RO_vnf
["vdus"][vdu_descriptor
["id"]]:
887 RO_vnf
["vdus"][vdu_descriptor
["id"]]["interfaces"] = {}
888 RO_ifaces
= RO_vnf
["vdus"][vdu_descriptor
["id"]]["interfaces"]
889 if vdu_interface
["name"] not in RO_ifaces
:
890 RO_ifaces
[vdu_interface
["name"]] = {}
892 RO_ifaces
[vdu_interface
["name"]]["ip_address"] = icp_params
["ip-address"]
898 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
899 "internal-vld:id-ref={} is not present at vnfd:internal-"
900 "connection-point".format(vnf_params
["member-vnf-index"],
901 icp_params
["id-ref"]))
903 if not RO_vnf
["vdus"]:
905 if not RO_vnf
["networks"]:
906 del RO_vnf
["networks"]
908 RO_ns_params
["vnfs"][vnf_params
["member-vnf-index"]] = RO_vnf
909 if ns_params
.get("vld"):
910 for vld_params
in ns_params
["vld"]:
912 if "ip-profile" in vld_params
:
913 RO_vld
["ip-profile"] = ip_profile_2_RO(vld_params
["ip-profile"])
914 if "vim-network-name" in vld_params
:
916 if isinstance(vld_params
["vim-network-name"], dict):
917 for vim_account
, vim_net
in vld_params
["vim-network-name"].items():
918 RO_vld
["sites"].append({
919 "netmap-use": vim_net
,
920 "datacenter": vim_account_2_RO(vim_account
)
922 else: # isinstance str
923 RO_vld
["sites"].append({"netmap-use": vld_params
["vim-network-name"]})
925 RO_ns_params
["networks"][vld_params
["name"]] = RO_vld
928 def ns_update_vnfr(self
, db_vnfrs
, ns_RO_info
):
930 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
935 for vnf_index
, db_vnfr
in db_vnfrs
.items():
936 vnfr_deployed
= ns_RO_info
.get(vnf_index
)
937 if not vnfr_deployed
:
940 db_vnfr
["ip-address"] = vnfr_update
["ip-address"] = vnfr_deployed
.get("ip_address")
941 for index
, vdur
in enumerate(db_vnfr
["vdur"]):
942 vdu_deployed
= vnfr_deployed
["vdur"].get(vdur
["vdu-id-ref"])
945 vnfr_update
["vdur.{}.vim-id".format(index
)] = vdu_deployed
.get("vim_id")
946 db_vnfr
["vdur"][index
]["vim-id"] = vnfr_update
["vdur.{}.vim-id".format(index
)]
947 vnfr_update
["vdur.{}.ip-address".format(index
)] = vdu_deployed
.get("ip_address")
948 db_vnfr
["vdur"][index
]["ip-address"] = vnfr_update
["vdur.{}.ip-address".format(index
)]
949 for index2
, interface
in enumerate(vdur
["interfaces"]):
950 iface_deployed
= vdu_deployed
["interfaces"].get(interface
["name"])
951 if not iface_deployed
:
953 db_vnfr
["vdur"][index
]["interfaces"][index2
]["vim-id"] =\
954 vnfr_update
["vdur.{}.interfaces.{}.vim-id".format(index
, index2
)] = iface_deployed
.get("vim_id")
955 db_vnfr
["vdur"][index
]["interfaces"][index2
]["ip-address"] =\
956 vnfr_update
["vdur.{}.interfaces.{}.ip-address".format(index
, index2
)] = iface_deployed
.get(
958 db_vnfr
["vdur"][index
]["interfaces"][index2
]["mac-address"] =\
959 vnfr_update
["vdur.{}.interfaces.{}.mac-address".format(index
, index2
)] = iface_deployed
.get(
961 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
963 def ns_update_vnfr_2(self
, db_vnfrs
, nsr_desc_RO
):
965 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
970 for vnf_index
, db_vnfr
in db_vnfrs
.items():
971 for vnf_RO
in nsr_desc_RO
["vnfs"]:
972 if vnf_RO
["member_vnf_index"] == vnf_index
:
974 db_vnfr
["ip-address"] = vnfr_update
["ip-address"] = vnf_RO
.get("ip_address")
976 for vdur_RO
in vnf_RO
.get("vms", ()):
978 "vim-id": vdur_RO
.get("vim_vm_id"),
979 "ip-address": vdur_RO
.get("ip_address"),
980 "vdu-id-ref": vdur_RO
.get("vdu_osm_id"),
981 "name": vdur_RO
.get("vim_name"),
982 "status": vdur_RO
.get("status"),
983 "status-detailed": vdur_RO
.get("error_msg"),
987 for interface_RO
in vdur_RO
.get("interfaces", ()):
988 vdur
["interfaces"].append({
989 "ip-address": interface_RO
.get("ip_address"),
990 "mac-address": interface_RO
.get("mac_address"),
991 "name": interface_RO
.get("external_name"),
993 vdur_list
.append(vdur
)
994 db_vnfr
["vdur"] = vnfr_update
["vdur"] = vdur_list
995 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
999 raise LcmException("ns_update_vnfr_2: Not found member_vnf_index={} at RO info".format(vnf_index
))
1001 async def create_monitoring(self
, nsr_id
, vnf_member_index
, vnfd_desc
):
1002 if not vnfd_desc
.get("scaling-group-descriptor"):
1004 for scaling_group
in vnfd_desc
["scaling-group-descriptor"]:
1005 scaling_policy_desc
= {}
1008 "scaling_group_descriptor": {
1009 "name": scaling_group
["name"],
1010 "scaling_policy": scaling_policy_desc
1013 for scaling_policy
in scaling_group
.get("scaling-policy"):
1014 scaling_policy_desc
["scale_in_operation_type"] = scaling_policy_desc
["scale_out_operation_type"] = \
1015 scaling_policy
["scaling-type"]
1016 scaling_policy_desc
["threshold_time"] = scaling_policy
["threshold-time"]
1017 scaling_policy_desc
["cooldown_time"] = scaling_policy
["cooldown-time"]
1018 scaling_policy_desc
["scaling_criteria"] = []
1019 for scaling_criteria
in scaling_policy
.get("scaling-criteria"):
1020 scaling_criteria_desc
= {"scale_in_threshold": scaling_criteria
.get("scale-in-threshold"),
1021 "scale_out_threshold": scaling_criteria
.get("scale-out-threshold"),
1023 if not scaling_criteria
.get("vnf-monitoring-param-ref"):
1025 for monitoring_param
in vnfd_desc
.get("monitoring-param", ()):
1026 if monitoring_param
["id"] == scaling_criteria
["vnf-monitoring-param-ref"]:
1027 scaling_criteria_desc
["monitoring_param"] = {
1028 "id": monitoring_param
["id"],
1029 "name": monitoring_param
["name"],
1030 "aggregation_type": monitoring_param
.get("aggregation-type"),
1031 "vdu_name": monitoring_param
.get("vdu-ref"),
1032 "vnf_member_index": vnf_member_index
,
1035 scaling_policy_desc
["scaling_criteria"].append(scaling_criteria_desc
)
1039 "Task ns={} member_vnf_index={} Invalid vnfd vnf-monitoring-param-ref={} not in "
1040 "monitoring-param list".format(nsr_id
, vnf_member_index
,
1041 scaling_criteria
["vnf-monitoring-param-ref"]))
1043 await self
.msg
.aiowrite("lcm_pm", "configure_scaling", scaling_desc
, self
.loop
)
1045 async def ns_instantiate(self
, nsr_id
, nslcmop_id
):
1046 logging_text
= "Task ns={} instantiate={} ".format(nsr_id
, nslcmop_id
)
1047 self
.logger
.debug(logging_text
+ "Enter")
1048 # get all needed from database
1052 db_nslcmop_update
= {}
1054 RO_descriptor_number
= 0 # number of descriptors created at RO
1055 descriptor_id_2_RO
= {} # map between vnfd/nsd id to the id used at RO
1058 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
1059 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1060 step
= "Getting nsr={} from db".format(nsr_id
)
1061 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1062 ns_params
= db_nsr
.get("instantiate_params")
1064 nsr_name
= db_nsr
["name"] # TODO short-name??
1066 vnfr_filter
= {"nsr-id-ref": nsr_id
, "member-vnf-index-ref": None}
1067 for c_vnf
in nsd
["constituent-vnfd"]:
1068 vnfd_id
= c_vnf
["vnfd-id-ref"]
1069 vnfr_filter
["member-vnf-index-ref"] = c_vnf
["member-vnf-index"]
1070 step
= "Getting vnfr={} of nsr={} from db".format(c_vnf
["member-vnf-index"], nsr_id
)
1071 db_vnfrs
[c_vnf
["member-vnf-index"]] = self
.db
.get_one("vnfrs", vnfr_filter
)
1072 if vnfd_id
not in needed_vnfd
:
1073 step
= "Getting vnfd={} from db".format(vnfd_id
)
1074 needed_vnfd
[vnfd_id
] = self
.db
.get_one("vnfds", {"id": vnfd_id
})
1076 nsr_lcm
= db_nsr
["_admin"].get("deployed")
1078 nsr_lcm
= db_nsr
["_admin"]["deployed"] = {
1080 "RO": {"vnfd_id": {}, "nsd_id": None, "nsr_id": None, "nsr_status": "SCHEDULED"},
1084 db_nsr_update
["detailed-status"] = "creating"
1085 db_nsr_update
["operational-status"] = "init"
1087 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
1089 # get vnfds, instantiate at RO
1090 for vnfd_id
, vnfd
in needed_vnfd
.items():
1091 step
= db_nsr_update
["detailed-status"] = "Creating vnfd={} at RO".format(vnfd_id
)
1092 # self.logger.debug(logging_text + step)
1093 vnfd_id_RO
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, vnfd_id
[:23])
1094 descriptor_id_2_RO
[vnfd_id
] = vnfd_id_RO
1095 RO_descriptor_number
+= 1
1098 vnfd_list
= await RO
.get_list("vnfd", filter_by
={"osm_id": vnfd_id_RO
})
1100 db_nsr_update
["_admin.deployed.RO.vnfd_id.{}".format(vnfd_id
)] = vnfd_list
[0]["uuid"]
1101 self
.logger
.debug(logging_text
+ "vnfd={} exists at RO. Using RO_id={}".format(
1102 vnfd_id
, vnfd_list
[0]["uuid"]))
1104 vnfd_RO
= self
.vnfd2RO(vnfd
, vnfd_id_RO
)
1105 desc
= await RO
.create("vnfd", descriptor
=vnfd_RO
)
1106 db_nsr_update
["_admin.deployed.RO.vnfd_id.{}".format(vnfd_id
)] = desc
["uuid"]
1107 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1108 self
.logger
.debug(logging_text
+ "vnfd={} created at RO. RO_id={}".format(
1109 vnfd_id
, desc
["uuid"]))
1110 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1114 step
= db_nsr_update
["detailed-status"] = "Creating nsd={} at RO".format(nsd_id
)
1115 # self.logger.debug(logging_text + step)
1117 RO_osm_nsd_id
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, nsd_id
[:23])
1118 descriptor_id_2_RO
[nsd_id
] = RO_osm_nsd_id
1119 RO_descriptor_number
+= 1
1120 nsd_list
= await RO
.get_list("nsd", filter_by
={"osm_id": RO_osm_nsd_id
})
1122 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= nsd_list
[0]["uuid"]
1123 self
.logger
.debug(logging_text
+ "nsd={} exists at RO. Using RO_id={}".format(
1124 nsd_id
, RO_nsd_uuid
))
1126 nsd_RO
= deepcopy(nsd
)
1127 nsd_RO
["id"] = RO_osm_nsd_id
1128 nsd_RO
.pop("_id", None)
1129 nsd_RO
.pop("_admin", None)
1130 for c_vnf
in nsd_RO
["constituent-vnfd"]:
1131 vnfd_id
= c_vnf
["vnfd-id-ref"]
1132 c_vnf
["vnfd-id-ref"] = descriptor_id_2_RO
[vnfd_id
]
1133 desc
= await RO
.create("nsd", descriptor
=nsd_RO
)
1134 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1135 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= desc
["uuid"]
1136 self
.logger
.debug(logging_text
+ "nsd={} created at RO. RO_id={}".format(nsd_id
, RO_nsd_uuid
))
1137 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1140 # if present use it unless in error status
1141 RO_nsr_id
= db_nsr
["_admin"].get("deployed", {}).get("RO", {}).get("nsr_id")
1144 step
= db_nsr_update
["detailed-status"] = "Looking for existing ns at RO"
1145 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
1146 desc
= await RO
.show("ns", RO_nsr_id
)
1147 except ROclient
.ROClientException
as e
:
1148 if e
.http_code
!= HTTPStatus
.NOT_FOUND
:
1150 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1152 ns_status
, ns_status_info
= RO
.check_ns_status(desc
)
1153 db_nsr_update
["_admin.deployed.RO.nsr_status"] = ns_status
1154 if ns_status
== "ERROR":
1155 step
= db_nsr_update
["detailed-status"] = "Deleting ns at RO. RO_ns_id={}".format(RO_nsr_id
)
1156 self
.logger
.debug(logging_text
+ step
)
1157 await RO
.delete("ns", RO_nsr_id
)
1158 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1160 step
= db_nsr_update
["detailed-status"] = "Creating ns at RO"
1161 # self.logger.debug(logging_text + step)
1163 # check if VIM is creating and wait look if previous tasks in process
1164 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account", ns_params
["vimAccountId"])
1166 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
1167 self
.logger
.debug(logging_text
+ step
)
1168 await asyncio
.wait(task_dependency
, timeout
=3600)
1169 if ns_params
.get("vnf"):
1170 for vnf
in ns_params
["vnf"]:
1171 if "vimAccountId" in vnf
:
1172 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account",
1173 vnf
["vimAccountId"])
1175 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
1176 self
.logger
.debug(logging_text
+ step
)
1177 await asyncio
.wait(task_dependency
, timeout
=3600)
1179 RO_ns_params
= self
.ns_params_2_RO(ns_params
, nsd
, needed_vnfd
)
1180 desc
= await RO
.create("ns", descriptor
=RO_ns_params
,
1181 name
=db_nsr
["name"],
1182 scenario
=RO_nsd_uuid
)
1183 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = desc
["uuid"]
1184 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1185 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "BUILD"
1186 self
.logger
.debug(logging_text
+ "ns created at RO. RO_id={}".format(desc
["uuid"]))
1187 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1189 # update VNFR vimAccount
1190 step
= "Updating VNFR vimAcccount"
1191 for vnf_index
, vnfr
in db_vnfrs
.items():
1192 if vnfr
.get("vim-account-id"):
1194 vnfr_update
= {"vim-account-id": db_nsr
["instantiate_params"]["vimAccountId"]}
1195 if db_nsr
["instantiate_params"].get("vnf"):
1196 for vnf_params
in db_nsr
["instantiate_params"]["vnf"]:
1197 if vnf_params
.get("member-vnf-index") == vnf_index
:
1198 if vnf_params
.get("vimAccountId"):
1199 vnfr_update
["vim-account-id"] = vnf_params
.get("vimAccountId")
1201 self
.update_db_2("vnfrs", vnfr
["_id"], vnfr_update
)
1203 # wait until NS is ready
1204 step
= ns_status_detailed
= detailed_status
= "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id
)
1205 detailed_status_old
= None
1206 self
.logger
.debug(logging_text
+ step
)
1208 deployment_timeout
= 2 * 3600 # Two hours
1209 while deployment_timeout
> 0:
1210 desc
= await RO
.show("ns", RO_nsr_id
)
1211 ns_status
, ns_status_info
= RO
.check_ns_status(desc
)
1212 db_nsr_update
["admin.deployed.RO.nsr_status"] = ns_status
1213 if ns_status
== "ERROR":
1214 raise ROclient
.ROClientException(ns_status_info
)
1215 elif ns_status
== "BUILD":
1216 detailed_status
= ns_status_detailed
+ "; {}".format(ns_status_info
)
1217 elif ns_status
== "ACTIVE":
1218 step
= detailed_status
= "Waiting for management IP address reported by the VIM"
1220 nsr_lcm
["nsr_ip"] = RO
.get_ns_vnf_info(desc
)
1222 except ROclient
.ROClientException
as e
:
1223 if e
.http_code
!= 409: # IP address is not ready return code is 409 CONFLICT
1226 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
1227 if detailed_status
!= detailed_status_old
:
1228 detailed_status_old
= db_nsr_update
["detailed-status"] = detailed_status
1229 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1230 await asyncio
.sleep(5, loop
=self
.loop
)
1231 deployment_timeout
-= 5
1232 if deployment_timeout
<= 0:
1233 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
1235 step
= "Updating VNFRs"
1236 # self.ns_update_vnfr(db_vnfrs, ns_RO_info)
1237 self
.ns_update_vnfr_2(db_vnfrs
, desc
)
1239 db_nsr
["detailed-status"] = "Configuring vnfr"
1240 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1242 # The parameters we'll need to deploy a charm
1243 number_to_configure
= 0
1246 """An inner function to deploy the charm from either vnf or vdu
1250 # if number_to_configure == 0:
1251 # self.logger.debug("Logging into N2VC...")
1252 # task = asyncio.ensure_future(self.n2vc.login())
1253 # yield from asyncio.wait_for(task, 30.0)
1254 # self.logger.debug("Logged into N2VC!")
1256 # # await self.n2vc.login()
1258 # Note: The charm needs to exist on disk at the location
1259 # specified by charm_path.
1260 base_folder
= vnfd
["_admin"]["storage"]
1261 storage_params
= self
.fs
.get_params()
1262 charm_path
= "{}{}/{}/charms/{}".format(
1263 storage_params
["path"],
1264 base_folder
["folder"],
1265 base_folder
["pkg-dir"],
1269 # Setup the runtime parameters for this VNF
1270 params
['rw_mgmt_ip'] = db_vnfrs
[vnf_index
]["ip-address"]
1272 # ns_name will be ignored in the current version of N2VC
1273 # but will be implemented for the next point release.
1274 model_name
= 'default'
1275 application_name
= self
.n2vc
.FormatApplicationName(
1280 if not nsr_lcm
.get("VCA"):
1282 nsr_lcm
["VCA"][vnf_index
] = db_nsr_update
["_admin.deployed.VCA.{}".format(vnf_index
)] = {
1283 "model": model_name
,
1284 "application": application_name
,
1285 "operational-status": "init",
1286 "detailed-status": "",
1289 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1291 self
.logger
.debug("Task create_ns={} Passing artifacts path '{}' for {}".format(nsr_id
, charm_path
,
1293 task
= asyncio
.ensure_future(
1294 self
.n2vc
.DeployCharms(
1295 model_name
, # The network service name
1296 application_name
, # The application name
1297 vnfd
, # The vnf descriptor
1298 charm_path
, # Path to charm
1299 params
, # Runtime params, like mgmt ip
1300 {}, # for native charms only
1301 self
.n2vc_callback
, # Callback for status changes
1302 db_nsr
, # Callback parameter
1304 vnf_index
, # Callback parameter
1305 None, # Callback parameter (task)
1308 task
.add_done_callback(functools
.partial(self
.n2vc_callback
, model_name
, application_name
, None, None,
1309 db_nsr
, db_nslcmop
, vnf_index
))
1310 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "create_charm:" + vnf_index
, task
)
1312 step
= "Looking for needed vnfd to configure"
1313 self
.logger
.debug(logging_text
+ step
)
1315 for c_vnf
in nsd
["constituent-vnfd"]:
1316 vnfd_id
= c_vnf
["vnfd-id-ref"]
1317 vnf_index
= str(c_vnf
["member-vnf-index"])
1318 vnfd
= needed_vnfd
[vnfd_id
]
1320 # Check if this VNF has a charm configuration
1321 vnf_config
= vnfd
.get("vnf-configuration")
1323 if vnf_config
and vnf_config
.get("juju"):
1324 proxy_charm
= vnf_config
["juju"]["charm"]
1328 if 'initial-config-primitive' in vnf_config
:
1329 params
['initial-config-primitive'] = vnf_config
['initial-config-primitive']
1331 # Login to the VCA. If there are multiple calls to login(),
1332 # subsequent calls will be a nop and return immediately.
1333 step
= "connecting to N2VC to configure vnf {}".format(vnf_index
)
1334 await self
.n2vc
.login()
1336 number_to_configure
+= 1
1338 # Deploy charms for each VDU that supports one.
1339 for vdu
in vnfd
['vdu']:
1340 vdu_config
= vdu
.get('vdu-configuration')
1344 if vdu_config
and vdu_config
.get("juju"):
1345 proxy_charm
= vdu_config
["juju"]["charm"]
1347 if 'initial-config-primitive' in vdu_config
:
1348 params
['initial-config-primitive'] = vdu_config
['initial-config-primitive']
1351 step
= "connecting to N2VC to configure vdu {} from vnf {}".format(vdu
["id"], vnf_index
)
1352 await self
.n2vc
.login()
1354 number_to_configure
+= 1
1356 if number_to_configure
:
1357 db_nsr_update
["config-status"] = "configuring"
1358 db_nsr_update
["operational-status"] = "running"
1359 db_nsr_update
["detailed-status"] = "configuring: init: {}".format(number_to_configure
)
1360 db_nslcmop_update
["detailed-status"] = "configuring: init: {}".format(number_to_configure
)
1362 db_nslcmop_update
["operationState"] = "COMPLETED"
1363 db_nslcmop_update
["statusEnteredTime"] = time()
1364 db_nslcmop_update
["detailed-status"] = "done"
1365 db_nsr_update
["config-status"] = "configured"
1366 db_nsr_update
["detailed-status"] = "done"
1367 db_nsr_update
["operational-status"] = "running"
1368 step
= "Sending monitoring parameters to PM"
1369 # for c_vnf in nsd["constituent-vnfd"]:
1370 # await self.create_monitoring(nsr_id, c_vnf["member-vnf-index"], needed_vnfd[c_vnf["vnfd-id-ref"]])
1372 await self
.msg
.aiowrite("ns", "instantiated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
})
1373 except Exception as e
:
1374 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1376 self
.logger
.debug(logging_text
+ "Exit")
1379 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
1380 self
.logger
.error(logging_text
+ "Exit Exception while '{}': {}".format(step
, e
))
1382 except asyncio
.CancelledError
:
1383 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1384 exc
= "Operation was cancelled"
1385 except Exception as e
:
1386 exc
= traceback
.format_exc()
1387 self
.logger
.critical(logging_text
+ "Exit Exception {} while '{}': {}".format(type(e
).__name
__, step
, e
),
1392 db_nsr_update
["detailed-status"] = "ERROR {}: {}".format(step
, exc
)
1393 db_nsr_update
["operational-status"] = "failed"
1395 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
1396 db_nslcmop_update
["operationState"] = "FAILED"
1397 db_nslcmop_update
["statusEnteredTime"] = time()
1399 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1400 if db_nslcmop_update
:
1401 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1402 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_instantiate")
1404 async def ns_terminate(self
, nsr_id
, nslcmop_id
):
1405 logging_text
= "Task ns={} terminate={} ".format(nsr_id
, nslcmop_id
)
1406 self
.logger
.debug(logging_text
+ "Enter")
1410 failed_detail
= [] # annotates all failed error messages
1414 db_nslcmop_update
= {}
1416 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
1417 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1418 step
= "Getting nsr={} from db".format(nsr_id
)
1419 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1420 # nsd = db_nsr["nsd"]
1421 nsr_lcm
= deepcopy(db_nsr
["_admin"].get("deployed"))
1422 if db_nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
1425 # db_vim = self.db.get_one("vim_accounts", {"_id": db_nsr["datacenter"]})
1426 # #TODO check if VIM is creating and wait
1427 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
1429 db_nsr_update
["operational-status"] = "terminating"
1430 db_nsr_update
["config-status"] = "terminating"
1432 if nsr_lcm
and nsr_lcm
.get("VCA"):
1434 step
= "Scheduling configuration charms removing"
1435 db_nsr_update
["detailed-status"] = "Deleting charms"
1436 self
.logger
.debug(logging_text
+ step
)
1437 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1438 for vnf_index
, deploy_info
in nsr_lcm
["VCA"].items():
1439 if deploy_info
and deploy_info
.get("application"):
1440 task
= asyncio
.ensure_future(
1441 self
.n2vc
.RemoveCharms(
1442 deploy_info
['model'],
1443 deploy_info
['application'],
1444 # self.n2vc_callback,
1450 vca_task_list
.append(task
)
1451 vca_task_dict
[vnf_index
] = task
1452 # task.add_done_callback(functools.partial(self.n2vc_callback, deploy_info['model'],
1453 # deploy_info['application'], None, db_nsr,
1454 # db_nslcmop, vnf_index))
1455 self
.lcm_ns_tasks
[nsr_id
][nslcmop_id
]["delete_charm:" + vnf_index
] = task
1456 except Exception as e
:
1457 self
.logger
.debug(logging_text
+ "Failed while deleting charms: {}".format(e
))
1461 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
1463 if nsr_lcm
and nsr_lcm
.get("RO") and nsr_lcm
["RO"].get("nsr_id"):
1464 RO_nsr_id
= nsr_lcm
["RO"]["nsr_id"]
1466 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] = "Deleting ns at RO"
1467 self
.logger
.debug(logging_text
+ step
)
1468 await RO
.delete("ns", RO_nsr_id
)
1469 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1470 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
1471 except ROclient
.ROClientException
as e
:
1472 if e
.http_code
== 404: # not found
1473 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1474 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
1475 self
.logger
.debug(logging_text
+ "RO_ns_id={} already deleted".format(RO_nsr_id
))
1476 elif e
.http_code
== 409: # conflict
1477 failed_detail
.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id
, e
))
1478 self
.logger
.debug(logging_text
+ failed_detail
[-1])
1481 failed_detail
.append("RO_ns_id={} delete error: {}".format(RO_nsr_id
, e
))
1482 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("nsd_id"):
1487 RO_nsd_id
= nsr_lcm
["RO"]["nsd_id"]
1489 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
1490 "Deleting nsd at RO"
1491 await RO
.delete("nsd", RO_nsd_id
)
1492 self
.logger
.debug(logging_text
+ "RO_nsd_id={} deleted".format(RO_nsd_id
))
1493 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
1494 except ROclient
.ROClientException
as e
:
1495 if e
.http_code
== 404: # not found
1496 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
1497 self
.logger
.debug(logging_text
+ "RO_nsd_id={} already deleted".format(RO_nsd_id
))
1498 elif e
.http_code
== 409: # conflict
1499 failed_detail
.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id
, e
))
1500 self
.logger
.debug(logging_text
+ failed_detail
[-1])
1503 failed_detail
.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id
, e
))
1504 self
.logger
.error(logging_text
+ failed_detail
[-1])
1507 if not RO_fail
and nsr_lcm
and nsr_lcm
.get("RO") and nsr_lcm
["RO"].get("vnfd_id"):
1508 for vnf_id
, RO_vnfd_id
in nsr_lcm
["RO"]["vnfd_id"].items():
1512 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
1513 "Deleting vnfd={} at RO".format(vnf_id
)
1514 await RO
.delete("vnfd", RO_vnfd_id
)
1515 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} deleted".format(RO_vnfd_id
))
1516 db_nsr_update
["_admin.deployed.RO.vnfd_id.{}".format(vnf_id
)] = None
1517 except ROclient
.ROClientException
as e
:
1518 if e
.http_code
== 404: # not found
1519 db_nsr_update
["_admin.deployed.RO.vnfd_id.{}".format(vnf_id
)] = None
1520 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} already deleted ".format(RO_vnfd_id
))
1521 elif e
.http_code
== 409: # conflict
1522 failed_detail
.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id
, e
))
1523 self
.logger
.debug(logging_text
+ failed_detail
[-1])
1525 failed_detail
.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id
, e
))
1526 self
.logger
.error(logging_text
+ failed_detail
[-1])
1529 db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
1530 "Waiting for deletion of configuration charms"
1531 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1532 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1533 await asyncio
.wait(vca_task_list
, timeout
=300)
1534 for vnf_index
, task
in vca_task_dict
.items():
1535 if task
.cancelled():
1536 failed_detail
.append("VCA[{}] Deletion has been cancelled".format(vnf_index
))
1538 exc
= task
.exception()
1540 failed_detail
.append("VCA[{}] Deletion exception: {}".format(vnf_index
, exc
))
1542 db_nsr_update
["_admin.deployed.VCA.{}".format(vnf_index
)] = None
1544 # TODO Should it be cancelled?!!
1546 failed_detail
.append("VCA[{}] Deletion timeout".format(vnf_index
))
1549 self
.logger
.error(logging_text
+ " ;".join(failed_detail
))
1550 db_nsr_update
["operational-status"] = "failed"
1551 db_nsr_update
["detailed-status"] = "Deletion errors " + "; ".join(failed_detail
)
1552 db_nslcmop_update
["detailed-status"] = "; ".join(failed_detail
)
1553 db_nslcmop_update
["operationState"] = "FAILED"
1554 db_nslcmop_update
["statusEnteredTime"] = time()
1555 elif db_nslcmop
["operationParams"].get("autoremove"):
1556 self
.db
.del_one("nsrs", {"_id": nsr_id
})
1557 db_nsr_update
.clear()
1558 self
.db
.del_list("nslcmops", {"nsInstanceId": nsr_id
})
1559 db_nslcmop_update
.clear()
1560 self
.db
.del_list("vnfrs", {"nsr-id-ref": nsr_id
})
1561 self
.logger
.debug(logging_text
+ "Delete from database")
1563 db_nsr_update
["operational-status"] = "terminated"
1564 db_nsr_update
["detailed-status"] = "Done"
1565 db_nsr_update
["_admin.nsState"] = "NOT_INSTANTIATED"
1566 db_nslcmop_update
["detailed-status"] = "Done"
1567 db_nslcmop_update
["operationState"] = "COMPLETED"
1568 db_nslcmop_update
["statusEnteredTime"] = time()
1570 await self
.msg
.aiowrite("ns", "terminated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
})
1571 except Exception as e
:
1572 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1573 self
.logger
.debug(logging_text
+ "Exit")
1575 except (ROclient
.ROClientException
, DbException
) as e
:
1576 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
1578 except asyncio
.CancelledError
:
1579 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1580 exc
= "Operation was cancelled"
1581 except Exception as e
:
1582 exc
= traceback
.format_exc()
1583 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
1585 if exc
and db_nslcmop
:
1586 db_nslcmop_update
= {
1587 "detailed-status": "FAILED {}: {}".format(step
, exc
),
1588 "operationState": "FAILED",
1589 "statusEnteredTime": time(),
1591 if db_nslcmop_update
:
1592 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1594 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1595 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_terminate")
1597 async def _ns_execute_primitive(self
, db_deployed
, member_vnf_index
, primitive
, primitive_params
):
1598 vca_deployed
= db_deployed
["VCA"].get(member_vnf_index
)
1599 if not vca_deployed
:
1600 raise LcmException("charm for member_vnf_index={} is not deployed".format(member_vnf_index
))
1601 model_name
= vca_deployed
.get("model")
1602 application_name
= vca_deployed
.get("application")
1603 if not model_name
or not application_name
:
1604 raise LcmException("charm for member_vnf_index={} is not properly deployed".format(member_vnf_index
))
1605 if vca_deployed
["operational-status"] != "active":
1606 raise LcmException("charm for member_vnf_index={} operational_status={} not 'active'".format(
1607 member_vnf_index
, vca_deployed
["operational-status"]))
1608 callback
= None # self.n2vc_callback
1609 callback_args
= () # [db_nsr, db_nslcmop, member_vnf_index, None]
1610 await self
.n2vc
.login()
1611 task
= asyncio
.ensure_future(
1612 self
.n2vc
.ExecutePrimitive(
1615 primitive
, callback
,
1620 # task.add_done_callback(functools.partial(self.n2vc_callback, model_name, application_name, None,
1621 # db_nsr, db_nslcmop, member_vnf_index))
1622 # self.lcm_ns_tasks[nsr_id][nslcmop_id]["action: " + primitive] = task
1623 # wait until completed with timeout
1624 await asyncio
.wait((task
,), timeout
=600)
1626 result
= "FAILED" # by default
1628 if task
.cancelled():
1629 result_detail
= "Task has been cancelled"
1631 exc
= task
.exception()
1633 result_detail
= str(exc
)
1635 # TODO revise with Adam if action is finished and ok when task is done or callback is needed
1636 result
= "COMPLETED"
1637 result_detail
= "Done"
1639 # TODO Should it be cancelled?!!
1641 result_detail
= "timeout"
1642 return result
, result_detail
1644 async def ns_action(self
, nsr_id
, nslcmop_id
):
1645 logging_text
= "Task ns={} action={} ".format(nsr_id
, nslcmop_id
)
1646 self
.logger
.debug(logging_text
+ "Enter")
1647 # get all needed from database
1650 db_nslcmop_update
= None
1653 step
= "Getting information from database"
1654 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1655 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1656 nsr_lcm
= db_nsr
["_admin"].get("deployed")
1657 vnf_index
= db_nslcmop
["operationParams"]["member_vnf_index"]
1659 # TODO check if ns is in a proper status
1660 primitive
= db_nslcmop
["operationParams"]["primitive"]
1661 primitive_params
= db_nslcmop
["operationParams"]["primitive_params"]
1662 result
, result_detail
= await self
._ns
_execute
_primitive
(nsr_lcm
, vnf_index
, primitive
, primitive_params
)
1663 db_nslcmop_update
= {
1664 "detailed-status": result_detail
,
1665 "operationState": result
,
1666 "statusEnteredTime": time()
1668 self
.logger
.debug(logging_text
+ " task Done with result {} {}".format(result
, result_detail
))
1669 return # database update is called inside finally
1671 except (DbException
, LcmException
) as e
:
1672 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
1674 except asyncio
.CancelledError
:
1675 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1676 exc
= "Operation was cancelled"
1677 except Exception as e
:
1678 exc
= traceback
.format_exc()
1679 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
1681 if exc
and db_nslcmop
:
1682 db_nslcmop_update
= {
1683 "detailed-status": "FAILED {}: {}".format(step
, exc
),
1684 "operationState": "FAILED",
1685 "statusEnteredTime": time(),
1687 if db_nslcmop_update
:
1688 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1689 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_action")
1691 async def ns_scale(self
, nsr_id
, nslcmop_id
):
1692 logging_text
= "Task ns={} scale={} ".format(nsr_id
, nslcmop_id
)
1693 self
.logger
.debug(logging_text
+ "Enter")
1694 # get all needed from database
1697 db_nslcmop_update
= {}
1701 step
= "Getting nslcmop from database"
1702 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1703 step
= "Getting nsr from database"
1704 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1705 step
= "Parsing scaling parameters"
1706 db_nsr_update
["operational-status"] = "scaling"
1707 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1708 nsr_lcm
= db_nsr
["_admin"].get("deployed")
1709 RO_nsr_id
= nsr_lcm
["RO"]["nsr_id"]
1710 vnf_index
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
1711 scaling_group
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1712 scaling_type
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleVnfType"]
1713 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
1715 step
= "Getting vnfr from database"
1716 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
1717 step
= "Getting vnfd from database"
1718 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
1719 step
= "Getting scaling-group-descriptor"
1720 for scaling_descriptor
in db_vnfd
["scaling-group-descriptor"]:
1721 if scaling_descriptor
["name"] == scaling_group
:
1724 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
1725 "at vnfd:scaling-group-descriptor".format(scaling_group
))
1727 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
1728 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
1729 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
1732 # TODO check if ns is in a proper status
1733 step
= "Sending scale order to RO"
1735 if not db_nsr
["_admin"].get("scaling-group"):
1736 self
.update_db_2("nsrs", nsr_id
, {"_admin.scaling-group": [{"name": scaling_group
, "nb-scale-op": 0}]})
1737 admin_scale_index
= 0
1739 for admin_scale_index
, admin_scale_info
in enumerate(db_nsr
["_admin"]["scaling-group"]):
1740 if admin_scale_info
["name"] == scaling_group
:
1741 nb_scale_op
= admin_scale_info
.get("nb-scale-op", 0)
1743 RO_scaling_info
= []
1744 vdu_scaling_info
= {"scaling_group_name": scaling_group
, "vdu": []}
1745 if scaling_type
== "SCALE_OUT":
1746 # count if max-instance-count is reached
1747 if "max-instance-count" in scaling_descriptor
and scaling_descriptor
["max-instance-count"] is not None:
1748 max_instance_count
= int(scaling_descriptor
["max-instance-count"])
1749 if nb_scale_op
>= max_instance_count
:
1750 raise LcmException("reached the limit of {} (max-instance-count) scaling-out operations for the"
1751 " scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
1752 nb_scale_op
= nb_scale_op
+ 1
1753 vdu_scaling_info
["scaling_direction"] = "OUT"
1754 vdu_scaling_info
["vdu-create"] = {}
1755 for vdu_scale_info
in scaling_descriptor
["vdu"]:
1756 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
1757 "type": "create", "count": vdu_scale_info
.get("count", 1)})
1758 vdu_scaling_info
["vdu-create"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
1759 elif scaling_type
== "SCALE_IN":
1760 # count if min-instance-count is reached
1761 if "min-instance-count" in scaling_descriptor
and scaling_descriptor
["min-instance-count"] is not None:
1762 min_instance_count
= int(scaling_descriptor
["min-instance-count"])
1763 if nb_scale_op
<= min_instance_count
:
1764 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
1765 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
1766 nb_scale_op
= nb_scale_op
- 1
1767 vdu_scaling_info
["scaling_direction"] = "IN"
1768 vdu_scaling_info
["vdu-delete"] = {}
1769 for vdu_scale_info
in scaling_descriptor
["vdu"]:
1770 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
1771 "type": "delete", "count": vdu_scale_info
.get("count", 1)})
1772 vdu_scaling_info
["vdu-delete"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
1774 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
1775 if vdu_scaling_info
["scaling_direction"] == "IN":
1776 for vdur
in reversed(db_vnfr
["vdur"]):
1777 if vdu_scaling_info
["vdu-delete"].get(vdur
["vdu-id-ref"]):
1778 vdu_scaling_info
["vdu-delete"][vdur
["vdu-id-ref"]] -= 1
1779 vdu_scaling_info
["vdu"].append({
1780 "name": vdur
["name"],
1781 "vdu_id": vdur
["vdu-id-ref"],
1784 for interface
in vdur
["interfaces"]:
1785 vdu_scaling_info
["vdu"][-1]["interface"].append({
1786 "name": interface
["name"],
1787 "ip_address": interface
["ip-address"],
1788 "mac_address": interface
.get("mac-address"),
1790 del vdu_scaling_info
["vdu-delete"]
1792 # execute primitive service PRE-SCALING
1793 step
= "Executing pre-scale vnf-config-primitive"
1794 if scaling_descriptor
.get("scaling-config-action"):
1795 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
1796 if scaling_config_action
.get("trigger") and scaling_config_action
["trigger"] == "pre-scale-in" \
1797 and scaling_type
== "SCALE_IN":
1798 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
1799 step
= db_nslcmop_update
["detailed-status"] = \
1800 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive
)
1801 # look for primitive
1802 primitive_params
= {}
1803 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
1804 if config_primitive
["name"] == vnf_config_primitive
:
1805 for parameter
in config_primitive
.get("parameter", ()):
1806 if 'default-value' in parameter
and \
1807 parameter
['default-value'] == "<VDU_SCALE_INFO>":
1808 primitive_params
[parameter
["name"]] = yaml
.safe_dump(vdu_scaling_info
,
1809 default_flow_style
=True,
1814 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
1815 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-cnfiguration:config-"
1816 "primitive".format(scaling_group
, config_primitive
))
1817 result
, result_detail
= await self
._ns
_execute
_primitive
(nsr_lcm
, vnf_index
,
1818 vnf_config_primitive
, primitive_params
)
1819 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
1820 vnf_config_primitive
, result
, result_detail
))
1821 if result
== "FAILED":
1822 raise LcmException(result_detail
)
1825 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
1826 RO_desc
= await RO
.create_action("ns", RO_nsr_id
, {"vdu-scaling": RO_scaling_info
})
1827 db_nsr_update
["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index
)] = nb_scale_op
1828 db_nsr_update
["_admin.scaling-group.{}.time".format(admin_scale_index
)] = time()
1829 # TODO mark db_nsr_update as scaling
1831 RO_nslcmop_id
= RO_desc
["instance_action_id"]
1832 db_nslcmop_update
["_admin.deploy.RO"] = RO_nslcmop_id
1834 RO_task_done
= False
1835 step
= detailed_status
= "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id
)
1836 detailed_status_old
= None
1837 self
.logger
.debug(logging_text
+ step
)
1839 deployment_timeout
= 1 * 3600 # One hours
1840 while deployment_timeout
> 0:
1841 if not RO_task_done
:
1842 desc
= await RO
.show("ns", item_id_name
=RO_nsr_id
, extra_item
="action",
1843 extra_item_id
=RO_nslcmop_id
)
1844 ns_status
, ns_status_info
= RO
.check_action_status(desc
)
1845 if ns_status
== "ERROR":
1846 raise ROclient
.ROClientException(ns_status_info
)
1847 elif ns_status
== "BUILD":
1848 detailed_status
= step
+ "; {}".format(ns_status_info
)
1849 elif ns_status
== "ACTIVE":
1851 step
= detailed_status
= "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id
)
1852 self
.logger
.debug(logging_text
+ step
)
1854 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
1856 desc
= await RO
.show("ns", RO_nsr_id
)
1857 ns_status
, ns_status_info
= RO
.check_ns_status(desc
)
1858 if ns_status
== "ERROR":
1859 raise ROclient
.ROClientException(ns_status_info
)
1860 elif ns_status
== "BUILD":
1861 detailed_status
= step
+ "; {}".format(ns_status_info
)
1862 elif ns_status
== "ACTIVE":
1863 step
= detailed_status
= "Waiting for management IP address reported by the VIM"
1865 desc
= await RO
.show("ns", RO_nsr_id
)
1866 nsr_lcm
["nsr_ip"] = RO
.get_ns_vnf_info(desc
)
1868 except ROclient
.ROClientException
as e
:
1869 if e
.http_code
!= 409: # IP address is not ready return code is 409 CONFLICT
1872 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
1873 if detailed_status
!= detailed_status_old
:
1874 detailed_status_old
= db_nslcmop_update
["detailed-status"] = detailed_status
1875 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1877 await asyncio
.sleep(5, loop
=self
.loop
)
1878 deployment_timeout
-= 5
1879 if deployment_timeout
<= 0:
1880 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
1882 step
= "Updating VNFRs"
1883 # self.ns_update_vnfr({db_vnfr["member-vnf-index-ref"]: db_vnfr}, ns_RO_info)
1884 self
.ns_update_vnfr_2({db_vnfr
["member-vnf-index-ref"]: db_vnfr
}, desc
)
1886 # update VDU_SCALING_INFO with the obtained ip_addresses
1887 if vdu_scaling_info
["scaling_direction"] == "OUT":
1888 for vdur
in reversed(db_vnfr
["vdur"]):
1889 if vdu_scaling_info
["vdu-create"].get(vdur
["vdu-id-ref"]):
1890 vdu_scaling_info
["vdu-create"][vdur
["vdu-id-ref"]] -= 1
1891 vdu_scaling_info
["vdu"].append({
1892 "name": vdur
["name"],
1893 "vdu_id": vdur
["vdu-id-ref"],
1896 for interface
in vdur
["interfaces"]:
1897 vdu_scaling_info
["vdu"][-1]["interface"].append({
1898 "name": interface
["name"],
1899 "ip_address": interface
["ip-address"],
1900 "mac_address": interface
.get("mac-address"),
1902 del vdu_scaling_info
["vdu-create"]
1905 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1907 # execute primitive service POST-SCALING
1908 step
= "Executing post-scale vnf-config-primitive"
1909 if scaling_descriptor
.get("scaling-config-action"):
1910 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
1911 if scaling_config_action
.get("trigger") and scaling_config_action
["trigger"] == "post-scale-out" \
1912 and scaling_type
== "SCALE_OUT":
1913 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
1914 step
= db_nslcmop_update
["detailed-status"] = \
1915 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive
)
1916 # look for primitive
1917 primitive_params
= {}
1918 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
1919 if config_primitive
["name"] == vnf_config_primitive
:
1920 for parameter
in config_primitive
.get("parameter", ()):
1921 if 'default-value' in parameter
and \
1922 parameter
['default-value'] == "<VDU_SCALE_INFO>":
1923 primitive_params
[parameter
["name"]] = yaml
.safe_dump(vdu_scaling_info
,
1924 default_flow_style
=True,
1928 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
1929 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
1930 "match any vnf-cnfiguration:config-primitive".format(scaling_group
,
1932 result
, result_detail
= await self
._ns
_execute
_primitive
(nsr_lcm
, vnf_index
,
1933 vnf_config_primitive
, primitive_params
)
1934 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
1935 vnf_config_primitive
, result
, result_detail
))
1936 if result
== "FAILED":
1937 raise LcmException(result_detail
)
1939 db_nslcmop_update
["operationState"] = "COMPLETED"
1940 db_nslcmop_update
["statusEnteredTime"] = time()
1941 db_nslcmop_update
["detailed-status"] = "done"
1942 db_nsr_update
["detailed-status"] = "done"
1943 db_nsr_update
["operational-status"] = "running"
1945 await self
.msg
.aiowrite("ns", "scaled", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
})
1947 # await asyncio.sleep(cooldown_time)
1948 # await self.msg.aiowrite("ns", "scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
1949 except Exception as e
:
1950 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1951 self
.logger
.debug(logging_text
+ "Exit Ok")
1953 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
1954 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
1956 except asyncio
.CancelledError
:
1957 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1958 exc
= "Operation was cancelled"
1959 except Exception as e
:
1960 exc
= traceback
.format_exc()
1961 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
1965 db_nslcmop_update
= {
1966 "detailed-status": "FAILED {}: {}".format(step
, exc
),
1967 "operationState": "FAILED",
1968 "statusEnteredTime": time(),
1971 db_nsr_update
["operational-status"] = "FAILED {}: {}".format(step
, exc
),
1972 db_nsr_update
["detailed-status"] = "failed"
1973 if db_nslcmop_update
:
1974 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1976 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1977 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_scale")
1979 async def test(self
, param
=None):
1980 self
.logger
.debug("Starting/Ending test task: {}".format(param
))
1982 async def kafka_ping(self
):
1983 self
.logger
.debug("Task kafka_ping Enter")
1984 consecutive_errors
= 0
1986 kafka_has_received
= False
1987 self
.pings_not_received
= 1
1990 await self
.msg
.aiowrite("admin", "ping", {"from": "lcm", "to": "lcm"}, self
.loop
)
1991 # time between pings are low when it is not received and at starting
1992 wait_time
= 5 if not kafka_has_received
else 120
1993 if not self
.pings_not_received
:
1994 kafka_has_received
= True
1995 self
.pings_not_received
+= 1
1996 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
1997 if self
.pings_not_received
> 10:
1998 raise LcmException("It is not receiving pings from Kafka bus")
1999 consecutive_errors
= 0
2001 except LcmException
:
2003 except Exception as e
:
2004 # if not first_start is the first time after starting. So leave more time and wait
2005 # to allow kafka starts
2006 if consecutive_errors
== 8 if not first_start
else 30:
2007 self
.logger
.error("Task kafka_read task exit error too many errors. Exception: {}".format(e
))
2009 consecutive_errors
+= 1
2010 self
.logger
.error("Task kafka_read retrying after Exception {}".format(e
))
2011 wait_time
= 1 if not first_start
else 5
2012 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
2014 async def kafka_read(self
):
2015 self
.logger
.debug("Task kafka_read Enter")
2017 # future = asyncio.Future()
2018 consecutive_errors
= 0
2020 while consecutive_errors
< 10:
2022 topics
= ("admin", "ns", "vim_account", "sdn")
2023 topic
, command
, params
= await self
.msg
.aioread(topics
, self
.loop
)
2024 if topic
!= "admin" and command
!= "ping":
2025 self
.logger
.debug("Task kafka_read receives {} {}: {}".format(topic
, command
, params
))
2026 consecutive_errors
= 0
2029 if command
== "exit":
2032 elif command
.startswith("#"):
2034 elif command
== "echo":
2039 elif command
== "test":
2040 asyncio
.Task(self
.test(params
), loop
=self
.loop
)
2043 if topic
== "admin":
2044 if command
== "ping" and params
["to"] == "lcm" and params
["from"] == "lcm":
2045 self
.pings_not_received
= 0
2048 if command
== "instantiate":
2049 # self.logger.debug("Deploying NS {}".format(nsr_id))
2051 nslcmop_id
= nslcmop
["_id"]
2052 nsr_id
= nslcmop
["nsInstanceId"]
2053 task
= asyncio
.ensure_future(self
.ns_instantiate(nsr_id
, nslcmop_id
))
2054 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_instantiate", task
)
2056 elif command
== "terminate":
2057 # self.logger.debug("Deleting NS {}".format(nsr_id))
2059 nslcmop_id
= nslcmop
["_id"]
2060 nsr_id
= nslcmop
["nsInstanceId"]
2061 self
.lcm_tasks
.cancel(topic
, nsr_id
)
2062 task
= asyncio
.ensure_future(self
.ns_terminate(nsr_id
, nslcmop_id
))
2063 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_terminate", task
)
2065 elif command
== "action":
2066 # self.logger.debug("Update NS {}".format(nsr_id))
2068 nslcmop_id
= nslcmop
["_id"]
2069 nsr_id
= nslcmop
["nsInstanceId"]
2070 task
= asyncio
.ensure_future(self
.ns_action(nsr_id
, nslcmop_id
))
2071 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_action", task
)
2073 elif command
== "scale":
2074 # self.logger.debug("Update NS {}".format(nsr_id))
2076 nslcmop_id
= nslcmop
["_id"]
2077 nsr_id
= nslcmop
["nsInstanceId"]
2078 task
= asyncio
.ensure_future(self
.ns_scale(nsr_id
, nslcmop_id
))
2079 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_scale", task
)
2081 elif command
== "show":
2083 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2084 print("nsr:\n _id={}\n operational-status: {}\n config-status: {}"
2085 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
2086 "".format(nsr_id
, db_nsr
["operational-status"], db_nsr
["config-status"],
2087 db_nsr
["detailed-status"],
2088 db_nsr
["_admin"]["deployed"], self
.lcm_ns_tasks
.get(nsr_id
)))
2089 except Exception as e
:
2090 print("nsr {} not found: {}".format(nsr_id
, e
))
2093 elif command
== "deleted":
2094 continue # TODO cleaning of task just in case should be done
2095 elif command
in ("terminated", "instantiated", "scaled", "actioned"): # "scaled-cooldown-time"
2097 elif topic
== "vim_account":
2098 vim_id
= params
["_id"]
2099 if command
== "create":
2100 task
= asyncio
.ensure_future(self
.vim_create(params
, order_id
))
2101 self
.lcm_tasks
.register("vim_account", vim_id
, order_id
, "vim_create", task
)
2103 elif command
== "delete":
2104 self
.lcm_tasks
.cancel(topic
, vim_id
)
2105 task
= asyncio
.ensure_future(self
.vim_delete(vim_id
, order_id
))
2106 self
.lcm_tasks
.register("vim_account", vim_id
, order_id
, "vim_delete", task
)
2108 elif command
== "show":
2109 print("not implemented show with vim_account")
2112 elif command
== "edit":
2113 task
= asyncio
.ensure_future(self
.vim_edit(params
, order_id
))
2114 self
.lcm_tasks
.register("vim_account", vim_id
, order_id
, "vim_edit", task
)
2116 elif topic
== "sdn":
2117 _sdn_id
= params
["_id"]
2118 if command
== "create":
2119 task
= asyncio
.ensure_future(self
.sdn_create(params
, order_id
))
2120 self
.lcm_tasks
.register("sdn", _sdn_id
, order_id
, "sdn_create", task
)
2122 elif command
== "delete":
2123 self
.lcm_tasks
.cancel(topic
, _sdn_id
)
2124 task
= asyncio
.ensure_future(self
.sdn_delete(_sdn_id
, order_id
))
2125 self
.lcm_tasks
.register("sdn", _sdn_id
, order_id
, "sdn_delete", task
)
2127 elif command
== "edit":
2128 task
= asyncio
.ensure_future(self
.sdn_edit(params
, order_id
))
2129 self
.lcm_tasks
.register("sdn", _sdn_id
, order_id
, "sdn_edit", task
)
2131 self
.logger
.critical("unknown topic {} and command '{}'".format(topic
, command
))
2132 except Exception as e
:
2133 # if not first_start is the first time after starting. So leave more time and wait
2134 # to allow kafka starts
2135 if consecutive_errors
== 8 if not first_start
else 30:
2136 self
.logger
.error("Task kafka_read task exit error too many errors. Exception: {}".format(e
))
2138 consecutive_errors
+= 1
2139 self
.logger
.error("Task kafka_read retrying after Exception {}".format(e
))
2140 wait_time
= 2 if not first_start
else 5
2141 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
2143 # self.logger.debug("Task kafka_read terminating")
2144 self
.logger
.debug("Task kafka_read exit")
2147 self
.loop
= asyncio
.get_event_loop()
2150 self
.loop
.run_until_complete(self
.check_RO_version())
2152 self
.loop
.run_until_complete(asyncio
.gather(
2157 # self.logger.debug("Terminating cancelling creation tasks")
2158 # self.lcm_tasks.cancel("ALL", "create")
2160 # while self.is_pending_tasks():
2161 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
2162 # await asyncio.sleep(2, loop=self.loop)
2165 # self.lcm_tasks.cancel("ALL", "ALL")
2169 self
.db
.db_disconnect()
2171 self
.msg
.disconnect()
2173 self
.fs
.fs_disconnect()
2175 def read_config_file(self
, config_file
):
2176 # TODO make a [ini] + yaml inside parser
2177 # the configparser library is not suitable, because it does not admit comments at the end of line,
2178 # and not parse integer or boolean
2180 with
open(config_file
) as f
:
2182 for k
, v
in environ
.items():
2183 if not k
.startswith("OSMLCM_"):
2185 k_items
= k
.lower().split("_")
2188 for k_item
in k_items
[1:-1]:
2189 if k_item
in ("ro", "vca"):
2190 # put in capital letter
2191 k_item
= k_item
.upper()
2193 if k_items
[-1] == "port":
2194 c
[k_items
[-1]] = int(v
)
2197 except Exception as e
:
2198 self
.logger
.warn("skipping environ '{}' on exception '{}'".format(k
, e
))
2201 except Exception as e
:
2202 self
.logger
.critical("At config file '{}': {}".format(config_file
, e
))
2207 print("""Usage: {} [options]
2208 -c|--config [configuration_file]: loads the configuration file (default: ./nbi.cfg)
2209 -h|--help: shows this help
2210 """.format(sys
.argv
[0]))
2211 # --log-socket-host HOST: send logs to this host")
2212 # --log-socket-port PORT: send logs using this port (default: 9022)")
2215 if __name__
== '__main__':
2217 # load parameters and configuration
2218 opts
, args
= getopt
.getopt(sys
.argv
[1:], "hc:", ["config=", "help"])
2219 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
2222 if o
in ("-h", "--help"):
2225 elif o
in ("-c", "--config"):
2227 # elif o == "--log-socket-port":
2228 # log_socket_port = a
2229 # elif o == "--log-socket-host":
2230 # log_socket_host = a
2231 # elif o == "--log-file":
2234 assert False, "Unhandled option"
2236 if not path
.isfile(config_file
):
2237 print("configuration file '{}' that not exist".format(config_file
), file=sys
.stderr
)
2240 for config_file
in (__file__
[:__file__
.rfind(".")] + ".cfg", "./lcm.cfg", "/etc/osm/lcm.cfg"):
2241 if path
.isfile(config_file
):
2244 print("No configuration file 'nbi.cfg' found neither at local folder nor at /etc/osm/", file=sys
.stderr
)
2246 lcm
= Lcm(config_file
)
2248 except (LcmException
, getopt
.GetoptError
) as e
:
2249 print(str(e
), file=sys
.stderr
)