2 # -*- coding: utf-8 -*-
8 import logging
.handlers
12 from osm_common
import dbmemory
13 from osm_common
import dbmongo
14 from osm_common
import fslocal
15 from osm_common
import msglocal
16 from osm_common
import msgkafka
17 from osm_common
.dbbase
import DbException
18 from osm_common
.fsbase
import FsException
19 from osm_common
.msgbase
import MsgException
20 from os
import environ
, path
21 from n2vc
.vnf
import N2VC
22 from n2vc
import version
as N2VC_version
24 from copy
import deepcopy
25 from http
import HTTPStatus
29 __author__
= "Alfonso Tierno"
32 class LcmException(Exception):
38 def __init__(self
, config_file
):
40 Init, Connect to database, filesystem storage, and messaging
41 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
48 self
.pings_not_received
= 1
50 # contains created tasks/futures to be able to cancel
51 self
.lcm_ns_tasks
= {}
52 self
.lcm_vim_tasks
= {}
53 self
.lcm_sdn_tasks
= {}
55 self
.logger
= logging
.getLogger('lcm')
57 config
= self
.read_config_file(config_file
)
60 "endpoint_url": "http://{}:{}/openmano".format(config
["RO"]["host"], config
["RO"]["port"]),
61 "tenant": config
.get("tenant", "osm"),
62 "logger_name": "lcm.ROclient",
66 self
.vca
= config
["VCA"] # TODO VCA
70 log_format_simple
= "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
71 log_formatter_simple
= logging
.Formatter(log_format_simple
, datefmt
='%Y-%m-%dT%H:%M:%S')
72 config
["database"]["logger_name"] = "lcm.db"
73 config
["storage"]["logger_name"] = "lcm.fs"
74 config
["message"]["logger_name"] = "lcm.msg"
75 if "logfile" in config
["global"]:
76 file_handler
= logging
.handlers
.RotatingFileHandler(config
["global"]["logfile"],
77 maxBytes
=100e6
, backupCount
=9, delay
=0)
78 file_handler
.setFormatter(log_formatter_simple
)
79 self
.logger
.addHandler(file_handler
)
81 str_handler
= logging
.StreamHandler()
82 str_handler
.setFormatter(log_formatter_simple
)
83 self
.logger
.addHandler(str_handler
)
85 if config
["global"].get("loglevel"):
86 self
.logger
.setLevel(config
["global"]["loglevel"])
88 # logging other modules
89 for k1
, logname
in {"message": "lcm.msg", "database": "lcm.db", "storage": "lcm.fs"}.items():
90 config
[k1
]["logger_name"] = logname
91 logger_module
= logging
.getLogger(logname
)
92 if "logfile" in config
[k1
]:
93 file_handler
= logging
.handlers
.RotatingFileHandler(config
[k1
]["logfile"],
94 maxBytes
=100e6
, backupCount
=9, delay
=0)
95 file_handler
.setFormatter(log_formatter_simple
)
96 logger_module
.addHandler(file_handler
)
97 if "loglevel" in config
[k1
]:
98 logger_module
.setLevel(config
[k1
]["loglevel"])
102 server
=config
['VCA']['host'],
103 port
=config
['VCA']['port'],
104 user
=config
['VCA']['user'],
105 secret
=config
['VCA']['secret'],
106 # TODO: This should point to the base folder where charms are stored,
107 # if there is a common one (like object storage). Otherwise, leave
108 # it unset and pass it via DeployCharms
109 # artifacts=config['VCA'][''],
112 # check version of N2VC
113 # TODO enhance with int conversion or from distutils.version import LooseVersion
114 # or with list(map(int, version.split(".")))
115 if N2VC_version
< "0.0.2":
116 raise LcmException("Not compatible osm/N2VC version '{}'. Needed '0.0.2' or higher".format(N2VC_version
))
118 if config
["database"]["driver"] == "mongo":
119 self
.db
= dbmongo
.DbMongo()
120 self
.db
.db_connect(config
["database"])
121 elif config
["database"]["driver"] == "memory":
122 self
.db
= dbmemory
.DbMemory()
123 self
.db
.db_connect(config
["database"])
125 raise LcmException("Invalid configuration param '{}' at '[database]':'driver'".format(
126 config
["database"]["driver"]))
128 if config
["storage"]["driver"] == "local":
129 self
.fs
= fslocal
.FsLocal()
130 self
.fs
.fs_connect(config
["storage"])
132 raise LcmException("Invalid configuration param '{}' at '[storage]':'driver'".format(
133 config
["storage"]["driver"]))
135 if config
["message"]["driver"] == "local":
136 self
.msg
= msglocal
.MsgLocal()
137 self
.msg
.connect(config
["message"])
138 elif config
["message"]["driver"] == "kafka":
139 self
.msg
= msgkafka
.MsgKafka()
140 self
.msg
.connect(config
["message"])
142 raise LcmException("Invalid configuration param '{}' at '[message]':'driver'".format(
143 config
["storage"]["driver"]))
144 except (DbException
, FsException
, MsgException
) as e
:
145 self
.logger
.critical(str(e
), exc_info
=True)
146 raise LcmException(str(e
))
148 def update_db(self
, item
, _id
, _desc
):
150 self
.db
.replace(item
, _id
, _desc
)
151 except DbException
as e
:
152 self
.logger
.error("Updating {} _id={}: {}".format(item
, _id
, e
))
154 def update_db_2(self
, item
, _id
, _desc
):
156 self
.db
.set_one(item
, {"_id": _id
}, _desc
)
157 except DbException
as e
:
158 self
.logger
.error("Updating {} _id={}: {}".format(item
, _id
, e
))
160 async def vim_create(self
, vim_content
, order_id
):
161 vim_id
= vim_content
["_id"]
162 logging_text
= "Task vim_create={} ".format(vim_id
)
163 self
.logger
.debug(logging_text
+ "Enter")
168 step
= "Getting vim-id='{}' from db".format(vim_id
)
169 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_id
})
170 if "_admin" not in db_vim
:
171 db_vim
["_admin"] = {}
172 if "deployed" not in db_vim
["_admin"]:
173 db_vim
["_admin"]["deployed"] = {}
174 db_vim
["_admin"]["deployed"]["RO"] = None
175 if vim_content
.get("config") and vim_content
["config"].get("sdn-controller"):
176 step
= "Getting sdn-controller-id='{}' from db".format(vim_content
["config"]["sdn-controller"])
177 db_sdn
= self
.db
.get_one("sdns", {"_id": vim_content
["config"]["sdn-controller"]})
178 if db_sdn
.get("_admin") and db_sdn
["_admin"].get("deployed") and db_sdn
["_admin"]["deployed"].get("RO"):
179 RO_sdn_id
= db_sdn
["_admin"]["deployed"]["RO"]
181 raise LcmException("sdn-controller={} is not available. Not deployed at RO".format(
182 vim_content
["config"]["sdn-controller"]))
184 step
= "Creating vim at RO"
185 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
186 vim_RO
= deepcopy(vim_content
)
187 vim_RO
.pop("_id", None)
188 vim_RO
.pop("_admin", None)
189 vim_RO
.pop("schema_version", None)
190 vim_RO
.pop("schema_type", None)
191 vim_RO
.pop("vim_tenant_name", None)
192 vim_RO
["type"] = vim_RO
.pop("vim_type")
193 vim_RO
.pop("vim_user", None)
194 vim_RO
.pop("vim_password", None)
196 vim_RO
["config"]["sdn-controller"] = RO_sdn_id
197 desc
= await RO
.create("vim", descriptor
=vim_RO
)
198 RO_vim_id
= desc
["uuid"]
199 db_vim
["_admin"]["deployed"]["RO"] = RO_vim_id
200 self
.update_db("vim_accounts", vim_id
, db_vim
)
202 step
= "Creating vim_account at RO"
203 vim_account_RO
= {"vim_tenant_name": vim_content
["vim_tenant_name"],
204 "vim_username": vim_content
["vim_user"],
205 "vim_password": vim_content
["vim_password"]
207 if vim_RO
.get("config"):
208 vim_account_RO
["config"] = vim_RO
["config"]
209 if "sdn-controller" in vim_account_RO
["config"]:
210 del vim_account_RO
["config"]["sdn-controller"]
211 if "sdn-port-mapping" in vim_account_RO
["config"]:
212 del vim_account_RO
["config"]["sdn-port-mapping"]
213 await RO
.attach_datacenter(RO_vim_id
, descriptor
=vim_account_RO
)
214 db_vim
["_admin"]["operationalState"] = "ENABLED"
215 self
.update_db("vim_accounts", vim_id
, db_vim
)
217 self
.logger
.debug(logging_text
+ "Exit Ok RO_vim_id".format(RO_vim_id
))
220 except (ROclient
.ROClientException
, DbException
) as e
:
221 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
223 except Exception as e
:
224 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
228 db_vim
["_admin"]["operationalState"] = "ERROR"
229 db_vim
["_admin"]["detailed-status"] = "ERROR {}: {}".format(step
, exc
)
230 self
.update_db("vim_accounts", vim_id
, db_vim
)
232 async def vim_edit(self
, vim_content
, order_id
):
233 vim_id
= vim_content
["_id"]
234 logging_text
= "Task vim_edit={} ".format(vim_id
)
235 self
.logger
.debug(logging_text
+ "Enter")
239 step
= "Getting vim-id='{}' from db".format(vim_id
)
241 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_id
})
242 if db_vim
.get("_admin") and db_vim
["_admin"].get("deployed") and db_vim
["_admin"]["deployed"].get("RO"):
243 if vim_content
.get("config") and vim_content
["config"].get("sdn-controller"):
244 step
= "Getting sdn-controller-id='{}' from db".format(vim_content
["config"]["sdn-controller"])
245 db_sdn
= self
.db
.get_one("sdns", {"_id": vim_content
["config"]["sdn-controller"]})
246 if db_sdn
.get("_admin") and db_sdn
["_admin"].get("deployed") and db_sdn
["_admin"]["deployed"].get(
248 RO_sdn_id
= db_sdn
["_admin"]["deployed"]["RO"]
250 raise LcmException("sdn-controller={} is not available. Not deployed at RO".format(
251 vim_content
["config"]["sdn-controller"]))
253 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
254 step
= "Editing vim at RO"
255 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
256 vim_RO
= deepcopy(vim_content
)
257 vim_RO
.pop("_id", None)
258 vim_RO
.pop("_admin", None)
259 vim_RO
.pop("schema_version", None)
260 vim_RO
.pop("schema_type", None)
261 vim_RO
.pop("vim_tenant_name", None)
262 if "vim_type" in vim_RO
:
263 vim_RO
["type"] = vim_RO
.pop("vim_type")
264 vim_RO
.pop("vim_user", None)
265 vim_RO
.pop("vim_password", None)
267 vim_RO
["config"]["sdn-controller"] = RO_sdn_id
268 # TODO make a deep update of sdn-port-mapping
270 await RO
.edit("vim", RO_vim_id
, descriptor
=vim_RO
)
272 step
= "Editing vim-account at RO tenant"
274 if "config" in vim_content
:
275 if "sdn-controller" in vim_content
["config"]:
276 del vim_content
["config"]["sdn-controller"]
277 if "sdn-port-mapping" in vim_content
["config"]:
278 del vim_content
["config"]["sdn-port-mapping"]
279 if not vim_content
["config"]:
280 del vim_content
["config"]
281 for k
in ("vim_tenant_name", "vim_password", "config"):
283 vim_account_RO
[k
] = vim_content
[k
]
284 if "vim_user" in vim_content
:
285 vim_content
["vim_username"] = vim_content
["vim_user"]
287 await RO
.edit("vim_account", RO_vim_id
, descriptor
=vim_account_RO
)
288 db_vim
["_admin"]["operationalState"] = "ENABLED"
289 self
.update_db("vim_accounts", vim_id
, db_vim
)
291 self
.logger
.debug(logging_text
+ "Exit Ok RO_vim_id".format(RO_vim_id
))
294 except (ROclient
.ROClientException
, DbException
) as e
:
295 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
297 except Exception as e
:
298 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
302 db_vim
["_admin"]["operationalState"] = "ERROR"
303 db_vim
["_admin"]["detailed-status"] = "ERROR {}: {}".format(step
, exc
)
304 self
.update_db("vim_accounts", vim_id
, db_vim
)
306 async def vim_delete(self
, vim_id
, order_id
):
307 logging_text
= "Task vim_delete={} ".format(vim_id
)
308 self
.logger
.debug(logging_text
+ "Enter")
311 step
= "Getting vim from db"
313 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_id
})
314 if db_vim
.get("_admin") and db_vim
["_admin"].get("deployed") and db_vim
["_admin"]["deployed"].get("RO"):
315 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
316 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
317 step
= "Detaching vim from RO tenant"
319 await RO
.detach_datacenter(RO_vim_id
)
320 except ROclient
.ROClientException
as e
:
321 if e
.http_code
== 404: # not found
322 self
.logger
.debug(logging_text
+ "RO_vim_id={} already detached".format(RO_vim_id
))
326 step
= "Deleting vim from RO"
328 await RO
.delete("vim", RO_vim_id
)
329 except ROclient
.ROClientException
as e
:
330 if e
.http_code
== 404: # not found
331 self
.logger
.debug(logging_text
+ "RO_vim_id={} already deleted".format(RO_vim_id
))
336 self
.logger
.error(logging_text
+ "Skipping. There is not RO information at database")
337 self
.db
.del_one("vim_accounts", {"_id": vim_id
})
338 self
.logger
.debug("vim_delete task vim_id={} Exit Ok".format(vim_id
))
341 except (ROclient
.ROClientException
, DbException
) as e
:
342 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
344 except Exception as e
:
345 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
349 db_vim
["_admin"]["operationalState"] = "ERROR"
350 db_vim
["_admin"]["detailed-status"] = "ERROR {}: {}".format(step
, exc
)
351 self
.update_db("vim_accounts", vim_id
, db_vim
)
353 async def sdn_create(self
, sdn_content
, order_id
):
354 sdn_id
= sdn_content
["_id"]
355 logging_text
= "Task sdn_create={} ".format(sdn_id
)
356 self
.logger
.debug(logging_text
+ "Enter")
360 step
= "Getting sdn from db"
361 db_sdn
= self
.db
.get_one("sdns", {"_id": sdn_id
})
362 if "_admin" not in db_sdn
:
363 db_sdn
["_admin"] = {}
364 if "deployed" not in db_sdn
["_admin"]:
365 db_sdn
["_admin"]["deployed"] = {}
366 db_sdn
["_admin"]["deployed"]["RO"] = None
368 step
= "Creating sdn at RO"
369 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
370 sdn_RO
= deepcopy(sdn_content
)
371 sdn_RO
.pop("_id", None)
372 sdn_RO
.pop("_admin", None)
373 sdn_RO
.pop("schema_version", None)
374 sdn_RO
.pop("schema_type", None)
375 sdn_RO
.pop("description", None)
376 desc
= await RO
.create("sdn", descriptor
=sdn_RO
)
377 RO_sdn_id
= desc
["uuid"]
378 db_sdn
["_admin"]["deployed"]["RO"] = RO_sdn_id
379 db_sdn
["_admin"]["operationalState"] = "ENABLED"
380 self
.update_db("sdns", sdn_id
, db_sdn
)
381 self
.logger
.debug(logging_text
+ "Exit Ok RO_sdn_id".format(RO_sdn_id
))
384 except (ROclient
.ROClientException
, DbException
) as e
:
385 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
387 except Exception as e
:
388 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
392 db_sdn
["_admin"]["operationalState"] = "ERROR"
393 db_sdn
["_admin"]["detailed-status"] = "ERROR {}: {}".format(step
, exc
)
394 self
.update_db("sdns", sdn_id
, db_sdn
)
396 async def sdn_edit(self
, sdn_content
, order_id
):
397 sdn_id
= sdn_content
["_id"]
398 logging_text
= "Task sdn_edit={} ".format(sdn_id
)
399 self
.logger
.debug(logging_text
+ "Enter")
402 step
= "Getting sdn from db"
404 db_sdn
= self
.db
.get_one("sdns", {"_id": sdn_id
})
405 if db_sdn
.get("_admin") and db_sdn
["_admin"].get("deployed") and db_sdn
["_admin"]["deployed"].get("RO"):
406 RO_sdn_id
= db_sdn
["_admin"]["deployed"]["RO"]
407 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
408 step
= "Editing sdn at RO"
409 sdn_RO
= deepcopy(sdn_content
)
410 sdn_RO
.pop("_id", None)
411 sdn_RO
.pop("_admin", None)
412 sdn_RO
.pop("schema_version", None)
413 sdn_RO
.pop("schema_type", None)
414 sdn_RO
.pop("description", None)
416 await RO
.edit("sdn", RO_sdn_id
, descriptor
=sdn_RO
)
417 db_sdn
["_admin"]["operationalState"] = "ENABLED"
418 self
.update_db("sdns", sdn_id
, db_sdn
)
420 self
.logger
.debug(logging_text
+ "Exit Ok RO_sdn_id".format(RO_sdn_id
))
423 except (ROclient
.ROClientException
, DbException
) as e
:
424 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
426 except Exception as e
:
427 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
431 db_sdn
["_admin"]["operationalState"] = "ERROR"
432 db_sdn
["_admin"]["detailed-status"] = "ERROR {}: {}".format(step
, exc
)
433 self
.update_db("sdns", sdn_id
, db_sdn
)
435 async def sdn_delete(self
, sdn_id
, order_id
):
436 logging_text
= "Task sdn_delete={} ".format(sdn_id
)
437 self
.logger
.debug(logging_text
+ "Enter")
440 step
= "Getting sdn from db"
442 db_sdn
= self
.db
.get_one("sdns", {"_id": sdn_id
})
443 if db_sdn
.get("_admin") and db_sdn
["_admin"].get("deployed") and db_sdn
["_admin"]["deployed"].get("RO"):
444 RO_sdn_id
= db_sdn
["_admin"]["deployed"]["RO"]
445 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
446 step
= "Deleting sdn from RO"
448 await RO
.delete("sdn", RO_sdn_id
)
449 except ROclient
.ROClientException
as e
:
450 if e
.http_code
== 404: # not found
451 self
.logger
.debug(logging_text
+ "RO_sdn_id={} already deleted".format(RO_sdn_id
))
456 self
.logger
.error(logging_text
+ "Skipping. There is not RO information at database")
457 self
.db
.del_one("sdns", {"_id": sdn_id
})
458 self
.logger
.debug("sdn_delete task sdn_id={} Exit Ok".format(sdn_id
))
461 except (ROclient
.ROClientException
, DbException
) as e
:
462 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
464 except Exception as e
:
465 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
469 db_sdn
["_admin"]["operationalState"] = "ERROR"
470 db_sdn
["_admin"]["detailed-status"] = "ERROR {}: {}".format(step
, exc
)
471 self
.update_db("sdns", sdn_id
, db_sdn
)
473 def vnfd2RO(self
, vnfd
, new_id
=None):
475 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
476 :param vnfd: input vnfd
477 :param new_id: overrides vnf id if provided
478 :return: copy of vnfd
482 vnfd_RO
= deepcopy(vnfd
)
483 vnfd_RO
.pop("_id", None)
484 vnfd_RO
.pop("_admin", None)
486 vnfd_RO
["id"] = new_id
487 for vdu
in vnfd_RO
["vdu"]:
488 if "cloud-init-file" in vdu
:
489 base_folder
= vnfd
["_admin"]["storage"]
490 clout_init_file
= "{}/{}/cloud_init/{}".format(
491 base_folder
["folder"],
492 base_folder
["pkg-dir"],
493 vdu
["cloud-init-file"]
495 ci_file
= self
.fs
.file_open(clout_init_file
, "r")
496 # TODO: detect if binary or text. Propose to read as binary and try to decode to utf8. If fails
497 # convert to base 64 or similar
498 clout_init_content
= ci_file
.read()
501 vdu
.pop("cloud-init-file", None)
502 vdu
["cloud-init"] = clout_init_content
504 except FsException
as e
:
505 raise LcmException("Error reading file at vnfd {}: {} ".format(vnfd
["_id"], e
))
510 def n2vc_callback(self
, model_name
, application_name
, status
, message
, db_nsr
, db_nslcmop
, member_vnf_index
,
513 Callback both for charm status change and task completion
514 :param model_name: Charm model name
515 :param application_name: Charm application name
516 :param status: Can be
517 - blocked: The unit needs manual intervention
518 - maintenance: The unit is actively deploying/configuring
519 - waiting: The unit is waiting for another charm to be ready
520 - active: The unit is deployed, configured, and ready
521 - error: The charm has failed and needs attention.
522 - terminated: The charm has been destroyed
525 :param message: detailed message error
526 :param db_nsr: nsr database content
527 :param db_nslcmop: nslcmop database content
528 :param member_vnf_index: NSD member-vnf-index
529 :param task: None for charm status change, or task for completion task callback
534 update_nsr
= update_nslcmop
= False
536 nsr_id
= db_nsr
["_id"]
537 nslcmop_id
= db_nslcmop
["_id"]
538 nsr_lcm
= db_nsr
["_admin"]["deployed"]
539 ns_action
= db_nslcmop
["lcmOperationType"]
540 logging_text
= "Task ns={} {}={} [n2vc_callback] vnf_index={}".format(nsr_id
, ns_action
, nslcmop_id
,
545 self
.logger
.debug(logging_text
+ " task Cancelled")
546 # TODO update db_nslcmop
550 exc
= task
.exception()
552 self
.logger
.error(logging_text
+ " task Exception={}".format(exc
))
553 if ns_action
in ("instantiate", "terminate"):
554 nsr_lcm
["VCA"][member_vnf_index
]['operational-status'] = "error"
555 nsr_lcm
["VCA"][member_vnf_index
]['detailed-status'] = str(exc
)
556 elif ns_action
== "action":
557 db_nslcmop
["operationState"] = "FAILED"
558 db_nslcmop
["detailed-status"] = str(exc
)
559 db_nslcmop
["statusEnteredTime"] = time()
560 update_nslcmop
= True
564 self
.logger
.debug(logging_text
+ " task Done")
565 # TODO revise with Adam if action is finished and ok when task is done
566 if ns_action
== "action":
567 db_nslcmop
["operationState"] = "COMPLETED"
568 db_nslcmop
["detailed-status"] = "Done"
569 db_nslcmop
["statusEnteredTime"] = time()
570 update_nslcmop
= True
571 # task is Done, but callback is still ongoing. So ignore
574 self
.logger
.debug(logging_text
+ " Enter status={}".format(status
))
575 if nsr_lcm
["VCA"][member_vnf_index
]['operational-status'] == status
:
576 return # same status, ignore
577 nsr_lcm
["VCA"][member_vnf_index
]['operational-status'] = status
578 nsr_lcm
["VCA"][member_vnf_index
]['detailed-status'] = str(message
)
580 self
.logger
.critical(logging_text
+ " Enter with bad parameters", exc_info
=True)
585 n2vc_error_text
= [] # contain text error list. If empty no one is in error status
586 for vnf_index
, vca_info
in nsr_lcm
["VCA"].items():
587 vca_status
= vca_info
["operational-status"]
588 if vca_status
not in status_map
:
590 status_map
[vca_status
] = 0
591 status_map
[vca_status
] += 1
593 if vca_status
!= "active":
595 elif vca_status
in ("error", "blocked"):
596 n2vc_error_text
.append("member_vnf_index={} {}: {}".format(member_vnf_index
, vca_status
,
597 vca_info
["detailed-status"]))
600 self
.logger
.debug("[n2vc_callback] ns_instantiate={} vnf_index={} All active".format(nsr_id
,
602 db_nsr
["config-status"] = "configured"
603 db_nsr
["detailed-status"] = "done"
604 db_nslcmop
["operationState"] = "COMPLETED"
605 db_nslcmop
["detailed-status"] = "Done"
606 db_nslcmop
["statusEnteredTime"] = time()
607 elif n2vc_error_text
:
608 db_nsr
["config-status"] = "failed"
609 error_text
= "fail configuring " + ";".join(n2vc_error_text
)
610 db_nsr
["detailed-status"] = error_text
611 db_nslcmop
["operationState"] = "FAILED_TEMP"
612 db_nslcmop
["detailed-status"] = error_text
613 db_nslcmop
["statusEnteredTime"] = time()
617 for status
, num
in status_map
.items():
618 cs
+= separator
+ "{}: {}".format(status
, num
)
620 db_nsr
["config-status"] = cs
621 db_nsr
["detailed-status"] = cs
622 db_nslcmop
["detailed-status"] = cs
623 update_nsr
= update_nslcmop
= True
625 except Exception as e
:
626 self
.logger
.critical("[n2vc_callback] vnf_index={} Exception {}".format(member_vnf_index
, e
), exc_info
=True)
630 self
.update_db("nslcmops", nslcmop_id
, db_nslcmop
)
632 self
.update_db("nsrs", nsr_id
, db_nsr
)
633 except Exception as e
:
634 self
.logger
.critical("[n2vc_callback] vnf_index={} Update database Exception {}".format(
635 member_vnf_index
, e
), exc_info
=True)
637 def ns_params_2_RO(self
, ns_params
):
639 Creates a RO ns descriptor from OSM ns_instantite params
640 :param ns_params: OSM instantiate params
641 :return: The RO ns descriptor
645 def vim_account_2_RO(vim_account
):
646 if vim_account
in vim_2_RO
:
647 return vim_2_RO
[vim_account
]
648 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_account
})
649 # if db_vim["_admin"]["operationalState"] == "PROCESSING":
650 # #TODO check if VIM is creating and wait
651 if db_vim
["_admin"]["operationalState"] != "ENABLED":
652 raise LcmException("VIM={} is not available. operationalState={}".format(
653 vim_account
, db_vim
["_admin"]["operationalState"]))
654 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
655 vim_2_RO
[vim_account
] = RO_vim_id
661 # "name": ns_params["nsName"],
662 # "description": ns_params.get("nsDescription"),
663 "datacenter": vim_account_2_RO(ns_params
["vimAccountId"]),
664 # "scenario": ns_params["nsdId"],
668 if ns_params
.get("ssh-authorized-key"):
669 RO_ns_params
["cloud-config"] = {"key-pairs": ns_params
["ssh-authorized-key"]}
670 if ns_params
.get("vnf"):
671 for vnf
in ns_params
["vnf"]:
673 if "vimAccountId" in vnf
:
674 RO_vnf
["datacenter"] = vim_account_2_RO(vnf
["vimAccountId"])
676 RO_ns_params
["vnfs"][vnf
["member-vnf-index"]] = RO_vnf
677 if ns_params
.get("vld"):
678 for vld
in ns_params
["vld"]:
680 if "ip-profile" in vld
:
681 RO_vld
["ip-profile"] = vld
["ip-profile"]
682 if "vim-network-name" in vld
:
684 if isinstance(vld
["vim-network-name"], dict):
685 for vim_account
, vim_net
in vld
["vim-network-name"].items():
686 RO_vld
["sites"].append({
687 "netmap-use": vim_net
,
688 "datacenter": vim_account_2_RO(vim_account
)
690 else: # isinstance str
691 RO_vld
["sites"].append({"netmap-use": vld
["vim-network-name"]})
693 RO_ns_params
["networks"][vld
["name"]] = RO_vld
696 async def ns_instantiate(self
, nsr_id
, nslcmop_id
):
697 logging_text
= "Task ns={} instantiate={} ".format(nsr_id
, nslcmop_id
)
698 self
.logger
.debug(logging_text
+ "Enter")
699 # get all needed from database
705 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
706 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
707 step
= "Getting nsr={} from db".format(nsr_id
)
708 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
710 nsr_name
= db_nsr
["name"] # TODO short-name??
712 vnfr_filter
= {"nsr-id-ref": nsr_id
, "member-vnf-index-ref": None}
713 for c_vnf
in nsd
["constituent-vnfd"]:
714 vnfd_id
= c_vnf
["vnfd-id-ref"]
715 vnfr_filter
["member-vnf-index-ref"] = c_vnf
["member-vnf-index"]
716 db_vnfr
[c_vnf
["member-vnf-index"]] = self
.db
.get_one("vnfrs", vnfr_filter
)
717 if vnfd_id
not in needed_vnfd
:
718 step
= "Getting vnfd={} from db".format(vnfd_id
)
719 needed_vnfd
[vnfd_id
] = self
.db
.get_one("vnfds", {"id": vnfd_id
})
721 nsr_lcm
= db_nsr
["_admin"].get("deployed")
723 nsr_lcm
= db_nsr
["_admin"]["deployed"] = {
725 "RO": {"vnfd_id": {}, "nsd_id": None, "nsr_id": None, "nsr_status": "SCHEDULED"},
729 db_nsr
["detailed-status"] = "creating"
730 db_nsr
["operational-status"] = "init"
732 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
734 # get vnfds, instantiate at RO
735 for vnfd_id
, vnfd
in needed_vnfd
.items():
736 step
= db_nsr
["detailed-status"] = "Creating vnfd={} at RO".format(vnfd_id
)
737 # self.logger.debug(logging_text + step)
738 vnfd_id_RO
= nsr_id
+ "." + vnfd_id
[:200]
741 vnfd_list
= await RO
.get_list("vnfd", filter_by
={"osm_id": vnfd_id_RO
})
743 nsr_lcm
["RO"]["vnfd_id"][vnfd_id
] = vnfd_list
[0]["uuid"]
744 self
.logger
.debug(logging_text
+ "vnfd={} exists at RO. Using RO_id={}".format(
745 vnfd_id
, vnfd_list
[0]["uuid"]))
747 vnfd_RO
= self
.vnfd2RO(vnfd
, vnfd_id_RO
)
748 desc
= await RO
.create("vnfd", descriptor
=vnfd_RO
)
749 nsr_lcm
["RO"]["vnfd_id"][vnfd_id
] = desc
["uuid"]
750 db_nsr
["_admin"]["nsState"] = "INSTANTIATED"
751 self
.logger
.debug(logging_text
+ "vnfd={} created at RO. RO_id={}".format(
752 vnfd_id
, desc
["uuid"]))
753 self
.update_db("nsrs", nsr_id
, db_nsr
)
757 step
= db_nsr
["detailed-status"] = "Creating nsd={} at RO".format(nsd_id
)
758 # self.logger.debug(logging_text + step)
760 nsd_id_RO
= nsr_id
+ "." + nsd_id
[:200]
761 nsd_list
= await RO
.get_list("nsd", filter_by
={"osm_id": nsd_id_RO
})
763 nsr_lcm
["RO"]["nsd_id"] = nsd_list
[0]["uuid"]
764 self
.logger
.debug(logging_text
+ "nsd={} exists at RO. Using RO_id={}".format(
765 nsd_id
, nsd_list
[0]["uuid"]))
767 nsd_RO
= deepcopy(nsd
)
768 nsd_RO
["id"] = nsd_id_RO
769 nsd_RO
.pop("_id", None)
770 nsd_RO
.pop("_admin", None)
771 for c_vnf
in nsd_RO
["constituent-vnfd"]:
772 vnfd_id
= c_vnf
["vnfd-id-ref"]
773 c_vnf
["vnfd-id-ref"] = nsr_id
+ "." + vnfd_id
[:200]
774 desc
= await RO
.create("nsd", descriptor
=nsd_RO
)
775 db_nsr
["_admin"]["nsState"] = "INSTANTIATED"
776 nsr_lcm
["RO"]["nsd_id"] = desc
["uuid"]
777 self
.logger
.debug(logging_text
+ "nsd={} created at RO. RO_id={}".format(nsd_id
, desc
["uuid"]))
778 self
.update_db("nsrs", nsr_id
, db_nsr
)
781 # if present use it unless in error status
782 RO_nsr_id
= nsr_lcm
["RO"].get("nsr_id")
785 step
= db_nsr
["detailed-status"] = "Looking for existing ns at RO"
786 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
787 desc
= await RO
.show("ns", RO_nsr_id
)
788 except ROclient
.ROClientException
as e
:
789 if e
.http_code
!= HTTPStatus
.NOT_FOUND
:
791 RO_nsr_id
= nsr_lcm
["RO"]["nsr_id"] = None
793 ns_status
, ns_status_info
= RO
.check_ns_status(desc
)
794 nsr_lcm
["RO"]["nsr_status"] = ns_status
795 if ns_status
== "ERROR":
796 step
= db_nsr
["detailed-status"] = "Deleting ns at RO. RO_ns_id={}".format(RO_nsr_id
)
797 self
.logger
.debug(logging_text
+ step
)
798 await RO
.delete("ns", RO_nsr_id
)
799 RO_nsr_id
= nsr_lcm
["RO"]["nsr_id"] = None
801 step
= db_nsr
["detailed-status"] = "Creating ns at RO"
802 # self.logger.debug(logging_text + step)
803 RO_ns_params
= self
.ns_params_2_RO(db_nsr
.get("instantiate_params"))
804 desc
= await RO
.create("ns", descriptor
=RO_ns_params
,
806 scenario
=nsr_lcm
["RO"]["nsd_id"])
807 RO_nsr_id
= nsr_lcm
["RO"]["nsr_id"] = desc
["uuid"]
808 db_nsr
["_admin"]["nsState"] = "INSTANTIATED"
809 nsr_lcm
["RO"]["nsr_status"] = "BUILD"
810 self
.logger
.debug(logging_text
+ "ns created at RO. RO_id={}".format(desc
["uuid"]))
811 self
.update_db("nsrs", nsr_id
, db_nsr
)
813 # update VNFR vimAccount
814 step
= "Updating VNFR vimAcccount"
815 for vnf_index
, vnfr
in db_vnfr
.items():
816 if vnfr
.get("vim-account-id"):
818 if db_nsr
["instantiate_params"].get("vnf") and db_nsr
["instantiate_params"]["vnf"].get(vnf_index
) \
819 and db_nsr
["instantiate_params"]["vnf"][vnf_index
].get("vimAccountId"):
820 vnfr
["vim-account-id"] = db_nsr
["instantiate_params"]["vnf"][vnf_index
]["vimAccountId"]
822 vnfr
["vim-account-id"] = db_nsr
["instantiate_params"]["vimAccountId"]
823 self
.update_db("vnfrs", vnfr
["_id"], vnfr
)
825 # wait until NS is ready
826 step
= ns_status_detailed
= "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id
)
827 db_nsr
["detailed-status"] = ns_status_detailed
828 self
.logger
.debug(logging_text
+ step
)
829 deployment_timeout
= 2 * 3600 # Two hours
830 while deployment_timeout
> 0:
831 desc
= await RO
.show("ns", RO_nsr_id
)
832 ns_status
, ns_status_info
= RO
.check_ns_status(desc
)
833 nsr_lcm
["RO"]["nsr_status"] = ns_status
834 if ns_status
== "ERROR":
835 raise ROclient
.ROClientException(ns_status_info
)
836 elif ns_status
== "BUILD":
837 db_nsr_detailed_status_old
= db_nsr
["detailed-status"]
838 db_nsr
["detailed-status"] = ns_status_detailed
+ "; {}".format(ns_status_info
)
839 if db_nsr_detailed_status_old
!= db_nsr
["detailed-status"]:
840 self
.update_db("nsrs", nsr_id
, db_nsr
)
841 elif ns_status
== "ACTIVE":
842 step
= "Waiting for management IP address from VIM"
844 ns_RO_info
= nsr_lcm
["nsr_ip"] = RO
.get_ns_vnf_info(desc
)
846 except ROclient
.ROClientException
as e
:
847 if e
.http_code
!= 409: # IP address is not ready return code is 409 CONFLICT
850 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
851 await asyncio
.sleep(5, loop
=self
.loop
)
852 deployment_timeout
-= 5
853 if deployment_timeout
<= 0:
854 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
856 step
= "Updating VNFRs"
857 for vnf_index
, vnfr_deployed
in ns_RO_info
.items():
858 vnfr
= db_vnfr
[vnf_index
]
859 vnfr
["ip-address"] = vnfr_deployed
.get("ip_address")
860 for vdu_id
, vdu_deployed
in vnfr_deployed
["vdur"].items():
861 for vdur
in vnfr
["vdur"]:
862 if vdur
["vdu-id-ref"] == vdu_id
:
863 vdur
["vim-id"] = vdu_deployed
.get("vim_id")
864 vdur
["ip-address"] = vdu_deployed
.get("ip_address")
866 self
.update_db("vnfrs", vnfr
["_id"], vnfr
)
868 db_nsr
["detailed-status"] = "Configuring vnfr"
869 self
.update_db("nsrs", nsr_id
, db_nsr
)
871 # The parameters we'll need to deploy a charm
872 number_to_configure
= 0
875 """An inner function to deploy the charm from either vnf or vdu
879 # if number_to_configure == 0:
880 # self.logger.debug("Logging into N2VC...")
881 # task = asyncio.ensure_future(self.n2vc.login())
882 # yield from asyncio.wait_for(task, 30.0)
883 # self.logger.debug("Logged into N2VC!")
885 # # await self.n2vc.login()
887 # Note: The charm needs to exist on disk at the location
888 # specified by charm_path.
889 base_folder
= vnfd
["_admin"]["storage"]
890 storage_params
= self
.fs
.get_params()
891 charm_path
= "{}{}/{}/charms/{}".format(
892 storage_params
["path"],
893 base_folder
["folder"],
894 base_folder
["pkg-dir"],
898 # Setup the runtime parameters for this VNF
899 params
['rw_mgmt_ip'] = db_vnfr
[vnf_index
]["ip-address"]
901 # ns_name will be ignored in the current version of N2VC
902 # but will be implemented for the next point release.
903 model_name
= 'default'
904 application_name
= self
.n2vc
.FormatApplicationName(
910 nsr_lcm
["VCA"][vnf_index
] = {
912 "application": application_name
,
913 "operational-status": "init",
914 "detailed-status": "",
918 self
.logger
.debug("Task create_ns={} Passing artifacts path '{}' for {}".format(nsr_id
, charm_path
,
920 task
= asyncio
.ensure_future(
921 self
.n2vc
.DeployCharms(
922 model_name
, # The network service name
923 application_name
, # The application name
924 vnfd
, # The vnf descriptor
925 charm_path
, # Path to charm
926 params
, # Runtime params, like mgmt ip
927 {}, # for native charms only
928 self
.n2vc_callback
, # Callback for status changes
929 db_nsr
, # Callback parameter
931 vnf_index
, # Callback parameter
932 None, # Callback parameter (task)
935 task
.add_done_callback(functools
.partial(self
.n2vc_callback
, model_name
, application_name
, None, None,
936 db_nsr
, db_nslcmop
, vnf_index
))
937 self
.lcm_ns_tasks
[nsr_id
][nslcmop_id
]["create_charm:" + vnf_index
] = task
939 # TODO: Make this call inside deploy()
940 # Login to the VCA. If there are multiple calls to login(),
941 # subsequent calls will be a nop and return immediately.
942 await self
.n2vc
.login()
944 step
= "Looking for needed vnfd to configure"
945 self
.logger
.debug(logging_text
+ step
)
946 for c_vnf
in nsd
["constituent-vnfd"]:
947 vnfd_id
= c_vnf
["vnfd-id-ref"]
948 vnf_index
= str(c_vnf
["member-vnf-index"])
949 vnfd
= needed_vnfd
[vnfd_id
]
951 # Check if this VNF has a charm configuration
952 vnf_config
= vnfd
.get("vnf-configuration")
954 if vnf_config
and vnf_config
.get("juju"):
955 proxy_charm
= vnf_config
["juju"]["charm"]
959 if 'initial-config-primitive' in vnf_config
:
960 params
['initial-config-primitive'] = vnf_config
['initial-config-primitive']
963 number_to_configure
+= 1
965 # Deploy charms for each VDU that supports one.
966 for vdu
in vnfd
['vdu']:
967 vdu_config
= vdu
.get('vdu-configuration')
971 if vdu_config
and vdu_config
.get("juju"):
972 proxy_charm
= vdu_config
["juju"]["charm"]
974 if 'initial-config-primitive' in vdu_config
:
975 params
['initial-config-primitive'] = vdu_config
['initial-config-primitive']
979 number_to_configure
+= 1
981 if number_to_configure
:
982 db_nsr
["config-status"] = "configuring"
983 db_nsr
["detailed-status"] = "configuring: init: {}".format(number_to_configure
)
984 db_nslcmop
["detailed-status"] = "configuring: init: {}".format(number_to_configure
)
986 db_nslcmop
["operationState"] = "COMPLETED"
987 db_nslcmop
["detailed-status"] = "done"
988 db_nsr
["config-status"] = "configured"
989 db_nsr
["detailed-status"] = "done"
990 db_nsr
["operational-status"] = "running"
991 self
.update_db("nsrs", nsr_id
, db_nsr
)
992 self
.update_db("nslcmops", nslcmop_id
, db_nslcmop
)
993 self
.logger
.debug("Task ns_instantiate={} Exit Ok".format(nsr_id
))
996 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
997 self
.logger
.error(logging_text
+ "Exit Exception while '{}': {}".format(step
, e
))
999 except Exception as e
:
1000 self
.logger
.critical(logging_text
+ "Exit Exception {} while '{}': {}".format(type(e
).__name
__, step
, e
),
1006 db_nsr
["detailed-status"] = "ERROR {}: {}".format(step
, exc
)
1007 db_nsr
["operational-status"] = "failed"
1008 self
.update_db("nsrs", nsr_id
, db_nsr
)
1010 db_nslcmop
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
1011 db_nslcmop
["operationState"] = "FAILED"
1012 db_nslcmop
["statusEnteredTime"] = time()
1013 self
.update_db("nslcmops", nslcmop_id
, db_nslcmop
)
1015 async def ns_terminate(self
, nsr_id
, nslcmop_id
):
1016 logging_text
= "Task ns={} terminate={} ".format(nsr_id
, nslcmop_id
)
1017 self
.logger
.debug(logging_text
+ "Enter")
1021 step
= "Getting nsr, nslcmop from db"
1022 failed_detail
= [] # annotates all failed error messages
1026 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1027 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1028 # nsd = db_nsr["nsd"]
1029 nsr_lcm
= deepcopy(db_nsr
["_admin"]["deployed"])
1030 if db_nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
1033 # db_vim = self.db.get_one("vim_accounts", {"_id": db_nsr["datacenter"]})
1034 # #TODO check if VIM is creating and wait
1035 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
1038 "operational-status": "terminating",
1039 "config-status": "terminating",
1040 "detailed-status": "Deleting charms",
1042 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1045 self
.logger
.debug(logging_text
+ step
)
1046 for vnf_index
, deploy_info
in nsr_lcm
["VCA"].items():
1047 if deploy_info
and deploy_info
.get("application"):
1048 task
= asyncio
.ensure_future(
1049 self
.n2vc
.RemoveCharms(
1050 deploy_info
['model'],
1051 deploy_info
['application'],
1052 # self.n2vc_callback,
1058 vca_task_list
.append(task
)
1059 vca_task_dict
[vnf_index
] = task
1060 # task.add_done_callback(functools.partial(self.n2vc_callback, deploy_info['model'],
1061 # deploy_info['application'], None, db_nsr,
1062 # db_nslcmop, vnf_index))
1063 self
.lcm_ns_tasks
[nsr_id
][nslcmop_id
]["delete_charm:" + vnf_index
] = task
1064 except Exception as e
:
1065 self
.logger
.debug(logging_text
+ "Failed while deleting charms: {}".format(e
))
1068 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
1070 RO_nsr_id
= nsr_lcm
["RO"].get("nsr_id")
1073 step
= db_nsr
["detailed-status"] = "Deleting ns at RO"
1074 self
.logger
.debug(logging_text
+ step
)
1075 await RO
.delete("ns", RO_nsr_id
)
1076 nsr_lcm
["RO"]["nsr_id"] = None
1077 nsr_lcm
["RO"]["nsr_status"] = "DELETED"
1078 except ROclient
.ROClientException
as e
:
1079 if e
.http_code
== 404: # not found
1080 nsr_lcm
["RO"]["nsr_id"] = None
1081 nsr_lcm
["RO"]["nsr_status"] = "DELETED"
1082 self
.logger
.debug(logging_text
+ "RO_ns_id={} already deleted".format(RO_nsr_id
))
1083 elif e
.http_code
== 409: # conflict
1084 failed_detail
.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id
, e
))
1085 self
.logger
.debug(logging_text
+ failed_detail
[-1])
1087 failed_detail
.append("RO_ns_id={} delete error: {}".format(RO_nsr_id
, e
))
1088 self
.logger
.error(logging_text
+ failed_detail
[-1])
1091 RO_nsd_id
= nsr_lcm
["RO"]["nsd_id"]
1094 step
= db_nsr
["detailed-status"] = "Deleting nsd at RO"
1095 await RO
.delete("nsd", RO_nsd_id
)
1096 self
.logger
.debug(logging_text
+ "RO_nsd_id={} deleted".format(RO_nsd_id
))
1097 nsr_lcm
["RO"]["nsd_id"] = None
1098 except ROclient
.ROClientException
as e
:
1099 if e
.http_code
== 404: # not found
1100 nsr_lcm
["RO"]["nsd_id"] = None
1101 self
.logger
.debug(logging_text
+ "RO_nsd_id={} already deleted".format(RO_nsd_id
))
1102 elif e
.http_code
== 409: # conflict
1103 failed_detail
.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id
, e
))
1104 self
.logger
.debug(logging_text
+ failed_detail
[-1])
1106 failed_detail
.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id
, e
))
1107 self
.logger
.error(logging_text
+ failed_detail
[-1])
1109 for vnf_id
, RO_vnfd_id
in nsr_lcm
["RO"]["vnfd_id"].items():
1113 step
= db_nsr
["detailed-status"] = "Deleting vnfd={} at RO".format(vnf_id
)
1114 await RO
.delete("vnfd", RO_vnfd_id
)
1115 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} deleted".format(RO_vnfd_id
))
1116 nsr_lcm
["RO"]["vnfd_id"][vnf_id
] = None
1117 except ROclient
.ROClientException
as e
:
1118 if e
.http_code
== 404: # not found
1119 nsr_lcm
["RO"]["vnfd_id"][vnf_id
] = None
1120 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} already deleted ".format(RO_vnfd_id
))
1121 elif e
.http_code
== 409: # conflict
1122 failed_detail
.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id
, e
))
1123 self
.logger
.debug(logging_text
+ failed_detail
[-1])
1125 failed_detail
.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id
, e
))
1126 self
.logger
.error(logging_text
+ failed_detail
[-1])
1129 await asyncio
.wait(vca_task_list
, timeout
=300)
1130 for vnf_index
, task
in vca_task_dict
.items():
1131 if task
.cancelled():
1132 failed_detail
.append("VCA[{}] Deletion has been cancelled".format(vnf_index
))
1134 exc
= task
.exception()
1136 failed_detail
.append("VCA[{}] Deletion exception: {}".format(vnf_index
, exc
))
1138 nsr_lcm
["VCA"][vnf_index
] = None
1140 # TODO Should it be cancelled?!!
1142 failed_detail
.append("VCA[{}] Deletion timeout".format(vnf_index
))
1145 self
.logger
.error(logging_text
+ " ;".join(failed_detail
))
1147 "operational-status": "failed",
1148 "detailed-status": "Deletion errors " + "; ".join(failed_detail
),
1149 "_admin.deployed": nsr_lcm
1151 db_nslcmop_update
= {
1152 "detailed-status": "; ".join(failed_detail
),
1153 "operationState": "FAILED",
1154 "statusEnteredTime": time()
1156 elif db_nslcmop
["operationParams"].get("autoremove"):
1157 self
.db
.del_one("nsrs", {"_id": nsr_id
})
1158 self
.db
.del_list("nslcmops", {"nsInstanceId": nsr_id
})
1159 self
.db
.del_list("vnfrs", {"nsr-id-ref": nsr_id
})
1162 "operational-status": "terminated",
1163 "detailed-status": "Done",
1164 "_admin.deployed": nsr_lcm
,
1165 "_admin.nsState": "NOT_INSTANTIATED"
1167 db_nslcmop_update
= {
1168 "detailed-status": "Done",
1169 "operationState": "COMPLETED",
1170 "statusEnteredTime": time()
1172 self
.logger
.debug(logging_text
+ "Exit")
1174 except (ROclient
.ROClientException
, DbException
) as e
:
1175 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
1177 except Exception as e
:
1178 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
1181 if exc
and db_nslcmop
:
1182 db_nslcmop_update
= {
1183 "detailed-status": "FAILED {}: {}".format(step
, exc
),
1184 "operationState": "FAILED",
1185 "statusEnteredTime": time(),
1187 if db_nslcmop_update
:
1188 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1190 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1192 async def ns_action(self
, nsr_id
, nslcmop_id
):
1193 logging_text
= "Task ns={} action={} ".format(nsr_id
, nslcmop_id
)
1194 self
.logger
.debug(logging_text
+ "Enter")
1195 # get all needed from database
1198 db_nslcmop_update
= None
1201 step
= "Getting information from database"
1202 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1203 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1204 nsr_lcm
= db_nsr
["_admin"].get("deployed")
1205 vnf_index
= db_nslcmop
["operationParams"]["member_vnf_index"]
1207 # TODO check if ns is in a proper status
1208 vca_deployed
= nsr_lcm
["VCA"].get(vnf_index
)
1209 if not vca_deployed
:
1210 raise LcmException("charm for member_vnf_index={} is not deployed".format(vnf_index
))
1211 model_name
= vca_deployed
.get("model")
1212 application_name
= vca_deployed
.get("application")
1213 if not model_name
or not application_name
:
1214 raise LcmException("charm for member_vnf_index={} is not properly deployed".format(vnf_index
))
1215 if vca_deployed
["operational-status"] != "active":
1216 raise LcmException("charm for member_vnf_index={} operational_status={} not 'active'".format(
1217 vnf_index
, vca_deployed
["operational-status"]))
1218 primitive
= db_nslcmop
["operationParams"]["primitive"]
1219 primitive_params
= db_nslcmop
["operationParams"]["primitive_params"]
1220 callback
= None # self.n2vc_callback
1221 callback_args
= () # [db_nsr, db_nslcmop, vnf_index, None]
1222 await self
.n2vc
.login()
1223 task
= asyncio
.ensure_future(
1224 self
.n2vc
.ExecutePrimitive(
1227 primitive
, callback
,
1232 # task.add_done_callback(functools.partial(self.n2vc_callback, model_name, application_name, None,
1233 # db_nsr, db_nslcmop, vnf_index))
1234 # self.lcm_ns_tasks[nsr_id][nslcmop_id]["action: " + primitive] = task
1235 # wait until completed with timeout
1236 await asyncio
.wait((task
,), timeout
=300)
1238 result
= "FAILED" # by default
1240 if task
.cancelled():
1241 db_nslcmop
["detailed-status"] = "Task has been cancelled"
1243 exc
= task
.exception()
1245 result_detail
= str(exc
)
1247 self
.logger
.debug(logging_text
+ " task Done")
1248 # TODO revise with Adam if action is finished and ok when task is done or callback is needed
1249 result
= "COMPLETED"
1250 result_detail
= "Done"
1252 # TODO Should it be cancelled?!!
1254 result_detail
= "timeout"
1256 db_nslcmop_update
= {
1257 "detailed-status": result_detail
,
1258 "operationState": result
,
1259 "statusEnteredTime": time()
1261 self
.logger
.debug(logging_text
+ " task Done with result {} {}".format(result
, result_detail
))
1262 return # database update is called inside finally
1264 except (DbException
, LcmException
) as e
:
1265 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
1267 except Exception as e
:
1268 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
1271 if exc
and db_nslcmop
:
1272 db_nslcmop_update
= {
1273 "detailed-status": "FAILED {}: {}".format(step
, exc
),
1274 "operationState": "FAILED",
1275 "statusEnteredTime": time(),
1277 if db_nslcmop_update
:
1278 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1280 async def test(self
, param
=None):
1281 self
.logger
.debug("Starting/Ending test task: {}".format(param
))
1283 def cancel_tasks(self
, topic
, _id
):
1285 Cancel all active tasks of a concrete nsr or vim identified for _id
1286 :param topic: can be ns or vim_account
1287 :param _id: nsr or vim identity
1288 :return: None, or raises an exception if not possible
1291 lcm_tasks
= self
.lcm_ns_tasks
1292 elif topic
== "vim_account":
1293 lcm_tasks
= self
.lcm_vim_tasks
1294 elif topic
== "sdn":
1295 lcm_tasks
= self
.lcm_sdn_tasks
1297 if not lcm_tasks
.get(_id
):
1299 for order_id
, tasks_set
in lcm_tasks
[_id
].items():
1300 for task_name
, task
in tasks_set
.items():
1301 result
= task
.cancel()
1303 self
.logger
.debug("{} _id={} order_id={} task={} cancelled".format(topic
, _id
, order_id
, task_name
))
1306 async def kafka_ping(self
):
1307 self
.logger
.debug("Task kafka_ping Enter")
1308 consecutive_errors
= 0
1310 kafka_has_received
= False
1311 self
.pings_not_received
= 1
1314 await self
.msg
.aiowrite("admin", "ping", {"from": "lcm", "to": "lcm"}, self
.loop
)
1315 # time between pings are low when it is not received and at starting
1316 wait_time
= 5 if not kafka_has_received
else 120
1317 if not self
.pings_not_received
:
1318 kafka_has_received
= True
1319 self
.pings_not_received
+= 1
1320 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
1321 if self
.pings_not_received
> 10:
1322 raise LcmException("It is not receiving pings from Kafka bus")
1323 consecutive_errors
= 0
1325 except LcmException
:
1327 except Exception as e
:
1328 # if not first_start is the first time after starting. So leave more time and wait
1329 # to allow kafka starts
1330 if consecutive_errors
== 8 if not first_start
else 30:
1331 self
.logger
.error("Task kafka_read task exit error too many errors. Exception: {}".format(e
))
1333 consecutive_errors
+= 1
1334 self
.logger
.error("Task kafka_read retrying after Exception {}".format(e
))
1335 wait_time
= 1 if not first_start
else 5
1336 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
1338 async def kafka_read(self
):
1339 self
.logger
.debug("Task kafka_read Enter")
1341 # future = asyncio.Future()
1342 consecutive_errors
= 0
1344 while consecutive_errors
< 10:
1346 topics
= ("admin", "ns", "vim_account", "sdn")
1347 topic
, command
, params
= await self
.msg
.aioread(topics
, self
.loop
)
1348 if topic
!= "admin" and command
!= "ping":
1349 self
.logger
.debug("Task kafka_read receives {} {}: {}".format(topic
, command
, params
))
1350 consecutive_errors
= 0
1353 if command
== "exit":
1356 elif command
.startswith("#"):
1358 elif command
== "echo":
1363 elif command
== "test":
1364 asyncio
.Task(self
.test(params
), loop
=self
.loop
)
1367 if topic
== "admin":
1368 if command
== "ping" and params
["to"] == "lcm" and params
["from"] == "lcm":
1369 self
.pings_not_received
= 0
1372 if command
== "instantiate":
1373 # self.logger.debug("Deploying NS {}".format(nsr_id))
1375 nslcmop_id
= nslcmop
["_id"]
1376 nsr_id
= nslcmop
["nsInstanceId"]
1377 task
= asyncio
.ensure_future(self
.ns_instantiate(nsr_id
, nslcmop_id
))
1378 if nsr_id
not in self
.lcm_ns_tasks
:
1379 self
.lcm_ns_tasks
[nsr_id
] = {}
1380 self
.lcm_ns_tasks
[nsr_id
][nslcmop_id
] = {"ns_instantiate": task
}
1382 elif command
== "terminate":
1383 # self.logger.debug("Deleting NS {}".format(nsr_id))
1385 nslcmop_id
= nslcmop
["_id"]
1386 nsr_id
= nslcmop
["nsInstanceId"]
1387 self
.cancel_tasks(topic
, nsr_id
)
1388 task
= asyncio
.ensure_future(self
.ns_terminate(nsr_id
, nslcmop_id
))
1389 if nsr_id
not in self
.lcm_ns_tasks
:
1390 self
.lcm_ns_tasks
[nsr_id
] = {}
1391 self
.lcm_ns_tasks
[nsr_id
][nslcmop_id
] = {"ns_terminate": task
}
1393 elif command
== "action":
1394 # self.logger.debug("Update NS {}".format(nsr_id))
1396 nslcmop_id
= nslcmop
["_id"]
1397 nsr_id
= nslcmop
["nsInstanceId"]
1398 task
= asyncio
.ensure_future(self
.ns_action(nsr_id
, nslcmop_id
))
1399 if nsr_id
not in self
.lcm_ns_tasks
:
1400 self
.lcm_ns_tasks
[nsr_id
] = {}
1401 self
.lcm_ns_tasks
[nsr_id
][nslcmop_id
] = {"ns_action": task
}
1403 elif command
== "show":
1405 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1406 print("nsr:\n _id={}\n operational-status: {}\n config-status: {}"
1407 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
1408 "".format(nsr_id
, db_nsr
["operational-status"], db_nsr
["config-status"],
1409 db_nsr
["detailed-status"],
1410 db_nsr
["_admin"]["deployed"], self
.lcm_ns_tasks
.get(nsr_id
)))
1411 except Exception as e
:
1412 print("nsr {} not found: {}".format(nsr_id
, e
))
1415 elif command
== "deleted":
1416 continue # TODO cleaning of task just in case should be done
1417 elif topic
== "vim_account":
1418 vim_id
= params
["_id"]
1419 if command
== "create":
1420 task
= asyncio
.ensure_future(self
.vim_create(params
, order_id
))
1421 if vim_id
not in self
.lcm_vim_tasks
:
1422 self
.lcm_vim_tasks
[vim_id
] = {}
1423 self
.lcm_vim_tasks
[vim_id
][order_id
] = {"vim_create": task
}
1425 elif command
== "delete":
1426 self
.cancel_tasks(topic
, vim_id
)
1427 task
= asyncio
.ensure_future(self
.vim_delete(vim_id
, order_id
))
1428 if vim_id
not in self
.lcm_vim_tasks
:
1429 self
.lcm_vim_tasks
[vim_id
] = {}
1430 self
.lcm_vim_tasks
[vim_id
][order_id
] = {"vim_delete": task
}
1432 elif command
== "show":
1433 print("not implemented show with vim_account")
1436 elif command
== "edit":
1437 task
= asyncio
.ensure_future(self
.vim_edit(params
, order_id
))
1438 if vim_id
not in self
.lcm_vim_tasks
:
1439 self
.lcm_vim_tasks
[vim_id
] = {}
1440 self
.lcm_vim_tasks
[vim_id
][order_id
] = {"vim_edit": task
}
1442 elif topic
== "sdn":
1443 _sdn_id
= params
["_id"]
1444 if command
== "create":
1445 task
= asyncio
.ensure_future(self
.sdn_create(params
, order_id
))
1446 if _sdn_id
not in self
.lcm_sdn_tasks
:
1447 self
.lcm_sdn_tasks
[_sdn_id
] = {}
1448 self
.lcm_sdn_tasks
[_sdn_id
][order_id
] = {"sdn_create": task
}
1450 elif command
== "delete":
1451 self
.cancel_tasks(topic
, _sdn_id
)
1452 task
= asyncio
.ensure_future(self
.sdn_delete(_sdn_id
, order_id
))
1453 if _sdn_id
not in self
.lcm_sdn_tasks
:
1454 self
.lcm_sdn_tasks
[_sdn_id
] = {}
1455 self
.lcm_sdn_tasks
[_sdn_id
][order_id
] = {"sdn_delete": task
}
1457 elif command
== "edit":
1458 task
= asyncio
.ensure_future(self
.sdn_edit(params
, order_id
))
1459 if _sdn_id
not in self
.lcm_sdn_tasks
:
1460 self
.lcm_sdn_tasks
[_sdn_id
] = {}
1461 self
.lcm_sdn_tasks
[_sdn_id
][order_id
] = {"sdn_edit": task
}
1463 self
.logger
.critical("unknown topic {} and command '{}'".format(topic
, command
))
1464 except Exception as e
:
1465 # if not first_start is the first time after starting. So leave more time and wait
1466 # to allow kafka starts
1467 if consecutive_errors
== 8 if not first_start
else 30:
1468 self
.logger
.error("Task kafka_read task exit error too many errors. Exception: {}".format(e
))
1470 consecutive_errors
+= 1
1471 self
.logger
.error("Task kafka_read retrying after Exception {}".format(e
))
1472 wait_time
= 2 if not first_start
else 5
1473 await asyncio
.sleep(wait_time
, loop
=self
.loop
)
1475 # self.logger.debug("Task kafka_read terminating")
1476 self
.logger
.debug("Task kafka_read exit")
1479 self
.loop
= asyncio
.get_event_loop()
1480 self
.loop
.run_until_complete(asyncio
.gather(
1485 # self.logger.debug("Terminating cancelling creation tasks")
1486 # self.cancel_tasks("ALL", "create")
1488 # while self.is_pending_tasks():
1489 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
1490 # await asyncio.sleep(2, loop=self.loop)
1493 # self.cancel_tasks("ALL", "ALL")
1497 self
.db
.db_disconnect()
1499 self
.msg
.disconnect()
1501 self
.fs
.fs_disconnect()
1503 def read_config_file(self
, config_file
):
1504 # TODO make a [ini] + yaml inside parser
1505 # the configparser library is not suitable, because it does not admit comments at the end of line,
1506 # and not parse integer or boolean
1508 with
open(config_file
) as f
:
1510 for k
, v
in environ
.items():
1511 if not k
.startswith("OSMLCM_"):
1513 k_items
= k
.lower().split("_")
1516 for k_item
in k_items
[1:-1]:
1517 if k_item
in ("ro", "vca"):
1518 # put in capital letter
1519 k_item
= k_item
.upper()
1521 if k_items
[-1] == "port":
1522 c
[k_items
[-1]] = int(v
)
1525 except Exception as e
:
1526 self
.logger
.warn("skipping environ '{}' on exception '{}'".format(k
, e
))
1529 except Exception as e
:
1530 self
.logger
.critical("At config file '{}': {}".format(config_file
, e
))
1535 print("""Usage: {} [options]
1536 -c|--config [configuration_file]: loads the configuration file (default: ./nbi.cfg)
1537 -h|--help: shows this help
1538 """.format(sys
.argv
[0]))
1539 # --log-socket-host HOST: send logs to this host")
1540 # --log-socket-port PORT: send logs using this port (default: 9022)")
1543 if __name__
== '__main__':
1545 # load parameters and configuration
1546 opts
, args
= getopt
.getopt(sys
.argv
[1:], "hc:", ["config=", "help"])
1547 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
1550 if o
in ("-h", "--help"):
1553 elif o
in ("-c", "--config"):
1555 # elif o == "--log-socket-port":
1556 # log_socket_port = a
1557 # elif o == "--log-socket-host":
1558 # log_socket_host = a
1559 # elif o == "--log-file":
1562 assert False, "Unhandled option"
1564 if not path
.isfile(config_file
):
1565 print("configuration file '{}' that not exist".format(config_file
), file=sys
.stderr
)
1568 for config_file
in (__file__
[:__file__
.rfind(".")] + ".cfg", "./lcm.cfg", "/etc/osm/lcm.cfg"):
1569 if path
.isfile(config_file
):
1572 print("No configuration file 'nbi.cfg' found neither at local folder nor at /etc/osm/", file=sys
.stderr
)
1574 lcm
= Lcm(config_file
)
1576 except getopt
.GetoptError
as e
:
1577 print(str(e
), file=sys
.stderr
)