1 # -*- coding: utf-8 -*-
4 # Copyright 2018 Telefonica S.A.
6 # Licensed under the Apache License, Version 2.0 (the "License"); you may
7 # not use this file except in compliance with the License. You may obtain
8 # a copy of the License at
10 # http://www.apache.org/licenses/LICENSE-2.0
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 # License for the specific language governing permissions and limitations
22 import logging
.handlers
25 from jinja2
import Environment
, Template
, meta
, TemplateError
, TemplateNotFound
, TemplateSyntaxError
28 from lcm_utils
import LcmException
, LcmExceptionNoMgmtIP
, LcmBase
30 from osm_common
.dbbase
import DbException
31 from osm_common
.fsbase
import FsException
32 from n2vc
.vnf
import N2VC
, N2VCPrimitiveExecutionFailed
, NetworkServiceDoesNotExist
34 from copy
import copy
, deepcopy
35 from http
import HTTPStatus
37 from uuid
import uuid4
39 __author__
= "Alfonso Tierno"
42 def get_iterable(in_dict
, in_key
):
44 Similar to <dict>.get(), but if value is None, False, ..., An empty tuple is returned instead
45 :param in_dict: a dictionary
46 :param in_key: the key to look for at in_dict
47 :return: in_dict[in_var] or () if it is None or not present
49 if not in_dict
.get(in_key
):
51 return in_dict
[in_key
]
54 def populate_dict(target_dict
, key_list
, value
):
56 Upate target_dict creating nested dictionaries with the key_list. Last key_list item is asigned the value.
57 Example target_dict={K: J}; key_list=[a,b,c]; target_dict will be {K: J, a: {b: {c: value}}}
58 :param target_dict: dictionary to be changed
59 :param key_list: list of keys to insert at target_dict
63 for key
in key_list
[0:-1]:
64 if key
not in target_dict
:
66 target_dict
= target_dict
[key
]
67 target_dict
[key_list
[-1]] = value
71 timeout_vca_on_error
= 5 * 60 # Time for charm from first time at blocked,error status to mark as failed
72 total_deploy_timeout
= 2 * 3600 # global timeout for deployment
73 timeout_charm_delete
= 10 * 60
74 timeout_primitive
= 10 * 60 # timeout for primitive execution
76 def __init__(self
, db
, msg
, fs
, lcm_tasks
, ro_config
, vca_config
, loop
):
78 Init, Connect to database, filesystem storage, and messaging
79 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
83 self
.logger
= logging
.getLogger('lcm.ns')
85 self
.lcm_tasks
= lcm_tasks
87 super().__init
__(db
, msg
, fs
, self
.logger
)
89 self
.ro_config
= ro_config
93 server
=vca_config
['host'],
94 port
=vca_config
['port'],
95 user
=vca_config
['user'],
96 secret
=vca_config
['secret'],
97 # TODO: This should point to the base folder where charms are stored,
98 # if there is a common one (like object storage). Otherwise, leave
99 # it unset and pass it via DeployCharms
100 # artifacts=vca_config[''],
102 juju_public_key
=vca_config
.get('pubkey'),
103 ca_cert
=vca_config
.get('cacert'),
106 def vnfd2RO(self
, vnfd
, new_id
=None, additionalParams
=None, nsrId
=None):
108 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
109 :param vnfd: input vnfd
110 :param new_id: overrides vnf id if provided
111 :param additionalParams: Instantiation params for VNFs provided
112 :param nsrId: Id of the NSR
113 :return: copy of vnfd
116 vnfd_RO
= deepcopy(vnfd
)
117 # remove unused by RO configuration, monitoring, scaling and internal keys
118 vnfd_RO
.pop("_id", None)
119 vnfd_RO
.pop("_admin", None)
120 vnfd_RO
.pop("vnf-configuration", None)
121 vnfd_RO
.pop("monitoring-param", None)
122 vnfd_RO
.pop("scaling-group-descriptor", None)
124 vnfd_RO
["id"] = new_id
126 # parse cloud-init or cloud-init-file with the provided variables using Jinja2
127 for vdu
in get_iterable(vnfd_RO
, "vdu"):
128 cloud_init_file
= None
129 if vdu
.get("cloud-init-file"):
130 base_folder
= vnfd
["_admin"]["storage"]
131 cloud_init_file
= "{}/{}/cloud_init/{}".format(base_folder
["folder"], base_folder
["pkg-dir"],
132 vdu
["cloud-init-file"])
133 with self
.fs
.file_open(cloud_init_file
, "r") as ci_file
:
134 cloud_init_content
= ci_file
.read()
135 vdu
.pop("cloud-init-file", None)
136 elif vdu
.get("cloud-init"):
137 cloud_init_content
= vdu
["cloud-init"]
142 ast
= env
.parse(cloud_init_content
)
143 mandatory_vars
= meta
.find_undeclared_variables(ast
)
145 for var
in mandatory_vars
:
146 if not additionalParams
or var
not in additionalParams
.keys():
147 raise LcmException("Variable '{}' defined at vnfd[id={}]:vdu[id={}]:cloud-init/cloud-init-"
148 "file, must be provided in the instantiation parameters inside the "
149 "'additionalParamsForVnf' block".format(var
, vnfd
["id"], vdu
["id"]))
150 template
= Template(cloud_init_content
)
151 cloud_init_content
= template
.render(additionalParams
or {})
152 vdu
["cloud-init"] = cloud_init_content
155 except FsException
as e
:
156 raise LcmException("Error reading vnfd[id={}]:vdu[id={}]:cloud-init-file={}: {}".
157 format(vnfd
["id"], vdu
["id"], cloud_init_file
, e
))
158 except (TemplateError
, TemplateNotFound
, TemplateSyntaxError
) as e
:
159 raise LcmException("Error parsing Jinja2 to cloud-init content at vnfd[id={}]:vdu[id={}]: {}".
160 format(vnfd
["id"], vdu
["id"], e
))
162 def n2vc_callback(self
, model_name
, application_name
, status
, message
, n2vc_info
, task
=None):
164 Callback both for charm status change and task completion
165 :param model_name: Charm model name
166 :param application_name: Charm application name
167 :param status: Can be
168 - blocked: The unit needs manual intervention
169 - maintenance: The unit is actively deploying/configuring
170 - waiting: The unit is waiting for another charm to be ready
171 - active: The unit is deployed, configured, and ready
172 - error: The charm has failed and needs attention.
173 - terminated: The charm has been destroyed
176 :param message: detailed message error
177 :param n2vc_info: dictionary with information shared with instantiate task. It contains:
180 lcmOperationType: currently "instantiate"
181 deployed: dictionary with {<application>: {operational-status: <status>, detailed-status: <text>}}
182 db_update: dictionary to be filled with the changes to be wrote to database with format key.key.key: value
183 n2vc_event: event used to notify instantiation task that some change has been produced
184 :param task: None for charm status change, or task for completion task callback
188 nsr_id
= n2vc_info
["nsr_id"]
189 deployed
= n2vc_info
["deployed"]
190 db_nsr_update
= n2vc_info
["db_update"]
191 nslcmop_id
= n2vc_info
["nslcmop_id"]
192 ns_operation
= n2vc_info
["lcmOperationType"]
193 n2vc_event
= n2vc_info
["n2vc_event"]
194 logging_text
= "Task ns={} {}={} [n2vc_callback] application={}".format(nsr_id
, ns_operation
, nslcmop_id
,
196 for vca_index
, vca_deployed
in enumerate(deployed
):
199 if model_name
== vca_deployed
["model"] and application_name
== vca_deployed
["application"]:
202 self
.logger
.error(logging_text
+ " Not present at nsr._admin.deployed.VCA. Received model_name={}".
207 self
.logger
.debug(logging_text
+ " task Cancelled")
208 vca_deployed
['operational-status'] = "error"
209 db_nsr_update
["_admin.deployed.VCA.{}.operational-status".format(vca_index
)] = "error"
210 vca_deployed
['detailed-status'] = "Task Cancelled"
211 db_nsr_update
["_admin.deployed.VCA.{}.detailed-status".format(vca_index
)] = "Task Cancelled"
214 exc
= task
.exception()
216 self
.logger
.error(logging_text
+ " task Exception={}".format(exc
))
217 vca_deployed
['operational-status'] = "error"
218 db_nsr_update
["_admin.deployed.VCA.{}.operational-status".format(vca_index
)] = "error"
219 vca_deployed
['detailed-status'] = str(exc
)
220 db_nsr_update
["_admin.deployed.VCA.{}.detailed-status".format(vca_index
)] = str(exc
)
222 self
.logger
.debug(logging_text
+ " task Done")
223 # task is Done, but callback is still ongoing. So ignore
226 self
.logger
.debug(logging_text
+ " Enter status={} message={}".format(status
, message
))
227 if vca_deployed
['operational-status'] == status
:
228 return # same status, ignore
229 vca_deployed
['operational-status'] = status
230 db_nsr_update
["_admin.deployed.VCA.{}.operational-status".format(vca_index
)] = status
231 vca_deployed
['detailed-status'] = str(message
)
232 db_nsr_update
["_admin.deployed.VCA.{}.detailed-status".format(vca_index
)] = str(message
)
234 self
.logger
.critical(logging_text
+ " Enter with bad parameters", exc_info
=True)
236 # wake up instantiate task
238 except Exception as e
:
239 self
.logger
.critical(logging_text
+ " Exception {}".format(e
), exc_info
=True)
241 def ns_params_2_RO(self
, ns_params
, nsd
, vnfd_dict
, n2vc_key_list
):
243 Creates a RO ns descriptor from OSM ns_instantiate params
244 :param ns_params: OSM instantiate params
245 :return: The RO ns descriptor
249 # TODO feature 1417: Check that no instantiation is set over PDU
250 # check if PDU forces a concrete vim-network-id and add it
251 # check if PDU contains a SDN-assist info (dpid, switch, port) and pass it to RO
253 def vim_account_2_RO(vim_account
):
254 if vim_account
in vim_2_RO
:
255 return vim_2_RO
[vim_account
]
257 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_account
})
258 if db_vim
["_admin"]["operationalState"] != "ENABLED":
259 raise LcmException("VIM={} is not available. operationalState={}".format(
260 vim_account
, db_vim
["_admin"]["operationalState"]))
261 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
262 vim_2_RO
[vim_account
] = RO_vim_id
265 def wim_account_2_RO(wim_account
):
266 if isinstance(wim_account
, str):
267 if wim_account
in wim_2_RO
:
268 return wim_2_RO
[wim_account
]
270 db_wim
= self
.db
.get_one("wim_accounts", {"_id": wim_account
})
271 if db_wim
["_admin"]["operationalState"] != "ENABLED":
272 raise LcmException("WIM={} is not available. operationalState={}".format(
273 wim_account
, db_wim
["_admin"]["operationalState"]))
274 RO_wim_id
= db_wim
["_admin"]["deployed"]["RO-account"]
275 wim_2_RO
[wim_account
] = RO_wim_id
280 def ip_profile_2_RO(ip_profile
):
281 RO_ip_profile
= deepcopy((ip_profile
))
282 if "dns-server" in RO_ip_profile
:
283 if isinstance(RO_ip_profile
["dns-server"], list):
284 RO_ip_profile
["dns-address"] = []
285 for ds
in RO_ip_profile
.pop("dns-server"):
286 RO_ip_profile
["dns-address"].append(ds
['address'])
288 RO_ip_profile
["dns-address"] = RO_ip_profile
.pop("dns-server")
289 if RO_ip_profile
.get("ip-version") == "ipv4":
290 RO_ip_profile
["ip-version"] = "IPv4"
291 if RO_ip_profile
.get("ip-version") == "ipv6":
292 RO_ip_profile
["ip-version"] = "IPv6"
293 if "dhcp-params" in RO_ip_profile
:
294 RO_ip_profile
["dhcp"] = RO_ip_profile
.pop("dhcp-params")
300 # "name": ns_params["nsName"],
301 # "description": ns_params.get("nsDescription"),
302 "datacenter": vim_account_2_RO(ns_params
["vimAccountId"]),
303 "wim_account": wim_account_2_RO(ns_params
.get("wimAccountId")),
304 # "scenario": ns_params["nsdId"],
307 for vnfd_ref
, vnfd
in vnfd_dict
.items():
308 vdu_needed_access
= []
310 if vnfd
.get("vnf-configuration"):
311 if vnfd
.get("mgmt-interface"):
312 if vnfd
["mgmt-interface"].get("vdu-id"):
313 vdu_needed_access
.append(vnfd
["mgmt-interface"]["vdu-id"])
314 elif vnfd
["mgmt-interface"].get("cp"):
315 mgmt_cp
= vnfd
["mgmt-interface"]["cp"]
317 for vdu
in vnfd
.get("vdu", ()):
318 if vdu
.get("vdu-configuration"):
319 vdu_needed_access
.append(vdu
["id"])
321 for vdu_interface
in vdu
.get("interface"):
322 if vdu_interface
.get("external-connection-point-ref") and \
323 vdu_interface
["external-connection-point-ref"] == mgmt_cp
:
324 vdu_needed_access
.append(vdu
["id"])
328 if vdu_needed_access
:
329 for vnf_member
in nsd
.get("constituent-vnfd"):
330 if vnf_member
["vnfd-id-ref"] != vnfd_ref
:
332 for vdu
in vdu_needed_access
:
333 populate_dict(RO_ns_params
,
334 ("vnfs", vnf_member
["member-vnf-index"], "vdus", vdu
, "mgmt_keys"),
337 if ns_params
.get("vduImage"):
338 RO_ns_params
["vduImage"] = ns_params
["vduImage"]
340 if ns_params
.get("ssh_keys"):
341 RO_ns_params
["cloud-config"] = {"key-pairs": ns_params
["ssh_keys"]}
342 for vnf_params
in get_iterable(ns_params
, "vnf"):
343 for constituent_vnfd
in nsd
["constituent-vnfd"]:
344 if constituent_vnfd
["member-vnf-index"] == vnf_params
["member-vnf-index"]:
345 vnf_descriptor
= vnfd_dict
[constituent_vnfd
["vnfd-id-ref"]]
348 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index={} is not present at nsd:"
349 "constituent-vnfd".format(vnf_params
["member-vnf-index"]))
350 if vnf_params
.get("vimAccountId"):
351 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "datacenter"),
352 vim_account_2_RO(vnf_params
["vimAccountId"]))
354 for vdu_params
in get_iterable(vnf_params
, "vdu"):
355 # TODO feature 1417: check that this VDU exist and it is not a PDU
356 if vdu_params
.get("volume"):
357 for volume_params
in vdu_params
["volume"]:
358 if volume_params
.get("vim-volume-id"):
359 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
360 vdu_params
["id"], "devices", volume_params
["name"], "vim_id"),
361 volume_params
["vim-volume-id"])
362 if vdu_params
.get("interface"):
363 for interface_params
in vdu_params
["interface"]:
364 if interface_params
.get("ip-address"):
365 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
366 vdu_params
["id"], "interfaces", interface_params
["name"],
368 interface_params
["ip-address"])
369 if interface_params
.get("mac-address"):
370 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
371 vdu_params
["id"], "interfaces", interface_params
["name"],
373 interface_params
["mac-address"])
374 if interface_params
.get("floating-ip-required"):
375 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
376 vdu_params
["id"], "interfaces", interface_params
["name"],
378 interface_params
["floating-ip-required"])
380 for internal_vld_params
in get_iterable(vnf_params
, "internal-vld"):
381 if internal_vld_params
.get("vim-network-name"):
382 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
383 internal_vld_params
["name"], "vim-network-name"),
384 internal_vld_params
["vim-network-name"])
385 if internal_vld_params
.get("vim-network-id"):
386 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
387 internal_vld_params
["name"], "vim-network-id"),
388 internal_vld_params
["vim-network-id"])
389 if internal_vld_params
.get("ip-profile"):
390 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
391 internal_vld_params
["name"], "ip-profile"),
392 ip_profile_2_RO(internal_vld_params
["ip-profile"]))
394 for icp_params
in get_iterable(internal_vld_params
, "internal-connection-point"):
397 for vdu_descriptor
in vnf_descriptor
["vdu"]:
398 for vdu_interface
in vdu_descriptor
["interface"]:
399 if vdu_interface
.get("internal-connection-point-ref") == icp_params
["id-ref"]:
400 if icp_params
.get("ip-address"):
401 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
402 vdu_descriptor
["id"], "interfaces",
403 vdu_interface
["name"], "ip_address"),
404 icp_params
["ip-address"])
406 if icp_params
.get("mac-address"):
407 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
408 vdu_descriptor
["id"], "interfaces",
409 vdu_interface
["name"], "mac_address"),
410 icp_params
["mac-address"])
416 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
417 "internal-vld:id-ref={} is not present at vnfd:internal-"
418 "connection-point".format(vnf_params
["member-vnf-index"],
419 icp_params
["id-ref"]))
421 for vld_params
in get_iterable(ns_params
, "vld"):
422 if "ip-profile" in vld_params
:
423 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "ip-profile"),
424 ip_profile_2_RO(vld_params
["ip-profile"]))
426 if "wimAccountId" in vld_params
and vld_params
["wimAccountId"] is not None:
427 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "wim_account"),
428 wim_account_2_RO(vld_params
["wimAccountId"])),
429 if vld_params
.get("vim-network-name"):
431 if isinstance(vld_params
["vim-network-name"], dict):
432 for vim_account
, vim_net
in vld_params
["vim-network-name"].items():
433 RO_vld_sites
.append({
434 "netmap-use": vim_net
,
435 "datacenter": vim_account_2_RO(vim_account
)
437 else: # isinstance str
438 RO_vld_sites
.append({"netmap-use": vld_params
["vim-network-name"]})
440 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "sites"), RO_vld_sites
)
441 if vld_params
.get("vim-network-id"):
443 if isinstance(vld_params
["vim-network-id"], dict):
444 for vim_account
, vim_net
in vld_params
["vim-network-id"].items():
445 RO_vld_sites
.append({
446 "netmap-use": vim_net
,
447 "datacenter": vim_account_2_RO(vim_account
)
449 else: # isinstance str
450 RO_vld_sites
.append({"netmap-use": vld_params
["vim-network-id"]})
452 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "sites"), RO_vld_sites
)
453 if vld_params
.get("ns-net"):
454 if isinstance(vld_params
["ns-net"], dict):
455 for vld_id
, instance_scenario_id
in vld_params
["ns-net"].items():
456 RO_vld_ns_net
= {"instance_scenario_id": instance_scenario_id
, "osm_id": vld_id
}
458 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "use-network"), RO_vld_ns_net
)
459 if "vnfd-connection-point-ref" in vld_params
:
460 for cp_params
in vld_params
["vnfd-connection-point-ref"]:
462 for constituent_vnfd
in nsd
["constituent-vnfd"]:
463 if constituent_vnfd
["member-vnf-index"] == cp_params
["member-vnf-index-ref"]:
464 vnf_descriptor
= vnfd_dict
[constituent_vnfd
["vnfd-id-ref"]]
468 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={} "
469 "is not present at nsd:constituent-vnfd".format(cp_params
["member-vnf-index-ref"]))
471 for vdu_descriptor
in vnf_descriptor
["vdu"]:
472 for interface_descriptor
in vdu_descriptor
["interface"]:
473 if interface_descriptor
.get("external-connection-point-ref") == \
474 cp_params
["vnfd-connection-point-ref"]:
481 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={}:"
482 "vnfd-connection-point-ref={} is not present at vnfd={}".format(
483 cp_params
["member-vnf-index-ref"],
484 cp_params
["vnfd-connection-point-ref"],
485 vnf_descriptor
["id"]))
486 if cp_params
.get("ip-address"):
487 populate_dict(RO_ns_params
, ("vnfs", cp_params
["member-vnf-index-ref"], "vdus",
488 vdu_descriptor
["id"], "interfaces",
489 interface_descriptor
["name"], "ip_address"),
490 cp_params
["ip-address"])
491 if cp_params
.get("mac-address"):
492 populate_dict(RO_ns_params
, ("vnfs", cp_params
["member-vnf-index-ref"], "vdus",
493 vdu_descriptor
["id"], "interfaces",
494 interface_descriptor
["name"], "mac_address"),
495 cp_params
["mac-address"])
498 def scale_vnfr(self
, db_vnfr
, vdu_create
=None, vdu_delete
=None):
499 # make a copy to do not change
500 vdu_create
= copy(vdu_create
)
501 vdu_delete
= copy(vdu_delete
)
503 vdurs
= db_vnfr
.get("vdur")
506 vdu_index
= len(vdurs
)
509 vdur
= vdurs
[vdu_index
]
510 if vdur
.get("pdu-type"):
512 vdu_id_ref
= vdur
["vdu-id-ref"]
513 if vdu_create
and vdu_create
.get(vdu_id_ref
):
514 for index
in range(0, vdu_create
[vdu_id_ref
]):
515 vdur
= deepcopy(vdur
)
516 vdur
["_id"] = str(uuid4())
517 vdur
["count-index"] += 1
518 vdurs
.insert(vdu_index
+1+index
, vdur
)
519 del vdu_create
[vdu_id_ref
]
520 if vdu_delete
and vdu_delete
.get(vdu_id_ref
):
522 vdu_delete
[vdu_id_ref
] -= 1
523 if not vdu_delete
[vdu_id_ref
]:
524 del vdu_delete
[vdu_id_ref
]
525 # check all operations are done
526 if vdu_create
or vdu_delete
:
527 raise LcmException("Error scaling OUT VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
530 raise LcmException("Error scaling IN VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
533 vnfr_update
= {"vdur": vdurs
}
534 db_vnfr
["vdur"] = vdurs
535 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
537 def ns_update_nsr(self
, ns_update_nsr
, db_nsr
, nsr_desc_RO
):
539 Updates database nsr with the RO info for the created vld
540 :param ns_update_nsr: dictionary to be filled with the updated info
541 :param db_nsr: content of db_nsr. This is also modified
542 :param nsr_desc_RO: nsr descriptor from RO
543 :return: Nothing, LcmException is raised on errors
546 for vld_index
, vld
in enumerate(get_iterable(db_nsr
, "vld")):
547 for net_RO
in get_iterable(nsr_desc_RO
, "nets"):
548 if vld
["id"] != net_RO
.get("ns_net_osm_id"):
550 vld
["vim-id"] = net_RO
.get("vim_net_id")
551 vld
["name"] = net_RO
.get("vim_name")
552 vld
["status"] = net_RO
.get("status")
553 vld
["status-detailed"] = net_RO
.get("error_msg")
554 ns_update_nsr
["vld.{}".format(vld_index
)] = vld
557 raise LcmException("ns_update_nsr: Not found vld={} at RO info".format(vld
["id"]))
559 def ns_update_vnfr(self
, db_vnfrs
, nsr_desc_RO
):
561 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
562 :param db_vnfrs: dictionary with member-vnf-index: vnfr-content
563 :param nsr_desc_RO: nsr descriptor from RO
564 :return: Nothing, LcmException is raised on errors
566 for vnf_index
, db_vnfr
in db_vnfrs
.items():
567 for vnf_RO
in nsr_desc_RO
["vnfs"]:
568 if vnf_RO
["member_vnf_index"] != vnf_index
:
571 if vnf_RO
.get("ip_address"):
572 db_vnfr
["ip-address"] = vnfr_update
["ip-address"] = vnf_RO
["ip_address"].split(";")[0]
573 elif not db_vnfr
.get("ip-address"):
574 raise LcmExceptionNoMgmtIP("ns member_vnf_index '{}' has no IP address".format(vnf_index
))
576 for vdu_index
, vdur
in enumerate(get_iterable(db_vnfr
, "vdur")):
577 vdur_RO_count_index
= 0
578 if vdur
.get("pdu-type"):
580 for vdur_RO
in get_iterable(vnf_RO
, "vms"):
581 if vdur
["vdu-id-ref"] != vdur_RO
["vdu_osm_id"]:
583 if vdur
["count-index"] != vdur_RO_count_index
:
584 vdur_RO_count_index
+= 1
586 vdur
["vim-id"] = vdur_RO
.get("vim_vm_id")
587 if vdur_RO
.get("ip_address"):
588 vdur
["ip-address"] = vdur_RO
["ip_address"].split(";")[0]
590 vdur
["ip-address"] = None
591 vdur
["vdu-id-ref"] = vdur_RO
.get("vdu_osm_id")
592 vdur
["name"] = vdur_RO
.get("vim_name")
593 vdur
["status"] = vdur_RO
.get("status")
594 vdur
["status-detailed"] = vdur_RO
.get("error_msg")
595 for ifacer
in get_iterable(vdur
, "interfaces"):
596 for interface_RO
in get_iterable(vdur_RO
, "interfaces"):
597 if ifacer
["name"] == interface_RO
.get("internal_name"):
598 ifacer
["ip-address"] = interface_RO
.get("ip_address")
599 ifacer
["mac-address"] = interface_RO
.get("mac_address")
602 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} interface={} "
603 "at RO info".format(vnf_index
, vdur
["vdu-id-ref"], ifacer
["name"]))
604 vnfr_update
["vdur.{}".format(vdu_index
)] = vdur
607 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} count_index={} at "
608 "RO info".format(vnf_index
, vdur
["vdu-id-ref"], vdur
["count-index"]))
610 for vld_index
, vld
in enumerate(get_iterable(db_vnfr
, "vld")):
611 for net_RO
in get_iterable(nsr_desc_RO
, "nets"):
612 if vld
["id"] != net_RO
.get("vnf_net_osm_id"):
614 vld
["vim-id"] = net_RO
.get("vim_net_id")
615 vld
["name"] = net_RO
.get("vim_name")
616 vld
["status"] = net_RO
.get("status")
617 vld
["status-detailed"] = net_RO
.get("error_msg")
618 vnfr_update
["vld.{}".format(vld_index
)] = vld
621 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vld={} at RO info".format(
622 vnf_index
, vld
["id"]))
624 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
628 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} at RO info".format(vnf_index
))
630 async def instantiate(self
, nsr_id
, nslcmop_id
):
631 logging_text
= "Task ns={} instantiate={} ".format(nsr_id
, nslcmop_id
)
632 self
.logger
.debug(logging_text
+ "Enter")
633 # get all needed from database
634 start_deploy
= time()
637 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
}
638 db_nslcmop_update
= {}
639 nslcmop_operation_state
= None
641 RO_descriptor_number
= 0 # number of descriptors created at RO
642 vnf_index_2_RO_id
= {} # map between vnfd/nsd id to the id used at RO
644 n2vc_key_list
= [] # list of public keys to be injected as authorized to VMs
647 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
648 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
649 step
= "Getting nsr={} from db".format(nsr_id
)
650 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
651 ns_params
= db_nslcmop
.get("operationParams")
653 nsr_name
= db_nsr
["name"] # TODO short-name??
655 # look if previous tasks in process
656 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("ns", nsr_id
, nslcmop_id
)
658 step
= db_nslcmop_update
["detailed-status"] = \
659 "Waiting for related tasks to be completed: {}".format(task_name
)
660 self
.logger
.debug(logging_text
+ step
)
661 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
662 _
, pending
= await asyncio
.wait(task_dependency
, timeout
=3600)
664 raise LcmException("Timeout waiting related tasks to be completed")
666 step
= "Getting vnfrs from db"
667 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
671 for vnfr
in db_vnfrs_list
:
672 db_vnfrs
[vnfr
["member-vnf-index-ref"]] = vnfr
673 vnfd_id
= vnfr
["vnfd-id"]
674 vnfd_ref
= vnfr
["vnfd-ref"]
675 if vnfd_id
not in db_vnfds
:
676 step
= "Getting vnfd={} id='{}' from db".format(vnfd_id
, vnfd_ref
)
677 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
678 db_vnfds_ref
[vnfd_ref
] = vnfd
679 db_vnfds
[vnfd_id
] = vnfd
680 db_vnfds_index
[vnfr
["member-vnf-index-ref"]] = db_vnfds
[vnfd_id
]
682 # Get or generates the _admin.deployed,VCA list
683 vca_deployed_list
= None
684 vca_model_name
= None
685 if db_nsr
["_admin"].get("deployed"):
686 vca_deployed_list
= db_nsr
["_admin"]["deployed"].get("VCA")
687 vca_model_name
= db_nsr
["_admin"]["deployed"].get("VCA-model-name")
688 if vca_deployed_list
is None:
689 vca_deployed_list
= []
690 db_nsr_update
["_admin.deployed.VCA"] = vca_deployed_list
691 populate_dict(db_nsr
, ("_admin", "deployed", "VCA"), vca_deployed_list
)
692 elif isinstance(vca_deployed_list
, dict):
693 # maintain backward compatibility. Change a dict to list at database
694 vca_deployed_list
= list(vca_deployed_list
.values())
695 db_nsr_update
["_admin.deployed.VCA"] = vca_deployed_list
696 populate_dict(db_nsr
, ("_admin", "deployed", "VCA"), vca_deployed_list
)
698 db_nsr_update
["detailed-status"] = "creating"
699 db_nsr_update
["operational-status"] = "init"
700 if not db_nsr
["_admin"].get("deployed") or not db_nsr
["_admin"]["deployed"].get("RO") or \
701 not db_nsr
["_admin"]["deployed"]["RO"].get("vnfd"):
702 populate_dict(db_nsr
, ("_admin", "deployed", "RO", "vnfd"), [])
703 db_nsr_update
["_admin.deployed.RO.vnfd"] = []
705 # set state to INSTANTIATED. When instantiated NBI will not delete directly
706 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
707 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
710 # The parameters we'll need to deploy a charm
711 number_to_configure
= 0
713 def deploy_charm(vnf_index
, vdu_id
, vdu_name
, vdu_count_index
, charm_params
, n2vc_info
, native_charm
=False):
714 """An inner function to deploy the charm from either ns, vnf or vdu
715 For ns both vnf_index and vdu_id are None.
716 For vnf only vdu_id is None
717 For vdu both vnf_index and vdu_id contain a value
719 # if not charm_params.get("rw_mgmt_ip") and vnf_index: # if NS skip mgmt_ip checking
720 # raise LcmException("ns/vnfd/vdu has not management ip address to configure it")
724 machine_spec
["username"] = charm_params
.get("username"),
725 machine_spec
["hostname"] = charm_params
.get("rw_mgmt_ip")
727 # Note: The charm needs to exist on disk at the location
728 # specified by charm_path.
729 descriptor
= vnfd
if vnf_index
else nsd
730 base_folder
= descriptor
["_admin"]["storage"]
731 storage_params
= self
.fs
.get_params()
732 charm_path
= "{}{}/{}/charms/{}".format(
733 storage_params
["path"],
734 base_folder
["folder"],
735 base_folder
["pkg-dir"],
739 # ns_name will be ignored in the current version of N2VC
740 # but will be implemented for the next point release.
742 vdu_id_text
= (str(vdu_id
) if vdu_id
else "") + "-"
743 vnf_index_text
= (str(vnf_index
) if vnf_index
else "") + "-"
744 application_name
= self
.n2vc
.FormatApplicationName(nsr_name
, vnf_index_text
, vdu_id_text
)
746 vca_index
= len(vca_deployed_list
)
747 # trunk name and add two char index at the end to ensure that it is unique. It is assumed no more than
748 # 26*26 charm in the same NS
749 application_name
= application_name
[0:48]
750 application_name
+= chr(97 + vca_index
// 26) + chr(97 + vca_index
% 26)
752 "member-vnf-index": vnf_index
,
755 "application": application_name
,
756 "operational-status": "init",
757 "detailed-status": "",
758 "step": "initial-deploy",
760 "vdu_name": vdu_name
,
761 "vdu_count_index": vdu_count_index
,
763 vca_deployed_list
.append(vca_deployed_
)
764 db_nsr_update
["_admin.deployed.VCA.{}".format(vca_index
)] = vca_deployed_
765 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
767 self
.logger
.debug("Task create_ns={} Passing artifacts path '{}' for {}".format(nsr_id
, charm_path
,
770 n2vc_info
["nsr_id"] = nsr_id
771 n2vc_info
["nslcmop_id"] = nslcmop_id
772 n2vc_info
["n2vc_event"] = asyncio
.Event(loop
=self
.loop
)
773 n2vc_info
["lcmOperationType"] = "instantiate"
774 n2vc_info
["deployed"] = vca_deployed_list
775 n2vc_info
["db_update"] = db_nsr_update
776 task
= asyncio
.ensure_future(
777 self
.n2vc
.DeployCharms(
778 model_name
, # The network service name
779 application_name
, # The application name
780 descriptor
, # The vnf/nsd descriptor
781 charm_path
, # Path to charm
782 charm_params
, # Runtime params, like mgmt ip
783 machine_spec
, # for native charms only
784 self
.n2vc_callback
, # Callback for status changes
785 n2vc_info
, # Callback parameter
786 None, # Callback parameter (task)
789 task
.add_done_callback(functools
.partial(self
.n2vc_callback
, model_name
, application_name
, None, None,
791 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "create_charm:" + application_name
, task
)
793 step
= "Looking for needed vnfd to configure with proxy charm"
794 self
.logger
.debug(logging_text
+ step
)
796 for c_vnf
in get_iterable(nsd
, "constituent-vnfd"):
797 vnfd_id
= c_vnf
["vnfd-id-ref"]
798 vnf_index
= str(c_vnf
["member-vnf-index"])
799 vnfd
= db_vnfds_ref
[vnfd_id
]
801 # Get additional parameters
803 if db_vnfrs
[vnf_index
].get("additionalParamsForVnf"):
804 vnfr_params
= db_vnfrs
[vnf_index
]["additionalParamsForVnf"].copy()
805 for k
, v
in vnfr_params
.items():
806 if isinstance(v
, str) and v
.startswith("!!yaml "):
807 vnfr_params
[k
] = yaml
.safe_load(v
[7:])
809 step
= "deploying proxy charms for configuration"
810 # Check if this VNF has a charm configuration
811 vnf_config
= vnfd
.get("vnf-configuration")
812 if vnf_config
and vnf_config
.get("juju"):
813 proxy_charm
= vnf_config
["juju"]["charm"]
814 if vnf_config
["juju"].get("proxy") is False:
815 # native_charm, will be deployed after VM. Skip
819 if not vca_model_name
:
820 step
= "creating VCA model name '{}'".format(nsr_id
)
821 self
.logger
.debug(logging_text
+ step
)
822 await self
.n2vc
.CreateNetworkService(nsr_id
)
823 vca_model_name
= nsr_id
824 db_nsr_update
["_admin.deployed.VCA-model-name"] = nsr_id
825 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
826 step
= "deploying proxy charm to configure vnf {}".format(vnf_index
)
827 vnfr_params
["rw_mgmt_ip"] = db_vnfrs
[vnf_index
]["ip-address"]
829 "user_values": vnfr_params
,
830 "rw_mgmt_ip": db_vnfrs
[vnf_index
]["ip-address"],
831 "initial-config-primitive": {} # vnf_config.get('initial-config-primitive') or {}
834 # Login to the VCA. If there are multiple calls to login(),
835 # subsequent calls will be a nop and return immediately.
836 await self
.n2vc
.login()
838 deploy_charm(vnf_index
, None, None, None, charm_params
, n2vc_info
)
839 number_to_configure
+= 1
841 # Deploy charms for each VDU that supports one.
842 for vdu_index
, vdu
in enumerate(get_iterable(vnfd
, 'vdu')):
843 vdu_config
= vdu
.get('vdu-configuration')
846 if vdu_config
and vdu_config
.get("juju"):
847 proxy_charm
= vdu_config
["juju"]["charm"]
848 if vdu_config
["juju"].get("proxy") is False:
849 # native_charm, will be deployed after VM. Skip
853 if not vca_model_name
:
854 step
= "creating VCA model name"
855 await self
.n2vc
.CreateNetworkService(nsr_id
)
856 vca_model_name
= nsr_id
857 db_nsr_update
["_admin.deployed.VCA-model-name"] = nsr_id
858 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
859 step
= "deploying proxy charm to configure member_vnf_index={} vdu={}".format(vnf_index
,
861 await self
.n2vc
.login()
862 vdur
= db_vnfrs
[vnf_index
]["vdur"][vdu_index
]
863 # TODO for the moment only first vdu_id contains a charm deployed
864 if vdur
["vdu-id-ref"] != vdu
["id"]:
865 raise LcmException("Mismatch vdur {}, vdu {} at index {} for member_vnf_index={}"
866 .format(vdur
["vdu-id-ref"], vdu
["id"], vdu_index
, vnf_index
))
867 vnfr_params
["rw_mgmt_ip"] = vdur
["ip-address"]
869 "user_values": vnfr_params
,
870 "rw_mgmt_ip": vdur
["ip-address"],
871 "initial-config-primitive": {} # vdu_config.get('initial-config-primitive') or {}
873 deploy_charm(vnf_index
, vdu
["id"], vdur
.get("name"), vdur
["count-index"],
874 charm_params
, n2vc_info
)
875 number_to_configure
+= 1
877 # Check if this NS has a charm configuration
879 ns_config
= nsd
.get("ns-configuration")
880 if ns_config
and ns_config
.get("juju"):
881 proxy_charm
= ns_config
["juju"]["charm"]
882 if ns_config
["juju"].get("proxy") is False:
883 # native_charm, will be deployed after VM. Skip
887 step
= "deploying proxy charm to configure ns"
888 # TODO is NS magmt IP address needed?
890 # Get additional parameters
891 additional_params
= {}
892 if db_nsr
.get("additionalParamsForNs"):
893 additional_params
= db_nsr
["additionalParamsForNs"].copy()
894 for k
, v
in additional_params
.items():
895 if isinstance(v
, str) and v
.startswith("!!yaml "):
896 additional_params
[k
] = yaml
.safe_load(v
[7:])
898 # additional_params["rw_mgmt_ip"] = db_nsr["ip-address"]
900 "user_values": additional_params
,
901 # "rw_mgmt_ip": db_nsr["ip-address"],
902 "initial-config-primitive": {} # ns_config.get('initial-config-primitive') or {}
905 # Login to the VCA. If there are multiple calls to login(),
906 # subsequent calls will be a nop and return immediately.
907 await self
.n2vc
.login()
908 deploy_charm(None, None, None, None, charm_params
, n2vc_info
)
909 number_to_configure
+= 1
911 db_nsr_update
["operational-status"] = "running"
913 # Wait until all charms has reached blocked or active status
914 step
= "waiting proxy charms to be ready"
915 if number_to_configure
:
916 # wait until all charms are configured.
921 # retry-get-ssh-public-key
922 # ssh-public-key-obtained
923 while time() <= start_deploy
+ self
.total_deploy_timeout
:
925 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
926 if db_nslcmop_update
:
927 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
930 for vca_index
, vca_deployed
in enumerate(vca_deployed_list
):
931 database_entry
= "_admin.deployed.VCA.{}.".format(vca_index
)
932 if vca_deployed
["step"] == "initial-deploy":
933 if vca_deployed
["operational-status"] in ("active", "blocked"):
934 step
= "execute charm primitive get-ssh-public-key for member_vnf_index={} vdu_id={}" \
935 .format(vca_deployed
["member-vnf-index"],
936 vca_deployed
["vdu_id"])
937 self
.logger
.debug(logging_text
+ step
)
938 primitive_id
= await self
.n2vc
.ExecutePrimitive(
939 vca_deployed
["model"],
940 vca_deployed
["application"],
941 "get-ssh-public-key",
944 vca_deployed
["step"] = db_nsr_update
[database_entry
+ "step"] = "get-ssh-public-key"
945 vca_deployed
["primitive_id"] = db_nsr_update
[database_entry
+ "primitive_id"] =\
947 db_nsr_update
[database_entry
+ "operational-status"] =\
948 vca_deployed
["operational-status"]
949 elif vca_deployed
["step"] in ("get-ssh-public-key", "retry-get-ssh-public-key"):
950 primitive_id
= vca_deployed
["primitive_id"]
951 primitive_status
= await self
.n2vc
.GetPrimitiveStatus(vca_deployed
["model"],
953 if primitive_status
in ("completed", "failed"):
954 primitive_result
= await self
.n2vc
.GetPrimitiveOutput(vca_deployed
["model"],
956 vca_deployed
["primitive_id"] = db_nsr_update
[database_entry
+ "primitive_id"] = None
957 if primitive_status
== "completed" and isinstance(primitive_result
, dict) and \
958 primitive_result
.get("pubkey"):
959 ssh_public_key
= primitive_result
.get("pubkey")
960 vca_deployed
["step"] = db_nsr_update
[database_entry
+ "step"] =\
961 "ssh-public-key-obtained"
962 vca_deployed
["ssh-public-key"] = db_nsr_update
[database_entry
+ "ssh-public-key"] =\
964 n2vc_key_list
.append(ssh_public_key
)
965 step
= "charm ssh-public-key for member_vnf_index={} vdu_id={} is '{}'".format(
966 vca_deployed
["member-vnf-index"], vca_deployed
["vdu_id"], ssh_public_key
)
967 self
.logger
.debug(logging_text
+ step
)
968 else: # primitive_status == "failed":
969 if vca_deployed
["step"] == "get-ssh-public-key":
970 step
= "execute charm primitive generate-ssh-public-key for member_vnf_index="\
971 "{} vdu_id={}".format(vca_deployed
["member-vnf-index"],
972 vca_deployed
["vdu_id"])
973 self
.logger
.debug(logging_text
+ step
)
974 vca_deployed
["step"] = db_nsr_update
[database_entry
+ "step"] =\
976 primitive_id
= await self
.n2vc
.ExecutePrimitive(
977 vca_deployed
["model"],
978 vca_deployed
["application"],
982 vca_deployed
["primitive_id"] = db_nsr_update
[database_entry
+ "primitive_id"] =\
984 else: # failed for second time
986 "error executing primitive get-ssh-public-key: {}".format(primitive_result
))
988 elif vca_deployed
["step"] == "generate-ssh-key":
989 primitive_id
= vca_deployed
["primitive_id"]
990 primitive_status
= await self
.n2vc
.GetPrimitiveStatus(vca_deployed
["model"],
992 if primitive_status
in ("completed", "failed"):
993 primitive_result
= await self
.n2vc
.GetPrimitiveOutput(vca_deployed
["model"],
995 vca_deployed
["primitive_id"] = db_nsr_update
[
996 database_entry
+ "primitive_id"] = None
997 if primitive_status
== "completed":
998 step
= "execute primitive get-ssh-public-key again for member_vnf_index={} "\
999 "vdu_id={}".format(vca_deployed
["member-vnf-index"],
1000 vca_deployed
["vdu_id"])
1001 self
.logger
.debug(logging_text
+ step
)
1002 vca_deployed
["step"] = db_nsr_update
[database_entry
+ "step"] = \
1003 "retry-get-ssh-public-key"
1004 primitive_id
= await self
.n2vc
.ExecutePrimitive(
1005 vca_deployed
["model"],
1006 vca_deployed
["application"],
1007 "get-ssh-public-key",
1010 vca_deployed
["primitive_id"] = db_nsr_update
[database_entry
+ "primitive_id"] =\
1013 else: # primitive_status == "failed":
1014 raise LcmException("error executing primitive generate-ssh-key: {}"
1015 .format(primitive_result
))
1017 if vca_deployed
["step"] != "ssh-public-key-obtained":
1022 await asyncio
.sleep(5)
1023 else: # total_deploy_timeout
1024 raise LcmException("Timeout waiting charm to be initialized for member_vnf_index={} vdu_id={}"
1025 .format(vca_deployed
["member-vnf-index"], vca_deployed
["vdu_id"]))
1028 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
1029 # get vnfds, instantiate at RO
1030 for c_vnf
in nsd
.get("constituent-vnfd", ()):
1031 member_vnf_index
= c_vnf
["member-vnf-index"]
1032 vnfd
= db_vnfds_ref
[c_vnf
['vnfd-id-ref']]
1033 vnfd_ref
= vnfd
["id"]
1034 step
= db_nsr_update
["detailed-status"] = "Creating vnfd='{}' member_vnf_index='{}' at RO".format(
1035 vnfd_ref
, member_vnf_index
)
1036 # self.logger.debug(logging_text + step)
1037 vnfd_id_RO
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, member_vnf_index
[:23])
1038 vnf_index_2_RO_id
[member_vnf_index
] = vnfd_id_RO
1039 RO_descriptor_number
+= 1
1041 # look position at deployed.RO.vnfd if not present it will be appended at the end
1042 for index
, vnf_deployed
in enumerate(db_nsr
["_admin"]["deployed"]["RO"]["vnfd"]):
1043 if vnf_deployed
["member-vnf-index"] == member_vnf_index
:
1046 index
= len(db_nsr
["_admin"]["deployed"]["RO"]["vnfd"])
1047 db_nsr
["_admin"]["deployed"]["RO"]["vnfd"].append(None)
1050 RO_update
= {"member-vnf-index": member_vnf_index
}
1051 vnfd_list
= await RO
.get_list("vnfd", filter_by
={"osm_id": vnfd_id_RO
})
1053 RO_update
["id"] = vnfd_list
[0]["uuid"]
1054 self
.logger
.debug(logging_text
+ "vnfd='{}' member_vnf_index='{}' exists at RO. Using RO_id={}".
1055 format(vnfd_ref
, member_vnf_index
, vnfd_list
[0]["uuid"]))
1057 vnfd_RO
= self
.vnfd2RO(vnfd
, vnfd_id_RO
, db_vnfrs
[c_vnf
["member-vnf-index"]].
1058 get("additionalParamsForVnf"), nsr_id
)
1059 desc
= await RO
.create("vnfd", descriptor
=vnfd_RO
)
1060 RO_update
["id"] = desc
["uuid"]
1061 self
.logger
.debug(logging_text
+ "vnfd='{}' member_vnf_index='{}' created at RO. RO_id={}".format(
1062 vnfd_ref
, member_vnf_index
, desc
["uuid"]))
1063 db_nsr_update
["_admin.deployed.RO.vnfd.{}".format(index
)] = RO_update
1064 db_nsr
["_admin"]["deployed"]["RO"]["vnfd"][index
] = RO_update
1065 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1069 step
= db_nsr_update
["detailed-status"] = "Creating nsd={} at RO".format(nsd_ref
)
1070 # self.logger.debug(logging_text + step)
1072 RO_osm_nsd_id
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, nsd_ref
[:23])
1073 RO_descriptor_number
+= 1
1074 nsd_list
= await RO
.get_list("nsd", filter_by
={"osm_id": RO_osm_nsd_id
})
1076 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= nsd_list
[0]["uuid"]
1077 self
.logger
.debug(logging_text
+ "nsd={} exists at RO. Using RO_id={}".format(
1078 nsd_ref
, RO_nsd_uuid
))
1080 nsd_RO
= deepcopy(nsd
)
1081 nsd_RO
["id"] = RO_osm_nsd_id
1082 nsd_RO
.pop("_id", None)
1083 nsd_RO
.pop("_admin", None)
1084 for c_vnf
in nsd_RO
.get("constituent-vnfd", ()):
1085 member_vnf_index
= c_vnf
["member-vnf-index"]
1086 c_vnf
["vnfd-id-ref"] = vnf_index_2_RO_id
[member_vnf_index
]
1087 for c_vld
in nsd_RO
.get("vld", ()):
1088 for cp
in c_vld
.get("vnfd-connection-point-ref", ()):
1089 member_vnf_index
= cp
["member-vnf-index-ref"]
1090 cp
["vnfd-id-ref"] = vnf_index_2_RO_id
[member_vnf_index
]
1092 desc
= await RO
.create("nsd", descriptor
=nsd_RO
)
1093 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1094 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= desc
["uuid"]
1095 self
.logger
.debug(logging_text
+ "nsd={} created at RO. RO_id={}".format(nsd_ref
, RO_nsd_uuid
))
1096 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1099 # if present use it unless in error status
1100 RO_nsr_id
= db_nsr
["_admin"].get("deployed", {}).get("RO", {}).get("nsr_id")
1103 step
= db_nsr_update
["detailed-status"] = "Looking for existing ns at RO"
1104 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
1105 desc
= await RO
.show("ns", RO_nsr_id
)
1106 except ROclient
.ROClientException
as e
:
1107 if e
.http_code
!= HTTPStatus
.NOT_FOUND
:
1109 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1111 ns_status
, ns_status_info
= RO
.check_ns_status(desc
)
1112 db_nsr_update
["_admin.deployed.RO.nsr_status"] = ns_status
1113 if ns_status
== "ERROR":
1114 step
= db_nsr_update
["detailed-status"] = "Deleting ns at RO. RO_ns_id={}".format(RO_nsr_id
)
1115 self
.logger
.debug(logging_text
+ step
)
1116 await RO
.delete("ns", RO_nsr_id
)
1117 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1119 step
= db_nsr_update
["detailed-status"] = "Checking dependencies"
1120 # self.logger.debug(logging_text + step)
1122 # check if VIM is creating and wait look if previous tasks in process
1123 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account", ns_params
["vimAccountId"])
1125 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
1126 self
.logger
.debug(logging_text
+ step
)
1127 await asyncio
.wait(task_dependency
, timeout
=3600)
1128 if ns_params
.get("vnf"):
1129 for vnf
in ns_params
["vnf"]:
1130 if "vimAccountId" in vnf
:
1131 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account",
1132 vnf
["vimAccountId"])
1134 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
1135 self
.logger
.debug(logging_text
+ step
)
1136 await asyncio
.wait(task_dependency
, timeout
=3600)
1138 step
= db_nsr_update
["detailed-status"] = "Checking instantiation parameters"
1140 # feature 1429. Add n2vc public key to needed VMs
1141 n2vc_key
= await self
.n2vc
.GetPublicKey()
1142 n2vc_key_list
.append(n2vc_key
)
1143 RO_ns_params
= self
.ns_params_2_RO(ns_params
, nsd
, db_vnfds_ref
, n2vc_key_list
)
1145 step
= db_nsr_update
["detailed-status"] = "Creating ns at RO"
1146 desc
= await RO
.create("ns", descriptor
=RO_ns_params
,
1147 name
=db_nsr
["name"],
1148 scenario
=RO_nsd_uuid
)
1149 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = desc
["uuid"]
1150 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1151 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "BUILD"
1152 self
.logger
.debug(logging_text
+ "ns created at RO. RO_id={}".format(desc
["uuid"]))
1153 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1155 # wait until NS is ready
1156 step
= ns_status_detailed
= detailed_status
= "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id
)
1157 detailed_status_old
= None
1158 self
.logger
.debug(logging_text
+ step
)
1160 while time() <= start_deploy
+ self
.total_deploy_timeout
:
1161 desc
= await RO
.show("ns", RO_nsr_id
)
1162 ns_status
, ns_status_info
= RO
.check_ns_status(desc
)
1163 db_nsr_update
["_admin.deployed.RO.nsr_status"] = ns_status
1164 if ns_status
== "ERROR":
1165 raise ROclient
.ROClientException(ns_status_info
)
1166 elif ns_status
== "BUILD":
1167 detailed_status
= ns_status_detailed
+ "; {}".format(ns_status_info
)
1168 elif ns_status
== "ACTIVE":
1169 step
= detailed_status
= "Waiting for management IP address reported by the VIM. Updating VNFRs"
1171 self
.ns_update_vnfr(db_vnfrs
, desc
)
1173 except LcmExceptionNoMgmtIP
:
1176 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
1177 if detailed_status
!= detailed_status_old
:
1178 detailed_status_old
= db_nsr_update
["detailed-status"] = detailed_status
1179 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1180 await asyncio
.sleep(5, loop
=self
.loop
)
1181 else: # total_deploy_timeout
1182 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
1184 step
= "Updating NSR"
1185 self
.ns_update_nsr(db_nsr_update
, db_nsr
, desc
)
1187 db_nsr_update
["operational-status"] = "running"
1188 db_nsr
["detailed-status"] = "Configuring vnfr"
1189 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1191 # Configure proxy charms once VMs are up
1192 for vca_index
, vca_deployed
in enumerate(vca_deployed_list
):
1193 vnf_index
= vca_deployed
.get("member-vnf-index")
1194 vdu_id
= vca_deployed
.get("vdu_id")
1196 vdu_count_index
= None
1198 step
= "executing proxy charm initial primitives for member_vnf_index={} vdu_id={}".format(vnf_index
,
1201 initial_config_primitive_list
= []
1203 if db_vnfrs
[vnf_index
].get("additionalParamsForVnf"):
1204 add_params
= db_vnfrs
[vnf_index
]["additionalParamsForVnf"].copy()
1205 vnfd
= db_vnfds_index
[vnf_index
]
1208 for vdu_index
, vdu
in enumerate(get_iterable(vnfd
, 'vdu')):
1209 if vdu
["id"] == vdu_id
:
1210 initial_config_primitive_list
= vdu
['vdu-configuration'].get(
1211 'initial-config-primitive', ())
1214 raise LcmException("Not found vdu_id={} at vnfd:vdu".format(vdu_id
))
1215 vdur
= db_vnfrs
[vnf_index
]["vdur"][vdu_index
]
1216 # TODO for the moment only first vdu_id contains a charm deployed
1217 if vdur
["vdu-id-ref"] != vdu
["id"]:
1218 raise LcmException("Mismatch vdur {}, vdu {} at index {} for vnf {}"
1219 .format(vdur
["vdu-id-ref"], vdu
["id"], vdu_index
, vnf_index
))
1220 add_params
["rw_mgmt_ip"] = vdur
["ip-address"]
1222 add_params
["rw_mgmt_ip"] = db_vnfrs
[vnf_index
]["ip-address"]
1223 initial_config_primitive_list
= vnfd
["vnf-configuration"].get('initial-config-primitive', ())
1225 if db_nsr
.get("additionalParamsForNs"):
1226 add_params
= db_nsr
["additionalParamsForNs"].copy()
1227 for k
, v
in add_params
.items():
1228 if isinstance(v
, str) and v
.startswith("!!yaml "):
1229 add_params
[k
] = yaml
.safe_load(v
[7:])
1230 add_params
["rw_mgmt_ip"] = None
1232 # add primitive verify-ssh-credentials to the list after config only when is a vnf or vdu charm
1233 initial_config_primitive_list
= initial_config_primitive_list
.copy()
1234 if initial_config_primitive_list
and vnf_index
:
1235 initial_config_primitive_list
.insert(1, {"name": "verify-ssh-credentials", "paramter": []})
1237 for initial_config_primitive
in initial_config_primitive_list
:
1238 primitive_result
, primitive_detail
= await self
._ns
_execute
_primitive
(
1239 db_nsr
["_admin"]["deployed"], vnf_index
, vdu_id
, vdu_name
, vdu_count_index
,
1240 initial_config_primitive
["name"],
1241 self
._map
_primitive
_params
(initial_config_primitive
, {}, add_params
))
1242 if primitive_result
!= "COMPLETED":
1243 raise LcmException("charm error executing primitive {} for member_vnf_index={} vdu_id={}: '{}'"
1244 .format(initial_config_primitive
["name"], vca_deployed
["member-vnf-index"],
1245 vca_deployed
["vdu_id"], primitive_detail
))
1247 # Deploy native charms
1248 step
= "Looking for needed vnfd to configure with native charm"
1249 self
.logger
.debug(logging_text
+ step
)
1251 for c_vnf
in get_iterable(nsd
, "constituent-vnfd"):
1252 vnfd_id
= c_vnf
["vnfd-id-ref"]
1253 vnf_index
= str(c_vnf
["member-vnf-index"])
1254 vnfd
= db_vnfds_ref
[vnfd_id
]
1256 # Get additional parameters
1258 if db_vnfrs
[vnf_index
].get("additionalParamsForVnf"):
1259 vnfr_params
= db_vnfrs
[vnf_index
]["additionalParamsForVnf"].copy()
1260 for k
, v
in vnfr_params
.items():
1261 if isinstance(v
, str) and v
.startswith("!!yaml "):
1262 vnfr_params
[k
] = yaml
.safe_load(v
[7:])
1264 # Check if this VNF has a charm configuration
1265 vnf_config
= vnfd
.get("vnf-configuration")
1266 if vnf_config
and vnf_config
.get("juju"):
1267 native_charm
= vnf_config
["juju"].get("proxy") is False
1270 if not vca_model_name
:
1271 step
= "creating VCA model name '{}'".format(nsr_id
)
1272 self
.logger
.debug(logging_text
+ step
)
1273 await self
.n2vc
.CreateNetworkService(nsr_id
)
1274 vca_model_name
= nsr_id
1275 db_nsr_update
["_admin.deployed.VCA-model-name"] = nsr_id
1276 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1277 step
= "deploying native charm for vnf_member_index={}".format(vnf_index
)
1278 vnfr_params
["rw_mgmt_ip"] = db_vnfrs
[vnf_index
]["ip-address"]
1280 "user_values": vnfr_params
,
1281 "rw_mgmt_ip": db_vnfrs
[vnf_index
]["ip-address"],
1282 "initial-config-primitive": vnf_config
.get('initial-config-primitive') or {},
1286 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1287 # merged. Meanwhile let's get username from initial-config-primitive
1288 if vnf_config
.get("initial-config-primitive"):
1289 for param
in vnf_config
["initial-config-primitive"][0].get("parameter", ()):
1290 if param
["name"] == "ssh-username":
1291 charm_params
["username"] = param
["value"]
1292 if vnf_config
.get("config-access") and vnf_config
["config-access"].get("ssh-access"):
1293 if vnf_config
["config-access"]["ssh-access"].get("required"):
1294 charm_params
["username"] = vnf_config
["config-access"]["ssh-access"].get("default-user")
1296 # Login to the VCA. If there are multiple calls to login(),
1297 # subsequent calls will be a nop and return immediately.
1298 await self
.n2vc
.login()
1300 deploy_charm(vnf_index
, None, None, None, charm_params
, n2vc_info
, native_charm
)
1301 number_to_configure
+= 1
1303 # Deploy charms for each VDU that supports one.
1304 for vdu_index
, vdu
in enumerate(get_iterable(vnfd
, 'vdu')):
1305 vdu_config
= vdu
.get('vdu-configuration')
1306 native_charm
= False
1308 if vdu_config
and vdu_config
.get("juju"):
1309 native_charm
= vdu_config
["juju"].get("proxy") is False
1312 if not vca_model_name
:
1313 step
= "creating VCA model name"
1314 await self
.n2vc
.CreateNetworkService(nsr_id
)
1315 vca_model_name
= nsr_id
1316 db_nsr_update
["_admin.deployed.VCA-model-name"] = nsr_id
1317 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1318 step
= "deploying native charm for vnf_member_index={} vdu_id={}".format(vnf_index
,
1320 await self
.n2vc
.login()
1321 vdur
= db_vnfrs
[vnf_index
]["vdur"][vdu_index
]
1322 # TODO for the moment only first vdu_id contains a charm deployed
1323 if vdur
["vdu-id-ref"] != vdu
["id"]:
1324 raise LcmException("Mismatch vdur {}, vdu {} at index {} for vnf {}"
1325 .format(vdur
["vdu-id-ref"], vdu
["id"], vdu_index
, vnf_index
))
1326 vnfr_params
["rw_mgmt_ip"] = vdur
["ip-address"]
1328 "user_values": vnfr_params
,
1329 "rw_mgmt_ip": vdur
["ip-address"],
1330 "initial-config-primitive": vdu_config
.get('initial-config-primitive') or {}
1334 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1335 # merged. Meanwhile let's get username from initial-config-primitive
1336 if vdu_config
.get("initial-config-primitive"):
1337 for param
in vdu_config
["initial-config-primitive"][0].get("parameter", ()):
1338 if param
["name"] == "ssh-username":
1339 charm_params
["username"] = param
["value"]
1340 if vdu_config
.get("config-access") and vdu_config
["config-access"].get("ssh-access"):
1341 if vdu_config
["config-access"]["ssh-access"].get("required"):
1342 charm_params
["username"] = vdu_config
["config-access"]["ssh-access"].get(
1345 deploy_charm(vnf_index
, vdu
["id"], vdur
.get("name"), vdur
["count-index"],
1346 charm_params
, n2vc_info
, native_charm
)
1347 number_to_configure
+= 1
1349 # Check if this NS has a charm configuration
1351 ns_config
= nsd
.get("ns-configuration")
1352 if ns_config
and ns_config
.get("juju"):
1353 native_charm
= ns_config
["juju"].get("proxy") is False
1356 step
= "deploying native charm to configure ns"
1357 # TODO is NS magmt IP address needed?
1359 # Get additional parameters
1360 additional_params
= {}
1361 if db_nsr
.get("additionalParamsForNs"):
1362 additional_params
= db_nsr
["additionalParamsForNs"].copy()
1363 for k
, v
in additional_params
.items():
1364 if isinstance(v
, str) and v
.startswith("!!yaml "):
1365 additional_params
[k
] = yaml
.safe_load(v
[7:])
1367 # additional_params["rw_mgmt_ip"] = db_nsr["ip-address"]
1369 "user_values": additional_params
,
1370 "rw_mgmt_ip": db_nsr
.get("ip-address"),
1371 "initial-config-primitive": ns_config
.get('initial-config-primitive') or {}
1375 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1376 # merged. Meanwhile let's get username from initial-config-primitive
1377 if ns_config
.get("initial-config-primitive"):
1378 for param
in ns_config
["initial-config-primitive"][0].get("parameter", ()):
1379 if param
["name"] == "ssh-username":
1380 charm_params
["username"] = param
["value"]
1381 if ns_config
.get("config-access") and ns_config
["config-access"].get("ssh-access"):
1382 if ns_config
["config-access"]["ssh-access"].get("required"):
1383 charm_params
["username"] = ns_config
["config-access"]["ssh-access"].get("default-user")
1385 # Login to the VCA. If there are multiple calls to login(),
1386 # subsequent calls will be a nop and return immediately.
1387 await self
.n2vc
.login()
1388 deploy_charm(None, None, None, None, charm_params
, n2vc_info
, native_charm
)
1389 number_to_configure
+= 1
1391 # waiting all charms are ok
1392 configuration_failed
= False
1393 if number_to_configure
:
1394 old_status
= "configuring: init: {}".format(number_to_configure
)
1395 db_nsr_update
["config-status"] = old_status
1396 db_nsr_update
["detailed-status"] = old_status
1397 db_nslcmop_update
["detailed-status"] = old_status
1399 # wait until all are configured.
1400 while time() <= start_deploy
+ self
.total_deploy_timeout
:
1402 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1403 if db_nslcmop_update
:
1404 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1405 # TODO add a fake task that set n2vc_event after some time
1406 await n2vc_info
["n2vc_event"].wait()
1407 n2vc_info
["n2vc_event"].clear()
1410 n2vc_error_text
= [] # contain text error list. If empty no one is in error status
1412 for vca_deployed
in vca_deployed_list
:
1413 vca_status
= vca_deployed
["operational-status"]
1414 if vca_status
not in status_map
:
1416 status_map
[vca_status
] = 0
1417 status_map
[vca_status
] += 1
1419 if vca_status
== "active":
1420 vca_deployed
.pop("time_first_error", None)
1421 vca_deployed
.pop("status_first_error", None)
1425 if vca_status
in ("error", "blocked"):
1426 vca_deployed
["detailed-status-error"] = vca_deployed
["detailed-status"]
1427 # if not first time in this status error
1428 if not vca_deployed
.get("time_first_error"):
1429 vca_deployed
["time_first_error"] = now
1431 if vca_deployed
.get("time_first_error") and \
1432 now
<= vca_deployed
["time_first_error"] + self
.timeout_vca_on_error
:
1433 n2vc_error_text
.append("member_vnf_index={} vdu_id={} {}: {}"
1434 .format(vca_deployed
["member-vnf-index"],
1435 vca_deployed
["vdu_id"], vca_status
,
1436 vca_deployed
["detailed-status-error"]))
1440 elif n2vc_error_text
:
1441 db_nsr_update
["config-status"] = "failed"
1442 error_text
= "fail configuring " + ";".join(n2vc_error_text
)
1443 db_nsr_update
["detailed-status"] = error_text
1444 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED_TEMP"
1445 db_nslcmop_update
["detailed-status"] = error_text
1446 db_nslcmop_update
["statusEnteredTime"] = time()
1447 configuration_failed
= True
1450 cs
= "configuring: "
1452 for status
, num
in status_map
.items():
1453 cs
+= separator
+ "{}: {}".format(status
, num
)
1455 if old_status
!= cs
:
1456 db_nsr_update
["config-status"] = cs
1457 db_nsr_update
["detailed-status"] = cs
1458 db_nslcmop_update
["detailed-status"] = cs
1460 else: # total_deploy_timeout
1461 raise LcmException("Timeout waiting ns to be configured")
1463 if not configuration_failed
:
1465 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
1466 db_nslcmop_update
["statusEnteredTime"] = time()
1467 db_nslcmop_update
["detailed-status"] = "done"
1468 db_nsr_update
["config-status"] = "configured"
1469 db_nsr_update
["detailed-status"] = "done"
1473 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
1474 self
.logger
.error(logging_text
+ "Exit Exception while '{}': {}".format(step
, e
))
1476 except asyncio
.CancelledError
:
1477 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1478 exc
= "Operation was cancelled"
1479 except Exception as e
:
1480 exc
= traceback
.format_exc()
1481 self
.logger
.critical(logging_text
+ "Exit Exception {} while '{}': {}".format(type(e
).__name
__, step
, e
),
1486 db_nsr_update
["detailed-status"] = "ERROR {}: {}".format(step
, exc
)
1487 db_nsr_update
["operational-status"] = "failed"
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()
1494 db_nsr_update
["_admin.nslcmop"] = None
1495 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1496 if db_nslcmop_update
:
1497 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1498 except DbException
as e
:
1499 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
1500 if nslcmop_operation_state
:
1502 await self
.msg
.aiowrite("ns", "instantiated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
1503 "operationState": nslcmop_operation_state
},
1505 except Exception as e
:
1506 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1508 self
.logger
.debug(logging_text
+ "Exit")
1509 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_instantiate")
1511 async def _destroy_charm(self
, model
, application
):
1513 Order N2VC destroy a charm
1516 :return: True if charm does not exist. False if it exist
1518 if not await self
.n2vc
.HasApplication(model
, application
):
1519 return True # Already removed
1520 await self
.n2vc
.RemoveCharms(model
, application
)
1523 async def _wait_charm_destroyed(self
, model
, application
, timeout
):
1525 Wait until charm does not exist
1529 :return: True if not exist, False if timeout
1532 if not await self
.n2vc
.HasApplication(model
, application
):
1536 await asyncio
.sleep(10)
1539 # Check if this VNFD has a configured terminate action
1540 def _has_terminate_config_primitive(self
, vnfd
):
1541 vnf_config
= vnfd
.get("vnf-configuration")
1542 if vnf_config
and vnf_config
.get("terminate-config-primitive"):
1547 # Get a numerically sorted list of the sequences for this VNFD's terminate action
1548 def _get_terminate_config_primitive_seq_list(self
, vnfd
):
1549 # No need to check for existing primitive twice, already done before
1550 vnf_config
= vnfd
.get("vnf-configuration")
1551 seq_list
= vnf_config
.get("terminate-config-primitive")
1552 # Get all 'seq' tags in seq_list, order sequences numerically, ascending.
1553 seq_list_sorted
= sorted(seq_list
, key
=lambda x
: int(x
['seq']))
1554 return seq_list_sorted
1557 def _create_nslcmop(nsr_id
, operation
, params
):
1559 Creates a ns-lcm-opp content to be stored at database.
1560 :param nsr_id: internal id of the instance
1561 :param operation: instantiate, terminate, scale, action, ...
1562 :param params: user parameters for the operation
1563 :return: dictionary following SOL005 format
1565 # Raise exception if invalid arguments
1566 if not (nsr_id
and operation
and params
):
1568 "Parameters 'nsr_id', 'operation' and 'params' needed to create primitive not provided")
1574 # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1575 "operationState": "PROCESSING",
1576 "statusEnteredTime": now
,
1577 "nsInstanceId": nsr_id
,
1578 "lcmOperationType": operation
,
1580 "isAutomaticInvocation": False,
1581 "operationParams": params
,
1582 "isCancelPending": False,
1584 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
1585 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
1590 # Create a primitive with params from VNFD
1591 # - Called from terminate() before deleting instance
1592 # - Calls action() to execute the primitive
1593 async def _terminate_action(self
, db_nslcmop
, nslcmop_id
, nsr_id
):
1594 logging_text
= "Task ns={} _terminate_action={} ".format(nsr_id
, nslcmop_id
)
1596 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1598 for vnfr
in db_vnfrs_list
:
1599 vnfd_id
= vnfr
["vnfd-id"]
1600 vnf_index
= vnfr
["member-vnf-index-ref"]
1601 if vnfd_id
not in db_vnfds
:
1602 step
= "Getting vnfd={} id='{}' from db".format(vnfd_id
, vnfd_id
)
1603 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
1604 db_vnfds
[vnfd_id
] = vnfd
1605 vnfd
= db_vnfds
[vnfd_id
]
1606 if not self
._has
_terminate
_config
_primitive
(vnfd
):
1608 # Get the primitive's sorted sequence list
1609 seq_list
= self
._get
_terminate
_config
_primitive
_seq
_list
(vnfd
)
1610 for seq
in seq_list
:
1611 # For each sequence in list, call terminate action
1612 step
= "Calling terminate action for vnf_member_index={} primitive={}".format(
1613 vnf_index
, seq
.get("name"))
1614 self
.logger
.debug(logging_text
+ step
)
1615 # Create the primitive for each sequence
1616 operation
= "action"
1617 # primitive, i.e. "primitive": "touch"
1618 primitive
= seq
.get('name')
1619 primitive_params
= {}
1621 "member_vnf_index": vnf_index
,
1622 "primitive": primitive
,
1623 "primitive_params": primitive_params
,
1625 nslcmop_primitive
= self
._create
_nslcmop
(nsr_id
, operation
, params
)
1626 # Get a copy of db_nslcmop 'admin' part
1627 db_nslcmop_action
= {"_admin": deepcopy(db_nslcmop
["_admin"])}
1628 # Update db_nslcmop with the primitive data
1629 db_nslcmop_action
.update(nslcmop_primitive
)
1630 # Create a new db entry for the created primitive, returns the new ID.
1631 # (The ID is normally obtained from Kafka.)
1632 nslcmop_terminate_action_id
= self
.db
.create(
1633 "nslcmops", db_nslcmop_action
)
1634 # Execute the primitive
1635 nslcmop_operation_state
, nslcmop_operation_state_detail
= await self
.action(
1636 nsr_id
, nslcmop_terminate_action_id
)
1637 # Launch Exception if action() returns other than ['COMPLETED', 'PARTIALLY_COMPLETED']
1638 nslcmop_operation_states_ok
= ['COMPLETED', 'PARTIALLY_COMPLETED']
1639 if nslcmop_operation_state
not in nslcmop_operation_states_ok
:
1641 "terminate_primitive_action for vnf_member_index={}",
1642 " primitive={} fails with error {}".format(
1643 vnf_index
, seq
.get("name"), nslcmop_operation_state_detail
))
1645 async def terminate(self
, nsr_id
, nslcmop_id
):
1646 logging_text
= "Task ns={} terminate={} ".format(nsr_id
, nslcmop_id
)
1647 self
.logger
.debug(logging_text
+ "Enter")
1651 failed_detail
= [] # annotates all failed error messages
1652 vca_time_destroy
= None # time of where destroy charm order
1653 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
}
1654 db_nslcmop_update
= {}
1655 nslcmop_operation_state
= None
1656 autoremove
= False # autoremove after terminated
1658 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
1659 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1660 step
= "Getting nsr={} from db".format(nsr_id
)
1661 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1662 # nsd = db_nsr["nsd"]
1663 nsr_deployed
= deepcopy(db_nsr
["_admin"].get("deployed"))
1664 if db_nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
1666 # #TODO check if VIM is creating and wait
1667 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
1668 # Call internal terminate action
1669 await self
._terminate
_action
(db_nslcmop
, nslcmop_id
, nsr_id
)
1671 db_nsr_update
["operational-status"] = "terminating"
1672 db_nsr_update
["config-status"] = "terminating"
1674 if nsr_deployed
and nsr_deployed
.get("VCA-model-name"):
1675 vca_model_name
= nsr_deployed
["VCA-model-name"]
1676 step
= "deleting VCA model name '{}' and all charms".format(vca_model_name
)
1677 self
.logger
.debug(logging_text
+ step
)
1679 await self
.n2vc
.DestroyNetworkService(vca_model_name
)
1680 except NetworkServiceDoesNotExist
:
1682 db_nsr_update
["_admin.deployed.VCA-model-name"] = None
1683 if nsr_deployed
.get("VCA"):
1684 for vca_index
in range(0, len(nsr_deployed
["VCA"])):
1685 db_nsr_update
["_admin.deployed.VCA.{}".format(vca_index
)] = None
1686 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1687 # for backward compatibility if charm have been created with "default" model name delete one by one
1688 elif nsr_deployed
and nsr_deployed
.get("VCA"):
1690 step
= "Scheduling configuration charms removing"
1691 db_nsr_update
["detailed-status"] = "Deleting charms"
1692 self
.logger
.debug(logging_text
+ step
)
1693 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1694 # for backward compatibility
1695 if isinstance(nsr_deployed
["VCA"], dict):
1696 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
1697 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
1698 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1700 for vca_index
, vca_deployed
in enumerate(nsr_deployed
["VCA"]):
1702 if await self
._destroy
_charm
(vca_deployed
['model'], vca_deployed
["application"]):
1703 vca_deployed
.clear()
1704 db_nsr
["_admin.deployed.VCA.{}".format(vca_index
)] = None
1706 vca_time_destroy
= time()
1707 except Exception as e
:
1708 self
.logger
.debug(logging_text
+ "Failed while deleting charms: {}".format(e
))
1712 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
1715 RO_nsr_id
= RO_delete_action
= None
1716 if nsr_deployed
and nsr_deployed
.get("RO"):
1717 RO_nsr_id
= nsr_deployed
["RO"].get("nsr_id")
1718 RO_delete_action
= nsr_deployed
["RO"].get("nsr_delete_action_id")
1721 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] = "Deleting ns at RO"
1722 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1723 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1724 self
.logger
.debug(logging_text
+ step
)
1725 desc
= await RO
.delete("ns", RO_nsr_id
)
1726 RO_delete_action
= desc
["action_id"]
1727 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = RO_delete_action
1728 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1729 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
1730 if RO_delete_action
:
1731 # wait until NS is deleted from VIM
1732 step
= detailed_status
= "Waiting ns deleted from VIM. RO_id={} RO_delete_action={}".\
1733 format(RO_nsr_id
, RO_delete_action
)
1734 detailed_status_old
= None
1735 self
.logger
.debug(logging_text
+ step
)
1737 delete_timeout
= 20 * 60 # 20 minutes
1738 while delete_timeout
> 0:
1739 desc
= await RO
.show("ns", item_id_name
=RO_nsr_id
, extra_item
="action",
1740 extra_item_id
=RO_delete_action
)
1741 ns_status
, ns_status_info
= RO
.check_action_status(desc
)
1742 if ns_status
== "ERROR":
1743 raise ROclient
.ROClientException(ns_status_info
)
1744 elif ns_status
== "BUILD":
1745 detailed_status
= step
+ "; {}".format(ns_status_info
)
1746 elif ns_status
== "ACTIVE":
1747 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
1748 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
1751 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
1752 if detailed_status
!= detailed_status_old
:
1753 detailed_status_old
= db_nslcmop_update
["detailed-status"] = \
1754 db_nsr_update
["detailed-status"] = detailed_status
1755 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1756 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1757 await asyncio
.sleep(5, loop
=self
.loop
)
1759 else: # delete_timeout <= 0:
1760 raise ROclient
.ROClientException("Timeout waiting ns deleted from VIM")
1762 except ROclient
.ROClientException
as e
:
1763 if e
.http_code
== 404: # not found
1764 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1765 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
1766 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
1767 self
.logger
.debug(logging_text
+ "RO_ns_id={} already deleted".format(RO_nsr_id
))
1768 elif e
.http_code
== 409: # conflict
1769 failed_detail
.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id
, e
))
1770 self
.logger
.debug(logging_text
+ failed_detail
[-1])
1773 failed_detail
.append("RO_ns_id={} delete error: {}".format(RO_nsr_id
, e
))
1774 self
.logger
.error(logging_text
+ failed_detail
[-1])
1778 if not RO_fail
and nsr_deployed
and nsr_deployed
.get("RO") and nsr_deployed
["RO"].get("nsd_id"):
1779 RO_nsd_id
= nsr_deployed
["RO"]["nsd_id"]
1781 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
1782 "Deleting nsd at RO"
1783 await RO
.delete("nsd", RO_nsd_id
)
1784 self
.logger
.debug(logging_text
+ "RO_nsd_id={} deleted".format(RO_nsd_id
))
1785 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
1786 except ROclient
.ROClientException
as e
:
1787 if e
.http_code
== 404: # not found
1788 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
1789 self
.logger
.debug(logging_text
+ "RO_nsd_id={} already deleted".format(RO_nsd_id
))
1790 elif e
.http_code
== 409: # conflict
1791 failed_detail
.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id
, e
))
1792 self
.logger
.debug(logging_text
+ failed_detail
[-1])
1795 failed_detail
.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id
, e
))
1796 self
.logger
.error(logging_text
+ failed_detail
[-1])
1799 if not RO_fail
and nsr_deployed
and nsr_deployed
.get("RO") and nsr_deployed
["RO"].get("vnfd"):
1800 for index
, vnf_deployed
in enumerate(nsr_deployed
["RO"]["vnfd"]):
1801 if not vnf_deployed
or not vnf_deployed
["id"]:
1804 RO_vnfd_id
= vnf_deployed
["id"]
1805 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
1806 "Deleting member_vnf_index={} RO_vnfd_id={} from RO".format(
1807 vnf_deployed
["member-vnf-index"], RO_vnfd_id
)
1808 await RO
.delete("vnfd", RO_vnfd_id
)
1809 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} deleted".format(RO_vnfd_id
))
1810 db_nsr_update
["_admin.deployed.RO.vnfd.{}.id".format(index
)] = None
1811 except ROclient
.ROClientException
as e
:
1812 if e
.http_code
== 404: # not found
1813 db_nsr_update
["_admin.deployed.RO.vnfd.{}.id".format(index
)] = None
1814 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} already deleted ".format(RO_vnfd_id
))
1815 elif e
.http_code
== 409: # conflict
1816 failed_detail
.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id
, e
))
1817 self
.logger
.debug(logging_text
+ failed_detail
[-1])
1819 failed_detail
.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id
, e
))
1820 self
.logger
.error(logging_text
+ failed_detail
[-1])
1822 # wait until charm deleted
1823 if vca_time_destroy
:
1824 db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] = step
= \
1825 "Waiting for deletion of configuration charms"
1826 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1827 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1828 for vca_index
, vca_deployed
in enumerate(nsr_deployed
["VCA"]):
1829 if not vca_deployed
:
1831 step
= "Waiting for deletion of charm application_name={}".format(vca_deployed
["application"])
1832 timeout
= self
.timeout_charm_delete
- int(time() - vca_time_destroy
)
1833 if not await self
._wait
_charm
_destroyed
(vca_deployed
['model'], vca_deployed
["application"],
1835 failed_detail
.append("VCA[application_name={}] Deletion timeout".format(
1836 vca_deployed
["application"]))
1838 db_nsr
["_admin.deployed.VCA.{}".format(vca_index
)] = None
1841 self
.logger
.error(logging_text
+ " ;".join(failed_detail
))
1842 db_nsr_update
["operational-status"] = "failed"
1843 db_nsr_update
["detailed-status"] = "Deletion errors " + "; ".join(failed_detail
)
1844 db_nslcmop_update
["detailed-status"] = "; ".join(failed_detail
)
1845 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
1846 db_nslcmop_update
["statusEnteredTime"] = time()
1848 db_nsr_update
["operational-status"] = "terminated"
1849 db_nsr_update
["detailed-status"] = "Done"
1850 db_nsr_update
["_admin.nsState"] = "NOT_INSTANTIATED"
1851 db_nslcmop_update
["detailed-status"] = "Done"
1852 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
1853 db_nslcmop_update
["statusEnteredTime"] = time()
1854 if db_nslcmop
["operationParams"].get("autoremove"):
1857 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
1858 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
1860 except asyncio
.CancelledError
:
1861 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1862 exc
= "Operation was cancelled"
1863 except Exception as e
:
1864 exc
= traceback
.format_exc()
1865 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
1867 if exc
and db_nslcmop
:
1868 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
1869 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
1870 db_nslcmop_update
["statusEnteredTime"] = time()
1872 if db_nslcmop
and db_nslcmop_update
:
1873 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1875 db_nsr_update
["_admin.nslcmop"] = None
1876 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1877 except DbException
as e
:
1878 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
1879 if nslcmop_operation_state
:
1881 await self
.msg
.aiowrite("ns", "terminated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
1882 "operationState": nslcmop_operation_state
,
1883 "autoremove": autoremove
},
1885 except Exception as e
:
1886 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1887 self
.logger
.debug(logging_text
+ "Exit")
1888 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_terminate")
1891 def _map_primitive_params(primitive_desc
, params
, instantiation_params
):
1893 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
1894 The default-value is used. If it is between < > it look for a value at instantiation_params
1895 :param primitive_desc: portion of VNFD/NSD that describes primitive
1896 :param params: Params provided by user
1897 :param instantiation_params: Instantiation params provided by user
1898 :return: a dictionary with the calculated params
1900 calculated_params
= {}
1901 for parameter
in primitive_desc
.get("parameter", ()):
1902 param_name
= parameter
["name"]
1903 if param_name
in params
:
1904 calculated_params
[param_name
] = params
[param_name
]
1905 elif "default-value" in parameter
or "value" in parameter
:
1906 if "value" in parameter
:
1907 calculated_params
[param_name
] = parameter
["value"]
1909 calculated_params
[param_name
] = parameter
["default-value"]
1910 if isinstance(calculated_params
[param_name
], str) and calculated_params
[param_name
].startswith("<") \
1911 and calculated_params
[param_name
].endswith(">"):
1912 if calculated_params
[param_name
][1:-1] in instantiation_params
:
1913 calculated_params
[param_name
] = instantiation_params
[calculated_params
[param_name
][1:-1]]
1915 raise LcmException("Parameter {} needed to execute primitive {} not provided".
1916 format(parameter
["default-value"], primitive_desc
["name"]))
1918 raise LcmException("Parameter {} needed to execute primitive {} not provided".
1919 format(param_name
, primitive_desc
["name"]))
1921 if isinstance(calculated_params
[param_name
], (dict, list, tuple)):
1922 calculated_params
[param_name
] = yaml
.safe_dump(calculated_params
[param_name
], default_flow_style
=True,
1924 elif isinstance(calculated_params
[param_name
], str) and calculated_params
[param_name
].startswith("!!yaml "):
1925 calculated_params
[param_name
] = calculated_params
[param_name
][7:]
1926 return calculated_params
1928 async def _ns_execute_primitive(self
, db_deployed
, member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
,
1929 primitive
, primitive_params
):
1930 start_primitive_time
= time()
1932 for vca_deployed
in db_deployed
["VCA"]:
1933 if not vca_deployed
:
1935 if member_vnf_index
!= vca_deployed
["member-vnf-index"] or vdu_id
!= vca_deployed
["vdu_id"]:
1937 if vdu_name
and vdu_name
!= vca_deployed
["vdu_name"]:
1939 if vdu_count_index
and vdu_count_index
!= vca_deployed
["vdu_count_index"]:
1943 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} is not "
1944 "deployed".format(member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
))
1945 model_name
= vca_deployed
.get("model")
1946 application_name
= vca_deployed
.get("application")
1947 if not model_name
or not application_name
:
1948 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} has not "
1949 "model or application name" .format(member_vnf_index
, vdu_id
, vdu_name
,
1951 # if vca_deployed["operational-status"] != "active":
1952 # raise LcmException("charm for member_vnf_index={} vdu_id={} operational_status={} not 'active'".format(
1953 # member_vnf_index, vdu_id, vca_deployed["operational-status"]))
1954 callback
= None # self.n2vc_callback
1955 callback_args
= () # [db_nsr, db_nslcmop, member_vnf_index, None]
1956 await self
.n2vc
.login()
1957 if primitive
== "config":
1958 primitive_params
= {"params": primitive_params
}
1959 primitive_id
= await self
.n2vc
.ExecutePrimitive(
1967 while time() - start_primitive_time
< self
.timeout_primitive
:
1968 primitive_result_
= await self
.n2vc
.GetPrimitiveStatus(model_name
, primitive_id
)
1969 if primitive_result_
in ("completed", "failed"):
1970 primitive_result
= "COMPLETED" if primitive_result_
== "completed" else "FAILED"
1971 detailed_result
= await self
.n2vc
.GetPrimitiveOutput(model_name
, primitive_id
)
1973 elif primitive_result_
is None and primitive
== "config":
1974 primitive_result
= "COMPLETED"
1975 detailed_result
= None
1977 else: # ("running", "pending", None):
1979 await asyncio
.sleep(5)
1981 raise LcmException("timeout after {} seconds".format(self
.timeout_primitive
))
1982 return primitive_result
, detailed_result
1983 except (N2VCPrimitiveExecutionFailed
, LcmException
) as e
:
1984 return "FAILED", str(e
)
1986 async def action(self
, nsr_id
, nslcmop_id
):
1987 logging_text
= "Task ns={} action={} ".format(nsr_id
, nslcmop_id
)
1988 self
.logger
.debug(logging_text
+ "Enter")
1989 # get all needed from database
1992 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
}
1993 db_nslcmop_update
= {}
1994 nslcmop_operation_state
= None
1995 nslcmop_operation_state_detail
= None
1998 step
= "Getting information from database"
1999 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
2000 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2002 nsr_deployed
= db_nsr
["_admin"].get("deployed")
2003 vnf_index
= db_nslcmop
["operationParams"].get("member_vnf_index")
2004 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
2005 vdu_count_index
= db_nslcmop
["operationParams"].get("vdu_count_index")
2006 vdu_name
= db_nslcmop
["operationParams"].get("vdu_name")
2009 step
= "Getting vnfr from database"
2010 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
2011 step
= "Getting vnfd from database"
2012 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
2014 if db_nsr
.get("nsd"):
2015 db_nsd
= db_nsr
.get("nsd") # TODO this will be removed
2017 step
= "Getting nsd from database"
2018 db_nsd
= self
.db
.get_one("nsds", {"_id": db_nsr
["nsd-id"]})
2020 # look if previous tasks in process
2021 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("ns", nsr_id
, nslcmop_id
)
2023 step
= db_nslcmop_update
["detailed-status"] = \
2024 "Waiting for related tasks to be completed: {}".format(task_name
)
2025 self
.logger
.debug(logging_text
+ step
)
2026 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2027 _
, pending
= await asyncio
.wait(task_dependency
, timeout
=3600)
2029 raise LcmException("Timeout waiting related tasks to be completed")
2031 # for backward compatibility
2032 if nsr_deployed
and isinstance(nsr_deployed
.get("VCA"), dict):
2033 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
2034 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
2035 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2037 primitive
= db_nslcmop
["operationParams"]["primitive"]
2038 primitive_params
= db_nslcmop
["operationParams"]["primitive_params"]
2040 # look for primitive
2041 config_primitive_desc
= None
2043 for vdu
in get_iterable(db_vnfd
, "vdu"):
2044 if vdu_id
== vdu
["id"]:
2045 for config_primitive
in vdu
.get("vdu-configuration", {}).get("config-primitive", ()):
2046 if config_primitive
["name"] == primitive
:
2047 config_primitive_desc
= config_primitive
2050 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
2051 if config_primitive
["name"] == primitive
:
2052 config_primitive_desc
= config_primitive
2055 for config_primitive
in db_nsd
.get("ns-configuration", {}).get("config-primitive", ()):
2056 if config_primitive
["name"] == primitive
:
2057 config_primitive_desc
= config_primitive
2060 if not config_primitive_desc
:
2061 raise LcmException("Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".
2066 if db_vnfr
.get("additionalParamsForVnf"):
2067 desc_params
.update(db_vnfr
["additionalParamsForVnf"])
2069 if db_nsr
.get("additionalParamsForVnf"):
2070 desc_params
.update(db_nsr
["additionalParamsForNs"])
2072 # TODO check if ns is in a proper status
2073 result
, result_detail
= await self
._ns
_execute
_primitive
(
2074 nsr_deployed
, vnf_index
, vdu_id
, vdu_name
, vdu_count_index
, primitive
,
2075 self
._map
_primitive
_params
(config_primitive_desc
, primitive_params
, desc_params
))
2076 db_nslcmop_update
["detailed-status"] = nslcmop_operation_state_detail
= result_detail
2077 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= result
2078 db_nslcmop_update
["statusEnteredTime"] = time()
2079 self
.logger
.debug(logging_text
+ " task Done with result {} {}".format(result
, result_detail
))
2080 return # database update is called inside finally
2082 except (DbException
, LcmException
) as e
:
2083 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
2085 except asyncio
.CancelledError
:
2086 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
2087 exc
= "Operation was cancelled"
2088 except Exception as e
:
2089 exc
= traceback
.format_exc()
2090 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
2092 if exc
and db_nslcmop
:
2093 db_nslcmop_update
["detailed-status"] = nslcmop_operation_state_detail
= \
2094 "FAILED {}: {}".format(step
, exc
)
2095 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2096 db_nslcmop_update
["statusEnteredTime"] = time()
2098 if db_nslcmop_update
:
2099 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2101 db_nsr_update
["_admin.nslcmop"] = None
2102 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2103 except DbException
as e
:
2104 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
2105 self
.logger
.debug(logging_text
+ "Exit")
2106 if nslcmop_operation_state
:
2108 await self
.msg
.aiowrite("ns", "actioned", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2109 "operationState": nslcmop_operation_state
},
2111 except Exception as e
:
2112 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
2113 self
.logger
.debug(logging_text
+ "Exit")
2114 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_action")
2115 return nslcmop_operation_state
, nslcmop_operation_state_detail
2117 async def scale(self
, nsr_id
, nslcmop_id
):
2118 logging_text
= "Task ns={} scale={} ".format(nsr_id
, nslcmop_id
)
2119 self
.logger
.debug(logging_text
+ "Enter")
2120 # get all needed from database
2123 db_nslcmop_update
= {}
2124 nslcmop_operation_state
= None
2125 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
}
2127 # in case of error, indicates what part of scale was failed to put nsr at error status
2128 scale_process
= None
2129 old_operational_status
= ""
2130 old_config_status
= ""
2133 # look if previous tasks in process
2134 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("ns", nsr_id
, nslcmop_id
)
2136 step
= db_nslcmop_update
["detailed-status"] = \
2137 "Waiting for related tasks to be completed: {}".format(task_name
)
2138 self
.logger
.debug(logging_text
+ step
)
2139 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2140 _
, pending
= await asyncio
.wait(task_dependency
, timeout
=3600)
2142 raise LcmException("Timeout waiting related tasks to be completed")
2144 step
= "Getting nslcmop from database"
2145 scale_process
= "RO"
2146 self
.logger
.debug(step
+ " after having waited for previous tasks to be completed")
2147 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
2148 step
= "Getting nsr from database"
2149 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2151 old_operational_status
= db_nsr
["operational-status"]
2152 old_config_status
= db_nsr
["config-status"]
2153 step
= "Parsing scaling parameters"
2154 self
.logger
.debug(step
)
2155 db_nsr_update
["operational-status"] = "scaling"
2156 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2157 nsr_deployed
= db_nsr
["_admin"].get("deployed")
2158 RO_nsr_id
= nsr_deployed
["RO"]["nsr_id"]
2159 vnf_index
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
2160 scaling_group
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
2161 scaling_type
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleVnfType"]
2162 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
2164 # for backward compatibility
2165 if nsr_deployed
and isinstance(nsr_deployed
.get("VCA"), dict):
2166 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
2167 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
2168 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2170 step
= "Getting vnfr from database"
2171 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
2172 step
= "Getting vnfd from database"
2173 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
2175 step
= "Getting scaling-group-descriptor"
2176 for scaling_descriptor
in db_vnfd
["scaling-group-descriptor"]:
2177 if scaling_descriptor
["name"] == scaling_group
:
2180 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
2181 "at vnfd:scaling-group-descriptor".format(scaling_group
))
2184 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
2185 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
2186 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
2189 # TODO check if ns is in a proper status
2190 step
= "Sending scale order to RO"
2192 if not db_nsr
["_admin"].get("scaling-group"):
2193 self
.update_db_2("nsrs", nsr_id
, {"_admin.scaling-group": [{"name": scaling_group
, "nb-scale-op": 0}]})
2194 admin_scale_index
= 0
2196 for admin_scale_index
, admin_scale_info
in enumerate(db_nsr
["_admin"]["scaling-group"]):
2197 if admin_scale_info
["name"] == scaling_group
:
2198 nb_scale_op
= admin_scale_info
.get("nb-scale-op", 0)
2200 else: # not found, set index one plus last element and add new entry with the name
2201 admin_scale_index
+= 1
2202 db_nsr_update
["_admin.scaling-group.{}.name".format(admin_scale_index
)] = scaling_group
2203 RO_scaling_info
= []
2204 vdu_scaling_info
= {"scaling_group_name": scaling_group
, "vdu": []}
2205 if scaling_type
== "SCALE_OUT":
2206 # count if max-instance-count is reached
2207 if "max-instance-count" in scaling_descriptor
and scaling_descriptor
["max-instance-count"] is not None:
2208 max_instance_count
= int(scaling_descriptor
["max-instance-count"])
2210 self
.logger
.debug("MAX_INSTANCE_COUNT is {}".format(scaling_descriptor
["max-instance-count"]))
2211 if nb_scale_op
>= max_instance_count
:
2212 raise LcmException("reached the limit of {} (max-instance-count) "
2213 "scaling-out operations for the "
2214 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
2216 # TODO: if we have more than one vdus # then it must be fixed.to get the correct # vdu_count
2218 vdu_scaling_info
["scaling_direction"] = "OUT"
2219 vdu_scaling_info
["vdu-create"] = {}
2220 for vdu_scale_info
in scaling_descriptor
["vdu"]:
2221 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
2222 "type": "create", "count": vdu_scale_info
.get("count", 1)})
2223 vdu_scaling_info
["vdu-create"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
2225 elif scaling_type
== "SCALE_IN":
2226 # count if min-instance-count is reached
2227 min_instance_count
= 0
2228 if "min-instance-count" in scaling_descriptor
and scaling_descriptor
["min-instance-count"] is not None:
2229 min_instance_count
= int(scaling_descriptor
["min-instance-count"])
2230 if nb_scale_op
<= min_instance_count
:
2231 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
2232 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
2234 vdu_scaling_info
["scaling_direction"] = "IN"
2235 vdu_scaling_info
["vdu-delete"] = {}
2236 for vdu_scale_info
in scaling_descriptor
["vdu"]:
2237 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
2238 "type": "delete", "count": vdu_scale_info
.get("count", 1)})
2239 vdu_scaling_info
["vdu-delete"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
2241 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
2242 vdu_create
= vdu_scaling_info
.get("vdu-create")
2243 vdu_delete
= copy(vdu_scaling_info
.get("vdu-delete"))
2244 if vdu_scaling_info
["scaling_direction"] == "IN":
2245 for vdur
in reversed(db_vnfr
["vdur"]):
2246 if vdu_delete
.get(vdur
["vdu-id-ref"]):
2247 vdu_delete
[vdur
["vdu-id-ref"]] -= 1
2248 vdu_scaling_info
["vdu"].append({
2249 "name": vdur
["name"],
2250 "vdu_id": vdur
["vdu-id-ref"],
2253 for interface
in vdur
["interfaces"]:
2254 vdu_scaling_info
["vdu"][-1]["interface"].append({
2255 "name": interface
["name"],
2256 "ip_address": interface
["ip-address"],
2257 "mac_address": interface
.get("mac-address"),
2259 vdu_delete
= vdu_scaling_info
.pop("vdu-delete")
2261 # execute primitive service PRE-SCALING
2262 step
= "Executing pre-scale vnf-config-primitive"
2263 if scaling_descriptor
.get("scaling-config-action"):
2264 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
2265 if scaling_config_action
.get("trigger") and scaling_config_action
["trigger"] == "pre-scale-in" \
2266 and scaling_type
== "SCALE_IN":
2267 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
2268 step
= db_nslcmop_update
["detailed-status"] = \
2269 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive
)
2271 # look for primitive
2272 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
2273 if config_primitive
["name"] == vnf_config_primitive
:
2277 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
2278 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
2279 "primitive".format(scaling_group
, config_primitive
))
2281 vnfr_params
= {"VDU_SCALE_INFO": vdu_scaling_info
}
2282 if db_vnfr
.get("additionalParamsForVnf"):
2283 vnfr_params
.update(db_vnfr
["additionalParamsForVnf"])
2285 scale_process
= "VCA"
2286 db_nsr_update
["config-status"] = "configuring pre-scaling"
2287 result
, result_detail
= await self
._ns
_execute
_primitive
(
2288 nsr_deployed
, vnf_index
, None, None, None, vnf_config_primitive
,
2289 self
._map
_primitive
_params
(config_primitive
, {}, vnfr_params
))
2290 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
2291 vnf_config_primitive
, result
, result_detail
))
2292 if result
== "FAILED":
2293 raise LcmException(result_detail
)
2294 db_nsr_update
["config-status"] = old_config_status
2295 scale_process
= None
2298 scale_process
= "RO"
2299 RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
2300 RO_desc
= await RO
.create_action("ns", RO_nsr_id
, {"vdu-scaling": RO_scaling_info
})
2301 db_nsr_update
["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index
)] = nb_scale_op
2302 db_nsr_update
["_admin.scaling-group.{}.time".format(admin_scale_index
)] = time()
2304 RO_nslcmop_id
= RO_desc
["instance_action_id"]
2305 db_nslcmop_update
["_admin.deploy.RO"] = RO_nslcmop_id
2307 RO_task_done
= False
2308 step
= detailed_status
= "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id
)
2309 detailed_status_old
= None
2310 self
.logger
.debug(logging_text
+ step
)
2312 deployment_timeout
= 1 * 3600 # One hour
2313 while deployment_timeout
> 0:
2314 if not RO_task_done
:
2315 desc
= await RO
.show("ns", item_id_name
=RO_nsr_id
, extra_item
="action",
2316 extra_item_id
=RO_nslcmop_id
)
2317 ns_status
, ns_status_info
= RO
.check_action_status(desc
)
2318 if ns_status
== "ERROR":
2319 raise ROclient
.ROClientException(ns_status_info
)
2320 elif ns_status
== "BUILD":
2321 detailed_status
= step
+ "; {}".format(ns_status_info
)
2322 elif ns_status
== "ACTIVE":
2324 step
= detailed_status
= "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id
)
2325 self
.logger
.debug(logging_text
+ step
)
2327 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
2329 desc
= await RO
.show("ns", RO_nsr_id
)
2330 ns_status
, ns_status_info
= RO
.check_ns_status(desc
)
2331 if ns_status
== "ERROR":
2332 raise ROclient
.ROClientException(ns_status_info
)
2333 elif ns_status
== "BUILD":
2334 detailed_status
= step
+ "; {}".format(ns_status_info
)
2335 elif ns_status
== "ACTIVE":
2336 step
= detailed_status
= \
2337 "Waiting for management IP address reported by the VIM. Updating VNFRs"
2339 self
.scale_vnfr(db_vnfr
, vdu_create
=vdu_create
, vdu_delete
=vdu_delete
)
2342 desc
= await RO
.show("ns", RO_nsr_id
)
2343 # nsr_deployed["nsr_ip"] = RO.get_ns_vnf_info(desc)
2344 self
.ns_update_vnfr({db_vnfr
["member-vnf-index-ref"]: db_vnfr
}, desc
)
2346 except LcmExceptionNoMgmtIP
:
2349 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
2350 if detailed_status
!= detailed_status_old
:
2351 detailed_status_old
= db_nslcmop_update
["detailed-status"] = detailed_status
2352 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2354 await asyncio
.sleep(5, loop
=self
.loop
)
2355 deployment_timeout
-= 5
2356 if deployment_timeout
<= 0:
2357 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
2359 # update VDU_SCALING_INFO with the obtained ip_addresses
2360 if vdu_scaling_info
["scaling_direction"] == "OUT":
2361 for vdur
in reversed(db_vnfr
["vdur"]):
2362 if vdu_scaling_info
["vdu-create"].get(vdur
["vdu-id-ref"]):
2363 vdu_scaling_info
["vdu-create"][vdur
["vdu-id-ref"]] -= 1
2364 vdu_scaling_info
["vdu"].append({
2365 "name": vdur
["name"],
2366 "vdu_id": vdur
["vdu-id-ref"],
2369 for interface
in vdur
["interfaces"]:
2370 vdu_scaling_info
["vdu"][-1]["interface"].append({
2371 "name": interface
["name"],
2372 "ip_address": interface
["ip-address"],
2373 "mac_address": interface
.get("mac-address"),
2375 del vdu_scaling_info
["vdu-create"]
2377 scale_process
= None
2379 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2381 # execute primitive service POST-SCALING
2382 step
= "Executing post-scale vnf-config-primitive"
2383 if scaling_descriptor
.get("scaling-config-action"):
2384 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
2385 if scaling_config_action
.get("trigger") and scaling_config_action
["trigger"] == "post-scale-out" \
2386 and scaling_type
== "SCALE_OUT":
2387 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
2388 step
= db_nslcmop_update
["detailed-status"] = \
2389 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive
)
2391 vnfr_params
= {"VDU_SCALE_INFO": vdu_scaling_info
}
2392 if db_vnfr
.get("additionalParamsForVnf"):
2393 vnfr_params
.update(db_vnfr
["additionalParamsForVnf"])
2395 # look for primitive
2396 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
2397 if config_primitive
["name"] == vnf_config_primitive
:
2400 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
2401 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
2402 "match any vnf-configuration:config-primitive".format(scaling_group
,
2404 scale_process
= "VCA"
2405 db_nsr_update
["config-status"] = "configuring post-scaling"
2407 result
, result_detail
= await self
._ns
_execute
_primitive
(
2408 nsr_deployed
, vnf_index
, None, None, None, vnf_config_primitive
,
2409 self
._map
_primitive
_params
(config_primitive
, {}, vnfr_params
))
2410 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
2411 vnf_config_primitive
, result
, result_detail
))
2412 if result
== "FAILED":
2413 raise LcmException(result_detail
)
2414 db_nsr_update
["config-status"] = old_config_status
2415 scale_process
= None
2417 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
2418 db_nslcmop_update
["statusEnteredTime"] = time()
2419 db_nslcmop_update
["detailed-status"] = "done"
2420 db_nsr_update
["detailed-status"] = "" # "scaled {} {}".format(scaling_group, scaling_type)
2421 db_nsr_update
["operational-status"] = "running" if old_operational_status
== "failed" \
2422 else old_operational_status
2423 db_nsr_update
["config-status"] = old_config_status
2425 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
2426 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
2428 except asyncio
.CancelledError
:
2429 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
2430 exc
= "Operation was cancelled"
2431 except Exception as e
:
2432 exc
= traceback
.format_exc()
2433 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
2437 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
2438 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2439 db_nslcmop_update
["statusEnteredTime"] = time()
2441 db_nsr_update
["operational-status"] = old_operational_status
2442 db_nsr_update
["config-status"] = old_config_status
2443 db_nsr_update
["detailed-status"] = ""
2444 db_nsr_update
["_admin.nslcmop"] = None
2446 if "VCA" in scale_process
:
2447 db_nsr_update
["config-status"] = "failed"
2448 if "RO" in scale_process
:
2449 db_nsr_update
["operational-status"] = "failed"
2450 db_nsr_update
["detailed-status"] = "FAILED scaling nslcmop={} {}: {}".format(nslcmop_id
, step
,
2453 if db_nslcmop
and db_nslcmop_update
:
2454 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2456 db_nsr_update
["_admin.nslcmop"] = None
2457 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2458 except DbException
as e
:
2459 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
2460 if nslcmop_operation_state
:
2462 await self
.msg
.aiowrite("ns", "scaled", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2463 "operationState": nslcmop_operation_state
},
2466 # await asyncio.sleep(cooldown_time)
2467 # await self.msg.aiowrite("ns","scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
2468 except Exception as e
:
2469 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
2470 self
.logger
.debug(logging_text
+ "Exit")
2471 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_scale")