1 # -*- coding: utf-8 -*-
4 # Copyright 2018 Telefonica S.A.
6 # Licensed under the Apache License, Version 2.0 (the "License"); you may
7 # not use this file except in compliance with the License. You may obtain
8 # a copy of the License at
10 # http://www.apache.org/licenses/LICENSE-2.0
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 # License for the specific language governing permissions and limitations
22 import logging
.handlers
24 from jinja2
import Environment
, Template
, meta
, TemplateError
, TemplateNotFound
, TemplateSyntaxError
26 from osm_lcm
import ROclient
27 from osm_lcm
.lcm_utils
import LcmException
, LcmExceptionNoMgmtIP
, LcmBase
28 from n2vc
.k8s_helm_conn
import K8sHelmConnector
30 from osm_common
.dbbase
import DbException
31 from osm_common
.fsbase
import FsException
33 from n2vc
.n2vc_juju_conn
import N2VCJujuConnector
35 from copy
import copy
, deepcopy
36 from http
import HTTPStatus
38 from uuid
import uuid4
40 __author__
= "Alfonso Tierno"
43 def get_iterable(in_dict
, in_key
):
45 Similar to <dict>.get(), but if value is None, False, ..., An empty tuple is returned instead
46 :param in_dict: a dictionary
47 :param in_key: the key to look for at in_dict
48 :return: in_dict[in_var] or () if it is None or not present
50 if not in_dict
.get(in_key
):
52 return in_dict
[in_key
]
55 def populate_dict(target_dict
, key_list
, value
):
57 Update target_dict creating nested dictionaries with the key_list. Last key_list item is asigned the value.
58 Example target_dict={K: J}; key_list=[a,b,c]; target_dict will be {K: J, a: {b: {c: value}}}
59 :param target_dict: dictionary to be changed
60 :param key_list: list of keys to insert at target_dict
64 for key
in key_list
[0:-1]:
65 if key
not in target_dict
:
67 target_dict
= target_dict
[key
]
68 target_dict
[key_list
[-1]] = value
71 def deep_get(target_dict
, key_list
):
73 Get a value from target_dict entering in the nested keys. If keys does not exist, it returns None
74 Example target_dict={a: {b: 5}}; key_list=[a,b] returns 5; both key_list=[a,b,c] and key_list=[f,h] return None
75 :param target_dict: dictionary to be read
76 :param key_list: list of keys to read from target_dict
77 :return: The wanted value if exist, None otherwise
80 if not isinstance(target_dict
, dict) or key
not in target_dict
:
82 target_dict
= target_dict
[key
]
87 timeout_vca_on_error
= 5 * 60 # Time for charm from first time at blocked,error status to mark as failed
88 total_deploy_timeout
= 2 * 3600 # global timeout for deployment
89 timeout_charm_delete
= 10 * 60
90 timeout_primitive
= 10 * 60 # timeout for primitive execution
92 SUBOPERATION_STATUS_NOT_FOUND
= -1
93 SUBOPERATION_STATUS_NEW
= -2
94 SUBOPERATION_STATUS_SKIP
= -3
96 def __init__(self
, db
, msg
, fs
, lcm_tasks
, ro_config
, vca_config
, loop
):
98 Init, Connect to database, filesystem storage, and messaging
99 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
106 logger
=logging
.getLogger('lcm.ns')
110 self
.lcm_tasks
= lcm_tasks
111 self
.ro_config
= ro_config
112 self
.vca_config
= vca_config
113 if 'pubkey' in self
.vca_config
:
114 self
.vca_config
['public_key'] = self
.vca_config
['pubkey']
115 if 'cacert' in self
.vca_config
:
116 self
.vca_config
['ca_cert'] = self
.vca_config
['cacert']
117 if 'apiproxy' in self
.vca_config
:
118 self
.vca_config
['api_proxy'] = self
.vca_config
['apiproxy']
120 # create N2VC connector
121 self
.n2vc
= N2VCJujuConnector(
126 url
='{}:{}'.format(self
.vca_config
['host'], self
.vca_config
['port']),
127 username
=self
.vca_config
.get('user', None),
128 vca_config
=self
.vca_config
,
129 on_update_db
=self
._on
_update
_n
2vc
_db
,
130 # ca_cert=self.vca_config.get('cacert'),
131 # api_proxy=self.vca_config.get('apiproxy'),
134 self
.k8sclusterhelm
= K8sHelmConnector(
135 kubectl_command
=self
.vca_config
.get("kubectlpath"),
136 helm_command
=self
.vca_config
.get("helmpath"),
144 self
.RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
146 def _on_update_n2vc_db(self
, table
, filter, path
, updated_data
):
148 self
.logger
.debug('_on_update_n2vc_db(table={}, filter={}, path={}, updated_data={}'
149 .format(table
, filter, path
, updated_data
))
152 # write NS status to database
154 # # nsrs_id = filter.get('_id')
157 # nsr = self.db.get_one(table=table, q_filter=filter)
158 # # get VCA deployed list
159 # vca_list = deep_get(target_dict=nsr, key_list=('_admin', 'deployed', 'VCA'))
161 # # ro_list = deep_get(target_dict=nsr, key_list=('_admin', 'deployed', 'RO'))
162 # for vca in vca_list:
163 # # status = vca.get('status')
165 # # detailed_status = vca.get('detailed-status')
166 # # print(detailed_status)
167 # # for ro in ro_list:
170 # except Exception as e:
171 # self.logger.error('Error writing NS status to db: {}'.format(e))
173 def vnfd2RO(self
, vnfd
, new_id
=None, additionalParams
=None, nsrId
=None):
175 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
176 :param vnfd: input vnfd
177 :param new_id: overrides vnf id if provided
178 :param additionalParams: Instantiation params for VNFs provided
179 :param nsrId: Id of the NSR
180 :return: copy of vnfd
183 vnfd_RO
= deepcopy(vnfd
)
184 # remove unused by RO configuration, monitoring, scaling and internal keys
185 vnfd_RO
.pop("_id", None)
186 vnfd_RO
.pop("_admin", None)
187 vnfd_RO
.pop("vnf-configuration", None)
188 vnfd_RO
.pop("monitoring-param", None)
189 vnfd_RO
.pop("scaling-group-descriptor", None)
190 vnfd_RO
.pop("kdu", None)
191 vnfd_RO
.pop("k8s-cluster", None)
193 vnfd_RO
["id"] = new_id
195 # parse cloud-init or cloud-init-file with the provided variables using Jinja2
196 for vdu
in get_iterable(vnfd_RO
, "vdu"):
197 cloud_init_file
= None
198 if vdu
.get("cloud-init-file"):
199 base_folder
= vnfd
["_admin"]["storage"]
200 cloud_init_file
= "{}/{}/cloud_init/{}".format(base_folder
["folder"], base_folder
["pkg-dir"],
201 vdu
["cloud-init-file"])
202 with self
.fs
.file_open(cloud_init_file
, "r") as ci_file
:
203 cloud_init_content
= ci_file
.read()
204 vdu
.pop("cloud-init-file", None)
205 elif vdu
.get("cloud-init"):
206 cloud_init_content
= vdu
["cloud-init"]
211 ast
= env
.parse(cloud_init_content
)
212 mandatory_vars
= meta
.find_undeclared_variables(ast
)
214 for var
in mandatory_vars
:
215 if not additionalParams
or var
not in additionalParams
.keys():
216 raise LcmException("Variable '{}' defined at vnfd[id={}]:vdu[id={}]:cloud-init/cloud-init-"
217 "file, must be provided in the instantiation parameters inside the "
218 "'additionalParamsForVnf' block".format(var
, vnfd
["id"], vdu
["id"]))
219 template
= Template(cloud_init_content
)
220 cloud_init_content
= template
.render(additionalParams
or {})
221 vdu
["cloud-init"] = cloud_init_content
224 except FsException
as e
:
225 raise LcmException("Error reading vnfd[id={}]:vdu[id={}]:cloud-init-file={}: {}".
226 format(vnfd
["id"], vdu
["id"], cloud_init_file
, e
))
227 except (TemplateError
, TemplateNotFound
, TemplateSyntaxError
) as e
:
228 raise LcmException("Error parsing Jinja2 to cloud-init content at vnfd[id={}]:vdu[id={}]: {}".
229 format(vnfd
["id"], vdu
["id"], e
))
231 def ns_params_2_RO(self
, ns_params
, nsd
, vnfd_dict
, n2vc_key_list
):
233 Creates a RO ns descriptor from OSM ns_instantiate params
234 :param ns_params: OSM instantiate params
235 :return: The RO ns descriptor
239 # TODO feature 1417: Check that no instantiation is set over PDU
240 # check if PDU forces a concrete vim-network-id and add it
241 # check if PDU contains a SDN-assist info (dpid, switch, port) and pass it to RO
243 def vim_account_2_RO(vim_account
):
244 if vim_account
in vim_2_RO
:
245 return vim_2_RO
[vim_account
]
247 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_account
})
248 if db_vim
["_admin"]["operationalState"] != "ENABLED":
249 raise LcmException("VIM={} is not available. operationalState={}".format(
250 vim_account
, db_vim
["_admin"]["operationalState"]))
251 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
252 vim_2_RO
[vim_account
] = RO_vim_id
255 def wim_account_2_RO(wim_account
):
256 if isinstance(wim_account
, str):
257 if wim_account
in wim_2_RO
:
258 return wim_2_RO
[wim_account
]
260 db_wim
= self
.db
.get_one("wim_accounts", {"_id": wim_account
})
261 if db_wim
["_admin"]["operationalState"] != "ENABLED":
262 raise LcmException("WIM={} is not available. operationalState={}".format(
263 wim_account
, db_wim
["_admin"]["operationalState"]))
264 RO_wim_id
= db_wim
["_admin"]["deployed"]["RO-account"]
265 wim_2_RO
[wim_account
] = RO_wim_id
270 def ip_profile_2_RO(ip_profile
):
271 RO_ip_profile
= deepcopy((ip_profile
))
272 if "dns-server" in RO_ip_profile
:
273 if isinstance(RO_ip_profile
["dns-server"], list):
274 RO_ip_profile
["dns-address"] = []
275 for ds
in RO_ip_profile
.pop("dns-server"):
276 RO_ip_profile
["dns-address"].append(ds
['address'])
278 RO_ip_profile
["dns-address"] = RO_ip_profile
.pop("dns-server")
279 if RO_ip_profile
.get("ip-version") == "ipv4":
280 RO_ip_profile
["ip-version"] = "IPv4"
281 if RO_ip_profile
.get("ip-version") == "ipv6":
282 RO_ip_profile
["ip-version"] = "IPv6"
283 if "dhcp-params" in RO_ip_profile
:
284 RO_ip_profile
["dhcp"] = RO_ip_profile
.pop("dhcp-params")
290 # "name": ns_params["nsName"],
291 # "description": ns_params.get("nsDescription"),
292 "datacenter": vim_account_2_RO(ns_params
["vimAccountId"]),
293 "wim_account": wim_account_2_RO(ns_params
.get("wimAccountId")),
294 # "scenario": ns_params["nsdId"],
297 n2vc_key_list
= n2vc_key_list
or []
298 for vnfd_ref
, vnfd
in vnfd_dict
.items():
299 vdu_needed_access
= []
301 if vnfd
.get("vnf-configuration"):
302 ssh_required
= deep_get(vnfd
, ("vnf-configuration", "config-access", "ssh-access", "required"))
303 if ssh_required
and vnfd
.get("mgmt-interface"):
304 if vnfd
["mgmt-interface"].get("vdu-id"):
305 vdu_needed_access
.append(vnfd
["mgmt-interface"]["vdu-id"])
306 elif vnfd
["mgmt-interface"].get("cp"):
307 mgmt_cp
= vnfd
["mgmt-interface"]["cp"]
309 for vdu
in vnfd
.get("vdu", ()):
310 if vdu
.get("vdu-configuration"):
311 ssh_required
= deep_get(vdu
, ("vdu-configuration", "config-access", "ssh-access", "required"))
313 vdu_needed_access
.append(vdu
["id"])
315 for vdu_interface
in vdu
.get("interface"):
316 if vdu_interface
.get("external-connection-point-ref") and \
317 vdu_interface
["external-connection-point-ref"] == mgmt_cp
:
318 vdu_needed_access
.append(vdu
["id"])
322 if vdu_needed_access
:
323 for vnf_member
in nsd
.get("constituent-vnfd"):
324 if vnf_member
["vnfd-id-ref"] != vnfd_ref
:
326 for vdu
in vdu_needed_access
:
327 populate_dict(RO_ns_params
,
328 ("vnfs", vnf_member
["member-vnf-index"], "vdus", vdu
, "mgmt_keys"),
331 if ns_params
.get("vduImage"):
332 RO_ns_params
["vduImage"] = ns_params
["vduImage"]
334 if ns_params
.get("ssh_keys"):
335 RO_ns_params
["cloud-config"] = {"key-pairs": ns_params
["ssh_keys"]}
336 for vnf_params
in get_iterable(ns_params
, "vnf"):
337 for constituent_vnfd
in nsd
["constituent-vnfd"]:
338 if constituent_vnfd
["member-vnf-index"] == vnf_params
["member-vnf-index"]:
339 vnf_descriptor
= vnfd_dict
[constituent_vnfd
["vnfd-id-ref"]]
342 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index={} is not present at nsd:"
343 "constituent-vnfd".format(vnf_params
["member-vnf-index"]))
344 if vnf_params
.get("vimAccountId"):
345 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "datacenter"),
346 vim_account_2_RO(vnf_params
["vimAccountId"]))
348 for vdu_params
in get_iterable(vnf_params
, "vdu"):
349 # TODO feature 1417: check that this VDU exist and it is not a PDU
350 if vdu_params
.get("volume"):
351 for volume_params
in vdu_params
["volume"]:
352 if volume_params
.get("vim-volume-id"):
353 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
354 vdu_params
["id"], "devices", volume_params
["name"], "vim_id"),
355 volume_params
["vim-volume-id"])
356 if vdu_params
.get("interface"):
357 for interface_params
in vdu_params
["interface"]:
358 if interface_params
.get("ip-address"):
359 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
360 vdu_params
["id"], "interfaces", interface_params
["name"],
362 interface_params
["ip-address"])
363 if interface_params
.get("mac-address"):
364 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
365 vdu_params
["id"], "interfaces", interface_params
["name"],
367 interface_params
["mac-address"])
368 if interface_params
.get("floating-ip-required"):
369 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
370 vdu_params
["id"], "interfaces", interface_params
["name"],
372 interface_params
["floating-ip-required"])
374 for internal_vld_params
in get_iterable(vnf_params
, "internal-vld"):
375 if internal_vld_params
.get("vim-network-name"):
376 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
377 internal_vld_params
["name"], "vim-network-name"),
378 internal_vld_params
["vim-network-name"])
379 if internal_vld_params
.get("vim-network-id"):
380 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
381 internal_vld_params
["name"], "vim-network-id"),
382 internal_vld_params
["vim-network-id"])
383 if internal_vld_params
.get("ip-profile"):
384 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
385 internal_vld_params
["name"], "ip-profile"),
386 ip_profile_2_RO(internal_vld_params
["ip-profile"]))
387 if internal_vld_params
.get("provider-network"):
389 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
390 internal_vld_params
["name"], "provider-network"),
391 internal_vld_params
["provider-network"].copy())
393 for icp_params
in get_iterable(internal_vld_params
, "internal-connection-point"):
396 for vdu_descriptor
in vnf_descriptor
["vdu"]:
397 for vdu_interface
in vdu_descriptor
["interface"]:
398 if vdu_interface
.get("internal-connection-point-ref") == icp_params
["id-ref"]:
399 if icp_params
.get("ip-address"):
400 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
401 vdu_descriptor
["id"], "interfaces",
402 vdu_interface
["name"], "ip_address"),
403 icp_params
["ip-address"])
405 if icp_params
.get("mac-address"):
406 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
407 vdu_descriptor
["id"], "interfaces",
408 vdu_interface
["name"], "mac_address"),
409 icp_params
["mac-address"])
415 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
416 "internal-vld:id-ref={} is not present at vnfd:internal-"
417 "connection-point".format(vnf_params
["member-vnf-index"],
418 icp_params
["id-ref"]))
420 for vld_params
in get_iterable(ns_params
, "vld"):
421 if "ip-profile" in vld_params
:
422 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "ip-profile"),
423 ip_profile_2_RO(vld_params
["ip-profile"]))
425 if vld_params
.get("provider-network"):
427 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "provider-network"),
428 vld_params
["provider-network"].copy())
430 if "wimAccountId" in vld_params
and vld_params
["wimAccountId"] is not None:
431 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "wim_account"),
432 wim_account_2_RO(vld_params
["wimAccountId"])),
433 if vld_params
.get("vim-network-name"):
435 if isinstance(vld_params
["vim-network-name"], dict):
436 for vim_account
, vim_net
in vld_params
["vim-network-name"].items():
437 RO_vld_sites
.append({
438 "netmap-use": vim_net
,
439 "datacenter": vim_account_2_RO(vim_account
)
441 else: # isinstance str
442 RO_vld_sites
.append({"netmap-use": vld_params
["vim-network-name"]})
444 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "sites"), RO_vld_sites
)
446 if vld_params
.get("vim-network-id"):
448 if isinstance(vld_params
["vim-network-id"], dict):
449 for vim_account
, vim_net
in vld_params
["vim-network-id"].items():
450 RO_vld_sites
.append({
451 "netmap-use": vim_net
,
452 "datacenter": vim_account_2_RO(vim_account
)
454 else: # isinstance str
455 RO_vld_sites
.append({"netmap-use": vld_params
["vim-network-id"]})
457 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "sites"), RO_vld_sites
)
458 if vld_params
.get("ns-net"):
459 if isinstance(vld_params
["ns-net"], dict):
460 for vld_id
, instance_scenario_id
in vld_params
["ns-net"].items():
461 RO_vld_ns_net
= {"instance_scenario_id": instance_scenario_id
, "osm_id": vld_id
}
463 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "use-network"), RO_vld_ns_net
)
464 if "vnfd-connection-point-ref" in vld_params
:
465 for cp_params
in vld_params
["vnfd-connection-point-ref"]:
467 for constituent_vnfd
in nsd
["constituent-vnfd"]:
468 if constituent_vnfd
["member-vnf-index"] == cp_params
["member-vnf-index-ref"]:
469 vnf_descriptor
= vnfd_dict
[constituent_vnfd
["vnfd-id-ref"]]
473 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={} "
474 "is not present at nsd:constituent-vnfd".format(cp_params
["member-vnf-index-ref"]))
476 for vdu_descriptor
in vnf_descriptor
["vdu"]:
477 for interface_descriptor
in vdu_descriptor
["interface"]:
478 if interface_descriptor
.get("external-connection-point-ref") == \
479 cp_params
["vnfd-connection-point-ref"]:
486 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={}:"
487 "vnfd-connection-point-ref={} is not present at vnfd={}".format(
488 cp_params
["member-vnf-index-ref"],
489 cp_params
["vnfd-connection-point-ref"],
490 vnf_descriptor
["id"]))
491 if cp_params
.get("ip-address"):
492 populate_dict(RO_ns_params
, ("vnfs", cp_params
["member-vnf-index-ref"], "vdus",
493 vdu_descriptor
["id"], "interfaces",
494 interface_descriptor
["name"], "ip_address"),
495 cp_params
["ip-address"])
496 if cp_params
.get("mac-address"):
497 populate_dict(RO_ns_params
, ("vnfs", cp_params
["member-vnf-index-ref"], "vdus",
498 vdu_descriptor
["id"], "interfaces",
499 interface_descriptor
["name"], "mac_address"),
500 cp_params
["mac-address"])
503 def scale_vnfr(self
, db_vnfr
, vdu_create
=None, vdu_delete
=None):
504 # make a copy to do not change
505 vdu_create
= copy(vdu_create
)
506 vdu_delete
= copy(vdu_delete
)
508 vdurs
= db_vnfr
.get("vdur")
511 vdu_index
= len(vdurs
)
514 vdur
= vdurs
[vdu_index
]
515 if vdur
.get("pdu-type"):
517 vdu_id_ref
= vdur
["vdu-id-ref"]
518 if vdu_create
and vdu_create
.get(vdu_id_ref
):
519 for index
in range(0, vdu_create
[vdu_id_ref
]):
520 vdur
= deepcopy(vdur
)
521 vdur
["_id"] = str(uuid4())
522 vdur
["count-index"] += 1
523 vdurs
.insert(vdu_index
+1+index
, vdur
)
524 del vdu_create
[vdu_id_ref
]
525 if vdu_delete
and vdu_delete
.get(vdu_id_ref
):
527 vdu_delete
[vdu_id_ref
] -= 1
528 if not vdu_delete
[vdu_id_ref
]:
529 del vdu_delete
[vdu_id_ref
]
530 # check all operations are done
531 if vdu_create
or vdu_delete
:
532 raise LcmException("Error scaling OUT VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
535 raise LcmException("Error scaling IN VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
538 vnfr_update
= {"vdur": vdurs
}
539 db_vnfr
["vdur"] = vdurs
540 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
542 def ns_update_nsr(self
, ns_update_nsr
, db_nsr
, nsr_desc_RO
):
544 Updates database nsr with the RO info for the created vld
545 :param ns_update_nsr: dictionary to be filled with the updated info
546 :param db_nsr: content of db_nsr. This is also modified
547 :param nsr_desc_RO: nsr descriptor from RO
548 :return: Nothing, LcmException is raised on errors
551 for vld_index
, vld
in enumerate(get_iterable(db_nsr
, "vld")):
552 for net_RO
in get_iterable(nsr_desc_RO
, "nets"):
553 if vld
["id"] != net_RO
.get("ns_net_osm_id"):
555 vld
["vim-id"] = net_RO
.get("vim_net_id")
556 vld
["name"] = net_RO
.get("vim_name")
557 vld
["status"] = net_RO
.get("status")
558 vld
["status-detailed"] = net_RO
.get("error_msg")
559 ns_update_nsr
["vld.{}".format(vld_index
)] = vld
562 raise LcmException("ns_update_nsr: Not found vld={} at RO info".format(vld
["id"]))
564 def ns_update_vnfr(self
, db_vnfrs
, nsr_desc_RO
):
566 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
567 :param db_vnfrs: dictionary with member-vnf-index: vnfr-content
568 :param nsr_desc_RO: nsr descriptor from RO
569 :return: Nothing, LcmException is raised on errors
571 for vnf_index
, db_vnfr
in db_vnfrs
.items():
572 for vnf_RO
in nsr_desc_RO
["vnfs"]:
573 if vnf_RO
["member_vnf_index"] != vnf_index
:
576 if vnf_RO
.get("ip_address"):
577 db_vnfr
["ip-address"] = vnfr_update
["ip-address"] = vnf_RO
["ip_address"].split(";")[0]
578 elif not db_vnfr
.get("ip-address"):
579 raise LcmExceptionNoMgmtIP("ns member_vnf_index '{}' has no IP address".format(vnf_index
))
581 for vdu_index
, vdur
in enumerate(get_iterable(db_vnfr
, "vdur")):
582 vdur_RO_count_index
= 0
583 if vdur
.get("pdu-type"):
585 for vdur_RO
in get_iterable(vnf_RO
, "vms"):
586 if vdur
["vdu-id-ref"] != vdur_RO
["vdu_osm_id"]:
588 if vdur
["count-index"] != vdur_RO_count_index
:
589 vdur_RO_count_index
+= 1
591 vdur
["vim-id"] = vdur_RO
.get("vim_vm_id")
592 if vdur_RO
.get("ip_address"):
593 vdur
["ip-address"] = vdur_RO
["ip_address"].split(";")[0]
595 vdur
["ip-address"] = None
596 vdur
["vdu-id-ref"] = vdur_RO
.get("vdu_osm_id")
597 vdur
["name"] = vdur_RO
.get("vim_name")
598 vdur
["status"] = vdur_RO
.get("status")
599 vdur
["status-detailed"] = vdur_RO
.get("error_msg")
600 for ifacer
in get_iterable(vdur
, "interfaces"):
601 for interface_RO
in get_iterable(vdur_RO
, "interfaces"):
602 if ifacer
["name"] == interface_RO
.get("internal_name"):
603 ifacer
["ip-address"] = interface_RO
.get("ip_address")
604 ifacer
["mac-address"] = interface_RO
.get("mac_address")
607 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} interface={} "
609 .format(vnf_index
, vdur
["vdu-id-ref"], ifacer
["name"]))
610 vnfr_update
["vdur.{}".format(vdu_index
)] = vdur
613 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} count_index={} from "
614 "VIM info".format(vnf_index
, vdur
["vdu-id-ref"], vdur
["count-index"]))
616 for vld_index
, vld
in enumerate(get_iterable(db_vnfr
, "vld")):
617 for net_RO
in get_iterable(nsr_desc_RO
, "nets"):
618 if vld
["id"] != net_RO
.get("vnf_net_osm_id"):
620 vld
["vim-id"] = net_RO
.get("vim_net_id")
621 vld
["name"] = net_RO
.get("vim_name")
622 vld
["status"] = net_RO
.get("status")
623 vld
["status-detailed"] = net_RO
.get("error_msg")
624 vnfr_update
["vld.{}".format(vld_index
)] = vld
627 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vld={} from VIM info".format(
628 vnf_index
, vld
["id"]))
630 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
634 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} from VIM info".format(vnf_index
))
637 def _get_ns_config_info(vca_deployed_list
):
639 Generates a mapping between vnf,vdu elements and the N2VC id
640 :param vca_deployed_list: List of database _admin.deploy.VCA that contains this list
641 :return: a dictionary with {osm-config-mapping: {}} where its element contains:
642 "<member-vnf-index>": <N2VC-id> for a vnf configuration, or
643 "<member-vnf-index>.<vdu.id>.<vdu replica(0, 1,..)>": <N2VC-id> for a vdu configuration
646 ns_config_info
= {"osm-config-mapping": mapping
}
647 for vca
in vca_deployed_list
:
648 if not vca
["member-vnf-index"]:
650 if not vca
["vdu_id"]:
651 mapping
[vca
["member-vnf-index"]] = vca
["application"]
653 mapping
["{}.{}.{}".format(vca
["member-vnf-index"], vca
["vdu_id"], vca
["vdu_count_index"])] =\
655 return ns_config_info
658 def _get_initial_config_primitive_list(desc_primitive_list
, vca_deployed
):
660 Generates a list of initial-config-primitive based on the list provided by the descriptor. It includes internal
661 primitives as verify-ssh-credentials, or config when needed
662 :param desc_primitive_list: information of the descriptor
663 :param vca_deployed: information of the deployed, needed for known if it is related to an NS, VNF, VDU and if
664 this element contains a ssh public key
665 :return: The modified list. Can ba an empty list, but always a list
667 if desc_primitive_list
:
668 primitive_list
= desc_primitive_list
.copy()
671 # look for primitive config, and get the position. None if not present
672 config_position
= None
673 for index
, primitive
in enumerate(primitive_list
):
674 if primitive
["name"] == "config":
675 config_position
= index
678 # for NS, add always a config primitive if not present (bug 874)
679 if not vca_deployed
["member-vnf-index"] and config_position
is None:
680 primitive_list
.insert(0, {"name": "config", "parameter": []})
682 # for VNF/VDU add verify-ssh-credentials after config
683 if vca_deployed
["member-vnf-index"] and config_position
is not None and vca_deployed
.get("ssh-public-key"):
684 primitive_list
.insert(config_position
+ 1, {"name": "verify-ssh-credentials", "parameter": []})
685 return primitive_list
687 async def instantiate_RO(self
, logging_text
, nsr_id
, nsd
, db_nsr
,
688 db_nslcmop
, db_vnfrs
, db_vnfds_ref
, n2vc_key_list
):
691 RO_descriptor_number
= 0 # number of descriptors created at RO
692 vnf_index_2_RO_id
= {} # map between vnfd/nsd id to the id used at RO
693 start_deploy
= time()
694 vdu_flag
= False # If any of the VNFDs has VDUs
695 ns_params
= db_nslcmop
.get("operationParams")
699 # get vnfds, instantiate at RO
701 for c_vnf
in nsd
.get("constituent-vnfd", ()):
702 member_vnf_index
= c_vnf
["member-vnf-index"]
703 vnfd
= db_vnfds_ref
[c_vnf
['vnfd-id-ref']]
706 vnfd_ref
= vnfd
["id"]
707 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Creating vnfd='{}' member_vnf_index='{}' at" \
708 " RO".format(vnfd_ref
, member_vnf_index
)
709 # self.logger.debug(logging_text + step)
710 vnfd_id_RO
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, member_vnf_index
[:23])
711 vnf_index_2_RO_id
[member_vnf_index
] = vnfd_id_RO
712 RO_descriptor_number
+= 1
714 # look position at deployed.RO.vnfd if not present it will be appended at the end
715 for index
, vnf_deployed
in enumerate(db_nsr
["_admin"]["deployed"]["RO"]["vnfd"]):
716 if vnf_deployed
["member-vnf-index"] == member_vnf_index
:
719 index
= len(db_nsr
["_admin"]["deployed"]["RO"]["vnfd"])
720 db_nsr
["_admin"]["deployed"]["RO"]["vnfd"].append(None)
723 RO_update
= {"member-vnf-index": member_vnf_index
}
724 vnfd_list
= await self
.RO
.get_list("vnfd", filter_by
={"osm_id": vnfd_id_RO
})
726 RO_update
["id"] = vnfd_list
[0]["uuid"]
727 self
.logger
.debug(logging_text
+ "vnfd='{}' member_vnf_index='{}' exists at RO. Using RO_id={}".
728 format(vnfd_ref
, member_vnf_index
, vnfd_list
[0]["uuid"]))
730 vnfd_RO
= self
.vnfd2RO(vnfd
, vnfd_id_RO
, db_vnfrs
[c_vnf
["member-vnf-index"]].
731 get("additionalParamsForVnf"), nsr_id
)
732 desc
= await self
.RO
.create("vnfd", descriptor
=vnfd_RO
)
733 RO_update
["id"] = desc
["uuid"]
734 self
.logger
.debug(logging_text
+ "vnfd='{}' member_vnf_index='{}' created at RO. RO_id={}".format(
735 vnfd_ref
, member_vnf_index
, desc
["uuid"]))
736 db_nsr_update
["_admin.deployed.RO.vnfd.{}".format(index
)] = RO_update
737 db_nsr
["_admin"]["deployed"]["RO"]["vnfd"][index
] = RO_update
738 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
739 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
743 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Creating nsd={} at RO".format(nsd_ref
)
744 # self.logger.debug(logging_text + step)
746 RO_osm_nsd_id
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, nsd_ref
[:23])
747 RO_descriptor_number
+= 1
748 nsd_list
= await self
.RO
.get_list("nsd", filter_by
={"osm_id": RO_osm_nsd_id
})
750 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= nsd_list
[0]["uuid"]
751 self
.logger
.debug(logging_text
+ "nsd={} exists at RO. Using RO_id={}".format(
752 nsd_ref
, RO_nsd_uuid
))
754 nsd_RO
= deepcopy(nsd
)
755 nsd_RO
["id"] = RO_osm_nsd_id
756 nsd_RO
.pop("_id", None)
757 nsd_RO
.pop("_admin", None)
758 for c_vnf
in nsd_RO
.get("constituent-vnfd", ()):
759 member_vnf_index
= c_vnf
["member-vnf-index"]
760 c_vnf
["vnfd-id-ref"] = vnf_index_2_RO_id
[member_vnf_index
]
761 for c_vld
in nsd_RO
.get("vld", ()):
762 for cp
in c_vld
.get("vnfd-connection-point-ref", ()):
763 member_vnf_index
= cp
["member-vnf-index-ref"]
764 cp
["vnfd-id-ref"] = vnf_index_2_RO_id
[member_vnf_index
]
766 desc
= await self
.RO
.create("nsd", descriptor
=nsd_RO
)
767 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
768 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= desc
["uuid"]
769 self
.logger
.debug(logging_text
+ "nsd={} created at RO. RO_id={}".format(nsd_ref
, RO_nsd_uuid
))
770 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
771 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
774 # if present use it unless in error status
775 RO_nsr_id
= deep_get(db_nsr
, ("_admin", "deployed", "RO", "nsr_id"))
778 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Looking for existing ns at RO"
779 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
780 desc
= await self
.RO
.show("ns", RO_nsr_id
)
781 except ROclient
.ROClientException
as e
:
782 if e
.http_code
!= HTTPStatus
.NOT_FOUND
:
784 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
786 ns_status
, ns_status_info
= self
.RO
.check_ns_status(desc
)
787 db_nsr_update
["_admin.deployed.RO.nsr_status"] = ns_status
788 if ns_status
== "ERROR":
789 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Deleting ns at RO. RO_ns_id={}"\
791 self
.logger
.debug(logging_text
+ step
)
792 await self
.RO
.delete("ns", RO_nsr_id
)
793 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
795 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Checking dependencies"
796 # self.logger.debug(logging_text + step)
798 # check if VIM is creating and wait look if previous tasks in process
799 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account", ns_params
["vimAccountId"])
801 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
802 self
.logger
.debug(logging_text
+ step
)
803 await asyncio
.wait(task_dependency
, timeout
=3600)
804 if ns_params
.get("vnf"):
805 for vnf
in ns_params
["vnf"]:
806 if "vimAccountId" in vnf
:
807 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account",
810 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
811 self
.logger
.debug(logging_text
+ step
)
812 await asyncio
.wait(task_dependency
, timeout
=3600)
814 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Checking instantiation parameters"
816 RO_ns_params
= self
.ns_params_2_RO(ns_params
, nsd
, db_vnfds_ref
, n2vc_key_list
)
818 step
= db_nsr_update
["detailed-status"] = "Deploying ns at VIM"
819 # step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Deploying ns at VIM"
820 desc
= await self
.RO
.create("ns", descriptor
=RO_ns_params
, name
=db_nsr
["name"], scenario
=RO_nsd_uuid
)
821 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = desc
["uuid"]
822 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
823 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "BUILD"
824 self
.logger
.debug(logging_text
+ "ns created at RO. RO_id={}".format(desc
["uuid"]))
825 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
826 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
828 # wait until NS is ready
829 step
= ns_status_detailed
= detailed_status
= "Waiting VIM to deploy ns. RO_ns_id={}".format(RO_nsr_id
)
830 detailed_status_old
= None
831 self
.logger
.debug(logging_text
+ step
)
833 while time() <= start_deploy
+ self
.total_deploy_timeout
:
834 desc
= await self
.RO
.show("ns", RO_nsr_id
)
835 ns_status
, ns_status_info
= self
.RO
.check_ns_status(desc
)
836 db_nsr_update
["_admin.deployed.RO.nsr_status"] = ns_status
837 if ns_status
== "ERROR":
838 raise ROclient
.ROClientException(ns_status_info
)
839 elif ns_status
== "BUILD":
840 detailed_status
= ns_status_detailed
+ "; {}".format(ns_status_info
)
841 elif ns_status
== "ACTIVE":
842 step
= detailed_status
= "Waiting for management IP address reported by the VIM. Updating VNFRs"
845 self
.ns_update_vnfr(db_vnfrs
, desc
)
847 except LcmExceptionNoMgmtIP
:
850 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
851 if detailed_status
!= detailed_status_old
:
852 detailed_status_old
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = detailed_status
853 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
854 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
855 await asyncio
.sleep(5, loop
=self
.loop
)
856 else: # total_deploy_timeout
857 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
859 step
= "Updating NSR"
860 self
.ns_update_nsr(db_nsr_update
, db_nsr
, desc
)
862 db_nsr_update
["_admin.deployed.RO.operational-status"] = "running"
863 db_nsr
["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
864 db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
865 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
866 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
868 step
= "Deployed at VIM"
869 self
.logger
.debug(logging_text
+ step
)
871 async def wait_vm_up_insert_key_ro(self
, logging_text
, nsr_id
, vnfr_id
, vdu_id
, vdu_index
, pub_key
=None, user
=None):
873 Wait for ip addres at RO, and optionally, insert public key in virtual machine
874 :param logging_text: prefix use for logging
879 :param pub_key: public ssh key to inject, None to skip
880 :param user: user to apply the public ssh key
884 # self.logger.debug(logging_text + "Starting wait_vm_up_insert_key_ro")
892 await asyncio
.sleep(10, loop
=self
.loop
)
893 # wait until NS is deployed at RO
895 db_nsrs
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
896 ro_nsr_id
= deep_get(db_nsrs
, ("_admin", "deployed", "RO", "nsr_id"))
901 if not target_vdu_id
:
902 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnfr_id
})
904 ip_address
= db_vnfr
.get("ip-address")
907 for vdur
in get_iterable(db_vnfr
, "vdur"):
908 if (vdur
["vdu-id-ref"] == vdu_id
and vdur
["count-index"] == vdu_index
) or \
909 (ip_address
and vdur
.get("ip-address") == ip_address
):
910 if vdur
["status"] == "ACTIVE":
911 target_vdu_id
= vdur
["vdu-id-ref"]
912 elif vdur
["status"] == "ERROR":
913 raise LcmException("Cannot inject ssh-key because target VM is in error state")
916 raise LcmException("Not found vnfr_id={}, vdu_index={}, vdu_index={}".format(
917 vnfr_id
, vdu_id
, vdu_index
920 if not target_vdu_id
:
923 # self.logger.debug(logging_text + "IP address={}".format(ip_address))
925 # inject public key into machine
927 # self.logger.debug(logging_text + "Inserting RO key")
929 ro_vm_id
= "{}-{}".format(db_vnfr
["member-vnf-index-ref"], target_vdu_id
) # TODO add vdu_index
930 result_dict
= await self
.RO
.create_action(
932 item_id_name
=ro_nsr_id
,
933 descriptor
={"add_public_key": pub_key
, "vms": [ro_vm_id
], "user": user
}
935 # result_dict contains the format {VM-id: {vim_result: 200, description: text}}
936 if not result_dict
or not isinstance(result_dict
, dict):
937 raise LcmException("Unknown response from RO when injecting key")
938 for result
in result_dict
.values():
939 if result
.get("vim_result") == 200:
942 raise ROclient
.ROClientException("error injecting key: {}".format(
943 result
.get("description")))
945 except ROclient
.ROClientException
as e
:
947 self
.logger
.debug(logging_text
+ "error injecting key: {}. Retrying until {} seconds".
951 raise LcmException("Reaching max tries injecting key. Error: {}".format(e
))
957 async def instantiate_N2VC(self
, logging_text
, vca_index
, nsi_id
, db_nsr
, db_vnfr
, vdu_id
,
958 kdu_name
, vdu_index
, config_descriptor
, deploy_params
, base_folder
):
959 nsr_id
= db_nsr
["_id"]
960 db_update_entry
= "_admin.deployed.VCA.{}.".format(vca_index
)
961 vca_deployed_list
= db_nsr
["_admin"]["deployed"]["VCA"]
962 vca_deployed
= db_nsr
["_admin"]["deployed"]["VCA"][vca_index
]
964 'collection': 'nsrs',
965 'filter': {'_id': nsr_id
},
966 'path': db_update_entry
968 logging_text
+= "member_vnf_index={} vdu_id={}, vdu_index={} ".format(db_vnfr
["member-vnf-index-ref"],
975 vnfr_id
= db_vnfr
["_id"]
977 namespace
= "{nsi}.{ns}".format(
978 nsi
=nsi_id
if nsi_id
else "",
981 namespace
+= "." + vnfr_id
983 namespace
+= ".{}-{}".format(vdu_id
, vdu_index
or 0)
986 artifact_path
= "/{}/{}/charms/{}".format(
987 base_folder
["folder"],
988 base_folder
["pkg-dir"],
989 config_descriptor
["juju"]["charm"]
992 is_proxy_charm
= deep_get(config_descriptor
, ('juju', 'charm')) is not None
993 if deep_get(config_descriptor
, ('juju', 'proxy')) is False:
994 is_proxy_charm
= False
996 # n2vc_redesign STEP 3.1
998 # find old ee_id if exists
999 ee_id
= vca_deployed
.get("ee_id")
1001 # create or register execution environment in VCA
1003 step
= "create execution environment"
1004 self
.logger
.debug(logging_text
+ step
)
1005 ee_id
, credentials
= await self
.n2vc
.create_execution_environment(namespace
=namespace
,
1009 step
= "Waiting to VM being up and getting IP address"
1010 self
.logger
.debug(logging_text
+ step
)
1011 rw_mgmt_ip
= await self
.wait_vm_up_insert_key_ro(logging_text
, nsr_id
, vnfr_id
, vdu_id
, vdu_index
,
1012 user
=None, pub_key
=None)
1013 credentials
= {"hostname": rw_mgmt_ip
}
1015 username
= deep_get(config_descriptor
, ("config-access", "ssh-access", "default-user"))
1016 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1017 # merged. Meanwhile let's get username from initial-config-primitive
1018 if not username
and config_descriptor
.get("initial-config-primitive"):
1019 for config_primitive
in config_descriptor
["initial-config-primitive"]:
1020 for param
in config_primitive
.get("parameter", ()):
1021 if param
["name"] == "ssh-username":
1022 username
= param
["value"]
1025 raise LcmException("Cannot determine the username neither with 'initial-config-promitive' nor with "
1026 "'config-access.ssh-access.default-user'")
1027 credentials
["username"] = username
1028 # n2vc_redesign STEP 3.2
1030 step
= "register execution environment {}".format(credentials
)
1031 self
.logger
.debug(logging_text
+ step
)
1032 ee_id
= await self
.n2vc
.register_execution_environment(credentials
=credentials
, namespace
=namespace
,
1035 # for compatibility with MON/POL modules, the need model and application name at database
1036 # TODO ask to N2VC instead of assuming the format "model_name.application_name"
1037 ee_id_parts
= ee_id
.split('.')
1038 model_name
= ee_id_parts
[0]
1039 application_name
= ee_id_parts
[1]
1040 self
.update_db_2("nsrs", nsr_id
, {db_update_entry
+ "model": model_name
,
1041 db_update_entry
+ "application": application_name
,
1042 db_update_entry
+ "ee_id": ee_id
})
1044 # n2vc_redesign STEP 3.3
1046 step
= "Install configuration Software"
1047 # TODO check if already done
1048 self
.logger
.debug(logging_text
+ step
)
1049 await self
.n2vc
.install_configuration_sw(ee_id
=ee_id
, artifact_path
=artifact_path
, db_dict
=db_dict
)
1051 # if SSH access is required, then get execution environment SSH public
1052 if is_proxy_charm
: # if native charm we have waited already to VM be UP
1055 if deep_get(config_descriptor
, ("config-access", "ssh-access", "required")):
1056 # Needed to inject a ssh key
1057 user
= deep_get(config_descriptor
, ("config-access", "ssh-access", "default-user"))
1058 step
= "Install configuration Software, getting public ssh key"
1059 pub_key
= await self
.n2vc
.get_ee_ssh_public__key(ee_id
=ee_id
, db_dict
=db_dict
)
1061 step
= "Insert public key into VM"
1063 step
= "Waiting to VM being up and getting IP address"
1064 self
.logger
.debug(logging_text
+ step
)
1066 # n2vc_redesign STEP 5.1
1067 # wait for RO (ip-address) Insert pub_key into VM
1068 rw_mgmt_ip
= await self
.wait_vm_up_insert_key_ro(logging_text
, nsr_id
, vnfr_id
, vdu_id
, vdu_index
,
1069 user
=user
, pub_key
=pub_key
)
1071 self
.logger
.debug(logging_text
+ ' VM_ip_address={}'.format(rw_mgmt_ip
))
1073 # store rw_mgmt_ip in deploy params for later replacement
1074 deploy_params
["rw_mgmt_ip"] = rw_mgmt_ip
1076 # n2vc_redesign STEP 6 Execute initial config primitive
1077 step
= 'execute initial config primitive'
1078 initial_config_primitive_list
= config_descriptor
.get('initial-config-primitive')
1080 # sort initial config primitives by 'seq'
1082 initial_config_primitive_list
.sort(key
=lambda val
: int(val
['seq']))
1083 except Exception as e
:
1084 self
.logger
.error(logging_text
+ step
+ ": " + str(e
))
1086 # add config if not present for NS charm
1087 initial_config_primitive_list
= self
._get
_initial
_config
_primitive
_list
(initial_config_primitive_list
,
1090 for initial_config_primitive
in initial_config_primitive_list
:
1091 # adding information on the vca_deployed if it is a NS execution environment
1092 if not vca_deployed
["member-vnf-index"]:
1093 deploy_params
["ns_config_info"] = self
._get
_ns
_config
_info
(vca_deployed_list
)
1094 # TODO check if already done
1095 primitive_params_
= self
._map
_primitive
_params
(initial_config_primitive
, {}, deploy_params
)
1097 step
= "execute primitive '{}' params '{}'".format(initial_config_primitive
["name"], primitive_params_
)
1098 self
.logger
.debug(logging_text
+ step
)
1099 await self
.n2vc
.exec_primitive(
1101 primitive_name
=initial_config_primitive
["name"],
1102 params_dict
=primitive_params_
,
1105 # TODO register in database that primitive is done
1107 step
= "instantiated at VCA"
1108 self
.logger
.debug(logging_text
+ step
)
1110 except Exception as e
: # TODO not use Exception but N2VC exception
1111 raise Exception("{} {}".format(step
, e
)) from e
1112 # TODO raise N2VC exception with 'step' extra information
1114 async def instantiate(self
, nsr_id
, nslcmop_id
):
1117 :param nsr_id: ns instance to deploy
1118 :param nslcmop_id: operation to run
1122 # Try to lock HA task here
1123 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
1124 if not task_is_locked_by_me
:
1125 self
.logger
.debug('instantiate() task is not locked by me')
1128 logging_text
= "Task ns={} instantiate={} ".format(nsr_id
, nslcmop_id
)
1129 self
.logger
.debug(logging_text
+ "Enter")
1131 # get all needed from database
1133 # database nsrs record
1136 # database nslcmops record
1139 # update operation on nsrs
1140 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
1141 "_admin.current-operation": nslcmop_id
,
1142 "_admin.operation-type": "instantiate"}
1143 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1145 # update operation on nslcmops
1146 db_nslcmop_update
= {}
1148 nslcmop_operation_state
= None
1149 db_vnfrs
= {} # vnf's info indexed by member-index
1151 task_instantiation_list
= []
1154 # wait for any previous tasks in process
1155 step
= "Waiting for previous operations to terminate"
1156 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
1158 # STEP 0: Reading database (nslcmops, nsrs, nsds, vnfrs, vnfds)
1160 # read from db: operation
1161 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
1162 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1165 step
= "Getting nsr={} from db".format(nsr_id
)
1166 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1167 # nsd is replicated into ns (no db read)
1169 # nsr_name = db_nsr["name"] # TODO short-name??
1171 # read from db: vnf's of this ns
1172 step
= "Getting vnfrs from db"
1173 self
.logger
.debug(logging_text
+ step
)
1174 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1176 # read from db: vnfd's for every vnf
1177 db_vnfds_ref
= {} # every vnfd data indexed by vnf name
1178 db_vnfds
= {} # every vnfd data indexed by vnf id
1179 db_vnfds_index
= {} # every vnfd data indexed by vnf member-index
1181 # for each vnf in ns, read vnfd
1182 for vnfr
in db_vnfrs_list
:
1183 db_vnfrs
[vnfr
["member-vnf-index-ref"]] = vnfr
# vnf's dict indexed by member-index: '1', '2', etc
1184 vnfd_id
= vnfr
["vnfd-id"] # vnfd uuid for this vnf
1185 vnfd_ref
= vnfr
["vnfd-ref"] # vnfd name for this vnf
1186 # if we haven't this vnfd, read it from db
1187 if vnfd_id
not in db_vnfds
:
1189 step
= "Getting vnfd={} id='{}' from db".format(vnfd_id
, vnfd_ref
)
1190 self
.logger
.debug(logging_text
+ step
)
1191 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
1194 db_vnfds_ref
[vnfd_ref
] = vnfd
# vnfd's indexed by name
1195 db_vnfds
[vnfd_id
] = vnfd
# vnfd's indexed by id
1196 db_vnfds_index
[vnfr
["member-vnf-index-ref"]] = db_vnfds
[vnfd_id
] # vnfd's indexed by member-index
1198 # Get or generates the _admin.deployed.VCA list
1199 vca_deployed_list
= None
1200 if db_nsr
["_admin"].get("deployed"):
1201 vca_deployed_list
= db_nsr
["_admin"]["deployed"].get("VCA")
1202 if vca_deployed_list
is None:
1203 vca_deployed_list
= []
1204 db_nsr_update
["_admin.deployed.VCA"] = vca_deployed_list
1205 # add _admin.deployed.VCA to db_nsr dictionary, value=vca_deployed_list
1206 populate_dict(db_nsr
, ("_admin", "deployed", "VCA"), vca_deployed_list
)
1207 elif isinstance(vca_deployed_list
, dict):
1208 # maintain backward compatibility. Change a dict to list at database
1209 vca_deployed_list
= list(vca_deployed_list
.values())
1210 db_nsr_update
["_admin.deployed.VCA"] = vca_deployed_list
1211 populate_dict(db_nsr
, ("_admin", "deployed", "VCA"), vca_deployed_list
)
1213 db_nsr_update
["detailed-status"] = "creating"
1214 db_nsr_update
["operational-status"] = "init"
1216 if not isinstance(deep_get(db_nsr
, ("_admin", "deployed", "RO", "vnfd")), list):
1217 populate_dict(db_nsr
, ("_admin", "deployed", "RO", "vnfd"), [])
1218 db_nsr_update
["_admin.deployed.RO.vnfd"] = []
1220 # set state to INSTANTIATED. When instantiated NBI will not delete directly
1221 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1222 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1223 self
.logger
.debug(logging_text
+ "Before deploy_kdus")
1224 db_k8scluster_list
= self
.db
.get_list("k8sclusters", {})
1225 # Call to deploy_kdus in case exists the "vdu:kdu" param
1226 task_kdu
= asyncio
.ensure_future(
1228 logging_text
=logging_text
,
1232 db_nslcmop
=db_nslcmop
,
1234 db_vnfds_ref
=db_vnfds_ref
,
1235 db_k8scluster
=db_k8scluster_list
1238 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_KDUs", task_kdu
)
1239 task_instantiation_list
.append(task_kdu
)
1240 # n2vc_redesign STEP 1 Get VCA public ssh-key
1241 # feature 1429. Add n2vc public key to needed VMs
1242 n2vc_key
= self
.n2vc
.get_public_key()
1243 n2vc_key_list
= [n2vc_key
]
1244 if self
.vca_config
.get("public_key"):
1245 n2vc_key_list
.append(self
.vca_config
["public_key"])
1247 # n2vc_redesign STEP 2 Deploy Network Scenario
1248 task_ro
= asyncio
.ensure_future(
1249 self
.instantiate_RO(
1250 logging_text
=logging_text
,
1254 db_nslcmop
=db_nslcmop
,
1256 db_vnfds_ref
=db_vnfds_ref
,
1257 n2vc_key_list
=n2vc_key_list
1260 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_RO", task_ro
)
1261 task_instantiation_list
.append(task_ro
)
1263 # n2vc_redesign STEP 3 to 6 Deploy N2VC
1264 step
= "Looking for needed vnfd to configure with proxy charm"
1265 self
.logger
.debug(logging_text
+ step
)
1267 nsi_id
= None # TODO put nsi_id when this nsr belongs to a NSI
1268 # get_iterable() returns a value from a dict or empty tuple if key does not exist
1269 for c_vnf
in get_iterable(nsd
, "constituent-vnfd"):
1270 vnfd_id
= c_vnf
["vnfd-id-ref"]
1271 vnfd
= db_vnfds_ref
[vnfd_id
]
1272 member_vnf_index
= str(c_vnf
["member-vnf-index"])
1273 db_vnfr
= db_vnfrs
[member_vnf_index
]
1274 base_folder
= vnfd
["_admin"]["storage"]
1280 # Get additional parameters
1282 if db_vnfr
.get("additionalParamsForVnf"):
1283 deploy_params
= db_vnfr
["additionalParamsForVnf"].copy()
1284 for k
, v
in deploy_params
.items():
1285 if isinstance(v
, str) and v
.startswith("!!yaml "):
1286 deploy_params
[k
] = yaml
.safe_load(v
[7:])
1288 descriptor_config
= vnfd
.get("vnf-configuration")
1289 if descriptor_config
and descriptor_config
.get("juju"):
1291 logging_text
=logging_text
,
1294 nslcmop_id
=nslcmop_id
,
1300 member_vnf_index
=member_vnf_index
,
1301 vdu_index
=vdu_index
,
1303 deploy_params
=deploy_params
,
1304 descriptor_config
=descriptor_config
,
1305 base_folder
=base_folder
,
1306 task_instantiation_list
=task_instantiation_list
1309 # Deploy charms for each VDU that supports one.
1310 for vdud
in get_iterable(vnfd
, 'vdu'):
1312 descriptor_config
= vdud
.get('vdu-configuration')
1313 if descriptor_config
and descriptor_config
.get("juju"):
1314 # look for vdu index in the db_vnfr["vdu"] section
1315 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
1316 # if vdur["vdu-id-ref"] == vdu_id:
1319 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
1320 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
1321 # vdu_name = vdur.get("name")
1324 for vdu_index
in range(int(vdud
.get("count", 1))):
1325 # TODO vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
1327 logging_text
=logging_text
,
1330 nslcmop_id
=nslcmop_id
,
1336 member_vnf_index
=member_vnf_index
,
1337 vdu_index
=vdu_index
,
1339 deploy_params
=deploy_params
,
1340 descriptor_config
=descriptor_config
,
1341 base_folder
=base_folder
,
1342 task_instantiation_list
=task_instantiation_list
1344 for kdud
in get_iterable(vnfd
, 'kdu'):
1345 kdu_name
= kdud
["name"]
1346 descriptor_config
= kdud
.get('kdu-configuration')
1347 if descriptor_config
and descriptor_config
.get("juju"):
1351 # look for vdu index in the db_vnfr["vdu"] section
1352 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
1353 # if vdur["vdu-id-ref"] == vdu_id:
1356 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
1357 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
1358 # vdu_name = vdur.get("name")
1362 logging_text
=logging_text
,
1365 nslcmop_id
=nslcmop_id
,
1371 member_vnf_index
=member_vnf_index
,
1372 vdu_index
=vdu_index
,
1374 deploy_params
=deploy_params
,
1375 descriptor_config
=descriptor_config
,
1376 base_folder
=base_folder
,
1377 task_instantiation_list
=task_instantiation_list
1380 # Check if this NS has a charm configuration
1381 descriptor_config
= nsd
.get("ns-configuration")
1382 if descriptor_config
and descriptor_config
.get("juju"):
1385 member_vnf_index
= None
1391 # Get additional parameters
1393 if db_nsr
.get("additionalParamsForNs"):
1394 deploy_params
= db_nsr
["additionalParamsForNs"].copy()
1395 for k
, v
in deploy_params
.items():
1396 if isinstance(v
, str) and v
.startswith("!!yaml "):
1397 deploy_params
[k
] = yaml
.safe_load(v
[7:])
1398 base_folder
= nsd
["_admin"]["storage"]
1400 logging_text
=logging_text
,
1403 nslcmop_id
=nslcmop_id
,
1409 member_vnf_index
=member_vnf_index
,
1410 vdu_index
=vdu_index
,
1412 deploy_params
=deploy_params
,
1413 descriptor_config
=descriptor_config
,
1414 base_folder
=base_folder
,
1415 task_instantiation_list
=task_instantiation_list
1418 # Wait until all tasks of "task_instantiation_list" have been finished
1420 # while time() <= start_deploy + self.total_deploy_timeout:
1422 timeout
= 3600 # time() - start_deploy
1423 task_instantiation_set
= set(task_instantiation_list
) # build a set with tasks
1426 if len(task_instantiation_set
) > 0:
1427 done
, pending
= await asyncio
.wait(task_instantiation_set
, timeout
=timeout
)
1429 error_text
= "timeout"
1431 if task
.cancelled():
1433 error_text
= "cancelled"
1435 exc
= task
.exception()
1437 error_text
= str(exc
)
1440 db_nsr_update
["config-status"] = "failed"
1441 error_text
= "fail configuring " + error_text
1442 db_nsr_update
["detailed-status"] = error_text
1443 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED_TEMP"
1444 db_nslcmop_update
["detailed-status"] = error_text
1445 db_nslcmop_update
["statusEnteredTime"] = time()
1448 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
1449 db_nslcmop_update
["statusEnteredTime"] = time()
1450 db_nslcmop_update
["detailed-status"] = "done"
1451 db_nsr_update
["config-status"] = "configured"
1452 db_nsr_update
["detailed-status"] = "done"
1454 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
1455 self
.logger
.error(logging_text
+ "Exit Exception while '{}': {}".format(step
, e
))
1457 except asyncio
.CancelledError
:
1458 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1459 exc
= "Operation was cancelled"
1460 except Exception as e
:
1461 exc
= traceback
.format_exc()
1462 self
.logger
.critical(logging_text
+ "Exit Exception {} while '{}': {}".format(type(e
).__name
__, step
, e
),
1467 db_nsr_update
["detailed-status"] = "ERROR {}: {}".format(step
, exc
)
1468 db_nsr_update
["operational-status"] = "failed"
1470 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
1471 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
1472 db_nslcmop_update
["statusEnteredTime"] = time()
1475 db_nsr_update
["_admin.nslcmop"] = None
1476 db_nsr_update
["_admin.current-operation"] = None
1477 db_nsr_update
["_admin.operation-type"] = None
1478 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1479 if db_nslcmop_update
:
1480 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1481 except DbException
as e
:
1482 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
1483 if nslcmop_operation_state
:
1485 await self
.msg
.aiowrite("ns", "instantiated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
1486 "operationState": nslcmop_operation_state
},
1488 except Exception as e
:
1489 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1491 self
.logger
.debug(logging_text
+ "Exit")
1492 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_instantiate")
1494 async def deploy_kdus(self
, logging_text
, nsr_id
, nsd
, db_nsr
, db_nslcmop
, db_vnfrs
, db_vnfds_ref
, db_k8scluster
):
1495 # Launch kdus if present in the descriptor
1496 logging_text
= "Deploy kdus: "
1498 db_nsr_update
["_admin.deployed.K8s"] = []
1500 # Look for all vnfds
1501 # db_nsr_update["_admin.deployed.K8s"] = []
1504 for c_vnf
in nsd
.get("constituent-vnfd", ()):
1505 vnfr
= db_vnfrs
[c_vnf
["member-vnf-index"]]
1506 member_vnf_index
= c_vnf
["member-vnf-index"]
1507 vnfd
= db_vnfds_ref
[c_vnf
['vnfd-id-ref']]
1508 vnfd_ref
= vnfd
["id"]
1511 step
= "Checking kdu from vnf: {} - member-vnf-index: {}".format(vnfd_ref
, member_vnf_index
)
1512 self
.logger
.debug(logging_text
+ step
)
1514 step
= "vnf: {} has kdus".format(vnfd_ref
)
1515 self
.logger
.debug(logging_text
+ step
)
1516 for vnfr_name
, vnfr_data
in db_vnfrs
.items():
1517 if vnfr_data
["vnfd-ref"] == vnfd
["id"]:
1518 if vnfr_data
.get("additionalParamsForVnf"):
1519 desc_params
= self
._format
_additional
_params
(vnfr_data
["additionalParamsForVnf"])
1522 raise LcmException("VNF descriptor not found with id: {}".format(vnfr_data
["vnfd-ref"]))
1523 self
.logger
.debug(logging_text
+ step
)
1525 for kdur
in vnfr
.get("kdur"):
1527 for k8scluster
in db_k8scluster
:
1528 if kdur
["k8s-cluster"]["id"] == k8scluster
["_id"]:
1529 cluster_uuid
= k8scluster
["cluster-uuid"]
1532 raise LcmException("K8scluster not found with id: {}".format(kdur
["k8s-cluster"]["id"]))
1533 self
.logger
.debug(logging_text
+ step
)
1535 step
= "Instantiate KDU {} in k8s cluster {}".format(kdur
["kdu-name"], cluster_uuid
)
1536 self
.logger
.debug(logging_text
+ step
)
1537 for kdu
in vnfd
.get("kdu"):
1538 if kdu
.get("name") == kdur
["kdu-name"]:
1541 raise LcmException("KDU not found with name: {} in VNFD {}".format(kdur
["kdu-name"],
1543 self
.logger
.debug(logging_text
+ step
)
1545 k8sclustertype
= None
1546 if kdu
.get("helm-chart"):
1547 kdumodel
= kdu
["helm-chart"]
1548 k8sclustertype
= "chart"
1549 elif kdu
.get("juju-bundle"):
1550 kdumodel
= kdu
["juju-bundle"]
1551 k8sclustertype
= "juju"
1552 k8s_instace_info
= {"kdu-instance": None, "k8scluster-uuid": cluster_uuid
,
1553 "vnfr-id": vnfr
["id"], "k8scluster-type": k8sclustertype
,
1554 "kdu-name": kdur
["kdu-name"], "kdu-model": kdumodel
}
1555 db_nsr_update
["_admin.deployed.K8s"].append(k8s_instace_info
)
1556 db_dict
= {"collection": "nsrs", "filter": {"_id": nsr_id
}, "path": "_admin.deployed.K8s."
1558 if k8sclustertype
== "chart":
1559 task
= self
.k8sclusterhelm
.install(cluster_uuid
=cluster_uuid
, kdu_model
=kdumodel
,
1560 atomic
=True, params
=desc_params
,
1561 db_dict
=db_dict
, timeout
=300)
1563 # TODO I need the juju connector in place
1565 task_list
.append(task
)
1567 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1570 if len(task_list
) > 0:
1571 self
.logger
.debug('Waiting for terminate pending tasks...')
1572 done
, pending
= await asyncio
.wait(task_list
, timeout
=3600)
1575 k8s_instance
= fut
.result()
1576 k8s_instace_info
= {"kdu-instance": k8s_instance
, "k8scluster-uuid": cluster_uuid
,
1577 "vnfr-id": vnfr
["id"], "k8scluster-type": k8sclustertype
,
1578 "kdu-name": kdur
["kdu-name"], "kdu-model": kdumodel
}
1579 vnf_update
.append(k8s_instace_info
)
1580 self
.logger
.debug('All tasks finished...')
1582 self
.logger
.info('There are pending tasks: {}'.format(pending
))
1584 db_nsr_update
["_admin.deployed.K8s"] = vnf_update
1585 except Exception as e
:
1586 self
.logger
.critical(logging_text
+ "Exit Exception {} while '{}': {}".format(type(e
).__name
__, step
, e
))
1587 raise LcmException("{} Exit Exception {} while '{}': {}".format(logging_text
, type(e
).__name
__, step
, e
))
1589 # TODO Write in data base
1591 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1593 def _deploy_n2vc(self
, logging_text
, db_nsr
, db_vnfr
, nslcmop_id
, nsr_id
, nsi_id
, vnfd_id
, vdu_id
,
1594 kdu_name
, member_vnf_index
, vdu_index
, vdu_name
, deploy_params
, descriptor_config
,
1595 base_folder
, task_instantiation_list
):
1596 # launch instantiate_N2VC in a asyncio task and register task object
1597 # Look where information of this charm is at database <nsrs>._admin.deployed.VCA
1598 # if not found, create one entry and update database
1600 # fill db_nsr._admin.deployed.VCA.<index>
1602 for vca_index
, vca_deployed
in enumerate(db_nsr
["_admin"]["deployed"]["VCA"]):
1603 if not vca_deployed
:
1605 if vca_deployed
.get("member-vnf-index") == member_vnf_index
and \
1606 vca_deployed
.get("vdu_id") == vdu_id
and \
1607 vca_deployed
.get("kdu_name") == kdu_name
and \
1608 vca_deployed
.get("vdu_count_index", 0) == vdu_index
:
1611 # not found, create one.
1613 "member-vnf-index": member_vnf_index
,
1615 "kdu_name": kdu_name
,
1616 "vdu_count_index": vdu_index
,
1617 "operational-status": "init", # TODO revise
1618 "detailed-status": "", # TODO revise
1619 "step": "initial-deploy", # TODO revise
1621 "vdu_name": vdu_name
,
1624 self
.update_db_2("nsrs", nsr_id
, {"_admin.deployed.VCA.{}".format(vca_index
): vca_deployed
})
1625 db_nsr
["_admin"]["deployed"]["VCA"].append(vca_deployed
)
1628 task_n2vc
= asyncio
.ensure_future(
1629 self
.instantiate_N2VC(
1630 logging_text
=logging_text
,
1631 vca_index
=vca_index
,
1637 vdu_index
=vdu_index
,
1638 deploy_params
=deploy_params
,
1639 config_descriptor
=descriptor_config
,
1640 base_folder
=base_folder
,
1643 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_N2VC-{}".format(vca_index
), task_n2vc
)
1644 task_instantiation_list
.append(task_n2vc
)
1646 # Check if this VNFD has a configured terminate action
1647 def _has_terminate_config_primitive(self
, vnfd
):
1648 vnf_config
= vnfd
.get("vnf-configuration")
1649 if vnf_config
and vnf_config
.get("terminate-config-primitive"):
1655 def _get_terminate_config_primitive_seq_list(vnfd
):
1656 """ Get a numerically sorted list of the sequences for this VNFD's terminate action """
1657 # No need to check for existing primitive twice, already done before
1658 vnf_config
= vnfd
.get("vnf-configuration")
1659 seq_list
= vnf_config
.get("terminate-config-primitive")
1660 # Get all 'seq' tags in seq_list, order sequences numerically, ascending.
1661 seq_list_sorted
= sorted(seq_list
, key
=lambda x
: int(x
['seq']))
1662 return seq_list_sorted
1665 def _create_nslcmop(nsr_id
, operation
, params
):
1667 Creates a ns-lcm-opp content to be stored at database.
1668 :param nsr_id: internal id of the instance
1669 :param operation: instantiate, terminate, scale, action, ...
1670 :param params: user parameters for the operation
1671 :return: dictionary following SOL005 format
1673 # Raise exception if invalid arguments
1674 if not (nsr_id
and operation
and params
):
1676 "Parameters 'nsr_id', 'operation' and 'params' needed to create primitive not provided")
1682 # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1683 "operationState": "PROCESSING",
1684 "statusEnteredTime": now
,
1685 "nsInstanceId": nsr_id
,
1686 "lcmOperationType": operation
,
1688 "isAutomaticInvocation": False,
1689 "operationParams": params
,
1690 "isCancelPending": False,
1692 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
1693 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
1698 def _format_additional_params(self
, params
):
1700 for key
, value
in params
.items():
1701 if str(value
).startswith("!!yaml "):
1702 params
[key
] = yaml
.safe_load(value
[7:])
1706 def _get_terminate_primitive_params(self
, seq
, vnf_index
):
1707 primitive
= seq
.get('name')
1708 primitive_params
= {}
1710 "member_vnf_index": vnf_index
,
1711 "primitive": primitive
,
1712 "primitive_params": primitive_params
,
1715 return self
._map
_primitive
_params
(seq
, params
, desc_params
)
1719 def _reintent_or_skip_suboperation(self
, db_nslcmop
, op_index
):
1720 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
1721 if (op
.get('operationState') == 'COMPLETED'):
1722 # b. Skip sub-operation
1723 # _ns_execute_primitive() or RO.create_action() will NOT be executed
1724 return self
.SUBOPERATION_STATUS_SKIP
1726 # c. Reintent executing sub-operation
1727 # The sub-operation exists, and operationState != 'COMPLETED'
1728 # Update operationState = 'PROCESSING' to indicate a reintent.
1729 operationState
= 'PROCESSING'
1730 detailed_status
= 'In progress'
1731 self
._update
_suboperation
_status
(
1732 db_nslcmop
, op_index
, operationState
, detailed_status
)
1733 # Return the sub-operation index
1734 # _ns_execute_primitive() or RO.create_action() will be called from scale()
1735 # with arguments extracted from the sub-operation
1738 # Find a sub-operation where all keys in a matching dictionary must match
1739 # Returns the index of the matching sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if no match
1740 def _find_suboperation(self
, db_nslcmop
, match
):
1741 if (db_nslcmop
and match
):
1742 op_list
= db_nslcmop
.get('_admin', {}).get('operations', [])
1743 for i
, op
in enumerate(op_list
):
1744 if all(op
.get(k
) == match
[k
] for k
in match
):
1746 return self
.SUBOPERATION_STATUS_NOT_FOUND
1748 # Update status for a sub-operation given its index
1749 def _update_suboperation_status(self
, db_nslcmop
, op_index
, operationState
, detailed_status
):
1750 # Update DB for HA tasks
1751 q_filter
= {'_id': db_nslcmop
['_id']}
1752 update_dict
= {'_admin.operations.{}.operationState'.format(op_index
): operationState
,
1753 '_admin.operations.{}.detailed-status'.format(op_index
): detailed_status
}
1754 self
.db
.set_one("nslcmops",
1756 update_dict
=update_dict
,
1757 fail_on_empty
=False)
1759 # Add sub-operation, return the index of the added sub-operation
1760 # Optionally, set operationState, detailed-status, and operationType
1761 # Status and type are currently set for 'scale' sub-operations:
1762 # 'operationState' : 'PROCESSING' | 'COMPLETED' | 'FAILED'
1763 # 'detailed-status' : status message
1764 # 'operationType': may be any type, in the case of scaling: 'PRE-SCALE' | 'POST-SCALE'
1765 # Status and operation type are currently only used for 'scale', but NOT for 'terminate' sub-operations.
1766 def _add_suboperation(self
, db_nslcmop
, vnf_index
, vdu_id
, vdu_count_index
, vdu_name
, primitive
,
1767 mapped_primitive_params
, operationState
=None, detailed_status
=None, operationType
=None,
1768 RO_nsr_id
=None, RO_scaling_info
=None):
1769 if not (db_nslcmop
):
1770 return self
.SUBOPERATION_STATUS_NOT_FOUND
1771 # Get the "_admin.operations" list, if it exists
1772 db_nslcmop_admin
= db_nslcmop
.get('_admin', {})
1773 op_list
= db_nslcmop_admin
.get('operations')
1774 # Create or append to the "_admin.operations" list
1775 new_op
= {'member_vnf_index': vnf_index
,
1777 'vdu_count_index': vdu_count_index
,
1778 'primitive': primitive
,
1779 'primitive_params': mapped_primitive_params
}
1781 new_op
['operationState'] = operationState
1783 new_op
['detailed-status'] = detailed_status
1785 new_op
['lcmOperationType'] = operationType
1787 new_op
['RO_nsr_id'] = RO_nsr_id
1789 new_op
['RO_scaling_info'] = RO_scaling_info
1791 # No existing operations, create key 'operations' with current operation as first list element
1792 db_nslcmop_admin
.update({'operations': [new_op
]})
1793 op_list
= db_nslcmop_admin
.get('operations')
1795 # Existing operations, append operation to list
1796 op_list
.append(new_op
)
1798 db_nslcmop_update
= {'_admin.operations': op_list
}
1799 self
.update_db_2("nslcmops", db_nslcmop
['_id'], db_nslcmop_update
)
1800 op_index
= len(op_list
) - 1
1803 # Helper methods for scale() sub-operations
1805 # pre-scale/post-scale:
1806 # Check for 3 different cases:
1807 # a. New: First time execution, return SUBOPERATION_STATUS_NEW
1808 # b. Skip: Existing sub-operation exists, operationState == 'COMPLETED', return SUBOPERATION_STATUS_SKIP
1809 # c. Reintent: Existing sub-operation exists, operationState != 'COMPLETED', return op_index to re-execute
1810 def _check_or_add_scale_suboperation(self
, db_nslcmop
, vnf_index
, vnf_config_primitive
, primitive_params
,
1811 operationType
, RO_nsr_id
=None, RO_scaling_info
=None):
1812 # Find this sub-operation
1813 if (RO_nsr_id
and RO_scaling_info
):
1814 operationType
= 'SCALE-RO'
1816 'member_vnf_index': vnf_index
,
1817 'RO_nsr_id': RO_nsr_id
,
1818 'RO_scaling_info': RO_scaling_info
,
1822 'member_vnf_index': vnf_index
,
1823 'primitive': vnf_config_primitive
,
1824 'primitive_params': primitive_params
,
1825 'lcmOperationType': operationType
1827 op_index
= self
._find
_suboperation
(db_nslcmop
, match
)
1828 if (op_index
== self
.SUBOPERATION_STATUS_NOT_FOUND
):
1829 # a. New sub-operation
1830 # The sub-operation does not exist, add it.
1831 # _ns_execute_primitive() will be called from scale() as usual, with non-modified arguments
1832 # The following parameters are set to None for all kind of scaling:
1834 vdu_count_index
= None
1836 if (RO_nsr_id
and RO_scaling_info
):
1837 vnf_config_primitive
= None
1838 primitive_params
= None
1841 RO_scaling_info
= None
1842 # Initial status for sub-operation
1843 operationState
= 'PROCESSING'
1844 detailed_status
= 'In progress'
1845 # Add sub-operation for pre/post-scaling (zero or more operations)
1846 self
._add
_suboperation
(db_nslcmop
,
1851 vnf_config_primitive
,
1858 return self
.SUBOPERATION_STATUS_NEW
1860 # Return either SUBOPERATION_STATUS_SKIP (operationState == 'COMPLETED'),
1861 # or op_index (operationState != 'COMPLETED')
1862 return self
._reintent
_or
_skip
_suboperation
(db_nslcmop
, op_index
)
1864 # Helper methods for terminate()
1866 async def _terminate_action(self
, db_nslcmop
, nslcmop_id
, nsr_id
):
1867 """ Create a primitive with params from VNFD
1868 Called from terminate() before deleting instance
1869 Calls action() to execute the primitive """
1870 logging_text
= "Task ns={} _terminate_action={} ".format(nsr_id
, nslcmop_id
)
1871 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1874 for vnfr
in db_vnfrs_list
:
1875 vnfd_id
= vnfr
["vnfd-id"]
1876 vnf_index
= vnfr
["member-vnf-index-ref"]
1877 if vnfd_id
not in db_vnfds
:
1878 step
= "Getting vnfd={} id='{}' from db".format(vnfd_id
, vnfd_id
)
1879 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
1880 db_vnfds
[vnfd_id
] = vnfd
1881 vnfd
= db_vnfds
[vnfd_id
]
1882 if not self
._has
_terminate
_config
_primitive
(vnfd
):
1884 # Get the primitive's sorted sequence list
1885 seq_list
= self
._get
_terminate
_config
_primitive
_seq
_list
(vnfd
)
1886 for seq
in seq_list
:
1887 # For each sequence in list, get primitive and call _ns_execute_primitive()
1888 step
= "Calling terminate action for vnf_member_index={} primitive={}".format(
1889 vnf_index
, seq
.get("name"))
1890 self
.logger
.debug(logging_text
+ step
)
1891 # Create the primitive for each sequence, i.e. "primitive": "touch"
1892 primitive
= seq
.get('name')
1893 mapped_primitive_params
= self
._get
_terminate
_primitive
_params
(seq
, vnf_index
)
1894 # The following 3 parameters are currently set to None for 'terminate':
1895 # vdu_id, vdu_count_index, vdu_name
1896 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
1897 vdu_count_index
= db_nslcmop
["operationParams"].get("vdu_count_index")
1898 vdu_name
= db_nslcmop
["operationParams"].get("vdu_name")
1900 self
._add
_suboperation
(db_nslcmop
,
1907 mapped_primitive_params
)
1908 # Sub-operations: Call _ns_execute_primitive() instead of action()
1909 # db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1910 # nsr_deployed = db_nsr["_admin"]["deployed"]
1912 # nslcmop_operation_state, nslcmop_operation_state_detail = await self.action(
1913 # nsr_id, nslcmop_terminate_action_id)
1914 # Launch Exception if action() returns other than ['COMPLETED', 'PARTIALLY_COMPLETED']
1915 # result_ok = ['COMPLETED', 'PARTIALLY_COMPLETED']
1916 # if result not in result_ok:
1917 # raise LcmException(
1918 # "terminate_primitive_action for vnf_member_index={}",
1919 # " primitive={} fails with error {}".format(
1920 # vnf_index, seq.get("name"), result_detail))
1925 await self
.n2vc
.exec_primitive(
1927 primitive_name
=primitive
,
1928 params_dict
=mapped_primitive_params
1930 except Exception as e
:
1931 self
.logger
.error('Error executing primitive {}: {}'.format(primitive
, e
))
1933 "terminate_primitive_action for vnf_member_index={}, primitive={} fails with error {}"
1934 .format(vnf_index
, seq
.get("name"), e
),
1937 async def terminate(self
, nsr_id
, nslcmop_id
):
1939 # Try to lock HA task here
1940 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
1941 if not task_is_locked_by_me
:
1944 logging_text
= "Task ns={} terminate={} ".format(nsr_id
, nslcmop_id
)
1945 self
.logger
.debug(logging_text
+ "Enter")
1949 failed_detail
= [] # annotates all failed error messages
1950 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
1951 "_admin.current-operation": nslcmop_id
,
1952 "_admin.operation-type": "terminate"}
1953 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1954 db_nslcmop_update
= {}
1955 nslcmop_operation_state
= None
1956 autoremove
= False # autoremove after terminated
1959 # wait for any previous tasks in process
1960 step
= "Waiting for previous operations to terminate"
1961 await self
.lcm_tasks
.waitfor_related_HA("ns", 'nslcmops', nslcmop_id
)
1963 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
1964 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1965 step
= "Getting nsr={} from db".format(nsr_id
)
1966 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1967 # nsd = db_nsr["nsd"]
1968 nsr_deployed
= deepcopy(db_nsr
["_admin"].get("deployed"))
1969 if db_nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
1971 # #TODO check if VIM is creating and wait
1972 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
1973 # Call internal terminate action
1974 await self
._terminate
_action
(db_nslcmop
, nslcmop_id
, nsr_id
)
1978 db_nsr_update
["operational-status"] = "terminating"
1979 db_nsr_update
["config-status"] = "terminating"
1983 step
= "delete execution environment"
1984 self
.logger
.debug(logging_text
+ step
)
1986 task_delete_ee
= asyncio
.ensure_future(self
.n2vc
.delete_namespace(namespace
="." + nsr_id
))
1987 pending_tasks
.append(task_delete_ee
)
1988 except Exception as e
:
1989 msg
= "Failed while deleting NS in VCA: {}".format(e
)
1990 self
.logger
.error(msg
)
1991 failed_detail
.append(msg
)
1994 # Delete from k8scluster
1995 step
= "delete kdus"
1996 self
.logger
.debug(logging_text
+ step
)
1999 for kdu
in nsr_deployed
.get("K8s"):
2000 if kdu
.get("k8scluster-type") == "chart":
2001 task_delete_kdu_instance
= asyncio
.ensure_future(self
.k8sclusterhelm
.uninstall(
2002 cluster_uuid
=kdu
.get("k8scluster-uuid"), kdu_instance
=kdu
.get("kdu-instance")))
2003 elif kdu
.get("k8scluster-type") == "juju":
2004 # TODO Juju connector needed
2007 msg
= "k8scluster-type not defined"
2008 raise LcmException(msg
)
2010 pending_tasks
.append(task_delete_kdu_instance
)
2011 except LcmException
as e
:
2012 msg
= "Failed while deleting KDUs from NS: {}".format(e
)
2013 self
.logger
.error(msg
)
2014 failed_detail
.append(msg
)
2020 RO_nsr_id
= RO_delete_action
= None
2021 if nsr_deployed
and nsr_deployed
.get("RO"):
2022 RO_nsr_id
= nsr_deployed
["RO"].get("nsr_id")
2023 RO_delete_action
= nsr_deployed
["RO"].get("nsr_delete_action_id")
2026 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] = \
2027 "Deleting ns from VIM"
2028 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2029 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2030 self
.logger
.debug(logging_text
+ step
)
2031 desc
= await self
.RO
.delete("ns", RO_nsr_id
)
2032 RO_delete_action
= desc
["action_id"]
2033 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = RO_delete_action
2034 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
2035 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
2036 if RO_delete_action
:
2037 # wait until NS is deleted from VIM
2038 step
= detailed_status
= "Waiting ns deleted from VIM. RO_id={} RO_delete_action={}".\
2039 format(RO_nsr_id
, RO_delete_action
)
2040 detailed_status_old
= None
2041 self
.logger
.debug(logging_text
+ step
)
2043 delete_timeout
= 20 * 60 # 20 minutes
2044 while delete_timeout
> 0:
2045 desc
= await self
.RO
.show(
2047 item_id_name
=RO_nsr_id
,
2048 extra_item
="action",
2049 extra_item_id
=RO_delete_action
)
2050 ns_status
, ns_status_info
= self
.RO
.check_action_status(desc
)
2051 if ns_status
== "ERROR":
2052 raise ROclient
.ROClientException(ns_status_info
)
2053 elif ns_status
== "BUILD":
2054 detailed_status
= step
+ "; {}".format(ns_status_info
)
2055 elif ns_status
== "ACTIVE":
2056 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
2057 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
2060 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
2061 if detailed_status
!= detailed_status_old
:
2062 detailed_status_old
= db_nslcmop_update
["detailed-status"] = \
2063 db_nsr_update
["detailed-status"] = detailed_status
2064 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2065 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2066 await asyncio
.sleep(5, loop
=self
.loop
)
2068 else: # delete_timeout <= 0:
2069 raise ROclient
.ROClientException("Timeout waiting ns deleted from VIM")
2071 except ROclient
.ROClientException
as e
:
2072 if e
.http_code
== 404: # not found
2073 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
2074 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
2075 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
2076 self
.logger
.debug(logging_text
+ "RO_ns_id={} already deleted".format(RO_nsr_id
))
2077 elif e
.http_code
== 409: # conflict
2078 failed_detail
.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id
, e
))
2079 self
.logger
.debug(logging_text
+ failed_detail
[-1])
2082 failed_detail
.append("RO_ns_id={} delete error: {}".format(RO_nsr_id
, e
))
2083 self
.logger
.error(logging_text
+ failed_detail
[-1])
2087 if not RO_fail
and nsr_deployed
and nsr_deployed
.get("RO") and nsr_deployed
["RO"].get("nsd_id"):
2088 RO_nsd_id
= nsr_deployed
["RO"]["nsd_id"]
2090 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
2091 "Deleting nsd from RO"
2092 await self
.RO
.delete("nsd", RO_nsd_id
)
2093 self
.logger
.debug(logging_text
+ "RO_nsd_id={} deleted".format(RO_nsd_id
))
2094 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
2095 except ROclient
.ROClientException
as e
:
2096 if e
.http_code
== 404: # not found
2097 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
2098 self
.logger
.debug(logging_text
+ "RO_nsd_id={} already deleted".format(RO_nsd_id
))
2099 elif e
.http_code
== 409: # conflict
2100 failed_detail
.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id
, e
))
2101 self
.logger
.debug(logging_text
+ failed_detail
[-1])
2104 failed_detail
.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id
, e
))
2105 self
.logger
.error(logging_text
+ failed_detail
[-1])
2108 if not RO_fail
and nsr_deployed
and nsr_deployed
.get("RO") and nsr_deployed
["RO"].get("vnfd"):
2109 for index
, vnf_deployed
in enumerate(nsr_deployed
["RO"]["vnfd"]):
2110 if not vnf_deployed
or not vnf_deployed
["id"]:
2113 RO_vnfd_id
= vnf_deployed
["id"]
2114 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
2115 "Deleting member_vnf_index={} RO_vnfd_id={} from RO".format(
2116 vnf_deployed
["member-vnf-index"], RO_vnfd_id
)
2117 await self
.RO
.delete("vnfd", RO_vnfd_id
)
2118 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} deleted".format(RO_vnfd_id
))
2119 db_nsr_update
["_admin.deployed.RO.vnfd.{}.id".format(index
)] = None
2120 except ROclient
.ROClientException
as e
:
2121 if e
.http_code
== 404: # not found
2122 db_nsr_update
["_admin.deployed.RO.vnfd.{}.id".format(index
)] = None
2123 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} already deleted ".format(RO_vnfd_id
))
2124 elif e
.http_code
== 409: # conflict
2125 failed_detail
.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id
, e
))
2126 self
.logger
.debug(logging_text
+ failed_detail
[-1])
2128 failed_detail
.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id
, e
))
2129 self
.logger
.error(logging_text
+ failed_detail
[-1])
2132 self
.logger
.error(logging_text
+ " ;".join(failed_detail
))
2133 db_nsr_update
["operational-status"] = "failed"
2134 db_nsr_update
["detailed-status"] = "Deletion errors " + "; ".join(failed_detail
)
2135 db_nslcmop_update
["detailed-status"] = "; ".join(failed_detail
)
2136 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2137 db_nslcmop_update
["statusEnteredTime"] = time()
2139 db_nsr_update
["operational-status"] = "terminated"
2140 db_nsr_update
["detailed-status"] = "Done"
2141 db_nsr_update
["_admin.nsState"] = "NOT_INSTANTIATED"
2142 db_nslcmop_update
["detailed-status"] = "Done"
2143 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
2144 db_nslcmop_update
["statusEnteredTime"] = time()
2145 if db_nslcmop
["operationParams"].get("autoremove"):
2148 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
2149 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
2151 except asyncio
.CancelledError
:
2152 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
2153 exc
= "Operation was cancelled"
2154 except Exception as e
:
2155 exc
= traceback
.format_exc()
2156 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
2158 if exc
and db_nslcmop
:
2159 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
2160 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2161 db_nslcmop_update
["statusEnteredTime"] = time()
2163 if db_nslcmop
and db_nslcmop_update
:
2164 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2166 db_nsr_update
["_admin.nslcmop"] = None
2167 db_nsr_update
["_admin.current-operation"] = None
2168 db_nsr_update
["_admin.operation-type"] = None
2169 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2170 except DbException
as e
:
2171 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
2172 if nslcmop_operation_state
:
2174 await self
.msg
.aiowrite("ns", "terminated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2175 "operationState": nslcmop_operation_state
,
2176 "autoremove": autoremove
},
2178 except Exception as e
:
2179 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
2181 # wait for pending tasks
2185 self
.logger
.debug(logging_text
+ 'Waiting for terminate pending tasks...')
2186 done
, pending
= await asyncio
.wait(pending_tasks
, timeout
=3600)
2188 self
.logger
.debug(logging_text
+ 'All tasks finished...')
2190 self
.logger
.info(logging_text
+ 'There are pending tasks: {}'.format(pending
))
2192 self
.logger
.debug(logging_text
+ "Exit")
2193 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_terminate")
2196 def _map_primitive_params(primitive_desc
, params
, instantiation_params
):
2198 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
2199 The default-value is used. If it is between < > it look for a value at instantiation_params
2200 :param primitive_desc: portion of VNFD/NSD that describes primitive
2201 :param params: Params provided by user
2202 :param instantiation_params: Instantiation params provided by user
2203 :return: a dictionary with the calculated params
2205 calculated_params
= {}
2206 for parameter
in primitive_desc
.get("parameter", ()):
2207 param_name
= parameter
["name"]
2208 if param_name
in params
:
2209 calculated_params
[param_name
] = params
[param_name
]
2210 elif "default-value" in parameter
or "value" in parameter
:
2211 if "value" in parameter
:
2212 calculated_params
[param_name
] = parameter
["value"]
2214 calculated_params
[param_name
] = parameter
["default-value"]
2215 if isinstance(calculated_params
[param_name
], str) and calculated_params
[param_name
].startswith("<") \
2216 and calculated_params
[param_name
].endswith(">"):
2217 if calculated_params
[param_name
][1:-1] in instantiation_params
:
2218 calculated_params
[param_name
] = instantiation_params
[calculated_params
[param_name
][1:-1]]
2220 raise LcmException("Parameter {} needed to execute primitive {} not provided".
2221 format(calculated_params
[param_name
], primitive_desc
["name"]))
2223 raise LcmException("Parameter {} needed to execute primitive {} not provided".
2224 format(param_name
, primitive_desc
["name"]))
2226 if isinstance(calculated_params
[param_name
], (dict, list, tuple)):
2227 calculated_params
[param_name
] = yaml
.safe_dump(calculated_params
[param_name
], default_flow_style
=True,
2229 elif isinstance(calculated_params
[param_name
], str) and calculated_params
[param_name
].startswith("!!yaml "):
2230 calculated_params
[param_name
] = calculated_params
[param_name
][7:]
2232 # add always ns_config_info if primitive name is config
2233 if primitive_desc
["name"] == "config":
2234 if "ns_config_info" in instantiation_params
:
2235 calculated_params
["ns_config_info"] = instantiation_params
["ns_config_info"]
2236 return calculated_params
2238 async def _ns_execute_primitive(self
, db_deployed
, member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
,
2239 primitive
, primitive_params
, retries
=0, retries_interval
=30) -> (str, str):
2241 # find vca_deployed record for this action
2243 for vca_deployed
in db_deployed
["VCA"]:
2244 if not vca_deployed
:
2246 if member_vnf_index
!= vca_deployed
["member-vnf-index"] or vdu_id
!= vca_deployed
["vdu_id"]:
2248 if vdu_name
and vdu_name
!= vca_deployed
["vdu_name"]:
2250 if vdu_count_index
and vdu_count_index
!= vca_deployed
["vdu_count_index"]:
2254 # vca_deployed not found
2255 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} is not "
2256 "deployed".format(member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
))
2259 ee_id
= vca_deployed
.get("ee_id")
2261 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} has not "
2262 "execution environment"
2263 .format(member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
))
2265 if primitive
== "config":
2266 primitive_params
= {"params": primitive_params
}
2270 output
= await self
.n2vc
.exec_primitive(
2272 primitive_name
=primitive
,
2273 params_dict
=primitive_params
2277 except Exception as e
:
2280 self
.logger
.debug('Error executing action {} on {} -> {}'.format(primitive
, ee_id
, e
))
2282 await asyncio
.sleep(retries_interval
, loop
=self
.loop
)
2284 return 'Cannot execute action {} on {}: {}'.format(primitive
, ee_id
, e
), 'FAIL'
2288 except Exception as e
:
2289 return 'Error executing action {}: {}'.format(primitive
, e
), 'FAIL'
2291 async def action(self
, nsr_id
, nslcmop_id
):
2293 # Try to lock HA task here
2294 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
2295 if not task_is_locked_by_me
:
2298 logging_text
= "Task ns={} action={} ".format(nsr_id
, nslcmop_id
)
2299 self
.logger
.debug(logging_text
+ "Enter")
2300 # get all needed from database
2303 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
2304 "_admin.current-operation": nslcmop_id
,
2305 "_admin.operation-type": "action"}
2306 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2307 db_nslcmop_update
= {}
2308 nslcmop_operation_state
= None
2309 nslcmop_operation_state_detail
= None
2312 # wait for any previous tasks in process
2313 step
= "Waiting for previous operations to terminate"
2314 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
2316 step
= "Getting information from database"
2317 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
2318 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2320 nsr_deployed
= db_nsr
["_admin"].get("deployed")
2321 vnf_index
= db_nslcmop
["operationParams"].get("member_vnf_index")
2322 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
2323 kdu_name
= db_nslcmop
["operationParams"].get("kdu_name")
2324 vdu_count_index
= db_nslcmop
["operationParams"].get("vdu_count_index")
2325 vdu_name
= db_nslcmop
["operationParams"].get("vdu_name")
2328 step
= "Getting vnfr from database"
2329 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
2330 step
= "Getting vnfd from database"
2331 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
2333 if db_nsr
.get("nsd"):
2334 db_nsd
= db_nsr
.get("nsd") # TODO this will be removed
2336 step
= "Getting nsd from database"
2337 db_nsd
= self
.db
.get_one("nsds", {"_id": db_nsr
["nsd-id"]})
2339 # for backward compatibility
2340 if nsr_deployed
and isinstance(nsr_deployed
.get("VCA"), dict):
2341 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
2342 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
2343 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2345 primitive
= db_nslcmop
["operationParams"]["primitive"]
2346 primitive_params
= db_nslcmop
["operationParams"]["primitive_params"]
2348 # look for primitive
2349 config_primitive_desc
= None
2351 for vdu
in get_iterable(db_vnfd
, "vdu"):
2352 if vdu_id
== vdu
["id"]:
2353 for config_primitive
in vdu
.get("vdu-configuration", {}).get("config-primitive", ()):
2354 if config_primitive
["name"] == primitive
:
2355 config_primitive_desc
= config_primitive
2358 self
.logger
.debug(logging_text
+ "Checking actions in KDUs")
2361 if db_vnfr
.get("additionalParamsForVnf") and db_vnfr
["additionalParamsForVnf"].\
2362 get("member-vnf-index") == vnf_index
:
2363 desc_params
= self
._format
_additional
_params
(db_vnfr
["additionalParamsForVnf"].
2364 get("additionalParams"))
2365 if primitive_params
:
2366 desc_params
.update(primitive_params
)
2367 # TODO Check if we will need something at vnf level
2369 for kdu
in get_iterable(nsr_deployed
, "K8s"):
2370 if kdu_name
== kdu
["kdu-name"]:
2371 db_dict
= {"collection": "nsrs", "filter": {"_id": nsr_id
},
2372 "path": "_admin.deployed.K8s.{}".format(index
)}
2373 if primitive
== "upgrade":
2374 if desc_params
.get("kdu_model"):
2375 kdu_model
= desc_params
.get("kdu_model")
2376 del desc_params
["kdu_model"]
2378 kdu_model
= kdu
.get("kdu-model")
2379 parts
= kdu_model
.split(sep
=":")
2381 kdu_model
= parts
[0]
2383 if kdu
.get("k8scluster-type") == "chart":
2384 output
= await self
.k8sclusterhelm
.upgrade(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2385 kdu_instance
=kdu
.get("kdu-instance"),
2386 atomic
=True, kdu_model
=kdu_model
,
2387 params
=desc_params
, db_dict
=db_dict
,
2389 elif kdu
.get("k8scluster-type") == "juju":
2390 # TODO Juju connector needed
2393 msg
= "k8scluster-type not defined"
2394 raise LcmException(msg
)
2396 self
.logger
.debug(logging_text
+ " Upgrade of kdu {} done".format(output
))
2398 elif primitive
== "rollback":
2399 if kdu
.get("k8scluster-type") == "chart":
2400 output
= await self
.k8sclusterhelm
.rollback(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2401 kdu_instance
=kdu
.get("kdu-instance"),
2403 elif kdu
.get("k8scluster-type") == "juju":
2404 # TODO Juju connector needed
2407 msg
= "k8scluster-type not defined"
2408 raise LcmException(msg
)
2410 elif primitive
== "status":
2411 if kdu
.get("k8scluster-type") == "chart":
2412 output
= await self
.k8sclusterhelm
.status_kdu(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2413 kdu_instance
=kdu
.get("kdu-instance"))
2414 elif kdu
.get("k8scluster-type") == "juju":
2415 # TODO Juju connector needed
2418 msg
= "k8scluster-type not defined"
2419 raise LcmException(msg
)
2424 raise LcmException("KDU '{}' not found".format(kdu_name
))
2426 db_nslcmop_update
["detailed-status"] = output
2427 db_nslcmop_update
["operationState"] = 'COMPLETED'
2428 db_nslcmop_update
["statusEnteredTime"] = time()
2430 db_nslcmop_update
["detailed-status"] = ''
2431 db_nslcmop_update
["operationState"] = 'FAILED'
2432 db_nslcmop_update
["statusEnteredTime"] = time()
2435 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
2436 if config_primitive
["name"] == primitive
:
2437 config_primitive_desc
= config_primitive
2440 for config_primitive
in db_nsd
.get("ns-configuration", {}).get("config-primitive", ()):
2441 if config_primitive
["name"] == primitive
:
2442 config_primitive_desc
= config_primitive
2445 if not config_primitive_desc
:
2446 raise LcmException("Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".
2451 if db_vnfr
.get("additionalParamsForVnf"):
2452 desc_params
.update(db_vnfr
["additionalParamsForVnf"])
2454 if db_nsr
.get("additionalParamsForNs"):
2455 desc_params
.update(db_nsr
["additionalParamsForNs"])
2457 # TODO check if ns is in a proper status
2458 output
, detail
= await self
._ns
_execute
_primitive
(
2459 db_deployed
=nsr_deployed
,
2460 member_vnf_index
=vnf_index
,
2463 vdu_count_index
=vdu_count_index
,
2464 primitive
=primitive
,
2465 primitive_params
=self
._map
_primitive
_params
(config_primitive_desc
, primitive_params
, desc_params
))
2467 detailed_status
= output
2469 result
= 'COMPLETED'
2473 db_nslcmop_update
["detailed-status"] = nslcmop_operation_state_detail
= detailed_status
2474 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= result
2475 db_nslcmop_update
["statusEnteredTime"] = time()
2476 self
.logger
.debug(logging_text
+ " task Done with result {} {}".format(result
, detailed_status
))
2477 return # database update is called inside finally
2479 except (DbException
, LcmException
) as e
:
2480 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
2482 except asyncio
.CancelledError
:
2483 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
2484 exc
= "Operation was cancelled"
2485 except Exception as e
:
2486 exc
= traceback
.format_exc()
2487 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
2489 if exc
and db_nslcmop
:
2490 db_nslcmop_update
["detailed-status"] = nslcmop_operation_state_detail
= \
2491 "FAILED {}: {}".format(step
, exc
)
2492 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2493 db_nslcmop_update
["statusEnteredTime"] = time()
2495 if db_nslcmop_update
:
2496 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2498 db_nsr_update
["_admin.nslcmop"] = None
2499 db_nsr_update
["_admin.operation-type"] = None
2500 db_nsr_update
["_admin.nslcmop"] = None
2501 db_nsr_update
["_admin.current-operation"] = None
2502 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2503 except DbException
as e
:
2504 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
2505 self
.logger
.debug(logging_text
+ "Exit")
2506 if nslcmop_operation_state
:
2508 await self
.msg
.aiowrite("ns", "actioned", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2509 "operationState": nslcmop_operation_state
},
2511 except Exception as e
:
2512 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
2513 self
.logger
.debug(logging_text
+ "Exit")
2514 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_action")
2515 return nslcmop_operation_state
, nslcmop_operation_state_detail
2517 async def scale(self
, nsr_id
, nslcmop_id
):
2519 # Try to lock HA task here
2520 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
2521 if not task_is_locked_by_me
:
2524 logging_text
= "Task ns={} scale={} ".format(nsr_id
, nslcmop_id
)
2525 self
.logger
.debug(logging_text
+ "Enter")
2526 # get all needed from database
2529 db_nslcmop_update
= {}
2530 nslcmop_operation_state
= None
2531 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
2532 "_admin.current-operation": nslcmop_id
,
2533 "_admin.operation-type": "scale"}
2534 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2536 # in case of error, indicates what part of scale was failed to put nsr at error status
2537 scale_process
= None
2538 old_operational_status
= ""
2539 old_config_status
= ""
2542 # wait for any previous tasks in process
2543 step
= "Waiting for previous operations to terminate"
2544 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
2546 step
= "Getting nslcmop from database"
2547 self
.logger
.debug(step
+ " after having waited for previous tasks to be completed")
2548 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
2549 step
= "Getting nsr from database"
2550 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2552 old_operational_status
= db_nsr
["operational-status"]
2553 old_config_status
= db_nsr
["config-status"]
2554 step
= "Parsing scaling parameters"
2555 # self.logger.debug(step)
2556 db_nsr_update
["operational-status"] = "scaling"
2557 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2558 nsr_deployed
= db_nsr
["_admin"].get("deployed")
2561 nsr_deployed
= db_nsr
["_admin"].get("deployed")
2562 vnf_index
= db_nslcmop
["operationParams"].get("member_vnf_index")
2563 # vdu_id = db_nslcmop["operationParams"].get("vdu_id")
2564 # vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
2565 # vdu_name = db_nslcmop["operationParams"].get("vdu_name")
2568 RO_nsr_id
= nsr_deployed
["RO"]["nsr_id"]
2569 vnf_index
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
2570 scaling_group
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
2571 scaling_type
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleVnfType"]
2572 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
2574 # for backward compatibility
2575 if nsr_deployed
and isinstance(nsr_deployed
.get("VCA"), dict):
2576 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
2577 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
2578 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2580 step
= "Getting vnfr from database"
2581 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
2582 step
= "Getting vnfd from database"
2583 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
2585 step
= "Getting scaling-group-descriptor"
2586 for scaling_descriptor
in db_vnfd
["scaling-group-descriptor"]:
2587 if scaling_descriptor
["name"] == scaling_group
:
2590 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
2591 "at vnfd:scaling-group-descriptor".format(scaling_group
))
2594 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
2595 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
2596 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
2599 # TODO check if ns is in a proper status
2600 step
= "Sending scale order to VIM"
2602 if not db_nsr
["_admin"].get("scaling-group"):
2603 self
.update_db_2("nsrs", nsr_id
, {"_admin.scaling-group": [{"name": scaling_group
, "nb-scale-op": 0}]})
2604 admin_scale_index
= 0
2606 for admin_scale_index
, admin_scale_info
in enumerate(db_nsr
["_admin"]["scaling-group"]):
2607 if admin_scale_info
["name"] == scaling_group
:
2608 nb_scale_op
= admin_scale_info
.get("nb-scale-op", 0)
2610 else: # not found, set index one plus last element and add new entry with the name
2611 admin_scale_index
+= 1
2612 db_nsr_update
["_admin.scaling-group.{}.name".format(admin_scale_index
)] = scaling_group
2613 RO_scaling_info
= []
2614 vdu_scaling_info
= {"scaling_group_name": scaling_group
, "vdu": []}
2615 if scaling_type
== "SCALE_OUT":
2616 # count if max-instance-count is reached
2617 max_instance_count
= scaling_descriptor
.get("max-instance-count", 10)
2618 # self.logger.debug("MAX_INSTANCE_COUNT is {}".format(max_instance_count))
2619 if nb_scale_op
>= max_instance_count
:
2620 raise LcmException("reached the limit of {} (max-instance-count) "
2621 "scaling-out operations for the "
2622 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
2625 vdu_scaling_info
["scaling_direction"] = "OUT"
2626 vdu_scaling_info
["vdu-create"] = {}
2627 for vdu_scale_info
in scaling_descriptor
["vdu"]:
2628 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
2629 "type": "create", "count": vdu_scale_info
.get("count", 1)})
2630 vdu_scaling_info
["vdu-create"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
2632 elif scaling_type
== "SCALE_IN":
2633 # count if min-instance-count is reached
2634 min_instance_count
= 0
2635 if "min-instance-count" in scaling_descriptor
and scaling_descriptor
["min-instance-count"] is not None:
2636 min_instance_count
= int(scaling_descriptor
["min-instance-count"])
2637 if nb_scale_op
<= min_instance_count
:
2638 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
2639 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
2641 vdu_scaling_info
["scaling_direction"] = "IN"
2642 vdu_scaling_info
["vdu-delete"] = {}
2643 for vdu_scale_info
in scaling_descriptor
["vdu"]:
2644 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
2645 "type": "delete", "count": vdu_scale_info
.get("count", 1)})
2646 vdu_scaling_info
["vdu-delete"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
2648 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
2649 vdu_create
= vdu_scaling_info
.get("vdu-create")
2650 vdu_delete
= copy(vdu_scaling_info
.get("vdu-delete"))
2651 if vdu_scaling_info
["scaling_direction"] == "IN":
2652 for vdur
in reversed(db_vnfr
["vdur"]):
2653 if vdu_delete
.get(vdur
["vdu-id-ref"]):
2654 vdu_delete
[vdur
["vdu-id-ref"]] -= 1
2655 vdu_scaling_info
["vdu"].append({
2656 "name": vdur
["name"],
2657 "vdu_id": vdur
["vdu-id-ref"],
2660 for interface
in vdur
["interfaces"]:
2661 vdu_scaling_info
["vdu"][-1]["interface"].append({
2662 "name": interface
["name"],
2663 "ip_address": interface
["ip-address"],
2664 "mac_address": interface
.get("mac-address"),
2666 vdu_delete
= vdu_scaling_info
.pop("vdu-delete")
2669 step
= "Executing pre-scale vnf-config-primitive"
2670 if scaling_descriptor
.get("scaling-config-action"):
2671 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
2672 if (scaling_config_action
.get("trigger") == "pre-scale-in" and scaling_type
== "SCALE_IN") \
2673 or (scaling_config_action
.get("trigger") == "pre-scale-out" and scaling_type
== "SCALE_OUT"):
2674 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
2675 step
= db_nslcmop_update
["detailed-status"] = \
2676 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive
)
2678 # look for primitive
2679 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
2680 if config_primitive
["name"] == vnf_config_primitive
:
2684 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
2685 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
2686 "primitive".format(scaling_group
, config_primitive
))
2688 vnfr_params
= {"VDU_SCALE_INFO": vdu_scaling_info
}
2689 if db_vnfr
.get("additionalParamsForVnf"):
2690 vnfr_params
.update(db_vnfr
["additionalParamsForVnf"])
2692 scale_process
= "VCA"
2693 db_nsr_update
["config-status"] = "configuring pre-scaling"
2694 primitive_params
= self
._map
_primitive
_params
(config_primitive
, {}, vnfr_params
)
2696 # Pre-scale reintent check: Check if this sub-operation has been executed before
2697 op_index
= self
._check
_or
_add
_scale
_suboperation
(
2698 db_nslcmop
, nslcmop_id
, vnf_index
, vnf_config_primitive
, primitive_params
, 'PRE-SCALE')
2699 if (op_index
== self
.SUBOPERATION_STATUS_SKIP
):
2700 # Skip sub-operation
2701 result
= 'COMPLETED'
2702 result_detail
= 'Done'
2703 self
.logger
.debug(logging_text
+
2704 "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
2705 vnf_config_primitive
, result
, result_detail
))
2707 if (op_index
== self
.SUBOPERATION_STATUS_NEW
):
2708 # New sub-operation: Get index of this sub-operation
2709 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
2710 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} New sub-operation".
2711 format(vnf_config_primitive
))
2713 # Reintent: Get registered params for this existing sub-operation
2714 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
2715 vnf_index
= op
.get('member_vnf_index')
2716 vnf_config_primitive
= op
.get('primitive')
2717 primitive_params
= op
.get('primitive_params')
2718 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Sub-operation reintent".
2719 format(vnf_config_primitive
))
2720 # Execute the primitive, either with new (first-time) or registered (reintent) args
2721 result
, result_detail
= await self
._ns
_execute
_primitive
(
2722 nsr_deployed
, vnf_index
, None, None, None, vnf_config_primitive
, primitive_params
)
2723 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
2724 vnf_config_primitive
, result
, result_detail
))
2725 # Update operationState = COMPLETED | FAILED
2726 self
._update
_suboperation
_status
(
2727 db_nslcmop
, op_index
, result
, result_detail
)
2729 if result
== "FAILED":
2730 raise LcmException(result_detail
)
2731 db_nsr_update
["config-status"] = old_config_status
2732 scale_process
= None
2736 # Should this block be skipped if 'RO_nsr_id' == None ?
2737 # if (RO_nsr_id and RO_scaling_info):
2739 scale_process
= "RO"
2740 # Scale RO reintent check: Check if this sub-operation has been executed before
2741 op_index
= self
._check
_or
_add
_scale
_suboperation
(
2742 db_nslcmop
, vnf_index
, None, None, 'SCALE-RO', RO_nsr_id
, RO_scaling_info
)
2743 if (op_index
== self
.SUBOPERATION_STATUS_SKIP
):
2744 # Skip sub-operation
2745 result
= 'COMPLETED'
2746 result_detail
= 'Done'
2747 self
.logger
.debug(logging_text
+ "Skipped sub-operation RO, result {} {}".format(
2748 result
, result_detail
))
2750 if (op_index
== self
.SUBOPERATION_STATUS_NEW
):
2751 # New sub-operation: Get index of this sub-operation
2752 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
2753 self
.logger
.debug(logging_text
+ "New sub-operation RO")
2755 # Reintent: Get registered params for this existing sub-operation
2756 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
2757 RO_nsr_id
= op
.get('RO_nsr_id')
2758 RO_scaling_info
= op
.get('RO_scaling_info')
2759 self
.logger
.debug(logging_text
+ "Sub-operation RO reintent".format(
2760 vnf_config_primitive
))
2762 RO_desc
= await self
.RO
.create_action("ns", RO_nsr_id
, {"vdu-scaling": RO_scaling_info
})
2763 db_nsr_update
["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index
)] = nb_scale_op
2764 db_nsr_update
["_admin.scaling-group.{}.time".format(admin_scale_index
)] = time()
2766 RO_nslcmop_id
= RO_desc
["instance_action_id"]
2767 db_nslcmop_update
["_admin.deploy.RO"] = RO_nslcmop_id
2769 RO_task_done
= False
2770 step
= detailed_status
= "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id
)
2771 detailed_status_old
= None
2772 self
.logger
.debug(logging_text
+ step
)
2774 deployment_timeout
= 1 * 3600 # One hour
2775 while deployment_timeout
> 0:
2776 if not RO_task_done
:
2777 desc
= await self
.RO
.show("ns", item_id_name
=RO_nsr_id
, extra_item
="action",
2778 extra_item_id
=RO_nslcmop_id
)
2779 ns_status
, ns_status_info
= self
.RO
.check_action_status(desc
)
2780 if ns_status
== "ERROR":
2781 raise ROclient
.ROClientException(ns_status_info
)
2782 elif ns_status
== "BUILD":
2783 detailed_status
= step
+ "; {}".format(ns_status_info
)
2784 elif ns_status
== "ACTIVE":
2786 step
= detailed_status
= "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id
)
2787 self
.logger
.debug(logging_text
+ step
)
2789 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
2792 if ns_status
== "ERROR":
2793 raise ROclient
.ROClientException(ns_status_info
)
2794 elif ns_status
== "BUILD":
2795 detailed_status
= step
+ "; {}".format(ns_status_info
)
2796 elif ns_status
== "ACTIVE":
2797 step
= detailed_status
= \
2798 "Waiting for management IP address reported by the VIM. Updating VNFRs"
2800 self
.scale_vnfr(db_vnfr
, vdu_create
=vdu_create
, vdu_delete
=vdu_delete
)
2803 desc
= await self
.RO
.show("ns", RO_nsr_id
)
2804 # nsr_deployed["nsr_ip"] = RO.get_ns_vnf_info(desc)
2805 self
.ns_update_vnfr({db_vnfr
["member-vnf-index-ref"]: db_vnfr
}, desc
)
2807 except LcmExceptionNoMgmtIP
:
2810 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
2811 if detailed_status
!= detailed_status_old
:
2812 self
._update
_suboperation
_status
(
2813 db_nslcmop
, op_index
, 'COMPLETED', detailed_status
)
2814 detailed_status_old
= db_nslcmop_update
["detailed-status"] = detailed_status
2815 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2817 await asyncio
.sleep(5, loop
=self
.loop
)
2818 deployment_timeout
-= 5
2819 if deployment_timeout
<= 0:
2820 self
._update
_suboperation
_status
(
2821 db_nslcmop
, nslcmop_id
, op_index
, 'FAILED', "Timeout when waiting for ns to get ready")
2822 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
2824 # update VDU_SCALING_INFO with the obtained ip_addresses
2825 if vdu_scaling_info
["scaling_direction"] == "OUT":
2826 for vdur
in reversed(db_vnfr
["vdur"]):
2827 if vdu_scaling_info
["vdu-create"].get(vdur
["vdu-id-ref"]):
2828 vdu_scaling_info
["vdu-create"][vdur
["vdu-id-ref"]] -= 1
2829 vdu_scaling_info
["vdu"].append({
2830 "name": vdur
["name"],
2831 "vdu_id": vdur
["vdu-id-ref"],
2834 for interface
in vdur
["interfaces"]:
2835 vdu_scaling_info
["vdu"][-1]["interface"].append({
2836 "name": interface
["name"],
2837 "ip_address": interface
["ip-address"],
2838 "mac_address": interface
.get("mac-address"),
2840 del vdu_scaling_info
["vdu-create"]
2842 self
._update
_suboperation
_status
(db_nslcmop
, op_index
, 'COMPLETED', 'Done')
2845 scale_process
= None
2847 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2850 # execute primitive service POST-SCALING
2851 step
= "Executing post-scale vnf-config-primitive"
2852 if scaling_descriptor
.get("scaling-config-action"):
2853 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
2854 if (scaling_config_action
.get("trigger") == "post-scale-in" and scaling_type
== "SCALE_IN") \
2855 or (scaling_config_action
.get("trigger") == "post-scale-out" and scaling_type
== "SCALE_OUT"):
2856 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
2857 step
= db_nslcmop_update
["detailed-status"] = \
2858 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive
)
2860 vnfr_params
= {"VDU_SCALE_INFO": vdu_scaling_info
}
2861 if db_vnfr
.get("additionalParamsForVnf"):
2862 vnfr_params
.update(db_vnfr
["additionalParamsForVnf"])
2864 # look for primitive
2865 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
2866 if config_primitive
["name"] == vnf_config_primitive
:
2869 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
2870 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
2871 "match any vnf-configuration:config-primitive".format(scaling_group
,
2873 scale_process
= "VCA"
2874 db_nsr_update
["config-status"] = "configuring post-scaling"
2875 primitive_params
= self
._map
_primitive
_params
(config_primitive
, {}, vnfr_params
)
2877 # Post-scale reintent check: Check if this sub-operation has been executed before
2878 op_index
= self
._check
_or
_add
_scale
_suboperation
(
2879 db_nslcmop
, nslcmop_id
, vnf_index
, vnf_config_primitive
, primitive_params
, 'POST-SCALE')
2880 if (op_index
== self
.SUBOPERATION_STATUS_SKIP
):
2881 # Skip sub-operation
2882 result
= 'COMPLETED'
2883 result_detail
= 'Done'
2884 self
.logger
.debug(logging_text
+
2885 "vnf_config_primitive={} Skipped sub-operation, result {} {}".
2886 format(vnf_config_primitive
, result
, result_detail
))
2888 if (op_index
== self
.SUBOPERATION_STATUS_NEW
):
2889 # New sub-operation: Get index of this sub-operation
2890 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
2891 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} New sub-operation".
2892 format(vnf_config_primitive
))
2894 # Reintent: Get registered params for this existing sub-operation
2895 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
2896 vnf_index
= op
.get('member_vnf_index')
2897 vnf_config_primitive
= op
.get('primitive')
2898 primitive_params
= op
.get('primitive_params')
2899 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Sub-operation reintent".
2900 format(vnf_config_primitive
))
2901 # Execute the primitive, either with new (first-time) or registered (reintent) args
2902 result
, result_detail
= await self
._ns
_execute
_primitive
(
2903 nsr_deployed
, vnf_index
, None, None, None, vnf_config_primitive
, primitive_params
)
2904 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
2905 vnf_config_primitive
, result
, result_detail
))
2906 # Update operationState = COMPLETED | FAILED
2907 self
._update
_suboperation
_status
(
2908 db_nslcmop
, op_index
, result
, result_detail
)
2910 if result
== "FAILED":
2911 raise LcmException(result_detail
)
2912 db_nsr_update
["config-status"] = old_config_status
2913 scale_process
= None
2916 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
2917 db_nslcmop_update
["statusEnteredTime"] = time()
2918 db_nslcmop_update
["detailed-status"] = "done"
2919 db_nsr_update
["detailed-status"] = "" # "scaled {} {}".format(scaling_group, scaling_type)
2920 db_nsr_update
["operational-status"] = "running" if old_operational_status
== "failed" \
2921 else old_operational_status
2922 db_nsr_update
["config-status"] = old_config_status
2924 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
2925 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
2927 except asyncio
.CancelledError
:
2928 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
2929 exc
= "Operation was cancelled"
2930 except Exception as e
:
2931 exc
= traceback
.format_exc()
2932 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
2936 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
2937 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2938 db_nslcmop_update
["statusEnteredTime"] = time()
2940 db_nsr_update
["operational-status"] = old_operational_status
2941 db_nsr_update
["config-status"] = old_config_status
2942 db_nsr_update
["detailed-status"] = ""
2943 db_nsr_update
["_admin.nslcmop"] = None
2945 if "VCA" in scale_process
:
2946 db_nsr_update
["config-status"] = "failed"
2947 if "RO" in scale_process
:
2948 db_nsr_update
["operational-status"] = "failed"
2949 db_nsr_update
["detailed-status"] = "FAILED scaling nslcmop={} {}: {}".format(nslcmop_id
, step
,
2952 if db_nslcmop
and db_nslcmop_update
:
2953 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2955 db_nsr_update
["_admin.current-operation"] = None
2956 db_nsr_update
["_admin.operation-type"] = None
2957 db_nsr_update
["_admin.nslcmop"] = None
2958 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2959 except DbException
as e
:
2960 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
2961 if nslcmop_operation_state
:
2963 await self
.msg
.aiowrite("ns", "scaled", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2964 "operationState": nslcmop_operation_state
},
2967 # await asyncio.sleep(cooldown_time, loop=self.loop)
2968 # await self.msg.aiowrite("ns","scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
2969 except Exception as e
:
2970 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
2971 self
.logger
.debug(logging_text
+ "Exit")
2972 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_scale")