1 # -*- coding: utf-8 -*-
4 # Copyright 2018 Telefonica S.A.
6 # Licensed under the Apache License, Version 2.0 (the "License"); you may
7 # not use this file except in compliance with the License. You may obtain
8 # a copy of the License at
10 # http://www.apache.org/licenses/LICENSE-2.0
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 # License for the specific language governing permissions and limitations
22 import logging
.handlers
24 from jinja2
import Environment
, Template
, meta
, TemplateError
, TemplateNotFound
, TemplateSyntaxError
26 from osm_lcm
import ROclient
27 from osm_lcm
.lcm_utils
import LcmException
, LcmExceptionNoMgmtIP
, LcmBase
, deep_get
28 from n2vc
.k8s_helm_conn
import K8sHelmConnector
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
72 timeout_vca_on_error
= 5 * 60 # Time for charm from first time at blocked,error status to mark as failed
73 total_deploy_timeout
= 2 * 3600 # global timeout for deployment
74 timeout_charm_delete
= 10 * 60
75 timeout_primitive
= 10 * 60 # timeout for primitive execution
77 SUBOPERATION_STATUS_NOT_FOUND
= -1
78 SUBOPERATION_STATUS_NEW
= -2
79 SUBOPERATION_STATUS_SKIP
= -3
81 def __init__(self
, db
, msg
, fs
, lcm_tasks
, ro_config
, vca_config
, loop
):
83 Init, Connect to database, filesystem storage, and messaging
84 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
91 logger
=logging
.getLogger('lcm.ns')
95 self
.lcm_tasks
= lcm_tasks
96 self
.ro_config
= ro_config
97 self
.vca_config
= vca_config
98 if 'pubkey' in self
.vca_config
:
99 self
.vca_config
['public_key'] = self
.vca_config
['pubkey']
100 if 'cacert' in self
.vca_config
:
101 self
.vca_config
['ca_cert'] = self
.vca_config
['cacert']
102 if 'apiproxy' in self
.vca_config
:
103 self
.vca_config
['api_proxy'] = self
.vca_config
['apiproxy']
105 # create N2VC connector
106 self
.n2vc
= N2VCJujuConnector(
111 url
='{}:{}'.format(self
.vca_config
['host'], self
.vca_config
['port']),
112 username
=self
.vca_config
.get('user', None),
113 vca_config
=self
.vca_config
,
114 on_update_db
=self
._on
_update
_n
2vc
_db
,
115 # ca_cert=self.vca_config.get('cacert'),
116 # api_proxy=self.vca_config.get('apiproxy'),
119 self
.k8sclusterhelm
= K8sHelmConnector(
120 kubectl_command
=self
.vca_config
.get("kubectlpath"),
121 helm_command
=self
.vca_config
.get("helmpath"),
129 self
.RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
131 def _on_update_n2vc_db(self
, table
, filter, path
, updated_data
):
133 self
.logger
.debug('_on_update_n2vc_db(table={}, filter={}, path={}, updated_data={}'
134 .format(table
, filter, path
, updated_data
))
137 # write NS status to database
139 # # nsrs_id = filter.get('_id')
142 # nsr = self.db.get_one(table=table, q_filter=filter)
143 # # get VCA deployed list
144 # vca_list = deep_get(target_dict=nsr, key_list=('_admin', 'deployed', 'VCA'))
146 # # ro_list = deep_get(target_dict=nsr, key_list=('_admin', 'deployed', 'RO'))
147 # for vca in vca_list:
148 # # status = vca.get('status')
150 # # detailed_status = vca.get('detailed-status')
151 # # print(detailed_status)
152 # # for ro in ro_list:
155 # except Exception as e:
156 # self.logger.error('Error writing NS status to db: {}'.format(e))
158 def vnfd2RO(self
, vnfd
, new_id
=None, additionalParams
=None, nsrId
=None):
160 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
161 :param vnfd: input vnfd
162 :param new_id: overrides vnf id if provided
163 :param additionalParams: Instantiation params for VNFs provided
164 :param nsrId: Id of the NSR
165 :return: copy of vnfd
168 vnfd_RO
= deepcopy(vnfd
)
169 # remove unused by RO configuration, monitoring, scaling and internal keys
170 vnfd_RO
.pop("_id", None)
171 vnfd_RO
.pop("_admin", None)
172 vnfd_RO
.pop("vnf-configuration", None)
173 vnfd_RO
.pop("monitoring-param", None)
174 vnfd_RO
.pop("scaling-group-descriptor", None)
175 vnfd_RO
.pop("kdu", None)
176 vnfd_RO
.pop("k8s-cluster", None)
178 vnfd_RO
["id"] = new_id
180 # parse cloud-init or cloud-init-file with the provided variables using Jinja2
181 for vdu
in get_iterable(vnfd_RO
, "vdu"):
182 cloud_init_file
= None
183 if vdu
.get("cloud-init-file"):
184 base_folder
= vnfd
["_admin"]["storage"]
185 cloud_init_file
= "{}/{}/cloud_init/{}".format(base_folder
["folder"], base_folder
["pkg-dir"],
186 vdu
["cloud-init-file"])
187 with self
.fs
.file_open(cloud_init_file
, "r") as ci_file
:
188 cloud_init_content
= ci_file
.read()
189 vdu
.pop("cloud-init-file", None)
190 elif vdu
.get("cloud-init"):
191 cloud_init_content
= vdu
["cloud-init"]
196 ast
= env
.parse(cloud_init_content
)
197 mandatory_vars
= meta
.find_undeclared_variables(ast
)
199 for var
in mandatory_vars
:
200 if not additionalParams
or var
not in additionalParams
.keys():
201 raise LcmException("Variable '{}' defined at vnfd[id={}]:vdu[id={}]:cloud-init/cloud-init-"
202 "file, must be provided in the instantiation parameters inside the "
203 "'additionalParamsForVnf' block".format(var
, vnfd
["id"], vdu
["id"]))
204 template
= Template(cloud_init_content
)
205 cloud_init_content
= template
.render(additionalParams
or {})
206 vdu
["cloud-init"] = cloud_init_content
209 except FsException
as e
:
210 raise LcmException("Error reading vnfd[id={}]:vdu[id={}]:cloud-init-file={}: {}".
211 format(vnfd
["id"], vdu
["id"], cloud_init_file
, e
))
212 except (TemplateError
, TemplateNotFound
, TemplateSyntaxError
) as e
:
213 raise LcmException("Error parsing Jinja2 to cloud-init content at vnfd[id={}]:vdu[id={}]: {}".
214 format(vnfd
["id"], vdu
["id"], e
))
216 def ns_params_2_RO(self
, ns_params
, nsd
, vnfd_dict
, n2vc_key_list
):
218 Creates a RO ns descriptor from OSM ns_instantiate params
219 :param ns_params: OSM instantiate params
220 :return: The RO ns descriptor
224 # TODO feature 1417: Check that no instantiation is set over PDU
225 # check if PDU forces a concrete vim-network-id and add it
226 # check if PDU contains a SDN-assist info (dpid, switch, port) and pass it to RO
228 def vim_account_2_RO(vim_account
):
229 if vim_account
in vim_2_RO
:
230 return vim_2_RO
[vim_account
]
232 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_account
})
233 if db_vim
["_admin"]["operationalState"] != "ENABLED":
234 raise LcmException("VIM={} is not available. operationalState={}".format(
235 vim_account
, db_vim
["_admin"]["operationalState"]))
236 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
237 vim_2_RO
[vim_account
] = RO_vim_id
240 def wim_account_2_RO(wim_account
):
241 if isinstance(wim_account
, str):
242 if wim_account
in wim_2_RO
:
243 return wim_2_RO
[wim_account
]
245 db_wim
= self
.db
.get_one("wim_accounts", {"_id": wim_account
})
246 if db_wim
["_admin"]["operationalState"] != "ENABLED":
247 raise LcmException("WIM={} is not available. operationalState={}".format(
248 wim_account
, db_wim
["_admin"]["operationalState"]))
249 RO_wim_id
= db_wim
["_admin"]["deployed"]["RO-account"]
250 wim_2_RO
[wim_account
] = RO_wim_id
255 def ip_profile_2_RO(ip_profile
):
256 RO_ip_profile
= deepcopy((ip_profile
))
257 if "dns-server" in RO_ip_profile
:
258 if isinstance(RO_ip_profile
["dns-server"], list):
259 RO_ip_profile
["dns-address"] = []
260 for ds
in RO_ip_profile
.pop("dns-server"):
261 RO_ip_profile
["dns-address"].append(ds
['address'])
263 RO_ip_profile
["dns-address"] = RO_ip_profile
.pop("dns-server")
264 if RO_ip_profile
.get("ip-version") == "ipv4":
265 RO_ip_profile
["ip-version"] = "IPv4"
266 if RO_ip_profile
.get("ip-version") == "ipv6":
267 RO_ip_profile
["ip-version"] = "IPv6"
268 if "dhcp-params" in RO_ip_profile
:
269 RO_ip_profile
["dhcp"] = RO_ip_profile
.pop("dhcp-params")
275 # "name": ns_params["nsName"],
276 # "description": ns_params.get("nsDescription"),
277 "datacenter": vim_account_2_RO(ns_params
["vimAccountId"]),
278 "wim_account": wim_account_2_RO(ns_params
.get("wimAccountId")),
279 # "scenario": ns_params["nsdId"],
282 n2vc_key_list
= n2vc_key_list
or []
283 for vnfd_ref
, vnfd
in vnfd_dict
.items():
284 vdu_needed_access
= []
286 if vnfd
.get("vnf-configuration"):
287 ssh_required
= deep_get(vnfd
, ("vnf-configuration", "config-access", "ssh-access", "required"))
288 if ssh_required
and vnfd
.get("mgmt-interface"):
289 if vnfd
["mgmt-interface"].get("vdu-id"):
290 vdu_needed_access
.append(vnfd
["mgmt-interface"]["vdu-id"])
291 elif vnfd
["mgmt-interface"].get("cp"):
292 mgmt_cp
= vnfd
["mgmt-interface"]["cp"]
294 for vdu
in vnfd
.get("vdu", ()):
295 if vdu
.get("vdu-configuration"):
296 ssh_required
= deep_get(vdu
, ("vdu-configuration", "config-access", "ssh-access", "required"))
298 vdu_needed_access
.append(vdu
["id"])
300 for vdu_interface
in vdu
.get("interface"):
301 if vdu_interface
.get("external-connection-point-ref") and \
302 vdu_interface
["external-connection-point-ref"] == mgmt_cp
:
303 vdu_needed_access
.append(vdu
["id"])
307 if vdu_needed_access
:
308 for vnf_member
in nsd
.get("constituent-vnfd"):
309 if vnf_member
["vnfd-id-ref"] != vnfd_ref
:
311 for vdu
in vdu_needed_access
:
312 populate_dict(RO_ns_params
,
313 ("vnfs", vnf_member
["member-vnf-index"], "vdus", vdu
, "mgmt_keys"),
316 if ns_params
.get("vduImage"):
317 RO_ns_params
["vduImage"] = ns_params
["vduImage"]
319 if ns_params
.get("ssh_keys"):
320 RO_ns_params
["cloud-config"] = {"key-pairs": ns_params
["ssh_keys"]}
321 for vnf_params
in get_iterable(ns_params
, "vnf"):
322 for constituent_vnfd
in nsd
["constituent-vnfd"]:
323 if constituent_vnfd
["member-vnf-index"] == vnf_params
["member-vnf-index"]:
324 vnf_descriptor
= vnfd_dict
[constituent_vnfd
["vnfd-id-ref"]]
327 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index={} is not present at nsd:"
328 "constituent-vnfd".format(vnf_params
["member-vnf-index"]))
329 if vnf_params
.get("vimAccountId"):
330 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "datacenter"),
331 vim_account_2_RO(vnf_params
["vimAccountId"]))
333 for vdu_params
in get_iterable(vnf_params
, "vdu"):
334 # TODO feature 1417: check that this VDU exist and it is not a PDU
335 if vdu_params
.get("volume"):
336 for volume_params
in vdu_params
["volume"]:
337 if volume_params
.get("vim-volume-id"):
338 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
339 vdu_params
["id"], "devices", volume_params
["name"], "vim_id"),
340 volume_params
["vim-volume-id"])
341 if vdu_params
.get("interface"):
342 for interface_params
in vdu_params
["interface"]:
343 if interface_params
.get("ip-address"):
344 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
345 vdu_params
["id"], "interfaces", interface_params
["name"],
347 interface_params
["ip-address"])
348 if interface_params
.get("mac-address"):
349 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
350 vdu_params
["id"], "interfaces", interface_params
["name"],
352 interface_params
["mac-address"])
353 if interface_params
.get("floating-ip-required"):
354 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
355 vdu_params
["id"], "interfaces", interface_params
["name"],
357 interface_params
["floating-ip-required"])
359 for internal_vld_params
in get_iterable(vnf_params
, "internal-vld"):
360 if internal_vld_params
.get("vim-network-name"):
361 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
362 internal_vld_params
["name"], "vim-network-name"),
363 internal_vld_params
["vim-network-name"])
364 if internal_vld_params
.get("vim-network-id"):
365 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
366 internal_vld_params
["name"], "vim-network-id"),
367 internal_vld_params
["vim-network-id"])
368 if internal_vld_params
.get("ip-profile"):
369 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
370 internal_vld_params
["name"], "ip-profile"),
371 ip_profile_2_RO(internal_vld_params
["ip-profile"]))
372 if internal_vld_params
.get("provider-network"):
374 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
375 internal_vld_params
["name"], "provider-network"),
376 internal_vld_params
["provider-network"].copy())
378 for icp_params
in get_iterable(internal_vld_params
, "internal-connection-point"):
381 for vdu_descriptor
in vnf_descriptor
["vdu"]:
382 for vdu_interface
in vdu_descriptor
["interface"]:
383 if vdu_interface
.get("internal-connection-point-ref") == icp_params
["id-ref"]:
384 if icp_params
.get("ip-address"):
385 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
386 vdu_descriptor
["id"], "interfaces",
387 vdu_interface
["name"], "ip_address"),
388 icp_params
["ip-address"])
390 if icp_params
.get("mac-address"):
391 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
392 vdu_descriptor
["id"], "interfaces",
393 vdu_interface
["name"], "mac_address"),
394 icp_params
["mac-address"])
400 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
401 "internal-vld:id-ref={} is not present at vnfd:internal-"
402 "connection-point".format(vnf_params
["member-vnf-index"],
403 icp_params
["id-ref"]))
405 for vld_params
in get_iterable(ns_params
, "vld"):
406 if "ip-profile" in vld_params
:
407 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "ip-profile"),
408 ip_profile_2_RO(vld_params
["ip-profile"]))
410 if vld_params
.get("provider-network"):
412 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "provider-network"),
413 vld_params
["provider-network"].copy())
415 if "wimAccountId" in vld_params
and vld_params
["wimAccountId"] is not None:
416 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "wim_account"),
417 wim_account_2_RO(vld_params
["wimAccountId"])),
418 if vld_params
.get("vim-network-name"):
420 if isinstance(vld_params
["vim-network-name"], dict):
421 for vim_account
, vim_net
in vld_params
["vim-network-name"].items():
422 RO_vld_sites
.append({
423 "netmap-use": vim_net
,
424 "datacenter": vim_account_2_RO(vim_account
)
426 else: # isinstance str
427 RO_vld_sites
.append({"netmap-use": vld_params
["vim-network-name"]})
429 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "sites"), RO_vld_sites
)
431 if vld_params
.get("vim-network-id"):
433 if isinstance(vld_params
["vim-network-id"], dict):
434 for vim_account
, vim_net
in vld_params
["vim-network-id"].items():
435 RO_vld_sites
.append({
436 "netmap-use": vim_net
,
437 "datacenter": vim_account_2_RO(vim_account
)
439 else: # isinstance str
440 RO_vld_sites
.append({"netmap-use": vld_params
["vim-network-id"]})
442 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "sites"), RO_vld_sites
)
443 if vld_params
.get("ns-net"):
444 if isinstance(vld_params
["ns-net"], dict):
445 for vld_id
, instance_scenario_id
in vld_params
["ns-net"].items():
446 RO_vld_ns_net
= {"instance_scenario_id": instance_scenario_id
, "osm_id": vld_id
}
448 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "use-network"), RO_vld_ns_net
)
449 if "vnfd-connection-point-ref" in vld_params
:
450 for cp_params
in vld_params
["vnfd-connection-point-ref"]:
452 for constituent_vnfd
in nsd
["constituent-vnfd"]:
453 if constituent_vnfd
["member-vnf-index"] == cp_params
["member-vnf-index-ref"]:
454 vnf_descriptor
= vnfd_dict
[constituent_vnfd
["vnfd-id-ref"]]
458 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={} "
459 "is not present at nsd:constituent-vnfd".format(cp_params
["member-vnf-index-ref"]))
461 for vdu_descriptor
in vnf_descriptor
["vdu"]:
462 for interface_descriptor
in vdu_descriptor
["interface"]:
463 if interface_descriptor
.get("external-connection-point-ref") == \
464 cp_params
["vnfd-connection-point-ref"]:
471 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={}:"
472 "vnfd-connection-point-ref={} is not present at vnfd={}".format(
473 cp_params
["member-vnf-index-ref"],
474 cp_params
["vnfd-connection-point-ref"],
475 vnf_descriptor
["id"]))
476 if cp_params
.get("ip-address"):
477 populate_dict(RO_ns_params
, ("vnfs", cp_params
["member-vnf-index-ref"], "vdus",
478 vdu_descriptor
["id"], "interfaces",
479 interface_descriptor
["name"], "ip_address"),
480 cp_params
["ip-address"])
481 if cp_params
.get("mac-address"):
482 populate_dict(RO_ns_params
, ("vnfs", cp_params
["member-vnf-index-ref"], "vdus",
483 vdu_descriptor
["id"], "interfaces",
484 interface_descriptor
["name"], "mac_address"),
485 cp_params
["mac-address"])
488 def scale_vnfr(self
, db_vnfr
, vdu_create
=None, vdu_delete
=None):
489 # make a copy to do not change
490 vdu_create
= copy(vdu_create
)
491 vdu_delete
= copy(vdu_delete
)
493 vdurs
= db_vnfr
.get("vdur")
496 vdu_index
= len(vdurs
)
499 vdur
= vdurs
[vdu_index
]
500 if vdur
.get("pdu-type"):
502 vdu_id_ref
= vdur
["vdu-id-ref"]
503 if vdu_create
and vdu_create
.get(vdu_id_ref
):
504 for index
in range(0, vdu_create
[vdu_id_ref
]):
505 vdur
= deepcopy(vdur
)
506 vdur
["_id"] = str(uuid4())
507 vdur
["count-index"] += 1
508 vdurs
.insert(vdu_index
+1+index
, vdur
)
509 del vdu_create
[vdu_id_ref
]
510 if vdu_delete
and vdu_delete
.get(vdu_id_ref
):
512 vdu_delete
[vdu_id_ref
] -= 1
513 if not vdu_delete
[vdu_id_ref
]:
514 del vdu_delete
[vdu_id_ref
]
515 # check all operations are done
516 if vdu_create
or vdu_delete
:
517 raise LcmException("Error scaling OUT VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
520 raise LcmException("Error scaling IN VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
523 vnfr_update
= {"vdur": vdurs
}
524 db_vnfr
["vdur"] = vdurs
525 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
527 def ns_update_nsr(self
, ns_update_nsr
, db_nsr
, nsr_desc_RO
):
529 Updates database nsr with the RO info for the created vld
530 :param ns_update_nsr: dictionary to be filled with the updated info
531 :param db_nsr: content of db_nsr. This is also modified
532 :param nsr_desc_RO: nsr descriptor from RO
533 :return: Nothing, LcmException is raised on errors
536 for vld_index
, vld
in enumerate(get_iterable(db_nsr
, "vld")):
537 for net_RO
in get_iterable(nsr_desc_RO
, "nets"):
538 if vld
["id"] != net_RO
.get("ns_net_osm_id"):
540 vld
["vim-id"] = net_RO
.get("vim_net_id")
541 vld
["name"] = net_RO
.get("vim_name")
542 vld
["status"] = net_RO
.get("status")
543 vld
["status-detailed"] = net_RO
.get("error_msg")
544 ns_update_nsr
["vld.{}".format(vld_index
)] = vld
547 raise LcmException("ns_update_nsr: Not found vld={} at RO info".format(vld
["id"]))
549 def ns_update_vnfr(self
, db_vnfrs
, nsr_desc_RO
):
551 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
552 :param db_vnfrs: dictionary with member-vnf-index: vnfr-content
553 :param nsr_desc_RO: nsr descriptor from RO
554 :return: Nothing, LcmException is raised on errors
556 for vnf_index
, db_vnfr
in db_vnfrs
.items():
557 for vnf_RO
in nsr_desc_RO
["vnfs"]:
558 if vnf_RO
["member_vnf_index"] != vnf_index
:
561 if vnf_RO
.get("ip_address"):
562 db_vnfr
["ip-address"] = vnfr_update
["ip-address"] = vnf_RO
["ip_address"].split(";")[0]
563 elif not db_vnfr
.get("ip-address"):
564 raise LcmExceptionNoMgmtIP("ns member_vnf_index '{}' has no IP address".format(vnf_index
))
566 for vdu_index
, vdur
in enumerate(get_iterable(db_vnfr
, "vdur")):
567 vdur_RO_count_index
= 0
568 if vdur
.get("pdu-type"):
570 for vdur_RO
in get_iterable(vnf_RO
, "vms"):
571 if vdur
["vdu-id-ref"] != vdur_RO
["vdu_osm_id"]:
573 if vdur
["count-index"] != vdur_RO_count_index
:
574 vdur_RO_count_index
+= 1
576 vdur
["vim-id"] = vdur_RO
.get("vim_vm_id")
577 if vdur_RO
.get("ip_address"):
578 vdur
["ip-address"] = vdur_RO
["ip_address"].split(";")[0]
580 vdur
["ip-address"] = None
581 vdur
["vdu-id-ref"] = vdur_RO
.get("vdu_osm_id")
582 vdur
["name"] = vdur_RO
.get("vim_name")
583 vdur
["status"] = vdur_RO
.get("status")
584 vdur
["status-detailed"] = vdur_RO
.get("error_msg")
585 for ifacer
in get_iterable(vdur
, "interfaces"):
586 for interface_RO
in get_iterable(vdur_RO
, "interfaces"):
587 if ifacer
["name"] == interface_RO
.get("internal_name"):
588 ifacer
["ip-address"] = interface_RO
.get("ip_address")
589 ifacer
["mac-address"] = interface_RO
.get("mac_address")
592 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} interface={} "
594 .format(vnf_index
, vdur
["vdu-id-ref"], ifacer
["name"]))
595 vnfr_update
["vdur.{}".format(vdu_index
)] = vdur
598 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} count_index={} from "
599 "VIM info".format(vnf_index
, vdur
["vdu-id-ref"], vdur
["count-index"]))
601 for vld_index
, vld
in enumerate(get_iterable(db_vnfr
, "vld")):
602 for net_RO
in get_iterable(nsr_desc_RO
, "nets"):
603 if vld
["id"] != net_RO
.get("vnf_net_osm_id"):
605 vld
["vim-id"] = net_RO
.get("vim_net_id")
606 vld
["name"] = net_RO
.get("vim_name")
607 vld
["status"] = net_RO
.get("status")
608 vld
["status-detailed"] = net_RO
.get("error_msg")
609 vnfr_update
["vld.{}".format(vld_index
)] = vld
612 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vld={} from VIM info".format(
613 vnf_index
, vld
["id"]))
615 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
619 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} from VIM info".format(vnf_index
))
622 def _get_ns_config_info(vca_deployed_list
):
624 Generates a mapping between vnf,vdu elements and the N2VC id
625 :param vca_deployed_list: List of database _admin.deploy.VCA that contains this list
626 :return: a dictionary with {osm-config-mapping: {}} where its element contains:
627 "<member-vnf-index>": <N2VC-id> for a vnf configuration, or
628 "<member-vnf-index>.<vdu.id>.<vdu replica(0, 1,..)>": <N2VC-id> for a vdu configuration
631 ns_config_info
= {"osm-config-mapping": mapping
}
632 for vca
in vca_deployed_list
:
633 if not vca
["member-vnf-index"]:
635 if not vca
["vdu_id"]:
636 mapping
[vca
["member-vnf-index"]] = vca
["application"]
638 mapping
["{}.{}.{}".format(vca
["member-vnf-index"], vca
["vdu_id"], vca
["vdu_count_index"])] =\
640 return ns_config_info
643 def _get_initial_config_primitive_list(desc_primitive_list
, vca_deployed
):
645 Generates a list of initial-config-primitive based on the list provided by the descriptor. It includes internal
646 primitives as verify-ssh-credentials, or config when needed
647 :param desc_primitive_list: information of the descriptor
648 :param vca_deployed: information of the deployed, needed for known if it is related to an NS, VNF, VDU and if
649 this element contains a ssh public key
650 :return: The modified list. Can ba an empty list, but always a list
652 if desc_primitive_list
:
653 primitive_list
= desc_primitive_list
.copy()
656 # look for primitive config, and get the position. None if not present
657 config_position
= None
658 for index
, primitive
in enumerate(primitive_list
):
659 if primitive
["name"] == "config":
660 config_position
= index
663 # for NS, add always a config primitive if not present (bug 874)
664 if not vca_deployed
["member-vnf-index"] and config_position
is None:
665 primitive_list
.insert(0, {"name": "config", "parameter": []})
667 # for VNF/VDU add verify-ssh-credentials after config
668 if vca_deployed
["member-vnf-index"] and config_position
is not None and vca_deployed
.get("ssh-public-key"):
669 primitive_list
.insert(config_position
+ 1, {"name": "verify-ssh-credentials", "parameter": []})
670 return primitive_list
672 async def instantiate_RO(self
, logging_text
, nsr_id
, nsd
, db_nsr
,
673 db_nslcmop
, db_vnfrs
, db_vnfds_ref
, n2vc_key_list
):
676 RO_descriptor_number
= 0 # number of descriptors created at RO
677 vnf_index_2_RO_id
= {} # map between vnfd/nsd id to the id used at RO
678 start_deploy
= time()
679 vdu_flag
= False # If any of the VNFDs has VDUs
680 ns_params
= db_nslcmop
.get("operationParams")
684 # get vnfds, instantiate at RO
686 for c_vnf
in nsd
.get("constituent-vnfd", ()):
687 member_vnf_index
= c_vnf
["member-vnf-index"]
688 vnfd
= db_vnfds_ref
[c_vnf
['vnfd-id-ref']]
691 vnfd_ref
= vnfd
["id"]
692 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Creating vnfd='{}' member_vnf_index='{}' at" \
693 " RO".format(vnfd_ref
, member_vnf_index
)
694 # self.logger.debug(logging_text + step)
695 vnfd_id_RO
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, member_vnf_index
[:23])
696 vnf_index_2_RO_id
[member_vnf_index
] = vnfd_id_RO
697 RO_descriptor_number
+= 1
699 # look position at deployed.RO.vnfd if not present it will be appended at the end
700 for index
, vnf_deployed
in enumerate(db_nsr
["_admin"]["deployed"]["RO"]["vnfd"]):
701 if vnf_deployed
["member-vnf-index"] == member_vnf_index
:
704 index
= len(db_nsr
["_admin"]["deployed"]["RO"]["vnfd"])
705 db_nsr
["_admin"]["deployed"]["RO"]["vnfd"].append(None)
708 RO_update
= {"member-vnf-index": member_vnf_index
}
709 vnfd_list
= await self
.RO
.get_list("vnfd", filter_by
={"osm_id": vnfd_id_RO
})
711 RO_update
["id"] = vnfd_list
[0]["uuid"]
712 self
.logger
.debug(logging_text
+ "vnfd='{}' member_vnf_index='{}' exists at RO. Using RO_id={}".
713 format(vnfd_ref
, member_vnf_index
, vnfd_list
[0]["uuid"]))
715 vnfd_RO
= self
.vnfd2RO(vnfd
, vnfd_id_RO
, db_vnfrs
[c_vnf
["member-vnf-index"]].
716 get("additionalParamsForVnf"), nsr_id
)
717 desc
= await self
.RO
.create("vnfd", descriptor
=vnfd_RO
)
718 RO_update
["id"] = desc
["uuid"]
719 self
.logger
.debug(logging_text
+ "vnfd='{}' member_vnf_index='{}' created at RO. RO_id={}".format(
720 vnfd_ref
, member_vnf_index
, desc
["uuid"]))
721 db_nsr_update
["_admin.deployed.RO.vnfd.{}".format(index
)] = RO_update
722 db_nsr
["_admin"]["deployed"]["RO"]["vnfd"][index
] = RO_update
723 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
724 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
728 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Creating nsd={} at RO".format(nsd_ref
)
729 # self.logger.debug(logging_text + step)
731 RO_osm_nsd_id
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, nsd_ref
[:23])
732 RO_descriptor_number
+= 1
733 nsd_list
= await self
.RO
.get_list("nsd", filter_by
={"osm_id": RO_osm_nsd_id
})
735 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= nsd_list
[0]["uuid"]
736 self
.logger
.debug(logging_text
+ "nsd={} exists at RO. Using RO_id={}".format(
737 nsd_ref
, RO_nsd_uuid
))
739 nsd_RO
= deepcopy(nsd
)
740 nsd_RO
["id"] = RO_osm_nsd_id
741 nsd_RO
.pop("_id", None)
742 nsd_RO
.pop("_admin", None)
743 for c_vnf
in nsd_RO
.get("constituent-vnfd", ()):
744 member_vnf_index
= c_vnf
["member-vnf-index"]
745 c_vnf
["vnfd-id-ref"] = vnf_index_2_RO_id
[member_vnf_index
]
746 for c_vld
in nsd_RO
.get("vld", ()):
747 for cp
in c_vld
.get("vnfd-connection-point-ref", ()):
748 member_vnf_index
= cp
["member-vnf-index-ref"]
749 cp
["vnfd-id-ref"] = vnf_index_2_RO_id
[member_vnf_index
]
751 desc
= await self
.RO
.create("nsd", descriptor
=nsd_RO
)
752 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
753 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= desc
["uuid"]
754 self
.logger
.debug(logging_text
+ "nsd={} created at RO. RO_id={}".format(nsd_ref
, RO_nsd_uuid
))
755 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
756 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
759 # if present use it unless in error status
760 RO_nsr_id
= deep_get(db_nsr
, ("_admin", "deployed", "RO", "nsr_id"))
763 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Looking for existing ns at RO"
764 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
765 desc
= await self
.RO
.show("ns", RO_nsr_id
)
766 except ROclient
.ROClientException
as e
:
767 if e
.http_code
!= HTTPStatus
.NOT_FOUND
:
769 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
771 ns_status
, ns_status_info
= self
.RO
.check_ns_status(desc
)
772 db_nsr_update
["_admin.deployed.RO.nsr_status"] = ns_status
773 if ns_status
== "ERROR":
774 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Deleting ns at RO. RO_ns_id={}"\
776 self
.logger
.debug(logging_text
+ step
)
777 await self
.RO
.delete("ns", RO_nsr_id
)
778 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
780 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Checking dependencies"
781 # self.logger.debug(logging_text + step)
783 # check if VIM is creating and wait look if previous tasks in process
784 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account", ns_params
["vimAccountId"])
786 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
787 self
.logger
.debug(logging_text
+ step
)
788 await asyncio
.wait(task_dependency
, timeout
=3600)
789 if ns_params
.get("vnf"):
790 for vnf
in ns_params
["vnf"]:
791 if "vimAccountId" in vnf
:
792 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account",
795 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
796 self
.logger
.debug(logging_text
+ step
)
797 await asyncio
.wait(task_dependency
, timeout
=3600)
799 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Checking instantiation parameters"
801 RO_ns_params
= self
.ns_params_2_RO(ns_params
, nsd
, db_vnfds_ref
, n2vc_key_list
)
803 step
= db_nsr_update
["detailed-status"] = "Deploying ns at VIM"
804 # step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Deploying ns at VIM"
805 desc
= await self
.RO
.create("ns", descriptor
=RO_ns_params
, name
=db_nsr
["name"], scenario
=RO_nsd_uuid
)
806 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = desc
["uuid"]
807 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
808 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "BUILD"
809 self
.logger
.debug(logging_text
+ "ns created at RO. RO_id={}".format(desc
["uuid"]))
810 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
811 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
813 # wait until NS is ready
814 step
= ns_status_detailed
= detailed_status
= "Waiting VIM to deploy ns. RO_ns_id={}".format(RO_nsr_id
)
815 detailed_status_old
= None
816 self
.logger
.debug(logging_text
+ step
)
818 while time() <= start_deploy
+ self
.total_deploy_timeout
:
819 desc
= await self
.RO
.show("ns", RO_nsr_id
)
820 ns_status
, ns_status_info
= self
.RO
.check_ns_status(desc
)
821 db_nsr_update
["_admin.deployed.RO.nsr_status"] = ns_status
822 if ns_status
== "ERROR":
823 raise ROclient
.ROClientException(ns_status_info
)
824 elif ns_status
== "BUILD":
825 detailed_status
= ns_status_detailed
+ "; {}".format(ns_status_info
)
826 elif ns_status
== "ACTIVE":
827 step
= detailed_status
= "Waiting for management IP address reported by the VIM. Updating VNFRs"
830 self
.ns_update_vnfr(db_vnfrs
, desc
)
832 except LcmExceptionNoMgmtIP
:
835 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
836 if detailed_status
!= detailed_status_old
:
837 detailed_status_old
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = detailed_status
838 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
839 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
840 await asyncio
.sleep(5, loop
=self
.loop
)
841 else: # total_deploy_timeout
842 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
844 step
= "Updating NSR"
845 self
.ns_update_nsr(db_nsr_update
, db_nsr
, desc
)
847 db_nsr_update
["_admin.deployed.RO.operational-status"] = "running"
848 db_nsr
["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
849 db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
850 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
851 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
853 step
= "Deployed at VIM"
854 self
.logger
.debug(logging_text
+ step
)
856 async def wait_vm_up_insert_key_ro(self
, logging_text
, nsr_id
, vnfr_id
, vdu_id
, vdu_index
, pub_key
=None, user
=None):
858 Wait for ip addres at RO, and optionally, insert public key in virtual machine
859 :param logging_text: prefix use for logging
864 :param pub_key: public ssh key to inject, None to skip
865 :param user: user to apply the public ssh key
869 # self.logger.debug(logging_text + "Starting wait_vm_up_insert_key_ro")
877 await asyncio
.sleep(10, loop
=self
.loop
)
878 # wait until NS is deployed at RO
880 db_nsrs
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
881 ro_nsr_id
= deep_get(db_nsrs
, ("_admin", "deployed", "RO", "nsr_id"))
886 if not target_vdu_id
:
887 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnfr_id
})
889 ip_address
= db_vnfr
.get("ip-address")
892 for vdur
in get_iterable(db_vnfr
, "vdur"):
893 if (vdur
["vdu-id-ref"] == vdu_id
and vdur
["count-index"] == vdu_index
) or \
894 (ip_address
and vdur
.get("ip-address") == ip_address
):
895 if vdur
.get("status") == "ACTIVE":
896 target_vdu_id
= vdur
["vdu-id-ref"]
897 elif vdur
.get("status") == "ERROR":
898 raise LcmException("Cannot inject ssh-key because target VM is in error state")
901 raise LcmException("Not found vnfr_id={}, vdu_index={}, vdu_index={}".format(
902 vnfr_id
, vdu_id
, vdu_index
905 if not target_vdu_id
:
908 # self.logger.debug(logging_text + "IP address={}".format(ip_address))
910 # inject public key into machine
912 # self.logger.debug(logging_text + "Inserting RO key")
914 ro_vm_id
= "{}-{}".format(db_vnfr
["member-vnf-index-ref"], target_vdu_id
) # TODO add vdu_index
915 result_dict
= await self
.RO
.create_action(
917 item_id_name
=ro_nsr_id
,
918 descriptor
={"add_public_key": pub_key
, "vms": [ro_vm_id
], "user": user
}
920 # result_dict contains the format {VM-id: {vim_result: 200, description: text}}
921 if not result_dict
or not isinstance(result_dict
, dict):
922 raise LcmException("Unknown response from RO when injecting key")
923 for result
in result_dict
.values():
924 if result
.get("vim_result") == 200:
927 raise ROclient
.ROClientException("error injecting key: {}".format(
928 result
.get("description")))
930 except ROclient
.ROClientException
as e
:
932 self
.logger
.debug(logging_text
+ "error injecting key: {}. Retrying until {} seconds".
936 raise LcmException("Reaching max tries injecting key. Error: {}".format(e
))
942 async def instantiate_N2VC(self
, logging_text
, vca_index
, nsi_id
, db_nsr
, db_vnfr
, vdu_id
,
943 kdu_name
, vdu_index
, config_descriptor
, deploy_params
, base_folder
):
944 nsr_id
= db_nsr
["_id"]
945 db_update_entry
= "_admin.deployed.VCA.{}.".format(vca_index
)
946 vca_deployed_list
= db_nsr
["_admin"]["deployed"]["VCA"]
947 vca_deployed
= db_nsr
["_admin"]["deployed"]["VCA"][vca_index
]
949 'collection': 'nsrs',
950 'filter': {'_id': nsr_id
},
951 'path': db_update_entry
953 logging_text
+= "member_vnf_index={} vdu_id={}, vdu_index={} ".format(db_vnfr
["member-vnf-index-ref"],
960 vnfr_id
= db_vnfr
["_id"]
962 namespace
= "{nsi}.{ns}".format(
963 nsi
=nsi_id
if nsi_id
else "",
966 namespace
+= "." + vnfr_id
968 namespace
+= ".{}-{}".format(vdu_id
, vdu_index
or 0)
971 artifact_path
= "/{}/{}/charms/{}".format(
972 base_folder
["folder"],
973 base_folder
["pkg-dir"],
974 config_descriptor
["juju"]["charm"]
977 is_proxy_charm
= deep_get(config_descriptor
, ('juju', 'charm')) is not None
978 if deep_get(config_descriptor
, ('juju', 'proxy')) is False:
979 is_proxy_charm
= False
981 # n2vc_redesign STEP 3.1
983 # find old ee_id if exists
984 ee_id
= vca_deployed
.get("ee_id")
986 # create or register execution environment in VCA
988 step
= "create execution environment"
989 self
.logger
.debug(logging_text
+ step
)
990 ee_id
, credentials
= await self
.n2vc
.create_execution_environment(namespace
=namespace
,
994 step
= "Waiting to VM being up and getting IP address"
995 self
.logger
.debug(logging_text
+ step
)
996 rw_mgmt_ip
= await self
.wait_vm_up_insert_key_ro(logging_text
, nsr_id
, vnfr_id
, vdu_id
, vdu_index
,
997 user
=None, pub_key
=None)
998 credentials
= {"hostname": rw_mgmt_ip
}
1000 username
= deep_get(config_descriptor
, ("config-access", "ssh-access", "default-user"))
1001 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1002 # merged. Meanwhile let's get username from initial-config-primitive
1003 if not username
and config_descriptor
.get("initial-config-primitive"):
1004 for config_primitive
in config_descriptor
["initial-config-primitive"]:
1005 for param
in config_primitive
.get("parameter", ()):
1006 if param
["name"] == "ssh-username":
1007 username
= param
["value"]
1010 raise LcmException("Cannot determine the username neither with 'initial-config-promitive' nor with "
1011 "'config-access.ssh-access.default-user'")
1012 credentials
["username"] = username
1013 # n2vc_redesign STEP 3.2
1015 step
= "register execution environment {}".format(credentials
)
1016 self
.logger
.debug(logging_text
+ step
)
1017 ee_id
= await self
.n2vc
.register_execution_environment(credentials
=credentials
, namespace
=namespace
,
1020 # for compatibility with MON/POL modules, the need model and application name at database
1021 # TODO ask to N2VC instead of assuming the format "model_name.application_name"
1022 ee_id_parts
= ee_id
.split('.')
1023 model_name
= ee_id_parts
[0]
1024 application_name
= ee_id_parts
[1]
1025 self
.update_db_2("nsrs", nsr_id
, {db_update_entry
+ "model": model_name
,
1026 db_update_entry
+ "application": application_name
,
1027 db_update_entry
+ "ee_id": ee_id
})
1029 # n2vc_redesign STEP 3.3
1031 step
= "Install configuration Software"
1032 # TODO check if already done
1033 self
.logger
.debug(logging_text
+ step
)
1034 await self
.n2vc
.install_configuration_sw(ee_id
=ee_id
, artifact_path
=artifact_path
, db_dict
=db_dict
)
1036 # if SSH access is required, then get execution environment SSH public
1037 if is_proxy_charm
: # if native charm we have waited already to VM be UP
1040 if deep_get(config_descriptor
, ("config-access", "ssh-access", "required")):
1041 # Needed to inject a ssh key
1042 user
= deep_get(config_descriptor
, ("config-access", "ssh-access", "default-user"))
1043 step
= "Install configuration Software, getting public ssh key"
1044 pub_key
= await self
.n2vc
.get_ee_ssh_public__key(ee_id
=ee_id
, db_dict
=db_dict
)
1046 step
= "Insert public key into VM"
1048 step
= "Waiting to VM being up and getting IP address"
1049 self
.logger
.debug(logging_text
+ step
)
1051 # n2vc_redesign STEP 5.1
1052 # wait for RO (ip-address) Insert pub_key into VM
1053 rw_mgmt_ip
= await self
.wait_vm_up_insert_key_ro(logging_text
, nsr_id
, vnfr_id
, vdu_id
, vdu_index
,
1054 user
=user
, pub_key
=pub_key
)
1056 self
.logger
.debug(logging_text
+ ' VM_ip_address={}'.format(rw_mgmt_ip
))
1058 # store rw_mgmt_ip in deploy params for later replacement
1059 deploy_params
["rw_mgmt_ip"] = rw_mgmt_ip
1061 # n2vc_redesign STEP 6 Execute initial config primitive
1062 step
= 'execute initial config primitive'
1063 initial_config_primitive_list
= config_descriptor
.get('initial-config-primitive')
1065 # sort initial config primitives by 'seq'
1067 initial_config_primitive_list
.sort(key
=lambda val
: int(val
['seq']))
1068 except Exception as e
:
1069 self
.logger
.error(logging_text
+ step
+ ": " + str(e
))
1071 # add config if not present for NS charm
1072 initial_config_primitive_list
= self
._get
_initial
_config
_primitive
_list
(initial_config_primitive_list
,
1075 for initial_config_primitive
in initial_config_primitive_list
:
1076 # adding information on the vca_deployed if it is a NS execution environment
1077 if not vca_deployed
["member-vnf-index"]:
1078 deploy_params
["ns_config_info"] = self
._get
_ns
_config
_info
(vca_deployed_list
)
1079 # TODO check if already done
1080 primitive_params_
= self
._map
_primitive
_params
(initial_config_primitive
, {}, deploy_params
)
1082 step
= "execute primitive '{}' params '{}'".format(initial_config_primitive
["name"], primitive_params_
)
1083 self
.logger
.debug(logging_text
+ step
)
1084 await self
.n2vc
.exec_primitive(
1086 primitive_name
=initial_config_primitive
["name"],
1087 params_dict
=primitive_params_
,
1090 # TODO register in database that primitive is done
1092 step
= "instantiated at VCA"
1093 self
.logger
.debug(logging_text
+ step
)
1095 except Exception as e
: # TODO not use Exception but N2VC exception
1096 raise Exception("{} {}".format(step
, e
)) from e
1097 # TODO raise N2VC exception with 'step' extra information
1099 async def instantiate(self
, nsr_id
, nslcmop_id
):
1102 :param nsr_id: ns instance to deploy
1103 :param nslcmop_id: operation to run
1107 # Try to lock HA task here
1108 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
1109 if not task_is_locked_by_me
:
1110 self
.logger
.debug('instantiate() task is not locked by me')
1113 logging_text
= "Task ns={} instantiate={} ".format(nsr_id
, nslcmop_id
)
1114 self
.logger
.debug(logging_text
+ "Enter")
1116 # get all needed from database
1118 # database nsrs record
1121 # database nslcmops record
1124 # update operation on nsrs
1125 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
1126 "_admin.current-operation": nslcmop_id
,
1127 "_admin.operation-type": "instantiate"}
1128 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1130 # update operation on nslcmops
1131 db_nslcmop_update
= {}
1133 nslcmop_operation_state
= None
1134 db_vnfrs
= {} # vnf's info indexed by member-index
1136 task_instantiation_list
= []
1139 # wait for any previous tasks in process
1140 step
= "Waiting for previous operations to terminate"
1141 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
1143 # STEP 0: Reading database (nslcmops, nsrs, nsds, vnfrs, vnfds)
1145 # read from db: operation
1146 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
1147 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1150 step
= "Getting nsr={} from db".format(nsr_id
)
1151 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1152 # nsd is replicated into ns (no db read)
1154 # nsr_name = db_nsr["name"] # TODO short-name??
1156 # read from db: vnf's of this ns
1157 step
= "Getting vnfrs from db"
1158 self
.logger
.debug(logging_text
+ step
)
1159 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1161 # read from db: vnfd's for every vnf
1162 db_vnfds_ref
= {} # every vnfd data indexed by vnf name
1163 db_vnfds
= {} # every vnfd data indexed by vnf id
1164 db_vnfds_index
= {} # every vnfd data indexed by vnf member-index
1166 # for each vnf in ns, read vnfd
1167 for vnfr
in db_vnfrs_list
:
1168 db_vnfrs
[vnfr
["member-vnf-index-ref"]] = vnfr
# vnf's dict indexed by member-index: '1', '2', etc
1169 vnfd_id
= vnfr
["vnfd-id"] # vnfd uuid for this vnf
1170 vnfd_ref
= vnfr
["vnfd-ref"] # vnfd name for this vnf
1171 # if we haven't this vnfd, read it from db
1172 if vnfd_id
not in db_vnfds
:
1174 step
= "Getting vnfd={} id='{}' from db".format(vnfd_id
, vnfd_ref
)
1175 self
.logger
.debug(logging_text
+ step
)
1176 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
1179 db_vnfds_ref
[vnfd_ref
] = vnfd
# vnfd's indexed by name
1180 db_vnfds
[vnfd_id
] = vnfd
# vnfd's indexed by id
1181 db_vnfds_index
[vnfr
["member-vnf-index-ref"]] = db_vnfds
[vnfd_id
] # vnfd's indexed by member-index
1183 # Get or generates the _admin.deployed.VCA list
1184 vca_deployed_list
= None
1185 if db_nsr
["_admin"].get("deployed"):
1186 vca_deployed_list
= db_nsr
["_admin"]["deployed"].get("VCA")
1187 if vca_deployed_list
is None:
1188 vca_deployed_list
= []
1189 db_nsr_update
["_admin.deployed.VCA"] = vca_deployed_list
1190 # add _admin.deployed.VCA to db_nsr dictionary, value=vca_deployed_list
1191 populate_dict(db_nsr
, ("_admin", "deployed", "VCA"), vca_deployed_list
)
1192 elif isinstance(vca_deployed_list
, dict):
1193 # maintain backward compatibility. Change a dict to list at database
1194 vca_deployed_list
= list(vca_deployed_list
.values())
1195 db_nsr_update
["_admin.deployed.VCA"] = vca_deployed_list
1196 populate_dict(db_nsr
, ("_admin", "deployed", "VCA"), vca_deployed_list
)
1198 db_nsr_update
["detailed-status"] = "creating"
1199 db_nsr_update
["operational-status"] = "init"
1201 if not isinstance(deep_get(db_nsr
, ("_admin", "deployed", "RO", "vnfd")), list):
1202 populate_dict(db_nsr
, ("_admin", "deployed", "RO", "vnfd"), [])
1203 db_nsr_update
["_admin.deployed.RO.vnfd"] = []
1205 # set state to INSTANTIATED. When instantiated NBI will not delete directly
1206 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1207 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1208 self
.logger
.debug(logging_text
+ "Before deploy_kdus")
1209 # Call to deploy_kdus in case exists the "vdu:kdu" param
1210 task_kdu
= asyncio
.ensure_future(
1212 logging_text
=logging_text
,
1218 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_KDUs", task_kdu
)
1219 task_instantiation_list
.append(task_kdu
)
1220 # n2vc_redesign STEP 1 Get VCA public ssh-key
1221 # feature 1429. Add n2vc public key to needed VMs
1222 n2vc_key
= self
.n2vc
.get_public_key()
1223 n2vc_key_list
= [n2vc_key
]
1224 if self
.vca_config
.get("public_key"):
1225 n2vc_key_list
.append(self
.vca_config
["public_key"])
1227 # n2vc_redesign STEP 2 Deploy Network Scenario
1228 task_ro
= asyncio
.ensure_future(
1229 self
.instantiate_RO(
1230 logging_text
=logging_text
,
1234 db_nslcmop
=db_nslcmop
,
1236 db_vnfds_ref
=db_vnfds_ref
,
1237 n2vc_key_list
=n2vc_key_list
1240 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_RO", task_ro
)
1241 task_instantiation_list
.append(task_ro
)
1243 # n2vc_redesign STEP 3 to 6 Deploy N2VC
1244 step
= "Looking for needed vnfd to configure with proxy charm"
1245 self
.logger
.debug(logging_text
+ step
)
1247 nsi_id
= None # TODO put nsi_id when this nsr belongs to a NSI
1248 # get_iterable() returns a value from a dict or empty tuple if key does not exist
1249 for c_vnf
in get_iterable(nsd
, "constituent-vnfd"):
1250 vnfd_id
= c_vnf
["vnfd-id-ref"]
1251 vnfd
= db_vnfds_ref
[vnfd_id
]
1252 member_vnf_index
= str(c_vnf
["member-vnf-index"])
1253 db_vnfr
= db_vnfrs
[member_vnf_index
]
1254 base_folder
= vnfd
["_admin"]["storage"]
1260 # Get additional parameters
1262 if db_vnfr
.get("additionalParamsForVnf"):
1263 deploy_params
= self
._format
_additional
_params
(db_vnfr
["additionalParamsForVnf"].copy())
1265 descriptor_config
= vnfd
.get("vnf-configuration")
1266 if descriptor_config
and descriptor_config
.get("juju"):
1268 logging_text
=logging_text
,
1271 nslcmop_id
=nslcmop_id
,
1277 member_vnf_index
=member_vnf_index
,
1278 vdu_index
=vdu_index
,
1280 deploy_params
=deploy_params
,
1281 descriptor_config
=descriptor_config
,
1282 base_folder
=base_folder
,
1283 task_instantiation_list
=task_instantiation_list
1286 # Deploy charms for each VDU that supports one.
1287 for vdud
in get_iterable(vnfd
, 'vdu'):
1289 descriptor_config
= vdud
.get('vdu-configuration')
1290 vdur
= next((x
for x
in db_vnfr
["vdur"] if x
["vdu-id-ref"] == vdu_id
), None)
1291 if vdur
.get("additionalParams"):
1292 deploy_params_vdu
= self
._format
_additional
_params
(vdur
["additionalParams"])
1294 deploy_params_vdu
= deploy_params
1295 if descriptor_config
and descriptor_config
.get("juju"):
1296 # look for vdu index in the db_vnfr["vdu"] section
1297 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
1298 # if vdur["vdu-id-ref"] == vdu_id:
1301 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
1302 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
1303 # vdu_name = vdur.get("name")
1306 for vdu_index
in range(int(vdud
.get("count", 1))):
1307 # TODO vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
1309 logging_text
=logging_text
,
1312 nslcmop_id
=nslcmop_id
,
1318 member_vnf_index
=member_vnf_index
,
1319 vdu_index
=vdu_index
,
1321 deploy_params
=deploy_params_vdu
,
1322 descriptor_config
=descriptor_config
,
1323 base_folder
=base_folder
,
1324 task_instantiation_list
=task_instantiation_list
1326 for kdud
in get_iterable(vnfd
, 'kdu'):
1327 kdu_name
= kdud
["name"]
1328 descriptor_config
= kdud
.get('kdu-configuration')
1329 if descriptor_config
and descriptor_config
.get("juju"):
1333 # look for vdu index in the db_vnfr["vdu"] section
1334 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
1335 # if vdur["vdu-id-ref"] == vdu_id:
1338 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
1339 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
1340 # vdu_name = vdur.get("name")
1344 logging_text
=logging_text
,
1347 nslcmop_id
=nslcmop_id
,
1353 member_vnf_index
=member_vnf_index
,
1354 vdu_index
=vdu_index
,
1356 deploy_params
=deploy_params
,
1357 descriptor_config
=descriptor_config
,
1358 base_folder
=base_folder
,
1359 task_instantiation_list
=task_instantiation_list
1362 # Check if this NS has a charm configuration
1363 descriptor_config
= nsd
.get("ns-configuration")
1364 if descriptor_config
and descriptor_config
.get("juju"):
1367 member_vnf_index
= None
1373 # Get additional parameters
1375 if db_nsr
.get("additionalParamsForNs"):
1376 deploy_params
= self
._format
_additional
_params
(db_nsr
["additionalParamsForNs"].copy())
1377 base_folder
= nsd
["_admin"]["storage"]
1379 logging_text
=logging_text
,
1382 nslcmop_id
=nslcmop_id
,
1388 member_vnf_index
=member_vnf_index
,
1389 vdu_index
=vdu_index
,
1391 deploy_params
=deploy_params
,
1392 descriptor_config
=descriptor_config
,
1393 base_folder
=base_folder
,
1394 task_instantiation_list
=task_instantiation_list
1397 # Wait until all tasks of "task_instantiation_list" have been finished
1399 # while time() <= start_deploy + self.total_deploy_timeout:
1401 timeout
= 3600 # time() - start_deploy
1402 task_instantiation_set
= set(task_instantiation_list
) # build a set with tasks
1405 if len(task_instantiation_set
) > 0:
1406 done
, pending
= await asyncio
.wait(task_instantiation_set
, timeout
=timeout
)
1408 error_text
= "timeout"
1410 if task
.cancelled():
1412 error_text
= "cancelled"
1414 exc
= task
.exception()
1416 error_text
= str(exc
)
1419 db_nsr_update
["config-status"] = "failed"
1420 error_text
= "fail configuring " + error_text
1421 db_nsr_update
["detailed-status"] = error_text
1422 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED_TEMP"
1423 db_nslcmop_update
["detailed-status"] = error_text
1424 db_nslcmop_update
["statusEnteredTime"] = time()
1427 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
1428 db_nslcmop_update
["statusEnteredTime"] = time()
1429 db_nslcmop_update
["detailed-status"] = "done"
1430 db_nsr_update
["config-status"] = "configured"
1431 db_nsr_update
["detailed-status"] = "done"
1433 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
1434 self
.logger
.error(logging_text
+ "Exit Exception while '{}': {}".format(step
, e
))
1436 except asyncio
.CancelledError
:
1437 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1438 exc
= "Operation was cancelled"
1439 except Exception as e
:
1440 exc
= traceback
.format_exc()
1441 self
.logger
.critical(logging_text
+ "Exit Exception {} while '{}': {}".format(type(e
).__name
__, step
, e
),
1446 db_nsr_update
["detailed-status"] = "ERROR {}: {}".format(step
, exc
)
1447 db_nsr_update
["operational-status"] = "failed"
1449 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
1450 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
1451 db_nslcmop_update
["statusEnteredTime"] = time()
1454 db_nsr_update
["_admin.nslcmop"] = None
1455 db_nsr_update
["_admin.current-operation"] = None
1456 db_nsr_update
["_admin.operation-type"] = None
1457 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1458 if db_nslcmop_update
:
1459 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1460 except DbException
as e
:
1461 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
1462 if nslcmop_operation_state
:
1464 await self
.msg
.aiowrite("ns", "instantiated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
1465 "operationState": nslcmop_operation_state
},
1467 except Exception as e
:
1468 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1470 self
.logger
.debug(logging_text
+ "Exit")
1471 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_instantiate")
1473 async def deploy_kdus(self
, logging_text
, nsr_id
, db_nsr
, db_vnfrs
):
1474 # Launch kdus if present in the descriptor
1476 k8scluster_id_2_uuic
= {"helm-chart": {}, "juju-bundle": {}}
1478 def _get_cluster_id(cluster_id
, cluster_type
):
1479 nonlocal k8scluster_id_2_uuic
1480 if cluster_id
in k8scluster_id_2_uuic
[cluster_type
]:
1481 return k8scluster_id_2_uuic
[cluster_type
][cluster_id
]
1483 db_k8scluster
= self
.db
.get_one("k8sclusters", {"_id": cluster_id
}, fail_on_empty
=False)
1484 if not db_k8scluster
:
1485 raise LcmException("K8s cluster {} cannot be found".format(cluster_id
))
1486 k8s_id
= deep_get(db_k8scluster
, ("_admin", cluster_type
, "id"))
1488 raise LcmException("K8s cluster '{}' has not been initilized for '{}'".format(cluster_id
, cluster_type
))
1489 k8scluster_id_2_uuic
[cluster_type
][cluster_id
] = k8s_id
1492 logging_text
+= "Deploy kdus: "
1494 db_nsr_update
= {"_admin.deployed.K8s": []}
1495 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1497 # Look for all vnfds
1500 for vnfr_data
in db_vnfrs
.values():
1501 for kdur
in get_iterable(vnfr_data
, "kdur"):
1502 desc_params
= self
._format
_additional
_params
(kdur
.get("additionalParams"))
1504 k8sclustertype
= None
1507 if kdur
.get("helm-chart"):
1508 kdumodel
= kdur
["helm-chart"]
1509 k8sclustertype
= "chart"
1510 k8sclustertype_full
= "helm-chart"
1511 elif kdur
.get("juju-bundle"):
1512 kdumodel
= kdur
["juju-bundle"]
1513 k8sclustertype
= "juju"
1514 k8sclustertype_full
= "juju-bundle"
1516 error_text
= "kdu type is neither helm-chart not juju-bundle. Maybe an old NBI version is" \
1520 cluster_uuid
= _get_cluster_id(kdur
["k8s-cluster"]["id"], k8sclustertype_full
)
1521 except LcmException
as e
:
1523 step
= "Instantiate KDU {} in k8s cluster {}".format(kdur
["kdu-name"], cluster_uuid
)
1525 k8s_instace_info
= {"kdu-instance": None, "k8scluster-uuid": cluster_uuid
,
1526 "k8scluster-type": k8sclustertype
,
1527 "kdu-name": kdur
["kdu-name"], "kdu-model": kdumodel
}
1529 k8s_instace_info
["detailed-status"] = error_text
1530 db_nsr_update
["_admin.deployed.K8s.{}".format(index
)] = k8s_instace_info
1531 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1535 db_dict
= {"collection": "nsrs", "filter": {"_id": nsr_id
}, "path": "_admin.deployed.K8s."
1537 if k8sclustertype
== "chart":
1538 task
= asyncio
.ensure_future(
1539 self
.k8sclusterhelm
.install(cluster_uuid
=cluster_uuid
, kdu_model
=kdumodel
, atomic
=True,
1540 params
=desc_params
, db_dict
=db_dict
, timeout
=3600)
1543 # TODO juju-bundle connector in place
1545 pending_tasks
[task
] = "_admin.deployed.K8s.{}.".format(index
)
1547 if not pending_tasks
:
1549 self
.logger
.debug(logging_text
+ 'Waiting for terminate pending tasks...')
1550 pending_list
= list(pending_tasks
.keys())
1552 done_list
, pending_list
= await asyncio
.wait(pending_list
, timeout
=30*60,
1553 return_when
=asyncio
.FIRST_COMPLETED
)
1554 if not done_list
: # timeout
1555 for task
in pending_list
:
1556 db_nsr_update
[pending_tasks(task
) + "detailed-status"] = "Timeout"
1558 for task
in done_list
:
1559 exc
= task
.exception()
1561 db_nsr_update
[pending_tasks
[task
] + "detailed-status"] = "{}".format(exc
)
1563 db_nsr_update
[pending_tasks
[task
] + "kdu-instance"] = task
.result()
1565 except Exception as e
:
1566 self
.logger
.critical(logging_text
+ "Exit Exception {} while '{}': {}".format(type(e
).__name
__, step
, e
))
1567 raise LcmException("{} Exit Exception {} while '{}': {}".format(logging_text
, type(e
).__name
__, step
, e
))
1569 # TODO Write in data base
1571 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1573 def _deploy_n2vc(self
, logging_text
, db_nsr
, db_vnfr
, nslcmop_id
, nsr_id
, nsi_id
, vnfd_id
, vdu_id
,
1574 kdu_name
, member_vnf_index
, vdu_index
, vdu_name
, deploy_params
, descriptor_config
,
1575 base_folder
, task_instantiation_list
):
1576 # launch instantiate_N2VC in a asyncio task and register task object
1577 # Look where information of this charm is at database <nsrs>._admin.deployed.VCA
1578 # if not found, create one entry and update database
1580 # fill db_nsr._admin.deployed.VCA.<index>
1582 for vca_index
, vca_deployed
in enumerate(db_nsr
["_admin"]["deployed"]["VCA"]):
1583 if not vca_deployed
:
1585 if vca_deployed
.get("member-vnf-index") == member_vnf_index
and \
1586 vca_deployed
.get("vdu_id") == vdu_id
and \
1587 vca_deployed
.get("kdu_name") == kdu_name
and \
1588 vca_deployed
.get("vdu_count_index", 0) == vdu_index
:
1591 # not found, create one.
1593 "member-vnf-index": member_vnf_index
,
1595 "kdu_name": kdu_name
,
1596 "vdu_count_index": vdu_index
,
1597 "operational-status": "init", # TODO revise
1598 "detailed-status": "", # TODO revise
1599 "step": "initial-deploy", # TODO revise
1601 "vdu_name": vdu_name
,
1604 self
.update_db_2("nsrs", nsr_id
, {"_admin.deployed.VCA.{}".format(vca_index
): vca_deployed
})
1605 db_nsr
["_admin"]["deployed"]["VCA"].append(vca_deployed
)
1608 task_n2vc
= asyncio
.ensure_future(
1609 self
.instantiate_N2VC(
1610 logging_text
=logging_text
,
1611 vca_index
=vca_index
,
1617 vdu_index
=vdu_index
,
1618 deploy_params
=deploy_params
,
1619 config_descriptor
=descriptor_config
,
1620 base_folder
=base_folder
,
1623 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_N2VC-{}".format(vca_index
), task_n2vc
)
1624 task_instantiation_list
.append(task_n2vc
)
1626 # Check if this VNFD has a configured terminate action
1627 def _has_terminate_config_primitive(self
, vnfd
):
1628 vnf_config
= vnfd
.get("vnf-configuration")
1629 if vnf_config
and vnf_config
.get("terminate-config-primitive"):
1635 def _get_terminate_config_primitive_seq_list(vnfd
):
1636 """ Get a numerically sorted list of the sequences for this VNFD's terminate action """
1637 # No need to check for existing primitive twice, already done before
1638 vnf_config
= vnfd
.get("vnf-configuration")
1639 seq_list
= vnf_config
.get("terminate-config-primitive")
1640 # Get all 'seq' tags in seq_list, order sequences numerically, ascending.
1641 seq_list_sorted
= sorted(seq_list
, key
=lambda x
: int(x
['seq']))
1642 return seq_list_sorted
1645 def _create_nslcmop(nsr_id
, operation
, params
):
1647 Creates a ns-lcm-opp content to be stored at database.
1648 :param nsr_id: internal id of the instance
1649 :param operation: instantiate, terminate, scale, action, ...
1650 :param params: user parameters for the operation
1651 :return: dictionary following SOL005 format
1653 # Raise exception if invalid arguments
1654 if not (nsr_id
and operation
and params
):
1656 "Parameters 'nsr_id', 'operation' and 'params' needed to create primitive not provided")
1662 # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1663 "operationState": "PROCESSING",
1664 "statusEnteredTime": now
,
1665 "nsInstanceId": nsr_id
,
1666 "lcmOperationType": operation
,
1668 "isAutomaticInvocation": False,
1669 "operationParams": params
,
1670 "isCancelPending": False,
1672 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
1673 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
1678 def _format_additional_params(self
, params
):
1679 params
= params
or {}
1680 for key
, value
in params
.items():
1681 if str(value
).startswith("!!yaml "):
1682 params
[key
] = yaml
.safe_load(value
[7:])
1685 def _get_terminate_primitive_params(self
, seq
, vnf_index
):
1686 primitive
= seq
.get('name')
1687 primitive_params
= {}
1689 "member_vnf_index": vnf_index
,
1690 "primitive": primitive
,
1691 "primitive_params": primitive_params
,
1694 return self
._map
_primitive
_params
(seq
, params
, desc_params
)
1698 def _reintent_or_skip_suboperation(self
, db_nslcmop
, op_index
):
1699 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
1700 if (op
.get('operationState') == 'COMPLETED'):
1701 # b. Skip sub-operation
1702 # _ns_execute_primitive() or RO.create_action() will NOT be executed
1703 return self
.SUBOPERATION_STATUS_SKIP
1705 # c. Reintent executing sub-operation
1706 # The sub-operation exists, and operationState != 'COMPLETED'
1707 # Update operationState = 'PROCESSING' to indicate a reintent.
1708 operationState
= 'PROCESSING'
1709 detailed_status
= 'In progress'
1710 self
._update
_suboperation
_status
(
1711 db_nslcmop
, op_index
, operationState
, detailed_status
)
1712 # Return the sub-operation index
1713 # _ns_execute_primitive() or RO.create_action() will be called from scale()
1714 # with arguments extracted from the sub-operation
1717 # Find a sub-operation where all keys in a matching dictionary must match
1718 # Returns the index of the matching sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if no match
1719 def _find_suboperation(self
, db_nslcmop
, match
):
1720 if (db_nslcmop
and match
):
1721 op_list
= db_nslcmop
.get('_admin', {}).get('operations', [])
1722 for i
, op
in enumerate(op_list
):
1723 if all(op
.get(k
) == match
[k
] for k
in match
):
1725 return self
.SUBOPERATION_STATUS_NOT_FOUND
1727 # Update status for a sub-operation given its index
1728 def _update_suboperation_status(self
, db_nslcmop
, op_index
, operationState
, detailed_status
):
1729 # Update DB for HA tasks
1730 q_filter
= {'_id': db_nslcmop
['_id']}
1731 update_dict
= {'_admin.operations.{}.operationState'.format(op_index
): operationState
,
1732 '_admin.operations.{}.detailed-status'.format(op_index
): detailed_status
}
1733 self
.db
.set_one("nslcmops",
1735 update_dict
=update_dict
,
1736 fail_on_empty
=False)
1738 # Add sub-operation, return the index of the added sub-operation
1739 # Optionally, set operationState, detailed-status, and operationType
1740 # Status and type are currently set for 'scale' sub-operations:
1741 # 'operationState' : 'PROCESSING' | 'COMPLETED' | 'FAILED'
1742 # 'detailed-status' : status message
1743 # 'operationType': may be any type, in the case of scaling: 'PRE-SCALE' | 'POST-SCALE'
1744 # Status and operation type are currently only used for 'scale', but NOT for 'terminate' sub-operations.
1745 def _add_suboperation(self
, db_nslcmop
, vnf_index
, vdu_id
, vdu_count_index
, vdu_name
, primitive
,
1746 mapped_primitive_params
, operationState
=None, detailed_status
=None, operationType
=None,
1747 RO_nsr_id
=None, RO_scaling_info
=None):
1748 if not (db_nslcmop
):
1749 return self
.SUBOPERATION_STATUS_NOT_FOUND
1750 # Get the "_admin.operations" list, if it exists
1751 db_nslcmop_admin
= db_nslcmop
.get('_admin', {})
1752 op_list
= db_nslcmop_admin
.get('operations')
1753 # Create or append to the "_admin.operations" list
1754 new_op
= {'member_vnf_index': vnf_index
,
1756 'vdu_count_index': vdu_count_index
,
1757 'primitive': primitive
,
1758 'primitive_params': mapped_primitive_params
}
1760 new_op
['operationState'] = operationState
1762 new_op
['detailed-status'] = detailed_status
1764 new_op
['lcmOperationType'] = operationType
1766 new_op
['RO_nsr_id'] = RO_nsr_id
1768 new_op
['RO_scaling_info'] = RO_scaling_info
1770 # No existing operations, create key 'operations' with current operation as first list element
1771 db_nslcmop_admin
.update({'operations': [new_op
]})
1772 op_list
= db_nslcmop_admin
.get('operations')
1774 # Existing operations, append operation to list
1775 op_list
.append(new_op
)
1777 db_nslcmop_update
= {'_admin.operations': op_list
}
1778 self
.update_db_2("nslcmops", db_nslcmop
['_id'], db_nslcmop_update
)
1779 op_index
= len(op_list
) - 1
1782 # Helper methods for scale() sub-operations
1784 # pre-scale/post-scale:
1785 # Check for 3 different cases:
1786 # a. New: First time execution, return SUBOPERATION_STATUS_NEW
1787 # b. Skip: Existing sub-operation exists, operationState == 'COMPLETED', return SUBOPERATION_STATUS_SKIP
1788 # c. Reintent: Existing sub-operation exists, operationState != 'COMPLETED', return op_index to re-execute
1789 def _check_or_add_scale_suboperation(self
, db_nslcmop
, vnf_index
, vnf_config_primitive
, primitive_params
,
1790 operationType
, RO_nsr_id
=None, RO_scaling_info
=None):
1791 # Find this sub-operation
1792 if (RO_nsr_id
and RO_scaling_info
):
1793 operationType
= 'SCALE-RO'
1795 'member_vnf_index': vnf_index
,
1796 'RO_nsr_id': RO_nsr_id
,
1797 'RO_scaling_info': RO_scaling_info
,
1801 'member_vnf_index': vnf_index
,
1802 'primitive': vnf_config_primitive
,
1803 'primitive_params': primitive_params
,
1804 'lcmOperationType': operationType
1806 op_index
= self
._find
_suboperation
(db_nslcmop
, match
)
1807 if (op_index
== self
.SUBOPERATION_STATUS_NOT_FOUND
):
1808 # a. New sub-operation
1809 # The sub-operation does not exist, add it.
1810 # _ns_execute_primitive() will be called from scale() as usual, with non-modified arguments
1811 # The following parameters are set to None for all kind of scaling:
1813 vdu_count_index
= None
1815 if (RO_nsr_id
and RO_scaling_info
):
1816 vnf_config_primitive
= None
1817 primitive_params
= None
1820 RO_scaling_info
= None
1821 # Initial status for sub-operation
1822 operationState
= 'PROCESSING'
1823 detailed_status
= 'In progress'
1824 # Add sub-operation for pre/post-scaling (zero or more operations)
1825 self
._add
_suboperation
(db_nslcmop
,
1830 vnf_config_primitive
,
1837 return self
.SUBOPERATION_STATUS_NEW
1839 # Return either SUBOPERATION_STATUS_SKIP (operationState == 'COMPLETED'),
1840 # or op_index (operationState != 'COMPLETED')
1841 return self
._reintent
_or
_skip
_suboperation
(db_nslcmop
, op_index
)
1843 # Helper methods for terminate()
1845 async def _terminate_action(self
, db_nslcmop
, nslcmop_id
, nsr_id
):
1846 """ Create a primitive with params from VNFD
1847 Called from terminate() before deleting instance
1848 Calls action() to execute the primitive """
1849 logging_text
= "Task ns={} _terminate_action={} ".format(nsr_id
, nslcmop_id
)
1850 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1853 for vnfr
in db_vnfrs_list
:
1854 vnfd_id
= vnfr
["vnfd-id"]
1855 vnf_index
= vnfr
["member-vnf-index-ref"]
1856 if vnfd_id
not in db_vnfds
:
1857 step
= "Getting vnfd={} id='{}' from db".format(vnfd_id
, vnfd_id
)
1858 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
1859 db_vnfds
[vnfd_id
] = vnfd
1860 vnfd
= db_vnfds
[vnfd_id
]
1861 if not self
._has
_terminate
_config
_primitive
(vnfd
):
1863 # Get the primitive's sorted sequence list
1864 seq_list
= self
._get
_terminate
_config
_primitive
_seq
_list
(vnfd
)
1865 for seq
in seq_list
:
1866 # For each sequence in list, get primitive and call _ns_execute_primitive()
1867 step
= "Calling terminate action for vnf_member_index={} primitive={}".format(
1868 vnf_index
, seq
.get("name"))
1869 self
.logger
.debug(logging_text
+ step
)
1870 # Create the primitive for each sequence, i.e. "primitive": "touch"
1871 primitive
= seq
.get('name')
1872 mapped_primitive_params
= self
._get
_terminate
_primitive
_params
(seq
, vnf_index
)
1873 # The following 3 parameters are currently set to None for 'terminate':
1874 # vdu_id, vdu_count_index, vdu_name
1875 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
1876 vdu_count_index
= db_nslcmop
["operationParams"].get("vdu_count_index")
1877 vdu_name
= db_nslcmop
["operationParams"].get("vdu_name")
1879 self
._add
_suboperation
(db_nslcmop
,
1886 mapped_primitive_params
)
1887 # Sub-operations: Call _ns_execute_primitive() instead of action()
1888 # db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1889 # nsr_deployed = db_nsr["_admin"]["deployed"]
1891 # nslcmop_operation_state, nslcmop_operation_state_detail = await self.action(
1892 # nsr_id, nslcmop_terminate_action_id)
1893 # Launch Exception if action() returns other than ['COMPLETED', 'PARTIALLY_COMPLETED']
1894 # result_ok = ['COMPLETED', 'PARTIALLY_COMPLETED']
1895 # if result not in result_ok:
1896 # raise LcmException(
1897 # "terminate_primitive_action for vnf_member_index={}",
1898 # " primitive={} fails with error {}".format(
1899 # vnf_index, seq.get("name"), result_detail))
1904 await self
.n2vc
.exec_primitive(
1906 primitive_name
=primitive
,
1907 params_dict
=mapped_primitive_params
1909 except Exception as e
:
1910 self
.logger
.error('Error executing primitive {}: {}'.format(primitive
, e
))
1912 "terminate_primitive_action for vnf_member_index={}, primitive={} fails with error {}"
1913 .format(vnf_index
, seq
.get("name"), e
),
1916 async def terminate(self
, nsr_id
, nslcmop_id
):
1918 # Try to lock HA task here
1919 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
1920 if not task_is_locked_by_me
:
1923 logging_text
= "Task ns={} terminate={} ".format(nsr_id
, nslcmop_id
)
1924 self
.logger
.debug(logging_text
+ "Enter")
1928 failed_detail
= [] # annotates all failed error messages
1929 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
1930 "_admin.current-operation": nslcmop_id
,
1931 "_admin.operation-type": "terminate"}
1932 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1933 db_nslcmop_update
= {}
1934 nslcmop_operation_state
= None
1935 autoremove
= False # autoremove after terminated
1938 # wait for any previous tasks in process
1939 step
= "Waiting for previous operations to terminate"
1940 await self
.lcm_tasks
.waitfor_related_HA("ns", 'nslcmops', nslcmop_id
)
1942 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
1943 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1944 step
= "Getting nsr={} from db".format(nsr_id
)
1945 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1946 # nsd = db_nsr["nsd"]
1947 nsr_deployed
= deepcopy(db_nsr
["_admin"].get("deployed"))
1948 if db_nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
1950 # #TODO check if VIM is creating and wait
1951 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
1952 # Call internal terminate action
1953 await self
._terminate
_action
(db_nslcmop
, nslcmop_id
, nsr_id
)
1957 db_nsr_update
["operational-status"] = "terminating"
1958 db_nsr_update
["config-status"] = "terminating"
1962 step
= "delete execution environment"
1963 self
.logger
.debug(logging_text
+ step
)
1965 task_delete_ee
= asyncio
.ensure_future(self
.n2vc
.delete_namespace(namespace
="." + nsr_id
))
1966 pending_tasks
.append(task_delete_ee
)
1967 except Exception as e
:
1968 msg
= "Failed while deleting NS in VCA: {}".format(e
)
1969 self
.logger
.error(msg
)
1970 failed_detail
.append(msg
)
1973 # Delete from k8scluster
1974 step
= "delete kdus"
1975 self
.logger
.debug(logging_text
+ step
)
1976 # print(nsr_deployed)
1978 for kdu
in nsr_deployed
.get("K8s", ()):
1979 kdu_instance
= kdu
.get("kdu-instance")
1980 if not kdu_instance
:
1982 if kdu
.get("k8scluster-type") == "chart":
1983 task_delete_kdu_instance
= asyncio
.ensure_future(
1984 self
.k8sclusterhelm
.uninstall(cluster_uuid
=kdu
.get("k8scluster-uuid"),
1985 kdu_instance
=kdu_instance
))
1986 elif kdu
.get("k8scluster-type") == "juju":
1987 # TODO Juju connector needed
1990 self
.error(logging_text
+ "Unknown k8s deployment type {}".
1991 format(kdu
.get("k8scluster-type")))
1993 pending_tasks
.append(task_delete_kdu_instance
)
1994 except LcmException
as e
:
1995 msg
= "Failed while deleting KDUs from NS: {}".format(e
)
1996 self
.logger
.error(msg
)
1997 failed_detail
.append(msg
)
2003 RO_nsr_id
= RO_delete_action
= None
2004 if nsr_deployed
and nsr_deployed
.get("RO"):
2005 RO_nsr_id
= nsr_deployed
["RO"].get("nsr_id")
2006 RO_delete_action
= nsr_deployed
["RO"].get("nsr_delete_action_id")
2009 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] = \
2010 "Deleting ns from VIM"
2011 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2012 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2013 self
.logger
.debug(logging_text
+ step
)
2014 desc
= await self
.RO
.delete("ns", RO_nsr_id
)
2015 RO_delete_action
= desc
["action_id"]
2016 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = RO_delete_action
2017 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
2018 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
2019 if RO_delete_action
:
2020 # wait until NS is deleted from VIM
2021 step
= detailed_status
= "Waiting ns deleted from VIM. RO_id={} RO_delete_action={}".\
2022 format(RO_nsr_id
, RO_delete_action
)
2023 detailed_status_old
= None
2024 self
.logger
.debug(logging_text
+ step
)
2026 delete_timeout
= 20 * 60 # 20 minutes
2027 while delete_timeout
> 0:
2028 desc
= await self
.RO
.show(
2030 item_id_name
=RO_nsr_id
,
2031 extra_item
="action",
2032 extra_item_id
=RO_delete_action
)
2033 ns_status
, ns_status_info
= self
.RO
.check_action_status(desc
)
2034 if ns_status
== "ERROR":
2035 raise ROclient
.ROClientException(ns_status_info
)
2036 elif ns_status
== "BUILD":
2037 detailed_status
= step
+ "; {}".format(ns_status_info
)
2038 elif ns_status
== "ACTIVE":
2039 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
2040 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
2043 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
2044 if detailed_status
!= detailed_status_old
:
2045 detailed_status_old
= db_nslcmop_update
["detailed-status"] = \
2046 db_nsr_update
["detailed-status"] = detailed_status
2047 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2048 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2049 await asyncio
.sleep(5, loop
=self
.loop
)
2051 else: # delete_timeout <= 0:
2052 raise ROclient
.ROClientException("Timeout waiting ns deleted from VIM")
2054 except ROclient
.ROClientException
as e
:
2055 if e
.http_code
== 404: # not found
2056 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
2057 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
2058 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
2059 self
.logger
.debug(logging_text
+ "RO_ns_id={} already deleted".format(RO_nsr_id
))
2060 elif e
.http_code
== 409: # conflict
2061 failed_detail
.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id
, e
))
2062 self
.logger
.debug(logging_text
+ failed_detail
[-1])
2065 failed_detail
.append("RO_ns_id={} delete error: {}".format(RO_nsr_id
, e
))
2066 self
.logger
.error(logging_text
+ failed_detail
[-1])
2070 if not RO_fail
and nsr_deployed
and nsr_deployed
.get("RO") and nsr_deployed
["RO"].get("nsd_id"):
2071 RO_nsd_id
= nsr_deployed
["RO"]["nsd_id"]
2073 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
2074 "Deleting nsd from RO"
2075 await self
.RO
.delete("nsd", RO_nsd_id
)
2076 self
.logger
.debug(logging_text
+ "RO_nsd_id={} deleted".format(RO_nsd_id
))
2077 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
2078 except ROclient
.ROClientException
as e
:
2079 if e
.http_code
== 404: # not found
2080 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
2081 self
.logger
.debug(logging_text
+ "RO_nsd_id={} already deleted".format(RO_nsd_id
))
2082 elif e
.http_code
== 409: # conflict
2083 failed_detail
.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id
, e
))
2084 self
.logger
.debug(logging_text
+ failed_detail
[-1])
2087 failed_detail
.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id
, e
))
2088 self
.logger
.error(logging_text
+ failed_detail
[-1])
2091 if not RO_fail
and nsr_deployed
and nsr_deployed
.get("RO") and nsr_deployed
["RO"].get("vnfd"):
2092 for index
, vnf_deployed
in enumerate(nsr_deployed
["RO"]["vnfd"]):
2093 if not vnf_deployed
or not vnf_deployed
["id"]:
2096 RO_vnfd_id
= vnf_deployed
["id"]
2097 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
2098 "Deleting member_vnf_index={} RO_vnfd_id={} from RO".format(
2099 vnf_deployed
["member-vnf-index"], RO_vnfd_id
)
2100 await self
.RO
.delete("vnfd", RO_vnfd_id
)
2101 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} deleted".format(RO_vnfd_id
))
2102 db_nsr_update
["_admin.deployed.RO.vnfd.{}.id".format(index
)] = None
2103 except ROclient
.ROClientException
as e
:
2104 if e
.http_code
== 404: # not found
2105 db_nsr_update
["_admin.deployed.RO.vnfd.{}.id".format(index
)] = None
2106 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} already deleted ".format(RO_vnfd_id
))
2107 elif e
.http_code
== 409: # conflict
2108 failed_detail
.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id
, e
))
2109 self
.logger
.debug(logging_text
+ failed_detail
[-1])
2111 failed_detail
.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id
, e
))
2112 self
.logger
.error(logging_text
+ failed_detail
[-1])
2115 self
.logger
.error(logging_text
+ " ;".join(failed_detail
))
2116 db_nsr_update
["operational-status"] = "failed"
2117 db_nsr_update
["detailed-status"] = "Deletion errors " + "; ".join(failed_detail
)
2118 db_nslcmop_update
["detailed-status"] = "; ".join(failed_detail
)
2119 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2120 db_nslcmop_update
["statusEnteredTime"] = time()
2122 db_nsr_update
["operational-status"] = "terminated"
2123 db_nsr_update
["detailed-status"] = "Done"
2124 db_nsr_update
["_admin.nsState"] = "NOT_INSTANTIATED"
2125 db_nslcmop_update
["detailed-status"] = "Done"
2126 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
2127 db_nslcmop_update
["statusEnteredTime"] = time()
2128 if db_nslcmop
["operationParams"].get("autoremove"):
2131 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
2132 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
2134 except asyncio
.CancelledError
:
2135 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
2136 exc
= "Operation was cancelled"
2137 except Exception as e
:
2138 exc
= traceback
.format_exc()
2139 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
2141 if exc
and db_nslcmop
:
2142 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
2143 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2144 db_nslcmop_update
["statusEnteredTime"] = time()
2146 if db_nslcmop
and db_nslcmop_update
:
2147 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2149 db_nsr_update
["_admin.nslcmop"] = None
2150 db_nsr_update
["_admin.current-operation"] = None
2151 db_nsr_update
["_admin.operation-type"] = None
2152 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2153 except DbException
as e
:
2154 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
2155 if nslcmop_operation_state
:
2157 await self
.msg
.aiowrite("ns", "terminated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2158 "operationState": nslcmop_operation_state
,
2159 "autoremove": autoremove
},
2161 except Exception as e
:
2162 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
2164 # wait for pending tasks
2168 self
.logger
.debug(logging_text
+ 'Waiting for terminate pending tasks...')
2169 done
, pending
= await asyncio
.wait(pending_tasks
, timeout
=3600)
2171 self
.logger
.debug(logging_text
+ 'All tasks finished...')
2173 self
.logger
.info(logging_text
+ 'There are pending tasks: {}'.format(pending
))
2175 self
.logger
.debug(logging_text
+ "Exit")
2176 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_terminate")
2179 def _map_primitive_params(primitive_desc
, params
, instantiation_params
):
2181 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
2182 The default-value is used. If it is between < > it look for a value at instantiation_params
2183 :param primitive_desc: portion of VNFD/NSD that describes primitive
2184 :param params: Params provided by user
2185 :param instantiation_params: Instantiation params provided by user
2186 :return: a dictionary with the calculated params
2188 calculated_params
= {}
2189 for parameter
in primitive_desc
.get("parameter", ()):
2190 param_name
= parameter
["name"]
2191 if param_name
in params
:
2192 calculated_params
[param_name
] = params
[param_name
]
2193 elif "default-value" in parameter
or "value" in parameter
:
2194 if "value" in parameter
:
2195 calculated_params
[param_name
] = parameter
["value"]
2197 calculated_params
[param_name
] = parameter
["default-value"]
2198 if isinstance(calculated_params
[param_name
], str) and calculated_params
[param_name
].startswith("<") \
2199 and calculated_params
[param_name
].endswith(">"):
2200 if calculated_params
[param_name
][1:-1] in instantiation_params
:
2201 calculated_params
[param_name
] = instantiation_params
[calculated_params
[param_name
][1:-1]]
2203 raise LcmException("Parameter {} needed to execute primitive {} not provided".
2204 format(calculated_params
[param_name
], primitive_desc
["name"]))
2206 raise LcmException("Parameter {} needed to execute primitive {} not provided".
2207 format(param_name
, primitive_desc
["name"]))
2209 if isinstance(calculated_params
[param_name
], (dict, list, tuple)):
2210 calculated_params
[param_name
] = yaml
.safe_dump(calculated_params
[param_name
], default_flow_style
=True,
2212 elif isinstance(calculated_params
[param_name
], str) and calculated_params
[param_name
].startswith("!!yaml "):
2213 calculated_params
[param_name
] = calculated_params
[param_name
][7:]
2215 # add always ns_config_info if primitive name is config
2216 if primitive_desc
["name"] == "config":
2217 if "ns_config_info" in instantiation_params
:
2218 calculated_params
["ns_config_info"] = instantiation_params
["ns_config_info"]
2219 return calculated_params
2221 async def _ns_execute_primitive(self
, db_deployed
, member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
,
2222 primitive
, primitive_params
, retries
=0, retries_interval
=30) -> (str, str):
2224 # find vca_deployed record for this action
2226 for vca_deployed
in db_deployed
["VCA"]:
2227 if not vca_deployed
:
2229 if member_vnf_index
!= vca_deployed
["member-vnf-index"] or vdu_id
!= vca_deployed
["vdu_id"]:
2231 if vdu_name
and vdu_name
!= vca_deployed
["vdu_name"]:
2233 if vdu_count_index
and vdu_count_index
!= vca_deployed
["vdu_count_index"]:
2237 # vca_deployed not found
2238 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} is not "
2239 "deployed".format(member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
))
2242 ee_id
= vca_deployed
.get("ee_id")
2244 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} has not "
2245 "execution environment"
2246 .format(member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
))
2248 if primitive
== "config":
2249 primitive_params
= {"params": primitive_params
}
2253 output
= await self
.n2vc
.exec_primitive(
2255 primitive_name
=primitive
,
2256 params_dict
=primitive_params
2260 except Exception as e
:
2263 self
.logger
.debug('Error executing action {} on {} -> {}'.format(primitive
, ee_id
, e
))
2265 await asyncio
.sleep(retries_interval
, loop
=self
.loop
)
2267 return 'Cannot execute action {} on {}: {}'.format(primitive
, ee_id
, e
), 'FAIL'
2271 except Exception as e
:
2272 return 'Error executing action {}: {}'.format(primitive
, e
), 'FAIL'
2274 async def action(self
, nsr_id
, nslcmop_id
):
2276 # Try to lock HA task here
2277 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
2278 if not task_is_locked_by_me
:
2281 logging_text
= "Task ns={} action={} ".format(nsr_id
, nslcmop_id
)
2282 self
.logger
.debug(logging_text
+ "Enter")
2283 # get all needed from database
2286 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
2287 "_admin.current-operation": nslcmop_id
,
2288 "_admin.operation-type": "action"}
2289 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2290 db_nslcmop_update
= {}
2291 nslcmop_operation_state
= None
2292 nslcmop_operation_state_detail
= None
2295 # wait for any previous tasks in process
2296 step
= "Waiting for previous operations to terminate"
2297 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
2299 step
= "Getting information from database"
2300 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
2301 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2303 nsr_deployed
= db_nsr
["_admin"].get("deployed")
2304 vnf_index
= db_nslcmop
["operationParams"].get("member_vnf_index")
2305 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
2306 kdu_name
= db_nslcmop
["operationParams"].get("kdu_name")
2307 vdu_count_index
= db_nslcmop
["operationParams"].get("vdu_count_index")
2308 vdu_name
= db_nslcmop
["operationParams"].get("vdu_name")
2311 step
= "Getting vnfr from database"
2312 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
2313 step
= "Getting vnfd from database"
2314 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
2316 if db_nsr
.get("nsd"):
2317 db_nsd
= db_nsr
.get("nsd") # TODO this will be removed
2319 step
= "Getting nsd from database"
2320 db_nsd
= self
.db
.get_one("nsds", {"_id": db_nsr
["nsd-id"]})
2322 # for backward compatibility
2323 if nsr_deployed
and isinstance(nsr_deployed
.get("VCA"), dict):
2324 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
2325 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
2326 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2328 primitive
= db_nslcmop
["operationParams"]["primitive"]
2329 primitive_params
= db_nslcmop
["operationParams"]["primitive_params"]
2331 # look for primitive
2332 config_primitive_desc
= None
2334 for vdu
in get_iterable(db_vnfd
, "vdu"):
2335 if vdu_id
== vdu
["id"]:
2336 for config_primitive
in vdu
.get("vdu-configuration", {}).get("config-primitive", ()):
2337 if config_primitive
["name"] == primitive
:
2338 config_primitive_desc
= config_primitive
2341 self
.logger
.debug(logging_text
+ "Checking actions in KDUs")
2342 kdur
= next((x
for x
in db_vnfr
["kdur"] if x
["kdu_name"] == kdu_name
), None)
2343 desc_params
= self
._format
_additional
_params
(kdur
.get("additionalParams")) or {}
2344 if primitive_params
:
2345 desc_params
.update(primitive_params
)
2346 # TODO Check if we will need something at vnf level
2348 for kdu
in get_iterable(nsr_deployed
, "K8s"):
2349 if kdu_name
== kdu
["kdu-name"]:
2350 db_dict
= {"collection": "nsrs", "filter": {"_id": nsr_id
},
2351 "path": "_admin.deployed.K8s.{}".format(index
)}
2352 if primitive
== "upgrade":
2353 if desc_params
.get("kdu_model"):
2354 kdu_model
= desc_params
.get("kdu_model")
2355 del desc_params
["kdu_model"]
2357 kdu_model
= kdu
.get("kdu-model")
2358 parts
= kdu_model
.split(sep
=":")
2360 kdu_model
= parts
[0]
2362 if kdu
.get("k8scluster-type") == "chart":
2363 output
= await self
.k8sclusterhelm
.upgrade(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2364 kdu_instance
=kdu
.get("kdu-instance"),
2365 atomic
=True, kdu_model
=kdu_model
,
2366 params
=desc_params
, db_dict
=db_dict
,
2368 elif kdu
.get("k8scluster-type") == "juju":
2369 # TODO Juju connector needed
2372 msg
= "k8scluster-type not defined"
2373 raise LcmException(msg
)
2375 self
.logger
.debug(logging_text
+ " Upgrade of kdu {} done".format(output
))
2377 elif primitive
== "rollback":
2378 if kdu
.get("k8scluster-type") == "chart":
2379 output
= await self
.k8sclusterhelm
.rollback(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2380 kdu_instance
=kdu
.get("kdu-instance"),
2382 elif kdu
.get("k8scluster-type") == "juju":
2383 # TODO Juju connector needed
2386 msg
= "k8scluster-type not defined"
2387 raise LcmException(msg
)
2389 elif primitive
== "status":
2390 if kdu
.get("k8scluster-type") == "chart":
2391 output
= await self
.k8sclusterhelm
.status_kdu(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2392 kdu_instance
=kdu
.get("kdu-instance"))
2393 elif kdu
.get("k8scluster-type") == "juju":
2394 # TODO Juju connector needed
2397 msg
= "k8scluster-type not defined"
2398 raise LcmException(msg
)
2403 raise LcmException("KDU '{}' not found".format(kdu_name
))
2405 db_nslcmop_update
["detailed-status"] = output
2406 db_nslcmop_update
["operationState"] = 'COMPLETED'
2407 db_nslcmop_update
["statusEnteredTime"] = time()
2409 db_nslcmop_update
["detailed-status"] = ''
2410 db_nslcmop_update
["operationState"] = 'FAILED'
2411 db_nslcmop_update
["statusEnteredTime"] = time()
2414 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
2415 if config_primitive
["name"] == primitive
:
2416 config_primitive_desc
= config_primitive
2419 for config_primitive
in db_nsd
.get("ns-configuration", {}).get("config-primitive", ()):
2420 if config_primitive
["name"] == primitive
:
2421 config_primitive_desc
= config_primitive
2424 if not config_primitive_desc
:
2425 raise LcmException("Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".
2430 if db_vnfr
.get("additionalParamsForVnf"):
2431 desc_params
= self
._format
_additional
_params
(db_vnfr
["additionalParamsForVnf"])
2433 vdur
= next((x
for x
in db_vnfr
["vdur"] if x
["vdu-id-ref"] == vdu_id
), None)
2434 if vdur
.get("additionalParams"):
2435 desc_params
= self
._format
_additional
_params
(vdur
["additionalParams"])
2437 if db_nsr
.get("additionalParamsForNs"):
2438 desc_params
.update(self
._format
_additional
_params
(db_nsr
["additionalParamsForNs"]))
2440 # TODO check if ns is in a proper status
2441 output
, detail
= await self
._ns
_execute
_primitive
(
2442 db_deployed
=nsr_deployed
,
2443 member_vnf_index
=vnf_index
,
2446 vdu_count_index
=vdu_count_index
,
2447 primitive
=primitive
,
2448 primitive_params
=self
._map
_primitive
_params
(config_primitive_desc
, primitive_params
, desc_params
))
2450 detailed_status
= output
2452 result
= 'COMPLETED'
2456 db_nslcmop_update
["detailed-status"] = nslcmop_operation_state_detail
= detailed_status
2457 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= result
2458 db_nslcmop_update
["statusEnteredTime"] = time()
2459 self
.logger
.debug(logging_text
+ " task Done with result {} {}".format(result
, detailed_status
))
2460 return # database update is called inside finally
2462 except (DbException
, LcmException
) as e
:
2463 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
2465 except asyncio
.CancelledError
:
2466 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
2467 exc
= "Operation was cancelled"
2468 except Exception as e
:
2469 exc
= traceback
.format_exc()
2470 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
2472 if exc
and db_nslcmop
:
2473 db_nslcmop_update
["detailed-status"] = nslcmop_operation_state_detail
= \
2474 "FAILED {}: {}".format(step
, exc
)
2475 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2476 db_nslcmop_update
["statusEnteredTime"] = time()
2478 if db_nslcmop_update
:
2479 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2481 db_nsr_update
["_admin.nslcmop"] = None
2482 db_nsr_update
["_admin.operation-type"] = None
2483 db_nsr_update
["_admin.nslcmop"] = None
2484 db_nsr_update
["_admin.current-operation"] = None
2485 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2486 except DbException
as e
:
2487 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
2488 self
.logger
.debug(logging_text
+ "Exit")
2489 if nslcmop_operation_state
:
2491 await self
.msg
.aiowrite("ns", "actioned", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2492 "operationState": nslcmop_operation_state
},
2494 except Exception as e
:
2495 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
2496 self
.logger
.debug(logging_text
+ "Exit")
2497 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_action")
2498 return nslcmop_operation_state
, nslcmop_operation_state_detail
2500 async def scale(self
, nsr_id
, nslcmop_id
):
2502 # Try to lock HA task here
2503 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
2504 if not task_is_locked_by_me
:
2507 logging_text
= "Task ns={} scale={} ".format(nsr_id
, nslcmop_id
)
2508 self
.logger
.debug(logging_text
+ "Enter")
2509 # get all needed from database
2512 db_nslcmop_update
= {}
2513 nslcmop_operation_state
= None
2514 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
2515 "_admin.current-operation": nslcmop_id
,
2516 "_admin.operation-type": "scale"}
2517 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2519 # in case of error, indicates what part of scale was failed to put nsr at error status
2520 scale_process
= None
2521 old_operational_status
= ""
2522 old_config_status
= ""
2525 # wait for any previous tasks in process
2526 step
= "Waiting for previous operations to terminate"
2527 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
2529 step
= "Getting nslcmop from database"
2530 self
.logger
.debug(step
+ " after having waited for previous tasks to be completed")
2531 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
2532 step
= "Getting nsr from database"
2533 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2535 old_operational_status
= db_nsr
["operational-status"]
2536 old_config_status
= db_nsr
["config-status"]
2537 step
= "Parsing scaling parameters"
2538 # self.logger.debug(step)
2539 db_nsr_update
["operational-status"] = "scaling"
2540 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2541 nsr_deployed
= db_nsr
["_admin"].get("deployed")
2544 nsr_deployed
= db_nsr
["_admin"].get("deployed")
2545 vnf_index
= db_nslcmop
["operationParams"].get("member_vnf_index")
2546 # vdu_id = db_nslcmop["operationParams"].get("vdu_id")
2547 # vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
2548 # vdu_name = db_nslcmop["operationParams"].get("vdu_name")
2551 RO_nsr_id
= nsr_deployed
["RO"]["nsr_id"]
2552 vnf_index
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
2553 scaling_group
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
2554 scaling_type
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleVnfType"]
2555 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
2557 # for backward compatibility
2558 if nsr_deployed
and isinstance(nsr_deployed
.get("VCA"), dict):
2559 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
2560 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
2561 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2563 step
= "Getting vnfr from database"
2564 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
2565 step
= "Getting vnfd from database"
2566 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
2568 step
= "Getting scaling-group-descriptor"
2569 for scaling_descriptor
in db_vnfd
["scaling-group-descriptor"]:
2570 if scaling_descriptor
["name"] == scaling_group
:
2573 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
2574 "at vnfd:scaling-group-descriptor".format(scaling_group
))
2577 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
2578 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
2579 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
2582 # TODO check if ns is in a proper status
2583 step
= "Sending scale order to VIM"
2585 if not db_nsr
["_admin"].get("scaling-group"):
2586 self
.update_db_2("nsrs", nsr_id
, {"_admin.scaling-group": [{"name": scaling_group
, "nb-scale-op": 0}]})
2587 admin_scale_index
= 0
2589 for admin_scale_index
, admin_scale_info
in enumerate(db_nsr
["_admin"]["scaling-group"]):
2590 if admin_scale_info
["name"] == scaling_group
:
2591 nb_scale_op
= admin_scale_info
.get("nb-scale-op", 0)
2593 else: # not found, set index one plus last element and add new entry with the name
2594 admin_scale_index
+= 1
2595 db_nsr_update
["_admin.scaling-group.{}.name".format(admin_scale_index
)] = scaling_group
2596 RO_scaling_info
= []
2597 vdu_scaling_info
= {"scaling_group_name": scaling_group
, "vdu": []}
2598 if scaling_type
== "SCALE_OUT":
2599 # count if max-instance-count is reached
2600 max_instance_count
= scaling_descriptor
.get("max-instance-count", 10)
2601 # self.logger.debug("MAX_INSTANCE_COUNT is {}".format(max_instance_count))
2602 if nb_scale_op
>= max_instance_count
:
2603 raise LcmException("reached the limit of {} (max-instance-count) "
2604 "scaling-out operations for the "
2605 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
2608 vdu_scaling_info
["scaling_direction"] = "OUT"
2609 vdu_scaling_info
["vdu-create"] = {}
2610 for vdu_scale_info
in scaling_descriptor
["vdu"]:
2611 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
2612 "type": "create", "count": vdu_scale_info
.get("count", 1)})
2613 vdu_scaling_info
["vdu-create"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
2615 elif scaling_type
== "SCALE_IN":
2616 # count if min-instance-count is reached
2617 min_instance_count
= 0
2618 if "min-instance-count" in scaling_descriptor
and scaling_descriptor
["min-instance-count"] is not None:
2619 min_instance_count
= int(scaling_descriptor
["min-instance-count"])
2620 if nb_scale_op
<= min_instance_count
:
2621 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
2622 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
2624 vdu_scaling_info
["scaling_direction"] = "IN"
2625 vdu_scaling_info
["vdu-delete"] = {}
2626 for vdu_scale_info
in scaling_descriptor
["vdu"]:
2627 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
2628 "type": "delete", "count": vdu_scale_info
.get("count", 1)})
2629 vdu_scaling_info
["vdu-delete"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
2631 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
2632 vdu_create
= vdu_scaling_info
.get("vdu-create")
2633 vdu_delete
= copy(vdu_scaling_info
.get("vdu-delete"))
2634 if vdu_scaling_info
["scaling_direction"] == "IN":
2635 for vdur
in reversed(db_vnfr
["vdur"]):
2636 if vdu_delete
.get(vdur
["vdu-id-ref"]):
2637 vdu_delete
[vdur
["vdu-id-ref"]] -= 1
2638 vdu_scaling_info
["vdu"].append({
2639 "name": vdur
["name"],
2640 "vdu_id": vdur
["vdu-id-ref"],
2643 for interface
in vdur
["interfaces"]:
2644 vdu_scaling_info
["vdu"][-1]["interface"].append({
2645 "name": interface
["name"],
2646 "ip_address": interface
["ip-address"],
2647 "mac_address": interface
.get("mac-address"),
2649 vdu_delete
= vdu_scaling_info
.pop("vdu-delete")
2652 step
= "Executing pre-scale vnf-config-primitive"
2653 if scaling_descriptor
.get("scaling-config-action"):
2654 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
2655 if (scaling_config_action
.get("trigger") == "pre-scale-in" and scaling_type
== "SCALE_IN") \
2656 or (scaling_config_action
.get("trigger") == "pre-scale-out" and scaling_type
== "SCALE_OUT"):
2657 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
2658 step
= db_nslcmop_update
["detailed-status"] = \
2659 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive
)
2661 # look for primitive
2662 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
2663 if config_primitive
["name"] == vnf_config_primitive
:
2667 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
2668 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
2669 "primitive".format(scaling_group
, config_primitive
))
2671 vnfr_params
= {"VDU_SCALE_INFO": vdu_scaling_info
}
2672 if db_vnfr
.get("additionalParamsForVnf"):
2673 vnfr_params
.update(db_vnfr
["additionalParamsForVnf"])
2675 scale_process
= "VCA"
2676 db_nsr_update
["config-status"] = "configuring pre-scaling"
2677 primitive_params
= self
._map
_primitive
_params
(config_primitive
, {}, vnfr_params
)
2679 # Pre-scale reintent check: Check if this sub-operation has been executed before
2680 op_index
= self
._check
_or
_add
_scale
_suboperation
(
2681 db_nslcmop
, nslcmop_id
, vnf_index
, vnf_config_primitive
, primitive_params
, 'PRE-SCALE')
2682 if (op_index
== self
.SUBOPERATION_STATUS_SKIP
):
2683 # Skip sub-operation
2684 result
= 'COMPLETED'
2685 result_detail
= 'Done'
2686 self
.logger
.debug(logging_text
+
2687 "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
2688 vnf_config_primitive
, result
, result_detail
))
2690 if (op_index
== self
.SUBOPERATION_STATUS_NEW
):
2691 # New sub-operation: Get index of this sub-operation
2692 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
2693 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} New sub-operation".
2694 format(vnf_config_primitive
))
2696 # Reintent: Get registered params for this existing sub-operation
2697 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
2698 vnf_index
= op
.get('member_vnf_index')
2699 vnf_config_primitive
= op
.get('primitive')
2700 primitive_params
= op
.get('primitive_params')
2701 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Sub-operation reintent".
2702 format(vnf_config_primitive
))
2703 # Execute the primitive, either with new (first-time) or registered (reintent) args
2704 result
, result_detail
= await self
._ns
_execute
_primitive
(
2705 nsr_deployed
, vnf_index
, None, None, None, vnf_config_primitive
, primitive_params
)
2706 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
2707 vnf_config_primitive
, result
, result_detail
))
2708 # Update operationState = COMPLETED | FAILED
2709 self
._update
_suboperation
_status
(
2710 db_nslcmop
, op_index
, result
, result_detail
)
2712 if result
== "FAILED":
2713 raise LcmException(result_detail
)
2714 db_nsr_update
["config-status"] = old_config_status
2715 scale_process
= None
2719 # Should this block be skipped if 'RO_nsr_id' == None ?
2720 # if (RO_nsr_id and RO_scaling_info):
2722 scale_process
= "RO"
2723 # Scale RO reintent check: Check if this sub-operation has been executed before
2724 op_index
= self
._check
_or
_add
_scale
_suboperation
(
2725 db_nslcmop
, vnf_index
, None, None, 'SCALE-RO', RO_nsr_id
, RO_scaling_info
)
2726 if (op_index
== self
.SUBOPERATION_STATUS_SKIP
):
2727 # Skip sub-operation
2728 result
= 'COMPLETED'
2729 result_detail
= 'Done'
2730 self
.logger
.debug(logging_text
+ "Skipped sub-operation RO, result {} {}".format(
2731 result
, result_detail
))
2733 if (op_index
== self
.SUBOPERATION_STATUS_NEW
):
2734 # New sub-operation: Get index of this sub-operation
2735 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
2736 self
.logger
.debug(logging_text
+ "New sub-operation RO")
2738 # Reintent: Get registered params for this existing sub-operation
2739 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
2740 RO_nsr_id
= op
.get('RO_nsr_id')
2741 RO_scaling_info
= op
.get('RO_scaling_info')
2742 self
.logger
.debug(logging_text
+ "Sub-operation RO reintent".format(
2743 vnf_config_primitive
))
2745 RO_desc
= await self
.RO
.create_action("ns", RO_nsr_id
, {"vdu-scaling": RO_scaling_info
})
2746 db_nsr_update
["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index
)] = nb_scale_op
2747 db_nsr_update
["_admin.scaling-group.{}.time".format(admin_scale_index
)] = time()
2749 RO_nslcmop_id
= RO_desc
["instance_action_id"]
2750 db_nslcmop_update
["_admin.deploy.RO"] = RO_nslcmop_id
2752 RO_task_done
= False
2753 step
= detailed_status
= "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id
)
2754 detailed_status_old
= None
2755 self
.logger
.debug(logging_text
+ step
)
2757 deployment_timeout
= 1 * 3600 # One hour
2758 while deployment_timeout
> 0:
2759 if not RO_task_done
:
2760 desc
= await self
.RO
.show("ns", item_id_name
=RO_nsr_id
, extra_item
="action",
2761 extra_item_id
=RO_nslcmop_id
)
2762 ns_status
, ns_status_info
= self
.RO
.check_action_status(desc
)
2763 if ns_status
== "ERROR":
2764 raise ROclient
.ROClientException(ns_status_info
)
2765 elif ns_status
== "BUILD":
2766 detailed_status
= step
+ "; {}".format(ns_status_info
)
2767 elif ns_status
== "ACTIVE":
2769 step
= detailed_status
= "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id
)
2770 self
.logger
.debug(logging_text
+ step
)
2772 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
2775 if ns_status
== "ERROR":
2776 raise ROclient
.ROClientException(ns_status_info
)
2777 elif ns_status
== "BUILD":
2778 detailed_status
= step
+ "; {}".format(ns_status_info
)
2779 elif ns_status
== "ACTIVE":
2780 step
= detailed_status
= \
2781 "Waiting for management IP address reported by the VIM. Updating VNFRs"
2783 self
.scale_vnfr(db_vnfr
, vdu_create
=vdu_create
, vdu_delete
=vdu_delete
)
2786 desc
= await self
.RO
.show("ns", RO_nsr_id
)
2787 # nsr_deployed["nsr_ip"] = RO.get_ns_vnf_info(desc)
2788 self
.ns_update_vnfr({db_vnfr
["member-vnf-index-ref"]: db_vnfr
}, desc
)
2790 except LcmExceptionNoMgmtIP
:
2793 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
2794 if detailed_status
!= detailed_status_old
:
2795 self
._update
_suboperation
_status
(
2796 db_nslcmop
, op_index
, 'COMPLETED', detailed_status
)
2797 detailed_status_old
= db_nslcmop_update
["detailed-status"] = detailed_status
2798 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2800 await asyncio
.sleep(5, loop
=self
.loop
)
2801 deployment_timeout
-= 5
2802 if deployment_timeout
<= 0:
2803 self
._update
_suboperation
_status
(
2804 db_nslcmop
, nslcmop_id
, op_index
, 'FAILED', "Timeout when waiting for ns to get ready")
2805 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
2807 # update VDU_SCALING_INFO with the obtained ip_addresses
2808 if vdu_scaling_info
["scaling_direction"] == "OUT":
2809 for vdur
in reversed(db_vnfr
["vdur"]):
2810 if vdu_scaling_info
["vdu-create"].get(vdur
["vdu-id-ref"]):
2811 vdu_scaling_info
["vdu-create"][vdur
["vdu-id-ref"]] -= 1
2812 vdu_scaling_info
["vdu"].append({
2813 "name": vdur
["name"],
2814 "vdu_id": vdur
["vdu-id-ref"],
2817 for interface
in vdur
["interfaces"]:
2818 vdu_scaling_info
["vdu"][-1]["interface"].append({
2819 "name": interface
["name"],
2820 "ip_address": interface
["ip-address"],
2821 "mac_address": interface
.get("mac-address"),
2823 del vdu_scaling_info
["vdu-create"]
2825 self
._update
_suboperation
_status
(db_nslcmop
, op_index
, 'COMPLETED', 'Done')
2828 scale_process
= None
2830 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2833 # execute primitive service POST-SCALING
2834 step
= "Executing post-scale vnf-config-primitive"
2835 if scaling_descriptor
.get("scaling-config-action"):
2836 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
2837 if (scaling_config_action
.get("trigger") == "post-scale-in" and scaling_type
== "SCALE_IN") \
2838 or (scaling_config_action
.get("trigger") == "post-scale-out" and scaling_type
== "SCALE_OUT"):
2839 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
2840 step
= db_nslcmop_update
["detailed-status"] = \
2841 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive
)
2843 vnfr_params
= {"VDU_SCALE_INFO": vdu_scaling_info
}
2844 if db_vnfr
.get("additionalParamsForVnf"):
2845 vnfr_params
.update(db_vnfr
["additionalParamsForVnf"])
2847 # look for primitive
2848 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
2849 if config_primitive
["name"] == vnf_config_primitive
:
2852 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
2853 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
2854 "match any vnf-configuration:config-primitive".format(scaling_group
,
2856 scale_process
= "VCA"
2857 db_nsr_update
["config-status"] = "configuring post-scaling"
2858 primitive_params
= self
._map
_primitive
_params
(config_primitive
, {}, vnfr_params
)
2860 # Post-scale reintent check: Check if this sub-operation has been executed before
2861 op_index
= self
._check
_or
_add
_scale
_suboperation
(
2862 db_nslcmop
, nslcmop_id
, vnf_index
, vnf_config_primitive
, primitive_params
, 'POST-SCALE')
2863 if (op_index
== self
.SUBOPERATION_STATUS_SKIP
):
2864 # Skip sub-operation
2865 result
= 'COMPLETED'
2866 result_detail
= 'Done'
2867 self
.logger
.debug(logging_text
+
2868 "vnf_config_primitive={} Skipped sub-operation, result {} {}".
2869 format(vnf_config_primitive
, result
, result_detail
))
2871 if (op_index
== self
.SUBOPERATION_STATUS_NEW
):
2872 # New sub-operation: Get index of this sub-operation
2873 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
2874 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} New sub-operation".
2875 format(vnf_config_primitive
))
2877 # Reintent: Get registered params for this existing sub-operation
2878 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
2879 vnf_index
= op
.get('member_vnf_index')
2880 vnf_config_primitive
= op
.get('primitive')
2881 primitive_params
= op
.get('primitive_params')
2882 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Sub-operation reintent".
2883 format(vnf_config_primitive
))
2884 # Execute the primitive, either with new (first-time) or registered (reintent) args
2885 result
, result_detail
= await self
._ns
_execute
_primitive
(
2886 nsr_deployed
, vnf_index
, None, None, None, vnf_config_primitive
, primitive_params
)
2887 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
2888 vnf_config_primitive
, result
, result_detail
))
2889 # Update operationState = COMPLETED | FAILED
2890 self
._update
_suboperation
_status
(
2891 db_nslcmop
, op_index
, result
, result_detail
)
2893 if result
== "FAILED":
2894 raise LcmException(result_detail
)
2895 db_nsr_update
["config-status"] = old_config_status
2896 scale_process
= None
2899 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
2900 db_nslcmop_update
["statusEnteredTime"] = time()
2901 db_nslcmop_update
["detailed-status"] = "done"
2902 db_nsr_update
["detailed-status"] = "" # "scaled {} {}".format(scaling_group, scaling_type)
2903 db_nsr_update
["operational-status"] = "running" if old_operational_status
== "failed" \
2904 else old_operational_status
2905 db_nsr_update
["config-status"] = old_config_status
2907 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
2908 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
2910 except asyncio
.CancelledError
:
2911 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
2912 exc
= "Operation was cancelled"
2913 except Exception as e
:
2914 exc
= traceback
.format_exc()
2915 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
2919 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
2920 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2921 db_nslcmop_update
["statusEnteredTime"] = time()
2923 db_nsr_update
["operational-status"] = old_operational_status
2924 db_nsr_update
["config-status"] = old_config_status
2925 db_nsr_update
["detailed-status"] = ""
2926 db_nsr_update
["_admin.nslcmop"] = None
2928 if "VCA" in scale_process
:
2929 db_nsr_update
["config-status"] = "failed"
2930 if "RO" in scale_process
:
2931 db_nsr_update
["operational-status"] = "failed"
2932 db_nsr_update
["detailed-status"] = "FAILED scaling nslcmop={} {}: {}".format(nslcmop_id
, step
,
2935 if db_nslcmop
and db_nslcmop_update
:
2936 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2938 db_nsr_update
["_admin.current-operation"] = None
2939 db_nsr_update
["_admin.operation-type"] = None
2940 db_nsr_update
["_admin.nslcmop"] = None
2941 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2942 except DbException
as e
:
2943 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
2944 if nslcmop_operation_state
:
2946 await self
.msg
.aiowrite("ns", "scaled", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2947 "operationState": nslcmop_operation_state
},
2950 # await asyncio.sleep(cooldown_time, loop=self.loop)
2951 # await self.msg.aiowrite("ns","scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
2952 except Exception as e
:
2953 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
2954 self
.logger
.debug(logging_text
+ "Exit")
2955 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_scale")