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
24 from jinja2
import Environment
, Template
, meta
, TemplateError
, TemplateNotFound
, TemplateSyntaxError
26 from osm_lcm
import ROclient
27 from osm_lcm
.lcm_utils
import LcmException
, LcmExceptionNoMgmtIP
, LcmBase
, deep_get
28 from n2vc
.k8s_helm_conn
import K8sHelmConnector
29 from n2vc
.k8s_juju_conn
import K8sJujuConnector
31 from osm_common
.dbbase
import DbException
32 from osm_common
.fsbase
import FsException
34 from n2vc
.n2vc_juju_conn
import N2VCJujuConnector
36 from copy
import copy
, deepcopy
37 from http
import HTTPStatus
39 from uuid
import uuid4
41 __author__
= "Alfonso Tierno"
44 def get_iterable(in_dict
, in_key
):
46 Similar to <dict>.get(), but if value is None, False, ..., An empty tuple is returned instead
47 :param in_dict: a dictionary
48 :param in_key: the key to look for at in_dict
49 :return: in_dict[in_var] or () if it is None or not present
51 if not in_dict
.get(in_key
):
53 return in_dict
[in_key
]
56 def populate_dict(target_dict
, key_list
, value
):
58 Update target_dict creating nested dictionaries with the key_list. Last key_list item is asigned the value.
59 Example target_dict={K: J}; key_list=[a,b,c]; target_dict will be {K: J, a: {b: {c: value}}}
60 :param target_dict: dictionary to be changed
61 :param key_list: list of keys to insert at target_dict
65 for key
in key_list
[0:-1]:
66 if key
not in target_dict
:
68 target_dict
= target_dict
[key
]
69 target_dict
[key_list
[-1]] = value
73 timeout_vca_on_error
= 5 * 60 # Time for charm from first time at blocked,error status to mark as failed
74 total_deploy_timeout
= 2 * 3600 # global timeout for deployment
75 timeout_charm_delete
= 10 * 60
76 timeout_primitive
= 10 * 60 # timeout for primitive execution
78 SUBOPERATION_STATUS_NOT_FOUND
= -1
79 SUBOPERATION_STATUS_NEW
= -2
80 SUBOPERATION_STATUS_SKIP
= -3
82 def __init__(self
, db
, msg
, fs
, lcm_tasks
, ro_config
, vca_config
, loop
):
84 Init, Connect to database, filesystem storage, and messaging
85 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
92 logger
=logging
.getLogger('lcm.ns')
96 self
.lcm_tasks
= lcm_tasks
97 self
.ro_config
= ro_config
98 self
.vca_config
= vca_config
99 if 'pubkey' in self
.vca_config
:
100 self
.vca_config
['public_key'] = self
.vca_config
['pubkey']
101 if 'cacert' in self
.vca_config
:
102 self
.vca_config
['ca_cert'] = self
.vca_config
['cacert']
103 if 'apiproxy' in self
.vca_config
:
104 self
.vca_config
['api_proxy'] = self
.vca_config
['apiproxy']
106 # create N2VC connector
107 self
.n2vc
= N2VCJujuConnector(
112 url
='{}:{}'.format(self
.vca_config
['host'], self
.vca_config
['port']),
113 username
=self
.vca_config
.get('user', None),
114 vca_config
=self
.vca_config
,
115 on_update_db
=self
._on
_update
_n
2vc
_db
,
116 # ca_cert=self.vca_config.get('cacert'),
117 # api_proxy=self.vca_config.get('apiproxy'),
120 self
.k8sclusterhelm
= K8sHelmConnector(
121 kubectl_command
=self
.vca_config
.get("kubectlpath"),
122 helm_command
=self
.vca_config
.get("helmpath"),
129 self
.k8sclusterjuju
= K8sJujuConnector(
130 kubectl_command
=self
.vca_config
.get("kubectlpath"),
131 juju_command
=self
.vca_config
.get("jujupath"),
139 self
.RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
141 def _on_update_n2vc_db(self
, table
, filter, path
, updated_data
):
143 self
.logger
.debug('_on_update_n2vc_db(table={}, filter={}, path={}, updated_data={}'
144 .format(table
, filter, path
, updated_data
))
147 # write NS status to database
149 # # nsrs_id = filter.get('_id')
152 # nsr = self.db.get_one(table=table, q_filter=filter)
153 # # get VCA deployed list
154 # vca_list = deep_get(target_dict=nsr, key_list=('_admin', 'deployed', 'VCA'))
156 # # ro_list = deep_get(target_dict=nsr, key_list=('_admin', 'deployed', 'RO'))
157 # for vca in vca_list:
158 # # status = vca.get('status')
160 # # detailed_status = vca.get('detailed-status')
161 # # print(detailed_status)
162 # # for ro in ro_list:
165 # except Exception as e:
166 # self.logger.error('Error writing NS status to db: {}'.format(e))
168 def vnfd2RO(self
, vnfd
, new_id
=None, additionalParams
=None, nsrId
=None):
170 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
171 :param vnfd: input vnfd
172 :param new_id: overrides vnf id if provided
173 :param additionalParams: Instantiation params for VNFs provided
174 :param nsrId: Id of the NSR
175 :return: copy of vnfd
178 vnfd_RO
= deepcopy(vnfd
)
179 # remove unused by RO configuration, monitoring, scaling and internal keys
180 vnfd_RO
.pop("_id", None)
181 vnfd_RO
.pop("_admin", None)
182 vnfd_RO
.pop("vnf-configuration", None)
183 vnfd_RO
.pop("monitoring-param", None)
184 vnfd_RO
.pop("scaling-group-descriptor", None)
185 vnfd_RO
.pop("kdu", None)
186 vnfd_RO
.pop("k8s-cluster", None)
188 vnfd_RO
["id"] = new_id
190 # parse cloud-init or cloud-init-file with the provided variables using Jinja2
191 for vdu
in get_iterable(vnfd_RO
, "vdu"):
192 cloud_init_file
= None
193 if vdu
.get("cloud-init-file"):
194 base_folder
= vnfd
["_admin"]["storage"]
195 cloud_init_file
= "{}/{}/cloud_init/{}".format(base_folder
["folder"], base_folder
["pkg-dir"],
196 vdu
["cloud-init-file"])
197 with self
.fs
.file_open(cloud_init_file
, "r") as ci_file
:
198 cloud_init_content
= ci_file
.read()
199 vdu
.pop("cloud-init-file", None)
200 elif vdu
.get("cloud-init"):
201 cloud_init_content
= vdu
["cloud-init"]
206 ast
= env
.parse(cloud_init_content
)
207 mandatory_vars
= meta
.find_undeclared_variables(ast
)
209 for var
in mandatory_vars
:
210 if not additionalParams
or var
not in additionalParams
.keys():
211 raise LcmException("Variable '{}' defined at vnfd[id={}]:vdu[id={}]:cloud-init/cloud-init-"
212 "file, must be provided in the instantiation parameters inside the "
213 "'additionalParamsForVnf' block".format(var
, vnfd
["id"], vdu
["id"]))
214 template
= Template(cloud_init_content
)
215 cloud_init_content
= template
.render(additionalParams
or {})
216 vdu
["cloud-init"] = cloud_init_content
219 except FsException
as e
:
220 raise LcmException("Error reading vnfd[id={}]:vdu[id={}]:cloud-init-file={}: {}".
221 format(vnfd
["id"], vdu
["id"], cloud_init_file
, e
))
222 except (TemplateError
, TemplateNotFound
, TemplateSyntaxError
) as e
:
223 raise LcmException("Error parsing Jinja2 to cloud-init content at vnfd[id={}]:vdu[id={}]: {}".
224 format(vnfd
["id"], vdu
["id"], e
))
226 def ns_params_2_RO(self
, ns_params
, nsd
, vnfd_dict
, n2vc_key_list
):
228 Creates a RO ns descriptor from OSM ns_instantiate params
229 :param ns_params: OSM instantiate params
230 :return: The RO ns descriptor
234 # TODO feature 1417: Check that no instantiation is set over PDU
235 # check if PDU forces a concrete vim-network-id and add it
236 # check if PDU contains a SDN-assist info (dpid, switch, port) and pass it to RO
238 def vim_account_2_RO(vim_account
):
239 if vim_account
in vim_2_RO
:
240 return vim_2_RO
[vim_account
]
242 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_account
})
243 if db_vim
["_admin"]["operationalState"] != "ENABLED":
244 raise LcmException("VIM={} is not available. operationalState={}".format(
245 vim_account
, db_vim
["_admin"]["operationalState"]))
246 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
247 vim_2_RO
[vim_account
] = RO_vim_id
250 def wim_account_2_RO(wim_account
):
251 if isinstance(wim_account
, str):
252 if wim_account
in wim_2_RO
:
253 return wim_2_RO
[wim_account
]
255 db_wim
= self
.db
.get_one("wim_accounts", {"_id": wim_account
})
256 if db_wim
["_admin"]["operationalState"] != "ENABLED":
257 raise LcmException("WIM={} is not available. operationalState={}".format(
258 wim_account
, db_wim
["_admin"]["operationalState"]))
259 RO_wim_id
= db_wim
["_admin"]["deployed"]["RO-account"]
260 wim_2_RO
[wim_account
] = RO_wim_id
265 def ip_profile_2_RO(ip_profile
):
266 RO_ip_profile
= deepcopy((ip_profile
))
267 if "dns-server" in RO_ip_profile
:
268 if isinstance(RO_ip_profile
["dns-server"], list):
269 RO_ip_profile
["dns-address"] = []
270 for ds
in RO_ip_profile
.pop("dns-server"):
271 RO_ip_profile
["dns-address"].append(ds
['address'])
273 RO_ip_profile
["dns-address"] = RO_ip_profile
.pop("dns-server")
274 if RO_ip_profile
.get("ip-version") == "ipv4":
275 RO_ip_profile
["ip-version"] = "IPv4"
276 if RO_ip_profile
.get("ip-version") == "ipv6":
277 RO_ip_profile
["ip-version"] = "IPv6"
278 if "dhcp-params" in RO_ip_profile
:
279 RO_ip_profile
["dhcp"] = RO_ip_profile
.pop("dhcp-params")
285 # "name": ns_params["nsName"],
286 # "description": ns_params.get("nsDescription"),
287 "datacenter": vim_account_2_RO(ns_params
["vimAccountId"]),
288 "wim_account": wim_account_2_RO(ns_params
.get("wimAccountId")),
289 # "scenario": ns_params["nsdId"],
292 n2vc_key_list
= n2vc_key_list
or []
293 for vnfd_ref
, vnfd
in vnfd_dict
.items():
294 vdu_needed_access
= []
296 if vnfd
.get("vnf-configuration"):
297 ssh_required
= deep_get(vnfd
, ("vnf-configuration", "config-access", "ssh-access", "required"))
298 if ssh_required
and vnfd
.get("mgmt-interface"):
299 if vnfd
["mgmt-interface"].get("vdu-id"):
300 vdu_needed_access
.append(vnfd
["mgmt-interface"]["vdu-id"])
301 elif vnfd
["mgmt-interface"].get("cp"):
302 mgmt_cp
= vnfd
["mgmt-interface"]["cp"]
304 for vdu
in vnfd
.get("vdu", ()):
305 if vdu
.get("vdu-configuration"):
306 ssh_required
= deep_get(vdu
, ("vdu-configuration", "config-access", "ssh-access", "required"))
308 vdu_needed_access
.append(vdu
["id"])
310 for vdu_interface
in vdu
.get("interface"):
311 if vdu_interface
.get("external-connection-point-ref") and \
312 vdu_interface
["external-connection-point-ref"] == mgmt_cp
:
313 vdu_needed_access
.append(vdu
["id"])
317 if vdu_needed_access
:
318 for vnf_member
in nsd
.get("constituent-vnfd"):
319 if vnf_member
["vnfd-id-ref"] != vnfd_ref
:
321 for vdu
in vdu_needed_access
:
322 populate_dict(RO_ns_params
,
323 ("vnfs", vnf_member
["member-vnf-index"], "vdus", vdu
, "mgmt_keys"),
326 if ns_params
.get("vduImage"):
327 RO_ns_params
["vduImage"] = ns_params
["vduImage"]
329 if ns_params
.get("ssh_keys"):
330 RO_ns_params
["cloud-config"] = {"key-pairs": ns_params
["ssh_keys"]}
331 for vnf_params
in get_iterable(ns_params
, "vnf"):
332 for constituent_vnfd
in nsd
["constituent-vnfd"]:
333 if constituent_vnfd
["member-vnf-index"] == vnf_params
["member-vnf-index"]:
334 vnf_descriptor
= vnfd_dict
[constituent_vnfd
["vnfd-id-ref"]]
337 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index={} is not present at nsd:"
338 "constituent-vnfd".format(vnf_params
["member-vnf-index"]))
339 if vnf_params
.get("vimAccountId"):
340 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "datacenter"),
341 vim_account_2_RO(vnf_params
["vimAccountId"]))
343 for vdu_params
in get_iterable(vnf_params
, "vdu"):
344 # TODO feature 1417: check that this VDU exist and it is not a PDU
345 if vdu_params
.get("volume"):
346 for volume_params
in vdu_params
["volume"]:
347 if volume_params
.get("vim-volume-id"):
348 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
349 vdu_params
["id"], "devices", volume_params
["name"], "vim_id"),
350 volume_params
["vim-volume-id"])
351 if vdu_params
.get("interface"):
352 for interface_params
in vdu_params
["interface"]:
353 if interface_params
.get("ip-address"):
354 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
355 vdu_params
["id"], "interfaces", interface_params
["name"],
357 interface_params
["ip-address"])
358 if interface_params
.get("mac-address"):
359 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
360 vdu_params
["id"], "interfaces", interface_params
["name"],
362 interface_params
["mac-address"])
363 if interface_params
.get("floating-ip-required"):
364 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
365 vdu_params
["id"], "interfaces", interface_params
["name"],
367 interface_params
["floating-ip-required"])
369 for internal_vld_params
in get_iterable(vnf_params
, "internal-vld"):
370 if internal_vld_params
.get("vim-network-name"):
371 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
372 internal_vld_params
["name"], "vim-network-name"),
373 internal_vld_params
["vim-network-name"])
374 if internal_vld_params
.get("vim-network-id"):
375 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
376 internal_vld_params
["name"], "vim-network-id"),
377 internal_vld_params
["vim-network-id"])
378 if internal_vld_params
.get("ip-profile"):
379 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
380 internal_vld_params
["name"], "ip-profile"),
381 ip_profile_2_RO(internal_vld_params
["ip-profile"]))
382 if internal_vld_params
.get("provider-network"):
384 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
385 internal_vld_params
["name"], "provider-network"),
386 internal_vld_params
["provider-network"].copy())
388 for icp_params
in get_iterable(internal_vld_params
, "internal-connection-point"):
391 for vdu_descriptor
in vnf_descriptor
["vdu"]:
392 for vdu_interface
in vdu_descriptor
["interface"]:
393 if vdu_interface
.get("internal-connection-point-ref") == icp_params
["id-ref"]:
394 if icp_params
.get("ip-address"):
395 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
396 vdu_descriptor
["id"], "interfaces",
397 vdu_interface
["name"], "ip_address"),
398 icp_params
["ip-address"])
400 if icp_params
.get("mac-address"):
401 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
402 vdu_descriptor
["id"], "interfaces",
403 vdu_interface
["name"], "mac_address"),
404 icp_params
["mac-address"])
410 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
411 "internal-vld:id-ref={} is not present at vnfd:internal-"
412 "connection-point".format(vnf_params
["member-vnf-index"],
413 icp_params
["id-ref"]))
415 for vld_params
in get_iterable(ns_params
, "vld"):
416 if "ip-profile" in vld_params
:
417 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "ip-profile"),
418 ip_profile_2_RO(vld_params
["ip-profile"]))
420 if vld_params
.get("provider-network"):
422 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "provider-network"),
423 vld_params
["provider-network"].copy())
425 if "wimAccountId" in vld_params
and vld_params
["wimAccountId"] is not None:
426 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "wim_account"),
427 wim_account_2_RO(vld_params
["wimAccountId"])),
428 if vld_params
.get("vim-network-name"):
430 if isinstance(vld_params
["vim-network-name"], dict):
431 for vim_account
, vim_net
in vld_params
["vim-network-name"].items():
432 RO_vld_sites
.append({
433 "netmap-use": vim_net
,
434 "datacenter": vim_account_2_RO(vim_account
)
436 else: # isinstance str
437 RO_vld_sites
.append({"netmap-use": vld_params
["vim-network-name"]})
439 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={} "
604 .format(vnf_index
, vdur
["vdu-id-ref"], ifacer
["name"]))
605 vnfr_update
["vdur.{}".format(vdu_index
)] = vdur
608 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} count_index={} from "
609 "VIM info".format(vnf_index
, vdur
["vdu-id-ref"], vdur
["count-index"]))
611 for vld_index
, vld
in enumerate(get_iterable(db_vnfr
, "vld")):
612 for net_RO
in get_iterable(nsr_desc_RO
, "nets"):
613 if vld
["id"] != net_RO
.get("vnf_net_osm_id"):
615 vld
["vim-id"] = net_RO
.get("vim_net_id")
616 vld
["name"] = net_RO
.get("vim_name")
617 vld
["status"] = net_RO
.get("status")
618 vld
["status-detailed"] = net_RO
.get("error_msg")
619 vnfr_update
["vld.{}".format(vld_index
)] = vld
622 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vld={} from VIM info".format(
623 vnf_index
, vld
["id"]))
625 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
629 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} from VIM info".format(vnf_index
))
632 def _get_ns_config_info(vca_deployed_list
):
634 Generates a mapping between vnf,vdu elements and the N2VC id
635 :param vca_deployed_list: List of database _admin.deploy.VCA that contains this list
636 :return: a dictionary with {osm-config-mapping: {}} where its element contains:
637 "<member-vnf-index>": <N2VC-id> for a vnf configuration, or
638 "<member-vnf-index>.<vdu.id>.<vdu replica(0, 1,..)>": <N2VC-id> for a vdu configuration
641 ns_config_info
= {"osm-config-mapping": mapping
}
642 for vca
in vca_deployed_list
:
643 if not vca
["member-vnf-index"]:
645 if not vca
["vdu_id"]:
646 mapping
[vca
["member-vnf-index"]] = vca
["application"]
648 mapping
["{}.{}.{}".format(vca
["member-vnf-index"], vca
["vdu_id"], vca
["vdu_count_index"])] =\
650 return ns_config_info
653 def _get_initial_config_primitive_list(desc_primitive_list
, vca_deployed
):
655 Generates a list of initial-config-primitive based on the list provided by the descriptor. It includes internal
656 primitives as verify-ssh-credentials, or config when needed
657 :param desc_primitive_list: information of the descriptor
658 :param vca_deployed: information of the deployed, needed for known if it is related to an NS, VNF, VDU and if
659 this element contains a ssh public key
660 :return: The modified list. Can ba an empty list, but always a list
662 if desc_primitive_list
:
663 primitive_list
= desc_primitive_list
.copy()
666 # look for primitive config, and get the position. None if not present
667 config_position
= None
668 for index
, primitive
in enumerate(primitive_list
):
669 if primitive
["name"] == "config":
670 config_position
= index
673 # for NS, add always a config primitive if not present (bug 874)
674 if not vca_deployed
["member-vnf-index"] and config_position
is None:
675 primitive_list
.insert(0, {"name": "config", "parameter": []})
677 # for VNF/VDU add verify-ssh-credentials after config
678 if vca_deployed
["member-vnf-index"] and config_position
is not None and vca_deployed
.get("ssh-public-key"):
679 primitive_list
.insert(config_position
+ 1, {"name": "verify-ssh-credentials", "parameter": []})
680 return primitive_list
682 async def instantiate_RO(self
, logging_text
, nsr_id
, nsd
, db_nsr
,
683 db_nslcmop
, db_vnfrs
, db_vnfds_ref
, n2vc_key_list
):
686 RO_descriptor_number
= 0 # number of descriptors created at RO
687 vnf_index_2_RO_id
= {} # map between vnfd/nsd id to the id used at RO
688 start_deploy
= time()
689 vdu_flag
= False # If any of the VNFDs has VDUs
690 ns_params
= db_nslcmop
.get("operationParams")
694 # get vnfds, instantiate at RO
696 for c_vnf
in nsd
.get("constituent-vnfd", ()):
697 member_vnf_index
= c_vnf
["member-vnf-index"]
698 vnfd
= db_vnfds_ref
[c_vnf
['vnfd-id-ref']]
701 vnfd_ref
= vnfd
["id"]
702 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Creating vnfd='{}' member_vnf_index='{}' at" \
703 " RO".format(vnfd_ref
, member_vnf_index
)
704 # self.logger.debug(logging_text + step)
705 vnfd_id_RO
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, member_vnf_index
[:23])
706 vnf_index_2_RO_id
[member_vnf_index
] = vnfd_id_RO
707 RO_descriptor_number
+= 1
709 # look position at deployed.RO.vnfd if not present it will be appended at the end
710 for index
, vnf_deployed
in enumerate(db_nsr
["_admin"]["deployed"]["RO"]["vnfd"]):
711 if vnf_deployed
["member-vnf-index"] == member_vnf_index
:
714 index
= len(db_nsr
["_admin"]["deployed"]["RO"]["vnfd"])
715 db_nsr
["_admin"]["deployed"]["RO"]["vnfd"].append(None)
718 RO_update
= {"member-vnf-index": member_vnf_index
}
719 vnfd_list
= await self
.RO
.get_list("vnfd", filter_by
={"osm_id": vnfd_id_RO
})
721 RO_update
["id"] = vnfd_list
[0]["uuid"]
722 self
.logger
.debug(logging_text
+ "vnfd='{}' member_vnf_index='{}' exists at RO. Using RO_id={}".
723 format(vnfd_ref
, member_vnf_index
, vnfd_list
[0]["uuid"]))
725 vnfd_RO
= self
.vnfd2RO(vnfd
, vnfd_id_RO
, db_vnfrs
[c_vnf
["member-vnf-index"]].
726 get("additionalParamsForVnf"), nsr_id
)
727 desc
= await self
.RO
.create("vnfd", descriptor
=vnfd_RO
)
728 RO_update
["id"] = desc
["uuid"]
729 self
.logger
.debug(logging_text
+ "vnfd='{}' member_vnf_index='{}' created at RO. RO_id={}".format(
730 vnfd_ref
, member_vnf_index
, desc
["uuid"]))
731 db_nsr_update
["_admin.deployed.RO.vnfd.{}".format(index
)] = RO_update
732 db_nsr
["_admin"]["deployed"]["RO"]["vnfd"][index
] = RO_update
733 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
734 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
738 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Creating nsd={} at RO".format(nsd_ref
)
739 # self.logger.debug(logging_text + step)
741 RO_osm_nsd_id
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, nsd_ref
[:23])
742 RO_descriptor_number
+= 1
743 nsd_list
= await self
.RO
.get_list("nsd", filter_by
={"osm_id": RO_osm_nsd_id
})
745 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= nsd_list
[0]["uuid"]
746 self
.logger
.debug(logging_text
+ "nsd={} exists at RO. Using RO_id={}".format(
747 nsd_ref
, RO_nsd_uuid
))
749 nsd_RO
= deepcopy(nsd
)
750 nsd_RO
["id"] = RO_osm_nsd_id
751 nsd_RO
.pop("_id", None)
752 nsd_RO
.pop("_admin", None)
753 for c_vnf
in nsd_RO
.get("constituent-vnfd", ()):
754 member_vnf_index
= c_vnf
["member-vnf-index"]
755 c_vnf
["vnfd-id-ref"] = vnf_index_2_RO_id
[member_vnf_index
]
756 for c_vld
in nsd_RO
.get("vld", ()):
757 for cp
in c_vld
.get("vnfd-connection-point-ref", ()):
758 member_vnf_index
= cp
["member-vnf-index-ref"]
759 cp
["vnfd-id-ref"] = vnf_index_2_RO_id
[member_vnf_index
]
761 desc
= await self
.RO
.create("nsd", descriptor
=nsd_RO
)
762 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
763 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= desc
["uuid"]
764 self
.logger
.debug(logging_text
+ "nsd={} created at RO. RO_id={}".format(nsd_ref
, RO_nsd_uuid
))
765 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
766 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
769 # if present use it unless in error status
770 RO_nsr_id
= deep_get(db_nsr
, ("_admin", "deployed", "RO", "nsr_id"))
773 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Looking for existing ns at RO"
774 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
775 desc
= await self
.RO
.show("ns", RO_nsr_id
)
776 except ROclient
.ROClientException
as e
:
777 if e
.http_code
!= HTTPStatus
.NOT_FOUND
:
779 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
781 ns_status
, ns_status_info
= self
.RO
.check_ns_status(desc
)
782 db_nsr_update
["_admin.deployed.RO.nsr_status"] = ns_status
783 if ns_status
== "ERROR":
784 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Deleting ns at RO. RO_ns_id={}"\
786 self
.logger
.debug(logging_text
+ step
)
787 await self
.RO
.delete("ns", RO_nsr_id
)
788 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
790 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Checking dependencies"
791 # self.logger.debug(logging_text + step)
793 # check if VIM is creating and wait look if previous tasks in process
794 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account", ns_params
["vimAccountId"])
796 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
797 self
.logger
.debug(logging_text
+ step
)
798 await asyncio
.wait(task_dependency
, timeout
=3600)
799 if ns_params
.get("vnf"):
800 for vnf
in ns_params
["vnf"]:
801 if "vimAccountId" in vnf
:
802 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account",
805 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
806 self
.logger
.debug(logging_text
+ step
)
807 await asyncio
.wait(task_dependency
, timeout
=3600)
809 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Checking instantiation parameters"
811 RO_ns_params
= self
.ns_params_2_RO(ns_params
, nsd
, db_vnfds_ref
, n2vc_key_list
)
813 step
= db_nsr_update
["detailed-status"] = "Deploying ns at VIM"
814 # step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Deploying ns at VIM"
815 desc
= await self
.RO
.create("ns", descriptor
=RO_ns_params
, name
=db_nsr
["name"], scenario
=RO_nsd_uuid
)
816 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = desc
["uuid"]
817 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
818 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "BUILD"
819 self
.logger
.debug(logging_text
+ "ns created at RO. RO_id={}".format(desc
["uuid"]))
820 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
821 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
823 # wait until NS is ready
824 step
= ns_status_detailed
= detailed_status
= "Waiting VIM to deploy ns. RO_ns_id={}".format(RO_nsr_id
)
825 detailed_status_old
= None
826 self
.logger
.debug(logging_text
+ step
)
828 while time() <= start_deploy
+ self
.total_deploy_timeout
:
829 desc
= await self
.RO
.show("ns", RO_nsr_id
)
830 ns_status
, ns_status_info
= self
.RO
.check_ns_status(desc
)
831 db_nsr_update
["_admin.deployed.RO.nsr_status"] = ns_status
832 if ns_status
== "ERROR":
833 raise ROclient
.ROClientException(ns_status_info
)
834 elif ns_status
== "BUILD":
835 detailed_status
= ns_status_detailed
+ "; {}".format(ns_status_info
)
836 elif ns_status
== "ACTIVE":
837 step
= detailed_status
= "Waiting for management IP address reported by the VIM. Updating VNFRs"
840 self
.ns_update_vnfr(db_vnfrs
, desc
)
842 except LcmExceptionNoMgmtIP
:
845 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
846 if detailed_status
!= detailed_status_old
:
847 detailed_status_old
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = detailed_status
848 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
849 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
850 await asyncio
.sleep(5, loop
=self
.loop
)
851 else: # total_deploy_timeout
852 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
854 step
= "Updating NSR"
855 self
.ns_update_nsr(db_nsr_update
, db_nsr
, desc
)
857 db_nsr_update
["_admin.deployed.RO.operational-status"] = "running"
858 db_nsr
["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
859 db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
860 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
861 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
863 step
= "Deployed at VIM"
864 self
.logger
.debug(logging_text
+ step
)
866 async def wait_vm_up_insert_key_ro(self
, logging_text
, nsr_id
, vnfr_id
, vdu_id
, vdu_index
, pub_key
=None, user
=None):
868 Wait for ip addres at RO, and optionally, insert public key in virtual machine
869 :param logging_text: prefix use for logging
874 :param pub_key: public ssh key to inject, None to skip
875 :param user: user to apply the public ssh key
879 # self.logger.debug(logging_text + "Starting wait_vm_up_insert_key_ro")
887 await asyncio
.sleep(10, loop
=self
.loop
)
888 # wait until NS is deployed at RO
890 db_nsrs
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
891 ro_nsr_id
= deep_get(db_nsrs
, ("_admin", "deployed", "RO", "nsr_id"))
896 if not target_vdu_id
:
897 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnfr_id
})
899 ip_address
= db_vnfr
.get("ip-address")
902 for vdur
in get_iterable(db_vnfr
, "vdur"):
903 if (vdur
["vdu-id-ref"] == vdu_id
and vdur
["count-index"] == vdu_index
) or \
904 (ip_address
and vdur
.get("ip-address") == ip_address
):
905 if vdur
.get("status") == "ACTIVE":
906 target_vdu_id
= vdur
["vdu-id-ref"]
907 elif vdur
.get("status") == "ERROR":
908 raise LcmException("Cannot inject ssh-key because target VM is in error state")
911 raise LcmException("Not found vnfr_id={}, vdu_index={}, vdu_index={}".format(
912 vnfr_id
, vdu_id
, vdu_index
915 if not target_vdu_id
:
918 # self.logger.debug(logging_text + "IP address={}".format(ip_address))
920 # inject public key into machine
922 # self.logger.debug(logging_text + "Inserting RO key")
924 ro_vm_id
= "{}-{}".format(db_vnfr
["member-vnf-index-ref"], target_vdu_id
) # TODO add vdu_index
925 result_dict
= await self
.RO
.create_action(
927 item_id_name
=ro_nsr_id
,
928 descriptor
={"add_public_key": pub_key
, "vms": [ro_vm_id
], "user": user
}
930 # result_dict contains the format {VM-id: {vim_result: 200, description: text}}
931 if not result_dict
or not isinstance(result_dict
, dict):
932 raise LcmException("Unknown response from RO when injecting key")
933 for result
in result_dict
.values():
934 if result
.get("vim_result") == 200:
937 raise ROclient
.ROClientException("error injecting key: {}".format(
938 result
.get("description")))
940 except ROclient
.ROClientException
as e
:
942 self
.logger
.debug(logging_text
+ "error injecting key: {}. Retrying until {} seconds".
946 raise LcmException("Reaching max tries injecting key. Error: {}".format(e
))
952 async def instantiate_N2VC(self
, logging_text
, vca_index
, nsi_id
, db_nsr
, db_vnfr
, vdu_id
,
953 kdu_name
, vdu_index
, config_descriptor
, deploy_params
, base_folder
):
954 nsr_id
= db_nsr
["_id"]
955 db_update_entry
= "_admin.deployed.VCA.{}.".format(vca_index
)
956 vca_deployed_list
= db_nsr
["_admin"]["deployed"]["VCA"]
957 vca_deployed
= db_nsr
["_admin"]["deployed"]["VCA"][vca_index
]
959 'collection': 'nsrs',
960 'filter': {'_id': nsr_id
},
961 'path': db_update_entry
963 logging_text
+= "member_vnf_index={} vdu_id={}, vdu_index={} ".format(db_vnfr
["member-vnf-index-ref"],
970 vnfr_id
= db_vnfr
["_id"]
972 namespace
= "{nsi}.{ns}".format(
973 nsi
=nsi_id
if nsi_id
else "",
976 namespace
+= "." + vnfr_id
978 namespace
+= ".{}-{}".format(vdu_id
, vdu_index
or 0)
981 artifact_path
= "/{}/{}/charms/{}".format(
982 base_folder
["folder"],
983 base_folder
["pkg-dir"],
984 config_descriptor
["juju"]["charm"]
987 is_proxy_charm
= deep_get(config_descriptor
, ('juju', 'charm')) is not None
988 if deep_get(config_descriptor
, ('juju', 'proxy')) is False:
989 is_proxy_charm
= False
991 # n2vc_redesign STEP 3.1
993 # find old ee_id if exists
994 ee_id
= vca_deployed
.get("ee_id")
996 # create or register execution environment in VCA
998 step
= "create execution environment"
999 self
.logger
.debug(logging_text
+ step
)
1000 ee_id
, credentials
= await self
.n2vc
.create_execution_environment(namespace
=namespace
,
1004 step
= "Waiting to VM being up and getting IP address"
1005 self
.logger
.debug(logging_text
+ step
)
1006 rw_mgmt_ip
= await self
.wait_vm_up_insert_key_ro(logging_text
, nsr_id
, vnfr_id
, vdu_id
, vdu_index
,
1007 user
=None, pub_key
=None)
1008 credentials
= {"hostname": rw_mgmt_ip
}
1010 username
= deep_get(config_descriptor
, ("config-access", "ssh-access", "default-user"))
1011 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1012 # merged. Meanwhile let's get username from initial-config-primitive
1013 if not username
and config_descriptor
.get("initial-config-primitive"):
1014 for config_primitive
in config_descriptor
["initial-config-primitive"]:
1015 for param
in config_primitive
.get("parameter", ()):
1016 if param
["name"] == "ssh-username":
1017 username
= param
["value"]
1020 raise LcmException("Cannot determine the username neither with 'initial-config-promitive' nor with "
1021 "'config-access.ssh-access.default-user'")
1022 credentials
["username"] = username
1023 # n2vc_redesign STEP 3.2
1025 step
= "register execution environment {}".format(credentials
)
1026 self
.logger
.debug(logging_text
+ step
)
1027 ee_id
= await self
.n2vc
.register_execution_environment(credentials
=credentials
, namespace
=namespace
,
1030 # for compatibility with MON/POL modules, the need model and application name at database
1031 # TODO ask to N2VC instead of assuming the format "model_name.application_name"
1032 ee_id_parts
= ee_id
.split('.')
1033 model_name
= ee_id_parts
[0]
1034 application_name
= ee_id_parts
[1]
1035 self
.update_db_2("nsrs", nsr_id
, {db_update_entry
+ "model": model_name
,
1036 db_update_entry
+ "application": application_name
,
1037 db_update_entry
+ "ee_id": ee_id
})
1039 # n2vc_redesign STEP 3.3
1041 step
= "Install configuration Software"
1042 # TODO check if already done
1043 self
.logger
.debug(logging_text
+ step
)
1044 await self
.n2vc
.install_configuration_sw(ee_id
=ee_id
, artifact_path
=artifact_path
, db_dict
=db_dict
)
1046 # if SSH access is required, then get execution environment SSH public
1047 if is_proxy_charm
: # if native charm we have waited already to VM be UP
1050 if deep_get(config_descriptor
, ("config-access", "ssh-access", "required")):
1051 # Needed to inject a ssh key
1052 user
= deep_get(config_descriptor
, ("config-access", "ssh-access", "default-user"))
1053 step
= "Install configuration Software, getting public ssh key"
1054 pub_key
= await self
.n2vc
.get_ee_ssh_public__key(ee_id
=ee_id
, db_dict
=db_dict
)
1056 step
= "Insert public key into VM"
1058 step
= "Waiting to VM being up and getting IP address"
1059 self
.logger
.debug(logging_text
+ step
)
1061 # n2vc_redesign STEP 5.1
1062 # wait for RO (ip-address) Insert pub_key into VM
1063 rw_mgmt_ip
= await self
.wait_vm_up_insert_key_ro(logging_text
, nsr_id
, vnfr_id
, vdu_id
, vdu_index
,
1064 user
=user
, pub_key
=pub_key
)
1066 self
.logger
.debug(logging_text
+ ' VM_ip_address={}'.format(rw_mgmt_ip
))
1068 # store rw_mgmt_ip in deploy params for later replacement
1069 deploy_params
["rw_mgmt_ip"] = rw_mgmt_ip
1071 # n2vc_redesign STEP 6 Execute initial config primitive
1072 step
= 'execute initial config primitive'
1073 initial_config_primitive_list
= config_descriptor
.get('initial-config-primitive')
1075 # sort initial config primitives by 'seq'
1077 initial_config_primitive_list
.sort(key
=lambda val
: int(val
['seq']))
1078 except Exception as e
:
1079 self
.logger
.error(logging_text
+ step
+ ": " + str(e
))
1081 # add config if not present for NS charm
1082 initial_config_primitive_list
= self
._get
_initial
_config
_primitive
_list
(initial_config_primitive_list
,
1085 for initial_config_primitive
in initial_config_primitive_list
:
1086 # adding information on the vca_deployed if it is a NS execution environment
1087 if not vca_deployed
["member-vnf-index"]:
1088 deploy_params
["ns_config_info"] = self
._get
_ns
_config
_info
(vca_deployed_list
)
1089 # TODO check if already done
1090 primitive_params_
= self
._map
_primitive
_params
(initial_config_primitive
, {}, deploy_params
)
1092 step
= "execute primitive '{}' params '{}'".format(initial_config_primitive
["name"], primitive_params_
)
1093 self
.logger
.debug(logging_text
+ step
)
1094 await self
.n2vc
.exec_primitive(
1096 primitive_name
=initial_config_primitive
["name"],
1097 params_dict
=primitive_params_
,
1100 # TODO register in database that primitive is done
1102 step
= "instantiated at VCA"
1103 self
.logger
.debug(logging_text
+ step
)
1105 except Exception as e
: # TODO not use Exception but N2VC exception
1106 raise Exception("{} {}".format(step
, e
)) from e
1107 # TODO raise N2VC exception with 'step' extra information
1109 async def instantiate(self
, nsr_id
, nslcmop_id
):
1112 :param nsr_id: ns instance to deploy
1113 :param nslcmop_id: operation to run
1117 # Try to lock HA task here
1118 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
1119 if not task_is_locked_by_me
:
1120 self
.logger
.debug('instantiate() task is not locked by me')
1123 logging_text
= "Task ns={} instantiate={} ".format(nsr_id
, nslcmop_id
)
1124 self
.logger
.debug(logging_text
+ "Enter")
1126 # get all needed from database
1128 # database nsrs record
1131 # database nslcmops record
1134 # update operation on nsrs
1135 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
1136 "_admin.current-operation": nslcmop_id
,
1137 "_admin.operation-type": "instantiate"}
1138 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1140 # update operation on nslcmops
1141 db_nslcmop_update
= {}
1143 nslcmop_operation_state
= None
1144 db_vnfrs
= {} # vnf's info indexed by member-index
1146 task_instantiation_list
= []
1149 # wait for any previous tasks in process
1150 step
= "Waiting for previous operations to terminate"
1151 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
1153 # STEP 0: Reading database (nslcmops, nsrs, nsds, vnfrs, vnfds)
1155 # read from db: operation
1156 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
1157 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1160 step
= "Getting nsr={} from db".format(nsr_id
)
1161 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1162 # nsd is replicated into ns (no db read)
1164 # nsr_name = db_nsr["name"] # TODO short-name??
1166 # read from db: vnf's of this ns
1167 step
= "Getting vnfrs from db"
1168 self
.logger
.debug(logging_text
+ step
)
1169 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1171 # read from db: vnfd's for every vnf
1172 db_vnfds_ref
= {} # every vnfd data indexed by vnf name
1173 db_vnfds
= {} # every vnfd data indexed by vnf id
1174 db_vnfds_index
= {} # every vnfd data indexed by vnf member-index
1176 # for each vnf in ns, read vnfd
1177 for vnfr
in db_vnfrs_list
:
1178 db_vnfrs
[vnfr
["member-vnf-index-ref"]] = vnfr
# vnf's dict indexed by member-index: '1', '2', etc
1179 vnfd_id
= vnfr
["vnfd-id"] # vnfd uuid for this vnf
1180 vnfd_ref
= vnfr
["vnfd-ref"] # vnfd name for this vnf
1181 # if we haven't this vnfd, read it from db
1182 if vnfd_id
not in db_vnfds
:
1184 step
= "Getting vnfd={} id='{}' from db".format(vnfd_id
, vnfd_ref
)
1185 self
.logger
.debug(logging_text
+ step
)
1186 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
1189 db_vnfds_ref
[vnfd_ref
] = vnfd
# vnfd's indexed by name
1190 db_vnfds
[vnfd_id
] = vnfd
# vnfd's indexed by id
1191 db_vnfds_index
[vnfr
["member-vnf-index-ref"]] = db_vnfds
[vnfd_id
] # vnfd's indexed by member-index
1193 # Get or generates the _admin.deployed.VCA list
1194 vca_deployed_list
= None
1195 if db_nsr
["_admin"].get("deployed"):
1196 vca_deployed_list
= db_nsr
["_admin"]["deployed"].get("VCA")
1197 if vca_deployed_list
is None:
1198 vca_deployed_list
= []
1199 db_nsr_update
["_admin.deployed.VCA"] = vca_deployed_list
1200 # add _admin.deployed.VCA to db_nsr dictionary, value=vca_deployed_list
1201 populate_dict(db_nsr
, ("_admin", "deployed", "VCA"), vca_deployed_list
)
1202 elif isinstance(vca_deployed_list
, dict):
1203 # maintain backward compatibility. Change a dict to list at database
1204 vca_deployed_list
= list(vca_deployed_list
.values())
1205 db_nsr_update
["_admin.deployed.VCA"] = vca_deployed_list
1206 populate_dict(db_nsr
, ("_admin", "deployed", "VCA"), vca_deployed_list
)
1208 db_nsr_update
["detailed-status"] = "creating"
1209 db_nsr_update
["operational-status"] = "init"
1211 if not isinstance(deep_get(db_nsr
, ("_admin", "deployed", "RO", "vnfd")), list):
1212 populate_dict(db_nsr
, ("_admin", "deployed", "RO", "vnfd"), [])
1213 db_nsr_update
["_admin.deployed.RO.vnfd"] = []
1215 # set state to INSTANTIATED. When instantiated NBI will not delete directly
1216 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1217 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1218 self
.logger
.debug(logging_text
+ "Before deploy_kdus")
1219 # Call to deploy_kdus in case exists the "vdu:kdu" param
1220 task_kdu
= asyncio
.ensure_future(
1222 logging_text
=logging_text
,
1228 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_KDUs", task_kdu
)
1229 task_instantiation_list
.append(task_kdu
)
1230 # n2vc_redesign STEP 1 Get VCA public ssh-key
1231 # feature 1429. Add n2vc public key to needed VMs
1232 n2vc_key
= self
.n2vc
.get_public_key()
1233 n2vc_key_list
= [n2vc_key
]
1234 if self
.vca_config
.get("public_key"):
1235 n2vc_key_list
.append(self
.vca_config
["public_key"])
1237 # n2vc_redesign STEP 2 Deploy Network Scenario
1238 task_ro
= asyncio
.ensure_future(
1239 self
.instantiate_RO(
1240 logging_text
=logging_text
,
1244 db_nslcmop
=db_nslcmop
,
1246 db_vnfds_ref
=db_vnfds_ref
,
1247 n2vc_key_list
=n2vc_key_list
1250 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_RO", task_ro
)
1251 task_instantiation_list
.append(task_ro
)
1253 # n2vc_redesign STEP 3 to 6 Deploy N2VC
1254 step
= "Looking for needed vnfd to configure with proxy charm"
1255 self
.logger
.debug(logging_text
+ step
)
1257 nsi_id
= None # TODO put nsi_id when this nsr belongs to a NSI
1258 # get_iterable() returns a value from a dict or empty tuple if key does not exist
1259 for c_vnf
in get_iterable(nsd
, "constituent-vnfd"):
1260 vnfd_id
= c_vnf
["vnfd-id-ref"]
1261 vnfd
= db_vnfds_ref
[vnfd_id
]
1262 member_vnf_index
= str(c_vnf
["member-vnf-index"])
1263 db_vnfr
= db_vnfrs
[member_vnf_index
]
1264 base_folder
= vnfd
["_admin"]["storage"]
1270 # Get additional parameters
1272 if db_vnfr
.get("additionalParamsForVnf"):
1273 deploy_params
= self
._format
_additional
_params
(db_vnfr
["additionalParamsForVnf"].copy())
1275 descriptor_config
= vnfd
.get("vnf-configuration")
1276 if descriptor_config
and descriptor_config
.get("juju"):
1278 logging_text
=logging_text
,
1281 nslcmop_id
=nslcmop_id
,
1287 member_vnf_index
=member_vnf_index
,
1288 vdu_index
=vdu_index
,
1290 deploy_params
=deploy_params
,
1291 descriptor_config
=descriptor_config
,
1292 base_folder
=base_folder
,
1293 task_instantiation_list
=task_instantiation_list
1296 # Deploy charms for each VDU that supports one.
1297 for vdud
in get_iterable(vnfd
, 'vdu'):
1299 descriptor_config
= vdud
.get('vdu-configuration')
1300 vdur
= next((x
for x
in db_vnfr
["vdur"] if x
["vdu-id-ref"] == vdu_id
), None)
1301 if vdur
.get("additionalParams"):
1302 deploy_params_vdu
= self
._format
_additional
_params
(vdur
["additionalParams"])
1304 deploy_params_vdu
= deploy_params
1305 if descriptor_config
and descriptor_config
.get("juju"):
1306 # look for vdu index in the db_vnfr["vdu"] section
1307 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
1308 # if vdur["vdu-id-ref"] == vdu_id:
1311 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
1312 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
1313 # vdu_name = vdur.get("name")
1316 for vdu_index
in range(int(vdud
.get("count", 1))):
1317 # TODO vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
1319 logging_text
=logging_text
,
1322 nslcmop_id
=nslcmop_id
,
1328 member_vnf_index
=member_vnf_index
,
1329 vdu_index
=vdu_index
,
1331 deploy_params
=deploy_params_vdu
,
1332 descriptor_config
=descriptor_config
,
1333 base_folder
=base_folder
,
1334 task_instantiation_list
=task_instantiation_list
1336 for kdud
in get_iterable(vnfd
, 'kdu'):
1337 kdu_name
= kdud
["name"]
1338 descriptor_config
= kdud
.get('kdu-configuration')
1339 if descriptor_config
and descriptor_config
.get("juju"):
1343 # look for vdu index in the db_vnfr["vdu"] section
1344 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
1345 # if vdur["vdu-id-ref"] == vdu_id:
1348 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
1349 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
1350 # vdu_name = vdur.get("name")
1354 logging_text
=logging_text
,
1357 nslcmop_id
=nslcmop_id
,
1363 member_vnf_index
=member_vnf_index
,
1364 vdu_index
=vdu_index
,
1366 deploy_params
=deploy_params
,
1367 descriptor_config
=descriptor_config
,
1368 base_folder
=base_folder
,
1369 task_instantiation_list
=task_instantiation_list
1372 # Check if this NS has a charm configuration
1373 descriptor_config
= nsd
.get("ns-configuration")
1374 if descriptor_config
and descriptor_config
.get("juju"):
1377 member_vnf_index
= None
1383 # Get additional parameters
1385 if db_nsr
.get("additionalParamsForNs"):
1386 deploy_params
= self
._format
_additional
_params
(db_nsr
["additionalParamsForNs"].copy())
1387 base_folder
= nsd
["_admin"]["storage"]
1389 logging_text
=logging_text
,
1392 nslcmop_id
=nslcmop_id
,
1398 member_vnf_index
=member_vnf_index
,
1399 vdu_index
=vdu_index
,
1401 deploy_params
=deploy_params
,
1402 descriptor_config
=descriptor_config
,
1403 base_folder
=base_folder
,
1404 task_instantiation_list
=task_instantiation_list
1407 # Wait until all tasks of "task_instantiation_list" have been finished
1409 # while time() <= start_deploy + self.total_deploy_timeout:
1411 timeout
= 3600 # time() - start_deploy
1412 task_instantiation_set
= set(task_instantiation_list
) # build a set with tasks
1415 if len(task_instantiation_set
) > 0:
1416 done
, pending
= await asyncio
.wait(task_instantiation_set
, timeout
=timeout
)
1418 error_text
= "timeout"
1420 if task
.cancelled():
1422 error_text
= "cancelled"
1424 exc
= task
.exception()
1426 error_text
= str(exc
)
1429 db_nsr_update
["config-status"] = "failed"
1430 error_text
= "fail configuring " + error_text
1431 db_nsr_update
["detailed-status"] = error_text
1432 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED_TEMP"
1433 db_nslcmop_update
["detailed-status"] = error_text
1434 db_nslcmop_update
["statusEnteredTime"] = time()
1437 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
1438 db_nslcmop_update
["statusEnteredTime"] = time()
1439 db_nslcmop_update
["detailed-status"] = "done"
1440 db_nsr_update
["config-status"] = "configured"
1441 db_nsr_update
["detailed-status"] = "done"
1443 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
1444 self
.logger
.error(logging_text
+ "Exit Exception while '{}': {}".format(step
, e
))
1446 except asyncio
.CancelledError
:
1447 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1448 exc
= "Operation was cancelled"
1449 except Exception as e
:
1450 exc
= traceback
.format_exc()
1451 self
.logger
.critical(logging_text
+ "Exit Exception {} while '{}': {}".format(type(e
).__name
__, step
, e
),
1456 db_nsr_update
["detailed-status"] = "ERROR {}: {}".format(step
, exc
)
1457 db_nsr_update
["operational-status"] = "failed"
1459 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
1460 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
1461 db_nslcmop_update
["statusEnteredTime"] = time()
1464 db_nsr_update
["_admin.nslcmop"] = None
1465 db_nsr_update
["_admin.current-operation"] = None
1466 db_nsr_update
["_admin.operation-type"] = None
1467 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1468 if db_nslcmop_update
:
1469 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1470 except DbException
as e
:
1471 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
1472 if nslcmop_operation_state
:
1474 await self
.msg
.aiowrite("ns", "instantiated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
1475 "operationState": nslcmop_operation_state
},
1477 except Exception as e
:
1478 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1480 self
.logger
.debug(logging_text
+ "Exit")
1481 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_instantiate")
1483 async def deploy_kdus(self
, logging_text
, nsr_id
, db_nsr
, db_vnfrs
):
1484 # Launch kdus if present in the descriptor
1486 k8scluster_id_2_uuic
= {"helm-chart": {}, "juju-bundle": {}}
1488 def _get_cluster_id(cluster_id
, cluster_type
):
1489 nonlocal k8scluster_id_2_uuic
1490 if cluster_id
in k8scluster_id_2_uuic
[cluster_type
]:
1491 return k8scluster_id_2_uuic
[cluster_type
][cluster_id
]
1493 db_k8scluster
= self
.db
.get_one("k8sclusters", {"_id": cluster_id
}, fail_on_empty
=False)
1494 if not db_k8scluster
:
1495 raise LcmException("K8s cluster {} cannot be found".format(cluster_id
))
1496 k8s_id
= deep_get(db_k8scluster
, ("_admin", cluster_type
, "id"))
1498 raise LcmException("K8s cluster '{}' has not been initilized for '{}'".format(cluster_id
, cluster_type
))
1499 k8scluster_id_2_uuic
[cluster_type
][cluster_id
] = k8s_id
1502 logging_text
+= "Deploy kdus: "
1504 db_nsr_update
= {"_admin.deployed.K8s": []}
1505 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1507 # Look for all vnfds
1510 for vnfr_data
in db_vnfrs
.values():
1511 for kdur
in get_iterable(vnfr_data
, "kdur"):
1512 desc_params
= self
._format
_additional
_params
(kdur
.get("additionalParams"))
1514 k8sclustertype
= None
1517 if kdur
.get("helm-chart"):
1518 kdumodel
= kdur
["helm-chart"]
1519 k8sclustertype
= "chart"
1520 k8sclustertype_full
= "helm-chart"
1521 elif kdur
.get("juju-bundle"):
1522 kdumodel
= kdur
["juju-bundle"]
1523 k8sclustertype
= "juju"
1524 k8sclustertype_full
= "juju-bundle"
1526 error_text
= "kdu type is neither helm-chart not juju-bundle. Maybe an old NBI version is" \
1530 cluster_uuid
= _get_cluster_id(kdur
["k8s-cluster"]["id"], k8sclustertype_full
)
1531 except LcmException
as e
:
1533 step
= "Instantiate KDU {} in k8s cluster {}".format(kdur
["kdu-name"], cluster_uuid
)
1535 k8s_instace_info
= {"kdu-instance": None, "k8scluster-uuid": cluster_uuid
,
1536 "k8scluster-type": k8sclustertype
,
1537 "kdu-name": kdur
["kdu-name"], "kdu-model": kdumodel
}
1539 k8s_instace_info
["detailed-status"] = error_text
1540 db_nsr_update
["_admin.deployed.K8s.{}".format(index
)] = k8s_instace_info
1541 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1545 db_dict
= {"collection": "nsrs", "filter": {"_id": nsr_id
}, "path": "_admin.deployed.K8s."
1547 if k8sclustertype
== "chart":
1548 task
= asyncio
.ensure_future(
1549 self
.k8sclusterhelm
.install(cluster_uuid
=cluster_uuid
, kdu_model
=kdumodel
, atomic
=True,
1550 params
=desc_params
, db_dict
=db_dict
, timeout
=3600)
1553 task
= self
.k8sclusterjuju
.install(cluster_uuid
=cluster_uuid
, kdu_model
=kdumodel
,
1554 atomic
=True, params
=desc_params
,
1555 db_dict
=db_dict
, timeout
=600)
1557 pending_tasks
[task
] = "_admin.deployed.K8s.{}.".format(index
)
1559 if not pending_tasks
:
1561 self
.logger
.debug(logging_text
+ 'Waiting for terminate pending tasks...')
1562 pending_list
= list(pending_tasks
.keys())
1564 done_list
, pending_list
= await asyncio
.wait(pending_list
, timeout
=30*60,
1565 return_when
=asyncio
.FIRST_COMPLETED
)
1566 if not done_list
: # timeout
1567 for task
in pending_list
:
1568 db_nsr_update
[pending_tasks(task
) + "detailed-status"] = "Timeout"
1570 for task
in done_list
:
1571 exc
= task
.exception()
1573 db_nsr_update
[pending_tasks
[task
] + "detailed-status"] = "{}".format(exc
)
1575 db_nsr_update
[pending_tasks
[task
] + "kdu-instance"] = task
.result()
1577 except Exception as e
:
1578 self
.logger
.critical(logging_text
+ "Exit Exception {} while '{}': {}".format(type(e
).__name
__, step
, e
))
1579 raise LcmException("{} Exit Exception {} while '{}': {}".format(logging_text
, type(e
).__name
__, step
, e
))
1581 # TODO Write in data base
1583 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1585 def _deploy_n2vc(self
, logging_text
, db_nsr
, db_vnfr
, nslcmop_id
, nsr_id
, nsi_id
, vnfd_id
, vdu_id
,
1586 kdu_name
, member_vnf_index
, vdu_index
, vdu_name
, deploy_params
, descriptor_config
,
1587 base_folder
, task_instantiation_list
):
1588 # launch instantiate_N2VC in a asyncio task and register task object
1589 # Look where information of this charm is at database <nsrs>._admin.deployed.VCA
1590 # if not found, create one entry and update database
1592 # fill db_nsr._admin.deployed.VCA.<index>
1594 for vca_index
, vca_deployed
in enumerate(db_nsr
["_admin"]["deployed"]["VCA"]):
1595 if not vca_deployed
:
1597 if vca_deployed
.get("member-vnf-index") == member_vnf_index
and \
1598 vca_deployed
.get("vdu_id") == vdu_id
and \
1599 vca_deployed
.get("kdu_name") == kdu_name
and \
1600 vca_deployed
.get("vdu_count_index", 0) == vdu_index
:
1603 # not found, create one.
1605 "member-vnf-index": member_vnf_index
,
1607 "kdu_name": kdu_name
,
1608 "vdu_count_index": vdu_index
,
1609 "operational-status": "init", # TODO revise
1610 "detailed-status": "", # TODO revise
1611 "step": "initial-deploy", # TODO revise
1613 "vdu_name": vdu_name
,
1616 self
.update_db_2("nsrs", nsr_id
, {"_admin.deployed.VCA.{}".format(vca_index
): vca_deployed
})
1617 db_nsr
["_admin"]["deployed"]["VCA"].append(vca_deployed
)
1620 task_n2vc
= asyncio
.ensure_future(
1621 self
.instantiate_N2VC(
1622 logging_text
=logging_text
,
1623 vca_index
=vca_index
,
1629 vdu_index
=vdu_index
,
1630 deploy_params
=deploy_params
,
1631 config_descriptor
=descriptor_config
,
1632 base_folder
=base_folder
,
1635 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_N2VC-{}".format(vca_index
), task_n2vc
)
1636 task_instantiation_list
.append(task_n2vc
)
1638 # Check if this VNFD has a configured terminate action
1639 def _has_terminate_config_primitive(self
, vnfd
):
1640 vnf_config
= vnfd
.get("vnf-configuration")
1641 if vnf_config
and vnf_config
.get("terminate-config-primitive"):
1647 def _get_terminate_config_primitive_seq_list(vnfd
):
1648 """ Get a numerically sorted list of the sequences for this VNFD's terminate action """
1649 # No need to check for existing primitive twice, already done before
1650 vnf_config
= vnfd
.get("vnf-configuration")
1651 seq_list
= vnf_config
.get("terminate-config-primitive")
1652 # Get all 'seq' tags in seq_list, order sequences numerically, ascending.
1653 seq_list_sorted
= sorted(seq_list
, key
=lambda x
: int(x
['seq']))
1654 return seq_list_sorted
1657 def _create_nslcmop(nsr_id
, operation
, params
):
1659 Creates a ns-lcm-opp content to be stored at database.
1660 :param nsr_id: internal id of the instance
1661 :param operation: instantiate, terminate, scale, action, ...
1662 :param params: user parameters for the operation
1663 :return: dictionary following SOL005 format
1665 # Raise exception if invalid arguments
1666 if not (nsr_id
and operation
and params
):
1668 "Parameters 'nsr_id', 'operation' and 'params' needed to create primitive not provided")
1674 # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1675 "operationState": "PROCESSING",
1676 "statusEnteredTime": now
,
1677 "nsInstanceId": nsr_id
,
1678 "lcmOperationType": operation
,
1680 "isAutomaticInvocation": False,
1681 "operationParams": params
,
1682 "isCancelPending": False,
1684 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
1685 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
1690 def _format_additional_params(self
, params
):
1691 params
= params
or {}
1692 for key
, value
in params
.items():
1693 if str(value
).startswith("!!yaml "):
1694 params
[key
] = yaml
.safe_load(value
[7:])
1697 def _get_terminate_primitive_params(self
, seq
, vnf_index
):
1698 primitive
= seq
.get('name')
1699 primitive_params
= {}
1701 "member_vnf_index": vnf_index
,
1702 "primitive": primitive
,
1703 "primitive_params": primitive_params
,
1706 return self
._map
_primitive
_params
(seq
, params
, desc_params
)
1710 def _reintent_or_skip_suboperation(self
, db_nslcmop
, op_index
):
1711 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
1712 if (op
.get('operationState') == 'COMPLETED'):
1713 # b. Skip sub-operation
1714 # _ns_execute_primitive() or RO.create_action() will NOT be executed
1715 return self
.SUBOPERATION_STATUS_SKIP
1717 # c. Reintent executing sub-operation
1718 # The sub-operation exists, and operationState != 'COMPLETED'
1719 # Update operationState = 'PROCESSING' to indicate a reintent.
1720 operationState
= 'PROCESSING'
1721 detailed_status
= 'In progress'
1722 self
._update
_suboperation
_status
(
1723 db_nslcmop
, op_index
, operationState
, detailed_status
)
1724 # Return the sub-operation index
1725 # _ns_execute_primitive() or RO.create_action() will be called from scale()
1726 # with arguments extracted from the sub-operation
1729 # Find a sub-operation where all keys in a matching dictionary must match
1730 # Returns the index of the matching sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if no match
1731 def _find_suboperation(self
, db_nslcmop
, match
):
1732 if (db_nslcmop
and match
):
1733 op_list
= db_nslcmop
.get('_admin', {}).get('operations', [])
1734 for i
, op
in enumerate(op_list
):
1735 if all(op
.get(k
) == match
[k
] for k
in match
):
1737 return self
.SUBOPERATION_STATUS_NOT_FOUND
1739 # Update status for a sub-operation given its index
1740 def _update_suboperation_status(self
, db_nslcmop
, op_index
, operationState
, detailed_status
):
1741 # Update DB for HA tasks
1742 q_filter
= {'_id': db_nslcmop
['_id']}
1743 update_dict
= {'_admin.operations.{}.operationState'.format(op_index
): operationState
,
1744 '_admin.operations.{}.detailed-status'.format(op_index
): detailed_status
}
1745 self
.db
.set_one("nslcmops",
1747 update_dict
=update_dict
,
1748 fail_on_empty
=False)
1750 # Add sub-operation, return the index of the added sub-operation
1751 # Optionally, set operationState, detailed-status, and operationType
1752 # Status and type are currently set for 'scale' sub-operations:
1753 # 'operationState' : 'PROCESSING' | 'COMPLETED' | 'FAILED'
1754 # 'detailed-status' : status message
1755 # 'operationType': may be any type, in the case of scaling: 'PRE-SCALE' | 'POST-SCALE'
1756 # Status and operation type are currently only used for 'scale', but NOT for 'terminate' sub-operations.
1757 def _add_suboperation(self
, db_nslcmop
, vnf_index
, vdu_id
, vdu_count_index
, vdu_name
, primitive
,
1758 mapped_primitive_params
, operationState
=None, detailed_status
=None, operationType
=None,
1759 RO_nsr_id
=None, RO_scaling_info
=None):
1760 if not (db_nslcmop
):
1761 return self
.SUBOPERATION_STATUS_NOT_FOUND
1762 # Get the "_admin.operations" list, if it exists
1763 db_nslcmop_admin
= db_nslcmop
.get('_admin', {})
1764 op_list
= db_nslcmop_admin
.get('operations')
1765 # Create or append to the "_admin.operations" list
1766 new_op
= {'member_vnf_index': vnf_index
,
1768 'vdu_count_index': vdu_count_index
,
1769 'primitive': primitive
,
1770 'primitive_params': mapped_primitive_params
}
1772 new_op
['operationState'] = operationState
1774 new_op
['detailed-status'] = detailed_status
1776 new_op
['lcmOperationType'] = operationType
1778 new_op
['RO_nsr_id'] = RO_nsr_id
1780 new_op
['RO_scaling_info'] = RO_scaling_info
1782 # No existing operations, create key 'operations' with current operation as first list element
1783 db_nslcmop_admin
.update({'operations': [new_op
]})
1784 op_list
= db_nslcmop_admin
.get('operations')
1786 # Existing operations, append operation to list
1787 op_list
.append(new_op
)
1789 db_nslcmop_update
= {'_admin.operations': op_list
}
1790 self
.update_db_2("nslcmops", db_nslcmop
['_id'], db_nslcmop_update
)
1791 op_index
= len(op_list
) - 1
1794 # Helper methods for scale() sub-operations
1796 # pre-scale/post-scale:
1797 # Check for 3 different cases:
1798 # a. New: First time execution, return SUBOPERATION_STATUS_NEW
1799 # b. Skip: Existing sub-operation exists, operationState == 'COMPLETED', return SUBOPERATION_STATUS_SKIP
1800 # c. Reintent: Existing sub-operation exists, operationState != 'COMPLETED', return op_index to re-execute
1801 def _check_or_add_scale_suboperation(self
, db_nslcmop
, vnf_index
, vnf_config_primitive
, primitive_params
,
1802 operationType
, RO_nsr_id
=None, RO_scaling_info
=None):
1803 # Find this sub-operation
1804 if (RO_nsr_id
and RO_scaling_info
):
1805 operationType
= 'SCALE-RO'
1807 'member_vnf_index': vnf_index
,
1808 'RO_nsr_id': RO_nsr_id
,
1809 'RO_scaling_info': RO_scaling_info
,
1813 'member_vnf_index': vnf_index
,
1814 'primitive': vnf_config_primitive
,
1815 'primitive_params': primitive_params
,
1816 'lcmOperationType': operationType
1818 op_index
= self
._find
_suboperation
(db_nslcmop
, match
)
1819 if (op_index
== self
.SUBOPERATION_STATUS_NOT_FOUND
):
1820 # a. New sub-operation
1821 # The sub-operation does not exist, add it.
1822 # _ns_execute_primitive() will be called from scale() as usual, with non-modified arguments
1823 # The following parameters are set to None for all kind of scaling:
1825 vdu_count_index
= None
1827 if (RO_nsr_id
and RO_scaling_info
):
1828 vnf_config_primitive
= None
1829 primitive_params
= None
1832 RO_scaling_info
= None
1833 # Initial status for sub-operation
1834 operationState
= 'PROCESSING'
1835 detailed_status
= 'In progress'
1836 # Add sub-operation for pre/post-scaling (zero or more operations)
1837 self
._add
_suboperation
(db_nslcmop
,
1842 vnf_config_primitive
,
1849 return self
.SUBOPERATION_STATUS_NEW
1851 # Return either SUBOPERATION_STATUS_SKIP (operationState == 'COMPLETED'),
1852 # or op_index (operationState != 'COMPLETED')
1853 return self
._reintent
_or
_skip
_suboperation
(db_nslcmop
, op_index
)
1855 # Helper methods for terminate()
1857 async def _terminate_action(self
, db_nslcmop
, nslcmop_id
, nsr_id
):
1858 """ Create a primitive with params from VNFD
1859 Called from terminate() before deleting instance
1860 Calls action() to execute the primitive """
1861 logging_text
= "Task ns={} _terminate_action={} ".format(nsr_id
, nslcmop_id
)
1862 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1865 for vnfr
in db_vnfrs_list
:
1866 vnfd_id
= vnfr
["vnfd-id"]
1867 vnf_index
= vnfr
["member-vnf-index-ref"]
1868 if vnfd_id
not in db_vnfds
:
1869 step
= "Getting vnfd={} id='{}' from db".format(vnfd_id
, vnfd_id
)
1870 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
1871 db_vnfds
[vnfd_id
] = vnfd
1872 vnfd
= db_vnfds
[vnfd_id
]
1873 if not self
._has
_terminate
_config
_primitive
(vnfd
):
1875 # Get the primitive's sorted sequence list
1876 seq_list
= self
._get
_terminate
_config
_primitive
_seq
_list
(vnfd
)
1877 for seq
in seq_list
:
1878 # For each sequence in list, get primitive and call _ns_execute_primitive()
1879 step
= "Calling terminate action for vnf_member_index={} primitive={}".format(
1880 vnf_index
, seq
.get("name"))
1881 self
.logger
.debug(logging_text
+ step
)
1882 # Create the primitive for each sequence, i.e. "primitive": "touch"
1883 primitive
= seq
.get('name')
1884 mapped_primitive_params
= self
._get
_terminate
_primitive
_params
(seq
, vnf_index
)
1885 # The following 3 parameters are currently set to None for 'terminate':
1886 # vdu_id, vdu_count_index, vdu_name
1887 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
1888 vdu_count_index
= db_nslcmop
["operationParams"].get("vdu_count_index")
1889 vdu_name
= db_nslcmop
["operationParams"].get("vdu_name")
1891 self
._add
_suboperation
(db_nslcmop
,
1898 mapped_primitive_params
)
1899 # Sub-operations: Call _ns_execute_primitive() instead of action()
1900 # db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1901 # nsr_deployed = db_nsr["_admin"]["deployed"]
1903 # nslcmop_operation_state, nslcmop_operation_state_detail = await self.action(
1904 # nsr_id, nslcmop_terminate_action_id)
1905 # Launch Exception if action() returns other than ['COMPLETED', 'PARTIALLY_COMPLETED']
1906 # result_ok = ['COMPLETED', 'PARTIALLY_COMPLETED']
1907 # if result not in result_ok:
1908 # raise LcmException(
1909 # "terminate_primitive_action for vnf_member_index={}",
1910 # " primitive={} fails with error {}".format(
1911 # vnf_index, seq.get("name"), result_detail))
1916 await self
.n2vc
.exec_primitive(
1918 primitive_name
=primitive
,
1919 params_dict
=mapped_primitive_params
1921 except Exception as e
:
1922 self
.logger
.error('Error executing primitive {}: {}'.format(primitive
, e
))
1924 "terminate_primitive_action for vnf_member_index={}, primitive={} fails with error {}"
1925 .format(vnf_index
, seq
.get("name"), e
),
1928 async def terminate(self
, nsr_id
, nslcmop_id
):
1930 # Try to lock HA task here
1931 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
1932 if not task_is_locked_by_me
:
1935 logging_text
= "Task ns={} terminate={} ".format(nsr_id
, nslcmop_id
)
1936 self
.logger
.debug(logging_text
+ "Enter")
1940 failed_detail
= [] # annotates all failed error messages
1941 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
1942 "_admin.current-operation": nslcmop_id
,
1943 "_admin.operation-type": "terminate"}
1944 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1945 db_nslcmop_update
= {}
1946 nslcmop_operation_state
= None
1947 autoremove
= False # autoremove after terminated
1950 # wait for any previous tasks in process
1951 step
= "Waiting for previous operations to terminate"
1952 await self
.lcm_tasks
.waitfor_related_HA("ns", 'nslcmops', nslcmop_id
)
1954 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
1955 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1956 step
= "Getting nsr={} from db".format(nsr_id
)
1957 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1958 # nsd = db_nsr["nsd"]
1959 nsr_deployed
= deepcopy(db_nsr
["_admin"].get("deployed"))
1960 if db_nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
1962 # #TODO check if VIM is creating and wait
1963 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
1964 # Call internal terminate action
1965 await self
._terminate
_action
(db_nslcmop
, nslcmop_id
, nsr_id
)
1969 db_nsr_update
["operational-status"] = "terminating"
1970 db_nsr_update
["config-status"] = "terminating"
1974 step
= "delete execution environment"
1975 self
.logger
.debug(logging_text
+ step
)
1977 task_delete_ee
= asyncio
.ensure_future(self
.n2vc
.delete_namespace(namespace
="." + nsr_id
))
1978 pending_tasks
.append(task_delete_ee
)
1979 except Exception as e
:
1980 msg
= "Failed while deleting NS in VCA: {}".format(e
)
1981 self
.logger
.error(msg
)
1982 failed_detail
.append(msg
)
1985 # Delete from k8scluster
1986 step
= "delete kdus"
1987 self
.logger
.debug(logging_text
+ step
)
1988 # print(nsr_deployed)
1990 for kdu
in nsr_deployed
.get("K8s", ()):
1991 kdu_instance
= kdu
.get("kdu-instance")
1992 if not kdu_instance
:
1994 if kdu
.get("k8scluster-type") == "chart":
1995 task_delete_kdu_instance
= asyncio
.ensure_future(
1996 self
.k8sclusterhelm
.uninstall(cluster_uuid
=kdu
.get("k8scluster-uuid"),
1997 kdu_instance
=kdu_instance
))
1998 elif kdu
.get("k8scluster-type") == "juju":
1999 task_delete_kdu_instance
= asyncio
.ensure_future(
2000 self
.k8sclusterjuju
.uninstall(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2001 kdu_instance
=kdu_instance
))
2003 self
.error(logging_text
+ "Unknown k8s deployment type {}".
2004 format(kdu
.get("k8scluster-type")))
2006 pending_tasks
.append(task_delete_kdu_instance
)
2007 except LcmException
as e
:
2008 msg
= "Failed while deleting KDUs from NS: {}".format(e
)
2009 self
.logger
.error(msg
)
2010 failed_detail
.append(msg
)
2016 RO_nsr_id
= RO_delete_action
= None
2017 if nsr_deployed
and nsr_deployed
.get("RO"):
2018 RO_nsr_id
= nsr_deployed
["RO"].get("nsr_id")
2019 RO_delete_action
= nsr_deployed
["RO"].get("nsr_delete_action_id")
2022 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] = \
2023 "Deleting ns from VIM"
2024 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2025 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2026 self
.logger
.debug(logging_text
+ step
)
2027 desc
= await self
.RO
.delete("ns", RO_nsr_id
)
2028 RO_delete_action
= desc
["action_id"]
2029 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = RO_delete_action
2030 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
2031 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
2032 if RO_delete_action
:
2033 # wait until NS is deleted from VIM
2034 step
= detailed_status
= "Waiting ns deleted from VIM. RO_id={} RO_delete_action={}".\
2035 format(RO_nsr_id
, RO_delete_action
)
2036 detailed_status_old
= None
2037 self
.logger
.debug(logging_text
+ step
)
2039 delete_timeout
= 20 * 60 # 20 minutes
2040 while delete_timeout
> 0:
2041 desc
= await self
.RO
.show(
2043 item_id_name
=RO_nsr_id
,
2044 extra_item
="action",
2045 extra_item_id
=RO_delete_action
)
2046 ns_status
, ns_status_info
= self
.RO
.check_action_status(desc
)
2047 if ns_status
== "ERROR":
2048 raise ROclient
.ROClientException(ns_status_info
)
2049 elif ns_status
== "BUILD":
2050 detailed_status
= step
+ "; {}".format(ns_status_info
)
2051 elif ns_status
== "ACTIVE":
2052 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
2053 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
2056 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
2057 if detailed_status
!= detailed_status_old
:
2058 detailed_status_old
= db_nslcmop_update
["detailed-status"] = \
2059 db_nsr_update
["detailed-status"] = detailed_status
2060 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2061 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2062 await asyncio
.sleep(5, loop
=self
.loop
)
2064 else: # delete_timeout <= 0:
2065 raise ROclient
.ROClientException("Timeout waiting ns deleted from VIM")
2067 except ROclient
.ROClientException
as e
:
2068 if e
.http_code
== 404: # not found
2069 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
2070 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
2071 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
2072 self
.logger
.debug(logging_text
+ "RO_ns_id={} already deleted".format(RO_nsr_id
))
2073 elif e
.http_code
== 409: # conflict
2074 failed_detail
.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id
, e
))
2075 self
.logger
.debug(logging_text
+ failed_detail
[-1])
2078 failed_detail
.append("RO_ns_id={} delete error: {}".format(RO_nsr_id
, e
))
2079 self
.logger
.error(logging_text
+ failed_detail
[-1])
2083 if not RO_fail
and nsr_deployed
and nsr_deployed
.get("RO") and nsr_deployed
["RO"].get("nsd_id"):
2084 RO_nsd_id
= nsr_deployed
["RO"]["nsd_id"]
2086 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
2087 "Deleting nsd from RO"
2088 await self
.RO
.delete("nsd", RO_nsd_id
)
2089 self
.logger
.debug(logging_text
+ "RO_nsd_id={} deleted".format(RO_nsd_id
))
2090 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
2091 except ROclient
.ROClientException
as e
:
2092 if e
.http_code
== 404: # not found
2093 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
2094 self
.logger
.debug(logging_text
+ "RO_nsd_id={} already deleted".format(RO_nsd_id
))
2095 elif e
.http_code
== 409: # conflict
2096 failed_detail
.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id
, e
))
2097 self
.logger
.debug(logging_text
+ failed_detail
[-1])
2100 failed_detail
.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id
, e
))
2101 self
.logger
.error(logging_text
+ failed_detail
[-1])
2104 if not RO_fail
and nsr_deployed
and nsr_deployed
.get("RO") and nsr_deployed
["RO"].get("vnfd"):
2105 for index
, vnf_deployed
in enumerate(nsr_deployed
["RO"]["vnfd"]):
2106 if not vnf_deployed
or not vnf_deployed
["id"]:
2109 RO_vnfd_id
= vnf_deployed
["id"]
2110 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
2111 "Deleting member_vnf_index={} RO_vnfd_id={} from RO".format(
2112 vnf_deployed
["member-vnf-index"], RO_vnfd_id
)
2113 await self
.RO
.delete("vnfd", RO_vnfd_id
)
2114 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} deleted".format(RO_vnfd_id
))
2115 db_nsr_update
["_admin.deployed.RO.vnfd.{}.id".format(index
)] = None
2116 except ROclient
.ROClientException
as e
:
2117 if e
.http_code
== 404: # not found
2118 db_nsr_update
["_admin.deployed.RO.vnfd.{}.id".format(index
)] = None
2119 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} already deleted ".format(RO_vnfd_id
))
2120 elif e
.http_code
== 409: # conflict
2121 failed_detail
.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id
, e
))
2122 self
.logger
.debug(logging_text
+ failed_detail
[-1])
2124 failed_detail
.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id
, e
))
2125 self
.logger
.error(logging_text
+ failed_detail
[-1])
2128 self
.logger
.error(logging_text
+ " ;".join(failed_detail
))
2129 db_nsr_update
["operational-status"] = "failed"
2130 db_nsr_update
["detailed-status"] = "Deletion errors " + "; ".join(failed_detail
)
2131 db_nslcmop_update
["detailed-status"] = "; ".join(failed_detail
)
2132 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2133 db_nslcmop_update
["statusEnteredTime"] = time()
2135 db_nsr_update
["operational-status"] = "terminated"
2136 db_nsr_update
["detailed-status"] = "Done"
2137 db_nsr_update
["_admin.nsState"] = "NOT_INSTANTIATED"
2138 db_nslcmop_update
["detailed-status"] = "Done"
2139 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
2140 db_nslcmop_update
["statusEnteredTime"] = time()
2141 if db_nslcmop
["operationParams"].get("autoremove"):
2144 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
2145 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
2147 except asyncio
.CancelledError
:
2148 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
2149 exc
= "Operation was cancelled"
2150 except Exception as e
:
2151 exc
= traceback
.format_exc()
2152 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
2154 if exc
and db_nslcmop
:
2155 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
2156 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2157 db_nslcmop_update
["statusEnteredTime"] = time()
2159 if db_nslcmop
and db_nslcmop_update
:
2160 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2162 db_nsr_update
["_admin.nslcmop"] = None
2163 db_nsr_update
["_admin.current-operation"] = None
2164 db_nsr_update
["_admin.operation-type"] = None
2165 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2166 except DbException
as e
:
2167 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
2168 if nslcmop_operation_state
:
2170 await self
.msg
.aiowrite("ns", "terminated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2171 "operationState": nslcmop_operation_state
,
2172 "autoremove": autoremove
},
2174 except Exception as e
:
2175 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
2177 # wait for pending tasks
2181 self
.logger
.debug(logging_text
+ 'Waiting for terminate pending tasks...')
2182 done
, pending
= await asyncio
.wait(pending_tasks
, timeout
=3600)
2184 self
.logger
.debug(logging_text
+ 'All tasks finished...')
2186 self
.logger
.info(logging_text
+ 'There are pending tasks: {}'.format(pending
))
2188 self
.logger
.debug(logging_text
+ "Exit")
2189 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_terminate")
2192 def _map_primitive_params(primitive_desc
, params
, instantiation_params
):
2194 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
2195 The default-value is used. If it is between < > it look for a value at instantiation_params
2196 :param primitive_desc: portion of VNFD/NSD that describes primitive
2197 :param params: Params provided by user
2198 :param instantiation_params: Instantiation params provided by user
2199 :return: a dictionary with the calculated params
2201 calculated_params
= {}
2202 for parameter
in primitive_desc
.get("parameter", ()):
2203 param_name
= parameter
["name"]
2204 if param_name
in params
:
2205 calculated_params
[param_name
] = params
[param_name
]
2206 elif "default-value" in parameter
or "value" in parameter
:
2207 if "value" in parameter
:
2208 calculated_params
[param_name
] = parameter
["value"]
2210 calculated_params
[param_name
] = parameter
["default-value"]
2211 if isinstance(calculated_params
[param_name
], str) and calculated_params
[param_name
].startswith("<") \
2212 and calculated_params
[param_name
].endswith(">"):
2213 if calculated_params
[param_name
][1:-1] in instantiation_params
:
2214 calculated_params
[param_name
] = instantiation_params
[calculated_params
[param_name
][1:-1]]
2216 raise LcmException("Parameter {} needed to execute primitive {} not provided".
2217 format(calculated_params
[param_name
], primitive_desc
["name"]))
2219 raise LcmException("Parameter {} needed to execute primitive {} not provided".
2220 format(param_name
, primitive_desc
["name"]))
2222 if isinstance(calculated_params
[param_name
], (dict, list, tuple)):
2223 calculated_params
[param_name
] = yaml
.safe_dump(calculated_params
[param_name
], default_flow_style
=True,
2225 elif isinstance(calculated_params
[param_name
], str) and calculated_params
[param_name
].startswith("!!yaml "):
2226 calculated_params
[param_name
] = calculated_params
[param_name
][7:]
2228 # add always ns_config_info if primitive name is config
2229 if primitive_desc
["name"] == "config":
2230 if "ns_config_info" in instantiation_params
:
2231 calculated_params
["ns_config_info"] = instantiation_params
["ns_config_info"]
2232 return calculated_params
2234 async def _ns_execute_primitive(self
, db_deployed
, member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
,
2235 primitive
, primitive_params
, retries
=0, retries_interval
=30) -> (str, str):
2237 # find vca_deployed record for this action
2239 for vca_deployed
in db_deployed
["VCA"]:
2240 if not vca_deployed
:
2242 if member_vnf_index
!= vca_deployed
["member-vnf-index"] or vdu_id
!= vca_deployed
["vdu_id"]:
2244 if vdu_name
and vdu_name
!= vca_deployed
["vdu_name"]:
2246 if vdu_count_index
and vdu_count_index
!= vca_deployed
["vdu_count_index"]:
2250 # vca_deployed not found
2251 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} is not "
2252 "deployed".format(member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
))
2255 ee_id
= vca_deployed
.get("ee_id")
2257 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} has not "
2258 "execution environment"
2259 .format(member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
))
2261 if primitive
== "config":
2262 primitive_params
= {"params": primitive_params
}
2266 output
= await self
.n2vc
.exec_primitive(
2268 primitive_name
=primitive
,
2269 params_dict
=primitive_params
2273 except Exception as e
:
2276 self
.logger
.debug('Error executing action {} on {} -> {}'.format(primitive
, ee_id
, e
))
2278 await asyncio
.sleep(retries_interval
, loop
=self
.loop
)
2280 return 'Cannot execute action {} on {}: {}'.format(primitive
, ee_id
, e
), 'FAIL'
2284 except Exception as e
:
2285 return 'Error executing action {}: {}'.format(primitive
, e
), 'FAIL'
2287 async def action(self
, nsr_id
, nslcmop_id
):
2289 # Try to lock HA task here
2290 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
2291 if not task_is_locked_by_me
:
2294 logging_text
= "Task ns={} action={} ".format(nsr_id
, nslcmop_id
)
2295 self
.logger
.debug(logging_text
+ "Enter")
2296 # get all needed from database
2299 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
2300 "_admin.current-operation": nslcmop_id
,
2301 "_admin.operation-type": "action"}
2302 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2303 db_nslcmop_update
= {}
2304 nslcmop_operation_state
= None
2305 nslcmop_operation_state_detail
= None
2308 # wait for any previous tasks in process
2309 step
= "Waiting for previous operations to terminate"
2310 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
2312 step
= "Getting information from database"
2313 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
2314 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2316 nsr_deployed
= db_nsr
["_admin"].get("deployed")
2317 vnf_index
= db_nslcmop
["operationParams"].get("member_vnf_index")
2318 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
2319 kdu_name
= db_nslcmop
["operationParams"].get("kdu_name")
2320 vdu_count_index
= db_nslcmop
["operationParams"].get("vdu_count_index")
2321 vdu_name
= db_nslcmop
["operationParams"].get("vdu_name")
2324 step
= "Getting vnfr from database"
2325 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
2326 step
= "Getting vnfd from database"
2327 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
2329 if db_nsr
.get("nsd"):
2330 db_nsd
= db_nsr
.get("nsd") # TODO this will be removed
2332 step
= "Getting nsd from database"
2333 db_nsd
= self
.db
.get_one("nsds", {"_id": db_nsr
["nsd-id"]})
2335 # for backward compatibility
2336 if nsr_deployed
and isinstance(nsr_deployed
.get("VCA"), dict):
2337 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
2338 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
2339 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2341 primitive
= db_nslcmop
["operationParams"]["primitive"]
2342 primitive_params
= db_nslcmop
["operationParams"]["primitive_params"]
2344 # look for primitive
2345 config_primitive_desc
= None
2347 for vdu
in get_iterable(db_vnfd
, "vdu"):
2348 if vdu_id
== vdu
["id"]:
2349 for config_primitive
in vdu
.get("vdu-configuration", {}).get("config-primitive", ()):
2350 if config_primitive
["name"] == primitive
:
2351 config_primitive_desc
= config_primitive
2354 self
.logger
.debug(logging_text
+ "Checking actions in KDUs")
2355 kdur
= next((x
for x
in db_vnfr
["kdur"] if x
["kdu_name"] == kdu_name
), None)
2356 desc_params
= self
._format
_additional
_params
(kdur
.get("additionalParams")) or {}
2357 if primitive_params
:
2358 desc_params
.update(primitive_params
)
2359 # TODO Check if we will need something at vnf level
2361 for kdu
in get_iterable(nsr_deployed
, "K8s"):
2362 if kdu_name
== kdu
["kdu-name"]:
2363 db_dict
= {"collection": "nsrs", "filter": {"_id": nsr_id
},
2364 "path": "_admin.deployed.K8s.{}".format(index
)}
2365 if primitive
== "upgrade":
2366 if desc_params
.get("kdu_model"):
2367 kdu_model
= desc_params
.get("kdu_model")
2368 del desc_params
["kdu_model"]
2370 kdu_model
= kdu
.get("kdu-model")
2371 parts
= kdu_model
.split(sep
=":")
2373 kdu_model
= parts
[0]
2375 if kdu
.get("k8scluster-type") == "chart":
2376 output
= await self
.k8sclusterhelm
.upgrade(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2377 kdu_instance
=kdu
.get("kdu-instance"),
2378 atomic
=True, kdu_model
=kdu_model
,
2379 params
=desc_params
, db_dict
=db_dict
,
2381 elif kdu
.get("k8scluster-type") == "juju":
2382 output
= await self
.k8sclusterjuju
.upgrade(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2383 kdu_instance
=kdu
.get("kdu-instance"),
2384 atomic
=True, kdu_model
=kdu_model
,
2385 params
=desc_params
, db_dict
=db_dict
,
2389 msg
= "k8scluster-type not defined"
2390 raise LcmException(msg
)
2392 self
.logger
.debug(logging_text
+ " Upgrade of kdu {} done".format(output
))
2394 elif primitive
== "rollback":
2395 if kdu
.get("k8scluster-type") == "chart":
2396 output
= await self
.k8sclusterhelm
.rollback(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2397 kdu_instance
=kdu
.get("kdu-instance"),
2399 elif kdu
.get("k8scluster-type") == "juju":
2400 output
= await self
.k8sclusterjuju
.rollback(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2401 kdu_instance
=kdu
.get("kdu-instance"),
2404 msg
= "k8scluster-type not defined"
2405 raise LcmException(msg
)
2407 elif primitive
== "status":
2408 if kdu
.get("k8scluster-type") == "chart":
2409 output
= await self
.k8sclusterhelm
.status_kdu(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2410 kdu_instance
=kdu
.get("kdu-instance"))
2411 elif kdu
.get("k8scluster-type") == "juju":
2412 output
= await self
.k8sclusterjuju
.status_kdu(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2413 kdu_instance
=kdu
.get("kdu-instance"))
2415 msg
= "k8scluster-type not defined"
2416 raise LcmException(msg
)
2421 raise LcmException("KDU '{}' not found".format(kdu_name
))
2423 db_nslcmop_update
["detailed-status"] = output
2424 db_nslcmop_update
["operationState"] = 'COMPLETED'
2425 db_nslcmop_update
["statusEnteredTime"] = time()
2427 db_nslcmop_update
["detailed-status"] = ''
2428 db_nslcmop_update
["operationState"] = 'FAILED'
2429 db_nslcmop_update
["statusEnteredTime"] = time()
2432 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
2433 if config_primitive
["name"] == primitive
:
2434 config_primitive_desc
= config_primitive
2437 for config_primitive
in db_nsd
.get("ns-configuration", {}).get("config-primitive", ()):
2438 if config_primitive
["name"] == primitive
:
2439 config_primitive_desc
= config_primitive
2442 if not config_primitive_desc
:
2443 raise LcmException("Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".
2448 if db_vnfr
.get("additionalParamsForVnf"):
2449 desc_params
= self
._format
_additional
_params
(db_vnfr
["additionalParamsForVnf"])
2451 vdur
= next((x
for x
in db_vnfr
["vdur"] if x
["vdu-id-ref"] == vdu_id
), None)
2452 if vdur
.get("additionalParams"):
2453 desc_params
= self
._format
_additional
_params
(vdur
["additionalParams"])
2455 if db_nsr
.get("additionalParamsForNs"):
2456 desc_params
.update(self
._format
_additional
_params
(db_nsr
["additionalParamsForNs"]))
2458 # TODO check if ns is in a proper status
2459 output
, detail
= await self
._ns
_execute
_primitive
(
2460 db_deployed
=nsr_deployed
,
2461 member_vnf_index
=vnf_index
,
2464 vdu_count_index
=vdu_count_index
,
2465 primitive
=primitive
,
2466 primitive_params
=self
._map
_primitive
_params
(config_primitive_desc
, primitive_params
, desc_params
))
2468 detailed_status
= output
2470 result
= 'COMPLETED'
2474 db_nslcmop_update
["detailed-status"] = nslcmop_operation_state_detail
= detailed_status
2475 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= result
2476 db_nslcmop_update
["statusEnteredTime"] = time()
2477 self
.logger
.debug(logging_text
+ " task Done with result {} {}".format(result
, detailed_status
))
2478 return # database update is called inside finally
2480 except (DbException
, LcmException
) as e
:
2481 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
2483 except asyncio
.CancelledError
:
2484 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
2485 exc
= "Operation was cancelled"
2486 except Exception as e
:
2487 exc
= traceback
.format_exc()
2488 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
2490 if exc
and db_nslcmop
:
2491 db_nslcmop_update
["detailed-status"] = nslcmop_operation_state_detail
= \
2492 "FAILED {}: {}".format(step
, exc
)
2493 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2494 db_nslcmop_update
["statusEnteredTime"] = time()
2496 if db_nslcmop_update
:
2497 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2499 db_nsr_update
["_admin.nslcmop"] = None
2500 db_nsr_update
["_admin.operation-type"] = None
2501 db_nsr_update
["_admin.nslcmop"] = None
2502 db_nsr_update
["_admin.current-operation"] = None
2503 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2504 except DbException
as e
:
2505 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
2506 self
.logger
.debug(logging_text
+ "Exit")
2507 if nslcmop_operation_state
:
2509 await self
.msg
.aiowrite("ns", "actioned", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2510 "operationState": nslcmop_operation_state
},
2512 except Exception as e
:
2513 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
2514 self
.logger
.debug(logging_text
+ "Exit")
2515 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_action")
2516 return nslcmop_operation_state
, nslcmop_operation_state_detail
2518 async def scale(self
, nsr_id
, nslcmop_id
):
2520 # Try to lock HA task here
2521 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
2522 if not task_is_locked_by_me
:
2525 logging_text
= "Task ns={} scale={} ".format(nsr_id
, nslcmop_id
)
2526 self
.logger
.debug(logging_text
+ "Enter")
2527 # get all needed from database
2530 db_nslcmop_update
= {}
2531 nslcmop_operation_state
= None
2532 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
2533 "_admin.current-operation": nslcmop_id
,
2534 "_admin.operation-type": "scale"}
2535 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2537 # in case of error, indicates what part of scale was failed to put nsr at error status
2538 scale_process
= None
2539 old_operational_status
= ""
2540 old_config_status
= ""
2543 # wait for any previous tasks in process
2544 step
= "Waiting for previous operations to terminate"
2545 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
2547 step
= "Getting nslcmop from database"
2548 self
.logger
.debug(step
+ " after having waited for previous tasks to be completed")
2549 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
2550 step
= "Getting nsr from database"
2551 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2553 old_operational_status
= db_nsr
["operational-status"]
2554 old_config_status
= db_nsr
["config-status"]
2555 step
= "Parsing scaling parameters"
2556 # self.logger.debug(step)
2557 db_nsr_update
["operational-status"] = "scaling"
2558 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2559 nsr_deployed
= db_nsr
["_admin"].get("deployed")
2562 nsr_deployed
= db_nsr
["_admin"].get("deployed")
2563 vnf_index
= db_nslcmop
["operationParams"].get("member_vnf_index")
2564 # vdu_id = db_nslcmop["operationParams"].get("vdu_id")
2565 # vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
2566 # vdu_name = db_nslcmop["operationParams"].get("vdu_name")
2569 RO_nsr_id
= nsr_deployed
["RO"]["nsr_id"]
2570 vnf_index
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
2571 scaling_group
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
2572 scaling_type
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleVnfType"]
2573 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
2575 # for backward compatibility
2576 if nsr_deployed
and isinstance(nsr_deployed
.get("VCA"), dict):
2577 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
2578 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
2579 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2581 step
= "Getting vnfr from database"
2582 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
2583 step
= "Getting vnfd from database"
2584 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
2586 step
= "Getting scaling-group-descriptor"
2587 for scaling_descriptor
in db_vnfd
["scaling-group-descriptor"]:
2588 if scaling_descriptor
["name"] == scaling_group
:
2591 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
2592 "at vnfd:scaling-group-descriptor".format(scaling_group
))
2595 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
2596 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
2597 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
2600 # TODO check if ns is in a proper status
2601 step
= "Sending scale order to VIM"
2603 if not db_nsr
["_admin"].get("scaling-group"):
2604 self
.update_db_2("nsrs", nsr_id
, {"_admin.scaling-group": [{"name": scaling_group
, "nb-scale-op": 0}]})
2605 admin_scale_index
= 0
2607 for admin_scale_index
, admin_scale_info
in enumerate(db_nsr
["_admin"]["scaling-group"]):
2608 if admin_scale_info
["name"] == scaling_group
:
2609 nb_scale_op
= admin_scale_info
.get("nb-scale-op", 0)
2611 else: # not found, set index one plus last element and add new entry with the name
2612 admin_scale_index
+= 1
2613 db_nsr_update
["_admin.scaling-group.{}.name".format(admin_scale_index
)] = scaling_group
2614 RO_scaling_info
= []
2615 vdu_scaling_info
= {"scaling_group_name": scaling_group
, "vdu": []}
2616 if scaling_type
== "SCALE_OUT":
2617 # count if max-instance-count is reached
2618 max_instance_count
= scaling_descriptor
.get("max-instance-count", 10)
2619 # self.logger.debug("MAX_INSTANCE_COUNT is {}".format(max_instance_count))
2620 if nb_scale_op
>= max_instance_count
:
2621 raise LcmException("reached the limit of {} (max-instance-count) "
2622 "scaling-out operations for the "
2623 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
2626 vdu_scaling_info
["scaling_direction"] = "OUT"
2627 vdu_scaling_info
["vdu-create"] = {}
2628 for vdu_scale_info
in scaling_descriptor
["vdu"]:
2629 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
2630 "type": "create", "count": vdu_scale_info
.get("count", 1)})
2631 vdu_scaling_info
["vdu-create"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
2633 elif scaling_type
== "SCALE_IN":
2634 # count if min-instance-count is reached
2635 min_instance_count
= 0
2636 if "min-instance-count" in scaling_descriptor
and scaling_descriptor
["min-instance-count"] is not None:
2637 min_instance_count
= int(scaling_descriptor
["min-instance-count"])
2638 if nb_scale_op
<= min_instance_count
:
2639 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
2640 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
2642 vdu_scaling_info
["scaling_direction"] = "IN"
2643 vdu_scaling_info
["vdu-delete"] = {}
2644 for vdu_scale_info
in scaling_descriptor
["vdu"]:
2645 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
2646 "type": "delete", "count": vdu_scale_info
.get("count", 1)})
2647 vdu_scaling_info
["vdu-delete"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
2649 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
2650 vdu_create
= vdu_scaling_info
.get("vdu-create")
2651 vdu_delete
= copy(vdu_scaling_info
.get("vdu-delete"))
2652 if vdu_scaling_info
["scaling_direction"] == "IN":
2653 for vdur
in reversed(db_vnfr
["vdur"]):
2654 if vdu_delete
.get(vdur
["vdu-id-ref"]):
2655 vdu_delete
[vdur
["vdu-id-ref"]] -= 1
2656 vdu_scaling_info
["vdu"].append({
2657 "name": vdur
["name"],
2658 "vdu_id": vdur
["vdu-id-ref"],
2661 for interface
in vdur
["interfaces"]:
2662 vdu_scaling_info
["vdu"][-1]["interface"].append({
2663 "name": interface
["name"],
2664 "ip_address": interface
["ip-address"],
2665 "mac_address": interface
.get("mac-address"),
2667 vdu_delete
= vdu_scaling_info
.pop("vdu-delete")
2670 step
= "Executing pre-scale vnf-config-primitive"
2671 if scaling_descriptor
.get("scaling-config-action"):
2672 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
2673 if (scaling_config_action
.get("trigger") == "pre-scale-in" and scaling_type
== "SCALE_IN") \
2674 or (scaling_config_action
.get("trigger") == "pre-scale-out" and scaling_type
== "SCALE_OUT"):
2675 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
2676 step
= db_nslcmop_update
["detailed-status"] = \
2677 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive
)
2679 # look for primitive
2680 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
2681 if config_primitive
["name"] == vnf_config_primitive
:
2685 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
2686 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
2687 "primitive".format(scaling_group
, config_primitive
))
2689 vnfr_params
= {"VDU_SCALE_INFO": vdu_scaling_info
}
2690 if db_vnfr
.get("additionalParamsForVnf"):
2691 vnfr_params
.update(db_vnfr
["additionalParamsForVnf"])
2693 scale_process
= "VCA"
2694 db_nsr_update
["config-status"] = "configuring pre-scaling"
2695 primitive_params
= self
._map
_primitive
_params
(config_primitive
, {}, vnfr_params
)
2697 # Pre-scale reintent check: Check if this sub-operation has been executed before
2698 op_index
= self
._check
_or
_add
_scale
_suboperation
(
2699 db_nslcmop
, nslcmop_id
, vnf_index
, vnf_config_primitive
, primitive_params
, 'PRE-SCALE')
2700 if (op_index
== self
.SUBOPERATION_STATUS_SKIP
):
2701 # Skip sub-operation
2702 result
= 'COMPLETED'
2703 result_detail
= 'Done'
2704 self
.logger
.debug(logging_text
+
2705 "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
2706 vnf_config_primitive
, result
, result_detail
))
2708 if (op_index
== self
.SUBOPERATION_STATUS_NEW
):
2709 # New sub-operation: Get index of this sub-operation
2710 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
2711 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} New sub-operation".
2712 format(vnf_config_primitive
))
2714 # Reintent: Get registered params for this existing sub-operation
2715 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
2716 vnf_index
= op
.get('member_vnf_index')
2717 vnf_config_primitive
= op
.get('primitive')
2718 primitive_params
= op
.get('primitive_params')
2719 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Sub-operation reintent".
2720 format(vnf_config_primitive
))
2721 # Execute the primitive, either with new (first-time) or registered (reintent) args
2722 result
, result_detail
= await self
._ns
_execute
_primitive
(
2723 nsr_deployed
, vnf_index
, None, None, None, vnf_config_primitive
, primitive_params
)
2724 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
2725 vnf_config_primitive
, result
, result_detail
))
2726 # Update operationState = COMPLETED | FAILED
2727 self
._update
_suboperation
_status
(
2728 db_nslcmop
, op_index
, result
, result_detail
)
2730 if result
== "FAILED":
2731 raise LcmException(result_detail
)
2732 db_nsr_update
["config-status"] = old_config_status
2733 scale_process
= None
2737 # Should this block be skipped if 'RO_nsr_id' == None ?
2738 # if (RO_nsr_id and RO_scaling_info):
2740 scale_process
= "RO"
2741 # Scale RO reintent check: Check if this sub-operation has been executed before
2742 op_index
= self
._check
_or
_add
_scale
_suboperation
(
2743 db_nslcmop
, vnf_index
, None, None, 'SCALE-RO', RO_nsr_id
, RO_scaling_info
)
2744 if (op_index
== self
.SUBOPERATION_STATUS_SKIP
):
2745 # Skip sub-operation
2746 result
= 'COMPLETED'
2747 result_detail
= 'Done'
2748 self
.logger
.debug(logging_text
+ "Skipped sub-operation RO, result {} {}".format(
2749 result
, result_detail
))
2751 if (op_index
== self
.SUBOPERATION_STATUS_NEW
):
2752 # New sub-operation: Get index of this sub-operation
2753 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
2754 self
.logger
.debug(logging_text
+ "New sub-operation RO")
2756 # Reintent: Get registered params for this existing sub-operation
2757 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
2758 RO_nsr_id
= op
.get('RO_nsr_id')
2759 RO_scaling_info
= op
.get('RO_scaling_info')
2760 self
.logger
.debug(logging_text
+ "Sub-operation RO reintent".format(
2761 vnf_config_primitive
))
2763 RO_desc
= await self
.RO
.create_action("ns", RO_nsr_id
, {"vdu-scaling": RO_scaling_info
})
2764 db_nsr_update
["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index
)] = nb_scale_op
2765 db_nsr_update
["_admin.scaling-group.{}.time".format(admin_scale_index
)] = time()
2767 RO_nslcmop_id
= RO_desc
["instance_action_id"]
2768 db_nslcmop_update
["_admin.deploy.RO"] = RO_nslcmop_id
2770 RO_task_done
= False
2771 step
= detailed_status
= "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id
)
2772 detailed_status_old
= None
2773 self
.logger
.debug(logging_text
+ step
)
2775 deployment_timeout
= 1 * 3600 # One hour
2776 while deployment_timeout
> 0:
2777 if not RO_task_done
:
2778 desc
= await self
.RO
.show("ns", item_id_name
=RO_nsr_id
, extra_item
="action",
2779 extra_item_id
=RO_nslcmop_id
)
2780 ns_status
, ns_status_info
= self
.RO
.check_action_status(desc
)
2781 if ns_status
== "ERROR":
2782 raise ROclient
.ROClientException(ns_status_info
)
2783 elif ns_status
== "BUILD":
2784 detailed_status
= step
+ "; {}".format(ns_status_info
)
2785 elif ns_status
== "ACTIVE":
2787 step
= detailed_status
= "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id
)
2788 self
.logger
.debug(logging_text
+ step
)
2790 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
2793 if ns_status
== "ERROR":
2794 raise ROclient
.ROClientException(ns_status_info
)
2795 elif ns_status
== "BUILD":
2796 detailed_status
= step
+ "; {}".format(ns_status_info
)
2797 elif ns_status
== "ACTIVE":
2798 step
= detailed_status
= \
2799 "Waiting for management IP address reported by the VIM. Updating VNFRs"
2801 self
.scale_vnfr(db_vnfr
, vdu_create
=vdu_create
, vdu_delete
=vdu_delete
)
2804 desc
= await self
.RO
.show("ns", RO_nsr_id
)
2805 # nsr_deployed["nsr_ip"] = RO.get_ns_vnf_info(desc)
2806 self
.ns_update_vnfr({db_vnfr
["member-vnf-index-ref"]: db_vnfr
}, desc
)
2808 except LcmExceptionNoMgmtIP
:
2811 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
2812 if detailed_status
!= detailed_status_old
:
2813 self
._update
_suboperation
_status
(
2814 db_nslcmop
, op_index
, 'COMPLETED', detailed_status
)
2815 detailed_status_old
= db_nslcmop_update
["detailed-status"] = detailed_status
2816 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2818 await asyncio
.sleep(5, loop
=self
.loop
)
2819 deployment_timeout
-= 5
2820 if deployment_timeout
<= 0:
2821 self
._update
_suboperation
_status
(
2822 db_nslcmop
, nslcmop_id
, op_index
, 'FAILED', "Timeout when waiting for ns to get ready")
2823 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
2825 # update VDU_SCALING_INFO with the obtained ip_addresses
2826 if vdu_scaling_info
["scaling_direction"] == "OUT":
2827 for vdur
in reversed(db_vnfr
["vdur"]):
2828 if vdu_scaling_info
["vdu-create"].get(vdur
["vdu-id-ref"]):
2829 vdu_scaling_info
["vdu-create"][vdur
["vdu-id-ref"]] -= 1
2830 vdu_scaling_info
["vdu"].append({
2831 "name": vdur
["name"],
2832 "vdu_id": vdur
["vdu-id-ref"],
2835 for interface
in vdur
["interfaces"]:
2836 vdu_scaling_info
["vdu"][-1]["interface"].append({
2837 "name": interface
["name"],
2838 "ip_address": interface
["ip-address"],
2839 "mac_address": interface
.get("mac-address"),
2841 del vdu_scaling_info
["vdu-create"]
2843 self
._update
_suboperation
_status
(db_nslcmop
, op_index
, 'COMPLETED', 'Done')
2846 scale_process
= None
2848 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2851 # execute primitive service POST-SCALING
2852 step
= "Executing post-scale vnf-config-primitive"
2853 if scaling_descriptor
.get("scaling-config-action"):
2854 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
2855 if (scaling_config_action
.get("trigger") == "post-scale-in" and scaling_type
== "SCALE_IN") \
2856 or (scaling_config_action
.get("trigger") == "post-scale-out" and scaling_type
== "SCALE_OUT"):
2857 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
2858 step
= db_nslcmop_update
["detailed-status"] = \
2859 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive
)
2861 vnfr_params
= {"VDU_SCALE_INFO": vdu_scaling_info
}
2862 if db_vnfr
.get("additionalParamsForVnf"):
2863 vnfr_params
.update(db_vnfr
["additionalParamsForVnf"])
2865 # look for primitive
2866 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
2867 if config_primitive
["name"] == vnf_config_primitive
:
2870 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
2871 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
2872 "match any vnf-configuration:config-primitive".format(scaling_group
,
2874 scale_process
= "VCA"
2875 db_nsr_update
["config-status"] = "configuring post-scaling"
2876 primitive_params
= self
._map
_primitive
_params
(config_primitive
, {}, vnfr_params
)
2878 # Post-scale reintent check: Check if this sub-operation has been executed before
2879 op_index
= self
._check
_or
_add
_scale
_suboperation
(
2880 db_nslcmop
, nslcmop_id
, vnf_index
, vnf_config_primitive
, primitive_params
, 'POST-SCALE')
2881 if (op_index
== self
.SUBOPERATION_STATUS_SKIP
):
2882 # Skip sub-operation
2883 result
= 'COMPLETED'
2884 result_detail
= 'Done'
2885 self
.logger
.debug(logging_text
+
2886 "vnf_config_primitive={} Skipped sub-operation, result {} {}".
2887 format(vnf_config_primitive
, result
, result_detail
))
2889 if (op_index
== self
.SUBOPERATION_STATUS_NEW
):
2890 # New sub-operation: Get index of this sub-operation
2891 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
2892 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} New sub-operation".
2893 format(vnf_config_primitive
))
2895 # Reintent: Get registered params for this existing sub-operation
2896 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
2897 vnf_index
= op
.get('member_vnf_index')
2898 vnf_config_primitive
= op
.get('primitive')
2899 primitive_params
= op
.get('primitive_params')
2900 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Sub-operation reintent".
2901 format(vnf_config_primitive
))
2902 # Execute the primitive, either with new (first-time) or registered (reintent) args
2903 result
, result_detail
= await self
._ns
_execute
_primitive
(
2904 nsr_deployed
, vnf_index
, None, None, None, vnf_config_primitive
, primitive_params
)
2905 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
2906 vnf_config_primitive
, result
, result_detail
))
2907 # Update operationState = COMPLETED | FAILED
2908 self
._update
_suboperation
_status
(
2909 db_nslcmop
, op_index
, result
, result_detail
)
2911 if result
== "FAILED":
2912 raise LcmException(result_detail
)
2913 db_nsr_update
["config-status"] = old_config_status
2914 scale_process
= None
2917 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
2918 db_nslcmop_update
["statusEnteredTime"] = time()
2919 db_nslcmop_update
["detailed-status"] = "done"
2920 db_nsr_update
["detailed-status"] = "" # "scaled {} {}".format(scaling_group, scaling_type)
2921 db_nsr_update
["operational-status"] = "running" if old_operational_status
== "failed" \
2922 else old_operational_status
2923 db_nsr_update
["config-status"] = old_config_status
2925 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
2926 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
2928 except asyncio
.CancelledError
:
2929 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
2930 exc
= "Operation was cancelled"
2931 except Exception as e
:
2932 exc
= traceback
.format_exc()
2933 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
2937 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
2938 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2939 db_nslcmop_update
["statusEnteredTime"] = time()
2941 db_nsr_update
["operational-status"] = old_operational_status
2942 db_nsr_update
["config-status"] = old_config_status
2943 db_nsr_update
["detailed-status"] = ""
2944 db_nsr_update
["_admin.nslcmop"] = None
2946 if "VCA" in scale_process
:
2947 db_nsr_update
["config-status"] = "failed"
2948 if "RO" in scale_process
:
2949 db_nsr_update
["operational-status"] = "failed"
2950 db_nsr_update
["detailed-status"] = "FAILED scaling nslcmop={} {}: {}".format(nslcmop_id
, step
,
2953 if db_nslcmop
and db_nslcmop_update
:
2954 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2956 db_nsr_update
["_admin.current-operation"] = None
2957 db_nsr_update
["_admin.operation-type"] = None
2958 db_nsr_update
["_admin.nslcmop"] = None
2959 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2960 except DbException
as e
:
2961 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
2962 if nslcmop_operation_state
:
2964 await self
.msg
.aiowrite("ns", "scaled", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2965 "operationState": nslcmop_operation_state
},
2968 # await asyncio.sleep(cooldown_time, loop=self.loop)
2969 # await self.msg.aiowrite("ns","scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
2970 except Exception as e
:
2971 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
2972 self
.logger
.debug(logging_text
+ "Exit")
2973 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_scale")