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
28 from n2vc
.k8s_helm_conn
import K8sHelmConnector
30 from osm_common
.dbbase
import DbException
31 from osm_common
.fsbase
import FsException
33 from n2vc
.n2vc_juju_conn
import N2VCJujuConnector
35 from copy
import copy
, deepcopy
36 from http
import HTTPStatus
38 from uuid
import uuid4
40 __author__
= "Alfonso Tierno"
43 def get_iterable(in_dict
, in_key
):
45 Similar to <dict>.get(), but if value is None, False, ..., An empty tuple is returned instead
46 :param in_dict: a dictionary
47 :param in_key: the key to look for at in_dict
48 :return: in_dict[in_var] or () if it is None or not present
50 if not in_dict
.get(in_key
):
52 return in_dict
[in_key
]
55 def populate_dict(target_dict
, key_list
, value
):
57 Update target_dict creating nested dictionaries with the key_list. Last key_list item is asigned the value.
58 Example target_dict={K: J}; key_list=[a,b,c]; target_dict will be {K: J, a: {b: {c: value}}}
59 :param target_dict: dictionary to be changed
60 :param key_list: list of keys to insert at target_dict
64 for key
in key_list
[0:-1]:
65 if key
not in target_dict
:
67 target_dict
= target_dict
[key
]
68 target_dict
[key_list
[-1]] = value
71 def deep_get(target_dict
, key_list
):
73 Get a value from target_dict entering in the nested keys. If keys does not exist, it returns None
74 Example target_dict={a: {b: 5}}; key_list=[a,b] returns 5; both key_list=[a,b,c] and key_list=[f,h] return None
75 :param target_dict: dictionary to be read
76 :param key_list: list of keys to read from target_dict
77 :return: The wanted value if exist, None otherwise
80 if not isinstance(target_dict
, dict) or key
not in target_dict
:
82 target_dict
= target_dict
[key
]
87 timeout_vca_on_error
= 5 * 60 # Time for charm from first time at blocked,error status to mark as failed
88 total_deploy_timeout
= 2 * 3600 # global timeout for deployment
89 timeout_charm_delete
= 10 * 60
90 timeout_primitive
= 10 * 60 # timeout for primitive execution
92 SUBOPERATION_STATUS_NOT_FOUND
= -1
93 SUBOPERATION_STATUS_NEW
= -2
94 SUBOPERATION_STATUS_SKIP
= -3
96 def __init__(self
, db
, msg
, fs
, lcm_tasks
, ro_config
, vca_config
, loop
):
98 Init, Connect to database, filesystem storage, and messaging
99 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
106 logger
=logging
.getLogger('lcm.ns')
110 self
.lcm_tasks
= lcm_tasks
111 self
.ro_config
= ro_config
112 self
.vca_config
= vca_config
113 if 'pubkey' in self
.vca_config
:
114 self
.vca_config
['public_key'] = self
.vca_config
['pubkey']
115 if 'cacert' in self
.vca_config
:
116 self
.vca_config
['ca_cert'] = self
.vca_config
['cacert']
118 # create N2VC connector
119 self
.n2vc
= N2VCJujuConnector(
124 url
='{}:{}'.format(self
.vca_config
['host'], self
.vca_config
['port']),
125 username
=self
.vca_config
.get('user', None),
126 vca_config
=self
.vca_config
,
127 on_update_db
=self
._on
_update
_n
2vc
_db
130 # api_proxy=vca_config.get('apiproxy')
133 self
.k8sclusterhelm
= K8sHelmConnector(
134 kubectl_command
=self
.vca_config
.get("kubectlpath"),
135 helm_command
=self
.vca_config
.get("helmpath"),
143 self
.RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
145 def _on_update_n2vc_db(self
, table
, filter, path
, updated_data
):
147 self
.logger
.debug('_on_update_n2vc_db(table={}, filter={}, path={}, updated_data={}'
148 .format(table
, filter, path
, updated_data
))
151 # write NS status to database
153 # # nsrs_id = filter.get('_id')
156 # nsr = self.db.get_one(table=table, q_filter=filter)
157 # # get VCA deployed list
158 # vca_list = deep_get(target_dict=nsr, key_list=('_admin', 'deployed', 'VCA'))
160 # # ro_list = deep_get(target_dict=nsr, key_list=('_admin', 'deployed', 'RO'))
161 # for vca in vca_list:
162 # # status = vca.get('status')
164 # # detailed_status = vca.get('detailed-status')
165 # # print(detailed_status)
166 # # for ro in ro_list:
169 # except Exception as e:
170 # self.logger.error('Error writing NS status to db: {}'.format(e))
172 def vnfd2RO(self
, vnfd
, new_id
=None, additionalParams
=None, nsrId
=None):
174 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
175 :param vnfd: input vnfd
176 :param new_id: overrides vnf id if provided
177 :param additionalParams: Instantiation params for VNFs provided
178 :param nsrId: Id of the NSR
179 :return: copy of vnfd
182 vnfd_RO
= deepcopy(vnfd
)
183 # remove unused by RO configuration, monitoring, scaling and internal keys
184 vnfd_RO
.pop("_id", None)
185 vnfd_RO
.pop("_admin", None)
186 vnfd_RO
.pop("vnf-configuration", None)
187 vnfd_RO
.pop("monitoring-param", None)
188 vnfd_RO
.pop("scaling-group-descriptor", None)
189 vnfd_RO
.pop("kdu", None)
190 vnfd_RO
.pop("k8s-cluster", None)
192 vnfd_RO
["id"] = new_id
194 # parse cloud-init or cloud-init-file with the provided variables using Jinja2
195 for vdu
in get_iterable(vnfd_RO
, "vdu"):
196 cloud_init_file
= None
197 if vdu
.get("cloud-init-file"):
198 base_folder
= vnfd
["_admin"]["storage"]
199 cloud_init_file
= "{}/{}/cloud_init/{}".format(base_folder
["folder"], base_folder
["pkg-dir"],
200 vdu
["cloud-init-file"])
201 with self
.fs
.file_open(cloud_init_file
, "r") as ci_file
:
202 cloud_init_content
= ci_file
.read()
203 vdu
.pop("cloud-init-file", None)
204 elif vdu
.get("cloud-init"):
205 cloud_init_content
= vdu
["cloud-init"]
210 ast
= env
.parse(cloud_init_content
)
211 mandatory_vars
= meta
.find_undeclared_variables(ast
)
213 for var
in mandatory_vars
:
214 if not additionalParams
or var
not in additionalParams
.keys():
215 raise LcmException("Variable '{}' defined at vnfd[id={}]:vdu[id={}]:cloud-init/cloud-init-"
216 "file, must be provided in the instantiation parameters inside the "
217 "'additionalParamsForVnf' block".format(var
, vnfd
["id"], vdu
["id"]))
218 template
= Template(cloud_init_content
)
219 cloud_init_content
= template
.render(additionalParams
or {})
220 vdu
["cloud-init"] = cloud_init_content
223 except FsException
as e
:
224 raise LcmException("Error reading vnfd[id={}]:vdu[id={}]:cloud-init-file={}: {}".
225 format(vnfd
["id"], vdu
["id"], cloud_init_file
, e
))
226 except (TemplateError
, TemplateNotFound
, TemplateSyntaxError
) as e
:
227 raise LcmException("Error parsing Jinja2 to cloud-init content at vnfd[id={}]:vdu[id={}]: {}".
228 format(vnfd
["id"], vdu
["id"], e
))
230 def ns_params_2_RO(self
, ns_params
, nsd
, vnfd_dict
, n2vc_key_list
):
232 Creates a RO ns descriptor from OSM ns_instantiate params
233 :param ns_params: OSM instantiate params
234 :return: The RO ns descriptor
238 # TODO feature 1417: Check that no instantiation is set over PDU
239 # check if PDU forces a concrete vim-network-id and add it
240 # check if PDU contains a SDN-assist info (dpid, switch, port) and pass it to RO
242 def vim_account_2_RO(vim_account
):
243 if vim_account
in vim_2_RO
:
244 return vim_2_RO
[vim_account
]
246 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_account
})
247 if db_vim
["_admin"]["operationalState"] != "ENABLED":
248 raise LcmException("VIM={} is not available. operationalState={}".format(
249 vim_account
, db_vim
["_admin"]["operationalState"]))
250 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
251 vim_2_RO
[vim_account
] = RO_vim_id
254 def wim_account_2_RO(wim_account
):
255 if isinstance(wim_account
, str):
256 if wim_account
in wim_2_RO
:
257 return wim_2_RO
[wim_account
]
259 db_wim
= self
.db
.get_one("wim_accounts", {"_id": wim_account
})
260 if db_wim
["_admin"]["operationalState"] != "ENABLED":
261 raise LcmException("WIM={} is not available. operationalState={}".format(
262 wim_account
, db_wim
["_admin"]["operationalState"]))
263 RO_wim_id
= db_wim
["_admin"]["deployed"]["RO-account"]
264 wim_2_RO
[wim_account
] = RO_wim_id
269 def ip_profile_2_RO(ip_profile
):
270 RO_ip_profile
= deepcopy((ip_profile
))
271 if "dns-server" in RO_ip_profile
:
272 if isinstance(RO_ip_profile
["dns-server"], list):
273 RO_ip_profile
["dns-address"] = []
274 for ds
in RO_ip_profile
.pop("dns-server"):
275 RO_ip_profile
["dns-address"].append(ds
['address'])
277 RO_ip_profile
["dns-address"] = RO_ip_profile
.pop("dns-server")
278 if RO_ip_profile
.get("ip-version") == "ipv4":
279 RO_ip_profile
["ip-version"] = "IPv4"
280 if RO_ip_profile
.get("ip-version") == "ipv6":
281 RO_ip_profile
["ip-version"] = "IPv6"
282 if "dhcp-params" in RO_ip_profile
:
283 RO_ip_profile
["dhcp"] = RO_ip_profile
.pop("dhcp-params")
289 # "name": ns_params["nsName"],
290 # "description": ns_params.get("nsDescription"),
291 "datacenter": vim_account_2_RO(ns_params
["vimAccountId"]),
292 "wim_account": wim_account_2_RO(ns_params
.get("wimAccountId")),
293 # "scenario": ns_params["nsdId"],
296 n2vc_key_list
= n2vc_key_list
or []
297 for vnfd_ref
, vnfd
in vnfd_dict
.items():
298 vdu_needed_access
= []
300 if vnfd
.get("vnf-configuration"):
301 ssh_required
= deep_get(vnfd
, ("vnf-configuration", "config-access", "ssh-access", "required"))
302 if ssh_required
and vnfd
.get("mgmt-interface"):
303 if vnfd
["mgmt-interface"].get("vdu-id"):
304 vdu_needed_access
.append(vnfd
["mgmt-interface"]["vdu-id"])
305 elif vnfd
["mgmt-interface"].get("cp"):
306 mgmt_cp
= vnfd
["mgmt-interface"]["cp"]
308 for vdu
in vnfd
.get("vdu", ()):
309 if vdu
.get("vdu-configuration"):
310 ssh_required
= deep_get(vdu
, ("vdu-configuration", "config-access", "ssh-access", "required"))
312 vdu_needed_access
.append(vdu
["id"])
314 for vdu_interface
in vdu
.get("interface"):
315 if vdu_interface
.get("external-connection-point-ref") and \
316 vdu_interface
["external-connection-point-ref"] == mgmt_cp
:
317 vdu_needed_access
.append(vdu
["id"])
321 if vdu_needed_access
:
322 for vnf_member
in nsd
.get("constituent-vnfd"):
323 if vnf_member
["vnfd-id-ref"] != vnfd_ref
:
325 for vdu
in vdu_needed_access
:
326 populate_dict(RO_ns_params
,
327 ("vnfs", vnf_member
["member-vnf-index"], "vdus", vdu
, "mgmt_keys"),
330 if ns_params
.get("vduImage"):
331 RO_ns_params
["vduImage"] = ns_params
["vduImage"]
333 if ns_params
.get("ssh_keys"):
334 RO_ns_params
["cloud-config"] = {"key-pairs": ns_params
["ssh_keys"]}
335 for vnf_params
in get_iterable(ns_params
, "vnf"):
336 for constituent_vnfd
in nsd
["constituent-vnfd"]:
337 if constituent_vnfd
["member-vnf-index"] == vnf_params
["member-vnf-index"]:
338 vnf_descriptor
= vnfd_dict
[constituent_vnfd
["vnfd-id-ref"]]
341 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index={} is not present at nsd:"
342 "constituent-vnfd".format(vnf_params
["member-vnf-index"]))
343 if vnf_params
.get("vimAccountId"):
344 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "datacenter"),
345 vim_account_2_RO(vnf_params
["vimAccountId"]))
347 for vdu_params
in get_iterable(vnf_params
, "vdu"):
348 # TODO feature 1417: check that this VDU exist and it is not a PDU
349 if vdu_params
.get("volume"):
350 for volume_params
in vdu_params
["volume"]:
351 if volume_params
.get("vim-volume-id"):
352 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
353 vdu_params
["id"], "devices", volume_params
["name"], "vim_id"),
354 volume_params
["vim-volume-id"])
355 if vdu_params
.get("interface"):
356 for interface_params
in vdu_params
["interface"]:
357 if interface_params
.get("ip-address"):
358 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
359 vdu_params
["id"], "interfaces", interface_params
["name"],
361 interface_params
["ip-address"])
362 if interface_params
.get("mac-address"):
363 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
364 vdu_params
["id"], "interfaces", interface_params
["name"],
366 interface_params
["mac-address"])
367 if interface_params
.get("floating-ip-required"):
368 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
369 vdu_params
["id"], "interfaces", interface_params
["name"],
371 interface_params
["floating-ip-required"])
373 for internal_vld_params
in get_iterable(vnf_params
, "internal-vld"):
374 if internal_vld_params
.get("vim-network-name"):
375 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
376 internal_vld_params
["name"], "vim-network-name"),
377 internal_vld_params
["vim-network-name"])
378 if internal_vld_params
.get("vim-network-id"):
379 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
380 internal_vld_params
["name"], "vim-network-id"),
381 internal_vld_params
["vim-network-id"])
382 if internal_vld_params
.get("ip-profile"):
383 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
384 internal_vld_params
["name"], "ip-profile"),
385 ip_profile_2_RO(internal_vld_params
["ip-profile"]))
386 if internal_vld_params
.get("provider-network"):
388 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
389 internal_vld_params
["name"], "provider-network"),
390 internal_vld_params
["provider-network"].copy())
392 for icp_params
in get_iterable(internal_vld_params
, "internal-connection-point"):
395 for vdu_descriptor
in vnf_descriptor
["vdu"]:
396 for vdu_interface
in vdu_descriptor
["interface"]:
397 if vdu_interface
.get("internal-connection-point-ref") == icp_params
["id-ref"]:
398 if icp_params
.get("ip-address"):
399 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
400 vdu_descriptor
["id"], "interfaces",
401 vdu_interface
["name"], "ip_address"),
402 icp_params
["ip-address"])
404 if icp_params
.get("mac-address"):
405 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
406 vdu_descriptor
["id"], "interfaces",
407 vdu_interface
["name"], "mac_address"),
408 icp_params
["mac-address"])
414 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
415 "internal-vld:id-ref={} is not present at vnfd:internal-"
416 "connection-point".format(vnf_params
["member-vnf-index"],
417 icp_params
["id-ref"]))
419 for vld_params
in get_iterable(ns_params
, "vld"):
420 if "ip-profile" in vld_params
:
421 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "ip-profile"),
422 ip_profile_2_RO(vld_params
["ip-profile"]))
424 if vld_params
.get("provider-network"):
426 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "provider-network"),
427 vld_params
["provider-network"].copy())
429 if "wimAccountId" in vld_params
and vld_params
["wimAccountId"] is not None:
430 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "wim_account"),
431 wim_account_2_RO(vld_params
["wimAccountId"])),
432 if vld_params
.get("vim-network-name"):
434 if isinstance(vld_params
["vim-network-name"], dict):
435 for vim_account
, vim_net
in vld_params
["vim-network-name"].items():
436 RO_vld_sites
.append({
437 "netmap-use": vim_net
,
438 "datacenter": vim_account_2_RO(vim_account
)
440 else: # isinstance str
441 RO_vld_sites
.append({"netmap-use": vld_params
["vim-network-name"]})
443 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "sites"), RO_vld_sites
)
445 if vld_params
.get("vim-network-id"):
447 if isinstance(vld_params
["vim-network-id"], dict):
448 for vim_account
, vim_net
in vld_params
["vim-network-id"].items():
449 RO_vld_sites
.append({
450 "netmap-use": vim_net
,
451 "datacenter": vim_account_2_RO(vim_account
)
453 else: # isinstance str
454 RO_vld_sites
.append({"netmap-use": vld_params
["vim-network-id"]})
456 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "sites"), RO_vld_sites
)
457 if vld_params
.get("ns-net"):
458 if isinstance(vld_params
["ns-net"], dict):
459 for vld_id
, instance_scenario_id
in vld_params
["ns-net"].items():
460 RO_vld_ns_net
= {"instance_scenario_id": instance_scenario_id
, "osm_id": vld_id
}
462 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "use-network"), RO_vld_ns_net
)
463 if "vnfd-connection-point-ref" in vld_params
:
464 for cp_params
in vld_params
["vnfd-connection-point-ref"]:
466 for constituent_vnfd
in nsd
["constituent-vnfd"]:
467 if constituent_vnfd
["member-vnf-index"] == cp_params
["member-vnf-index-ref"]:
468 vnf_descriptor
= vnfd_dict
[constituent_vnfd
["vnfd-id-ref"]]
472 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={} "
473 "is not present at nsd:constituent-vnfd".format(cp_params
["member-vnf-index-ref"]))
475 for vdu_descriptor
in vnf_descriptor
["vdu"]:
476 for interface_descriptor
in vdu_descriptor
["interface"]:
477 if interface_descriptor
.get("external-connection-point-ref") == \
478 cp_params
["vnfd-connection-point-ref"]:
485 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={}:"
486 "vnfd-connection-point-ref={} is not present at vnfd={}".format(
487 cp_params
["member-vnf-index-ref"],
488 cp_params
["vnfd-connection-point-ref"],
489 vnf_descriptor
["id"]))
490 if cp_params
.get("ip-address"):
491 populate_dict(RO_ns_params
, ("vnfs", cp_params
["member-vnf-index-ref"], "vdus",
492 vdu_descriptor
["id"], "interfaces",
493 interface_descriptor
["name"], "ip_address"),
494 cp_params
["ip-address"])
495 if cp_params
.get("mac-address"):
496 populate_dict(RO_ns_params
, ("vnfs", cp_params
["member-vnf-index-ref"], "vdus",
497 vdu_descriptor
["id"], "interfaces",
498 interface_descriptor
["name"], "mac_address"),
499 cp_params
["mac-address"])
502 def scale_vnfr(self
, db_vnfr
, vdu_create
=None, vdu_delete
=None):
503 # make a copy to do not change
504 vdu_create
= copy(vdu_create
)
505 vdu_delete
= copy(vdu_delete
)
507 vdurs
= db_vnfr
.get("vdur")
510 vdu_index
= len(vdurs
)
513 vdur
= vdurs
[vdu_index
]
514 if vdur
.get("pdu-type"):
516 vdu_id_ref
= vdur
["vdu-id-ref"]
517 if vdu_create
and vdu_create
.get(vdu_id_ref
):
518 for index
in range(0, vdu_create
[vdu_id_ref
]):
519 vdur
= deepcopy(vdur
)
520 vdur
["_id"] = str(uuid4())
521 vdur
["count-index"] += 1
522 vdurs
.insert(vdu_index
+1+index
, vdur
)
523 del vdu_create
[vdu_id_ref
]
524 if vdu_delete
and vdu_delete
.get(vdu_id_ref
):
526 vdu_delete
[vdu_id_ref
] -= 1
527 if not vdu_delete
[vdu_id_ref
]:
528 del vdu_delete
[vdu_id_ref
]
529 # check all operations are done
530 if vdu_create
or vdu_delete
:
531 raise LcmException("Error scaling OUT VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
534 raise LcmException("Error scaling IN VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
537 vnfr_update
= {"vdur": vdurs
}
538 db_vnfr
["vdur"] = vdurs
539 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
541 def ns_update_nsr(self
, ns_update_nsr
, db_nsr
, nsr_desc_RO
):
543 Updates database nsr with the RO info for the created vld
544 :param ns_update_nsr: dictionary to be filled with the updated info
545 :param db_nsr: content of db_nsr. This is also modified
546 :param nsr_desc_RO: nsr descriptor from RO
547 :return: Nothing, LcmException is raised on errors
550 for vld_index
, vld
in enumerate(get_iterable(db_nsr
, "vld")):
551 for net_RO
in get_iterable(nsr_desc_RO
, "nets"):
552 if vld
["id"] != net_RO
.get("ns_net_osm_id"):
554 vld
["vim-id"] = net_RO
.get("vim_net_id")
555 vld
["name"] = net_RO
.get("vim_name")
556 vld
["status"] = net_RO
.get("status")
557 vld
["status-detailed"] = net_RO
.get("error_msg")
558 ns_update_nsr
["vld.{}".format(vld_index
)] = vld
561 raise LcmException("ns_update_nsr: Not found vld={} at RO info".format(vld
["id"]))
563 def ns_update_vnfr(self
, db_vnfrs
, nsr_desc_RO
):
565 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
566 :param db_vnfrs: dictionary with member-vnf-index: vnfr-content
567 :param nsr_desc_RO: nsr descriptor from RO
568 :return: Nothing, LcmException is raised on errors
570 for vnf_index
, db_vnfr
in db_vnfrs
.items():
571 for vnf_RO
in nsr_desc_RO
["vnfs"]:
572 if vnf_RO
["member_vnf_index"] != vnf_index
:
575 if vnf_RO
.get("ip_address"):
576 db_vnfr
["ip-address"] = vnfr_update
["ip-address"] = vnf_RO
["ip_address"].split(";")[0]
577 elif not db_vnfr
.get("ip-address"):
578 raise LcmExceptionNoMgmtIP("ns member_vnf_index '{}' has no IP address".format(vnf_index
))
580 for vdu_index
, vdur
in enumerate(get_iterable(db_vnfr
, "vdur")):
581 vdur_RO_count_index
= 0
582 if vdur
.get("pdu-type"):
584 for vdur_RO
in get_iterable(vnf_RO
, "vms"):
585 if vdur
["vdu-id-ref"] != vdur_RO
["vdu_osm_id"]:
587 if vdur
["count-index"] != vdur_RO_count_index
:
588 vdur_RO_count_index
+= 1
590 vdur
["vim-id"] = vdur_RO
.get("vim_vm_id")
591 if vdur_RO
.get("ip_address"):
592 vdur
["ip-address"] = vdur_RO
["ip_address"].split(";")[0]
594 vdur
["ip-address"] = None
595 vdur
["vdu-id-ref"] = vdur_RO
.get("vdu_osm_id")
596 vdur
["name"] = vdur_RO
.get("vim_name")
597 vdur
["status"] = vdur_RO
.get("status")
598 vdur
["status-detailed"] = vdur_RO
.get("error_msg")
599 for ifacer
in get_iterable(vdur
, "interfaces"):
600 for interface_RO
in get_iterable(vdur_RO
, "interfaces"):
601 if ifacer
["name"] == interface_RO
.get("internal_name"):
602 ifacer
["ip-address"] = interface_RO
.get("ip_address")
603 ifacer
["mac-address"] = interface_RO
.get("mac_address")
606 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} interface={} "
608 .format(vnf_index
, vdur
["vdu-id-ref"], ifacer
["name"]))
609 vnfr_update
["vdur.{}".format(vdu_index
)] = vdur
612 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} count_index={} from "
613 "VIM info".format(vnf_index
, vdur
["vdu-id-ref"], vdur
["count-index"]))
615 for vld_index
, vld
in enumerate(get_iterable(db_vnfr
, "vld")):
616 for net_RO
in get_iterable(nsr_desc_RO
, "nets"):
617 if vld
["id"] != net_RO
.get("vnf_net_osm_id"):
619 vld
["vim-id"] = net_RO
.get("vim_net_id")
620 vld
["name"] = net_RO
.get("vim_name")
621 vld
["status"] = net_RO
.get("status")
622 vld
["status-detailed"] = net_RO
.get("error_msg")
623 vnfr_update
["vld.{}".format(vld_index
)] = vld
626 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vld={} from VIM info".format(
627 vnf_index
, vld
["id"]))
629 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
633 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} from VIM info".format(vnf_index
))
636 def _get_ns_config_info(vca_deployed_list
):
638 Generates a mapping between vnf,vdu elements and the N2VC id
639 :param vca_deployed_list: List of database _admin.deploy.VCA that contains this list
640 :return: a dictionary with {osm-config-mapping: {}} where its element contains:
641 "<member-vnf-index>": <N2VC-id> for a vnf configuration, or
642 "<member-vnf-index>.<vdu.id>.<vdu replica(0, 1,..)>": <N2VC-id> for a vdu configuration
645 ns_config_info
= {"osm-config-mapping": mapping
}
646 for vca
in vca_deployed_list
:
647 if not vca
["member-vnf-index"]:
649 if not vca
["vdu_id"]:
650 mapping
[vca
["member-vnf-index"]] = vca
["application"]
652 mapping
["{}.{}.{}".format(vca
["member-vnf-index"], vca
["vdu_id"], vca
["vdu_count_index"])] =\
654 return ns_config_info
657 def _get_initial_config_primitive_list(desc_primitive_list
, vca_deployed
):
659 Generates a list of initial-config-primitive based on the list provided by the descriptor. It includes internal
660 primitives as verify-ssh-credentials, or config when needed
661 :param desc_primitive_list: information of the descriptor
662 :param vca_deployed: information of the deployed, needed for known if it is related to an NS, VNF, VDU and if
663 this element contains a ssh public key
664 :return: The modified list. Can ba an empty list, but always a list
666 if desc_primitive_list
:
667 primitive_list
= desc_primitive_list
.copy()
670 # look for primitive config, and get the position. None if not present
671 config_position
= None
672 for index
, primitive
in enumerate(primitive_list
):
673 if primitive
["name"] == "config":
674 config_position
= index
677 # for NS, add always a config primitive if not present (bug 874)
678 if not vca_deployed
["member-vnf-index"] and config_position
is None:
679 primitive_list
.insert(0, {"name": "config", "parameter": []})
681 # for VNF/VDU add verify-ssh-credentials after config
682 if vca_deployed
["member-vnf-index"] and config_position
is not None and vca_deployed
.get("ssh-public-key"):
683 primitive_list
.insert(config_position
+ 1, {"name": "verify-ssh-credentials", "parameter": []})
684 return primitive_list
686 async def instantiate_RO(self
, logging_text
, nsr_id
, nsd
, db_nsr
,
687 db_nslcmop
, db_vnfrs
, db_vnfds_ref
, n2vc_key_list
):
690 RO_descriptor_number
= 0 # number of descriptors created at RO
691 vnf_index_2_RO_id
= {} # map between vnfd/nsd id to the id used at RO
692 start_deploy
= time()
693 vdu_flag
= False # If any of the VNFDs has VDUs
694 ns_params
= db_nslcmop
.get("operationParams")
698 # get vnfds, instantiate at RO
700 for c_vnf
in nsd
.get("constituent-vnfd", ()):
701 member_vnf_index
= c_vnf
["member-vnf-index"]
702 vnfd
= db_vnfds_ref
[c_vnf
['vnfd-id-ref']]
705 vnfd_ref
= vnfd
["id"]
706 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Creating vnfd='{}' member_vnf_index='{}' at" \
707 " RO".format(vnfd_ref
, member_vnf_index
)
708 # self.logger.debug(logging_text + step)
709 vnfd_id_RO
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, member_vnf_index
[:23])
710 vnf_index_2_RO_id
[member_vnf_index
] = vnfd_id_RO
711 RO_descriptor_number
+= 1
713 # look position at deployed.RO.vnfd if not present it will be appended at the end
714 for index
, vnf_deployed
in enumerate(db_nsr
["_admin"]["deployed"]["RO"]["vnfd"]):
715 if vnf_deployed
["member-vnf-index"] == member_vnf_index
:
718 index
= len(db_nsr
["_admin"]["deployed"]["RO"]["vnfd"])
719 db_nsr
["_admin"]["deployed"]["RO"]["vnfd"].append(None)
722 RO_update
= {"member-vnf-index": member_vnf_index
}
723 vnfd_list
= await self
.RO
.get_list("vnfd", filter_by
={"osm_id": vnfd_id_RO
})
725 RO_update
["id"] = vnfd_list
[0]["uuid"]
726 self
.logger
.debug(logging_text
+ "vnfd='{}' member_vnf_index='{}' exists at RO. Using RO_id={}".
727 format(vnfd_ref
, member_vnf_index
, vnfd_list
[0]["uuid"]))
729 vnfd_RO
= self
.vnfd2RO(vnfd
, vnfd_id_RO
, db_vnfrs
[c_vnf
["member-vnf-index"]].
730 get("additionalParamsForVnf"), nsr_id
)
731 desc
= await self
.RO
.create("vnfd", descriptor
=vnfd_RO
)
732 RO_update
["id"] = desc
["uuid"]
733 self
.logger
.debug(logging_text
+ "vnfd='{}' member_vnf_index='{}' created at RO. RO_id={}".format(
734 vnfd_ref
, member_vnf_index
, desc
["uuid"]))
735 db_nsr_update
["_admin.deployed.RO.vnfd.{}".format(index
)] = RO_update
736 db_nsr
["_admin"]["deployed"]["RO"]["vnfd"][index
] = RO_update
737 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
738 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
742 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Creating nsd={} at RO".format(nsd_ref
)
743 # self.logger.debug(logging_text + step)
745 RO_osm_nsd_id
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, nsd_ref
[:23])
746 RO_descriptor_number
+= 1
747 nsd_list
= await self
.RO
.get_list("nsd", filter_by
={"osm_id": RO_osm_nsd_id
})
749 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= nsd_list
[0]["uuid"]
750 self
.logger
.debug(logging_text
+ "nsd={} exists at RO. Using RO_id={}".format(
751 nsd_ref
, RO_nsd_uuid
))
753 nsd_RO
= deepcopy(nsd
)
754 nsd_RO
["id"] = RO_osm_nsd_id
755 nsd_RO
.pop("_id", None)
756 nsd_RO
.pop("_admin", None)
757 for c_vnf
in nsd_RO
.get("constituent-vnfd", ()):
758 member_vnf_index
= c_vnf
["member-vnf-index"]
759 c_vnf
["vnfd-id-ref"] = vnf_index_2_RO_id
[member_vnf_index
]
760 for c_vld
in nsd_RO
.get("vld", ()):
761 for cp
in c_vld
.get("vnfd-connection-point-ref", ()):
762 member_vnf_index
= cp
["member-vnf-index-ref"]
763 cp
["vnfd-id-ref"] = vnf_index_2_RO_id
[member_vnf_index
]
765 desc
= await self
.RO
.create("nsd", descriptor
=nsd_RO
)
766 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
767 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= desc
["uuid"]
768 self
.logger
.debug(logging_text
+ "nsd={} created at RO. RO_id={}".format(nsd_ref
, RO_nsd_uuid
))
769 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
770 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
773 # if present use it unless in error status
774 RO_nsr_id
= deep_get(db_nsr
, ("_admin", "deployed", "RO", "nsr_id"))
777 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Looking for existing ns at RO"
778 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
779 desc
= await self
.RO
.show("ns", RO_nsr_id
)
780 except ROclient
.ROClientException
as e
:
781 if e
.http_code
!= HTTPStatus
.NOT_FOUND
:
783 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
785 ns_status
, ns_status_info
= self
.RO
.check_ns_status(desc
)
786 db_nsr_update
["_admin.deployed.RO.nsr_status"] = ns_status
787 if ns_status
== "ERROR":
788 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Deleting ns at RO. RO_ns_id={}"\
790 self
.logger
.debug(logging_text
+ step
)
791 await self
.RO
.delete("ns", RO_nsr_id
)
792 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
794 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Checking dependencies"
795 # self.logger.debug(logging_text + step)
797 # check if VIM is creating and wait look if previous tasks in process
798 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account", ns_params
["vimAccountId"])
800 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
801 self
.logger
.debug(logging_text
+ step
)
802 await asyncio
.wait(task_dependency
, timeout
=3600)
803 if ns_params
.get("vnf"):
804 for vnf
in ns_params
["vnf"]:
805 if "vimAccountId" in vnf
:
806 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account",
809 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
810 self
.logger
.debug(logging_text
+ step
)
811 await asyncio
.wait(task_dependency
, timeout
=3600)
813 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Checking instantiation parameters"
815 RO_ns_params
= self
.ns_params_2_RO(ns_params
, nsd
, db_vnfds_ref
, n2vc_key_list
)
817 step
= db_nsr_update
["detailed-status"] = "Deploying ns at VIM"
818 # step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Deploying ns at VIM"
819 desc
= await self
.RO
.create("ns", descriptor
=RO_ns_params
, name
=db_nsr
["name"], scenario
=RO_nsd_uuid
)
820 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = desc
["uuid"]
821 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
822 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "BUILD"
823 self
.logger
.debug(logging_text
+ "ns created at RO. RO_id={}".format(desc
["uuid"]))
824 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
825 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
827 # wait until NS is ready
828 step
= ns_status_detailed
= detailed_status
= "Waiting VIM to deploy ns. RO_ns_id={}".format(RO_nsr_id
)
829 detailed_status_old
= None
830 self
.logger
.debug(logging_text
+ step
)
832 while time() <= start_deploy
+ self
.total_deploy_timeout
:
833 desc
= await self
.RO
.show("ns", RO_nsr_id
)
834 ns_status
, ns_status_info
= self
.RO
.check_ns_status(desc
)
835 db_nsr_update
["_admin.deployed.RO.nsr_status"] = ns_status
836 if ns_status
== "ERROR":
837 raise ROclient
.ROClientException(ns_status_info
)
838 elif ns_status
== "BUILD":
839 detailed_status
= ns_status_detailed
+ "; {}".format(ns_status_info
)
840 elif ns_status
== "ACTIVE":
841 step
= detailed_status
= "Waiting for management IP address reported by the VIM. Updating VNFRs"
844 self
.ns_update_vnfr(db_vnfrs
, desc
)
846 except LcmExceptionNoMgmtIP
:
849 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
850 if detailed_status
!= detailed_status_old
:
851 detailed_status_old
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = detailed_status
852 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
853 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
854 await asyncio
.sleep(5, loop
=self
.loop
)
855 else: # total_deploy_timeout
856 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
858 step
= "Updating NSR"
859 self
.ns_update_nsr(db_nsr_update
, db_nsr
, desc
)
861 db_nsr_update
["_admin.deployed.RO.operational-status"] = "running"
862 db_nsr
["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
863 db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
864 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
865 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
867 step
= "Deployed at VIM"
868 self
.logger
.debug(logging_text
+ step
)
870 async def wait_vm_up_insert_key_ro(self
, logging_text
, nsr_id
, vnfr_id
, vdu_id
, vdu_index
, pub_key
=None, user
=None):
872 Wait for ip addres at RO, and optionally, insert public key in virtual machine
873 :param logging_text: prefix use for logging
878 :param pub_key: public ssh key to inject, None to skip
879 :param user: user to apply the public ssh key
883 # self.logger.debug(logging_text + "Starting wait_vm_up_insert_key_ro")
891 await asyncio
.sleep(10, loop
=self
.loop
)
892 # wait until NS is deployed at RO
894 db_nsrs
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
895 ro_nsr_id
= deep_get(db_nsrs
, ("_admin", "deployed", "RO", "nsr_id"))
900 if not target_vdu_id
:
901 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnfr_id
})
903 ip_address
= db_vnfr
.get("ip-address")
906 for vdur
in get_iterable(db_vnfr
, "vdur"):
907 if (vdur
["vdu-id-ref"] == vdu_id
and vdur
["count-index"] == vdu_index
) or \
908 (ip_address
and vdur
.get("ip-address") == ip_address
):
909 if vdur
["status"] == "ACTIVE":
910 target_vdu_id
= vdur
["vdu-id-ref"]
911 elif vdur
["status"] == "ERROR":
912 raise LcmException("Cannot inject ssh-key because target VM is in error state")
915 raise LcmException("Not found vnfr_id={}, vdu_index={}, vdu_index={}".format(
916 vnfr_id
, vdu_id
, vdu_index
919 if not target_vdu_id
:
922 # self.logger.debug(logging_text + "IP address={}".format(ip_address))
924 # inject public key into machine
926 # self.logger.debug(logging_text + "Inserting RO key")
928 ro_vm_id
= "{}-{}".format(db_vnfr
["member-vnf-index-ref"], target_vdu_id
) # TODO add vdu_index
929 result_dict
= await self
.RO
.create_action(
931 item_id_name
=ro_nsr_id
,
932 descriptor
={"add_public_key": pub_key
, "vms": [ro_vm_id
], "user": user
}
934 # result_dict contains the format {VM-id: {vim_result: 200, description: text}}
935 if not result_dict
or not isinstance(result_dict
, dict):
936 raise LcmException("Unknown response from RO when injecting key")
937 for result
in result_dict
.values():
938 if result
.get("vim_result") == 200:
941 raise ROclient
.ROClientException("error injecting key: {}".format(
942 result
.get("description")))
944 except ROclient
.ROClientException
as e
:
946 self
.logger
.debug(logging_text
+ "error injecting key: {}. Retrying until {} seconds".
950 raise LcmException("Reaching max tries injecting key. Error: {}".format(e
))
956 async def instantiate_N2VC(self
, logging_text
, vca_index
, nsi_id
, db_nsr
, db_vnfr
, vdu_id
,
957 kdu_name
, vdu_index
, config_descriptor
, deploy_params
, base_folder
):
958 nsr_id
= db_nsr
["_id"]
959 db_update_entry
= "_admin.deployed.VCA.{}.".format(vca_index
)
960 vca_deployed_list
= db_nsr
["_admin"]["deployed"]["VCA"]
961 vca_deployed
= db_nsr
["_admin"]["deployed"]["VCA"][vca_index
]
963 'collection': 'nsrs',
964 'filter': {'_id': nsr_id
},
965 'path': db_update_entry
967 logging_text
+= "member_vnf_index={} vdu_id={}, vdu_index={} ".format(db_vnfr
["member-vnf-index-ref"],
974 vnfr_id
= db_vnfr
["_id"]
976 namespace
= "{nsi}.{ns}".format(
977 nsi
=nsi_id
if nsi_id
else "",
980 namespace
+= "." + vnfr_id
982 namespace
+= ".{}-{}".format(vdu_id
, vdu_index
or 0)
985 artifact_path
= "/{}/{}/charms/{}".format(
986 base_folder
["folder"],
987 base_folder
["pkg-dir"],
988 config_descriptor
["juju"]["charm"]
991 is_proxy_charm
= deep_get(config_descriptor
, ('juju', 'charm')) is not None
992 if deep_get(config_descriptor
, ('juju', 'proxy')) is False:
993 is_proxy_charm
= False
995 # n2vc_redesign STEP 3.1
997 # find old ee_id if exists
998 ee_id
= vca_deployed
.get("ee_id")
1000 # create or register execution environment in VCA
1002 step
= "create execution environment"
1003 self
.logger
.debug(logging_text
+ step
)
1004 ee_id
, credentials
= await self
.n2vc
.create_execution_environment(
1005 namespace
=namespace
,
1011 step
= "register execution environment"
1012 # TODO wait until deployed by RO, when IP address has been filled. By pooling????
1013 credentials
= {} # TODO db_credentials["ip_address"]
1015 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1016 # merged. Meanwhile let's get username from initial-config-primitive
1017 if config_descriptor
.get("initial-config-primitive"):
1018 for param
in config_descriptor
["initial-config-primitive"][0].get("parameter", ()):
1019 if param
["name"] == "ssh-username":
1020 credentials
["username"] = param
["value"]
1021 if config_descriptor
.get("config-access") and config_descriptor
["config-access"].get("ssh-access"):
1022 if config_descriptor
["config-access"]["ssh-access"].get("required"):
1023 credentials
["username"] = \
1024 config_descriptor
["config-access"]["ssh-access"].get("default-user")
1026 # n2vc_redesign STEP 3.2
1027 self
.logger
.debug(logging_text
+ step
)
1028 ee_id
= await self
.n2vc
.register_execution_environment(
1029 credentials
=credentials
,
1030 namespace
=namespace
,
1034 # for compatibility with MON/POL modules, the need model and application name at database
1035 # TODO ask to N2VC instead of assuming the format "model_name.application_name"
1036 ee_id_parts
= ee_id
.split('.')
1037 model_name
= ee_id_parts
[0]
1038 application_name
= ee_id_parts
[1]
1039 self
.update_db_2("nsrs", nsr_id
, {db_update_entry
+ "model": model_name
,
1040 db_update_entry
+ "application": application_name
,
1041 db_update_entry
+ "ee_id": ee_id
})
1043 # n2vc_redesign STEP 3.3
1044 # TODO check if already done
1045 step
= "Install configuration Software"
1046 self
.logger
.debug(logging_text
+ step
)
1047 await self
.n2vc
.install_configuration_sw(
1049 artifact_path
=artifact_path
,
1053 # if SSH access is required, then get execution environment SSH public
1054 required
= deep_get(config_descriptor
, ("config-access", "ssh-access", "required"))
1057 if is_proxy_charm
and required
:
1058 user
= deep_get(config_descriptor
, ("config-access", "ssh-access", "default-user"))
1059 step
= "Install configuration Software, getting public ssh key"
1060 pub_key
= await self
.n2vc
.get_ee_ssh_public__key(
1065 step
= "Insert public key into VM"
1067 step
= "Waiting to VM being up and getting IP address"
1068 self
.logger
.debug(logging_text
+ step
)
1070 # n2vc_redesign STEP 5.1
1071 # wait for RO (ip-address) Insert pub_key into VM
1072 rw_mgmt_ip
= await self
.wait_vm_up_insert_key_ro(
1073 logging_text
=logging_text
,
1077 vdu_index
=vdu_index
,
1081 self
.logger
.debug(logging_text
+ ' VM_ip_address={}'.format(rw_mgmt_ip
))
1083 # store rw_mgmt_ip in deploy params for later replacement
1084 deploy_params
["rw_mgmt_ip"] = rw_mgmt_ip
1086 # n2vc_redesign STEP 6 Execute initial config primitive
1087 step
= 'execute initial config primitive'
1088 initial_config_primitive_list
= config_descriptor
.get('initial-config-primitive')
1090 # sort initial config primitives by 'seq'
1092 initial_config_primitive_list
.sort(key
=lambda val
: int(val
['seq']))
1093 except Exception as e
:
1094 self
.logger
.error(logging_text
+ step
+ ": " + str(e
))
1096 # add config if not present for NS charm
1097 initial_config_primitive_list
= self
._get
_initial
_config
_primitive
_list
(initial_config_primitive_list
,
1100 for initial_config_primitive
in initial_config_primitive_list
:
1101 # adding information on the vca_deployed if it is a NS execution environment
1102 if not vca_deployed
["member-vnf-index"]:
1103 deploy_params
["ns_config_info"] = self
._get
_ns
_config
_info
(vca_deployed_list
)
1104 # TODO check if already done
1105 primitive_params_
= self
._map
_primitive
_params
(initial_config_primitive
, {}, deploy_params
)
1106 step
= "execute primitive '{}' params '{}'".format(initial_config_primitive
["name"], primitive_params_
)
1107 self
.logger
.debug(logging_text
+ step
)
1108 await self
.n2vc
.exec_primitive(
1110 primitive_name
=initial_config_primitive
["name"],
1111 params_dict
=primitive_params_
,
1114 # TODO register in database that primitive is done
1116 step
= "instantiated at VCA"
1117 self
.logger
.debug(logging_text
+ step
)
1119 except Exception as e
: # TODO not use Exception but N2VC exception
1120 raise Exception("{} {}".format(step
, e
)) from e
1121 # TODO raise N2VC exception with 'step' extra information
1123 async def instantiate(self
, nsr_id
, nslcmop_id
):
1126 :param nsr_id: ns instance to deploy
1127 :param nslcmop_id: operation to run
1131 # Try to lock HA task here
1132 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
1133 if not task_is_locked_by_me
:
1134 self
.logger
.debug('instantiate() task is not locked by me')
1137 logging_text
= "Task ns={} instantiate={} ".format(nsr_id
, nslcmop_id
)
1138 self
.logger
.debug(logging_text
+ "Enter")
1140 # get all needed from database
1142 # database nsrs record
1145 # database nslcmops record
1148 # update operation on nsrs
1149 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
1150 "_admin.current-operation": nslcmop_id
,
1151 "_admin.operation-type": "instantiate"}
1152 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1154 # update operation on nslcmops
1155 db_nslcmop_update
= {}
1157 nslcmop_operation_state
= None
1158 db_vnfrs
= {} # vnf's info indexed by member-index
1160 task_instantiation_list
= []
1163 # wait for any previous tasks in process
1164 step
= "Waiting for previous operations to terminate"
1165 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
1167 # STEP 0: Reading database (nslcmops, nsrs, nsds, vnfrs, vnfds)
1169 # read from db: operation
1170 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
1171 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1174 step
= "Getting nsr={} from db".format(nsr_id
)
1175 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1176 # nsd is replicated into ns (no db read)
1178 # nsr_name = db_nsr["name"] # TODO short-name??
1180 # read from db: vnf's of this ns
1181 step
= "Getting vnfrs from db"
1182 self
.logger
.debug(logging_text
+ step
)
1183 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1185 # read from db: vnfd's for every vnf
1186 db_vnfds_ref
= {} # every vnfd data indexed by vnf name
1187 db_vnfds
= {} # every vnfd data indexed by vnf id
1188 db_vnfds_index
= {} # every vnfd data indexed by vnf member-index
1190 # for each vnf in ns, read vnfd
1191 for vnfr
in db_vnfrs_list
:
1192 db_vnfrs
[vnfr
["member-vnf-index-ref"]] = vnfr
# vnf's dict indexed by member-index: '1', '2', etc
1193 vnfd_id
= vnfr
["vnfd-id"] # vnfd uuid for this vnf
1194 vnfd_ref
= vnfr
["vnfd-ref"] # vnfd name for this vnf
1195 # if we haven't this vnfd, read it from db
1196 if vnfd_id
not in db_vnfds
:
1198 step
= "Getting vnfd={} id='{}' from db".format(vnfd_id
, vnfd_ref
)
1199 self
.logger
.debug(logging_text
+ step
)
1200 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
1203 db_vnfds_ref
[vnfd_ref
] = vnfd
# vnfd's indexed by name
1204 db_vnfds
[vnfd_id
] = vnfd
# vnfd's indexed by id
1205 db_vnfds_index
[vnfr
["member-vnf-index-ref"]] = db_vnfds
[vnfd_id
] # vnfd's indexed by member-index
1207 # Get or generates the _admin.deployed.VCA list
1208 vca_deployed_list
= None
1209 if db_nsr
["_admin"].get("deployed"):
1210 vca_deployed_list
= db_nsr
["_admin"]["deployed"].get("VCA")
1211 if vca_deployed_list
is None:
1212 vca_deployed_list
= []
1213 db_nsr_update
["_admin.deployed.VCA"] = vca_deployed_list
1214 # add _admin.deployed.VCA to db_nsr dictionary, value=vca_deployed_list
1215 populate_dict(db_nsr
, ("_admin", "deployed", "VCA"), vca_deployed_list
)
1216 elif isinstance(vca_deployed_list
, dict):
1217 # maintain backward compatibility. Change a dict to list at database
1218 vca_deployed_list
= list(vca_deployed_list
.values())
1219 db_nsr_update
["_admin.deployed.VCA"] = vca_deployed_list
1220 populate_dict(db_nsr
, ("_admin", "deployed", "VCA"), vca_deployed_list
)
1222 db_nsr_update
["detailed-status"] = "creating"
1223 db_nsr_update
["operational-status"] = "init"
1225 if not isinstance(deep_get(db_nsr
, ("_admin", "deployed", "RO", "vnfd")), list):
1226 populate_dict(db_nsr
, ("_admin", "deployed", "RO", "vnfd"), [])
1227 db_nsr_update
["_admin.deployed.RO.vnfd"] = []
1229 # set state to INSTANTIATED. When instantiated NBI will not delete directly
1230 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1231 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1232 self
.logger
.debug(logging_text
+ "Before deploy_kdus")
1233 db_k8scluster_list
= self
.db
.get_list("k8sclusters", {})
1234 # Call to deploy_kdus in case exists the "vdu:kdu" param
1235 task_kdu
= asyncio
.ensure_future(
1237 logging_text
=logging_text
,
1241 db_nslcmop
=db_nslcmop
,
1243 db_vnfds_ref
=db_vnfds_ref
,
1244 db_k8scluster
=db_k8scluster_list
1247 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_KDUs", task_kdu
)
1248 task_instantiation_list
.append(task_kdu
)
1249 # n2vc_redesign STEP 1 Get VCA public ssh-key
1250 # feature 1429. Add n2vc public key to needed VMs
1251 n2vc_key
= await self
.n2vc
.get_public_key()
1252 n2vc_key_list
= [n2vc_key
]
1253 if self
.vca_config
.get("public_key"):
1254 n2vc_key_list
.append(self
.vca_config
["public_key"])
1256 # n2vc_redesign STEP 2 Deploy Network Scenario
1257 task_ro
= asyncio
.ensure_future(
1258 self
.instantiate_RO(
1259 logging_text
=logging_text
,
1263 db_nslcmop
=db_nslcmop
,
1265 db_vnfds_ref
=db_vnfds_ref
,
1266 n2vc_key_list
=n2vc_key_list
1269 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_RO", task_ro
)
1270 task_instantiation_list
.append(task_ro
)
1272 # n2vc_redesign STEP 3 to 6 Deploy N2VC
1273 step
= "Looking for needed vnfd to configure with proxy charm"
1274 self
.logger
.debug(logging_text
+ step
)
1276 nsi_id
= None # TODO put nsi_id when this nsr belongs to a NSI
1277 # get_iterable() returns a value from a dict or empty tuple if key does not exist
1278 for c_vnf
in get_iterable(nsd
, "constituent-vnfd"):
1279 vnfd_id
= c_vnf
["vnfd-id-ref"]
1280 vnfd
= db_vnfds_ref
[vnfd_id
]
1281 member_vnf_index
= str(c_vnf
["member-vnf-index"])
1282 db_vnfr
= db_vnfrs
[member_vnf_index
]
1283 base_folder
= vnfd
["_admin"]["storage"]
1289 # Get additional parameters
1291 if db_vnfr
.get("additionalParamsForVnf"):
1292 deploy_params
= db_vnfr
["additionalParamsForVnf"].copy()
1293 for k
, v
in deploy_params
.items():
1294 if isinstance(v
, str) and v
.startswith("!!yaml "):
1295 deploy_params
[k
] = yaml
.safe_load(v
[7:])
1297 descriptor_config
= vnfd
.get("vnf-configuration")
1298 if descriptor_config
and descriptor_config
.get("juju"):
1300 logging_text
=logging_text
,
1303 nslcmop_id
=nslcmop_id
,
1309 member_vnf_index
=member_vnf_index
,
1310 vdu_index
=vdu_index
,
1312 deploy_params
=deploy_params
,
1313 descriptor_config
=descriptor_config
,
1314 base_folder
=base_folder
,
1315 task_instantiation_list
=task_instantiation_list
1318 # Deploy charms for each VDU that supports one.
1319 for vdud
in get_iterable(vnfd
, 'vdu'):
1321 descriptor_config
= vdud
.get('vdu-configuration')
1322 if descriptor_config
and descriptor_config
.get("juju"):
1323 # look for vdu index in the db_vnfr["vdu"] section
1324 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
1325 # if vdur["vdu-id-ref"] == vdu_id:
1328 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
1329 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
1330 # vdu_name = vdur.get("name")
1333 for vdu_index
in range(int(vdud
.get("count", 1))):
1334 # TODO vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
1336 logging_text
=logging_text
,
1339 nslcmop_id
=nslcmop_id
,
1345 member_vnf_index
=member_vnf_index
,
1346 vdu_index
=vdu_index
,
1348 deploy_params
=deploy_params
,
1349 descriptor_config
=descriptor_config
,
1350 base_folder
=base_folder
,
1351 task_instantiation_list
=task_instantiation_list
1353 for kdud
in get_iterable(vnfd
, 'kdu'):
1354 kdu_name
= kdud
["name"]
1355 descriptor_config
= kdud
.get('kdu-configuration')
1356 if descriptor_config
and descriptor_config
.get("juju"):
1360 # look for vdu index in the db_vnfr["vdu"] section
1361 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
1362 # if vdur["vdu-id-ref"] == vdu_id:
1365 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
1366 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
1367 # vdu_name = vdur.get("name")
1371 logging_text
=logging_text
,
1374 nslcmop_id
=nslcmop_id
,
1380 member_vnf_index
=member_vnf_index
,
1381 vdu_index
=vdu_index
,
1383 deploy_params
=deploy_params
,
1384 descriptor_config
=descriptor_config
,
1385 base_folder
=base_folder
,
1386 task_instantiation_list
=task_instantiation_list
1389 # Check if this NS has a charm configuration
1390 descriptor_config
= nsd
.get("ns-configuration")
1391 if descriptor_config
and descriptor_config
.get("juju"):
1394 member_vnf_index
= None
1400 # Get additional parameters
1402 if db_nsr
.get("additionalParamsForNs"):
1403 deploy_params
= db_nsr
["additionalParamsForNs"].copy()
1404 for k
, v
in deploy_params
.items():
1405 if isinstance(v
, str) and v
.startswith("!!yaml "):
1406 deploy_params
[k
] = yaml
.safe_load(v
[7:])
1407 base_folder
= nsd
["_admin"]["storage"]
1409 logging_text
=logging_text
,
1412 nslcmop_id
=nslcmop_id
,
1418 member_vnf_index
=member_vnf_index
,
1419 vdu_index
=vdu_index
,
1421 deploy_params
=deploy_params
,
1422 descriptor_config
=descriptor_config
,
1423 base_folder
=base_folder
,
1424 task_instantiation_list
=task_instantiation_list
1427 # Wait until all tasks of "task_instantiation_list" have been finished
1429 # while time() <= start_deploy + self.total_deploy_timeout:
1431 timeout
= 3600 # time() - start_deploy
1432 task_instantiation_set
= set(task_instantiation_list
) # build a set with tasks
1435 if len(task_instantiation_set
) > 0:
1436 done
, pending
= await asyncio
.wait(task_instantiation_set
, timeout
=timeout
)
1438 error_text
= "timeout"
1440 if task
.cancelled():
1442 error_text
= "cancelled"
1444 exc
= task
.exception()
1446 error_text
= str(exc
)
1449 db_nsr_update
["config-status"] = "failed"
1450 error_text
= "fail configuring " + error_text
1451 db_nsr_update
["detailed-status"] = error_text
1452 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED_TEMP"
1453 db_nslcmop_update
["detailed-status"] = error_text
1454 db_nslcmop_update
["statusEnteredTime"] = time()
1457 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
1458 db_nslcmop_update
["statusEnteredTime"] = time()
1459 db_nslcmop_update
["detailed-status"] = "done"
1460 db_nsr_update
["config-status"] = "configured"
1461 db_nsr_update
["detailed-status"] = "done"
1463 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
1464 self
.logger
.error(logging_text
+ "Exit Exception while '{}': {}".format(step
, e
))
1466 except asyncio
.CancelledError
:
1467 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1468 exc
= "Operation was cancelled"
1469 except Exception as e
:
1470 exc
= traceback
.format_exc()
1471 self
.logger
.critical(logging_text
+ "Exit Exception {} while '{}': {}".format(type(e
).__name
__, step
, e
),
1476 db_nsr_update
["detailed-status"] = "ERROR {}: {}".format(step
, exc
)
1477 db_nsr_update
["operational-status"] = "failed"
1479 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
1480 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
1481 db_nslcmop_update
["statusEnteredTime"] = time()
1484 db_nsr_update
["_admin.nslcmop"] = None
1485 db_nsr_update
["_admin.current-operation"] = None
1486 db_nsr_update
["_admin.operation-type"] = None
1487 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1488 if db_nslcmop_update
:
1489 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1490 except DbException
as e
:
1491 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
1492 if nslcmop_operation_state
:
1494 await self
.msg
.aiowrite("ns", "instantiated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
1495 "operationState": nslcmop_operation_state
},
1497 except Exception as e
:
1498 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1500 self
.logger
.debug(logging_text
+ "Exit")
1501 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_instantiate")
1503 async def deploy_kdus(self
, logging_text
, nsr_id
, nsd
, db_nsr
, db_nslcmop
, db_vnfrs
, db_vnfds_ref
, db_k8scluster
):
1504 # Launch kdus if present in the descriptor
1505 logging_text
= "Deploy kdus: "
1507 db_nsr_update
["_admin.deployed.K8s"] = []
1509 # Look for all vnfds
1510 # db_nsr_update["_admin.deployed.K8s"] = []
1513 for c_vnf
in nsd
.get("constituent-vnfd", ()):
1514 vnfr
= db_vnfrs
[c_vnf
["member-vnf-index"]]
1515 member_vnf_index
= c_vnf
["member-vnf-index"]
1516 vnfd
= db_vnfds_ref
[c_vnf
['vnfd-id-ref']]
1517 vnfd_ref
= vnfd
["id"]
1520 step
= "Checking kdu from vnf: {} - member-vnf-index: {}".format(vnfd_ref
, member_vnf_index
)
1521 self
.logger
.debug(logging_text
+ step
)
1523 step
= "vnf: {} has kdus".format(vnfd_ref
)
1524 self
.logger
.debug(logging_text
+ step
)
1525 for vnfr_name
, vnfr_data
in db_vnfrs
.items():
1526 if vnfr_data
["vnfd-ref"] == vnfd
["id"]:
1527 if vnfr_data
.get("additionalParamsForVnf"):
1528 desc_params
= self
._format
_additional
_params
(vnfr_data
["additionalParamsForVnf"])
1531 raise LcmException("VNF descriptor not found with id: {}".format(vnfr_data
["vnfd-ref"]))
1532 self
.logger
.debug(logging_text
+ step
)
1534 for kdur
in vnfr
.get("kdur"):
1536 for k8scluster
in db_k8scluster
:
1537 if kdur
["k8s-cluster"]["id"] == k8scluster
["_id"]:
1538 cluster_uuid
= k8scluster
["cluster-uuid"]
1541 raise LcmException("K8scluster not found with id: {}".format(kdur
["k8s-cluster"]["id"]))
1542 self
.logger
.debug(logging_text
+ step
)
1544 step
= "Instantiate KDU {} in k8s cluster {}".format(kdur
["kdu-name"], cluster_uuid
)
1545 self
.logger
.debug(logging_text
+ step
)
1546 for kdu
in vnfd
.get("kdu"):
1547 if kdu
.get("name") == kdur
["kdu-name"]:
1550 raise LcmException("KDU not found with name: {} in VNFD {}".format(kdur
["kdu-name"],
1552 self
.logger
.debug(logging_text
+ step
)
1554 k8sclustertype
= None
1555 if kdu
.get("helm-chart"):
1556 kdumodel
= kdu
["helm-chart"]
1557 k8sclustertype
= "chart"
1558 elif kdu
.get("juju-bundle"):
1559 kdumodel
= kdu
["juju-bundle"]
1560 k8sclustertype
= "juju"
1561 k8s_instace_info
= {"kdu-instance": None, "k8scluster-uuid": cluster_uuid
,
1562 "vnfr-id": vnfr
["id"], "k8scluster-type": k8sclustertype
,
1563 "kdu-name": kdur
["kdu-name"], "kdu-model": kdumodel
}
1564 db_nsr_update
["_admin.deployed.K8s"].append(k8s_instace_info
)
1565 db_dict
= {"collection": "nsrs", "filter": {"_id": nsr_id
}, "path": "_admin.deployed.K8s."
1567 if k8sclustertype
== "chart":
1568 task
= self
.k8sclusterhelm
.install(cluster_uuid
=cluster_uuid
, kdu_model
=kdumodel
,
1569 atomic
=True, params
=desc_params
,
1570 db_dict
=db_dict
, timeout
=300)
1572 # TODO I need the juju connector in place
1574 task_list
.append(task
)
1576 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1579 if len(task_list
) > 0:
1580 self
.logger
.debug('Waiting for terminate pending tasks...')
1581 done
, pending
= await asyncio
.wait(task_list
, timeout
=3600)
1584 k8s_instance
= fut
.result()
1585 k8s_instace_info
= {"kdu-instance": k8s_instance
, "k8scluster-uuid": cluster_uuid
,
1586 "vnfr-id": vnfr
["id"], "k8scluster-type": k8sclustertype
,
1587 "kdu-name": kdur
["kdu-name"], "kdu-model": kdumodel
}
1588 vnf_update
.append(k8s_instace_info
)
1589 self
.logger
.debug('All tasks finished...')
1591 self
.logger
.info('There are pending tasks: {}'.format(pending
))
1593 db_nsr_update
["_admin.deployed.K8s"] = vnf_update
1594 except Exception as e
:
1595 self
.logger
.critical(logging_text
+ "Exit Exception {} while '{}': {}".format(type(e
).__name
__, step
, e
))
1596 raise LcmException("{} Exit Exception {} while '{}': {}".format(logging_text
, type(e
).__name
__, step
, e
))
1598 # TODO Write in data base
1600 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1602 def _deploy_n2vc(self
, logging_text
, db_nsr
, db_vnfr
, nslcmop_id
, nsr_id
, nsi_id
, vnfd_id
, vdu_id
,
1603 kdu_name
, member_vnf_index
, vdu_index
, vdu_name
, deploy_params
, descriptor_config
,
1604 base_folder
, task_instantiation_list
):
1605 # launch instantiate_N2VC in a asyncio task and register task object
1606 # Look where information of this charm is at database <nsrs>._admin.deployed.VCA
1607 # if not found, create one entry and update database
1609 # fill db_nsr._admin.deployed.VCA.<index>
1611 for vca_index
, vca_deployed
in enumerate(db_nsr
["_admin"]["deployed"]["VCA"]):
1612 if not vca_deployed
:
1614 if vca_deployed
.get("member-vnf-index") == member_vnf_index
and \
1615 vca_deployed
.get("vdu_id") == vdu_id
and \
1616 vca_deployed
.get("kdu_name") == kdu_name
and \
1617 vca_deployed
.get("vdu_count_index", 0) == vdu_index
:
1620 # not found, create one.
1622 "member-vnf-index": member_vnf_index
,
1624 "kdu_name": kdu_name
,
1625 "vdu_count_index": vdu_index
,
1626 "operational-status": "init", # TODO revise
1627 "detailed-status": "", # TODO revise
1628 "step": "initial-deploy", # TODO revise
1630 "vdu_name": vdu_name
,
1633 self
.update_db_2("nsrs", nsr_id
, {"_admin.deployed.VCA.{}".format(vca_index
): vca_deployed
})
1634 db_nsr
["_admin"]["deployed"]["VCA"].append(vca_deployed
)
1637 task_n2vc
= asyncio
.ensure_future(
1638 self
.instantiate_N2VC(
1639 logging_text
=logging_text
,
1640 vca_index
=vca_index
,
1646 vdu_index
=vdu_index
,
1647 deploy_params
=deploy_params
,
1648 config_descriptor
=descriptor_config
,
1649 base_folder
=base_folder
,
1652 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_N2VC-{}".format(vca_index
), task_n2vc
)
1653 task_instantiation_list
.append(task_n2vc
)
1655 # Check if this VNFD has a configured terminate action
1656 def _has_terminate_config_primitive(self
, vnfd
):
1657 vnf_config
= vnfd
.get("vnf-configuration")
1658 if vnf_config
and vnf_config
.get("terminate-config-primitive"):
1664 def _get_terminate_config_primitive_seq_list(vnfd
):
1665 """ Get a numerically sorted list of the sequences for this VNFD's terminate action """
1666 # No need to check for existing primitive twice, already done before
1667 vnf_config
= vnfd
.get("vnf-configuration")
1668 seq_list
= vnf_config
.get("terminate-config-primitive")
1669 # Get all 'seq' tags in seq_list, order sequences numerically, ascending.
1670 seq_list_sorted
= sorted(seq_list
, key
=lambda x
: int(x
['seq']))
1671 return seq_list_sorted
1674 def _create_nslcmop(nsr_id
, operation
, params
):
1676 Creates a ns-lcm-opp content to be stored at database.
1677 :param nsr_id: internal id of the instance
1678 :param operation: instantiate, terminate, scale, action, ...
1679 :param params: user parameters for the operation
1680 :return: dictionary following SOL005 format
1682 # Raise exception if invalid arguments
1683 if not (nsr_id
and operation
and params
):
1685 "Parameters 'nsr_id', 'operation' and 'params' needed to create primitive not provided")
1691 # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1692 "operationState": "PROCESSING",
1693 "statusEnteredTime": now
,
1694 "nsInstanceId": nsr_id
,
1695 "lcmOperationType": operation
,
1697 "isAutomaticInvocation": False,
1698 "operationParams": params
,
1699 "isCancelPending": False,
1701 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
1702 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
1707 def _format_additional_params(self
, params
):
1709 for key
, value
in params
.items():
1710 if str(value
).startswith("!!yaml "):
1711 params
[key
] = yaml
.safe_load(value
[7:])
1715 def _get_terminate_primitive_params(self
, seq
, vnf_index
):
1716 primitive
= seq
.get('name')
1717 primitive_params
= {}
1719 "member_vnf_index": vnf_index
,
1720 "primitive": primitive
,
1721 "primitive_params": primitive_params
,
1724 return self
._map
_primitive
_params
(seq
, params
, desc_params
)
1728 def _reintent_or_skip_suboperation(self
, db_nslcmop
, op_index
):
1729 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
1730 if (op
.get('operationState') == 'COMPLETED'):
1731 # b. Skip sub-operation
1732 # _ns_execute_primitive() or RO.create_action() will NOT be executed
1733 return self
.SUBOPERATION_STATUS_SKIP
1735 # c. Reintent executing sub-operation
1736 # The sub-operation exists, and operationState != 'COMPLETED'
1737 # Update operationState = 'PROCESSING' to indicate a reintent.
1738 operationState
= 'PROCESSING'
1739 detailed_status
= 'In progress'
1740 self
._update
_suboperation
_status
(
1741 db_nslcmop
, op_index
, operationState
, detailed_status
)
1742 # Return the sub-operation index
1743 # _ns_execute_primitive() or RO.create_action() will be called from scale()
1744 # with arguments extracted from the sub-operation
1747 # Find a sub-operation where all keys in a matching dictionary must match
1748 # Returns the index of the matching sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if no match
1749 def _find_suboperation(self
, db_nslcmop
, match
):
1750 if (db_nslcmop
and match
):
1751 op_list
= db_nslcmop
.get('_admin', {}).get('operations', [])
1752 for i
, op
in enumerate(op_list
):
1753 if all(op
.get(k
) == match
[k
] for k
in match
):
1755 return self
.SUBOPERATION_STATUS_NOT_FOUND
1757 # Update status for a sub-operation given its index
1758 def _update_suboperation_status(self
, db_nslcmop
, op_index
, operationState
, detailed_status
):
1759 # Update DB for HA tasks
1760 q_filter
= {'_id': db_nslcmop
['_id']}
1761 update_dict
= {'_admin.operations.{}.operationState'.format(op_index
): operationState
,
1762 '_admin.operations.{}.detailed-status'.format(op_index
): detailed_status
}
1763 self
.db
.set_one("nslcmops",
1765 update_dict
=update_dict
,
1766 fail_on_empty
=False)
1768 # Add sub-operation, return the index of the added sub-operation
1769 # Optionally, set operationState, detailed-status, and operationType
1770 # Status and type are currently set for 'scale' sub-operations:
1771 # 'operationState' : 'PROCESSING' | 'COMPLETED' | 'FAILED'
1772 # 'detailed-status' : status message
1773 # 'operationType': may be any type, in the case of scaling: 'PRE-SCALE' | 'POST-SCALE'
1774 # Status and operation type are currently only used for 'scale', but NOT for 'terminate' sub-operations.
1775 def _add_suboperation(self
, db_nslcmop
, vnf_index
, vdu_id
, vdu_count_index
, vdu_name
, primitive
,
1776 mapped_primitive_params
, operationState
=None, detailed_status
=None, operationType
=None,
1777 RO_nsr_id
=None, RO_scaling_info
=None):
1778 if not (db_nslcmop
):
1779 return self
.SUBOPERATION_STATUS_NOT_FOUND
1780 # Get the "_admin.operations" list, if it exists
1781 db_nslcmop_admin
= db_nslcmop
.get('_admin', {})
1782 op_list
= db_nslcmop_admin
.get('operations')
1783 # Create or append to the "_admin.operations" list
1784 new_op
= {'member_vnf_index': vnf_index
,
1786 'vdu_count_index': vdu_count_index
,
1787 'primitive': primitive
,
1788 'primitive_params': mapped_primitive_params
}
1790 new_op
['operationState'] = operationState
1792 new_op
['detailed-status'] = detailed_status
1794 new_op
['lcmOperationType'] = operationType
1796 new_op
['RO_nsr_id'] = RO_nsr_id
1798 new_op
['RO_scaling_info'] = RO_scaling_info
1800 # No existing operations, create key 'operations' with current operation as first list element
1801 db_nslcmop_admin
.update({'operations': [new_op
]})
1802 op_list
= db_nslcmop_admin
.get('operations')
1804 # Existing operations, append operation to list
1805 op_list
.append(new_op
)
1807 db_nslcmop_update
= {'_admin.operations': op_list
}
1808 self
.update_db_2("nslcmops", db_nslcmop
['_id'], db_nslcmop_update
)
1809 op_index
= len(op_list
) - 1
1812 # Helper methods for scale() sub-operations
1814 # pre-scale/post-scale:
1815 # Check for 3 different cases:
1816 # a. New: First time execution, return SUBOPERATION_STATUS_NEW
1817 # b. Skip: Existing sub-operation exists, operationState == 'COMPLETED', return SUBOPERATION_STATUS_SKIP
1818 # c. Reintent: Existing sub-operation exists, operationState != 'COMPLETED', return op_index to re-execute
1819 def _check_or_add_scale_suboperation(self
, db_nslcmop
, vnf_index
, vnf_config_primitive
, primitive_params
,
1820 operationType
, RO_nsr_id
=None, RO_scaling_info
=None):
1821 # Find this sub-operation
1822 if (RO_nsr_id
and RO_scaling_info
):
1823 operationType
= 'SCALE-RO'
1825 'member_vnf_index': vnf_index
,
1826 'RO_nsr_id': RO_nsr_id
,
1827 'RO_scaling_info': RO_scaling_info
,
1831 'member_vnf_index': vnf_index
,
1832 'primitive': vnf_config_primitive
,
1833 'primitive_params': primitive_params
,
1834 'lcmOperationType': operationType
1836 op_index
= self
._find
_suboperation
(db_nslcmop
, match
)
1837 if (op_index
== self
.SUBOPERATION_STATUS_NOT_FOUND
):
1838 # a. New sub-operation
1839 # The sub-operation does not exist, add it.
1840 # _ns_execute_primitive() will be called from scale() as usual, with non-modified arguments
1841 # The following parameters are set to None for all kind of scaling:
1843 vdu_count_index
= None
1845 if (RO_nsr_id
and RO_scaling_info
):
1846 vnf_config_primitive
= None
1847 primitive_params
= None
1850 RO_scaling_info
= None
1851 # Initial status for sub-operation
1852 operationState
= 'PROCESSING'
1853 detailed_status
= 'In progress'
1854 # Add sub-operation for pre/post-scaling (zero or more operations)
1855 self
._add
_suboperation
(db_nslcmop
,
1860 vnf_config_primitive
,
1867 return self
.SUBOPERATION_STATUS_NEW
1869 # Return either SUBOPERATION_STATUS_SKIP (operationState == 'COMPLETED'),
1870 # or op_index (operationState != 'COMPLETED')
1871 return self
._reintent
_or
_skip
_suboperation
(db_nslcmop
, op_index
)
1873 # Helper methods for terminate()
1875 async def _terminate_action(self
, db_nslcmop
, nslcmop_id
, nsr_id
):
1876 """ Create a primitive with params from VNFD
1877 Called from terminate() before deleting instance
1878 Calls action() to execute the primitive """
1879 logging_text
= "Task ns={} _terminate_action={} ".format(nsr_id
, nslcmop_id
)
1880 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1883 for vnfr
in db_vnfrs_list
:
1884 vnfd_id
= vnfr
["vnfd-id"]
1885 vnf_index
= vnfr
["member-vnf-index-ref"]
1886 if vnfd_id
not in db_vnfds
:
1887 step
= "Getting vnfd={} id='{}' from db".format(vnfd_id
, vnfd_id
)
1888 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
1889 db_vnfds
[vnfd_id
] = vnfd
1890 vnfd
= db_vnfds
[vnfd_id
]
1891 if not self
._has
_terminate
_config
_primitive
(vnfd
):
1893 # Get the primitive's sorted sequence list
1894 seq_list
= self
._get
_terminate
_config
_primitive
_seq
_list
(vnfd
)
1895 for seq
in seq_list
:
1896 # For each sequence in list, get primitive and call _ns_execute_primitive()
1897 step
= "Calling terminate action for vnf_member_index={} primitive={}".format(
1898 vnf_index
, seq
.get("name"))
1899 self
.logger
.debug(logging_text
+ step
)
1900 # Create the primitive for each sequence, i.e. "primitive": "touch"
1901 primitive
= seq
.get('name')
1902 mapped_primitive_params
= self
._get
_terminate
_primitive
_params
(seq
, vnf_index
)
1903 # The following 3 parameters are currently set to None for 'terminate':
1904 # vdu_id, vdu_count_index, vdu_name
1905 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
1906 vdu_count_index
= db_nslcmop
["operationParams"].get("vdu_count_index")
1907 vdu_name
= db_nslcmop
["operationParams"].get("vdu_name")
1909 self
._add
_suboperation
(db_nslcmop
,
1916 mapped_primitive_params
)
1917 # Sub-operations: Call _ns_execute_primitive() instead of action()
1918 # db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1919 # nsr_deployed = db_nsr["_admin"]["deployed"]
1921 # nslcmop_operation_state, nslcmop_operation_state_detail = await self.action(
1922 # nsr_id, nslcmop_terminate_action_id)
1923 # Launch Exception if action() returns other than ['COMPLETED', 'PARTIALLY_COMPLETED']
1924 # result_ok = ['COMPLETED', 'PARTIALLY_COMPLETED']
1925 # if result not in result_ok:
1926 # raise LcmException(
1927 # "terminate_primitive_action for vnf_member_index={}",
1928 # " primitive={} fails with error {}".format(
1929 # vnf_index, seq.get("name"), result_detail))
1934 await self
.n2vc
.exec_primitive(
1936 primitive_name
=primitive
,
1937 params_dict
=mapped_primitive_params
1939 except Exception as e
:
1940 self
.logger
.error('Error executing primitive {}: {}'.format(primitive
, e
))
1942 "terminate_primitive_action for vnf_member_index={}, primitive={} fails with error {}"
1943 .format(vnf_index
, seq
.get("name"), e
),
1946 async def terminate(self
, nsr_id
, nslcmop_id
):
1948 # Try to lock HA task here
1949 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
1950 if not task_is_locked_by_me
:
1953 logging_text
= "Task ns={} terminate={} ".format(nsr_id
, nslcmop_id
)
1954 self
.logger
.debug(logging_text
+ "Enter")
1958 failed_detail
= [] # annotates all failed error messages
1959 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
1960 "_admin.current-operation": nslcmop_id
,
1961 "_admin.operation-type": "terminate"}
1962 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1963 db_nslcmop_update
= {}
1964 nslcmop_operation_state
= None
1965 autoremove
= False # autoremove after terminated
1968 # wait for any previous tasks in process
1969 step
= "Waiting for previous operations to terminate"
1970 await self
.lcm_tasks
.waitfor_related_HA("ns", 'nslcmops', nslcmop_id
)
1972 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
1973 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1974 step
= "Getting nsr={} from db".format(nsr_id
)
1975 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1976 # nsd = db_nsr["nsd"]
1977 nsr_deployed
= deepcopy(db_nsr
["_admin"].get("deployed"))
1978 if db_nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
1980 # #TODO check if VIM is creating and wait
1981 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
1982 # Call internal terminate action
1983 await self
._terminate
_action
(db_nslcmop
, nslcmop_id
, nsr_id
)
1987 db_nsr_update
["operational-status"] = "terminating"
1988 db_nsr_update
["config-status"] = "terminating"
1992 step
= "delete execution environment"
1993 self
.logger
.debug(logging_text
+ step
)
1995 task_delete_ee
= asyncio
.ensure_future(self
.n2vc
.delete_namespace(namespace
="." + nsr_id
))
1996 pending_tasks
.append(task_delete_ee
)
1997 except Exception as e
:
1998 msg
= "Failed while deleting NS in VCA: {}".format(e
)
1999 self
.logger
.error(msg
)
2000 failed_detail
.append(msg
)
2003 # Delete from k8scluster
2004 step
= "delete kdus"
2005 self
.logger
.debug(logging_text
+ step
)
2008 for kdu
in nsr_deployed
.get("K8s"):
2009 if kdu
.get("k8scluster-type") == "chart":
2010 task_delete_kdu_instance
= asyncio
.ensure_future(self
.k8sclusterhelm
.uninstall(
2011 cluster_uuid
=kdu
.get("k8scluster-uuid"), kdu_instance
=kdu
.get("kdu-instance")))
2012 elif kdu
.get("k8scluster-type") == "juju":
2013 # TODO Juju connector needed
2016 msg
= "k8scluster-type not defined"
2017 raise LcmException(msg
)
2019 pending_tasks
.append(task_delete_kdu_instance
)
2020 except LcmException
as e
:
2021 msg
= "Failed while deleting KDUs from NS: {}".format(e
)
2022 self
.logger
.error(msg
)
2023 failed_detail
.append(msg
)
2029 RO_nsr_id
= RO_delete_action
= None
2030 if nsr_deployed
and nsr_deployed
.get("RO"):
2031 RO_nsr_id
= nsr_deployed
["RO"].get("nsr_id")
2032 RO_delete_action
= nsr_deployed
["RO"].get("nsr_delete_action_id")
2035 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] = \
2036 "Deleting ns from VIM"
2037 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2038 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2039 self
.logger
.debug(logging_text
+ step
)
2040 desc
= await self
.RO
.delete("ns", RO_nsr_id
)
2041 RO_delete_action
= desc
["action_id"]
2042 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = RO_delete_action
2043 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
2044 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
2045 if RO_delete_action
:
2046 # wait until NS is deleted from VIM
2047 step
= detailed_status
= "Waiting ns deleted from VIM. RO_id={} RO_delete_action={}".\
2048 format(RO_nsr_id
, RO_delete_action
)
2049 detailed_status_old
= None
2050 self
.logger
.debug(logging_text
+ step
)
2052 delete_timeout
= 20 * 60 # 20 minutes
2053 while delete_timeout
> 0:
2054 desc
= await self
.RO
.show(
2056 item_id_name
=RO_nsr_id
,
2057 extra_item
="action",
2058 extra_item_id
=RO_delete_action
)
2059 ns_status
, ns_status_info
= self
.RO
.check_action_status(desc
)
2060 if ns_status
== "ERROR":
2061 raise ROclient
.ROClientException(ns_status_info
)
2062 elif ns_status
== "BUILD":
2063 detailed_status
= step
+ "; {}".format(ns_status_info
)
2064 elif ns_status
== "ACTIVE":
2065 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
2066 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
2069 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
2070 if detailed_status
!= detailed_status_old
:
2071 detailed_status_old
= db_nslcmop_update
["detailed-status"] = \
2072 db_nsr_update
["detailed-status"] = detailed_status
2073 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2074 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2075 await asyncio
.sleep(5, loop
=self
.loop
)
2077 else: # delete_timeout <= 0:
2078 raise ROclient
.ROClientException("Timeout waiting ns deleted from VIM")
2080 except ROclient
.ROClientException
as e
:
2081 if e
.http_code
== 404: # not found
2082 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
2083 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
2084 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
2085 self
.logger
.debug(logging_text
+ "RO_ns_id={} already deleted".format(RO_nsr_id
))
2086 elif e
.http_code
== 409: # conflict
2087 failed_detail
.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id
, e
))
2088 self
.logger
.debug(logging_text
+ failed_detail
[-1])
2091 failed_detail
.append("RO_ns_id={} delete error: {}".format(RO_nsr_id
, e
))
2092 self
.logger
.error(logging_text
+ failed_detail
[-1])
2096 if not RO_fail
and nsr_deployed
and nsr_deployed
.get("RO") and nsr_deployed
["RO"].get("nsd_id"):
2097 RO_nsd_id
= nsr_deployed
["RO"]["nsd_id"]
2099 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
2100 "Deleting nsd from RO"
2101 await self
.RO
.delete("nsd", RO_nsd_id
)
2102 self
.logger
.debug(logging_text
+ "RO_nsd_id={} deleted".format(RO_nsd_id
))
2103 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
2104 except ROclient
.ROClientException
as e
:
2105 if e
.http_code
== 404: # not found
2106 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
2107 self
.logger
.debug(logging_text
+ "RO_nsd_id={} already deleted".format(RO_nsd_id
))
2108 elif e
.http_code
== 409: # conflict
2109 failed_detail
.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id
, e
))
2110 self
.logger
.debug(logging_text
+ failed_detail
[-1])
2113 failed_detail
.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id
, e
))
2114 self
.logger
.error(logging_text
+ failed_detail
[-1])
2117 if not RO_fail
and nsr_deployed
and nsr_deployed
.get("RO") and nsr_deployed
["RO"].get("vnfd"):
2118 for index
, vnf_deployed
in enumerate(nsr_deployed
["RO"]["vnfd"]):
2119 if not vnf_deployed
or not vnf_deployed
["id"]:
2122 RO_vnfd_id
= vnf_deployed
["id"]
2123 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
2124 "Deleting member_vnf_index={} RO_vnfd_id={} from RO".format(
2125 vnf_deployed
["member-vnf-index"], RO_vnfd_id
)
2126 await self
.RO
.delete("vnfd", RO_vnfd_id
)
2127 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} deleted".format(RO_vnfd_id
))
2128 db_nsr_update
["_admin.deployed.RO.vnfd.{}.id".format(index
)] = None
2129 except ROclient
.ROClientException
as e
:
2130 if e
.http_code
== 404: # not found
2131 db_nsr_update
["_admin.deployed.RO.vnfd.{}.id".format(index
)] = None
2132 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} already deleted ".format(RO_vnfd_id
))
2133 elif e
.http_code
== 409: # conflict
2134 failed_detail
.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id
, e
))
2135 self
.logger
.debug(logging_text
+ failed_detail
[-1])
2137 failed_detail
.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id
, e
))
2138 self
.logger
.error(logging_text
+ failed_detail
[-1])
2141 self
.logger
.error(logging_text
+ " ;".join(failed_detail
))
2142 db_nsr_update
["operational-status"] = "failed"
2143 db_nsr_update
["detailed-status"] = "Deletion errors " + "; ".join(failed_detail
)
2144 db_nslcmop_update
["detailed-status"] = "; ".join(failed_detail
)
2145 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2146 db_nslcmop_update
["statusEnteredTime"] = time()
2148 db_nsr_update
["operational-status"] = "terminated"
2149 db_nsr_update
["detailed-status"] = "Done"
2150 db_nsr_update
["_admin.nsState"] = "NOT_INSTANTIATED"
2151 db_nslcmop_update
["detailed-status"] = "Done"
2152 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
2153 db_nslcmop_update
["statusEnteredTime"] = time()
2154 if db_nslcmop
["operationParams"].get("autoremove"):
2157 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
2158 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
2160 except asyncio
.CancelledError
:
2161 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
2162 exc
= "Operation was cancelled"
2163 except Exception as e
:
2164 exc
= traceback
.format_exc()
2165 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
2167 if exc
and db_nslcmop
:
2168 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
2169 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2170 db_nslcmop_update
["statusEnteredTime"] = time()
2172 if db_nslcmop
and db_nslcmop_update
:
2173 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2175 db_nsr_update
["_admin.nslcmop"] = None
2176 db_nsr_update
["_admin.current-operation"] = None
2177 db_nsr_update
["_admin.operation-type"] = None
2178 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2179 except DbException
as e
:
2180 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
2181 if nslcmop_operation_state
:
2183 await self
.msg
.aiowrite("ns", "terminated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2184 "operationState": nslcmop_operation_state
,
2185 "autoremove": autoremove
},
2187 except Exception as e
:
2188 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
2190 # wait for pending tasks
2194 self
.logger
.debug(logging_text
+ 'Waiting for terminate pending tasks...')
2195 done
, pending
= await asyncio
.wait(pending_tasks
, timeout
=3600)
2197 self
.logger
.debug(logging_text
+ 'All tasks finished...')
2199 self
.logger
.info(logging_text
+ 'There are pending tasks: {}'.format(pending
))
2201 self
.logger
.debug(logging_text
+ "Exit")
2202 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_terminate")
2205 def _map_primitive_params(primitive_desc
, params
, instantiation_params
):
2207 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
2208 The default-value is used. If it is between < > it look for a value at instantiation_params
2209 :param primitive_desc: portion of VNFD/NSD that describes primitive
2210 :param params: Params provided by user
2211 :param instantiation_params: Instantiation params provided by user
2212 :return: a dictionary with the calculated params
2214 calculated_params
= {}
2215 for parameter
in primitive_desc
.get("parameter", ()):
2216 param_name
= parameter
["name"]
2217 if param_name
in params
:
2218 calculated_params
[param_name
] = params
[param_name
]
2219 elif "default-value" in parameter
or "value" in parameter
:
2220 if "value" in parameter
:
2221 calculated_params
[param_name
] = parameter
["value"]
2223 calculated_params
[param_name
] = parameter
["default-value"]
2224 if isinstance(calculated_params
[param_name
], str) and calculated_params
[param_name
].startswith("<") \
2225 and calculated_params
[param_name
].endswith(">"):
2226 if calculated_params
[param_name
][1:-1] in instantiation_params
:
2227 calculated_params
[param_name
] = instantiation_params
[calculated_params
[param_name
][1:-1]]
2229 raise LcmException("Parameter {} needed to execute primitive {} not provided".
2230 format(calculated_params
[param_name
], primitive_desc
["name"]))
2232 raise LcmException("Parameter {} needed to execute primitive {} not provided".
2233 format(param_name
, primitive_desc
["name"]))
2235 if isinstance(calculated_params
[param_name
], (dict, list, tuple)):
2236 calculated_params
[param_name
] = yaml
.safe_dump(calculated_params
[param_name
], default_flow_style
=True,
2238 elif isinstance(calculated_params
[param_name
], str) and calculated_params
[param_name
].startswith("!!yaml "):
2239 calculated_params
[param_name
] = calculated_params
[param_name
][7:]
2241 # add always ns_config_info if primitive name is config
2242 if primitive_desc
["name"] == "config":
2243 if "ns_config_info" in instantiation_params
:
2244 calculated_params
["ns_config_info"] = instantiation_params
["ns_config_info"]
2245 return calculated_params
2247 async def _ns_execute_primitive(self
, db_deployed
, member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
,
2248 primitive
, primitive_params
, retries
=0, retries_interval
=30) -> (str, str):
2250 # find vca_deployed record for this action
2252 for vca_deployed
in db_deployed
["VCA"]:
2253 if not vca_deployed
:
2255 if member_vnf_index
!= vca_deployed
["member-vnf-index"] or vdu_id
!= vca_deployed
["vdu_id"]:
2257 if vdu_name
and vdu_name
!= vca_deployed
["vdu_name"]:
2259 if vdu_count_index
and vdu_count_index
!= vca_deployed
["vdu_count_index"]:
2263 # vca_deployed not found
2264 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} is not "
2265 "deployed".format(member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
))
2268 ee_id
= vca_deployed
.get("ee_id")
2270 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} has not "
2271 "execution environment"
2272 .format(member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
))
2274 if primitive
== "config":
2275 primitive_params
= {"params": primitive_params
}
2279 output
= await self
.n2vc
.exec_primitive(
2281 primitive_name
=primitive
,
2282 params_dict
=primitive_params
2286 except Exception as e
:
2289 self
.logger
.debug('Error executing action {} on {} -> {}'.format(primitive
, ee_id
, e
))
2291 await asyncio
.sleep(retries_interval
, loop
=self
.loop
)
2293 return 'Cannot execute action {} on {}: {}'.format(primitive
, ee_id
, e
), 'FAIL'
2297 except Exception as e
:
2298 return 'Error executing action {}: {}'.format(primitive
, e
), 'FAIL'
2300 async def action(self
, nsr_id
, nslcmop_id
):
2302 # Try to lock HA task here
2303 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
2304 if not task_is_locked_by_me
:
2307 logging_text
= "Task ns={} action={} ".format(nsr_id
, nslcmop_id
)
2308 self
.logger
.debug(logging_text
+ "Enter")
2309 # get all needed from database
2312 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
2313 "_admin.current-operation": nslcmop_id
,
2314 "_admin.operation-type": "action"}
2315 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2316 db_nslcmop_update
= {}
2317 nslcmop_operation_state
= None
2318 nslcmop_operation_state_detail
= None
2321 # wait for any previous tasks in process
2322 step
= "Waiting for previous operations to terminate"
2323 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
2325 step
= "Getting information from database"
2326 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
2327 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2329 nsr_deployed
= db_nsr
["_admin"].get("deployed")
2330 vnf_index
= db_nslcmop
["operationParams"].get("member_vnf_index")
2331 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
2332 kdu_name
= db_nslcmop
["operationParams"].get("kdu_name")
2333 vdu_count_index
= db_nslcmop
["operationParams"].get("vdu_count_index")
2334 vdu_name
= db_nslcmop
["operationParams"].get("vdu_name")
2337 step
= "Getting vnfr from database"
2338 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
2339 step
= "Getting vnfd from database"
2340 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
2342 if db_nsr
.get("nsd"):
2343 db_nsd
= db_nsr
.get("nsd") # TODO this will be removed
2345 step
= "Getting nsd from database"
2346 db_nsd
= self
.db
.get_one("nsds", {"_id": db_nsr
["nsd-id"]})
2348 # for backward compatibility
2349 if nsr_deployed
and isinstance(nsr_deployed
.get("VCA"), dict):
2350 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
2351 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
2352 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2354 primitive
= db_nslcmop
["operationParams"]["primitive"]
2355 primitive_params
= db_nslcmop
["operationParams"]["primitive_params"]
2357 # look for primitive
2358 config_primitive_desc
= None
2360 for vdu
in get_iterable(db_vnfd
, "vdu"):
2361 if vdu_id
== vdu
["id"]:
2362 for config_primitive
in vdu
.get("vdu-configuration", {}).get("config-primitive", ()):
2363 if config_primitive
["name"] == primitive
:
2364 config_primitive_desc
= config_primitive
2367 self
.logger
.debug(logging_text
+ "Checking actions in KDUs")
2370 if db_vnfr
.get("additionalParamsForVnf") and db_vnfr
["additionalParamsForVnf"].\
2371 get("member-vnf-index") == vnf_index
:
2372 desc_params
= self
._format
_additional
_params
(db_vnfr
["additionalParamsForVnf"].
2373 get("additionalParams"))
2374 if primitive_params
:
2375 desc_params
.update(primitive_params
)
2376 # TODO Check if we will need something at vnf level
2378 for kdu
in get_iterable(nsr_deployed
, "K8s"):
2379 if kdu_name
== kdu
["kdu-name"]:
2380 db_dict
= {"collection": "nsrs", "filter": {"_id": nsr_id
},
2381 "path": "_admin.deployed.K8s.{}".format(index
)}
2382 if primitive
== "upgrade":
2383 if desc_params
.get("kdu_model"):
2384 kdu_model
= desc_params
.get("kdu_model")
2385 del desc_params
["kdu_model"]
2387 kdu_model
= kdu
.get("kdu-model")
2388 parts
= kdu_model
.split(sep
=":")
2390 kdu_model
= parts
[0]
2392 if kdu
.get("k8scluster-type") == "chart":
2393 output
= await self
.k8sclusterhelm
.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
,
2398 elif kdu
.get("k8scluster-type") == "juju":
2399 # TODO Juju connector needed
2402 msg
= "k8scluster-type not defined"
2403 raise LcmException(msg
)
2405 self
.logger
.debug(logging_text
+ " Upgrade of kdu {} done".format(output
))
2407 elif primitive
== "rollback":
2408 if kdu
.get("k8scluster-type") == "chart":
2409 output
= await self
.k8sclusterhelm
.rollback(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2410 kdu_instance
=kdu
.get("kdu-instance"),
2412 elif kdu
.get("k8scluster-type") == "juju":
2413 # TODO Juju connector needed
2416 msg
= "k8scluster-type not defined"
2417 raise LcmException(msg
)
2419 elif primitive
== "status":
2420 if kdu
.get("k8scluster-type") == "chart":
2421 output
= await self
.k8sclusterhelm
.status_kdu(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2422 kdu_instance
=kdu
.get("kdu-instance"))
2423 elif kdu
.get("k8scluster-type") == "juju":
2424 # TODO Juju connector needed
2427 msg
= "k8scluster-type not defined"
2428 raise LcmException(msg
)
2433 raise LcmException("KDU '{}' not found".format(kdu_name
))
2435 db_nslcmop_update
["detailed-status"] = output
2436 db_nslcmop_update
["operationState"] = 'COMPLETED'
2437 db_nslcmop_update
["statusEnteredTime"] = time()
2439 db_nslcmop_update
["detailed-status"] = ''
2440 db_nslcmop_update
["operationState"] = 'FAILED'
2441 db_nslcmop_update
["statusEnteredTime"] = time()
2444 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
2445 if config_primitive
["name"] == primitive
:
2446 config_primitive_desc
= config_primitive
2449 for config_primitive
in db_nsd
.get("ns-configuration", {}).get("config-primitive", ()):
2450 if config_primitive
["name"] == primitive
:
2451 config_primitive_desc
= config_primitive
2454 if not config_primitive_desc
:
2455 raise LcmException("Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".
2460 if db_vnfr
.get("additionalParamsForVnf"):
2461 desc_params
.update(db_vnfr
["additionalParamsForVnf"])
2463 if db_nsr
.get("additionalParamsForNs"):
2464 desc_params
.update(db_nsr
["additionalParamsForNs"])
2466 # TODO check if ns is in a proper status
2467 output
, detail
= await self
._ns
_execute
_primitive
(
2468 db_deployed
=nsr_deployed
,
2469 member_vnf_index
=vnf_index
,
2472 vdu_count_index
=vdu_count_index
,
2473 primitive
=primitive
,
2474 primitive_params
=self
._map
_primitive
_params
(config_primitive_desc
, primitive_params
, desc_params
))
2476 detailed_status
= output
2478 result
= 'COMPLETED'
2482 db_nslcmop_update
["detailed-status"] = nslcmop_operation_state_detail
= detailed_status
2483 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= result
2484 db_nslcmop_update
["statusEnteredTime"] = time()
2485 self
.logger
.debug(logging_text
+ " task Done with result {} {}".format(result
, detailed_status
))
2486 return # database update is called inside finally
2488 except (DbException
, LcmException
) as e
:
2489 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
2491 except asyncio
.CancelledError
:
2492 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
2493 exc
= "Operation was cancelled"
2494 except Exception as e
:
2495 exc
= traceback
.format_exc()
2496 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
2498 if exc
and db_nslcmop
:
2499 db_nslcmop_update
["detailed-status"] = nslcmop_operation_state_detail
= \
2500 "FAILED {}: {}".format(step
, exc
)
2501 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2502 db_nslcmop_update
["statusEnteredTime"] = time()
2504 if db_nslcmop_update
:
2505 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2507 db_nsr_update
["_admin.nslcmop"] = None
2508 db_nsr_update
["_admin.operation-type"] = None
2509 db_nsr_update
["_admin.nslcmop"] = None
2510 db_nsr_update
["_admin.current-operation"] = None
2511 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2512 except DbException
as e
:
2513 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
2514 self
.logger
.debug(logging_text
+ "Exit")
2515 if nslcmop_operation_state
:
2517 await self
.msg
.aiowrite("ns", "actioned", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2518 "operationState": nslcmop_operation_state
},
2520 except Exception as e
:
2521 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
2522 self
.logger
.debug(logging_text
+ "Exit")
2523 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_action")
2524 return nslcmop_operation_state
, nslcmop_operation_state_detail
2526 async def scale(self
, nsr_id
, nslcmop_id
):
2528 # Try to lock HA task here
2529 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
2530 if not task_is_locked_by_me
:
2533 logging_text
= "Task ns={} scale={} ".format(nsr_id
, nslcmop_id
)
2534 self
.logger
.debug(logging_text
+ "Enter")
2535 # get all needed from database
2538 db_nslcmop_update
= {}
2539 nslcmop_operation_state
= None
2540 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
2541 "_admin.current-operation": nslcmop_id
,
2542 "_admin.operation-type": "scale"}
2543 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2545 # in case of error, indicates what part of scale was failed to put nsr at error status
2546 scale_process
= None
2547 old_operational_status
= ""
2548 old_config_status
= ""
2551 # wait for any previous tasks in process
2552 step
= "Waiting for previous operations to terminate"
2553 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
2555 step
= "Getting nslcmop from database"
2556 self
.logger
.debug(step
+ " after having waited for previous tasks to be completed")
2557 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
2558 step
= "Getting nsr from database"
2559 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2561 old_operational_status
= db_nsr
["operational-status"]
2562 old_config_status
= db_nsr
["config-status"]
2563 step
= "Parsing scaling parameters"
2564 # self.logger.debug(step)
2565 db_nsr_update
["operational-status"] = "scaling"
2566 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2567 nsr_deployed
= db_nsr
["_admin"].get("deployed")
2570 nsr_deployed
= db_nsr
["_admin"].get("deployed")
2571 vnf_index
= db_nslcmop
["operationParams"].get("member_vnf_index")
2572 # vdu_id = db_nslcmop["operationParams"].get("vdu_id")
2573 # vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
2574 # vdu_name = db_nslcmop["operationParams"].get("vdu_name")
2577 RO_nsr_id
= nsr_deployed
["RO"]["nsr_id"]
2578 vnf_index
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
2579 scaling_group
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
2580 scaling_type
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleVnfType"]
2581 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
2583 # for backward compatibility
2584 if nsr_deployed
and isinstance(nsr_deployed
.get("VCA"), dict):
2585 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
2586 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
2587 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2589 step
= "Getting vnfr from database"
2590 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
2591 step
= "Getting vnfd from database"
2592 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
2594 step
= "Getting scaling-group-descriptor"
2595 for scaling_descriptor
in db_vnfd
["scaling-group-descriptor"]:
2596 if scaling_descriptor
["name"] == scaling_group
:
2599 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
2600 "at vnfd:scaling-group-descriptor".format(scaling_group
))
2603 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
2604 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
2605 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
2608 # TODO check if ns is in a proper status
2609 step
= "Sending scale order to VIM"
2611 if not db_nsr
["_admin"].get("scaling-group"):
2612 self
.update_db_2("nsrs", nsr_id
, {"_admin.scaling-group": [{"name": scaling_group
, "nb-scale-op": 0}]})
2613 admin_scale_index
= 0
2615 for admin_scale_index
, admin_scale_info
in enumerate(db_nsr
["_admin"]["scaling-group"]):
2616 if admin_scale_info
["name"] == scaling_group
:
2617 nb_scale_op
= admin_scale_info
.get("nb-scale-op", 0)
2619 else: # not found, set index one plus last element and add new entry with the name
2620 admin_scale_index
+= 1
2621 db_nsr_update
["_admin.scaling-group.{}.name".format(admin_scale_index
)] = scaling_group
2622 RO_scaling_info
= []
2623 vdu_scaling_info
= {"scaling_group_name": scaling_group
, "vdu": []}
2624 if scaling_type
== "SCALE_OUT":
2625 # count if max-instance-count is reached
2626 max_instance_count
= scaling_descriptor
.get("max-instance-count", 10)
2627 # self.logger.debug("MAX_INSTANCE_COUNT is {}".format(max_instance_count))
2628 if nb_scale_op
>= max_instance_count
:
2629 raise LcmException("reached the limit of {} (max-instance-count) "
2630 "scaling-out operations for the "
2631 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
2634 vdu_scaling_info
["scaling_direction"] = "OUT"
2635 vdu_scaling_info
["vdu-create"] = {}
2636 for vdu_scale_info
in scaling_descriptor
["vdu"]:
2637 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
2638 "type": "create", "count": vdu_scale_info
.get("count", 1)})
2639 vdu_scaling_info
["vdu-create"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
2641 elif scaling_type
== "SCALE_IN":
2642 # count if min-instance-count is reached
2643 min_instance_count
= 0
2644 if "min-instance-count" in scaling_descriptor
and scaling_descriptor
["min-instance-count"] is not None:
2645 min_instance_count
= int(scaling_descriptor
["min-instance-count"])
2646 if nb_scale_op
<= min_instance_count
:
2647 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
2648 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
2650 vdu_scaling_info
["scaling_direction"] = "IN"
2651 vdu_scaling_info
["vdu-delete"] = {}
2652 for vdu_scale_info
in scaling_descriptor
["vdu"]:
2653 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
2654 "type": "delete", "count": vdu_scale_info
.get("count", 1)})
2655 vdu_scaling_info
["vdu-delete"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
2657 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
2658 vdu_create
= vdu_scaling_info
.get("vdu-create")
2659 vdu_delete
= copy(vdu_scaling_info
.get("vdu-delete"))
2660 if vdu_scaling_info
["scaling_direction"] == "IN":
2661 for vdur
in reversed(db_vnfr
["vdur"]):
2662 if vdu_delete
.get(vdur
["vdu-id-ref"]):
2663 vdu_delete
[vdur
["vdu-id-ref"]] -= 1
2664 vdu_scaling_info
["vdu"].append({
2665 "name": vdur
["name"],
2666 "vdu_id": vdur
["vdu-id-ref"],
2669 for interface
in vdur
["interfaces"]:
2670 vdu_scaling_info
["vdu"][-1]["interface"].append({
2671 "name": interface
["name"],
2672 "ip_address": interface
["ip-address"],
2673 "mac_address": interface
.get("mac-address"),
2675 vdu_delete
= vdu_scaling_info
.pop("vdu-delete")
2678 step
= "Executing pre-scale vnf-config-primitive"
2679 if scaling_descriptor
.get("scaling-config-action"):
2680 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
2681 if (scaling_config_action
.get("trigger") == "pre-scale-in" and scaling_type
== "SCALE_IN") \
2682 or (scaling_config_action
.get("trigger") == "pre-scale-out" and scaling_type
== "SCALE_OUT"):
2683 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
2684 step
= db_nslcmop_update
["detailed-status"] = \
2685 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive
)
2687 # look for primitive
2688 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
2689 if config_primitive
["name"] == vnf_config_primitive
:
2693 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
2694 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
2695 "primitive".format(scaling_group
, config_primitive
))
2697 vnfr_params
= {"VDU_SCALE_INFO": vdu_scaling_info
}
2698 if db_vnfr
.get("additionalParamsForVnf"):
2699 vnfr_params
.update(db_vnfr
["additionalParamsForVnf"])
2701 scale_process
= "VCA"
2702 db_nsr_update
["config-status"] = "configuring pre-scaling"
2703 primitive_params
= self
._map
_primitive
_params
(config_primitive
, {}, vnfr_params
)
2705 # Pre-scale reintent check: Check if this sub-operation has been executed before
2706 op_index
= self
._check
_or
_add
_scale
_suboperation
(
2707 db_nslcmop
, nslcmop_id
, vnf_index
, vnf_config_primitive
, primitive_params
, 'PRE-SCALE')
2708 if (op_index
== self
.SUBOPERATION_STATUS_SKIP
):
2709 # Skip sub-operation
2710 result
= 'COMPLETED'
2711 result_detail
= 'Done'
2712 self
.logger
.debug(logging_text
+
2713 "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
2714 vnf_config_primitive
, result
, result_detail
))
2716 if (op_index
== self
.SUBOPERATION_STATUS_NEW
):
2717 # New sub-operation: Get index of this sub-operation
2718 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
2719 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} New sub-operation".
2720 format(vnf_config_primitive
))
2722 # Reintent: Get registered params for this existing sub-operation
2723 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
2724 vnf_index
= op
.get('member_vnf_index')
2725 vnf_config_primitive
= op
.get('primitive')
2726 primitive_params
= op
.get('primitive_params')
2727 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Sub-operation reintent".
2728 format(vnf_config_primitive
))
2729 # Execute the primitive, either with new (first-time) or registered (reintent) args
2730 result
, result_detail
= await self
._ns
_execute
_primitive
(
2731 nsr_deployed
, vnf_index
, None, None, None, vnf_config_primitive
, primitive_params
)
2732 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
2733 vnf_config_primitive
, result
, result_detail
))
2734 # Update operationState = COMPLETED | FAILED
2735 self
._update
_suboperation
_status
(
2736 db_nslcmop
, op_index
, result
, result_detail
)
2738 if result
== "FAILED":
2739 raise LcmException(result_detail
)
2740 db_nsr_update
["config-status"] = old_config_status
2741 scale_process
= None
2745 # Should this block be skipped if 'RO_nsr_id' == None ?
2746 # if (RO_nsr_id and RO_scaling_info):
2748 scale_process
= "RO"
2749 # Scale RO reintent check: Check if this sub-operation has been executed before
2750 op_index
= self
._check
_or
_add
_scale
_suboperation
(
2751 db_nslcmop
, vnf_index
, None, None, 'SCALE-RO', RO_nsr_id
, RO_scaling_info
)
2752 if (op_index
== self
.SUBOPERATION_STATUS_SKIP
):
2753 # Skip sub-operation
2754 result
= 'COMPLETED'
2755 result_detail
= 'Done'
2756 self
.logger
.debug(logging_text
+ "Skipped sub-operation RO, result {} {}".format(
2757 result
, result_detail
))
2759 if (op_index
== self
.SUBOPERATION_STATUS_NEW
):
2760 # New sub-operation: Get index of this sub-operation
2761 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
2762 self
.logger
.debug(logging_text
+ "New sub-operation RO")
2764 # Reintent: Get registered params for this existing sub-operation
2765 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
2766 RO_nsr_id
= op
.get('RO_nsr_id')
2767 RO_scaling_info
= op
.get('RO_scaling_info')
2768 self
.logger
.debug(logging_text
+ "Sub-operation RO reintent".format(
2769 vnf_config_primitive
))
2771 RO_desc
= await self
.RO
.create_action("ns", RO_nsr_id
, {"vdu-scaling": RO_scaling_info
})
2772 db_nsr_update
["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index
)] = nb_scale_op
2773 db_nsr_update
["_admin.scaling-group.{}.time".format(admin_scale_index
)] = time()
2775 RO_nslcmop_id
= RO_desc
["instance_action_id"]
2776 db_nslcmop_update
["_admin.deploy.RO"] = RO_nslcmop_id
2778 RO_task_done
= False
2779 step
= detailed_status
= "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id
)
2780 detailed_status_old
= None
2781 self
.logger
.debug(logging_text
+ step
)
2783 deployment_timeout
= 1 * 3600 # One hour
2784 while deployment_timeout
> 0:
2785 if not RO_task_done
:
2786 desc
= await self
.RO
.show("ns", item_id_name
=RO_nsr_id
, extra_item
="action",
2787 extra_item_id
=RO_nslcmop_id
)
2788 ns_status
, ns_status_info
= self
.RO
.check_action_status(desc
)
2789 if ns_status
== "ERROR":
2790 raise ROclient
.ROClientException(ns_status_info
)
2791 elif ns_status
== "BUILD":
2792 detailed_status
= step
+ "; {}".format(ns_status_info
)
2793 elif ns_status
== "ACTIVE":
2795 step
= detailed_status
= "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id
)
2796 self
.logger
.debug(logging_text
+ step
)
2798 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
2801 if ns_status
== "ERROR":
2802 raise ROclient
.ROClientException(ns_status_info
)
2803 elif ns_status
== "BUILD":
2804 detailed_status
= step
+ "; {}".format(ns_status_info
)
2805 elif ns_status
== "ACTIVE":
2806 step
= detailed_status
= \
2807 "Waiting for management IP address reported by the VIM. Updating VNFRs"
2809 self
.scale_vnfr(db_vnfr
, vdu_create
=vdu_create
, vdu_delete
=vdu_delete
)
2812 desc
= await self
.RO
.show("ns", RO_nsr_id
)
2813 # nsr_deployed["nsr_ip"] = RO.get_ns_vnf_info(desc)
2814 self
.ns_update_vnfr({db_vnfr
["member-vnf-index-ref"]: db_vnfr
}, desc
)
2816 except LcmExceptionNoMgmtIP
:
2819 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
2820 if detailed_status
!= detailed_status_old
:
2821 self
._update
_suboperation
_status
(
2822 db_nslcmop
, op_index
, 'COMPLETED', detailed_status
)
2823 detailed_status_old
= db_nslcmop_update
["detailed-status"] = detailed_status
2824 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2826 await asyncio
.sleep(5, loop
=self
.loop
)
2827 deployment_timeout
-= 5
2828 if deployment_timeout
<= 0:
2829 self
._update
_suboperation
_status
(
2830 db_nslcmop
, nslcmop_id
, op_index
, 'FAILED', "Timeout when waiting for ns to get ready")
2831 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
2833 # update VDU_SCALING_INFO with the obtained ip_addresses
2834 if vdu_scaling_info
["scaling_direction"] == "OUT":
2835 for vdur
in reversed(db_vnfr
["vdur"]):
2836 if vdu_scaling_info
["vdu-create"].get(vdur
["vdu-id-ref"]):
2837 vdu_scaling_info
["vdu-create"][vdur
["vdu-id-ref"]] -= 1
2838 vdu_scaling_info
["vdu"].append({
2839 "name": vdur
["name"],
2840 "vdu_id": vdur
["vdu-id-ref"],
2843 for interface
in vdur
["interfaces"]:
2844 vdu_scaling_info
["vdu"][-1]["interface"].append({
2845 "name": interface
["name"],
2846 "ip_address": interface
["ip-address"],
2847 "mac_address": interface
.get("mac-address"),
2849 del vdu_scaling_info
["vdu-create"]
2851 self
._update
_suboperation
_status
(db_nslcmop
, op_index
, 'COMPLETED', 'Done')
2854 scale_process
= None
2856 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2859 # execute primitive service POST-SCALING
2860 step
= "Executing post-scale vnf-config-primitive"
2861 if scaling_descriptor
.get("scaling-config-action"):
2862 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
2863 if (scaling_config_action
.get("trigger") == "post-scale-in" and scaling_type
== "SCALE_IN") \
2864 or (scaling_config_action
.get("trigger") == "post-scale-out" and scaling_type
== "SCALE_OUT"):
2865 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
2866 step
= db_nslcmop_update
["detailed-status"] = \
2867 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive
)
2869 vnfr_params
= {"VDU_SCALE_INFO": vdu_scaling_info
}
2870 if db_vnfr
.get("additionalParamsForVnf"):
2871 vnfr_params
.update(db_vnfr
["additionalParamsForVnf"])
2873 # look for primitive
2874 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
2875 if config_primitive
["name"] == vnf_config_primitive
:
2878 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
2879 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
2880 "match any vnf-configuration:config-primitive".format(scaling_group
,
2882 scale_process
= "VCA"
2883 db_nsr_update
["config-status"] = "configuring post-scaling"
2884 primitive_params
= self
._map
_primitive
_params
(config_primitive
, {}, vnfr_params
)
2886 # Post-scale reintent check: Check if this sub-operation has been executed before
2887 op_index
= self
._check
_or
_add
_scale
_suboperation
(
2888 db_nslcmop
, nslcmop_id
, vnf_index
, vnf_config_primitive
, primitive_params
, 'POST-SCALE')
2889 if (op_index
== self
.SUBOPERATION_STATUS_SKIP
):
2890 # Skip sub-operation
2891 result
= 'COMPLETED'
2892 result_detail
= 'Done'
2893 self
.logger
.debug(logging_text
+
2894 "vnf_config_primitive={} Skipped sub-operation, result {} {}".
2895 format(vnf_config_primitive
, result
, result_detail
))
2897 if (op_index
== self
.SUBOPERATION_STATUS_NEW
):
2898 # New sub-operation: Get index of this sub-operation
2899 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
2900 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} New sub-operation".
2901 format(vnf_config_primitive
))
2903 # Reintent: Get registered params for this existing sub-operation
2904 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
2905 vnf_index
= op
.get('member_vnf_index')
2906 vnf_config_primitive
= op
.get('primitive')
2907 primitive_params
= op
.get('primitive_params')
2908 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Sub-operation reintent".
2909 format(vnf_config_primitive
))
2910 # Execute the primitive, either with new (first-time) or registered (reintent) args
2911 result
, result_detail
= await self
._ns
_execute
_primitive
(
2912 nsr_deployed
, vnf_index
, None, None, None, vnf_config_primitive
, primitive_params
)
2913 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
2914 vnf_config_primitive
, result
, result_detail
))
2915 # Update operationState = COMPLETED | FAILED
2916 self
._update
_suboperation
_status
(
2917 db_nslcmop
, op_index
, result
, result_detail
)
2919 if result
== "FAILED":
2920 raise LcmException(result_detail
)
2921 db_nsr_update
["config-status"] = old_config_status
2922 scale_process
= None
2925 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
2926 db_nslcmop_update
["statusEnteredTime"] = time()
2927 db_nslcmop_update
["detailed-status"] = "done"
2928 db_nsr_update
["detailed-status"] = "" # "scaled {} {}".format(scaling_group, scaling_type)
2929 db_nsr_update
["operational-status"] = "running" if old_operational_status
== "failed" \
2930 else old_operational_status
2931 db_nsr_update
["config-status"] = old_config_status
2933 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
2934 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
2936 except asyncio
.CancelledError
:
2937 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
2938 exc
= "Operation was cancelled"
2939 except Exception as e
:
2940 exc
= traceback
.format_exc()
2941 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
2945 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
2946 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2947 db_nslcmop_update
["statusEnteredTime"] = time()
2949 db_nsr_update
["operational-status"] = old_operational_status
2950 db_nsr_update
["config-status"] = old_config_status
2951 db_nsr_update
["detailed-status"] = ""
2952 db_nsr_update
["_admin.nslcmop"] = None
2954 if "VCA" in scale_process
:
2955 db_nsr_update
["config-status"] = "failed"
2956 if "RO" in scale_process
:
2957 db_nsr_update
["operational-status"] = "failed"
2958 db_nsr_update
["detailed-status"] = "FAILED scaling nslcmop={} {}: {}".format(nslcmop_id
, step
,
2961 if db_nslcmop
and db_nslcmop_update
:
2962 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2964 db_nsr_update
["_admin.current-operation"] = None
2965 db_nsr_update
["_admin.operation-type"] = None
2966 db_nsr_update
["_admin.nslcmop"] = None
2967 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2968 except DbException
as e
:
2969 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
2970 if nslcmop_operation_state
:
2972 await self
.msg
.aiowrite("ns", "scaled", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2973 "operationState": nslcmop_operation_state
},
2976 # await asyncio.sleep(cooldown_time, loop=self.loop)
2977 # await self.msg.aiowrite("ns","scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
2978 except Exception as e
:
2979 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
2980 self
.logger
.debug(logging_text
+ "Exit")
2981 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_scale")