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")
889 if ro_retries
>= 360: # 1 hour
890 raise LcmException("Not found _admin.deployed.RO.nsr_id for nsr_id: {}".format(nsr_id
))
892 await asyncio
.sleep(10, loop
=self
.loop
)
893 # wait until NS is deployed at RO
895 db_nsrs
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
896 ro_nsr_id
= deep_get(db_nsrs
, ("_admin", "deployed", "RO", "nsr_id"))
901 if not target_vdu_id
:
902 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnfr_id
})
904 if not vdu_id
: # for the VNF case
905 ip_address
= db_vnfr
.get("ip-address")
908 vdur
= next((x
for x
in get_iterable(db_vnfr
, "vdur") if x
.get("ip-address") == ip_address
), None)
910 vdur
= next((x
for x
in get_iterable(db_vnfr
, "vdur")
911 if x
.get("vdu-id-ref") == vdu_id
and x
.get("count-index") == vdu_index
), None)
914 raise LcmException("Not found vnfr_id={}, vdu_index={}, vdu_index={}".format(
915 vnfr_id
, vdu_id
, vdu_index
918 if vdur
.get("status") == "ACTIVE":
919 ip_address
= vdur
.get("ip-address")
922 target_vdu_id
= vdur
["vdu-id-ref"]
923 elif vdur
.get("status") == "ERROR":
924 raise LcmException("Cannot inject ssh-key because target VM is in error state")
926 if not target_vdu_id
:
929 # self.logger.debug(logging_text + "IP address={}".format(ip_address))
931 # inject public key into machine
933 # self.logger.debug(logging_text + "Inserting RO key")
935 ro_vm_id
= "{}-{}".format(db_vnfr
["member-vnf-index-ref"], target_vdu_id
) # TODO add vdu_index
936 result_dict
= await self
.RO
.create_action(
938 item_id_name
=ro_nsr_id
,
939 descriptor
={"add_public_key": pub_key
, "vms": [ro_vm_id
], "user": user
}
941 # result_dict contains the format {VM-id: {vim_result: 200, description: text}}
942 if not result_dict
or not isinstance(result_dict
, dict):
943 raise LcmException("Unknown response from RO when injecting key")
944 for result
in result_dict
.values():
945 if result
.get("vim_result") == 200:
948 raise ROclient
.ROClientException("error injecting key: {}".format(
949 result
.get("description")))
951 except ROclient
.ROClientException
as e
:
953 self
.logger
.debug(logging_text
+ "error injecting key: {}. Retrying until {} seconds".
957 raise LcmException("Reaching max tries injecting key. Error: {}".format(e
))
963 async def instantiate_N2VC(self
, logging_text
, vca_index
, nsi_id
, db_nsr
, db_vnfr
, vdu_id
,
964 kdu_name
, vdu_index
, config_descriptor
, deploy_params
, base_folder
):
965 nsr_id
= db_nsr
["_id"]
966 db_update_entry
= "_admin.deployed.VCA.{}.".format(vca_index
)
967 vca_deployed_list
= db_nsr
["_admin"]["deployed"]["VCA"]
968 vca_deployed
= db_nsr
["_admin"]["deployed"]["VCA"][vca_index
]
970 'collection': 'nsrs',
971 'filter': {'_id': nsr_id
},
972 'path': db_update_entry
974 logging_text
+= "member_vnf_index={} vdu_id={}, vdu_index={} ".format(db_vnfr
["member-vnf-index-ref"],
981 vnfr_id
= db_vnfr
["_id"]
983 namespace
= "{nsi}.{ns}".format(
984 nsi
=nsi_id
if nsi_id
else "",
987 namespace
+= "." + vnfr_id
989 namespace
+= ".{}-{}".format(vdu_id
, vdu_index
or 0)
992 artifact_path
= "{}/{}/charms/{}".format(
993 base_folder
["folder"],
994 base_folder
["pkg-dir"],
995 config_descriptor
["juju"]["charm"]
998 is_proxy_charm
= deep_get(config_descriptor
, ('juju', 'charm')) is not None
999 if deep_get(config_descriptor
, ('juju', 'proxy')) is False:
1000 is_proxy_charm
= False
1002 # n2vc_redesign STEP 3.1
1004 # find old ee_id if exists
1005 ee_id
= vca_deployed
.get("ee_id")
1007 # create or register execution environment in VCA
1009 step
= "create execution environment"
1010 self
.logger
.debug(logging_text
+ step
)
1011 ee_id
, credentials
= await self
.n2vc
.create_execution_environment(namespace
=namespace
,
1015 step
= "Waiting to VM being up and getting IP address"
1016 self
.logger
.debug(logging_text
+ step
)
1017 rw_mgmt_ip
= await self
.wait_vm_up_insert_key_ro(logging_text
, nsr_id
, vnfr_id
, vdu_id
, vdu_index
,
1018 user
=None, pub_key
=None)
1019 credentials
= {"hostname": rw_mgmt_ip
}
1021 username
= deep_get(config_descriptor
, ("config-access", "ssh-access", "default-user"))
1022 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1023 # merged. Meanwhile let's get username from initial-config-primitive
1024 if not username
and config_descriptor
.get("initial-config-primitive"):
1025 for config_primitive
in config_descriptor
["initial-config-primitive"]:
1026 for param
in config_primitive
.get("parameter", ()):
1027 if param
["name"] == "ssh-username":
1028 username
= param
["value"]
1031 raise LcmException("Cannot determine the username neither with 'initial-config-promitive' nor with "
1032 "'config-access.ssh-access.default-user'")
1033 credentials
["username"] = username
1034 # n2vc_redesign STEP 3.2
1036 step
= "register execution environment {}".format(credentials
)
1037 self
.logger
.debug(logging_text
+ step
)
1038 ee_id
= await self
.n2vc
.register_execution_environment(credentials
=credentials
, namespace
=namespace
,
1041 # for compatibility with MON/POL modules, the need model and application name at database
1042 # TODO ask to N2VC instead of assuming the format "model_name.application_name"
1043 ee_id_parts
= ee_id
.split('.')
1044 model_name
= ee_id_parts
[0]
1045 application_name
= ee_id_parts
[1]
1046 self
.update_db_2("nsrs", nsr_id
, {db_update_entry
+ "model": model_name
,
1047 db_update_entry
+ "application": application_name
,
1048 db_update_entry
+ "ee_id": ee_id
})
1050 # n2vc_redesign STEP 3.3
1052 step
= "Install configuration Software"
1053 # TODO check if already done
1054 self
.logger
.debug(logging_text
+ step
)
1055 await self
.n2vc
.install_configuration_sw(ee_id
=ee_id
, artifact_path
=artifact_path
, db_dict
=db_dict
)
1057 # if SSH access is required, then get execution environment SSH public
1058 if is_proxy_charm
: # if native charm we have waited already to VM be UP
1061 if deep_get(config_descriptor
, ("config-access", "ssh-access", "required")):
1062 # Needed to inject a ssh key
1063 user
= deep_get(config_descriptor
, ("config-access", "ssh-access", "default-user"))
1064 step
= "Install configuration Software, getting public ssh key"
1065 pub_key
= await self
.n2vc
.get_ee_ssh_public__key(ee_id
=ee_id
, db_dict
=db_dict
)
1067 step
= "Insert public key into VM"
1069 step
= "Waiting to VM being up and getting IP address"
1070 self
.logger
.debug(logging_text
+ step
)
1072 # n2vc_redesign STEP 5.1
1073 # wait for RO (ip-address) Insert pub_key into VM
1074 rw_mgmt_ip
= await self
.wait_vm_up_insert_key_ro(logging_text
, nsr_id
, vnfr_id
, vdu_id
, vdu_index
,
1075 user
=user
, pub_key
=pub_key
)
1077 self
.logger
.debug(logging_text
+ ' VM_ip_address={}'.format(rw_mgmt_ip
))
1079 # store rw_mgmt_ip in deploy params for later replacement
1080 deploy_params
["rw_mgmt_ip"] = rw_mgmt_ip
1082 # n2vc_redesign STEP 6 Execute initial config primitive
1083 step
= 'execute initial config primitive'
1084 initial_config_primitive_list
= config_descriptor
.get('initial-config-primitive')
1086 # sort initial config primitives by 'seq'
1088 initial_config_primitive_list
.sort(key
=lambda val
: int(val
['seq']))
1089 except Exception as e
:
1090 self
.logger
.error(logging_text
+ step
+ ": " + str(e
))
1092 # add config if not present for NS charm
1093 initial_config_primitive_list
= self
._get
_initial
_config
_primitive
_list
(initial_config_primitive_list
,
1096 for initial_config_primitive
in initial_config_primitive_list
:
1097 # adding information on the vca_deployed if it is a NS execution environment
1098 if not vca_deployed
["member-vnf-index"]:
1099 deploy_params
["ns_config_info"] = self
._get
_ns
_config
_info
(vca_deployed_list
)
1100 # TODO check if already done
1101 primitive_params_
= self
._map
_primitive
_params
(initial_config_primitive
, {}, deploy_params
)
1103 step
= "execute primitive '{}' params '{}'".format(initial_config_primitive
["name"], primitive_params_
)
1104 self
.logger
.debug(logging_text
+ step
)
1105 await self
.n2vc
.exec_primitive(
1107 primitive_name
=initial_config_primitive
["name"],
1108 params_dict
=primitive_params_
,
1111 # TODO register in database that primitive is done
1113 step
= "instantiated at VCA"
1114 self
.logger
.debug(logging_text
+ step
)
1116 except Exception as e
: # TODO not use Exception but N2VC exception
1117 raise Exception("{} {}".format(step
, e
)) from e
1118 # TODO raise N2VC exception with 'step' extra information
1120 async def instantiate(self
, nsr_id
, nslcmop_id
):
1123 :param nsr_id: ns instance to deploy
1124 :param nslcmop_id: operation to run
1128 # Try to lock HA task here
1129 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
1130 if not task_is_locked_by_me
:
1131 self
.logger
.debug('instantiate() task is not locked by me')
1134 logging_text
= "Task ns={} instantiate={} ".format(nsr_id
, nslcmop_id
)
1135 self
.logger
.debug(logging_text
+ "Enter")
1137 # get all needed from database
1139 # database nsrs record
1142 # database nslcmops record
1145 # update operation on nsrs
1146 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
1147 "_admin.current-operation": nslcmop_id
,
1148 "_admin.operation-type": "instantiate"}
1149 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1151 # update operation on nslcmops
1152 db_nslcmop_update
= {}
1154 nslcmop_operation_state
= None
1155 db_vnfrs
= {} # vnf's info indexed by member-index
1157 task_instantiation_list
= []
1160 # wait for any previous tasks in process
1161 step
= "Waiting for previous operations to terminate"
1162 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
1164 # STEP 0: Reading database (nslcmops, nsrs, nsds, vnfrs, vnfds)
1166 # read from db: operation
1167 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
1168 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1171 step
= "Getting nsr={} from db".format(nsr_id
)
1172 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1173 # nsd is replicated into ns (no db read)
1175 # nsr_name = db_nsr["name"] # TODO short-name??
1177 # read from db: vnf's of this ns
1178 step
= "Getting vnfrs from db"
1179 self
.logger
.debug(logging_text
+ step
)
1180 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1182 # read from db: vnfd's for every vnf
1183 db_vnfds_ref
= {} # every vnfd data indexed by vnf name
1184 db_vnfds
= {} # every vnfd data indexed by vnf id
1185 db_vnfds_index
= {} # every vnfd data indexed by vnf member-index
1187 # for each vnf in ns, read vnfd
1188 for vnfr
in db_vnfrs_list
:
1189 db_vnfrs
[vnfr
["member-vnf-index-ref"]] = vnfr
# vnf's dict indexed by member-index: '1', '2', etc
1190 vnfd_id
= vnfr
["vnfd-id"] # vnfd uuid for this vnf
1191 vnfd_ref
= vnfr
["vnfd-ref"] # vnfd name for this vnf
1192 # if we haven't this vnfd, read it from db
1193 if vnfd_id
not in db_vnfds
:
1195 step
= "Getting vnfd={} id='{}' from db".format(vnfd_id
, vnfd_ref
)
1196 self
.logger
.debug(logging_text
+ step
)
1197 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
1200 db_vnfds_ref
[vnfd_ref
] = vnfd
# vnfd's indexed by name
1201 db_vnfds
[vnfd_id
] = vnfd
# vnfd's indexed by id
1202 db_vnfds_index
[vnfr
["member-vnf-index-ref"]] = db_vnfds
[vnfd_id
] # vnfd's indexed by member-index
1204 # Get or generates the _admin.deployed.VCA list
1205 vca_deployed_list
= None
1206 if db_nsr
["_admin"].get("deployed"):
1207 vca_deployed_list
= db_nsr
["_admin"]["deployed"].get("VCA")
1208 if vca_deployed_list
is None:
1209 vca_deployed_list
= []
1210 db_nsr_update
["_admin.deployed.VCA"] = vca_deployed_list
1211 # add _admin.deployed.VCA to db_nsr dictionary, value=vca_deployed_list
1212 populate_dict(db_nsr
, ("_admin", "deployed", "VCA"), vca_deployed_list
)
1213 elif isinstance(vca_deployed_list
, dict):
1214 # maintain backward compatibility. Change a dict to list at database
1215 vca_deployed_list
= list(vca_deployed_list
.values())
1216 db_nsr_update
["_admin.deployed.VCA"] = vca_deployed_list
1217 populate_dict(db_nsr
, ("_admin", "deployed", "VCA"), vca_deployed_list
)
1219 db_nsr_update
["detailed-status"] = "creating"
1220 db_nsr_update
["operational-status"] = "init"
1222 if not isinstance(deep_get(db_nsr
, ("_admin", "deployed", "RO", "vnfd")), list):
1223 populate_dict(db_nsr
, ("_admin", "deployed", "RO", "vnfd"), [])
1224 db_nsr_update
["_admin.deployed.RO.vnfd"] = []
1226 # set state to INSTANTIATED. When instantiated NBI will not delete directly
1227 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1228 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1229 self
.logger
.debug(logging_text
+ "Before deploy_kdus")
1230 # Call to deploy_kdus in case exists the "vdu:kdu" param
1231 task_kdu
= asyncio
.ensure_future(
1233 logging_text
=logging_text
,
1239 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_KDUs", task_kdu
)
1240 task_instantiation_list
.append(task_kdu
)
1241 # n2vc_redesign STEP 1 Get VCA public ssh-key
1242 # feature 1429. Add n2vc public key to needed VMs
1243 n2vc_key
= self
.n2vc
.get_public_key()
1244 n2vc_key_list
= [n2vc_key
]
1245 if self
.vca_config
.get("public_key"):
1246 n2vc_key_list
.append(self
.vca_config
["public_key"])
1248 # n2vc_redesign STEP 2 Deploy Network Scenario
1249 task_ro
= asyncio
.ensure_future(
1250 self
.instantiate_RO(
1251 logging_text
=logging_text
,
1255 db_nslcmop
=db_nslcmop
,
1257 db_vnfds_ref
=db_vnfds_ref
,
1258 n2vc_key_list
=n2vc_key_list
1261 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_RO", task_ro
)
1262 task_instantiation_list
.append(task_ro
)
1264 # n2vc_redesign STEP 3 to 6 Deploy N2VC
1265 step
= "Looking for needed vnfd to configure with proxy charm"
1266 self
.logger
.debug(logging_text
+ step
)
1268 nsi_id
= None # TODO put nsi_id when this nsr belongs to a NSI
1269 # get_iterable() returns a value from a dict or empty tuple if key does not exist
1270 for c_vnf
in get_iterable(nsd
, "constituent-vnfd"):
1271 vnfd_id
= c_vnf
["vnfd-id-ref"]
1272 vnfd
= db_vnfds_ref
[vnfd_id
]
1273 member_vnf_index
= str(c_vnf
["member-vnf-index"])
1274 db_vnfr
= db_vnfrs
[member_vnf_index
]
1275 base_folder
= vnfd
["_admin"]["storage"]
1281 # Get additional parameters
1283 if db_vnfr
.get("additionalParamsForVnf"):
1284 deploy_params
= self
._format
_additional
_params
(db_vnfr
["additionalParamsForVnf"].copy())
1286 descriptor_config
= vnfd
.get("vnf-configuration")
1287 if descriptor_config
and descriptor_config
.get("juju"):
1289 logging_text
=logging_text
,
1292 nslcmop_id
=nslcmop_id
,
1298 member_vnf_index
=member_vnf_index
,
1299 vdu_index
=vdu_index
,
1301 deploy_params
=deploy_params
,
1302 descriptor_config
=descriptor_config
,
1303 base_folder
=base_folder
,
1304 task_instantiation_list
=task_instantiation_list
1307 # Deploy charms for each VDU that supports one.
1308 for vdud
in get_iterable(vnfd
, 'vdu'):
1310 descriptor_config
= vdud
.get('vdu-configuration')
1311 vdur
= next((x
for x
in db_vnfr
["vdur"] if x
["vdu-id-ref"] == vdu_id
), None)
1312 if vdur
.get("additionalParams"):
1313 deploy_params_vdu
= self
._format
_additional
_params
(vdur
["additionalParams"])
1315 deploy_params_vdu
= deploy_params
1316 if descriptor_config
and descriptor_config
.get("juju"):
1317 # look for vdu index in the db_vnfr["vdu"] section
1318 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
1319 # if vdur["vdu-id-ref"] == vdu_id:
1322 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
1323 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
1324 # vdu_name = vdur.get("name")
1327 for vdu_index
in range(int(vdud
.get("count", 1))):
1328 # TODO vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
1330 logging_text
=logging_text
,
1333 nslcmop_id
=nslcmop_id
,
1339 member_vnf_index
=member_vnf_index
,
1340 vdu_index
=vdu_index
,
1342 deploy_params
=deploy_params_vdu
,
1343 descriptor_config
=descriptor_config
,
1344 base_folder
=base_folder
,
1345 task_instantiation_list
=task_instantiation_list
1347 for kdud
in get_iterable(vnfd
, 'kdu'):
1348 kdu_name
= kdud
["name"]
1349 descriptor_config
= kdud
.get('kdu-configuration')
1350 if descriptor_config
and descriptor_config
.get("juju"):
1354 # look for vdu index in the db_vnfr["vdu"] section
1355 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
1356 # if vdur["vdu-id-ref"] == vdu_id:
1359 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
1360 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
1361 # vdu_name = vdur.get("name")
1365 logging_text
=logging_text
,
1368 nslcmop_id
=nslcmop_id
,
1374 member_vnf_index
=member_vnf_index
,
1375 vdu_index
=vdu_index
,
1377 deploy_params
=deploy_params
,
1378 descriptor_config
=descriptor_config
,
1379 base_folder
=base_folder
,
1380 task_instantiation_list
=task_instantiation_list
1383 # Check if this NS has a charm configuration
1384 descriptor_config
= nsd
.get("ns-configuration")
1385 if descriptor_config
and descriptor_config
.get("juju"):
1388 member_vnf_index
= None
1394 # Get additional parameters
1396 if db_nsr
.get("additionalParamsForNs"):
1397 deploy_params
= self
._format
_additional
_params
(db_nsr
["additionalParamsForNs"].copy())
1398 base_folder
= nsd
["_admin"]["storage"]
1400 logging_text
=logging_text
,
1403 nslcmop_id
=nslcmop_id
,
1409 member_vnf_index
=member_vnf_index
,
1410 vdu_index
=vdu_index
,
1412 deploy_params
=deploy_params
,
1413 descriptor_config
=descriptor_config
,
1414 base_folder
=base_folder
,
1415 task_instantiation_list
=task_instantiation_list
1418 # Wait until all tasks of "task_instantiation_list" have been finished
1420 # while time() <= start_deploy + self.total_deploy_timeout:
1422 timeout
= 3600 # time() - start_deploy
1423 task_instantiation_set
= set(task_instantiation_list
) # build a set with tasks
1426 if len(task_instantiation_set
) > 0:
1427 done
, pending
= await asyncio
.wait(task_instantiation_set
, timeout
=timeout
)
1429 error_text
= "timeout"
1431 if task
.cancelled():
1433 error_text
= "cancelled"
1435 exc
= task
.exception()
1437 error_text
= str(exc
)
1440 db_nsr_update
["config-status"] = "failed"
1441 error_text
= "fail configuring " + error_text
1442 db_nsr_update
["detailed-status"] = error_text
1443 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED_TEMP"
1444 db_nslcmop_update
["detailed-status"] = error_text
1445 db_nslcmop_update
["statusEnteredTime"] = time()
1448 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
1449 db_nslcmop_update
["statusEnteredTime"] = time()
1450 db_nslcmop_update
["detailed-status"] = "done"
1451 db_nsr_update
["config-status"] = "configured"
1452 db_nsr_update
["detailed-status"] = "done"
1454 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
1455 self
.logger
.error(logging_text
+ "Exit Exception while '{}': {}".format(step
, e
))
1457 except asyncio
.CancelledError
:
1458 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1459 exc
= "Operation was cancelled"
1460 except Exception as e
:
1461 exc
= traceback
.format_exc()
1462 self
.logger
.critical(logging_text
+ "Exit Exception {} while '{}': {}".format(type(e
).__name
__, step
, e
),
1467 db_nsr_update
["detailed-status"] = "ERROR {}: {}".format(step
, exc
)
1468 db_nsr_update
["operational-status"] = "failed"
1470 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
1471 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
1472 db_nslcmop_update
["statusEnteredTime"] = time()
1475 db_nsr_update
["_admin.nslcmop"] = None
1476 db_nsr_update
["_admin.current-operation"] = None
1477 db_nsr_update
["_admin.operation-type"] = None
1478 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1479 if db_nslcmop_update
:
1480 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1481 except DbException
as e
:
1482 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
1483 if nslcmop_operation_state
:
1485 await self
.msg
.aiowrite("ns", "instantiated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
1486 "operationState": nslcmop_operation_state
},
1488 except Exception as e
:
1489 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1491 self
.logger
.debug(logging_text
+ "Exit")
1492 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_instantiate")
1494 async def deploy_kdus(self
, logging_text
, nsr_id
, db_nsr
, db_vnfrs
):
1495 # Launch kdus if present in the descriptor
1497 k8scluster_id_2_uuic
= {"helm-chart": {}, "juju-bundle": {}}
1499 def _get_cluster_id(cluster_id
, cluster_type
):
1500 nonlocal k8scluster_id_2_uuic
1501 if cluster_id
in k8scluster_id_2_uuic
[cluster_type
]:
1502 return k8scluster_id_2_uuic
[cluster_type
][cluster_id
]
1504 db_k8scluster
= self
.db
.get_one("k8sclusters", {"_id": cluster_id
}, fail_on_empty
=False)
1505 if not db_k8scluster
:
1506 raise LcmException("K8s cluster {} cannot be found".format(cluster_id
))
1507 k8s_id
= deep_get(db_k8scluster
, ("_admin", cluster_type
, "id"))
1509 raise LcmException("K8s cluster '{}' has not been initilized for '{}'".format(cluster_id
, cluster_type
))
1510 k8scluster_id_2_uuic
[cluster_type
][cluster_id
] = k8s_id
1513 logging_text
+= "Deploy kdus: "
1515 db_nsr_update
= {"_admin.deployed.K8s": []}
1516 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1518 # Look for all vnfds
1521 for vnfr_data
in db_vnfrs
.values():
1522 for kdur
in get_iterable(vnfr_data
, "kdur"):
1523 desc_params
= self
._format
_additional
_params
(kdur
.get("additionalParams"))
1525 k8sclustertype
= None
1528 if kdur
.get("helm-chart"):
1529 kdumodel
= kdur
["helm-chart"]
1530 k8sclustertype
= "chart"
1531 k8sclustertype_full
= "helm-chart"
1532 elif kdur
.get("juju-bundle"):
1533 kdumodel
= kdur
["juju-bundle"]
1534 k8sclustertype
= "juju"
1535 k8sclustertype_full
= "juju-bundle"
1537 error_text
= "kdu type is neither helm-chart not juju-bundle. Maybe an old NBI version is" \
1541 cluster_uuid
= _get_cluster_id(kdur
["k8s-cluster"]["id"], k8sclustertype_full
)
1542 except LcmException
as e
:
1544 step
= "Instantiate KDU {} in k8s cluster {}".format(kdur
["kdu-name"], cluster_uuid
)
1546 k8s_instace_info
= {"kdu-instance": None, "k8scluster-uuid": cluster_uuid
,
1547 "k8scluster-type": k8sclustertype
,
1548 "kdu-name": kdur
["kdu-name"], "kdu-model": kdumodel
}
1550 k8s_instace_info
["detailed-status"] = error_text
1551 db_nsr_update
["_admin.deployed.K8s.{}".format(index
)] = k8s_instace_info
1552 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1556 db_dict
= {"collection": "nsrs", "filter": {"_id": nsr_id
}, "path": "_admin.deployed.K8s."
1558 if k8sclustertype
== "chart":
1559 task
= asyncio
.ensure_future(
1560 self
.k8sclusterhelm
.install(cluster_uuid
=cluster_uuid
, kdu_model
=kdumodel
, atomic
=True,
1561 params
=desc_params
, db_dict
=db_dict
, timeout
=3600)
1564 task
= self
.k8sclusterjuju
.install(cluster_uuid
=cluster_uuid
, kdu_model
=kdumodel
,
1565 atomic
=True, params
=desc_params
,
1566 db_dict
=db_dict
, timeout
=600)
1568 pending_tasks
[task
] = "_admin.deployed.K8s.{}.".format(index
)
1570 if not pending_tasks
:
1572 self
.logger
.debug(logging_text
+ 'Waiting for terminate pending tasks...')
1573 pending_list
= list(pending_tasks
.keys())
1575 done_list
, pending_list
= await asyncio
.wait(pending_list
, timeout
=30*60,
1576 return_when
=asyncio
.FIRST_COMPLETED
)
1577 if not done_list
: # timeout
1578 for task
in pending_list
:
1579 db_nsr_update
[pending_tasks(task
) + "detailed-status"] = "Timeout"
1581 for task
in done_list
:
1582 exc
= task
.exception()
1584 db_nsr_update
[pending_tasks
[task
] + "detailed-status"] = "{}".format(exc
)
1586 db_nsr_update
[pending_tasks
[task
] + "kdu-instance"] = task
.result()
1588 except Exception as e
:
1589 self
.logger
.critical(logging_text
+ "Exit Exception {} while '{}': {}".format(type(e
).__name
__, step
, e
))
1590 raise LcmException("{} Exit Exception {} while '{}': {}".format(logging_text
, type(e
).__name
__, step
, e
))
1592 # TODO Write in data base
1594 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1596 def _deploy_n2vc(self
, logging_text
, db_nsr
, db_vnfr
, nslcmop_id
, nsr_id
, nsi_id
, vnfd_id
, vdu_id
,
1597 kdu_name
, member_vnf_index
, vdu_index
, vdu_name
, deploy_params
, descriptor_config
,
1598 base_folder
, task_instantiation_list
):
1599 # launch instantiate_N2VC in a asyncio task and register task object
1600 # Look where information of this charm is at database <nsrs>._admin.deployed.VCA
1601 # if not found, create one entry and update database
1603 # fill db_nsr._admin.deployed.VCA.<index>
1605 for vca_index
, vca_deployed
in enumerate(db_nsr
["_admin"]["deployed"]["VCA"]):
1606 if not vca_deployed
:
1608 if vca_deployed
.get("member-vnf-index") == member_vnf_index
and \
1609 vca_deployed
.get("vdu_id") == vdu_id
and \
1610 vca_deployed
.get("kdu_name") == kdu_name
and \
1611 vca_deployed
.get("vdu_count_index", 0) == vdu_index
:
1614 # not found, create one.
1616 "member-vnf-index": member_vnf_index
,
1618 "kdu_name": kdu_name
,
1619 "vdu_count_index": vdu_index
,
1620 "operational-status": "init", # TODO revise
1621 "detailed-status": "", # TODO revise
1622 "step": "initial-deploy", # TODO revise
1624 "vdu_name": vdu_name
,
1627 self
.update_db_2("nsrs", nsr_id
, {"_admin.deployed.VCA.{}".format(vca_index
): vca_deployed
})
1628 db_nsr
["_admin"]["deployed"]["VCA"].append(vca_deployed
)
1631 task_n2vc
= asyncio
.ensure_future(
1632 self
.instantiate_N2VC(
1633 logging_text
=logging_text
,
1634 vca_index
=vca_index
,
1640 vdu_index
=vdu_index
,
1641 deploy_params
=deploy_params
,
1642 config_descriptor
=descriptor_config
,
1643 base_folder
=base_folder
,
1646 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_N2VC-{}".format(vca_index
), task_n2vc
)
1647 task_instantiation_list
.append(task_n2vc
)
1649 # Check if this VNFD has a configured terminate action
1650 def _has_terminate_config_primitive(self
, vnfd
):
1651 vnf_config
= vnfd
.get("vnf-configuration")
1652 if vnf_config
and vnf_config
.get("terminate-config-primitive"):
1658 def _get_terminate_config_primitive_seq_list(vnfd
):
1659 """ Get a numerically sorted list of the sequences for this VNFD's terminate action """
1660 # No need to check for existing primitive twice, already done before
1661 vnf_config
= vnfd
.get("vnf-configuration")
1662 seq_list
= vnf_config
.get("terminate-config-primitive")
1663 # Get all 'seq' tags in seq_list, order sequences numerically, ascending.
1664 seq_list_sorted
= sorted(seq_list
, key
=lambda x
: int(x
['seq']))
1665 return seq_list_sorted
1668 def _create_nslcmop(nsr_id
, operation
, params
):
1670 Creates a ns-lcm-opp content to be stored at database.
1671 :param nsr_id: internal id of the instance
1672 :param operation: instantiate, terminate, scale, action, ...
1673 :param params: user parameters for the operation
1674 :return: dictionary following SOL005 format
1676 # Raise exception if invalid arguments
1677 if not (nsr_id
and operation
and params
):
1679 "Parameters 'nsr_id', 'operation' and 'params' needed to create primitive not provided")
1685 # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1686 "operationState": "PROCESSING",
1687 "statusEnteredTime": now
,
1688 "nsInstanceId": nsr_id
,
1689 "lcmOperationType": operation
,
1691 "isAutomaticInvocation": False,
1692 "operationParams": params
,
1693 "isCancelPending": False,
1695 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
1696 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
1701 def _format_additional_params(self
, params
):
1702 params
= params
or {}
1703 for key
, value
in params
.items():
1704 if str(value
).startswith("!!yaml "):
1705 params
[key
] = yaml
.safe_load(value
[7:])
1708 def _get_terminate_primitive_params(self
, seq
, vnf_index
):
1709 primitive
= seq
.get('name')
1710 primitive_params
= {}
1712 "member_vnf_index": vnf_index
,
1713 "primitive": primitive
,
1714 "primitive_params": primitive_params
,
1717 return self
._map
_primitive
_params
(seq
, params
, desc_params
)
1721 def _reintent_or_skip_suboperation(self
, db_nslcmop
, op_index
):
1722 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
1723 if (op
.get('operationState') == 'COMPLETED'):
1724 # b. Skip sub-operation
1725 # _ns_execute_primitive() or RO.create_action() will NOT be executed
1726 return self
.SUBOPERATION_STATUS_SKIP
1728 # c. Reintent executing sub-operation
1729 # The sub-operation exists, and operationState != 'COMPLETED'
1730 # Update operationState = 'PROCESSING' to indicate a reintent.
1731 operationState
= 'PROCESSING'
1732 detailed_status
= 'In progress'
1733 self
._update
_suboperation
_status
(
1734 db_nslcmop
, op_index
, operationState
, detailed_status
)
1735 # Return the sub-operation index
1736 # _ns_execute_primitive() or RO.create_action() will be called from scale()
1737 # with arguments extracted from the sub-operation
1740 # Find a sub-operation where all keys in a matching dictionary must match
1741 # Returns the index of the matching sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if no match
1742 def _find_suboperation(self
, db_nslcmop
, match
):
1743 if (db_nslcmop
and match
):
1744 op_list
= db_nslcmop
.get('_admin', {}).get('operations', [])
1745 for i
, op
in enumerate(op_list
):
1746 if all(op
.get(k
) == match
[k
] for k
in match
):
1748 return self
.SUBOPERATION_STATUS_NOT_FOUND
1750 # Update status for a sub-operation given its index
1751 def _update_suboperation_status(self
, db_nslcmop
, op_index
, operationState
, detailed_status
):
1752 # Update DB for HA tasks
1753 q_filter
= {'_id': db_nslcmop
['_id']}
1754 update_dict
= {'_admin.operations.{}.operationState'.format(op_index
): operationState
,
1755 '_admin.operations.{}.detailed-status'.format(op_index
): detailed_status
}
1756 self
.db
.set_one("nslcmops",
1758 update_dict
=update_dict
,
1759 fail_on_empty
=False)
1761 # Add sub-operation, return the index of the added sub-operation
1762 # Optionally, set operationState, detailed-status, and operationType
1763 # Status and type are currently set for 'scale' sub-operations:
1764 # 'operationState' : 'PROCESSING' | 'COMPLETED' | 'FAILED'
1765 # 'detailed-status' : status message
1766 # 'operationType': may be any type, in the case of scaling: 'PRE-SCALE' | 'POST-SCALE'
1767 # Status and operation type are currently only used for 'scale', but NOT for 'terminate' sub-operations.
1768 def _add_suboperation(self
, db_nslcmop
, vnf_index
, vdu_id
, vdu_count_index
, vdu_name
, primitive
,
1769 mapped_primitive_params
, operationState
=None, detailed_status
=None, operationType
=None,
1770 RO_nsr_id
=None, RO_scaling_info
=None):
1771 if not (db_nslcmop
):
1772 return self
.SUBOPERATION_STATUS_NOT_FOUND
1773 # Get the "_admin.operations" list, if it exists
1774 db_nslcmop_admin
= db_nslcmop
.get('_admin', {})
1775 op_list
= db_nslcmop_admin
.get('operations')
1776 # Create or append to the "_admin.operations" list
1777 new_op
= {'member_vnf_index': vnf_index
,
1779 'vdu_count_index': vdu_count_index
,
1780 'primitive': primitive
,
1781 'primitive_params': mapped_primitive_params
}
1783 new_op
['operationState'] = operationState
1785 new_op
['detailed-status'] = detailed_status
1787 new_op
['lcmOperationType'] = operationType
1789 new_op
['RO_nsr_id'] = RO_nsr_id
1791 new_op
['RO_scaling_info'] = RO_scaling_info
1793 # No existing operations, create key 'operations' with current operation as first list element
1794 db_nslcmop_admin
.update({'operations': [new_op
]})
1795 op_list
= db_nslcmop_admin
.get('operations')
1797 # Existing operations, append operation to list
1798 op_list
.append(new_op
)
1800 db_nslcmop_update
= {'_admin.operations': op_list
}
1801 self
.update_db_2("nslcmops", db_nslcmop
['_id'], db_nslcmop_update
)
1802 op_index
= len(op_list
) - 1
1805 # Helper methods for scale() sub-operations
1807 # pre-scale/post-scale:
1808 # Check for 3 different cases:
1809 # a. New: First time execution, return SUBOPERATION_STATUS_NEW
1810 # b. Skip: Existing sub-operation exists, operationState == 'COMPLETED', return SUBOPERATION_STATUS_SKIP
1811 # c. Reintent: Existing sub-operation exists, operationState != 'COMPLETED', return op_index to re-execute
1812 def _check_or_add_scale_suboperation(self
, db_nslcmop
, vnf_index
, vnf_config_primitive
, primitive_params
,
1813 operationType
, RO_nsr_id
=None, RO_scaling_info
=None):
1814 # Find this sub-operation
1815 if (RO_nsr_id
and RO_scaling_info
):
1816 operationType
= 'SCALE-RO'
1818 'member_vnf_index': vnf_index
,
1819 'RO_nsr_id': RO_nsr_id
,
1820 'RO_scaling_info': RO_scaling_info
,
1824 'member_vnf_index': vnf_index
,
1825 'primitive': vnf_config_primitive
,
1826 'primitive_params': primitive_params
,
1827 'lcmOperationType': operationType
1829 op_index
= self
._find
_suboperation
(db_nslcmop
, match
)
1830 if (op_index
== self
.SUBOPERATION_STATUS_NOT_FOUND
):
1831 # a. New sub-operation
1832 # The sub-operation does not exist, add it.
1833 # _ns_execute_primitive() will be called from scale() as usual, with non-modified arguments
1834 # The following parameters are set to None for all kind of scaling:
1836 vdu_count_index
= None
1838 if (RO_nsr_id
and RO_scaling_info
):
1839 vnf_config_primitive
= None
1840 primitive_params
= None
1843 RO_scaling_info
= None
1844 # Initial status for sub-operation
1845 operationState
= 'PROCESSING'
1846 detailed_status
= 'In progress'
1847 # Add sub-operation for pre/post-scaling (zero or more operations)
1848 self
._add
_suboperation
(db_nslcmop
,
1853 vnf_config_primitive
,
1860 return self
.SUBOPERATION_STATUS_NEW
1862 # Return either SUBOPERATION_STATUS_SKIP (operationState == 'COMPLETED'),
1863 # or op_index (operationState != 'COMPLETED')
1864 return self
._reintent
_or
_skip
_suboperation
(db_nslcmop
, op_index
)
1866 # Helper methods for terminate()
1868 async def _terminate_action(self
, db_nslcmop
, nslcmop_id
, nsr_id
):
1869 """ Create a primitive with params from VNFD
1870 Called from terminate() before deleting instance
1871 Calls action() to execute the primitive """
1872 logging_text
= "Task ns={} _terminate_action={} ".format(nsr_id
, nslcmop_id
)
1873 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1876 for vnfr
in db_vnfrs_list
:
1877 vnfd_id
= vnfr
["vnfd-id"]
1878 vnf_index
= vnfr
["member-vnf-index-ref"]
1879 if vnfd_id
not in db_vnfds
:
1880 step
= "Getting vnfd={} id='{}' from db".format(vnfd_id
, vnfd_id
)
1881 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
1882 db_vnfds
[vnfd_id
] = vnfd
1883 vnfd
= db_vnfds
[vnfd_id
]
1884 if not self
._has
_terminate
_config
_primitive
(vnfd
):
1886 # Get the primitive's sorted sequence list
1887 seq_list
= self
._get
_terminate
_config
_primitive
_seq
_list
(vnfd
)
1888 for seq
in seq_list
:
1889 # For each sequence in list, get primitive and call _ns_execute_primitive()
1890 step
= "Calling terminate action for vnf_member_index={} primitive={}".format(
1891 vnf_index
, seq
.get("name"))
1892 self
.logger
.debug(logging_text
+ step
)
1893 # Create the primitive for each sequence, i.e. "primitive": "touch"
1894 primitive
= seq
.get('name')
1895 mapped_primitive_params
= self
._get
_terminate
_primitive
_params
(seq
, vnf_index
)
1896 # The following 3 parameters are currently set to None for 'terminate':
1897 # vdu_id, vdu_count_index, vdu_name
1898 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
1899 vdu_count_index
= db_nslcmop
["operationParams"].get("vdu_count_index")
1900 vdu_name
= db_nslcmop
["operationParams"].get("vdu_name")
1902 self
._add
_suboperation
(db_nslcmop
,
1909 mapped_primitive_params
)
1910 # Sub-operations: Call _ns_execute_primitive() instead of action()
1911 # db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1912 # nsr_deployed = db_nsr["_admin"]["deployed"]
1914 # nslcmop_operation_state, nslcmop_operation_state_detail = await self.action(
1915 # nsr_id, nslcmop_terminate_action_id)
1916 # Launch Exception if action() returns other than ['COMPLETED', 'PARTIALLY_COMPLETED']
1917 # result_ok = ['COMPLETED', 'PARTIALLY_COMPLETED']
1918 # if result not in result_ok:
1919 # raise LcmException(
1920 # "terminate_primitive_action for vnf_member_index={}",
1921 # " primitive={} fails with error {}".format(
1922 # vnf_index, seq.get("name"), result_detail))
1927 await self
.n2vc
.exec_primitive(
1929 primitive_name
=primitive
,
1930 params_dict
=mapped_primitive_params
1932 except Exception as e
:
1933 self
.logger
.error('Error executing primitive {}: {}'.format(primitive
, e
))
1935 "terminate_primitive_action for vnf_member_index={}, primitive={} fails with error {}"
1936 .format(vnf_index
, seq
.get("name"), e
),
1939 async def terminate(self
, nsr_id
, nslcmop_id
):
1941 # Try to lock HA task here
1942 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
1943 if not task_is_locked_by_me
:
1946 logging_text
= "Task ns={} terminate={} ".format(nsr_id
, nslcmop_id
)
1947 self
.logger
.debug(logging_text
+ "Enter")
1951 failed_detail
= [] # annotates all failed error messages
1952 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
1953 "_admin.current-operation": nslcmop_id
,
1954 "_admin.operation-type": "terminate"}
1955 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1956 db_nslcmop_update
= {}
1957 nslcmop_operation_state
= None
1958 autoremove
= False # autoremove after terminated
1961 # wait for any previous tasks in process
1962 step
= "Waiting for previous operations to terminate"
1963 await self
.lcm_tasks
.waitfor_related_HA("ns", 'nslcmops', nslcmop_id
)
1965 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
1966 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1967 step
= "Getting nsr={} from db".format(nsr_id
)
1968 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1969 # nsd = db_nsr["nsd"]
1970 nsr_deployed
= deepcopy(db_nsr
["_admin"].get("deployed"))
1971 if db_nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
1973 # #TODO check if VIM is creating and wait
1974 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
1975 # Call internal terminate action
1976 await self
._terminate
_action
(db_nslcmop
, nslcmop_id
, nsr_id
)
1980 db_nsr_update
["operational-status"] = "terminating"
1981 db_nsr_update
["config-status"] = "terminating"
1985 step
= "delete execution environment"
1986 self
.logger
.debug(logging_text
+ step
)
1988 task_delete_ee
= asyncio
.ensure_future(self
.n2vc
.delete_namespace(namespace
="." + nsr_id
))
1989 pending_tasks
.append(task_delete_ee
)
1990 except Exception as e
:
1991 msg
= "Failed while deleting NS in VCA: {}".format(e
)
1992 self
.logger
.error(msg
)
1993 failed_detail
.append(msg
)
1996 # Delete from k8scluster
1997 step
= "delete kdus"
1998 self
.logger
.debug(logging_text
+ step
)
1999 # print(nsr_deployed)
2001 for kdu
in nsr_deployed
.get("K8s", ()):
2002 kdu_instance
= kdu
.get("kdu-instance")
2003 if not kdu_instance
:
2005 if kdu
.get("k8scluster-type") == "chart":
2006 task_delete_kdu_instance
= asyncio
.ensure_future(
2007 self
.k8sclusterhelm
.uninstall(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2008 kdu_instance
=kdu_instance
))
2009 elif kdu
.get("k8scluster-type") == "juju":
2010 task_delete_kdu_instance
= asyncio
.ensure_future(
2011 self
.k8sclusterjuju
.uninstall(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2012 kdu_instance
=kdu_instance
))
2014 self
.error(logging_text
+ "Unknown k8s deployment type {}".
2015 format(kdu
.get("k8scluster-type")))
2017 pending_tasks
.append(task_delete_kdu_instance
)
2018 except LcmException
as e
:
2019 msg
= "Failed while deleting KDUs from NS: {}".format(e
)
2020 self
.logger
.error(msg
)
2021 failed_detail
.append(msg
)
2027 RO_nsr_id
= RO_delete_action
= None
2028 if nsr_deployed
and nsr_deployed
.get("RO"):
2029 RO_nsr_id
= nsr_deployed
["RO"].get("nsr_id")
2030 RO_delete_action
= nsr_deployed
["RO"].get("nsr_delete_action_id")
2033 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] = \
2034 "Deleting ns from VIM"
2035 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2036 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2037 self
.logger
.debug(logging_text
+ step
)
2038 desc
= await self
.RO
.delete("ns", RO_nsr_id
)
2039 RO_delete_action
= desc
["action_id"]
2040 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = RO_delete_action
2041 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
2042 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
2043 if RO_delete_action
:
2044 # wait until NS is deleted from VIM
2045 step
= detailed_status
= "Waiting ns deleted from VIM. RO_id={} RO_delete_action={}".\
2046 format(RO_nsr_id
, RO_delete_action
)
2047 detailed_status_old
= None
2048 self
.logger
.debug(logging_text
+ step
)
2050 delete_timeout
= 20 * 60 # 20 minutes
2051 while delete_timeout
> 0:
2052 desc
= await self
.RO
.show(
2054 item_id_name
=RO_nsr_id
,
2055 extra_item
="action",
2056 extra_item_id
=RO_delete_action
)
2057 ns_status
, ns_status_info
= self
.RO
.check_action_status(desc
)
2058 if ns_status
== "ERROR":
2059 raise ROclient
.ROClientException(ns_status_info
)
2060 elif ns_status
== "BUILD":
2061 detailed_status
= step
+ "; {}".format(ns_status_info
)
2062 elif ns_status
== "ACTIVE":
2063 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
2064 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
2067 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
2068 if detailed_status
!= detailed_status_old
:
2069 detailed_status_old
= db_nslcmop_update
["detailed-status"] = \
2070 db_nsr_update
["detailed-status"] = detailed_status
2071 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2072 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2073 await asyncio
.sleep(5, loop
=self
.loop
)
2075 else: # delete_timeout <= 0:
2076 raise ROclient
.ROClientException("Timeout waiting ns deleted from VIM")
2078 except ROclient
.ROClientException
as e
:
2079 if e
.http_code
== 404: # not found
2080 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
2081 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
2082 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
2083 self
.logger
.debug(logging_text
+ "RO_ns_id={} already deleted".format(RO_nsr_id
))
2084 elif e
.http_code
== 409: # conflict
2085 failed_detail
.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id
, e
))
2086 self
.logger
.debug(logging_text
+ failed_detail
[-1])
2089 failed_detail
.append("RO_ns_id={} delete error: {}".format(RO_nsr_id
, e
))
2090 self
.logger
.error(logging_text
+ failed_detail
[-1])
2094 if not RO_fail
and nsr_deployed
and nsr_deployed
.get("RO") and nsr_deployed
["RO"].get("nsd_id"):
2095 RO_nsd_id
= nsr_deployed
["RO"]["nsd_id"]
2097 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
2098 "Deleting nsd from RO"
2099 await self
.RO
.delete("nsd", RO_nsd_id
)
2100 self
.logger
.debug(logging_text
+ "RO_nsd_id={} deleted".format(RO_nsd_id
))
2101 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
2102 except ROclient
.ROClientException
as e
:
2103 if e
.http_code
== 404: # not found
2104 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
2105 self
.logger
.debug(logging_text
+ "RO_nsd_id={} already deleted".format(RO_nsd_id
))
2106 elif e
.http_code
== 409: # conflict
2107 failed_detail
.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id
, e
))
2108 self
.logger
.debug(logging_text
+ failed_detail
[-1])
2111 failed_detail
.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id
, e
))
2112 self
.logger
.error(logging_text
+ failed_detail
[-1])
2115 if not RO_fail
and nsr_deployed
and nsr_deployed
.get("RO") and nsr_deployed
["RO"].get("vnfd"):
2116 for index
, vnf_deployed
in enumerate(nsr_deployed
["RO"]["vnfd"]):
2117 if not vnf_deployed
or not vnf_deployed
["id"]:
2120 RO_vnfd_id
= vnf_deployed
["id"]
2121 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
2122 "Deleting member_vnf_index={} RO_vnfd_id={} from RO".format(
2123 vnf_deployed
["member-vnf-index"], RO_vnfd_id
)
2124 await self
.RO
.delete("vnfd", RO_vnfd_id
)
2125 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} deleted".format(RO_vnfd_id
))
2126 db_nsr_update
["_admin.deployed.RO.vnfd.{}.id".format(index
)] = None
2127 except ROclient
.ROClientException
as e
:
2128 if e
.http_code
== 404: # not found
2129 db_nsr_update
["_admin.deployed.RO.vnfd.{}.id".format(index
)] = None
2130 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} already deleted ".format(RO_vnfd_id
))
2131 elif e
.http_code
== 409: # conflict
2132 failed_detail
.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id
, e
))
2133 self
.logger
.debug(logging_text
+ failed_detail
[-1])
2135 failed_detail
.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id
, e
))
2136 self
.logger
.error(logging_text
+ failed_detail
[-1])
2139 self
.logger
.error(logging_text
+ " ;".join(failed_detail
))
2140 db_nsr_update
["operational-status"] = "failed"
2141 db_nsr_update
["detailed-status"] = "Deletion errors " + "; ".join(failed_detail
)
2142 db_nslcmop_update
["detailed-status"] = "; ".join(failed_detail
)
2143 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2144 db_nslcmop_update
["statusEnteredTime"] = time()
2146 db_nsr_update
["operational-status"] = "terminated"
2147 db_nsr_update
["detailed-status"] = "Done"
2148 db_nsr_update
["_admin.nsState"] = "NOT_INSTANTIATED"
2149 db_nslcmop_update
["detailed-status"] = "Done"
2150 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
2151 db_nslcmop_update
["statusEnteredTime"] = time()
2152 if db_nslcmop
["operationParams"].get("autoremove"):
2155 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
2156 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
2158 except asyncio
.CancelledError
:
2159 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
2160 exc
= "Operation was cancelled"
2161 except Exception as e
:
2162 exc
= traceback
.format_exc()
2163 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
2165 if exc
and db_nslcmop
:
2166 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
2167 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2168 db_nslcmop_update
["statusEnteredTime"] = time()
2170 if db_nslcmop
and db_nslcmop_update
:
2171 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2173 db_nsr_update
["_admin.nslcmop"] = None
2174 db_nsr_update
["_admin.current-operation"] = None
2175 db_nsr_update
["_admin.operation-type"] = None
2176 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2177 except DbException
as e
:
2178 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
2179 if nslcmop_operation_state
:
2181 await self
.msg
.aiowrite("ns", "terminated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2182 "operationState": nslcmop_operation_state
,
2183 "autoremove": autoremove
},
2185 except Exception as e
:
2186 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
2188 # wait for pending tasks
2192 self
.logger
.debug(logging_text
+ 'Waiting for terminate pending tasks...')
2193 done
, pending
= await asyncio
.wait(pending_tasks
, timeout
=3600)
2195 self
.logger
.debug(logging_text
+ 'All tasks finished...')
2197 self
.logger
.info(logging_text
+ 'There are pending tasks: {}'.format(pending
))
2199 self
.logger
.debug(logging_text
+ "Exit")
2200 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_terminate")
2203 def _map_primitive_params(primitive_desc
, params
, instantiation_params
):
2205 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
2206 The default-value is used. If it is between < > it look for a value at instantiation_params
2207 :param primitive_desc: portion of VNFD/NSD that describes primitive
2208 :param params: Params provided by user
2209 :param instantiation_params: Instantiation params provided by user
2210 :return: a dictionary with the calculated params
2212 calculated_params
= {}
2213 for parameter
in primitive_desc
.get("parameter", ()):
2214 param_name
= parameter
["name"]
2215 if param_name
in params
:
2216 calculated_params
[param_name
] = params
[param_name
]
2217 elif "default-value" in parameter
or "value" in parameter
:
2218 if "value" in parameter
:
2219 calculated_params
[param_name
] = parameter
["value"]
2221 calculated_params
[param_name
] = parameter
["default-value"]
2222 if isinstance(calculated_params
[param_name
], str) and calculated_params
[param_name
].startswith("<") \
2223 and calculated_params
[param_name
].endswith(">"):
2224 if calculated_params
[param_name
][1:-1] in instantiation_params
:
2225 calculated_params
[param_name
] = instantiation_params
[calculated_params
[param_name
][1:-1]]
2227 raise LcmException("Parameter {} needed to execute primitive {} not provided".
2228 format(calculated_params
[param_name
], primitive_desc
["name"]))
2230 raise LcmException("Parameter {} needed to execute primitive {} not provided".
2231 format(param_name
, primitive_desc
["name"]))
2233 if isinstance(calculated_params
[param_name
], (dict, list, tuple)):
2234 calculated_params
[param_name
] = yaml
.safe_dump(calculated_params
[param_name
], default_flow_style
=True,
2236 elif isinstance(calculated_params
[param_name
], str) and calculated_params
[param_name
].startswith("!!yaml "):
2237 calculated_params
[param_name
] = calculated_params
[param_name
][7:]
2239 # add always ns_config_info if primitive name is config
2240 if primitive_desc
["name"] == "config":
2241 if "ns_config_info" in instantiation_params
:
2242 calculated_params
["ns_config_info"] = instantiation_params
["ns_config_info"]
2243 return calculated_params
2245 async def _ns_execute_primitive(self
, db_deployed
, member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
,
2246 primitive
, primitive_params
, retries
=0, retries_interval
=30) -> (str, str):
2248 # find vca_deployed record for this action
2250 for vca_deployed
in db_deployed
["VCA"]:
2251 if not vca_deployed
:
2253 if member_vnf_index
!= vca_deployed
["member-vnf-index"] or vdu_id
!= vca_deployed
["vdu_id"]:
2255 if vdu_name
and vdu_name
!= vca_deployed
["vdu_name"]:
2257 if vdu_count_index
and vdu_count_index
!= vca_deployed
["vdu_count_index"]:
2261 # vca_deployed not found
2262 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} is not "
2263 "deployed".format(member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
))
2266 ee_id
= vca_deployed
.get("ee_id")
2268 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} has not "
2269 "execution environment"
2270 .format(member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
))
2272 if primitive
== "config":
2273 primitive_params
= {"params": primitive_params
}
2277 output
= await self
.n2vc
.exec_primitive(
2279 primitive_name
=primitive
,
2280 params_dict
=primitive_params
2284 except Exception as e
:
2287 self
.logger
.debug('Error executing action {} on {} -> {}'.format(primitive
, ee_id
, e
))
2289 await asyncio
.sleep(retries_interval
, loop
=self
.loop
)
2291 return 'Cannot execute action {} on {}: {}'.format(primitive
, ee_id
, e
), 'FAIL'
2295 except Exception as e
:
2296 return 'Error executing action {}: {}'.format(primitive
, e
), 'FAIL'
2298 async def action(self
, nsr_id
, nslcmop_id
):
2300 # Try to lock HA task here
2301 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
2302 if not task_is_locked_by_me
:
2305 logging_text
= "Task ns={} action={} ".format(nsr_id
, nslcmop_id
)
2306 self
.logger
.debug(logging_text
+ "Enter")
2307 # get all needed from database
2310 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
2311 "_admin.current-operation": nslcmop_id
,
2312 "_admin.operation-type": "action"}
2313 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2314 db_nslcmop_update
= {}
2315 nslcmop_operation_state
= None
2316 nslcmop_operation_state_detail
= None
2319 # wait for any previous tasks in process
2320 step
= "Waiting for previous operations to terminate"
2321 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
2323 step
= "Getting information from database"
2324 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
2325 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2327 nsr_deployed
= db_nsr
["_admin"].get("deployed")
2328 vnf_index
= db_nslcmop
["operationParams"].get("member_vnf_index")
2329 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
2330 kdu_name
= db_nslcmop
["operationParams"].get("kdu_name")
2331 vdu_count_index
= db_nslcmop
["operationParams"].get("vdu_count_index")
2332 vdu_name
= db_nslcmop
["operationParams"].get("vdu_name")
2335 step
= "Getting vnfr from database"
2336 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
2337 step
= "Getting vnfd from database"
2338 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
2340 if db_nsr
.get("nsd"):
2341 db_nsd
= db_nsr
.get("nsd") # TODO this will be removed
2343 step
= "Getting nsd from database"
2344 db_nsd
= self
.db
.get_one("nsds", {"_id": db_nsr
["nsd-id"]})
2346 # for backward compatibility
2347 if nsr_deployed
and isinstance(nsr_deployed
.get("VCA"), dict):
2348 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
2349 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
2350 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2352 primitive
= db_nslcmop
["operationParams"]["primitive"]
2353 primitive_params
= db_nslcmop
["operationParams"]["primitive_params"]
2355 # look for primitive
2356 config_primitive_desc
= None
2358 for vdu
in get_iterable(db_vnfd
, "vdu"):
2359 if vdu_id
== vdu
["id"]:
2360 for config_primitive
in vdu
.get("vdu-configuration", {}).get("config-primitive", ()):
2361 if config_primitive
["name"] == primitive
:
2362 config_primitive_desc
= config_primitive
2365 self
.logger
.debug(logging_text
+ "Checking actions in KDUs")
2366 kdur
= next((x
for x
in db_vnfr
["kdur"] if x
["kdu_name"] == kdu_name
), None)
2367 desc_params
= self
._format
_additional
_params
(kdur
.get("additionalParams")) or {}
2368 if primitive_params
:
2369 desc_params
.update(primitive_params
)
2370 # TODO Check if we will need something at vnf level
2372 for kdu
in get_iterable(nsr_deployed
, "K8s"):
2373 if kdu_name
== kdu
["kdu-name"]:
2374 db_dict
= {"collection": "nsrs", "filter": {"_id": nsr_id
},
2375 "path": "_admin.deployed.K8s.{}".format(index
)}
2376 if primitive
== "upgrade":
2377 if desc_params
.get("kdu_model"):
2378 kdu_model
= desc_params
.get("kdu_model")
2379 del desc_params
["kdu_model"]
2381 kdu_model
= kdu
.get("kdu-model")
2382 parts
= kdu_model
.split(sep
=":")
2384 kdu_model
= parts
[0]
2386 if kdu
.get("k8scluster-type") == "chart":
2387 output
= await self
.k8sclusterhelm
.upgrade(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2388 kdu_instance
=kdu
.get("kdu-instance"),
2389 atomic
=True, kdu_model
=kdu_model
,
2390 params
=desc_params
, db_dict
=db_dict
,
2392 elif kdu
.get("k8scluster-type") == "juju":
2393 output
= await self
.k8sclusterjuju
.upgrade(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2394 kdu_instance
=kdu
.get("kdu-instance"),
2395 atomic
=True, kdu_model
=kdu_model
,
2396 params
=desc_params
, db_dict
=db_dict
,
2400 msg
= "k8scluster-type not defined"
2401 raise LcmException(msg
)
2403 self
.logger
.debug(logging_text
+ " Upgrade of kdu {} done".format(output
))
2405 elif primitive
== "rollback":
2406 if kdu
.get("k8scluster-type") == "chart":
2407 output
= await self
.k8sclusterhelm
.rollback(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2408 kdu_instance
=kdu
.get("kdu-instance"),
2410 elif kdu
.get("k8scluster-type") == "juju":
2411 output
= await self
.k8sclusterjuju
.rollback(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2412 kdu_instance
=kdu
.get("kdu-instance"),
2415 msg
= "k8scluster-type not defined"
2416 raise LcmException(msg
)
2418 elif primitive
== "status":
2419 if kdu
.get("k8scluster-type") == "chart":
2420 output
= await self
.k8sclusterhelm
.status_kdu(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2421 kdu_instance
=kdu
.get("kdu-instance"))
2422 elif kdu
.get("k8scluster-type") == "juju":
2423 output
= await self
.k8sclusterjuju
.status_kdu(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2424 kdu_instance
=kdu
.get("kdu-instance"))
2426 msg
= "k8scluster-type not defined"
2427 raise LcmException(msg
)
2432 raise LcmException("KDU '{}' not found".format(kdu_name
))
2434 db_nslcmop_update
["detailed-status"] = output
2435 db_nslcmop_update
["operationState"] = 'COMPLETED'
2436 db_nslcmop_update
["statusEnteredTime"] = time()
2438 db_nslcmop_update
["detailed-status"] = ''
2439 db_nslcmop_update
["operationState"] = 'FAILED'
2440 db_nslcmop_update
["statusEnteredTime"] = time()
2443 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
2444 if config_primitive
["name"] == primitive
:
2445 config_primitive_desc
= config_primitive
2448 for config_primitive
in db_nsd
.get("ns-configuration", {}).get("config-primitive", ()):
2449 if config_primitive
["name"] == primitive
:
2450 config_primitive_desc
= config_primitive
2453 if not config_primitive_desc
:
2454 raise LcmException("Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".
2459 if db_vnfr
.get("additionalParamsForVnf"):
2460 desc_params
= self
._format
_additional
_params
(db_vnfr
["additionalParamsForVnf"])
2462 vdur
= next((x
for x
in db_vnfr
["vdur"] if x
["vdu-id-ref"] == vdu_id
), None)
2463 if vdur
.get("additionalParams"):
2464 desc_params
= self
._format
_additional
_params
(vdur
["additionalParams"])
2466 if db_nsr
.get("additionalParamsForNs"):
2467 desc_params
.update(self
._format
_additional
_params
(db_nsr
["additionalParamsForNs"]))
2469 # TODO check if ns is in a proper status
2470 output
, detail
= await self
._ns
_execute
_primitive
(
2471 db_deployed
=nsr_deployed
,
2472 member_vnf_index
=vnf_index
,
2475 vdu_count_index
=vdu_count_index
,
2476 primitive
=primitive
,
2477 primitive_params
=self
._map
_primitive
_params
(config_primitive_desc
, primitive_params
, desc_params
))
2479 detailed_status
= output
2481 result
= 'COMPLETED'
2485 db_nslcmop_update
["detailed-status"] = nslcmop_operation_state_detail
= detailed_status
2486 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= result
2487 db_nslcmop_update
["statusEnteredTime"] = time()
2488 self
.logger
.debug(logging_text
+ " task Done with result {} {}".format(result
, detailed_status
))
2489 return # database update is called inside finally
2491 except (DbException
, LcmException
) as e
:
2492 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
2494 except asyncio
.CancelledError
:
2495 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
2496 exc
= "Operation was cancelled"
2497 except Exception as e
:
2498 exc
= traceback
.format_exc()
2499 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
2501 if exc
and db_nslcmop
:
2502 db_nslcmop_update
["detailed-status"] = nslcmop_operation_state_detail
= \
2503 "FAILED {}: {}".format(step
, exc
)
2504 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2505 db_nslcmop_update
["statusEnteredTime"] = time()
2507 if db_nslcmop_update
:
2508 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2510 db_nsr_update
["_admin.nslcmop"] = None
2511 db_nsr_update
["_admin.operation-type"] = None
2512 db_nsr_update
["_admin.nslcmop"] = None
2513 db_nsr_update
["_admin.current-operation"] = None
2514 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2515 except DbException
as e
:
2516 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
2517 self
.logger
.debug(logging_text
+ "Exit")
2518 if nslcmop_operation_state
:
2520 await self
.msg
.aiowrite("ns", "actioned", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2521 "operationState": nslcmop_operation_state
},
2523 except Exception as e
:
2524 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
2525 self
.logger
.debug(logging_text
+ "Exit")
2526 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_action")
2527 return nslcmop_operation_state
, nslcmop_operation_state_detail
2529 async def scale(self
, nsr_id
, nslcmop_id
):
2531 # Try to lock HA task here
2532 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
2533 if not task_is_locked_by_me
:
2536 logging_text
= "Task ns={} scale={} ".format(nsr_id
, nslcmop_id
)
2537 self
.logger
.debug(logging_text
+ "Enter")
2538 # get all needed from database
2541 db_nslcmop_update
= {}
2542 nslcmop_operation_state
= None
2543 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
2544 "_admin.current-operation": nslcmop_id
,
2545 "_admin.operation-type": "scale"}
2546 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2548 # in case of error, indicates what part of scale was failed to put nsr at error status
2549 scale_process
= None
2550 old_operational_status
= ""
2551 old_config_status
= ""
2554 # wait for any previous tasks in process
2555 step
= "Waiting for previous operations to terminate"
2556 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
2558 step
= "Getting nslcmop from database"
2559 self
.logger
.debug(step
+ " after having waited for previous tasks to be completed")
2560 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
2561 step
= "Getting nsr from database"
2562 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2564 old_operational_status
= db_nsr
["operational-status"]
2565 old_config_status
= db_nsr
["config-status"]
2566 step
= "Parsing scaling parameters"
2567 # self.logger.debug(step)
2568 db_nsr_update
["operational-status"] = "scaling"
2569 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2570 nsr_deployed
= db_nsr
["_admin"].get("deployed")
2573 nsr_deployed
= db_nsr
["_admin"].get("deployed")
2574 vnf_index
= db_nslcmop
["operationParams"].get("member_vnf_index")
2575 # vdu_id = db_nslcmop["operationParams"].get("vdu_id")
2576 # vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
2577 # vdu_name = db_nslcmop["operationParams"].get("vdu_name")
2580 RO_nsr_id
= nsr_deployed
["RO"]["nsr_id"]
2581 vnf_index
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
2582 scaling_group
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
2583 scaling_type
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleVnfType"]
2584 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
2586 # for backward compatibility
2587 if nsr_deployed
and isinstance(nsr_deployed
.get("VCA"), dict):
2588 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
2589 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
2590 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2592 step
= "Getting vnfr from database"
2593 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
2594 step
= "Getting vnfd from database"
2595 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
2597 step
= "Getting scaling-group-descriptor"
2598 for scaling_descriptor
in db_vnfd
["scaling-group-descriptor"]:
2599 if scaling_descriptor
["name"] == scaling_group
:
2602 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
2603 "at vnfd:scaling-group-descriptor".format(scaling_group
))
2606 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
2607 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
2608 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
2611 # TODO check if ns is in a proper status
2612 step
= "Sending scale order to VIM"
2614 if not db_nsr
["_admin"].get("scaling-group"):
2615 self
.update_db_2("nsrs", nsr_id
, {"_admin.scaling-group": [{"name": scaling_group
, "nb-scale-op": 0}]})
2616 admin_scale_index
= 0
2618 for admin_scale_index
, admin_scale_info
in enumerate(db_nsr
["_admin"]["scaling-group"]):
2619 if admin_scale_info
["name"] == scaling_group
:
2620 nb_scale_op
= admin_scale_info
.get("nb-scale-op", 0)
2622 else: # not found, set index one plus last element and add new entry with the name
2623 admin_scale_index
+= 1
2624 db_nsr_update
["_admin.scaling-group.{}.name".format(admin_scale_index
)] = scaling_group
2625 RO_scaling_info
= []
2626 vdu_scaling_info
= {"scaling_group_name": scaling_group
, "vdu": []}
2627 if scaling_type
== "SCALE_OUT":
2628 # count if max-instance-count is reached
2629 max_instance_count
= scaling_descriptor
.get("max-instance-count", 10)
2630 # self.logger.debug("MAX_INSTANCE_COUNT is {}".format(max_instance_count))
2631 if nb_scale_op
>= max_instance_count
:
2632 raise LcmException("reached the limit of {} (max-instance-count) "
2633 "scaling-out operations for the "
2634 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
2637 vdu_scaling_info
["scaling_direction"] = "OUT"
2638 vdu_scaling_info
["vdu-create"] = {}
2639 for vdu_scale_info
in scaling_descriptor
["vdu"]:
2640 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
2641 "type": "create", "count": vdu_scale_info
.get("count", 1)})
2642 vdu_scaling_info
["vdu-create"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
2644 elif scaling_type
== "SCALE_IN":
2645 # count if min-instance-count is reached
2646 min_instance_count
= 0
2647 if "min-instance-count" in scaling_descriptor
and scaling_descriptor
["min-instance-count"] is not None:
2648 min_instance_count
= int(scaling_descriptor
["min-instance-count"])
2649 if nb_scale_op
<= min_instance_count
:
2650 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
2651 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
2653 vdu_scaling_info
["scaling_direction"] = "IN"
2654 vdu_scaling_info
["vdu-delete"] = {}
2655 for vdu_scale_info
in scaling_descriptor
["vdu"]:
2656 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
2657 "type": "delete", "count": vdu_scale_info
.get("count", 1)})
2658 vdu_scaling_info
["vdu-delete"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
2660 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
2661 vdu_create
= vdu_scaling_info
.get("vdu-create")
2662 vdu_delete
= copy(vdu_scaling_info
.get("vdu-delete"))
2663 if vdu_scaling_info
["scaling_direction"] == "IN":
2664 for vdur
in reversed(db_vnfr
["vdur"]):
2665 if vdu_delete
.get(vdur
["vdu-id-ref"]):
2666 vdu_delete
[vdur
["vdu-id-ref"]] -= 1
2667 vdu_scaling_info
["vdu"].append({
2668 "name": vdur
["name"],
2669 "vdu_id": vdur
["vdu-id-ref"],
2672 for interface
in vdur
["interfaces"]:
2673 vdu_scaling_info
["vdu"][-1]["interface"].append({
2674 "name": interface
["name"],
2675 "ip_address": interface
["ip-address"],
2676 "mac_address": interface
.get("mac-address"),
2678 vdu_delete
= vdu_scaling_info
.pop("vdu-delete")
2681 step
= "Executing pre-scale vnf-config-primitive"
2682 if scaling_descriptor
.get("scaling-config-action"):
2683 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
2684 if (scaling_config_action
.get("trigger") == "pre-scale-in" and scaling_type
== "SCALE_IN") \
2685 or (scaling_config_action
.get("trigger") == "pre-scale-out" and scaling_type
== "SCALE_OUT"):
2686 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
2687 step
= db_nslcmop_update
["detailed-status"] = \
2688 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive
)
2690 # look for primitive
2691 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
2692 if config_primitive
["name"] == vnf_config_primitive
:
2696 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
2697 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
2698 "primitive".format(scaling_group
, config_primitive
))
2700 vnfr_params
= {"VDU_SCALE_INFO": vdu_scaling_info
}
2701 if db_vnfr
.get("additionalParamsForVnf"):
2702 vnfr_params
.update(db_vnfr
["additionalParamsForVnf"])
2704 scale_process
= "VCA"
2705 db_nsr_update
["config-status"] = "configuring pre-scaling"
2706 primitive_params
= self
._map
_primitive
_params
(config_primitive
, {}, vnfr_params
)
2708 # Pre-scale reintent check: Check if this sub-operation has been executed before
2709 op_index
= self
._check
_or
_add
_scale
_suboperation
(
2710 db_nslcmop
, nslcmop_id
, vnf_index
, vnf_config_primitive
, primitive_params
, 'PRE-SCALE')
2711 if (op_index
== self
.SUBOPERATION_STATUS_SKIP
):
2712 # Skip sub-operation
2713 result
= 'COMPLETED'
2714 result_detail
= 'Done'
2715 self
.logger
.debug(logging_text
+
2716 "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
2717 vnf_config_primitive
, result
, result_detail
))
2719 if (op_index
== self
.SUBOPERATION_STATUS_NEW
):
2720 # New sub-operation: Get index of this sub-operation
2721 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
2722 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} New sub-operation".
2723 format(vnf_config_primitive
))
2725 # Reintent: Get registered params for this existing sub-operation
2726 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
2727 vnf_index
= op
.get('member_vnf_index')
2728 vnf_config_primitive
= op
.get('primitive')
2729 primitive_params
= op
.get('primitive_params')
2730 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Sub-operation reintent".
2731 format(vnf_config_primitive
))
2732 # Execute the primitive, either with new (first-time) or registered (reintent) args
2733 result
, result_detail
= await self
._ns
_execute
_primitive
(
2734 nsr_deployed
, vnf_index
, None, None, None, vnf_config_primitive
, primitive_params
)
2735 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
2736 vnf_config_primitive
, result
, result_detail
))
2737 # Update operationState = COMPLETED | FAILED
2738 self
._update
_suboperation
_status
(
2739 db_nslcmop
, op_index
, result
, result_detail
)
2741 if result
== "FAILED":
2742 raise LcmException(result_detail
)
2743 db_nsr_update
["config-status"] = old_config_status
2744 scale_process
= None
2748 # Should this block be skipped if 'RO_nsr_id' == None ?
2749 # if (RO_nsr_id and RO_scaling_info):
2751 scale_process
= "RO"
2752 # Scale RO reintent check: Check if this sub-operation has been executed before
2753 op_index
= self
._check
_or
_add
_scale
_suboperation
(
2754 db_nslcmop
, vnf_index
, None, None, 'SCALE-RO', RO_nsr_id
, RO_scaling_info
)
2755 if (op_index
== self
.SUBOPERATION_STATUS_SKIP
):
2756 # Skip sub-operation
2757 result
= 'COMPLETED'
2758 result_detail
= 'Done'
2759 self
.logger
.debug(logging_text
+ "Skipped sub-operation RO, result {} {}".format(
2760 result
, result_detail
))
2762 if (op_index
== self
.SUBOPERATION_STATUS_NEW
):
2763 # New sub-operation: Get index of this sub-operation
2764 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
2765 self
.logger
.debug(logging_text
+ "New sub-operation RO")
2767 # Reintent: Get registered params for this existing sub-operation
2768 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
2769 RO_nsr_id
= op
.get('RO_nsr_id')
2770 RO_scaling_info
= op
.get('RO_scaling_info')
2771 self
.logger
.debug(logging_text
+ "Sub-operation RO reintent".format(
2772 vnf_config_primitive
))
2774 RO_desc
= await self
.RO
.create_action("ns", RO_nsr_id
, {"vdu-scaling": RO_scaling_info
})
2775 db_nsr_update
["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index
)] = nb_scale_op
2776 db_nsr_update
["_admin.scaling-group.{}.time".format(admin_scale_index
)] = time()
2778 RO_nslcmop_id
= RO_desc
["instance_action_id"]
2779 db_nslcmop_update
["_admin.deploy.RO"] = RO_nslcmop_id
2781 RO_task_done
= False
2782 step
= detailed_status
= "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id
)
2783 detailed_status_old
= None
2784 self
.logger
.debug(logging_text
+ step
)
2786 deployment_timeout
= 1 * 3600 # One hour
2787 while deployment_timeout
> 0:
2788 if not RO_task_done
:
2789 desc
= await self
.RO
.show("ns", item_id_name
=RO_nsr_id
, extra_item
="action",
2790 extra_item_id
=RO_nslcmop_id
)
2791 ns_status
, ns_status_info
= self
.RO
.check_action_status(desc
)
2792 if ns_status
== "ERROR":
2793 raise ROclient
.ROClientException(ns_status_info
)
2794 elif ns_status
== "BUILD":
2795 detailed_status
= step
+ "; {}".format(ns_status_info
)
2796 elif ns_status
== "ACTIVE":
2798 step
= detailed_status
= "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id
)
2799 self
.logger
.debug(logging_text
+ step
)
2801 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
2804 if ns_status
== "ERROR":
2805 raise ROclient
.ROClientException(ns_status_info
)
2806 elif ns_status
== "BUILD":
2807 detailed_status
= step
+ "; {}".format(ns_status_info
)
2808 elif ns_status
== "ACTIVE":
2809 step
= detailed_status
= \
2810 "Waiting for management IP address reported by the VIM. Updating VNFRs"
2812 self
.scale_vnfr(db_vnfr
, vdu_create
=vdu_create
, vdu_delete
=vdu_delete
)
2815 desc
= await self
.RO
.show("ns", RO_nsr_id
)
2816 # nsr_deployed["nsr_ip"] = RO.get_ns_vnf_info(desc)
2817 self
.ns_update_vnfr({db_vnfr
["member-vnf-index-ref"]: db_vnfr
}, desc
)
2819 except LcmExceptionNoMgmtIP
:
2822 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
2823 if detailed_status
!= detailed_status_old
:
2824 self
._update
_suboperation
_status
(
2825 db_nslcmop
, op_index
, 'COMPLETED', detailed_status
)
2826 detailed_status_old
= db_nslcmop_update
["detailed-status"] = detailed_status
2827 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2829 await asyncio
.sleep(5, loop
=self
.loop
)
2830 deployment_timeout
-= 5
2831 if deployment_timeout
<= 0:
2832 self
._update
_suboperation
_status
(
2833 db_nslcmop
, nslcmop_id
, op_index
, 'FAILED', "Timeout when waiting for ns to get ready")
2834 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
2836 # update VDU_SCALING_INFO with the obtained ip_addresses
2837 if vdu_scaling_info
["scaling_direction"] == "OUT":
2838 for vdur
in reversed(db_vnfr
["vdur"]):
2839 if vdu_scaling_info
["vdu-create"].get(vdur
["vdu-id-ref"]):
2840 vdu_scaling_info
["vdu-create"][vdur
["vdu-id-ref"]] -= 1
2841 vdu_scaling_info
["vdu"].append({
2842 "name": vdur
["name"],
2843 "vdu_id": vdur
["vdu-id-ref"],
2846 for interface
in vdur
["interfaces"]:
2847 vdu_scaling_info
["vdu"][-1]["interface"].append({
2848 "name": interface
["name"],
2849 "ip_address": interface
["ip-address"],
2850 "mac_address": interface
.get("mac-address"),
2852 del vdu_scaling_info
["vdu-create"]
2854 self
._update
_suboperation
_status
(db_nslcmop
, op_index
, 'COMPLETED', 'Done')
2857 scale_process
= None
2859 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2862 # execute primitive service POST-SCALING
2863 step
= "Executing post-scale vnf-config-primitive"
2864 if scaling_descriptor
.get("scaling-config-action"):
2865 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
2866 if (scaling_config_action
.get("trigger") == "post-scale-in" and scaling_type
== "SCALE_IN") \
2867 or (scaling_config_action
.get("trigger") == "post-scale-out" and scaling_type
== "SCALE_OUT"):
2868 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
2869 step
= db_nslcmop_update
["detailed-status"] = \
2870 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive
)
2872 vnfr_params
= {"VDU_SCALE_INFO": vdu_scaling_info
}
2873 if db_vnfr
.get("additionalParamsForVnf"):
2874 vnfr_params
.update(db_vnfr
["additionalParamsForVnf"])
2876 # look for primitive
2877 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
2878 if config_primitive
["name"] == vnf_config_primitive
:
2881 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
2882 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
2883 "match any vnf-configuration:config-primitive".format(scaling_group
,
2885 scale_process
= "VCA"
2886 db_nsr_update
["config-status"] = "configuring post-scaling"
2887 primitive_params
= self
._map
_primitive
_params
(config_primitive
, {}, vnfr_params
)
2889 # Post-scale reintent check: Check if this sub-operation has been executed before
2890 op_index
= self
._check
_or
_add
_scale
_suboperation
(
2891 db_nslcmop
, nslcmop_id
, vnf_index
, vnf_config_primitive
, primitive_params
, 'POST-SCALE')
2892 if (op_index
== self
.SUBOPERATION_STATUS_SKIP
):
2893 # Skip sub-operation
2894 result
= 'COMPLETED'
2895 result_detail
= 'Done'
2896 self
.logger
.debug(logging_text
+
2897 "vnf_config_primitive={} Skipped sub-operation, result {} {}".
2898 format(vnf_config_primitive
, result
, result_detail
))
2900 if (op_index
== self
.SUBOPERATION_STATUS_NEW
):
2901 # New sub-operation: Get index of this sub-operation
2902 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
2903 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} New sub-operation".
2904 format(vnf_config_primitive
))
2906 # Reintent: Get registered params for this existing sub-operation
2907 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
2908 vnf_index
= op
.get('member_vnf_index')
2909 vnf_config_primitive
= op
.get('primitive')
2910 primitive_params
= op
.get('primitive_params')
2911 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Sub-operation reintent".
2912 format(vnf_config_primitive
))
2913 # Execute the primitive, either with new (first-time) or registered (reintent) args
2914 result
, result_detail
= await self
._ns
_execute
_primitive
(
2915 nsr_deployed
, vnf_index
, None, None, None, vnf_config_primitive
, primitive_params
)
2916 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
2917 vnf_config_primitive
, result
, result_detail
))
2918 # Update operationState = COMPLETED | FAILED
2919 self
._update
_suboperation
_status
(
2920 db_nslcmop
, op_index
, result
, result_detail
)
2922 if result
== "FAILED":
2923 raise LcmException(result_detail
)
2924 db_nsr_update
["config-status"] = old_config_status
2925 scale_process
= None
2928 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
2929 db_nslcmop_update
["statusEnteredTime"] = time()
2930 db_nslcmop_update
["detailed-status"] = "done"
2931 db_nsr_update
["detailed-status"] = "" # "scaled {} {}".format(scaling_group, scaling_type)
2932 db_nsr_update
["operational-status"] = "running" if old_operational_status
== "failed" \
2933 else old_operational_status
2934 db_nsr_update
["config-status"] = old_config_status
2936 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
2937 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
2939 except asyncio
.CancelledError
:
2940 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
2941 exc
= "Operation was cancelled"
2942 except Exception as e
:
2943 exc
= traceback
.format_exc()
2944 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
2948 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
2949 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2950 db_nslcmop_update
["statusEnteredTime"] = time()
2952 db_nsr_update
["operational-status"] = old_operational_status
2953 db_nsr_update
["config-status"] = old_config_status
2954 db_nsr_update
["detailed-status"] = ""
2955 db_nsr_update
["_admin.nslcmop"] = None
2957 if "VCA" in scale_process
:
2958 db_nsr_update
["config-status"] = "failed"
2959 if "RO" in scale_process
:
2960 db_nsr_update
["operational-status"] = "failed"
2961 db_nsr_update
["detailed-status"] = "FAILED scaling nslcmop={} {}: {}".format(nslcmop_id
, step
,
2964 if db_nslcmop
and db_nslcmop_update
:
2965 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2967 db_nsr_update
["_admin.current-operation"] = None
2968 db_nsr_update
["_admin.operation-type"] = None
2969 db_nsr_update
["_admin.nslcmop"] = None
2970 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2971 except DbException
as e
:
2972 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
2973 if nslcmop_operation_state
:
2975 await self
.msg
.aiowrite("ns", "scaled", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2976 "operationState": nslcmop_operation_state
},
2979 # await asyncio.sleep(cooldown_time, loop=self.loop)
2980 # await self.msg.aiowrite("ns","scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
2981 except Exception as e
:
2982 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
2983 self
.logger
.debug(logging_text
+ "Exit")
2984 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_scale")