784ece1fc2c313cd71d7bf4cfb4fe6914c1bb26f
2 # -*- coding: utf-8 -*-
7 import logging
.handlers
12 from lcm_utils
import LcmException
, LcmBase
14 from osm_common
.dbbase
import DbException
, deep_update
15 from osm_common
.fsbase
import FsException
16 from n2vc
.vnf
import N2VC
18 from copy
import deepcopy
19 from http
import HTTPStatus
23 __author__
= "Alfonso Tierno"
28 def __init__(self
, db
, msg
, fs
, lcm_tasks
, ro_config
, vca_config
, loop
):
30 Init, Connect to database, filesystem storage, and messaging
31 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
35 self
.logger
= logging
.getLogger('lcm.ns')
37 self
.lcm_tasks
= lcm_tasks
39 super().__init
__(db
, msg
, fs
, self
.logger
)
41 self
.ro_config
= ro_config
45 server
=vca_config
['host'],
46 port
=vca_config
['port'],
47 user
=vca_config
['user'],
48 secret
=vca_config
['secret'],
49 # TODO: This should point to the base folder where charms are stored,
50 # if there is a common one (like object storage). Otherwise, leave
51 # it unset and pass it via DeployCharms
52 # artifacts=vca_config[''],
56 def vnfd2RO(self
, vnfd
, new_id
=None):
58 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
59 :param vnfd: input vnfd
60 :param new_id: overrides vnf id if provided
65 vnfd_RO
= deepcopy(vnfd
)
66 vnfd_RO
.pop("_id", None)
67 vnfd_RO
.pop("_admin", None)
69 vnfd_RO
["id"] = new_id
70 for vdu
in vnfd_RO
["vdu"]:
71 if "cloud-init-file" in vdu
:
72 base_folder
= vnfd
["_admin"]["storage"]
73 clout_init_file
= "{}/{}/cloud_init/{}".format(
74 base_folder
["folder"],
75 base_folder
["pkg-dir"],
76 vdu
["cloud-init-file"]
78 ci_file
= self
.fs
.file_open(clout_init_file
, "r")
79 # TODO: detect if binary or text. Propose to read as binary and try to decode to utf8. If fails
80 # convert to base 64 or similar
81 clout_init_content
= ci_file
.read()
84 vdu
.pop("cloud-init-file", None)
85 vdu
["cloud-init"] = clout_init_content
86 # remnove unused by RO configuration, monitoring, scaling
87 vnfd_RO
.pop("vnf-configuration", None)
88 vnfd_RO
.pop("monitoring-param", None)
89 vnfd_RO
.pop("scaling-group-descriptor", None)
91 except FsException
as e
:
92 raise LcmException("Error reading file at vnfd {}: {} ".format(vnfd
["_id"], e
))
97 def n2vc_callback(self
, model_name
, application_name
, status
, message
, n2vc_info
, task
=None):
99 Callback both for charm status change and task completion
100 :param model_name: Charm model name
101 :param application_name: Charm application name
102 :param status: Can be
103 - blocked: The unit needs manual intervention
104 - maintenance: The unit is actively deploying/configuring
105 - waiting: The unit is waiting for another charm to be ready
106 - active: The unit is deployed, configured, and ready
107 - error: The charm has failed and needs attention.
108 - terminated: The charm has been destroyed
111 :param message: detailed message error
112 :param n2vc_info dictionary with information shared with instantiate task. Contains:
115 lcmOperationType: currently "instantiate"
116 deployed: dictionary with {<application>: {operational-status: <status>, detailed-status: <text>}}
117 db_update: dictionary to be filled with the changes to be wrote to database with format key.key.key: value
118 n2vc_event: event used to notify instantiation task that some change has been produced
119 :param task: None for charm status change, or task for completion task callback
123 nsr_id
= n2vc_info
["nsr_id"]
124 deployed
= n2vc_info
["deployed"]
125 db_nsr_update
= n2vc_info
["db_update"]
126 nslcmop_id
= n2vc_info
["nslcmop_id"]
127 ns_operation
= n2vc_info
["lcmOperationType"]
128 n2vc_event
= n2vc_info
["n2vc_event"]
129 logging_text
= "Task ns={} {}={} [n2vc_callback] application={}".format(nsr_id
, ns_operation
, nslcmop_id
,
131 vca_deployed
= deployed
.get(application_name
)
133 self
.logger
.error(logging_text
+ " Not present at nsr._admin.deployed.VCA")
138 self
.logger
.debug(logging_text
+ " task Cancelled")
139 vca_deployed
['operational-status'] = "error"
140 db_nsr_update
["_admin.deployed.VCA.{}.operational-status".format(application_name
)] = "error"
141 vca_deployed
['detailed-status'] = "Task Cancelled"
142 db_nsr_update
["_admin.deployed.VCA.{}.detailed-status".format(application_name
)] = "Task Cancelled"
145 exc
= task
.exception()
147 self
.logger
.error(logging_text
+ " task Exception={}".format(exc
))
148 vca_deployed
['operational-status'] = "error"
149 db_nsr_update
["_admin.deployed.VCA.{}.operational-status".format(application_name
)] = "error"
150 vca_deployed
['detailed-status'] = str(exc
)
151 db_nsr_update
["_admin.deployed.VCA.{}.detailed-status".format(application_name
)] = str(exc
)
153 self
.logger
.debug(logging_text
+ " task Done")
154 # task is Done, but callback is still ongoing. So ignore
157 self
.logger
.debug(logging_text
+ " Enter status={}".format(status
))
158 if vca_deployed
['operational-status'] == status
:
159 return # same status, ignore
160 vca_deployed
['operational-status'] = status
161 db_nsr_update
["_admin.deployed.VCA.{}.operational-status".format(application_name
)] = status
162 vca_deployed
['detailed-status'] = str(message
)
163 db_nsr_update
["_admin.deployed.VCA.{}.detailed-status".format(application_name
)] = str(message
)
165 self
.logger
.critical(logging_text
+ " Enter with bad parameters", exc_info
=True)
167 # wake up instantiate task
169 except Exception as e
:
170 self
.logger
.critical(logging_text
+ " Exception {}".format(e
), exc_info
=True)
172 def ns_params_2_RO(self
, ns_params
, nsd
, vnfd_dict
):
174 Creates a RO ns descriptor from OSM ns_instantite params
175 :param ns_params: OSM instantiate params
176 :return: The RO ns descriptor
180 def vim_account_2_RO(vim_account
):
181 if vim_account
in vim_2_RO
:
182 return vim_2_RO
[vim_account
]
184 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_account
})
185 if db_vim
["_admin"]["operationalState"] != "ENABLED":
186 raise LcmException("VIM={} is not available. operationalState={}".format(
187 vim_account
, db_vim
["_admin"]["operationalState"]))
188 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
189 vim_2_RO
[vim_account
] = RO_vim_id
192 def ip_profile_2_RO(ip_profile
):
193 RO_ip_profile
= deepcopy((ip_profile
))
194 if "dns-server" in RO_ip_profile
:
195 if isinstance(RO_ip_profile
["dns-server"], list):
196 RO_ip_profile
["dns-address"] = []
197 for ds
in RO_ip_profile
.pop("dns-server"):
198 RO_ip_profile
["dns-address"].append(ds
['address'])
200 RO_ip_profile
["dns-address"] = RO_ip_profile
.pop("dns-server")
201 if RO_ip_profile
.get("ip-version") == "ipv4":
202 RO_ip_profile
["ip-version"] = "IPv4"
203 if RO_ip_profile
.get("ip-version") == "ipv6":
204 RO_ip_profile
["ip-version"] = "IPv6"
205 if "dhcp-params" in RO_ip_profile
:
206 RO_ip_profile
["dhcp"] = RO_ip_profile
.pop("dhcp-params")
212 # "name": ns_params["nsName"],
213 # "description": ns_params.get("nsDescription"),
214 "datacenter": vim_account_2_RO(ns_params
["vimAccountId"]),
215 # "scenario": ns_params["nsdId"],
219 if ns_params
.get("ssh-authorized-key"):
220 RO_ns_params
["cloud-config"] = {"key-pairs": ns_params
["ssh-authorized-key"]}
221 if ns_params
.get("vnf"):
222 for vnf_params
in ns_params
["vnf"]:
223 for constituent_vnfd
in nsd
["constituent-vnfd"]:
224 if constituent_vnfd
["member-vnf-index"] == vnf_params
["member-vnf-index"]:
225 vnf_descriptor
= vnfd_dict
[constituent_vnfd
["vnfd-id-ref"]]
228 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index={} is not present at nsd:"
229 "constituent-vnfd".format(vnf_params
["member-vnf-index"]))
230 RO_vnf
= {"vdus": {}, "networks": {}}
231 if vnf_params
.get("vimAccountId"):
232 RO_vnf
["datacenter"] = vim_account_2_RO(vnf_params
["vimAccountId"])
233 if vnf_params
.get("vdu"):
234 for vdu_params
in vnf_params
["vdu"]:
235 RO_vnf
["vdus"][vdu_params
["id"]] = {}
236 if vdu_params
.get("volume"):
237 RO_vnf
["vdus"][vdu_params
["id"]]["devices"] = {}
238 for volume_params
in vdu_params
["volume"]:
239 RO_vnf
["vdus"][vdu_params
["id"]]["devices"][volume_params
["name"]] = {}
240 if volume_params
.get("vim-volume-id"):
241 RO_vnf
["vdus"][vdu_params
["id"]]["devices"][volume_params
["name"]]["vim_id"] = \
242 volume_params
["vim-volume-id"]
243 if vdu_params
.get("interface"):
244 RO_vnf
["vdus"][vdu_params
["id"]]["interfaces"] = {}
245 for interface_params
in vdu_params
["interface"]:
247 RO_vnf
["vdus"][vdu_params
["id"]]["interfaces"][interface_params
["name"]] = RO_interface
248 if interface_params
.get("ip-address"):
249 RO_interface
["ip_address"] = interface_params
["ip-address"]
250 if interface_params
.get("mac-address"):
251 RO_interface
["mac_address"] = interface_params
["mac-address"]
252 if interface_params
.get("floating-ip-required"):
253 RO_interface
["floating-ip"] = interface_params
["floating-ip-required"]
254 if vnf_params
.get("internal-vld"):
255 for internal_vld_params
in vnf_params
["internal-vld"]:
256 RO_vnf
["networks"][internal_vld_params
["name"]] = {}
257 if internal_vld_params
.get("vim-network-name"):
258 RO_vnf
["networks"][internal_vld_params
["name"]]["vim-network-name"] = \
259 internal_vld_params
["vim-network-name"]
260 if internal_vld_params
.get("ip-profile"):
261 RO_vnf
["networks"][internal_vld_params
["name"]]["ip-profile"] = \
262 ip_profile_2_RO(internal_vld_params
["ip-profile"])
263 if internal_vld_params
.get("internal-connection-point"):
264 for icp_params
in internal_vld_params
["internal-connection-point"]:
267 for vdu_descriptor
in vnf_descriptor
["vdu"]:
268 for vdu_interface
in vdu_descriptor
["interface"]:
269 if vdu_interface
.get("internal-connection-point-ref") == icp_params
["id-ref"]:
270 RO_interface_update
= {}
271 if icp_params
.get("ip-address"):
272 RO_interface_update
["ip_address"] = icp_params
["ip-address"]
273 if icp_params
.get("mac-address"):
274 RO_interface_update
["mac_address"] = icp_params
["mac-address"]
275 if RO_interface_update
:
276 RO_vnf_update
= {"vdus": {vdu_descriptor
["id"]: {
277 "interfaces": {vdu_interface
["name"]: RO_interface_update
}}}}
278 deep_update(RO_vnf
, RO_vnf_update
)
284 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
285 "internal-vld:id-ref={} is not present at vnfd:internal-"
286 "connection-point".format(vnf_params
["member-vnf-index"],
287 icp_params
["id-ref"]))
289 if not RO_vnf
["vdus"]:
291 if not RO_vnf
["networks"]:
292 del RO_vnf
["networks"]
294 RO_ns_params
["vnfs"][vnf_params
["member-vnf-index"]] = RO_vnf
295 if ns_params
.get("vld"):
296 for vld_params
in ns_params
["vld"]:
298 if "ip-profile" in vld_params
:
299 RO_vld
["ip-profile"] = ip_profile_2_RO(vld_params
["ip-profile"])
300 if "vim-network-name" in vld_params
:
302 if isinstance(vld_params
["vim-network-name"], dict):
303 for vim_account
, vim_net
in vld_params
["vim-network-name"].items():
304 RO_vld
["sites"].append({
305 "netmap-use": vim_net
,
306 "datacenter": vim_account_2_RO(vim_account
)
308 else: # isinstance str
309 RO_vld
["sites"].append({"netmap-use": vld_params
["vim-network-name"]})
310 if "vnfd-connection-point-ref" in vld_params
:
311 for cp_params
in vld_params
["vnfd-connection-point-ref"]:
313 for constituent_vnfd
in nsd
["constituent-vnfd"]:
314 if constituent_vnfd
["member-vnf-index"] == cp_params
["member-vnf-index-ref"]:
315 vnf_descriptor
= vnfd_dict
[constituent_vnfd
["vnfd-id-ref"]]
319 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={} "
320 "is not present at nsd:constituent-vnfd".format(cp_params
["member-vnf-index-ref"]))
322 for vdu_descriptor
in vnf_descriptor
["vdu"]:
323 for interface_descriptor
in vdu_descriptor
["interface"]:
324 if interface_descriptor
.get("external-connection-point-ref") == \
325 cp_params
["vnfd-connection-point-ref"]:
332 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={}:"
333 "vnfd-connection-point-ref={} is not present at vnfd={}".format(
334 cp_params
["member-vnf-index-ref"],
335 cp_params
["vnfd-connection-point-ref"],
336 vnf_descriptor
["id"]))
338 if cp_params
.get("ip-address"):
339 RO_cp_params
["ip_address"] = cp_params
["ip-address"]
340 if cp_params
.get("mac-address"):
341 RO_cp_params
["mac_address"] = cp_params
["mac-address"]
344 cp_params
["member-vnf-index-ref"]: {
346 vdu_descriptor
["id"]: {
348 interface_descriptor
["name"]: RO_cp_params
354 deep_update(RO_ns_params
["vnfs"], RO_vnf_params
)
356 RO_ns_params
["networks"][vld_params
["name"]] = RO_vld
359 def ns_update_vnfr(self
, db_vnfrs
, nsr_desc_RO
):
361 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
366 for vnf_index
, db_vnfr
in db_vnfrs
.items():
367 for vnf_RO
in nsr_desc_RO
["vnfs"]:
368 if vnf_RO
["member_vnf_index"] == vnf_index
:
370 db_vnfr
["ip-address"] = vnfr_update
["ip-address"] = vnf_RO
.get("ip_address")
372 for vdur_RO
in vnf_RO
.get("vms", ()):
374 "vim-id": vdur_RO
.get("vim_vm_id"),
375 "ip-address": vdur_RO
.get("ip_address"),
376 "vdu-id-ref": vdur_RO
.get("vdu_osm_id"),
377 "name": vdur_RO
.get("vim_name"),
378 "status": vdur_RO
.get("status"),
379 "status-detailed": vdur_RO
.get("error_msg"),
383 for interface_RO
in vdur_RO
.get("interfaces", ()):
384 vdur
["interfaces"].append({
385 "ip-address": interface_RO
.get("ip_address"),
386 "mac-address": interface_RO
.get("mac_address"),
387 "name": interface_RO
.get("internal_name"),
389 vdur_list
.append(vdur
)
390 db_vnfr
["vdur"] = vnfr_update
["vdur"] = vdur_list
391 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
395 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} at RO info".format(vnf_index
))
397 async def create_monitoring(self
, nsr_id
, vnf_member_index
, vnfd_desc
):
398 if not vnfd_desc
.get("scaling-group-descriptor"):
400 for scaling_group
in vnfd_desc
["scaling-group-descriptor"]:
401 scaling_policy_desc
= {}
404 "scaling_group_descriptor": {
405 "name": scaling_group
["name"],
406 "scaling_policy": scaling_policy_desc
409 for scaling_policy
in scaling_group
.get("scaling-policy"):
410 scaling_policy_desc
["scale_in_operation_type"] = scaling_policy_desc
["scale_out_operation_type"] = \
411 scaling_policy
["scaling-type"]
412 scaling_policy_desc
["threshold_time"] = scaling_policy
["threshold-time"]
413 scaling_policy_desc
["cooldown_time"] = scaling_policy
["cooldown-time"]
414 scaling_policy_desc
["scaling_criteria"] = []
415 for scaling_criteria
in scaling_policy
.get("scaling-criteria"):
416 scaling_criteria_desc
= {"scale_in_threshold": scaling_criteria
.get("scale-in-threshold"),
417 "scale_out_threshold": scaling_criteria
.get("scale-out-threshold"),
419 if not scaling_criteria
.get("vnf-monitoring-param-ref"):
421 for monitoring_param
in vnfd_desc
.get("monitoring-param", ()):
422 if monitoring_param
["id"] == scaling_criteria
["vnf-monitoring-param-ref"]:
423 scaling_criteria_desc
["monitoring_param"] = {
424 "id": monitoring_param
["id"],
425 "name": monitoring_param
["name"],
426 "aggregation_type": monitoring_param
.get("aggregation-type"),
427 "vdu_name": monitoring_param
.get("vdu-ref"),
428 "vnf_member_index": vnf_member_index
,
431 scaling_policy_desc
["scaling_criteria"].append(scaling_criteria_desc
)
435 "Task ns={} member_vnf_index={} Invalid vnfd vnf-monitoring-param-ref={} not in "
436 "monitoring-param list".format(nsr_id
, vnf_member_index
,
437 scaling_criteria
["vnf-monitoring-param-ref"]))
439 await self
.msg
.aiowrite("lcm_pm", "configure_scaling", scaling_desc
, self
.loop
)
441 async def instantiate(self
, nsr_id
, nslcmop_id
):
442 logging_text
= "Task ns={} instantiate={} ".format(nsr_id
, nslcmop_id
)
443 self
.logger
.debug(logging_text
+ "Enter")
444 # get all needed from database
448 db_nslcmop_update
= {}
449 nslcmop_operation_state
= None
451 RO_descriptor_number
= 0 # number of descriptors created at RO
452 descriptor_id_2_RO
= {} # map between vnfd/nsd id to the id used at RO
456 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
457 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
458 step
= "Getting nsr={} from db".format(nsr_id
)
459 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
460 ns_params
= db_nsr
.get("instantiate_params")
462 nsr_name
= db_nsr
["name"] # TODO short-name??
464 vnfr_filter
= {"nsr-id-ref": nsr_id
, "member-vnf-index-ref": None}
465 for c_vnf
in nsd
["constituent-vnfd"]:
466 vnfd_id
= c_vnf
["vnfd-id-ref"]
467 vnfr_filter
["member-vnf-index-ref"] = c_vnf
["member-vnf-index"]
468 step
= "Getting vnfr={} of nsr={} from db".format(c_vnf
["member-vnf-index"], nsr_id
)
469 db_vnfrs
[c_vnf
["member-vnf-index"]] = self
.db
.get_one("vnfrs", vnfr_filter
)
470 if vnfd_id
not in needed_vnfd
:
471 step
= "Getting vnfd={} from db".format(vnfd_id
)
472 needed_vnfd
[vnfd_id
] = self
.db
.get_one("vnfds", {"id": vnfd_id
})
474 nsr_lcm
= db_nsr
["_admin"].get("deployed")
476 nsr_lcm
= db_nsr
["_admin"]["deployed"] = {
478 "RO": {"vnfd_id": {}, "nsd_id": None, "nsr_id": None, "nsr_status": "SCHEDULED"},
482 db_nsr_update
["detailed-status"] = "creating"
483 db_nsr_update
["operational-status"] = "init"
485 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
487 # get vnfds, instantiate at RO
488 for vnfd_id
, vnfd
in needed_vnfd
.items():
489 step
= db_nsr_update
["detailed-status"] = "Creating vnfd={} at RO".format(vnfd_id
)
490 # self.logger.debug(logging_text + step)
491 vnfd_id_RO
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, vnfd_id
[:23])
492 descriptor_id_2_RO
[vnfd_id
] = vnfd_id_RO
493 RO_descriptor_number
+= 1
496 vnfd_list
= await RO
.get_list("vnfd", filter_by
={"osm_id": vnfd_id_RO
})
498 db_nsr_update
["_admin.deployed.RO.vnfd_id.{}".format(vnfd_id
)] = vnfd_list
[0]["uuid"]
499 self
.logger
.debug(logging_text
+ "vnfd={} exists at RO. Using RO_id={}".format(
500 vnfd_id
, vnfd_list
[0]["uuid"]))
502 vnfd_RO
= self
.vnfd2RO(vnfd
, vnfd_id_RO
)
503 desc
= await RO
.create("vnfd", descriptor
=vnfd_RO
)
504 db_nsr_update
["_admin.deployed.RO.vnfd_id.{}".format(vnfd_id
)] = desc
["uuid"]
505 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
506 self
.logger
.debug(logging_text
+ "vnfd={} created at RO. RO_id={}".format(
507 vnfd_id
, desc
["uuid"]))
508 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
512 step
= db_nsr_update
["detailed-status"] = "Creating nsd={} at RO".format(nsd_id
)
513 # self.logger.debug(logging_text + step)
515 RO_osm_nsd_id
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, nsd_id
[:23])
516 descriptor_id_2_RO
[nsd_id
] = RO_osm_nsd_id
517 RO_descriptor_number
+= 1
518 nsd_list
= await RO
.get_list("nsd", filter_by
={"osm_id": RO_osm_nsd_id
})
520 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= nsd_list
[0]["uuid"]
521 self
.logger
.debug(logging_text
+ "nsd={} exists at RO. Using RO_id={}".format(
522 nsd_id
, RO_nsd_uuid
))
524 nsd_RO
= deepcopy(nsd
)
525 nsd_RO
["id"] = RO_osm_nsd_id
526 nsd_RO
.pop("_id", None)
527 nsd_RO
.pop("_admin", None)
528 for c_vnf
in nsd_RO
["constituent-vnfd"]:
529 vnfd_id
= c_vnf
["vnfd-id-ref"]
530 c_vnf
["vnfd-id-ref"] = descriptor_id_2_RO
[vnfd_id
]
531 desc
= await RO
.create("nsd", descriptor
=nsd_RO
)
532 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
533 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= desc
["uuid"]
534 self
.logger
.debug(logging_text
+ "nsd={} created at RO. RO_id={}".format(nsd_id
, RO_nsd_uuid
))
535 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
538 # if present use it unless in error status
539 RO_nsr_id
= db_nsr
["_admin"].get("deployed", {}).get("RO", {}).get("nsr_id")
542 step
= db_nsr_update
["detailed-status"] = "Looking for existing ns at RO"
543 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
544 desc
= await RO
.show("ns", RO_nsr_id
)
545 except ROclient
.ROClientException
as e
:
546 if e
.http_code
!= HTTPStatus
.NOT_FOUND
:
548 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
550 ns_status
, ns_status_info
= RO
.check_ns_status(desc
)
551 db_nsr_update
["_admin.deployed.RO.nsr_status"] = ns_status
552 if ns_status
== "ERROR":
553 step
= db_nsr_update
["detailed-status"] = "Deleting ns at RO. RO_ns_id={}".format(RO_nsr_id
)
554 self
.logger
.debug(logging_text
+ step
)
555 await RO
.delete("ns", RO_nsr_id
)
556 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
558 step
= db_nsr_update
["detailed-status"] = "Checking dependencies"
559 # self.logger.debug(logging_text + step)
561 # check if VIM is creating and wait look if previous tasks in process
562 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account", ns_params
["vimAccountId"])
564 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
565 self
.logger
.debug(logging_text
+ step
)
566 await asyncio
.wait(task_dependency
, timeout
=3600)
567 if ns_params
.get("vnf"):
568 for vnf
in ns_params
["vnf"]:
569 if "vimAccountId" in vnf
:
570 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account",
573 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
574 self
.logger
.debug(logging_text
+ step
)
575 await asyncio
.wait(task_dependency
, timeout
=3600)
577 step
= db_nsr_update
["detailed-status"] = "Checking instantiation parameters"
578 RO_ns_params
= self
.ns_params_2_RO(ns_params
, nsd
, needed_vnfd
)
579 step
= db_nsr_update
["detailed-status"] = "Creating ns at RO"
580 desc
= await RO
.create("ns", descriptor
=RO_ns_params
,
582 scenario
=RO_nsd_uuid
)
583 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = desc
["uuid"]
584 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
585 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "BUILD"
586 self
.logger
.debug(logging_text
+ "ns created at RO. RO_id={}".format(desc
["uuid"]))
587 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
589 # update VNFR vimAccount
590 step
= "Updating VNFR vimAcccount"
591 for vnf_index
, vnfr
in db_vnfrs
.items():
592 if vnfr
.get("vim-account-id"):
594 vnfr_update
= {"vim-account-id": db_nsr
["instantiate_params"]["vimAccountId"]}
595 if db_nsr
["instantiate_params"].get("vnf"):
596 for vnf_params
in db_nsr
["instantiate_params"]["vnf"]:
597 if vnf_params
.get("member-vnf-index") == vnf_index
:
598 if vnf_params
.get("vimAccountId"):
599 vnfr_update
["vim-account-id"] = vnf_params
.get("vimAccountId")
601 self
.update_db_2("vnfrs", vnfr
["_id"], vnfr_update
)
603 # wait until NS is ready
604 step
= ns_status_detailed
= detailed_status
= "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id
)
605 detailed_status_old
= None
606 self
.logger
.debug(logging_text
+ step
)
608 deployment_timeout
= 2 * 3600 # Two hours
609 while deployment_timeout
> 0:
610 desc
= await RO
.show("ns", RO_nsr_id
)
611 ns_status
, ns_status_info
= RO
.check_ns_status(desc
)
612 db_nsr_update
["admin.deployed.RO.nsr_status"] = ns_status
613 if ns_status
== "ERROR":
614 raise ROclient
.ROClientException(ns_status_info
)
615 elif ns_status
== "BUILD":
616 detailed_status
= ns_status_detailed
+ "; {}".format(ns_status_info
)
617 elif ns_status
== "ACTIVE":
618 step
= detailed_status
= "Waiting for management IP address reported by the VIM"
620 nsr_lcm
["nsr_ip"] = RO
.get_ns_vnf_info(desc
)
622 except ROclient
.ROClientException
as e
:
623 if e
.http_code
!= 409: # IP address is not ready return code is 409 CONFLICT
626 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
627 if detailed_status
!= detailed_status_old
:
628 detailed_status_old
= db_nsr_update
["detailed-status"] = detailed_status
629 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
630 await asyncio
.sleep(5, loop
=self
.loop
)
631 deployment_timeout
-= 5
632 if deployment_timeout
<= 0:
633 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
635 step
= "Updating VNFRs"
636 self
.ns_update_vnfr(db_vnfrs
, desc
)
638 db_nsr
["detailed-status"] = "Configuring vnfr"
639 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
641 # The parameters we'll need to deploy a charm
642 number_to_configure
= 0
644 def deploy(vnf_index
, vdu_id
, mgmt_ip_address
, n2vc_info
, config_primitive
=None):
645 """An inner function to deploy the charm from either vnf or vdu
646 vnf_index is mandatory. vdu_id can be None for a vnf configuration or the id for vdu configuration
648 if not mgmt_ip_address
:
649 raise LcmException("vnfd/vdu has not management ip address to configure it")
651 # if number_to_configure == 0:
652 # self.logger.debug("Logging into N2VC...")
653 # task = asyncio.ensure_future(self.n2vc.login())
654 # yield from asyncio.wait_for(task, 30.0)
655 # self.logger.debug("Logged into N2VC!")
657 # # await self.n2vc.login()
659 # Note: The charm needs to exist on disk at the location
660 # specified by charm_path.
661 base_folder
= vnfd
["_admin"]["storage"]
662 storage_params
= self
.fs
.get_params()
663 charm_path
= "{}{}/{}/charms/{}".format(
664 storage_params
["path"],
665 base_folder
["folder"],
666 base_folder
["pkg-dir"],
670 # Setup the runtime parameters for this VNF
671 params
= {'rw_mgmt_ip': mgmt_ip_address
}
673 params
["initial-config-primitive"] = config_primitive
675 # ns_name will be ignored in the current version of N2VC
676 # but will be implemented for the next point release.
677 model_name
= 'default'
681 application_name
= self
.n2vc
.FormatApplicationName(
686 if not nsr_lcm
.get("VCA"):
688 nsr_lcm
["VCA"][application_name
] = db_nsr_update
["_admin.deployed.VCA.{}".format(application_name
)] = {
689 "member-vnf-index": vnf_index
,
692 "application": application_name
,
693 "operational-status": "init",
694 "detailed-status": "",
697 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
699 self
.logger
.debug("Task create_ns={} Passing artifacts path '{}' for {}".format(nsr_id
, charm_path
,
702 n2vc_info
["nsr_id"] = nsr_id
703 n2vc_info
["nslcmop_id"] = nslcmop_id
704 n2vc_info
["n2vc_event"] = asyncio
.Event(loop
=self
.loop
)
705 n2vc_info
["lcmOperationType"] = "instantiate"
706 n2vc_info
["deployed"] = nsr_lcm
["VCA"]
707 n2vc_info
["db_update"] = db_nsr_update
708 task
= asyncio
.ensure_future(
709 self
.n2vc
.DeployCharms(
710 model_name
, # The network service name
711 application_name
, # The application name
712 vnfd
, # The vnf descriptor
713 charm_path
, # Path to charm
714 params
, # Runtime params, like mgmt ip
715 {}, # for native charms only
716 self
.n2vc_callback
, # Callback for status changes
717 n2vc_info
, # Callback parameter
718 None, # Callback parameter (task)
721 task
.add_done_callback(functools
.partial(self
.n2vc_callback
, model_name
, application_name
, None, None,
723 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "create_charm:" + application_name
, task
)
725 step
= "Looking for needed vnfd to configure"
726 self
.logger
.debug(logging_text
+ step
)
728 for c_vnf
in nsd
["constituent-vnfd"]:
729 vnfd_id
= c_vnf
["vnfd-id-ref"]
730 vnf_index
= str(c_vnf
["member-vnf-index"])
731 vnfd
= needed_vnfd
[vnfd_id
]
733 # Check if this VNF has a charm configuration
734 vnf_config
= vnfd
.get("vnf-configuration")
736 if vnf_config
and vnf_config
.get("juju"):
737 proxy_charm
= vnf_config
["juju"]["charm"]
738 config_primitive
= None
741 if 'initial-config-primitive' in vnf_config
:
742 config_primitive
= vnf_config
['initial-config-primitive']
744 # Login to the VCA. If there are multiple calls to login(),
745 # subsequent calls will be a nop and return immediately.
746 step
= "connecting to N2VC to configure vnf {}".format(vnf_index
)
747 await self
.n2vc
.login()
748 deploy(vnf_index
, None, db_vnfrs
[vnf_index
]["ip-address"], n2vc_info
, config_primitive
)
749 number_to_configure
+= 1
751 # Deploy charms for each VDU that supports one.
753 for vdu
in vnfd
['vdu']:
754 vdu_config
= vdu
.get('vdu-configuration')
756 config_primitive
= None
758 if vdu_config
and vdu_config
.get("juju"):
759 proxy_charm
= vdu_config
["juju"]["charm"]
761 if 'initial-config-primitive' in vdu_config
:
762 config_primitive
= vdu_config
['initial-config-primitive']
765 step
= "connecting to N2VC to configure vdu {} from vnf {}".format(vdu
["id"], vnf_index
)
766 await self
.n2vc
.login()
767 deploy(vnf_index
, vdu
["id"], db_vnfrs
[vnf_index
]["vdur"][vdu_index
]["ip-address"],
768 n2vc_info
, config_primitive
)
769 number_to_configure
+= 1
772 db_nsr_update
["operational-status"] = "running"
773 configuration_failed
= False
774 if number_to_configure
:
775 old_status
= "configuring: init: {}".format(number_to_configure
)
776 db_nsr_update
["config-status"] = old_status
777 db_nsr_update
["detailed-status"] = old_status
778 db_nslcmop_update
["detailed-status"] = old_status
780 # wait until all are configured.
783 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
784 if db_nslcmop_update
:
785 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
786 await n2vc_info
["n2vc_event"].wait()
787 n2vc_info
["n2vc_event"].clear()
790 n2vc_error_text
= [] # contain text error list. If empty no one is in error status
791 for _
, vca_info
in nsr_lcm
["VCA"].items():
792 vca_status
= vca_info
["operational-status"]
793 if vca_status
not in status_map
:
795 status_map
[vca_status
] = 0
796 status_map
[vca_status
] += 1
798 if vca_status
!= "active":
800 if vca_status
in ("error", "blocked"):
801 n2vc_error_text
.append(
802 "member_vnf_index={} vdu_id={} {}: {}".format(vca_info
["member-vnf-index"],
803 vca_info
["vdu_id"], vca_status
,
804 vca_info
["detailed-status"]))
808 elif n2vc_error_text
:
809 db_nsr_update
["config-status"] = "failed"
810 error_text
= "fail configuring " + ";".join(n2vc_error_text
)
811 db_nsr_update
["detailed-status"] = error_text
812 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED_TEMP"
813 db_nslcmop_update
["detailed-status"] = error_text
814 db_nslcmop_update
["statusEnteredTime"] = time()
815 configuration_failed
= True
820 for status
, num
in status_map
.items():
821 cs
+= separator
+ "{}: {}".format(status
, num
)
824 db_nsr_update
["config-status"] = cs
825 db_nsr_update
["detailed-status"] = cs
826 db_nslcmop_update
["detailed-status"] = cs
829 if not configuration_failed
:
831 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
832 db_nslcmop_update
["statusEnteredTime"] = time()
833 db_nslcmop_update
["detailed-status"] = "done"
834 db_nsr_update
["config-status"] = "configured"
835 db_nsr_update
["detailed-status"] = "done"
837 # step = "Sending monitoring parameters to PM"
838 # for c_vnf in nsd["constituent-vnfd"]:
839 # await self.create_monitoring(nsr_id, c_vnf["member-vnf-index"], needed_vnfd[c_vnf["vnfd-id-ref"]])
842 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
843 self
.logger
.error(logging_text
+ "Exit Exception while '{}': {}".format(step
, e
))
845 except asyncio
.CancelledError
:
846 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
847 exc
= "Operation was cancelled"
848 except Exception as e
:
849 exc
= traceback
.format_exc()
850 self
.logger
.critical(logging_text
+ "Exit Exception {} while '{}': {}".format(type(e
).__name
__, step
, e
),
855 db_nsr_update
["detailed-status"] = "ERROR {}: {}".format(step
, exc
)
856 db_nsr_update
["operational-status"] = "failed"
858 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
859 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
860 db_nslcmop_update
["statusEnteredTime"] = time()
862 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
863 if db_nslcmop_update
:
864 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
865 if nslcmop_operation_state
:
867 await self
.msg
.aiowrite("ns", "instantiated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
868 "operationState": nslcmop_operation_state
})
869 except Exception as e
:
870 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
872 self
.logger
.debug(logging_text
+ "Exit")
873 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_instantiate")
875 async def terminate(self
, nsr_id
, nslcmop_id
):
876 logging_text
= "Task ns={} terminate={} ".format(nsr_id
, nslcmop_id
)
877 self
.logger
.debug(logging_text
+ "Enter")
881 failed_detail
= [] # annotates all failed error messages
885 db_nslcmop_update
= {}
886 nslcmop_operation_state
= None
888 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
889 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
890 step
= "Getting nsr={} from db".format(nsr_id
)
891 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
892 # nsd = db_nsr["nsd"]
893 nsr_lcm
= deepcopy(db_nsr
["_admin"].get("deployed"))
894 if db_nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
897 # db_vim = self.db.get_one("vim_accounts", {"_id": db_nsr["datacenter"]})
898 # #TODO check if VIM is creating and wait
899 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
901 db_nsr_update
["operational-status"] = "terminating"
902 db_nsr_update
["config-status"] = "terminating"
904 if nsr_lcm
and nsr_lcm
.get("VCA"):
906 step
= "Scheduling configuration charms removing"
907 db_nsr_update
["detailed-status"] = "Deleting charms"
908 self
.logger
.debug(logging_text
+ step
)
909 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
910 for application_name
, deploy_info
in nsr_lcm
["VCA"].items():
911 if deploy_info
: # TODO it would be desirable having a and deploy_info.get("deployed"):
912 task
= asyncio
.ensure_future(
913 self
.n2vc
.RemoveCharms(
914 deploy_info
['model'],
916 # self.n2vc_callback,
921 vca_task_list
.append(task
)
922 vca_task_dict
[application_name
] = task
923 # task.add_done_callback(functools.partial(self.n2vc_callback, deploy_info['model'],
924 # deploy_info['application'], None, db_nsr,
925 # db_nslcmop, vnf_index))
926 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "delete_charm:" + application_name
, task
)
927 except Exception as e
:
928 self
.logger
.debug(logging_text
+ "Failed while deleting charms: {}".format(e
))
932 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
935 RO_nsr_id
= RO_delete_action
= None
936 if nsr_lcm
and nsr_lcm
.get("RO"):
937 RO_nsr_id
= nsr_lcm
["RO"].get("nsr_id")
938 RO_delete_action
= nsr_lcm
["RO"].get("nsr_delete_action_id")
941 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] = "Deleting ns at RO"
942 self
.logger
.debug(logging_text
+ step
)
943 desc
= await RO
.delete("ns", RO_nsr_id
)
944 RO_delete_action
= desc
["action_id"]
945 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = RO_delete_action
946 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
947 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
949 # wait until NS is deleted from VIM
950 step
= detailed_status
= "Waiting ns deleted from VIM. RO_id={}".format(RO_nsr_id
)
951 detailed_status_old
= None
952 self
.logger
.debug(logging_text
+ step
)
954 delete_timeout
= 20 * 60 # 20 minutes
955 while delete_timeout
> 0:
956 desc
= await RO
.show("ns", item_id_name
=RO_nsr_id
, extra_item
="action",
957 extra_item_id
=RO_delete_action
)
958 ns_status
, ns_status_info
= RO
.check_action_status(desc
)
959 if ns_status
== "ERROR":
960 raise ROclient
.ROClientException(ns_status_info
)
961 elif ns_status
== "BUILD":
962 detailed_status
= step
+ "; {}".format(ns_status_info
)
963 elif ns_status
== "ACTIVE":
966 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
967 await asyncio
.sleep(5, loop
=self
.loop
)
969 if detailed_status
!= detailed_status_old
:
970 detailed_status_old
= db_nslcmop_update
["detailed-status"] = detailed_status
971 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
972 else: # delete_timeout <= 0:
973 raise ROclient
.ROClientException("Timeout waiting ns deleted from VIM")
975 except ROclient
.ROClientException
as e
:
976 if e
.http_code
== 404: # not found
977 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
978 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
979 self
.logger
.debug(logging_text
+ "RO_ns_id={} already deleted".format(RO_nsr_id
))
980 elif e
.http_code
== 409: # conflict
981 failed_detail
.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id
, e
))
982 self
.logger
.debug(logging_text
+ failed_detail
[-1])
985 failed_detail
.append("RO_ns_id={} delete error: {}".format(RO_nsr_id
, e
))
986 self
.logger
.error(logging_text
+ failed_detail
[-1])
990 if not RO_fail
and nsr_lcm
and nsr_lcm
.get("RO") and nsr_lcm
["RO"].get("nsd_id"):
991 RO_nsd_id
= nsr_lcm
["RO"]["nsd_id"]
993 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
995 await RO
.delete("nsd", RO_nsd_id
)
996 self
.logger
.debug(logging_text
+ "RO_nsd_id={} deleted".format(RO_nsd_id
))
997 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
998 except ROclient
.ROClientException
as e
:
999 if e
.http_code
== 404: # not found
1000 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
1001 self
.logger
.debug(logging_text
+ "RO_nsd_id={} already deleted".format(RO_nsd_id
))
1002 elif e
.http_code
== 409: # conflict
1003 failed_detail
.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id
, e
))
1004 self
.logger
.debug(logging_text
+ failed_detail
[-1])
1007 failed_detail
.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id
, e
))
1008 self
.logger
.error(logging_text
+ failed_detail
[-1])
1011 if not RO_fail
and nsr_lcm
and nsr_lcm
.get("RO") and nsr_lcm
["RO"].get("vnfd_id"):
1012 for vnf_id
, RO_vnfd_id
in nsr_lcm
["RO"]["vnfd_id"].items():
1016 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
1017 "Deleting vnfd={} at RO".format(vnf_id
)
1018 await RO
.delete("vnfd", RO_vnfd_id
)
1019 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} deleted".format(RO_vnfd_id
))
1020 db_nsr_update
["_admin.deployed.RO.vnfd_id.{}".format(vnf_id
)] = None
1021 except ROclient
.ROClientException
as e
:
1022 if e
.http_code
== 404: # not found
1023 db_nsr_update
["_admin.deployed.RO.vnfd_id.{}".format(vnf_id
)] = None
1024 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} already deleted ".format(RO_vnfd_id
))
1025 elif e
.http_code
== 409: # conflict
1026 failed_detail
.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id
, e
))
1027 self
.logger
.debug(logging_text
+ failed_detail
[-1])
1029 failed_detail
.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id
, e
))
1030 self
.logger
.error(logging_text
+ failed_detail
[-1])
1033 db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
1034 "Waiting for deletion of configuration charms"
1035 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1036 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1037 await asyncio
.wait(vca_task_list
, timeout
=300)
1038 for application_name
, task
in vca_task_dict
.items():
1039 if task
.cancelled():
1040 failed_detail
.append("VCA[{}] Deletion has been cancelled".format(application_name
))
1042 exc
= task
.exception()
1044 failed_detail
.append("VCA[{}] Deletion exception: {}".format(application_name
, exc
))
1046 db_nsr_update
["_admin.deployed.VCA.{}".format(application_name
)] = None
1048 # TODO Should it be cancelled?!!
1050 failed_detail
.append("VCA[{}] Deletion timeout".format(application_name
))
1053 self
.logger
.error(logging_text
+ " ;".join(failed_detail
))
1054 db_nsr_update
["operational-status"] = "failed"
1055 db_nsr_update
["detailed-status"] = "Deletion errors " + "; ".join(failed_detail
)
1056 db_nslcmop_update
["detailed-status"] = "; ".join(failed_detail
)
1057 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
1058 db_nslcmop_update
["statusEnteredTime"] = time()
1059 elif db_nslcmop
["operationParams"].get("autoremove"):
1060 self
.db
.del_one("nsrs", {"_id": nsr_id
})
1061 db_nsr_update
.clear()
1062 self
.db
.del_list("nslcmops", {"nsInstanceId": nsr_id
})
1063 nslcmop_operation_state
= "COMPLETED"
1064 db_nslcmop_update
.clear()
1065 self
.db
.del_list("vnfrs", {"nsr-id-ref": nsr_id
})
1066 self
.logger
.debug(logging_text
+ "Delete from database")
1068 db_nsr_update
["operational-status"] = "terminated"
1069 db_nsr_update
["detailed-status"] = "Done"
1070 db_nsr_update
["_admin.nsState"] = "NOT_INSTANTIATED"
1071 db_nslcmop_update
["detailed-status"] = "Done"
1072 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
1073 db_nslcmop_update
["statusEnteredTime"] = time()
1075 except (ROclient
.ROClientException
, DbException
) as e
:
1076 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
1078 except asyncio
.CancelledError
:
1079 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1080 exc
= "Operation was cancelled"
1081 except Exception as e
:
1082 exc
= traceback
.format_exc()
1083 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
1085 if exc
and db_nslcmop
:
1086 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
1087 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
1088 db_nslcmop_update
["statusEnteredTime"] = time()
1089 if db_nslcmop_update
:
1090 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1092 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1093 if nslcmop_operation_state
:
1095 await self
.msg
.aiowrite("ns", "terminated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
1096 "operationState": nslcmop_operation_state
})
1097 except Exception as e
:
1098 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1099 self
.logger
.debug(logging_text
+ "Exit")
1100 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_terminate")
1102 async def _ns_execute_primitive(self
, db_deployed
, nsr_name
, member_vnf_index
, vdu_id
, primitive
, primitive_params
):
1104 vdu_id_text
= "vnfd"
1106 vdu_id_text
= vdu_id
1107 application_name
= self
.n2vc
.FormatApplicationName(
1112 vca_deployed
= db_deployed
["VCA"].get(application_name
)
1113 if not vca_deployed
:
1114 raise LcmException("charm for member_vnf_index={} vdu_id={} is not deployed".format(member_vnf_index
,
1116 model_name
= vca_deployed
.get("model")
1117 application_name
= vca_deployed
.get("application")
1118 if not model_name
or not application_name
:
1119 raise LcmException("charm for member_vnf_index={} is not properly deployed".format(member_vnf_index
))
1120 if vca_deployed
["operational-status"] != "active":
1121 raise LcmException("charm for member_vnf_index={} operational_status={} not 'active'".format(
1122 member_vnf_index
, vca_deployed
["operational-status"]))
1123 callback
= None # self.n2vc_callback
1124 callback_args
= () # [db_nsr, db_nslcmop, member_vnf_index, None]
1125 await self
.n2vc
.login()
1126 task
= asyncio
.ensure_future(
1127 self
.n2vc
.ExecutePrimitive(
1130 primitive
, callback
,
1135 # task.add_done_callback(functools.partial(self.n2vc_callback, model_name, application_name, None,
1136 # db_nsr, db_nslcmop, member_vnf_index))
1137 # self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "action:" + primitive, task)
1138 # wait until completed with timeout
1139 await asyncio
.wait((task
,), timeout
=600)
1141 result
= "FAILED" # by default
1143 if task
.cancelled():
1144 result_detail
= "Task has been cancelled"
1146 exc
= task
.exception()
1148 result_detail
= str(exc
)
1150 # TODO revise with Adam if action is finished and ok when task is done or callback is needed
1151 result
= "COMPLETED"
1152 result_detail
= "Done"
1154 # TODO Should it be cancelled?!!
1156 result_detail
= "timeout"
1157 return result
, result_detail
1159 async def action(self
, nsr_id
, nslcmop_id
):
1160 logging_text
= "Task ns={} action={} ".format(nsr_id
, nslcmop_id
)
1161 self
.logger
.debug(logging_text
+ "Enter")
1162 # get all needed from database
1165 db_nslcmop_update
= {}
1166 nslcmop_operation_state
= None
1169 step
= "Getting information from database"
1170 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1171 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1172 nsr_lcm
= db_nsr
["_admin"].get("deployed")
1173 nsr_name
= db_nsr
["name"]
1174 vnf_index
= db_nslcmop
["operationParams"]["member_vnf_index"]
1175 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
1177 # TODO check if ns is in a proper status
1178 primitive
= db_nslcmop
["operationParams"]["primitive"]
1179 primitive_params
= db_nslcmop
["operationParams"]["primitive_params"]
1180 result
, result_detail
= await self
._ns
_execute
_primitive
(nsr_lcm
, nsr_name
, vnf_index
, vdu_id
, primitive
,
1182 db_nslcmop_update
["detailed-status"] = result_detail
1183 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= result
1184 db_nslcmop_update
["statusEnteredTime"] = time()
1185 self
.logger
.debug(logging_text
+ " task Done with result {} {}".format(result
, result_detail
))
1186 return # database update is called inside finally
1188 except (DbException
, LcmException
) as e
:
1189 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
1191 except asyncio
.CancelledError
:
1192 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1193 exc
= "Operation was cancelled"
1194 except Exception as e
:
1195 exc
= traceback
.format_exc()
1196 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
1198 if exc
and db_nslcmop
:
1199 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
1200 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
1201 db_nslcmop_update
["statusEnteredTime"] = time()
1202 if db_nslcmop_update
:
1203 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1204 self
.logger
.debug(logging_text
+ "Exit")
1205 if nslcmop_operation_state
:
1207 await self
.msg
.aiowrite("ns", "actioned", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
1208 "operationState": nslcmop_operation_state
})
1209 except Exception as e
:
1210 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1211 self
.logger
.debug(logging_text
+ "Exit")
1212 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_action")
1214 async def scale(self
, nsr_id
, nslcmop_id
):
1215 logging_text
= "Task ns={} scale={} ".format(nsr_id
, nslcmop_id
)
1216 self
.logger
.debug(logging_text
+ "Enter")
1217 # get all needed from database
1220 db_nslcmop_update
= {}
1221 nslcmop_operation_state
= None
1224 # in case of error, indicates what part of scale was failed to put nsr at error status
1225 scale_process
= None
1227 step
= "Getting nslcmop from database"
1228 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1229 step
= "Getting nsr from database"
1230 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1231 step
= "Parsing scaling parameters"
1232 db_nsr_update
["operational-status"] = "scaling"
1233 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1234 nsr_lcm
= db_nsr
["_admin"].get("deployed")
1235 RO_nsr_id
= nsr_lcm
["RO"]["nsr_id"]
1236 vnf_index
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
1237 scaling_group
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1238 scaling_type
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleVnfType"]
1239 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
1241 step
= "Getting vnfr from database"
1242 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
1243 step
= "Getting vnfd from database"
1244 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
1245 step
= "Getting scaling-group-descriptor"
1246 for scaling_descriptor
in db_vnfd
["scaling-group-descriptor"]:
1247 if scaling_descriptor
["name"] == scaling_group
:
1250 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
1251 "at vnfd:scaling-group-descriptor".format(scaling_group
))
1253 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
1254 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
1255 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
1258 # TODO check if ns is in a proper status
1259 step
= "Sending scale order to RO"
1261 if not db_nsr
["_admin"].get("scaling-group"):
1262 self
.update_db_2("nsrs", nsr_id
, {"_admin.scaling-group": [{"name": scaling_group
, "nb-scale-op": 0}]})
1263 admin_scale_index
= 0
1265 for admin_scale_index
, admin_scale_info
in enumerate(db_nsr
["_admin"]["scaling-group"]):
1266 if admin_scale_info
["name"] == scaling_group
:
1267 nb_scale_op
= admin_scale_info
.get("nb-scale-op", 0)
1269 else: # not found, set index one plus last element and add new entry with the name
1270 admin_scale_index
+= 1
1271 db_nsr_update
["_admin.scaling-group.{}.name".format(admin_scale_index
)] = scaling_group
1272 RO_scaling_info
= []
1273 vdu_scaling_info
= {"scaling_group_name": scaling_group
, "vdu": []}
1274 if scaling_type
== "SCALE_OUT":
1275 # count if max-instance-count is reached
1276 if "max-instance-count" in scaling_descriptor
and scaling_descriptor
["max-instance-count"] is not None:
1277 max_instance_count
= int(scaling_descriptor
["max-instance-count"])
1278 if nb_scale_op
>= max_instance_count
:
1279 raise LcmException("reached the limit of {} (max-instance-count) scaling-out operations for the"
1280 " scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
1281 nb_scale_op
= nb_scale_op
+ 1
1282 vdu_scaling_info
["scaling_direction"] = "OUT"
1283 vdu_scaling_info
["vdu-create"] = {}
1284 for vdu_scale_info
in scaling_descriptor
["vdu"]:
1285 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
1286 "type": "create", "count": vdu_scale_info
.get("count", 1)})
1287 vdu_scaling_info
["vdu-create"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
1288 elif scaling_type
== "SCALE_IN":
1289 # count if min-instance-count is reached
1290 if "min-instance-count" in scaling_descriptor
and scaling_descriptor
["min-instance-count"] is not None:
1291 min_instance_count
= int(scaling_descriptor
["min-instance-count"])
1292 if nb_scale_op
<= min_instance_count
:
1293 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
1294 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
1295 nb_scale_op
= nb_scale_op
- 1
1296 vdu_scaling_info
["scaling_direction"] = "IN"
1297 vdu_scaling_info
["vdu-delete"] = {}
1298 for vdu_scale_info
in scaling_descriptor
["vdu"]:
1299 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
1300 "type": "delete", "count": vdu_scale_info
.get("count", 1)})
1301 vdu_scaling_info
["vdu-delete"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
1303 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
1304 if vdu_scaling_info
["scaling_direction"] == "IN":
1305 for vdur
in reversed(db_vnfr
["vdur"]):
1306 if vdu_scaling_info
["vdu-delete"].get(vdur
["vdu-id-ref"]):
1307 vdu_scaling_info
["vdu-delete"][vdur
["vdu-id-ref"]] -= 1
1308 vdu_scaling_info
["vdu"].append({
1309 "name": vdur
["name"],
1310 "vdu_id": vdur
["vdu-id-ref"],
1313 for interface
in vdur
["interfaces"]:
1314 vdu_scaling_info
["vdu"][-1]["interface"].append({
1315 "name": interface
["name"],
1316 "ip_address": interface
["ip-address"],
1317 "mac_address": interface
.get("mac-address"),
1319 del vdu_scaling_info
["vdu-delete"]
1321 # execute primitive service PRE-SCALING
1322 step
= "Executing pre-scale vnf-config-primitive"
1323 if scaling_descriptor
.get("scaling-config-action"):
1324 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
1325 if scaling_config_action
.get("trigger") and scaling_config_action
["trigger"] == "pre-scale-in" \
1326 and scaling_type
== "SCALE_IN":
1327 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
1328 step
= db_nslcmop_update
["detailed-status"] = \
1329 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive
)
1330 # look for primitive
1331 primitive_params
= {}
1332 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
1333 if config_primitive
["name"] == vnf_config_primitive
:
1334 for parameter
in config_primitive
.get("parameter", ()):
1335 if 'default-value' in parameter
and \
1336 parameter
['default-value'] == "<VDU_SCALE_INFO>":
1337 primitive_params
[parameter
["name"]] = yaml
.safe_dump(vdu_scaling_info
,
1338 default_flow_style
=True,
1343 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
1344 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-cnfiguration:config-"
1345 "primitive".format(scaling_group
, config_primitive
))
1346 scale_process
= "VCA"
1347 result
, result_detail
= await self
._ns
_execute
_primitive
(nsr_lcm
, vnf_index
,
1348 vnf_config_primitive
, primitive_params
)
1349 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
1350 vnf_config_primitive
, result
, result_detail
))
1351 if result
== "FAILED":
1352 raise LcmException(result_detail
)
1355 scale_process
= "RO"
1356 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
1357 RO_desc
= await RO
.create_action("ns", RO_nsr_id
, {"vdu-scaling": RO_scaling_info
})
1358 db_nsr_update
["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index
)] = nb_scale_op
1359 db_nsr_update
["_admin.scaling-group.{}.time".format(admin_scale_index
)] = time()
1360 # TODO mark db_nsr_update as scaling
1362 RO_nslcmop_id
= RO_desc
["instance_action_id"]
1363 db_nslcmop_update
["_admin.deploy.RO"] = RO_nslcmop_id
1365 RO_task_done
= False
1366 step
= detailed_status
= "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id
)
1367 detailed_status_old
= None
1368 self
.logger
.debug(logging_text
+ step
)
1370 deployment_timeout
= 1 * 3600 # One hour
1371 while deployment_timeout
> 0:
1372 if not RO_task_done
:
1373 desc
= await RO
.show("ns", item_id_name
=RO_nsr_id
, extra_item
="action",
1374 extra_item_id
=RO_nslcmop_id
)
1375 ns_status
, ns_status_info
= RO
.check_action_status(desc
)
1376 if ns_status
== "ERROR":
1377 raise ROclient
.ROClientException(ns_status_info
)
1378 elif ns_status
== "BUILD":
1379 detailed_status
= step
+ "; {}".format(ns_status_info
)
1380 elif ns_status
== "ACTIVE":
1382 step
= detailed_status
= "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id
)
1383 self
.logger
.debug(logging_text
+ step
)
1385 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
1387 desc
= await RO
.show("ns", RO_nsr_id
)
1388 ns_status
, ns_status_info
= RO
.check_ns_status(desc
)
1389 if ns_status
== "ERROR":
1390 raise ROclient
.ROClientException(ns_status_info
)
1391 elif ns_status
== "BUILD":
1392 detailed_status
= step
+ "; {}".format(ns_status_info
)
1393 elif ns_status
== "ACTIVE":
1394 step
= detailed_status
= "Waiting for management IP address reported by the VIM"
1396 desc
= await RO
.show("ns", RO_nsr_id
)
1397 nsr_lcm
["nsr_ip"] = RO
.get_ns_vnf_info(desc
)
1399 except ROclient
.ROClientException
as e
:
1400 if e
.http_code
!= 409: # IP address is not ready return code is 409 CONFLICT
1403 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
1404 if detailed_status
!= detailed_status_old
:
1405 detailed_status_old
= db_nslcmop_update
["detailed-status"] = detailed_status
1406 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1408 await asyncio
.sleep(5, loop
=self
.loop
)
1409 deployment_timeout
-= 5
1410 if deployment_timeout
<= 0:
1411 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
1413 step
= "Updating VNFRs"
1414 self
.ns_update_vnfr({db_vnfr
["member-vnf-index-ref"]: db_vnfr
}, desc
)
1416 # update VDU_SCALING_INFO with the obtained ip_addresses
1417 if vdu_scaling_info
["scaling_direction"] == "OUT":
1418 for vdur
in reversed(db_vnfr
["vdur"]):
1419 if vdu_scaling_info
["vdu-create"].get(vdur
["vdu-id-ref"]):
1420 vdu_scaling_info
["vdu-create"][vdur
["vdu-id-ref"]] -= 1
1421 vdu_scaling_info
["vdu"].append({
1422 "name": vdur
["name"],
1423 "vdu_id": vdur
["vdu-id-ref"],
1426 for interface
in vdur
["interfaces"]:
1427 vdu_scaling_info
["vdu"][-1]["interface"].append({
1428 "name": interface
["name"],
1429 "ip_address": interface
["ip-address"],
1430 "mac_address": interface
.get("mac-address"),
1432 del vdu_scaling_info
["vdu-create"]
1434 scale_process
= None
1436 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1438 # execute primitive service POST-SCALING
1439 step
= "Executing post-scale vnf-config-primitive"
1440 if scaling_descriptor
.get("scaling-config-action"):
1441 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
1442 if scaling_config_action
.get("trigger") and scaling_config_action
["trigger"] == "post-scale-out" \
1443 and scaling_type
== "SCALE_OUT":
1444 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
1445 step
= db_nslcmop_update
["detailed-status"] = \
1446 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive
)
1447 # look for primitive
1448 primitive_params
= {}
1449 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
1450 if config_primitive
["name"] == vnf_config_primitive
:
1451 for parameter
in config_primitive
.get("parameter", ()):
1452 if 'default-value' in parameter
and \
1453 parameter
['default-value'] == "<VDU_SCALE_INFO>":
1454 primitive_params
[parameter
["name"]] = yaml
.safe_dump(vdu_scaling_info
,
1455 default_flow_style
=True,
1459 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
1460 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
1461 "match any vnf-cnfiguration:config-primitive".format(scaling_group
,
1463 scale_process
= "VCA"
1464 result
, result_detail
= await self
._ns
_execute
_primitive
(nsr_lcm
, vnf_index
,
1465 vnf_config_primitive
, primitive_params
)
1466 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
1467 vnf_config_primitive
, result
, result_detail
))
1468 if result
== "FAILED":
1469 raise LcmException(result_detail
)
1471 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
1472 db_nslcmop_update
["statusEnteredTime"] = time()
1473 db_nslcmop_update
["detailed-status"] = "done"
1474 db_nsr_update
["detailed-status"] = "done"
1475 db_nsr_update
["operational-status"] = "running"
1477 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
1478 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
1480 except asyncio
.CancelledError
:
1481 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1482 exc
= "Operation was cancelled"
1483 except Exception as e
:
1484 exc
= traceback
.format_exc()
1485 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
1489 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
1490 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
1491 db_nslcmop_update
["statusEnteredTime"] = time()
1493 if scale_process
and "VCA" in scale_process
:
1494 db_nsr_update
["config-status"] = "failed"
1495 if scale_process
and "RO" in scale_process
:
1496 db_nsr_update
["operational-status"] = "failed"
1497 db_nsr_update
["detailed-status"] = "FAILED scaling nslcmop={} {}: {}".format(nslcmop_id
, step
, exc
)
1498 if db_nslcmop_update
:
1499 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1501 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1502 if nslcmop_operation_state
:
1504 await self
.msg
.aiowrite("ns", "scaled", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
1505 "operationState": nslcmop_operation_state
})
1507 # await asyncio.sleep(cooldown_time)
1508 # await self.msg.aiowrite("ns","scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
1509 except Exception as e
:
1510 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1511 self
.logger
.debug(logging_text
+ "Exit")
1512 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_scale")