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.13'
36 lcm_version_date
= '2018-08-28'
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
:
133 # self.logger.debug("{} _id={} order_id={} task={} cancelled".format(topic, _id, op_id, task_name))
138 def __init__(self
, config_file
):
140 Init, Connect to database, filesystem storage, and messaging
141 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
148 self
.pings_not_received
= 1
150 # contains created tasks/futures to be able to cancel
151 self
.lcm_tasks
= TaskRegistry()
153 self
.logger
= logging
.getLogger('lcm')
155 config
= self
.read_config_file(config_file
)
158 "endpoint_url": "http://{}:{}/openmano".format(config
["RO"]["host"], config
["RO"]["port"]),
159 "tenant": config
.get("tenant", "osm"),
160 "logger_name": "lcm.ROclient",
164 self
.vca
= config
["VCA"] # TODO VCA
168 log_format_simple
= "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
169 log_formatter_simple
= logging
.Formatter(log_format_simple
, datefmt
='%Y-%m-%dT%H:%M:%S')
170 config
["database"]["logger_name"] = "lcm.db"
171 config
["storage"]["logger_name"] = "lcm.fs"
172 config
["message"]["logger_name"] = "lcm.msg"
173 if config
["global"].get("logfile"):
174 file_handler
= logging
.handlers
.RotatingFileHandler(config
["global"]["logfile"],
175 maxBytes
=100e6
, backupCount
=9, delay
=0)
176 file_handler
.setFormatter(log_formatter_simple
)
177 self
.logger
.addHandler(file_handler
)
178 if not config
["global"].get("nologging"):
179 str_handler
= logging
.StreamHandler()
180 str_handler
.setFormatter(log_formatter_simple
)
181 self
.logger
.addHandler(str_handler
)
183 if config
["global"].get("loglevel"):
184 self
.logger
.setLevel(config
["global"]["loglevel"])
186 # logging other modules
187 for k1
, logname
in {"message": "lcm.msg", "database": "lcm.db", "storage": "lcm.fs"}.items():
188 config
[k1
]["logger_name"] = logname
189 logger_module
= logging
.getLogger(logname
)
190 if config
[k1
].get("logfile"):
191 file_handler
= logging
.handlers
.RotatingFileHandler(config
[k1
]["logfile"],
192 maxBytes
=100e6
, backupCount
=9, delay
=0)
193 file_handler
.setFormatter(log_formatter_simple
)
194 logger_module
.addHandler(file_handler
)
195 if config
[k1
].get("loglevel"):
196 logger_module
.setLevel(config
[k1
]["loglevel"])
197 self
.logger
.critical("starting osm/lcm version {} {}".format(lcm_version
, lcm_version_date
))
200 server
=config
['VCA']['host'],
201 port
=config
['VCA']['port'],
202 user
=config
['VCA']['user'],
203 secret
=config
['VCA']['secret'],
204 # TODO: This should point to the base folder where charms are stored,
205 # if there is a common one (like object storage). Otherwise, leave
206 # it unset and pass it via DeployCharms
207 # artifacts=config['VCA'][''],
210 # check version of N2VC
211 # TODO enhance with int conversion or from distutils.version import LooseVersion
212 # or with list(map(int, version.split(".")))
213 if N2VC_version
< "0.0.2":
214 raise LcmException("Not compatible osm/N2VC version '{}'. Needed '0.0.2' or higher".format(N2VC_version
))
217 # TODO check database version
218 if config
["database"]["driver"] == "mongo":
219 self
.db
= dbmongo
.DbMongo()
220 self
.db
.db_connect(config
["database"])
221 elif config
["database"]["driver"] == "memory":
222 self
.db
= dbmemory
.DbMemory()
223 self
.db
.db_connect(config
["database"])
225 raise LcmException("Invalid configuration param '{}' at '[database]':'driver'".format(
226 config
["database"]["driver"]))
228 if config
["storage"]["driver"] == "local":
229 self
.fs
= fslocal
.FsLocal()
230 self
.fs
.fs_connect(config
["storage"])
232 raise LcmException("Invalid configuration param '{}' at '[storage]':'driver'".format(
233 config
["storage"]["driver"]))
235 if config
["message"]["driver"] == "local":
236 self
.msg
= msglocal
.MsgLocal()
237 self
.msg
.connect(config
["message"])
238 elif config
["message"]["driver"] == "kafka":
239 self
.msg
= msgkafka
.MsgKafka()
240 self
.msg
.connect(config
["message"])
242 raise LcmException("Invalid configuration param '{}' at '[message]':'driver'".format(
243 config
["storage"]["driver"]))
244 except (DbException
, FsException
, MsgException
) as e
:
245 self
.logger
.critical(str(e
), exc_info
=True)
246 raise LcmException(str(e
))
248 async def check_RO_version(self
):
250 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
251 RO_version
= await RO
.get_version()
252 if RO_version
< min_RO_version
:
253 raise LcmException("Not compatible osm/RO version '{}.{}.{}'. Needed '{}.{}.{}' or higher".format(
254 *RO_version
, *min_RO_version
256 except ROclient
.ROClientException
as e
:
257 self
.logger
.critical("Error while conneting to osm/RO " + str(e
), exc_info
=True)
258 raise LcmException(str(e
))
260 def update_db_2(self
, item
, _id
, _desc
):
262 Updates database with _desc information. Upon success _desc is cleared
271 self
.db
.set_one(item
, {"_id": _id
}, _desc
)
273 except DbException
as e
:
274 self
.logger
.error("Updating {} _id={} with '{}'. Error: {}".format(item
, _id
, _desc
, e
))
276 async def vim_create(self
, vim_content
, order_id
):
277 vim_id
= vim_content
["_id"]
278 logging_text
= "Task vim_create={} ".format(vim_id
)
279 self
.logger
.debug(logging_text
+ "Enter")
285 step
= "Getting vim-id='{}' from db".format(vim_id
)
286 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_id
})
287 db_vim_update
["_admin.deployed.RO"] = None
288 if vim_content
.get("config") and vim_content
["config"].get("sdn-controller"):
289 step
= "Getting sdn-controller-id='{}' from db".format(vim_content
["config"]["sdn-controller"])
290 db_sdn
= self
.db
.get_one("sdns", {"_id": vim_content
["config"]["sdn-controller"]})
291 if db_sdn
.get("_admin") and db_sdn
["_admin"].get("deployed") and db_sdn
["_admin"]["deployed"].get("RO"):
292 RO_sdn_id
= db_sdn
["_admin"]["deployed"]["RO"]
294 raise LcmException("sdn-controller={} is not available. Not deployed at RO".format(
295 vim_content
["config"]["sdn-controller"]))
297 step
= "Creating vim at RO"
298 db_vim_update
["_admin.detailed-status"] = step
299 self
.update_db_2("vim_accounts", vim_id
, db_vim_update
)
300 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
301 vim_RO
= deepcopy(vim_content
)
302 vim_RO
.pop("_id", None)
303 vim_RO
.pop("_admin", None)
304 vim_RO
.pop("schema_version", None)
305 vim_RO
.pop("schema_type", None)
306 vim_RO
.pop("vim_tenant_name", None)
307 vim_RO
["type"] = vim_RO
.pop("vim_type")
308 vim_RO
.pop("vim_user", None)
309 vim_RO
.pop("vim_password", None)
311 vim_RO
["config"]["sdn-controller"] = RO_sdn_id
312 desc
= await RO
.create("vim", descriptor
=vim_RO
)
313 RO_vim_id
= desc
["uuid"]
314 db_vim_update
["_admin.deployed.RO"] = RO_vim_id
316 step
= "Creating vim_account at RO"
317 db_vim_update
["_admin.detailed-status"] = step
318 self
.update_db_2("vim_accounts", vim_id
, db_vim_update
)
320 vim_account_RO
= {"vim_tenant_name": vim_content
["vim_tenant_name"],
321 "vim_username": vim_content
["vim_user"],
322 "vim_password": vim_content
["vim_password"]
324 if vim_RO
.get("config"):
325 vim_account_RO
["config"] = vim_RO
["config"]
326 if "sdn-controller" in vim_account_RO
["config"]:
327 del vim_account_RO
["config"]["sdn-controller"]
328 if "sdn-port-mapping" in vim_account_RO
["config"]:
329 del vim_account_RO
["config"]["sdn-port-mapping"]
330 desc
= await RO
.attach_datacenter(RO_vim_id
, descriptor
=vim_account_RO
)
331 db_vim_update
["_admin.deployed.RO-account"] = desc
["uuid"]
332 db_vim_update
["_admin.operationalState"] = "ENABLED"
333 db_vim_update
["_admin.detailed-status"] = "Done"
335 # await asyncio.sleep(15) # TODO remove. This is for test
336 self
.logger
.debug(logging_text
+ "Exit Ok RO_vim_id={}".format(RO_vim_id
))
339 except (ROclient
.ROClientException
, DbException
) as e
:
340 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
342 except Exception as e
:
343 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
347 db_vim_update
["_admin.operationalState"] = "ERROR"
348 db_vim_update
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
350 self
.update_db_2("vim_accounts", vim_id
, db_vim_update
)
351 self
.lcm_tasks
.remove("vim_account", vim_id
, order_id
)
353 async def vim_edit(self
, vim_content
, order_id
):
354 vim_id
= vim_content
["_id"]
355 logging_text
= "Task vim_edit={} ".format(vim_id
)
356 self
.logger
.debug(logging_text
+ "Enter")
362 step
= "Getting vim-id='{}' from db".format(vim_id
)
364 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_id
})
366 # look if previous tasks in process
367 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account", vim_id
, order_id
)
369 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
370 self
.logger
.debug(logging_text
+ step
)
371 # TODO write this to database
372 await asyncio
.wait(task_dependency
, timeout
=3600)
374 if db_vim
.get("_admin") and db_vim
["_admin"].get("deployed") and db_vim
["_admin"]["deployed"].get("RO"):
375 if vim_content
.get("config") and vim_content
["config"].get("sdn-controller"):
376 step
= "Getting sdn-controller-id='{}' from db".format(vim_content
["config"]["sdn-controller"])
377 db_sdn
= self
.db
.get_one("sdns", {"_id": vim_content
["config"]["sdn-controller"]})
379 # look if previous tasks in process
380 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("sdn", db_sdn
["_id"])
382 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
383 self
.logger
.debug(logging_text
+ step
)
384 # TODO write this to database
385 await asyncio
.wait(task_dependency
, timeout
=3600)
387 if db_sdn
.get("_admin") and db_sdn
["_admin"].get("deployed") and db_sdn
["_admin"]["deployed"].get(
389 RO_sdn_id
= db_sdn
["_admin"]["deployed"]["RO"]
391 raise LcmException("sdn-controller={} is not available. Not deployed at RO".format(
392 vim_content
["config"]["sdn-controller"]))
394 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
395 step
= "Editing vim at RO"
396 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
397 vim_RO
= deepcopy(vim_content
)
398 vim_RO
.pop("_id", None)
399 vim_RO
.pop("_admin", None)
400 vim_RO
.pop("schema_version", None)
401 vim_RO
.pop("schema_type", None)
402 vim_RO
.pop("vim_tenant_name", None)
403 if "vim_type" in vim_RO
:
404 vim_RO
["type"] = vim_RO
.pop("vim_type")
405 vim_RO
.pop("vim_user", None)
406 vim_RO
.pop("vim_password", None)
408 vim_RO
["config"]["sdn-controller"] = RO_sdn_id
409 # TODO make a deep update of sdn-port-mapping
411 await RO
.edit("vim", RO_vim_id
, descriptor
=vim_RO
)
413 step
= "Editing vim-account at RO tenant"
415 if "config" in vim_content
:
416 if "sdn-controller" in vim_content
["config"]:
417 del vim_content
["config"]["sdn-controller"]
418 if "sdn-port-mapping" in vim_content
["config"]:
419 del vim_content
["config"]["sdn-port-mapping"]
420 if not vim_content
["config"]:
421 del vim_content
["config"]
422 for k
in ("vim_tenant_name", "vim_password", "config"):
424 vim_account_RO
[k
] = vim_content
[k
]
425 if "vim_user" in vim_content
:
426 vim_content
["vim_username"] = vim_content
["vim_user"]
427 # vim_account must be edited always even if empty in order to ensure changes are translated to RO
428 # vim_thread. RO will remove and relaunch a new thread for this vim_account
429 await RO
.edit("vim_account", RO_vim_id
, descriptor
=vim_account_RO
)
430 db_vim_update
["_admin.operationalState"] = "ENABLED"
432 self
.logger
.debug(logging_text
+ "Exit Ok RO_vim_id={}".format(RO_vim_id
))
435 except (ROclient
.ROClientException
, DbException
) as e
:
436 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
438 except Exception as e
:
439 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
443 db_vim_update
["_admin.operationalState"] = "ERROR"
444 db_vim_update
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
446 self
.update_db_2("vim_accounts", vim_id
, db_vim_update
)
447 self
.lcm_tasks
.remove("vim_account", vim_id
, order_id
)
449 async def vim_delete(self
, vim_id
, order_id
):
450 logging_text
= "Task vim_delete={} ".format(vim_id
)
451 self
.logger
.debug(logging_text
+ "Enter")
455 step
= "Getting vim from db"
457 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_id
})
458 if db_vim
.get("_admin") and db_vim
["_admin"].get("deployed") and db_vim
["_admin"]["deployed"].get("RO"):
459 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
460 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
461 step
= "Detaching vim from RO tenant"
463 await RO
.detach_datacenter(RO_vim_id
)
464 except ROclient
.ROClientException
as e
:
465 if e
.http_code
== 404: # not found
466 self
.logger
.debug(logging_text
+ "RO_vim_id={} already detached".format(RO_vim_id
))
470 step
= "Deleting vim from RO"
472 await RO
.delete("vim", RO_vim_id
)
473 except ROclient
.ROClientException
as e
:
474 if e
.http_code
== 404: # not found
475 self
.logger
.debug(logging_text
+ "RO_vim_id={} already deleted".format(RO_vim_id
))
480 self
.logger
.error(logging_text
+ "Nohing to remove at RO")
481 self
.db
.del_one("vim_accounts", {"_id": vim_id
})
482 self
.logger
.debug(logging_text
+ "Exit Ok")
485 except (ROclient
.ROClientException
, DbException
) as e
:
486 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
488 except Exception as e
:
489 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
492 self
.lcm_tasks
.remove("vim_account", vim_id
, order_id
)
494 db_vim_update
["_admin.operationalState"] = "ERROR"
495 db_vim_update
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
497 self
.update_db_2("vim_accounts", vim_id
, db_vim_update
)
498 self
.lcm_tasks
.remove("vim_account", vim_id
, order_id
)
500 async def sdn_create(self
, sdn_content
, order_id
):
501 sdn_id
= sdn_content
["_id"]
502 logging_text
= "Task sdn_create={} ".format(sdn_id
)
503 self
.logger
.debug(logging_text
+ "Enter")
509 step
= "Getting sdn from db"
510 db_sdn
= self
.db
.get_one("sdns", {"_id": sdn_id
})
511 db_sdn_update
["_admin.deployed.RO"] = None
513 step
= "Creating sdn at RO"
514 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
515 sdn_RO
= deepcopy(sdn_content
)
516 sdn_RO
.pop("_id", None)
517 sdn_RO
.pop("_admin", None)
518 sdn_RO
.pop("schema_version", None)
519 sdn_RO
.pop("schema_type", None)
520 sdn_RO
.pop("description", None)
521 desc
= await RO
.create("sdn", descriptor
=sdn_RO
)
522 RO_sdn_id
= desc
["uuid"]
523 db_sdn_update
["_admin.deployed.RO"] = RO_sdn_id
524 db_sdn_update
["_admin.operationalState"] = "ENABLED"
525 self
.logger
.debug(logging_text
+ "Exit Ok RO_sdn_id={}".format(RO_sdn_id
))
528 except (ROclient
.ROClientException
, DbException
) as e
:
529 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
531 except Exception as e
:
532 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
536 db_sdn_update
["_admin.operationalState"] = "ERROR"
537 db_sdn_update
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
539 self
.update_db_2("sdns", sdn_id
, db_sdn_update
)
540 self
.lcm_tasks
.remove("sdn", sdn_id
, order_id
)
542 async def sdn_edit(self
, sdn_content
, order_id
):
543 sdn_id
= sdn_content
["_id"]
544 logging_text
= "Task sdn_edit={} ".format(sdn_id
)
545 self
.logger
.debug(logging_text
+ "Enter")
549 step
= "Getting sdn from db"
551 db_sdn
= self
.db
.get_one("sdns", {"_id": sdn_id
})
552 if db_sdn
.get("_admin") and db_sdn
["_admin"].get("deployed") and db_sdn
["_admin"]["deployed"].get("RO"):
553 RO_sdn_id
= db_sdn
["_admin"]["deployed"]["RO"]
554 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
555 step
= "Editing sdn at RO"
556 sdn_RO
= deepcopy(sdn_content
)
557 sdn_RO
.pop("_id", None)
558 sdn_RO
.pop("_admin", None)
559 sdn_RO
.pop("schema_version", None)
560 sdn_RO
.pop("schema_type", None)
561 sdn_RO
.pop("description", None)
563 await RO
.edit("sdn", RO_sdn_id
, descriptor
=sdn_RO
)
564 db_sdn_update
["_admin.operationalState"] = "ENABLED"
566 self
.logger
.debug(logging_text
+ "Exit Ok RO_sdn_id".format(RO_sdn_id
))
569 except (ROclient
.ROClientException
, DbException
) as e
:
570 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
572 except Exception as e
:
573 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
577 db_sdn
["_admin.operationalState"] = "ERROR"
578 db_sdn
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
580 self
.update_db_2("sdns", sdn_id
, db_sdn_update
)
581 self
.lcm_tasks
.remove("sdn", sdn_id
, order_id
)
583 async def sdn_delete(self
, sdn_id
, order_id
):
584 logging_text
= "Task sdn_delete={} ".format(sdn_id
)
585 self
.logger
.debug(logging_text
+ "Enter")
589 step
= "Getting sdn from db"
591 db_sdn
= self
.db
.get_one("sdns", {"_id": sdn_id
})
592 if db_sdn
.get("_admin") and db_sdn
["_admin"].get("deployed") and db_sdn
["_admin"]["deployed"].get("RO"):
593 RO_sdn_id
= db_sdn
["_admin"]["deployed"]["RO"]
594 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
595 step
= "Deleting sdn from RO"
597 await RO
.delete("sdn", RO_sdn_id
)
598 except ROclient
.ROClientException
as e
:
599 if e
.http_code
== 404: # not found
600 self
.logger
.debug(logging_text
+ "RO_sdn_id={} already deleted".format(RO_sdn_id
))
605 self
.logger
.error(logging_text
+ "Skipping. There is not RO information at database")
606 self
.db
.del_one("sdns", {"_id": sdn_id
})
607 self
.logger
.debug("sdn_delete task sdn_id={} Exit Ok".format(sdn_id
))
610 except (ROclient
.ROClientException
, DbException
) as e
:
611 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
613 except Exception as e
:
614 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
618 db_sdn
["_admin.operationalState"] = "ERROR"
619 db_sdn
["_admin.detailed-status"] = "ERROR {}: {}".format(step
, exc
)
621 self
.update_db_2("sdns", sdn_id
, db_sdn_update
)
622 self
.lcm_tasks
.remove("sdn", sdn_id
, order_id
)
624 def vnfd2RO(self
, vnfd
, new_id
=None):
626 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
627 :param vnfd: input vnfd
628 :param new_id: overrides vnf id if provided
629 :return: copy of vnfd
633 vnfd_RO
= deepcopy(vnfd
)
634 vnfd_RO
.pop("_id", None)
635 vnfd_RO
.pop("_admin", None)
637 vnfd_RO
["id"] = new_id
638 for vdu
in vnfd_RO
["vdu"]:
639 if "cloud-init-file" in vdu
:
640 base_folder
= vnfd
["_admin"]["storage"]
641 clout_init_file
= "{}/{}/cloud_init/{}".format(
642 base_folder
["folder"],
643 base_folder
["pkg-dir"],
644 vdu
["cloud-init-file"]
646 ci_file
= self
.fs
.file_open(clout_init_file
, "r")
647 # TODO: detect if binary or text. Propose to read as binary and try to decode to utf8. If fails
648 # convert to base 64 or similar
649 clout_init_content
= ci_file
.read()
652 vdu
.pop("cloud-init-file", None)
653 vdu
["cloud-init"] = clout_init_content
654 # remnove unused by RO configuration, monitoring, scaling
655 vnfd_RO
.pop("vnf-configuration", None)
656 vnfd_RO
.pop("monitoring-param", None)
657 vnfd_RO
.pop("scaling-group-descriptor", None)
659 except FsException
as e
:
660 raise LcmException("Error reading file at vnfd {}: {} ".format(vnfd
["_id"], e
))
665 def n2vc_callback(self
, model_name
, application_name
, status
, message
, db_nsr
, db_nslcmop
, task
=None):
667 Callback both for charm status change and task completion
668 :param model_name: Charm model name
669 :param application_name: Charm application name
670 :param status: Can be
671 - blocked: The unit needs manual intervention
672 - maintenance: The unit is actively deploying/configuring
673 - waiting: The unit is waiting for another charm to be ready
674 - active: The unit is deployed, configured, and ready
675 - error: The charm has failed and needs attention.
676 - terminated: The charm has been destroyed
679 :param message: detailed message error
680 :param db_nsr: nsr database content
681 :param db_nslcmop: nslcmop database content
682 :param task: None for charm status change, or task for completion task callback
688 db_nslcmop_update
= {}
690 nsr_id
= db_nsr
["_id"]
691 nsr_lcm
= db_nsr
["_admin"]["deployed"]
692 nslcmop_id
= db_nslcmop
["_id"]
693 ns_operation
= db_nslcmop
["lcmOperationType"]
694 logging_text
= "Task ns={} {}={} [n2vc_callback] application={}".format(nsr_id
, ns_operation
, nslcmop_id
,
696 vca_deployed
= nsr_lcm
["VCA"].get(application_name
)
698 self
.logger
.error(logging_text
+ " Not present at nsr._admin.deployed.VCA")
703 self
.logger
.debug(logging_text
+ " task Cancelled")
704 # TODO update db_nslcmop
708 exc
= task
.exception()
710 self
.logger
.error(logging_text
+ " task Exception={}".format(exc
))
711 if ns_operation
in ("instantiate", "terminate"):
712 vca_deployed
['operational-status'] = "error"
713 db_nsr_update
["_admin.deployed.VCA.{}.operational-status".format(application_name
)] = \
715 vca_deployed
['detailed-status'] = str(exc
)
717 "_admin.deployed.VCA.{}.detailed-status".format(application_name
)] = str(exc
)
718 elif ns_operation
== "action":
719 db_nslcmop_update
["operationState"] = "FAILED"
720 db_nslcmop_update
["detailed-status"] = str(exc
)
721 db_nslcmop_update
["statusEnteredTime"] = time()
725 self
.logger
.debug(logging_text
+ " task Done")
726 # TODO revise with Adam if action is finished and ok when task is done
727 if ns_operation
== "action":
728 db_nslcmop_update
["operationState"] = "COMPLETED"
729 db_nslcmop_update
["detailed-status"] = "Done"
730 db_nslcmop_update
["statusEnteredTime"] = time()
731 # task is Done, but callback is still ongoing. So ignore
734 self
.logger
.debug(logging_text
+ " Enter status={}".format(status
))
735 if vca_deployed
['operational-status'] == status
:
736 return # same status, ignore
737 vca_deployed
['operational-status'] = status
738 db_nsr_update
["_admin.deployed.VCA.{}.operational-status".format(application_name
)] = status
739 vca_deployed
['detailed-status'] = str(message
)
740 db_nsr_update
["_admin.deployed.VCA.{}.detailed-status".format(application_name
)] = str(message
)
742 self
.logger
.critical(logging_text
+ " Enter with bad parameters", exc_info
=True)
747 n2vc_error_text
= [] # contain text error list. If empty no one is in error status
748 for _
, vca_info
in nsr_lcm
["VCA"].items():
749 vca_status
= vca_info
["operational-status"]
750 if vca_status
not in status_map
:
752 status_map
[vca_status
] = 0
753 status_map
[vca_status
] += 1
755 if vca_status
!= "active":
757 if vca_status
in ("error", "blocked"):
758 n2vc_error_text
.append("member_vnf_index={} vdu_id={} {}: {}".format(vca_info
["member-vnf-index"],
759 vca_info
["vdu_id"], vca_status
,
760 vca_info
["detailed-status"]))
763 self
.logger
.debug(logging_text
+ " All active")
764 db_nsr_update
["config-status"] = "configured"
765 db_nsr_update
["detailed-status"] = "done"
766 db_nslcmop_update
["operationState"] = "COMPLETED"
767 db_nslcmop_update
["detailed-status"] = "Done"
768 db_nslcmop_update
["statusEnteredTime"] = time()
769 elif n2vc_error_text
:
770 db_nsr_update
["config-status"] = "failed"
771 error_text
= "fail configuring " + ";".join(n2vc_error_text
)
772 db_nsr_update
["detailed-status"] = error_text
773 db_nslcmop_update
["operationState"] = "FAILED_TEMP"
774 db_nslcmop_update
["detailed-status"] = error_text
775 db_nslcmop_update
["statusEnteredTime"] = time()
779 for status
, num
in status_map
.items():
780 cs
+= separator
+ "{}: {}".format(status
, num
)
782 db_nsr_update
["config-status"] = cs
783 db_nsr_update
["detailed-status"] = cs
784 db_nslcmop_update
["detailed-status"] = cs
786 except Exception as e
:
787 self
.logger
.critical(logging_text
+ " Exception {}".format(e
), exc_info
=True)
790 if db_nslcmop_update
:
791 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
793 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
794 except Exception as e
:
795 self
.logger
.critical(logging_text
+ " Update database Exception {}".format(e
), exc_info
=True)
797 def ns_params_2_RO(self
, ns_params
, nsd
, vnfd_dict
):
799 Creates a RO ns descriptor from OSM ns_instantite params
800 :param ns_params: OSM instantiate params
801 :return: The RO ns descriptor
805 def vim_account_2_RO(vim_account
):
806 if vim_account
in vim_2_RO
:
807 return vim_2_RO
[vim_account
]
809 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_account
})
810 if db_vim
["_admin"]["operationalState"] != "ENABLED":
811 raise LcmException("VIM={} is not available. operationalState={}".format(
812 vim_account
, db_vim
["_admin"]["operationalState"]))
813 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
814 vim_2_RO
[vim_account
] = RO_vim_id
817 def ip_profile_2_RO(ip_profile
):
818 RO_ip_profile
= deepcopy((ip_profile
))
819 if "dns-server" in RO_ip_profile
:
820 if isinstance(RO_ip_profile
["dns-server"], list):
821 RO_ip_profile
["dns-address"] = []
822 for ds
in RO_ip_profile
.pop("dns-server"):
823 RO_ip_profile
["dns-address"].append(ds
['address'])
825 RO_ip_profile
["dns-address"] = RO_ip_profile
.pop("dns-server")
826 if RO_ip_profile
.get("ip-version") == "ipv4":
827 RO_ip_profile
["ip-version"] = "IPv4"
828 if RO_ip_profile
.get("ip-version") == "ipv6":
829 RO_ip_profile
["ip-version"] = "IPv6"
830 if "dhcp-params" in RO_ip_profile
:
831 RO_ip_profile
["dhcp"] = RO_ip_profile
.pop("dhcp-params")
837 # "name": ns_params["nsName"],
838 # "description": ns_params.get("nsDescription"),
839 "datacenter": vim_account_2_RO(ns_params
["vimAccountId"]),
840 # "scenario": ns_params["nsdId"],
844 if ns_params
.get("ssh-authorized-key"):
845 RO_ns_params
["cloud-config"] = {"key-pairs": ns_params
["ssh-authorized-key"]}
846 if ns_params
.get("vnf"):
847 for vnf_params
in ns_params
["vnf"]:
848 for constituent_vnfd
in nsd
["constituent-vnfd"]:
849 if constituent_vnfd
["member-vnf-index"] == vnf_params
["member-vnf-index"]:
850 vnf_descriptor
= vnfd_dict
[constituent_vnfd
["vnfd-id-ref"]]
853 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index={} is not present at nsd:"
854 "constituent-vnfd".format(vnf_params
["member-vnf-index"]))
855 RO_vnf
= {"vdus": {}, "networks": {}}
856 if vnf_params
.get("vimAccountId"):
857 RO_vnf
["datacenter"] = vim_account_2_RO(vnf_params
["vimAccountId"])
858 if vnf_params
.get("vdu"):
859 for vdu_params
in vnf_params
["vdu"]:
860 RO_vnf
["vdus"][vdu_params
["id"]] = {}
861 if vdu_params
.get("volume"):
862 RO_vnf
["vdus"][vdu_params
["id"]]["devices"] = {}
863 for volume_params
in vdu_params
["volume"]:
864 RO_vnf
["vdus"][vdu_params
["id"]]["devices"][volume_params
["name"]] = {}
865 if volume_params
.get("vim-volume-id"):
866 RO_vnf
["vdus"][vdu_params
["id"]]["devices"][volume_params
["name"]]["vim_id"] = \
867 volume_params
["vim-volume-id"]
868 if vdu_params
.get("interface"):
869 RO_vnf
["vdus"][vdu_params
["id"]]["interfaces"] = {}
870 for interface_params
in vdu_params
["interface"]:
872 RO_vnf
["vdus"][vdu_params
["id"]]["interfaces"][interface_params
["name"]] = RO_interface
873 if interface_params
.get("ip-address"):
874 RO_interface
["ip_address"] = interface_params
["ip-address"]
875 if interface_params
.get("mac-address"):
876 RO_interface
["mac_address"] = interface_params
["mac-address"]
877 if interface_params
.get("floating-ip-required"):
878 RO_interface
["floating-ip"] = interface_params
["floating-ip-required"]
879 if vnf_params
.get("internal-vld"):
880 for internal_vld_params
in vnf_params
["internal-vld"]:
881 RO_vnf
["networks"][internal_vld_params
["name"]] = {}
882 if internal_vld_params
.get("vim-network-name"):
883 RO_vnf
["networks"][internal_vld_params
["name"]]["vim-network-name"] = \
884 internal_vld_params
["vim-network-name"]
885 if internal_vld_params
.get("ip-profile"):
886 RO_vnf
["networks"][internal_vld_params
["name"]]["ip-profile"] = \
887 ip_profile_2_RO(internal_vld_params
["ip-profile"])
888 if internal_vld_params
.get("internal-connection-point"):
889 for icp_params
in internal_vld_params
["internal-connection-point"]:
892 for vdu_descriptor
in vnf_descriptor
["vdu"]:
893 for vdu_interface
in vdu_descriptor
["interface"]:
894 if vdu_interface
.get("internal-connection-point-ref") == icp_params
["id-ref"]:
895 if vdu_descriptor
["id"] not in RO_vnf
["vdus"]:
896 RO_vnf
["vdus"][vdu_descriptor
["id"]] = {}
897 if "interfaces" not in RO_vnf
["vdus"][vdu_descriptor
["id"]]:
898 RO_vnf
["vdus"][vdu_descriptor
["id"]]["interfaces"] = {}
899 RO_ifaces
= RO_vnf
["vdus"][vdu_descriptor
["id"]]["interfaces"]
900 if vdu_interface
["name"] not in RO_ifaces
:
901 RO_ifaces
[vdu_interface
["name"]] = {}
903 RO_ifaces
[vdu_interface
["name"]]["ip_address"] = icp_params
["ip-address"]
909 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
910 "internal-vld:id-ref={} is not present at vnfd:internal-"
911 "connection-point".format(vnf_params
["member-vnf-index"],
912 icp_params
["id-ref"]))
914 if not RO_vnf
["vdus"]:
916 if not RO_vnf
["networks"]:
917 del RO_vnf
["networks"]
919 RO_ns_params
["vnfs"][vnf_params
["member-vnf-index"]] = RO_vnf
920 if ns_params
.get("vld"):
921 for vld_params
in ns_params
["vld"]:
923 if "ip-profile" in vld_params
:
924 RO_vld
["ip-profile"] = ip_profile_2_RO(vld_params
["ip-profile"])
925 if "vim-network-name" in vld_params
:
927 if isinstance(vld_params
["vim-network-name"], dict):
928 for vim_account
, vim_net
in vld_params
["vim-network-name"].items():
929 RO_vld
["sites"].append({
930 "netmap-use": vim_net
,
931 "datacenter": vim_account_2_RO(vim_account
)
933 else: # isinstance str
934 RO_vld
["sites"].append({"netmap-use": vld_params
["vim-network-name"]})
936 RO_ns_params
["networks"][vld_params
["name"]] = RO_vld
939 def ns_update_vnfr(self
, db_vnfrs
, nsr_desc_RO
):
941 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
946 for vnf_index
, db_vnfr
in db_vnfrs
.items():
947 for vnf_RO
in nsr_desc_RO
["vnfs"]:
948 if vnf_RO
["member_vnf_index"] == vnf_index
:
950 db_vnfr
["ip-address"] = vnfr_update
["ip-address"] = vnf_RO
.get("ip_address")
952 for vdur_RO
in vnf_RO
.get("vms", ()):
954 "vim-id": vdur_RO
.get("vim_vm_id"),
955 "ip-address": vdur_RO
.get("ip_address"),
956 "vdu-id-ref": vdur_RO
.get("vdu_osm_id"),
957 "name": vdur_RO
.get("vim_name"),
958 "status": vdur_RO
.get("status"),
959 "status-detailed": vdur_RO
.get("error_msg"),
963 for interface_RO
in vdur_RO
.get("interfaces", ()):
964 vdur
["interfaces"].append({
965 "ip-address": interface_RO
.get("ip_address"),
966 "mac-address": interface_RO
.get("mac_address"),
967 "name": interface_RO
.get("external_name"),
969 vdur_list
.append(vdur
)
970 db_vnfr
["vdur"] = vnfr_update
["vdur"] = vdur_list
971 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
975 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} at RO info".format(vnf_index
))
977 async def create_monitoring(self
, nsr_id
, vnf_member_index
, vnfd_desc
):
978 if not vnfd_desc
.get("scaling-group-descriptor"):
980 for scaling_group
in vnfd_desc
["scaling-group-descriptor"]:
981 scaling_policy_desc
= {}
984 "scaling_group_descriptor": {
985 "name": scaling_group
["name"],
986 "scaling_policy": scaling_policy_desc
989 for scaling_policy
in scaling_group
.get("scaling-policy"):
990 scaling_policy_desc
["scale_in_operation_type"] = scaling_policy_desc
["scale_out_operation_type"] = \
991 scaling_policy
["scaling-type"]
992 scaling_policy_desc
["threshold_time"] = scaling_policy
["threshold-time"]
993 scaling_policy_desc
["cooldown_time"] = scaling_policy
["cooldown-time"]
994 scaling_policy_desc
["scaling_criteria"] = []
995 for scaling_criteria
in scaling_policy
.get("scaling-criteria"):
996 scaling_criteria_desc
= {"scale_in_threshold": scaling_criteria
.get("scale-in-threshold"),
997 "scale_out_threshold": scaling_criteria
.get("scale-out-threshold"),
999 if not scaling_criteria
.get("vnf-monitoring-param-ref"):
1001 for monitoring_param
in vnfd_desc
.get("monitoring-param", ()):
1002 if monitoring_param
["id"] == scaling_criteria
["vnf-monitoring-param-ref"]:
1003 scaling_criteria_desc
["monitoring_param"] = {
1004 "id": monitoring_param
["id"],
1005 "name": monitoring_param
["name"],
1006 "aggregation_type": monitoring_param
.get("aggregation-type"),
1007 "vdu_name": monitoring_param
.get("vdu-ref"),
1008 "vnf_member_index": vnf_member_index
,
1011 scaling_policy_desc
["scaling_criteria"].append(scaling_criteria_desc
)
1015 "Task ns={} member_vnf_index={} Invalid vnfd vnf-monitoring-param-ref={} not in "
1016 "monitoring-param list".format(nsr_id
, vnf_member_index
,
1017 scaling_criteria
["vnf-monitoring-param-ref"]))
1019 await self
.msg
.aiowrite("lcm_pm", "configure_scaling", scaling_desc
, self
.loop
)
1021 async def ns_instantiate(self
, nsr_id
, nslcmop_id
):
1022 logging_text
= "Task ns={} instantiate={} ".format(nsr_id
, nslcmop_id
)
1023 self
.logger
.debug(logging_text
+ "Enter")
1024 # get all needed from database
1028 db_nslcmop_update
= {}
1030 RO_descriptor_number
= 0 # number of descriptors created at RO
1031 descriptor_id_2_RO
= {} # map between vnfd/nsd id to the id used at RO
1034 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
1035 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1036 step
= "Getting nsr={} from db".format(nsr_id
)
1037 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1038 ns_params
= db_nsr
.get("instantiate_params")
1040 nsr_name
= db_nsr
["name"] # TODO short-name??
1042 vnfr_filter
= {"nsr-id-ref": nsr_id
, "member-vnf-index-ref": None}
1043 for c_vnf
in nsd
["constituent-vnfd"]:
1044 vnfd_id
= c_vnf
["vnfd-id-ref"]
1045 vnfr_filter
["member-vnf-index-ref"] = c_vnf
["member-vnf-index"]
1046 step
= "Getting vnfr={} of nsr={} from db".format(c_vnf
["member-vnf-index"], nsr_id
)
1047 db_vnfrs
[c_vnf
["member-vnf-index"]] = self
.db
.get_one("vnfrs", vnfr_filter
)
1048 if vnfd_id
not in needed_vnfd
:
1049 step
= "Getting vnfd={} from db".format(vnfd_id
)
1050 needed_vnfd
[vnfd_id
] = self
.db
.get_one("vnfds", {"id": vnfd_id
})
1052 nsr_lcm
= db_nsr
["_admin"].get("deployed")
1054 nsr_lcm
= db_nsr
["_admin"]["deployed"] = {
1056 "RO": {"vnfd_id": {}, "nsd_id": None, "nsr_id": None, "nsr_status": "SCHEDULED"},
1060 db_nsr_update
["detailed-status"] = "creating"
1061 db_nsr_update
["operational-status"] = "init"
1063 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
1065 # get vnfds, instantiate at RO
1066 for vnfd_id
, vnfd
in needed_vnfd
.items():
1067 step
= db_nsr_update
["detailed-status"] = "Creating vnfd={} at RO".format(vnfd_id
)
1068 # self.logger.debug(logging_text + step)
1069 vnfd_id_RO
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, vnfd_id
[:23])
1070 descriptor_id_2_RO
[vnfd_id
] = vnfd_id_RO
1071 RO_descriptor_number
+= 1
1074 vnfd_list
= await RO
.get_list("vnfd", filter_by
={"osm_id": vnfd_id_RO
})
1076 db_nsr_update
["_admin.deployed.RO.vnfd_id.{}".format(vnfd_id
)] = vnfd_list
[0]["uuid"]
1077 self
.logger
.debug(logging_text
+ "vnfd={} exists at RO. Using RO_id={}".format(
1078 vnfd_id
, vnfd_list
[0]["uuid"]))
1080 vnfd_RO
= self
.vnfd2RO(vnfd
, vnfd_id_RO
)
1081 desc
= await RO
.create("vnfd", descriptor
=vnfd_RO
)
1082 db_nsr_update
["_admin.deployed.RO.vnfd_id.{}".format(vnfd_id
)] = desc
["uuid"]
1083 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1084 self
.logger
.debug(logging_text
+ "vnfd={} created at RO. RO_id={}".format(
1085 vnfd_id
, desc
["uuid"]))
1086 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1090 step
= db_nsr_update
["detailed-status"] = "Creating nsd={} at RO".format(nsd_id
)
1091 # self.logger.debug(logging_text + step)
1093 RO_osm_nsd_id
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, nsd_id
[:23])
1094 descriptor_id_2_RO
[nsd_id
] = RO_osm_nsd_id
1095 RO_descriptor_number
+= 1
1096 nsd_list
= await RO
.get_list("nsd", filter_by
={"osm_id": RO_osm_nsd_id
})
1098 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= nsd_list
[0]["uuid"]
1099 self
.logger
.debug(logging_text
+ "nsd={} exists at RO. Using RO_id={}".format(
1100 nsd_id
, RO_nsd_uuid
))
1102 nsd_RO
= deepcopy(nsd
)
1103 nsd_RO
["id"] = RO_osm_nsd_id
1104 nsd_RO
.pop("_id", None)
1105 nsd_RO
.pop("_admin", None)
1106 for c_vnf
in nsd_RO
["constituent-vnfd"]:
1107 vnfd_id
= c_vnf
["vnfd-id-ref"]
1108 c_vnf
["vnfd-id-ref"] = descriptor_id_2_RO
[vnfd_id
]
1109 desc
= await RO
.create("nsd", descriptor
=nsd_RO
)
1110 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1111 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= desc
["uuid"]
1112 self
.logger
.debug(logging_text
+ "nsd={} created at RO. RO_id={}".format(nsd_id
, RO_nsd_uuid
))
1113 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1116 # if present use it unless in error status
1117 RO_nsr_id
= db_nsr
["_admin"].get("deployed", {}).get("RO", {}).get("nsr_id")
1120 step
= db_nsr_update
["detailed-status"] = "Looking for existing ns at RO"
1121 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
1122 desc
= await RO
.show("ns", RO_nsr_id
)
1123 except ROclient
.ROClientException
as e
:
1124 if e
.http_code
!= HTTPStatus
.NOT_FOUND
:
1126 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1128 ns_status
, ns_status_info
= RO
.check_ns_status(desc
)
1129 db_nsr_update
["_admin.deployed.RO.nsr_status"] = ns_status
1130 if ns_status
== "ERROR":
1131 step
= db_nsr_update
["detailed-status"] = "Deleting ns at RO. RO_ns_id={}".format(RO_nsr_id
)
1132 self
.logger
.debug(logging_text
+ step
)
1133 await RO
.delete("ns", RO_nsr_id
)
1134 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1136 step
= db_nsr_update
["detailed-status"] = "Creating ns at RO"
1137 # self.logger.debug(logging_text + step)
1139 # check if VIM is creating and wait look if previous tasks in process
1140 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account", ns_params
["vimAccountId"])
1142 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
1143 self
.logger
.debug(logging_text
+ step
)
1144 await asyncio
.wait(task_dependency
, timeout
=3600)
1145 if ns_params
.get("vnf"):
1146 for vnf
in ns_params
["vnf"]:
1147 if "vimAccountId" in vnf
:
1148 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account",
1149 vnf
["vimAccountId"])
1151 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
1152 self
.logger
.debug(logging_text
+ step
)
1153 await asyncio
.wait(task_dependency
, timeout
=3600)
1155 RO_ns_params
= self
.ns_params_2_RO(ns_params
, nsd
, needed_vnfd
)
1156 desc
= await RO
.create("ns", descriptor
=RO_ns_params
,
1157 name
=db_nsr
["name"],
1158 scenario
=RO_nsd_uuid
)
1159 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = desc
["uuid"]
1160 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1161 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "BUILD"
1162 self
.logger
.debug(logging_text
+ "ns created at RO. RO_id={}".format(desc
["uuid"]))
1163 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1165 # update VNFR vimAccount
1166 step
= "Updating VNFR vimAcccount"
1167 for vnf_index
, vnfr
in db_vnfrs
.items():
1168 if vnfr
.get("vim-account-id"):
1170 vnfr_update
= {"vim-account-id": db_nsr
["instantiate_params"]["vimAccountId"]}
1171 if db_nsr
["instantiate_params"].get("vnf"):
1172 for vnf_params
in db_nsr
["instantiate_params"]["vnf"]:
1173 if vnf_params
.get("member-vnf-index") == vnf_index
:
1174 if vnf_params
.get("vimAccountId"):
1175 vnfr_update
["vim-account-id"] = vnf_params
.get("vimAccountId")
1177 self
.update_db_2("vnfrs", vnfr
["_id"], vnfr_update
)
1179 # wait until NS is ready
1180 step
= ns_status_detailed
= detailed_status
= "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id
)
1181 detailed_status_old
= None
1182 self
.logger
.debug(logging_text
+ step
)
1184 deployment_timeout
= 2 * 3600 # Two hours
1185 while deployment_timeout
> 0:
1186 desc
= await RO
.show("ns", RO_nsr_id
)
1187 ns_status
, ns_status_info
= RO
.check_ns_status(desc
)
1188 db_nsr_update
["admin.deployed.RO.nsr_status"] = ns_status
1189 if ns_status
== "ERROR":
1190 raise ROclient
.ROClientException(ns_status_info
)
1191 elif ns_status
== "BUILD":
1192 detailed_status
= ns_status_detailed
+ "; {}".format(ns_status_info
)
1193 elif ns_status
== "ACTIVE":
1194 step
= detailed_status
= "Waiting for management IP address reported by the VIM"
1196 nsr_lcm
["nsr_ip"] = RO
.get_ns_vnf_info(desc
)
1198 except ROclient
.ROClientException
as e
:
1199 if e
.http_code
!= 409: # IP address is not ready return code is 409 CONFLICT
1202 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
1203 if detailed_status
!= detailed_status_old
:
1204 detailed_status_old
= db_nsr_update
["detailed-status"] = detailed_status
1205 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1206 await asyncio
.sleep(5, loop
=self
.loop
)
1207 deployment_timeout
-= 5
1208 if deployment_timeout
<= 0:
1209 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
1211 step
= "Updating VNFRs"
1212 self
.ns_update_vnfr(db_vnfrs
, desc
)
1214 db_nsr
["detailed-status"] = "Configuring vnfr"
1215 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1217 # The parameters we'll need to deploy a charm
1218 number_to_configure
= 0
1220 def deploy(vnf_index
, vdu_id
, mgmt_ip_address
, config_primitive
=None):
1221 """An inner function to deploy the charm from either vnf or vdu
1222 vnf_index is mandatory. vdu_id can be None for a vnf configuration or the id for vdu configuration
1224 if not mgmt_ip_address
:
1225 raise LcmException("vnfd/vdu has not management ip address to configure it")
1227 # if number_to_configure == 0:
1228 # self.logger.debug("Logging into N2VC...")
1229 # task = asyncio.ensure_future(self.n2vc.login())
1230 # yield from asyncio.wait_for(task, 30.0)
1231 # self.logger.debug("Logged into N2VC!")
1233 # # await self.n2vc.login()
1235 # Note: The charm needs to exist on disk at the location
1236 # specified by charm_path.
1237 base_folder
= vnfd
["_admin"]["storage"]
1238 storage_params
= self
.fs
.get_params()
1239 charm_path
= "{}{}/{}/charms/{}".format(
1240 storage_params
["path"],
1241 base_folder
["folder"],
1242 base_folder
["pkg-dir"],
1246 # Setup the runtime parameters for this VNF
1247 params
= {'rw_mgmt_ip': mgmt_ip_address
}
1248 if config_primitive
:
1249 params
["initial-config-primitive"] = config_primitive
1251 # ns_name will be ignored in the current version of N2VC
1252 # but will be implemented for the next point release.
1253 model_name
= 'default'
1254 vdu_id_text
= "vnfd"
1256 vdu_id_text
= vdu_id
1257 application_name
= self
.n2vc
.FormatApplicationName(
1262 if not nsr_lcm
.get("VCA"):
1264 nsr_lcm
["VCA"][application_name
] = db_nsr_update
["_admin.deployed.VCA.{}".format(application_name
)] = {
1265 "member-vnf-index": vnf_index
,
1267 "model": model_name
,
1268 "application": application_name
,
1269 "operational-status": "init",
1270 "detailed-status": "",
1273 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1275 self
.logger
.debug("Task create_ns={} Passing artifacts path '{}' for {}".format(nsr_id
, charm_path
,
1277 task
= asyncio
.ensure_future(
1278 self
.n2vc
.DeployCharms(
1279 model_name
, # The network service name
1280 application_name
, # The application name
1281 vnfd
, # The vnf descriptor
1282 charm_path
, # Path to charm
1283 params
, # Runtime params, like mgmt ip
1284 {}, # for native charms only
1285 self
.n2vc_callback
, # Callback for status changes
1286 db_nsr
, # Callback parameter
1288 None, # Callback parameter (task)
1291 task
.add_done_callback(functools
.partial(self
.n2vc_callback
, model_name
, application_name
, None, None,
1292 db_nsr
, db_nslcmop
))
1293 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "create_charm:" + application_name
, task
)
1295 step
= "Looking for needed vnfd to configure"
1296 self
.logger
.debug(logging_text
+ step
)
1298 for c_vnf
in nsd
["constituent-vnfd"]:
1299 vnfd_id
= c_vnf
["vnfd-id-ref"]
1300 vnf_index
= str(c_vnf
["member-vnf-index"])
1301 vnfd
= needed_vnfd
[vnfd_id
]
1303 # Check if this VNF has a charm configuration
1304 vnf_config
= vnfd
.get("vnf-configuration")
1306 if vnf_config
and vnf_config
.get("juju"):
1307 proxy_charm
= vnf_config
["juju"]["charm"]
1308 config_primitive
= None
1311 if 'initial-config-primitive' in vnf_config
:
1312 config_primitive
= vnf_config
['initial-config-primitive']
1314 # Login to the VCA. If there are multiple calls to login(),
1315 # subsequent calls will be a nop and return immediately.
1316 step
= "connecting to N2VC to configure vnf {}".format(vnf_index
)
1317 await self
.n2vc
.login()
1318 deploy(vnf_index
, None, db_vnfrs
[vnf_index
]["ip-address"], config_primitive
)
1319 number_to_configure
+= 1
1321 # Deploy charms for each VDU that supports one.
1323 for vdu
in vnfd
['vdu']:
1324 vdu_config
= vdu
.get('vdu-configuration')
1326 config_primitive
= None
1328 if vdu_config
and vdu_config
.get("juju"):
1329 proxy_charm
= vdu_config
["juju"]["charm"]
1331 if 'initial-config-primitive' in vdu_config
:
1332 config_primitive
= vdu_config
['initial-config-primitive']
1335 step
= "connecting to N2VC to configure vdu {} from vnf {}".format(vdu
["id"], vnf_index
)
1336 await self
.n2vc
.login()
1337 deploy(vnf_index
, vdu
["id"], db_vnfrs
[vnf_index
]["vdur"][vdu_index
]["ip-address"],
1339 number_to_configure
+= 1
1342 if number_to_configure
:
1343 db_nsr_update
["config-status"] = "configuring"
1344 db_nsr_update
["operational-status"] = "running"
1345 db_nsr_update
["detailed-status"] = "configuring: init: {}".format(number_to_configure
)
1346 db_nslcmop_update
["detailed-status"] = "configuring: init: {}".format(number_to_configure
)
1348 db_nslcmop_update
["operationState"] = "COMPLETED"
1349 db_nslcmop_update
["statusEnteredTime"] = time()
1350 db_nslcmop_update
["detailed-status"] = "done"
1351 db_nsr_update
["config-status"] = "configured"
1352 db_nsr_update
["detailed-status"] = "done"
1353 db_nsr_update
["operational-status"] = "running"
1354 step
= "Sending monitoring parameters to PM"
1355 # for c_vnf in nsd["constituent-vnfd"]:
1356 # await self.create_monitoring(nsr_id, c_vnf["member-vnf-index"], needed_vnfd[c_vnf["vnfd-id-ref"]])
1358 await self
.msg
.aiowrite("ns", "instantiated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
})
1359 except Exception as e
:
1360 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1362 self
.logger
.debug(logging_text
+ "Exit")
1365 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
1366 self
.logger
.error(logging_text
+ "Exit Exception while '{}': {}".format(step
, e
))
1368 except asyncio
.CancelledError
:
1369 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1370 exc
= "Operation was cancelled"
1371 except Exception as e
:
1372 exc
= traceback
.format_exc()
1373 self
.logger
.critical(logging_text
+ "Exit Exception {} while '{}': {}".format(type(e
).__name
__, step
, e
),
1378 db_nsr_update
["detailed-status"] = "ERROR {}: {}".format(step
, exc
)
1379 db_nsr_update
["operational-status"] = "failed"
1381 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
1382 db_nslcmop_update
["operationState"] = "FAILED"
1383 db_nslcmop_update
["statusEnteredTime"] = time()
1385 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1386 if db_nslcmop_update
:
1387 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1388 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_instantiate")
1390 async def ns_terminate(self
, nsr_id
, nslcmop_id
):
1391 logging_text
= "Task ns={} terminate={} ".format(nsr_id
, nslcmop_id
)
1392 self
.logger
.debug(logging_text
+ "Enter")
1396 failed_detail
= [] # annotates all failed error messages
1400 db_nslcmop_update
= {}
1402 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
1403 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1404 step
= "Getting nsr={} from db".format(nsr_id
)
1405 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1406 # nsd = db_nsr["nsd"]
1407 nsr_lcm
= deepcopy(db_nsr
["_admin"].get("deployed"))
1408 if db_nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
1411 # db_vim = self.db.get_one("vim_accounts", {"_id": db_nsr["datacenter"]})
1412 # #TODO check if VIM is creating and wait
1413 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
1415 db_nsr_update
["operational-status"] = "terminating"
1416 db_nsr_update
["config-status"] = "terminating"
1418 if nsr_lcm
and nsr_lcm
.get("VCA"):
1420 step
= "Scheduling configuration charms removing"
1421 db_nsr_update
["detailed-status"] = "Deleting charms"
1422 self
.logger
.debug(logging_text
+ step
)
1423 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1424 for application_name
, deploy_info
in nsr_lcm
["VCA"].items():
1425 if deploy_info
: # TODO it would be desirable having a and deploy_info.get("deployed"):
1426 task
= asyncio
.ensure_future(
1427 self
.n2vc
.RemoveCharms(
1428 deploy_info
['model'],
1430 # self.n2vc_callback,
1435 vca_task_list
.append(task
)
1436 vca_task_dict
[application_name
] = task
1437 # task.add_done_callback(functools.partial(self.n2vc_callback, deploy_info['model'],
1438 # deploy_info['application'], None, db_nsr,
1439 # db_nslcmop, vnf_index))
1440 self
.lcm_ns_tasks
[nsr_id
][nslcmop_id
]["delete_charm:" + application_name
] = task
1441 except Exception as e
:
1442 self
.logger
.debug(logging_text
+ "Failed while deleting charms: {}".format(e
))
1446 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
1449 RO_nsr_id
= RO_delete_action
= None
1450 if nsr_lcm
and nsr_lcm
.get("RO"):
1451 RO_nsr_id
= nsr_lcm
["RO"].get("nsr_id")
1452 RO_delete_action
= nsr_lcm
["RO"].get("nsr_delete_action_id")
1455 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] = "Deleting ns at RO"
1456 self
.logger
.debug(logging_text
+ step
)
1457 desc
= await RO
.delete("ns", RO_nsr_id
)
1458 RO_delete_action
= desc
["action_id"]
1459 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = RO_delete_action
1460 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1461 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
1462 if RO_delete_action
:
1463 # wait until NS is deleted from VIM
1464 step
= detailed_status
= "Waiting ns deleted from VIM. RO_id={}".format(RO_nsr_id
)
1465 detailed_status_old
= None
1466 self
.logger
.debug(logging_text
+ step
)
1468 delete_timeout
= 20 * 60 # 20 minutes
1469 while delete_timeout
> 0:
1470 desc
= await RO
.show("ns", item_id_name
=RO_nsr_id
, extra_item
="action",
1471 extra_item_id
=RO_delete_action
)
1472 ns_status
, ns_status_info
= RO
.check_action_status(desc
)
1473 if ns_status
== "ERROR":
1474 raise ROclient
.ROClientException(ns_status_info
)
1475 elif ns_status
== "BUILD":
1476 detailed_status
= step
+ "; {}".format(ns_status_info
)
1477 elif ns_status
== "ACTIVE":
1480 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
1481 await asyncio
.sleep(5, loop
=self
.loop
)
1483 if detailed_status
!= detailed_status_old
:
1484 detailed_status_old
= db_nslcmop_update
["detailed-status"] = detailed_status
1485 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1486 else: # delete_timeout <= 0:
1487 raise ROclient
.ROClientException("Timeout waiting ns deleted from VIM")
1489 except ROclient
.ROClientException
as e
:
1490 if e
.http_code
== 404: # not found
1491 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1492 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
1493 self
.logger
.debug(logging_text
+ "RO_ns_id={} already deleted".format(RO_nsr_id
))
1494 elif e
.http_code
== 409: # conflict
1495 failed_detail
.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id
, e
))
1496 self
.logger
.debug(logging_text
+ failed_detail
[-1])
1499 failed_detail
.append("RO_ns_id={} delete error: {}".format(RO_nsr_id
, e
))
1500 self
.logger
.error(logging_text
+ failed_detail
[-1])
1504 if not RO_fail
and nsr_lcm
and nsr_lcm
.get("RO") and nsr_lcm
["RO"].get("nsd_id"):
1505 RO_nsd_id
= nsr_lcm
["RO"]["nsd_id"]
1507 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
1508 "Deleting nsd at RO"
1509 await RO
.delete("nsd", RO_nsd_id
)
1510 self
.logger
.debug(logging_text
+ "RO_nsd_id={} deleted".format(RO_nsd_id
))
1511 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
1512 except ROclient
.ROClientException
as e
:
1513 if e
.http_code
== 404: # not found
1514 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
1515 self
.logger
.debug(logging_text
+ "RO_nsd_id={} already deleted".format(RO_nsd_id
))
1516 elif e
.http_code
== 409: # conflict
1517 failed_detail
.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id
, e
))
1518 self
.logger
.debug(logging_text
+ failed_detail
[-1])
1521 failed_detail
.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id
, e
))
1522 self
.logger
.error(logging_text
+ failed_detail
[-1])
1525 if not RO_fail
and nsr_lcm
and nsr_lcm
.get("RO") and nsr_lcm
["RO"].get("vnfd_id"):
1526 for vnf_id
, RO_vnfd_id
in nsr_lcm
["RO"]["vnfd_id"].items():
1530 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
1531 "Deleting vnfd={} at RO".format(vnf_id
)
1532 await RO
.delete("vnfd", RO_vnfd_id
)
1533 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} deleted".format(RO_vnfd_id
))
1534 db_nsr_update
["_admin.deployed.RO.vnfd_id.{}".format(vnf_id
)] = None
1535 except ROclient
.ROClientException
as e
:
1536 if e
.http_code
== 404: # not found
1537 db_nsr_update
["_admin.deployed.RO.vnfd_id.{}".format(vnf_id
)] = None
1538 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} already deleted ".format(RO_vnfd_id
))
1539 elif e
.http_code
== 409: # conflict
1540 failed_detail
.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id
, e
))
1541 self
.logger
.debug(logging_text
+ failed_detail
[-1])
1543 failed_detail
.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id
, e
))
1544 self
.logger
.error(logging_text
+ failed_detail
[-1])
1547 db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
1548 "Waiting for deletion of configuration charms"
1549 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1550 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1551 await asyncio
.wait(vca_task_list
, timeout
=300)
1552 for application_name
, task
in vca_task_dict
.items():
1553 if task
.cancelled():
1554 failed_detail
.append("VCA[{}] Deletion has been cancelled".format(application_name
))
1556 exc
= task
.exception()
1558 failed_detail
.append("VCA[{}] Deletion exception: {}".format(application_name
, exc
))
1560 db_nsr_update
["_admin.deployed.VCA.{}".format(application_name
)] = None
1562 # TODO Should it be cancelled?!!
1564 failed_detail
.append("VCA[{}] Deletion timeout".format(application_name
))
1567 self
.logger
.error(logging_text
+ " ;".join(failed_detail
))
1568 db_nsr_update
["operational-status"] = "failed"
1569 db_nsr_update
["detailed-status"] = "Deletion errors " + "; ".join(failed_detail
)
1570 db_nslcmop_update
["detailed-status"] = "; ".join(failed_detail
)
1571 db_nslcmop_update
["operationState"] = "FAILED"
1572 db_nslcmop_update
["statusEnteredTime"] = time()
1573 elif db_nslcmop
["operationParams"].get("autoremove"):
1574 self
.db
.del_one("nsrs", {"_id": nsr_id
})
1575 db_nsr_update
.clear()
1576 self
.db
.del_list("nslcmops", {"nsInstanceId": nsr_id
})
1577 db_nslcmop_update
.clear()
1578 self
.db
.del_list("vnfrs", {"nsr-id-ref": nsr_id
})
1579 self
.logger
.debug(logging_text
+ "Delete from database")
1581 db_nsr_update
["operational-status"] = "terminated"
1582 db_nsr_update
["detailed-status"] = "Done"
1583 db_nsr_update
["_admin.nsState"] = "NOT_INSTANTIATED"
1584 db_nslcmop_update
["detailed-status"] = "Done"
1585 db_nslcmop_update
["operationState"] = "COMPLETED"
1586 db_nslcmop_update
["statusEnteredTime"] = time()
1588 await self
.msg
.aiowrite("ns", "terminated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
})
1589 except Exception as e
:
1590 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1591 self
.logger
.debug(logging_text
+ "Exit")
1593 except (ROclient
.ROClientException
, DbException
) as e
:
1594 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
1596 except asyncio
.CancelledError
:
1597 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1598 exc
= "Operation was cancelled"
1599 except Exception as e
:
1600 exc
= traceback
.format_exc()
1601 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
1603 if exc
and db_nslcmop
:
1604 db_nslcmop_update
= {
1605 "detailed-status": "FAILED {}: {}".format(step
, exc
),
1606 "operationState": "FAILED",
1607 "statusEnteredTime": time(),
1609 if db_nslcmop_update
:
1610 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1612 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1613 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_terminate")
1615 async def _ns_execute_primitive(self
, db_deployed
, nsr_name
, member_vnf_index
, vdu_id
, primitive
, primitive_params
):
1617 vdu_id_text
= "vnfd"
1619 vdu_id_text
= vdu_id
1620 application_name
= self
.n2vc
.FormatApplicationName(
1625 vca_deployed
= db_deployed
["VCA"].get(application_name
)
1626 if not vca_deployed
:
1627 raise LcmException("charm for member_vnf_index={} vdu_id={} is not deployed".format(member_vnf_index
,
1629 model_name
= vca_deployed
.get("model")
1630 application_name
= vca_deployed
.get("application")
1631 if not model_name
or not application_name
:
1632 raise LcmException("charm for member_vnf_index={} is not properly deployed".format(member_vnf_index
))
1633 if vca_deployed
["operational-status"] != "active":
1634 raise LcmException("charm for member_vnf_index={} operational_status={} not 'active'".format(
1635 member_vnf_index
, vca_deployed
["operational-status"]))
1636 callback
= None # self.n2vc_callback
1637 callback_args
= () # [db_nsr, db_nslcmop, member_vnf_index, None]
1638 await self
.n2vc
.login()
1639 task
= asyncio
.ensure_future(
1640 self
.n2vc
.ExecutePrimitive(
1643 primitive
, callback
,
1648 # task.add_done_callback(functools.partial(self.n2vc_callback, model_name, application_name, None,
1649 # db_nsr, db_nslcmop, member_vnf_index))
1650 # self.lcm_ns_tasks[nsr_id][nslcmop_id]["action: " + primitive] = task
1651 # wait until completed with timeout
1652 await asyncio
.wait((task
,), timeout
=600)
1654 result
= "FAILED" # by default
1656 if task
.cancelled():
1657 result_detail
= "Task has been cancelled"
1659 exc
= task
.exception()
1661 result_detail
= str(exc
)
1663 # TODO revise with Adam if action is finished and ok when task is done or callback is needed
1664 result
= "COMPLETED"
1665 result_detail
= "Done"
1667 # TODO Should it be cancelled?!!
1669 result_detail
= "timeout"
1670 return result
, result_detail
1672 async def ns_action(self
, nsr_id
, nslcmop_id
):
1673 logging_text
= "Task ns={} action={} ".format(nsr_id
, nslcmop_id
)
1674 self
.logger
.debug(logging_text
+ "Enter")
1675 # get all needed from database
1678 db_nslcmop_update
= None
1681 step
= "Getting information from database"
1682 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1683 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1684 nsr_lcm
= db_nsr
["_admin"].get("deployed")
1685 nsr_name
= db_nsr
["name"]
1686 vnf_index
= db_nslcmop
["operationParams"]["member_vnf_index"]
1687 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
1689 # TODO check if ns is in a proper status
1690 primitive
= db_nslcmop
["operationParams"]["primitive"]
1691 primitive_params
= db_nslcmop
["operationParams"]["primitive_params"]
1692 result
, result_detail
= await self
._ns
_execute
_primitive
(nsr_lcm
, nsr_name
, vnf_index
, vdu_id
, primitive
,
1694 db_nslcmop_update
= {
1695 "detailed-status": result_detail
,
1696 "operationState": result
,
1697 "statusEnteredTime": time()
1699 self
.logger
.debug(logging_text
+ " task Done with result {} {}".format(result
, result_detail
))
1700 return # database update is called inside finally
1702 except (DbException
, LcmException
) as e
:
1703 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
1705 except asyncio
.CancelledError
:
1706 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1707 exc
= "Operation was cancelled"
1708 except Exception as e
:
1709 exc
= traceback
.format_exc()
1710 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
1712 if exc
and db_nslcmop
:
1713 db_nslcmop_update
= {
1714 "detailed-status": "FAILED {}: {}".format(step
, exc
),
1715 "operationState": "FAILED",
1716 "statusEnteredTime": time(),
1718 if db_nslcmop_update
:
1719 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1720 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_action")
1722 async def ns_scale(self
, nsr_id
, nslcmop_id
):
1723 logging_text
= "Task ns={} scale={} ".format(nsr_id
, nslcmop_id
)
1724 self
.logger
.debug(logging_text
+ "Enter")
1725 # get all needed from database
1728 db_nslcmop_update
= {}
1732 step
= "Getting nslcmop from database"
1733 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1734 step
= "Getting nsr from database"
1735 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1736 step
= "Parsing scaling parameters"
1737 db_nsr_update
["operational-status"] = "scaling"
1738 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1739 nsr_lcm
= db_nsr
["_admin"].get("deployed")
1740 RO_nsr_id
= nsr_lcm
["RO"]["nsr_id"]
1741 vnf_index
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
1742 scaling_group
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1743 scaling_type
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleVnfType"]
1744 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
1746 step
= "Getting vnfr from database"
1747 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
1748 step
= "Getting vnfd from database"
1749 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
1750 step
= "Getting scaling-group-descriptor"
1751 for scaling_descriptor
in db_vnfd
["scaling-group-descriptor"]:
1752 if scaling_descriptor
["name"] == scaling_group
:
1755 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
1756 "at vnfd:scaling-group-descriptor".format(scaling_group
))
1758 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
1759 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
1760 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
1763 # TODO check if ns is in a proper status
1764 step
= "Sending scale order to RO"
1766 if not db_nsr
["_admin"].get("scaling-group"):
1767 self
.update_db_2("nsrs", nsr_id
, {"_admin.scaling-group": [{"name": scaling_group
, "nb-scale-op": 0}]})
1768 admin_scale_index
= 0
1770 for admin_scale_index
, admin_scale_info
in enumerate(db_nsr
["_admin"]["scaling-group"]):
1771 if admin_scale_info
["name"] == scaling_group
:
1772 nb_scale_op
= admin_scale_info
.get("nb-scale-op", 0)
1774 RO_scaling_info
= []
1775 vdu_scaling_info
= {"scaling_group_name": scaling_group
, "vdu": []}
1776 if scaling_type
== "SCALE_OUT":
1777 # count if max-instance-count is reached
1778 if "max-instance-count" in scaling_descriptor
and scaling_descriptor
["max-instance-count"] is not None:
1779 max_instance_count
= int(scaling_descriptor
["max-instance-count"])
1780 if nb_scale_op
>= max_instance_count
:
1781 raise LcmException("reached the limit of {} (max-instance-count) scaling-out operations for the"
1782 " scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
1783 nb_scale_op
= nb_scale_op
+ 1
1784 vdu_scaling_info
["scaling_direction"] = "OUT"
1785 vdu_scaling_info
["vdu-create"] = {}
1786 for vdu_scale_info
in scaling_descriptor
["vdu"]:
1787 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
1788 "type": "create", "count": vdu_scale_info
.get("count", 1)})
1789 vdu_scaling_info
["vdu-create"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
1790 elif scaling_type
== "SCALE_IN":
1791 # count if min-instance-count is reached
1792 if "min-instance-count" in scaling_descriptor
and scaling_descriptor
["min-instance-count"] is not None:
1793 min_instance_count
= int(scaling_descriptor
["min-instance-count"])
1794 if nb_scale_op
<= min_instance_count
:
1795 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
1796 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
1797 nb_scale_op
= nb_scale_op
- 1
1798 vdu_scaling_info
["scaling_direction"] = "IN"
1799 vdu_scaling_info
["vdu-delete"] = {}
1800 for vdu_scale_info
in scaling_descriptor
["vdu"]:
1801 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
1802 "type": "delete", "count": vdu_scale_info
.get("count", 1)})
1803 vdu_scaling_info
["vdu-delete"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
1805 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
1806 if vdu_scaling_info
["scaling_direction"] == "IN":
1807 for vdur
in reversed(db_vnfr
["vdur"]):
1808 if vdu_scaling_info
["vdu-delete"].get(vdur
["vdu-id-ref"]):
1809 vdu_scaling_info
["vdu-delete"][vdur
["vdu-id-ref"]] -= 1
1810 vdu_scaling_info
["vdu"].append({
1811 "name": vdur
["name"],
1812 "vdu_id": vdur
["vdu-id-ref"],
1815 for interface
in vdur
["interfaces"]:
1816 vdu_scaling_info
["vdu"][-1]["interface"].append({
1817 "name": interface
["name"],
1818 "ip_address": interface
["ip-address"],
1819 "mac_address": interface
.get("mac-address"),
1821 del vdu_scaling_info
["vdu-delete"]
1823 # execute primitive service PRE-SCALING
1824 step
= "Executing pre-scale vnf-config-primitive"
1825 if scaling_descriptor
.get("scaling-config-action"):
1826 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
1827 if scaling_config_action
.get("trigger") and scaling_config_action
["trigger"] == "pre-scale-in" \
1828 and scaling_type
== "SCALE_IN":
1829 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
1830 step
= db_nslcmop_update
["detailed-status"] = \
1831 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive
)
1832 # look for primitive
1833 primitive_params
= {}
1834 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
1835 if config_primitive
["name"] == vnf_config_primitive
:
1836 for parameter
in config_primitive
.get("parameter", ()):
1837 if 'default-value' in parameter
and \
1838 parameter
['default-value'] == "<VDU_SCALE_INFO>":
1839 primitive_params
[parameter
["name"]] = yaml
.safe_dump(vdu_scaling_info
,
1840 default_flow_style
=True,
1845 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
1846 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-cnfiguration:config-"
1847 "primitive".format(scaling_group
, config_primitive
))
1848 result
, result_detail
= await self
._ns
_execute
_primitive
(nsr_lcm
, vnf_index
,
1849 vnf_config_primitive
, primitive_params
)
1850 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
1851 vnf_config_primitive
, result
, result_detail
))
1852 if result
== "FAILED":
1853 raise LcmException(result_detail
)
1856 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
1857 RO_desc
= await RO
.create_action("ns", RO_nsr_id
, {"vdu-scaling": RO_scaling_info
})
1858 db_nsr_update
["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index
)] = nb_scale_op
1859 db_nsr_update
["_admin.scaling-group.{}.time".format(admin_scale_index
)] = time()
1860 # TODO mark db_nsr_update as scaling
1862 RO_nslcmop_id
= RO_desc
["instance_action_id"]
1863 db_nslcmop_update
["_admin.deploy.RO"] = RO_nslcmop_id
1865 RO_task_done
= False
1866 step
= detailed_status
= "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id
)
1867 detailed_status_old
= None
1868 self
.logger
.debug(logging_text
+ step
)
1870 deployment_timeout
= 1 * 3600 # One hours
1871 while deployment_timeout
> 0:
1872 if not RO_task_done
:
1873 desc
= await RO
.show("ns", item_id_name
=RO_nsr_id
, extra_item
="action",
1874 extra_item_id
=RO_nslcmop_id
)
1875 ns_status
, ns_status_info
= RO
.check_action_status(desc
)
1876 if ns_status
== "ERROR":
1877 raise ROclient
.ROClientException(ns_status_info
)
1878 elif ns_status
== "BUILD":
1879 detailed_status
= step
+ "; {}".format(ns_status_info
)
1880 elif ns_status
== "ACTIVE":
1882 step
= detailed_status
= "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id
)
1883 self
.logger
.debug(logging_text
+ step
)
1885 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
1887 desc
= await RO
.show("ns", RO_nsr_id
)
1888 ns_status
, ns_status_info
= RO
.check_ns_status(desc
)
1889 if ns_status
== "ERROR":
1890 raise ROclient
.ROClientException(ns_status_info
)
1891 elif ns_status
== "BUILD":
1892 detailed_status
= step
+ "; {}".format(ns_status_info
)
1893 elif ns_status
== "ACTIVE":
1894 step
= detailed_status
= "Waiting for management IP address reported by the VIM"
1896 desc
= await RO
.show("ns", RO_nsr_id
)
1897 nsr_lcm
["nsr_ip"] = RO
.get_ns_vnf_info(desc
)
1899 except ROclient
.ROClientException
as e
:
1900 if e
.http_code
!= 409: # IP address is not ready return code is 409 CONFLICT
1903 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
1904 if detailed_status
!= detailed_status_old
:
1905 detailed_status_old
= db_nslcmop_update
["detailed-status"] = detailed_status
1906 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1908 await asyncio
.sleep(5, loop
=self
.loop
)
1909 deployment_timeout
-= 5
1910 if deployment_timeout
<= 0:
1911 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
1913 step
= "Updating VNFRs"
1914 self
.ns_update_vnfr({db_vnfr
["member-vnf-index-ref"]: db_vnfr
}, desc
)
1916 # update VDU_SCALING_INFO with the obtained ip_addresses
1917 if vdu_scaling_info
["scaling_direction"] == "OUT":
1918 for vdur
in reversed(db_vnfr
["vdur"]):
1919 if vdu_scaling_info
["vdu-create"].get(vdur
["vdu-id-ref"]):
1920 vdu_scaling_info
["vdu-create"][vdur
["vdu-id-ref"]] -= 1
1921 vdu_scaling_info
["vdu"].append({
1922 "name": vdur
["name"],
1923 "vdu_id": vdur
["vdu-id-ref"],
1926 for interface
in vdur
["interfaces"]:
1927 vdu_scaling_info
["vdu"][-1]["interface"].append({
1928 "name": interface
["name"],
1929 "ip_address": interface
["ip-address"],
1930 "mac_address": interface
.get("mac-address"),
1932 del vdu_scaling_info
["vdu-create"]
1935 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1937 # execute primitive service POST-SCALING
1938 step
= "Executing post-scale vnf-config-primitive"
1939 if scaling_descriptor
.get("scaling-config-action"):
1940 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
1941 if scaling_config_action
.get("trigger") and scaling_config_action
["trigger"] == "post-scale-out" \
1942 and scaling_type
== "SCALE_OUT":
1943 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
1944 step
= db_nslcmop_update
["detailed-status"] = \
1945 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive
)
1946 # look for primitive
1947 primitive_params
= {}
1948 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
1949 if config_primitive
["name"] == vnf_config_primitive
:
1950 for parameter
in config_primitive
.get("parameter", ()):
1951 if 'default-value' in parameter
and \
1952 parameter
['default-value'] == "<VDU_SCALE_INFO>":
1953 primitive_params
[parameter
["name"]] = yaml
.safe_dump(vdu_scaling_info
,
1954 default_flow_style
=True,
1958 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
1959 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
1960 "match any vnf-cnfiguration:config-primitive".format(scaling_group
,
1962 result
, result_detail
= await self
._ns
_execute
_primitive
(nsr_lcm
, vnf_index
,
1963 vnf_config_primitive
, primitive_params
)
1964 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
1965 vnf_config_primitive
, result
, result_detail
))
1966 if result
== "FAILED":
1967 raise LcmException(result_detail
)
1969 db_nslcmop_update
["operationState"] = "COMPLETED"
1970 db_nslcmop_update
["statusEnteredTime"] = time()
1971 db_nslcmop_update
["detailed-status"] = "done"
1972 db_nsr_update
["detailed-status"] = "done"
1973 db_nsr_update
["operational-status"] = "running"
1975 await self
.msg
.aiowrite("ns", "scaled", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
})
1977 # await asyncio.sleep(cooldown_time)
1978 # await self.msg.aiowrite("ns", "scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
1979 except Exception as e
:
1980 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1981 self
.logger
.debug(logging_text
+ "Exit Ok")
1983 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
1984 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
1986 except asyncio
.CancelledError
:
1987 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1988 exc
= "Operation was cancelled"
1989 except Exception as e
:
1990 exc
= traceback
.format_exc()
1991 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
1995 db_nslcmop_update
= {
1996 "detailed-status": "FAILED {}: {}".format(step
, exc
),
1997 "operationState": "FAILED",
1998 "statusEnteredTime": time(),
2001 db_nsr_update
["operational-status"] = "FAILED {}: {}".format(step
, exc
),
2002 db_nsr_update
["detailed-status"] = "failed"
2003 if db_nslcmop_update
:
2004 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2006 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2007 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_scale")
2009 async def test(self
, param
=None):
2010 self
.logger
.debug("Starting/Ending test task: {}".format(param
))
2012 async def kafka_ping(self
):
2013 self
.logger
.debug("Task kafka_ping Enter")
2014 consecutive_errors
= 0
2016 kafka_has_received
= False
2017 self
.pings_not_received
= 1
2020 await self
.msg
.aiowrite("admin", "ping", {"from": "lcm", "to": "lcm"}, self
.loop
)
2021 # time between pings are low when it is not received and at starting
2022 wait_time
= 5 if not kafka_has_received
else 120
2023 if not self
.pings_not_received
:
2024 kafka_has_received
= True
2025 self
.pings_not_received
+= 1
2026 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
2027 if self
.pings_not_received
> 10:
2028 raise LcmException("It is not receiving pings from Kafka bus")
2029 consecutive_errors
= 0
2031 except LcmException
:
2033 except Exception as e
:
2034 # if not first_start is the first time after starting. So leave more time and wait
2035 # to allow kafka starts
2036 if consecutive_errors
== 8 if not first_start
else 30:
2037 self
.logger
.error("Task kafka_read task exit error too many errors. Exception: {}".format(e
))
2039 consecutive_errors
+= 1
2040 self
.logger
.error("Task kafka_read retrying after Exception {}".format(e
))
2041 wait_time
= 1 if not first_start
else 5
2042 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
2044 async def kafka_read(self
):
2045 self
.logger
.debug("Task kafka_read Enter")
2047 # future = asyncio.Future()
2048 consecutive_errors
= 0
2050 while consecutive_errors
< 10:
2052 topics
= ("admin", "ns", "vim_account", "sdn")
2053 topic
, command
, params
= await self
.msg
.aioread(topics
, self
.loop
)
2054 if topic
!= "admin" and command
!= "ping":
2055 self
.logger
.debug("Task kafka_read receives {} {}: {}".format(topic
, command
, params
))
2056 consecutive_errors
= 0
2059 if command
== "exit":
2062 elif command
.startswith("#"):
2064 elif command
== "echo":
2069 elif command
== "test":
2070 asyncio
.Task(self
.test(params
), loop
=self
.loop
)
2073 if topic
== "admin":
2074 if command
== "ping" and params
["to"] == "lcm" and params
["from"] == "lcm":
2075 self
.pings_not_received
= 0
2078 if command
== "instantiate":
2079 # self.logger.debug("Deploying NS {}".format(nsr_id))
2081 nslcmop_id
= nslcmop
["_id"]
2082 nsr_id
= nslcmop
["nsInstanceId"]
2083 task
= asyncio
.ensure_future(self
.ns_instantiate(nsr_id
, nslcmop_id
))
2084 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_instantiate", task
)
2086 elif command
== "terminate":
2087 # self.logger.debug("Deleting NS {}".format(nsr_id))
2089 nslcmop_id
= nslcmop
["_id"]
2090 nsr_id
= nslcmop
["nsInstanceId"]
2091 self
.lcm_tasks
.cancel(topic
, nsr_id
)
2092 task
= asyncio
.ensure_future(self
.ns_terminate(nsr_id
, nslcmop_id
))
2093 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_terminate", task
)
2095 elif command
== "action":
2096 # self.logger.debug("Update NS {}".format(nsr_id))
2098 nslcmop_id
= nslcmop
["_id"]
2099 nsr_id
= nslcmop
["nsInstanceId"]
2100 task
= asyncio
.ensure_future(self
.ns_action(nsr_id
, nslcmop_id
))
2101 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_action", task
)
2103 elif command
== "scale":
2104 # self.logger.debug("Update NS {}".format(nsr_id))
2106 nslcmop_id
= nslcmop
["_id"]
2107 nsr_id
= nslcmop
["nsInstanceId"]
2108 task
= asyncio
.ensure_future(self
.ns_scale(nsr_id
, nslcmop_id
))
2109 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "ns_scale", task
)
2111 elif command
== "show":
2113 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2114 print("nsr:\n _id={}\n operational-status: {}\n config-status: {}"
2115 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
2116 "".format(nsr_id
, db_nsr
["operational-status"], db_nsr
["config-status"],
2117 db_nsr
["detailed-status"],
2118 db_nsr
["_admin"]["deployed"], self
.lcm_ns_tasks
.get(nsr_id
)))
2119 except Exception as e
:
2120 print("nsr {} not found: {}".format(nsr_id
, e
))
2123 elif command
== "deleted":
2124 continue # TODO cleaning of task just in case should be done
2125 elif command
in ("terminated", "instantiated", "scaled", "actioned"): # "scaled-cooldown-time"
2127 elif topic
== "vim_account":
2128 vim_id
= params
["_id"]
2129 if command
== "create":
2130 task
= asyncio
.ensure_future(self
.vim_create(params
, order_id
))
2131 self
.lcm_tasks
.register("vim_account", vim_id
, order_id
, "vim_create", task
)
2133 elif command
== "delete":
2134 self
.lcm_tasks
.cancel(topic
, vim_id
)
2135 task
= asyncio
.ensure_future(self
.vim_delete(vim_id
, order_id
))
2136 self
.lcm_tasks
.register("vim_account", vim_id
, order_id
, "vim_delete", task
)
2138 elif command
== "show":
2139 print("not implemented show with vim_account")
2142 elif command
== "edit":
2143 task
= asyncio
.ensure_future(self
.vim_edit(params
, order_id
))
2144 self
.lcm_tasks
.register("vim_account", vim_id
, order_id
, "vim_edit", task
)
2146 elif topic
== "sdn":
2147 _sdn_id
= params
["_id"]
2148 if command
== "create":
2149 task
= asyncio
.ensure_future(self
.sdn_create(params
, order_id
))
2150 self
.lcm_tasks
.register("sdn", _sdn_id
, order_id
, "sdn_create", task
)
2152 elif command
== "delete":
2153 self
.lcm_tasks
.cancel(topic
, _sdn_id
)
2154 task
= asyncio
.ensure_future(self
.sdn_delete(_sdn_id
, order_id
))
2155 self
.lcm_tasks
.register("sdn", _sdn_id
, order_id
, "sdn_delete", task
)
2157 elif command
== "edit":
2158 task
= asyncio
.ensure_future(self
.sdn_edit(params
, order_id
))
2159 self
.lcm_tasks
.register("sdn", _sdn_id
, order_id
, "sdn_edit", task
)
2161 self
.logger
.critical("unknown topic {} and command '{}'".format(topic
, command
))
2162 except Exception as e
:
2163 # if not first_start is the first time after starting. So leave more time and wait
2164 # to allow kafka starts
2165 if consecutive_errors
== 8 if not first_start
else 30:
2166 self
.logger
.error("Task kafka_read task exit error too many errors. Exception: {}".format(e
))
2168 consecutive_errors
+= 1
2169 self
.logger
.error("Task kafka_read retrying after Exception {}".format(e
))
2170 wait_time
= 2 if not first_start
else 5
2171 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
2173 # self.logger.debug("Task kafka_read terminating")
2174 self
.logger
.debug("Task kafka_read exit")
2177 self
.loop
= asyncio
.get_event_loop()
2180 self
.loop
.run_until_complete(self
.check_RO_version())
2182 self
.loop
.run_until_complete(asyncio
.gather(
2187 # self.logger.debug("Terminating cancelling creation tasks")
2188 # self.lcm_tasks.cancel("ALL", "create")
2190 # while self.is_pending_tasks():
2191 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
2192 # await asyncio.sleep(2, loop=self.loop)
2195 # self.lcm_tasks.cancel("ALL", "ALL")
2199 self
.db
.db_disconnect()
2201 self
.msg
.disconnect()
2203 self
.fs
.fs_disconnect()
2205 def read_config_file(self
, config_file
):
2206 # TODO make a [ini] + yaml inside parser
2207 # the configparser library is not suitable, because it does not admit comments at the end of line,
2208 # and not parse integer or boolean
2210 with
open(config_file
) as f
:
2212 for k
, v
in environ
.items():
2213 if not k
.startswith("OSMLCM_"):
2215 k_items
= k
.lower().split("_")
2218 for k_item
in k_items
[1:-1]:
2219 if k_item
in ("ro", "vca"):
2220 # put in capital letter
2221 k_item
= k_item
.upper()
2223 if k_items
[-1] == "port":
2224 c
[k_items
[-1]] = int(v
)
2227 except Exception as e
:
2228 self
.logger
.warn("skipping environ '{}' on exception '{}'".format(k
, e
))
2231 except Exception as e
:
2232 self
.logger
.critical("At config file '{}': {}".format(config_file
, e
))
2237 print("""Usage: {} [options]
2238 -c|--config [configuration_file]: loads the configuration file (default: ./nbi.cfg)
2239 -h|--help: shows this help
2240 """.format(sys
.argv
[0]))
2241 # --log-socket-host HOST: send logs to this host")
2242 # --log-socket-port PORT: send logs using this port (default: 9022)")
2245 if __name__
== '__main__':
2247 # load parameters and configuration
2248 opts
, args
= getopt
.getopt(sys
.argv
[1:], "hc:", ["config=", "help"])
2249 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
2252 if o
in ("-h", "--help"):
2255 elif o
in ("-c", "--config"):
2257 # elif o == "--log-socket-port":
2258 # log_socket_port = a
2259 # elif o == "--log-socket-host":
2260 # log_socket_host = a
2261 # elif o == "--log-file":
2264 assert False, "Unhandled option"
2266 if not path
.isfile(config_file
):
2267 print("configuration file '{}' that not exist".format(config_file
), file=sys
.stderr
)
2270 for config_file
in (__file__
[:__file__
.rfind(".")] + ".cfg", "./lcm.cfg", "/etc/osm/lcm.cfg"):
2271 if path
.isfile(config_file
):
2274 print("No configuration file 'nbi.cfg' found neither at local folder nor at /etc/osm/", file=sys
.stderr
)
2276 lcm
= Lcm(config_file
)
2278 except (LcmException
, getopt
.GetoptError
) as e
:
2279 print(str(e
), file=sys
.stderr
)