1 # -*- coding: utf-8 -*-
4 # Copyright 2018 Telefonica S.A.
6 # Licensed under the Apache License, Version 2.0 (the "License"); you may
7 # not use this file except in compliance with the License. You may obtain
8 # a copy of the License at
10 # http://www.apache.org/licenses/LICENSE-2.0
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 # License for the specific language governing permissions and limitations
22 import logging
.handlers
24 from jinja2
import Environment
, Template
, meta
, TemplateError
, TemplateNotFound
, TemplateSyntaxError
26 from osm_lcm
import ROclient
27 from osm_lcm
.lcm_utils
import LcmException
, LcmExceptionNoMgmtIP
, LcmBase
28 from n2vc
.k8s_helm_conn
import K8sHelmConnector
30 from osm_common
.dbbase
import DbException
31 from osm_common
.fsbase
import FsException
33 from n2vc
.n2vc_juju_conn
import N2VCJujuConnector
35 from copy
import copy
, deepcopy
36 from http
import HTTPStatus
38 from uuid
import uuid4
40 __author__
= "Alfonso Tierno"
43 def get_iterable(in_dict
, in_key
):
45 Similar to <dict>.get(), but if value is None, False, ..., An empty tuple is returned instead
46 :param in_dict: a dictionary
47 :param in_key: the key to look for at in_dict
48 :return: in_dict[in_var] or () if it is None or not present
50 if not in_dict
.get(in_key
):
52 return in_dict
[in_key
]
55 def populate_dict(target_dict
, key_list
, value
):
57 Update target_dict creating nested dictionaries with the key_list. Last key_list item is asigned the value.
58 Example target_dict={K: J}; key_list=[a,b,c]; target_dict will be {K: J, a: {b: {c: value}}}
59 :param target_dict: dictionary to be changed
60 :param key_list: list of keys to insert at target_dict
64 for key
in key_list
[0:-1]:
65 if key
not in target_dict
:
67 target_dict
= target_dict
[key
]
68 target_dict
[key_list
[-1]] = value
71 def deep_get(target_dict
, key_list
):
73 Get a value from target_dict entering in the nested keys. If keys does not exist, it returns None
74 Example target_dict={a: {b: 5}}; key_list=[a,b] returns 5; both key_list=[a,b,c] and key_list=[f,h] return None
75 :param target_dict: dictionary to be read
76 :param key_list: list of keys to read from target_dict
77 :return: The wanted value if exist, None otherwise
80 if not isinstance(target_dict
, dict) or key
not in target_dict
:
82 target_dict
= target_dict
[key
]
87 timeout_vca_on_error
= 5 * 60 # Time for charm from first time at blocked,error status to mark as failed
88 total_deploy_timeout
= 2 * 3600 # global timeout for deployment
89 timeout_charm_delete
= 10 * 60
90 timeout_primitive
= 10 * 60 # timeout for primitive execution
92 SUBOPERATION_STATUS_NOT_FOUND
= -1
93 SUBOPERATION_STATUS_NEW
= -2
94 SUBOPERATION_STATUS_SKIP
= -3
96 def __init__(self
, db
, msg
, fs
, lcm_tasks
, ro_config
, vca_config
, loop
):
98 Init, Connect to database, filesystem storage, and messaging
99 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
106 logger
=logging
.getLogger('lcm.ns')
110 self
.lcm_tasks
= lcm_tasks
111 self
.ro_config
= ro_config
112 self
.vca_config
= vca_config
113 if 'pubkey' in self
.vca_config
:
114 self
.vca_config
['public_key'] = self
.vca_config
['pubkey']
115 if 'cacert' in self
.vca_config
:
116 self
.vca_config
['ca_cert'] = self
.vca_config
['cacert']
118 # create N2VC connector
119 self
.n2vc
= N2VCJujuConnector(
124 url
='{}:{}'.format(self
.vca_config
['host'], self
.vca_config
['port']),
125 username
=self
.vca_config
.get('user', None),
126 vca_config
=self
.vca_config
,
127 on_update_db
=self
._on
_update
_n
2vc
_db
130 # api_proxy=vca_config.get('apiproxy')
133 self
.k8sclusterhelm
= K8sHelmConnector(
134 kubectl_command
=self
.vca_config
.get("kubectlpath"),
135 helm_command
=self
.vca_config
.get("helmpath"),
143 self
.RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
145 def _on_update_n2vc_db(self
, table
, filter, path
, updated_data
):
147 self
.logger
.debug('_on_update_n2vc_db(table={}, filter={}, path={}, updated_data={}'
148 .format(table
, filter, path
, updated_data
))
151 # write NS status to database
153 # # nsrs_id = filter.get('_id')
156 # nsr = self.db.get_one(table=table, q_filter=filter)
157 # # get VCA deployed list
158 # vca_list = deep_get(target_dict=nsr, key_list=('_admin', 'deployed', 'VCA'))
160 # # ro_list = deep_get(target_dict=nsr, key_list=('_admin', 'deployed', 'RO'))
161 # for vca in vca_list:
162 # # status = vca.get('status')
164 # # detailed_status = vca.get('detailed-status')
165 # # print(detailed_status)
166 # # for ro in ro_list:
169 # except Exception as e:
170 # self.logger.error('Error writing NS status to db: {}'.format(e))
172 def vnfd2RO(self
, vnfd
, new_id
=None, additionalParams
=None, nsrId
=None):
174 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
175 :param vnfd: input vnfd
176 :param new_id: overrides vnf id if provided
177 :param additionalParams: Instantiation params for VNFs provided
178 :param nsrId: Id of the NSR
179 :return: copy of vnfd
182 vnfd_RO
= deepcopy(vnfd
)
183 # remove unused by RO configuration, monitoring, scaling and internal keys
184 vnfd_RO
.pop("_id", None)
185 vnfd_RO
.pop("_admin", None)
186 vnfd_RO
.pop("vnf-configuration", None)
187 vnfd_RO
.pop("monitoring-param", None)
188 vnfd_RO
.pop("scaling-group-descriptor", None)
189 vnfd_RO
.pop("kdu", None)
190 vnfd_RO
.pop("k8s-cluster", None)
192 vnfd_RO
["id"] = new_id
194 # parse cloud-init or cloud-init-file with the provided variables using Jinja2
195 for vdu
in get_iterable(vnfd_RO
, "vdu"):
196 cloud_init_file
= None
197 if vdu
.get("cloud-init-file"):
198 base_folder
= vnfd
["_admin"]["storage"]
199 cloud_init_file
= "{}/{}/cloud_init/{}".format(base_folder
["folder"], base_folder
["pkg-dir"],
200 vdu
["cloud-init-file"])
201 with self
.fs
.file_open(cloud_init_file
, "r") as ci_file
:
202 cloud_init_content
= ci_file
.read()
203 vdu
.pop("cloud-init-file", None)
204 elif vdu
.get("cloud-init"):
205 cloud_init_content
= vdu
["cloud-init"]
210 ast
= env
.parse(cloud_init_content
)
211 mandatory_vars
= meta
.find_undeclared_variables(ast
)
213 for var
in mandatory_vars
:
214 if not additionalParams
or var
not in additionalParams
.keys():
215 raise LcmException("Variable '{}' defined at vnfd[id={}]:vdu[id={}]:cloud-init/cloud-init-"
216 "file, must be provided in the instantiation parameters inside the "
217 "'additionalParamsForVnf' block".format(var
, vnfd
["id"], vdu
["id"]))
218 template
= Template(cloud_init_content
)
219 cloud_init_content
= template
.render(additionalParams
or {})
220 vdu
["cloud-init"] = cloud_init_content
223 except FsException
as e
:
224 raise LcmException("Error reading vnfd[id={}]:vdu[id={}]:cloud-init-file={}: {}".
225 format(vnfd
["id"], vdu
["id"], cloud_init_file
, e
))
226 except (TemplateError
, TemplateNotFound
, TemplateSyntaxError
) as e
:
227 raise LcmException("Error parsing Jinja2 to cloud-init content at vnfd[id={}]:vdu[id={}]: {}".
228 format(vnfd
["id"], vdu
["id"], e
))
230 def ns_params_2_RO(self
, ns_params
, nsd
, vnfd_dict
, n2vc_key_list
):
232 Creates a RO ns descriptor from OSM ns_instantiate params
233 :param ns_params: OSM instantiate params
234 :return: The RO ns descriptor
238 # TODO feature 1417: Check that no instantiation is set over PDU
239 # check if PDU forces a concrete vim-network-id and add it
240 # check if PDU contains a SDN-assist info (dpid, switch, port) and pass it to RO
242 def vim_account_2_RO(vim_account
):
243 if vim_account
in vim_2_RO
:
244 return vim_2_RO
[vim_account
]
246 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_account
})
247 if db_vim
["_admin"]["operationalState"] != "ENABLED":
248 raise LcmException("VIM={} is not available. operationalState={}".format(
249 vim_account
, db_vim
["_admin"]["operationalState"]))
250 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
251 vim_2_RO
[vim_account
] = RO_vim_id
254 def wim_account_2_RO(wim_account
):
255 if isinstance(wim_account
, str):
256 if wim_account
in wim_2_RO
:
257 return wim_2_RO
[wim_account
]
259 db_wim
= self
.db
.get_one("wim_accounts", {"_id": wim_account
})
260 if db_wim
["_admin"]["operationalState"] != "ENABLED":
261 raise LcmException("WIM={} is not available. operationalState={}".format(
262 wim_account
, db_wim
["_admin"]["operationalState"]))
263 RO_wim_id
= db_wim
["_admin"]["deployed"]["RO-account"]
264 wim_2_RO
[wim_account
] = RO_wim_id
269 def ip_profile_2_RO(ip_profile
):
270 RO_ip_profile
= deepcopy((ip_profile
))
271 if "dns-server" in RO_ip_profile
:
272 if isinstance(RO_ip_profile
["dns-server"], list):
273 RO_ip_profile
["dns-address"] = []
274 for ds
in RO_ip_profile
.pop("dns-server"):
275 RO_ip_profile
["dns-address"].append(ds
['address'])
277 RO_ip_profile
["dns-address"] = RO_ip_profile
.pop("dns-server")
278 if RO_ip_profile
.get("ip-version") == "ipv4":
279 RO_ip_profile
["ip-version"] = "IPv4"
280 if RO_ip_profile
.get("ip-version") == "ipv6":
281 RO_ip_profile
["ip-version"] = "IPv6"
282 if "dhcp-params" in RO_ip_profile
:
283 RO_ip_profile
["dhcp"] = RO_ip_profile
.pop("dhcp-params")
289 # "name": ns_params["nsName"],
290 # "description": ns_params.get("nsDescription"),
291 "datacenter": vim_account_2_RO(ns_params
["vimAccountId"]),
292 "wim_account": wim_account_2_RO(ns_params
.get("wimAccountId")),
293 # "scenario": ns_params["nsdId"],
296 n2vc_key_list
= n2vc_key_list
or []
297 for vnfd_ref
, vnfd
in vnfd_dict
.items():
298 vdu_needed_access
= []
300 if vnfd
.get("vnf-configuration"):
301 ssh_required
= deep_get(vnfd
, ("vnf-configuration", "config-access", "ssh-access", "required"))
302 if ssh_required
and vnfd
.get("mgmt-interface"):
303 if vnfd
["mgmt-interface"].get("vdu-id"):
304 vdu_needed_access
.append(vnfd
["mgmt-interface"]["vdu-id"])
305 elif vnfd
["mgmt-interface"].get("cp"):
306 mgmt_cp
= vnfd
["mgmt-interface"]["cp"]
308 for vdu
in vnfd
.get("vdu", ()):
309 if vdu
.get("vdu-configuration"):
310 ssh_required
= deep_get(vdu
, ("vdu-configuration", "config-access", "ssh-access", "required"))
312 vdu_needed_access
.append(vdu
["id"])
314 for vdu_interface
in vdu
.get("interface"):
315 if vdu_interface
.get("external-connection-point-ref") and \
316 vdu_interface
["external-connection-point-ref"] == mgmt_cp
:
317 vdu_needed_access
.append(vdu
["id"])
321 if vdu_needed_access
:
322 for vnf_member
in nsd
.get("constituent-vnfd"):
323 if vnf_member
["vnfd-id-ref"] != vnfd_ref
:
325 for vdu
in vdu_needed_access
:
326 populate_dict(RO_ns_params
,
327 ("vnfs", vnf_member
["member-vnf-index"], "vdus", vdu
, "mgmt_keys"),
330 if ns_params
.get("vduImage"):
331 RO_ns_params
["vduImage"] = ns_params
["vduImage"]
333 if ns_params
.get("ssh_keys"):
334 RO_ns_params
["cloud-config"] = {"key-pairs": ns_params
["ssh_keys"]}
335 for vnf_params
in get_iterable(ns_params
, "vnf"):
336 for constituent_vnfd
in nsd
["constituent-vnfd"]:
337 if constituent_vnfd
["member-vnf-index"] == vnf_params
["member-vnf-index"]:
338 vnf_descriptor
= vnfd_dict
[constituent_vnfd
["vnfd-id-ref"]]
341 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index={} is not present at nsd:"
342 "constituent-vnfd".format(vnf_params
["member-vnf-index"]))
343 if vnf_params
.get("vimAccountId"):
344 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "datacenter"),
345 vim_account_2_RO(vnf_params
["vimAccountId"]))
347 for vdu_params
in get_iterable(vnf_params
, "vdu"):
348 # TODO feature 1417: check that this VDU exist and it is not a PDU
349 if vdu_params
.get("volume"):
350 for volume_params
in vdu_params
["volume"]:
351 if volume_params
.get("vim-volume-id"):
352 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
353 vdu_params
["id"], "devices", volume_params
["name"], "vim_id"),
354 volume_params
["vim-volume-id"])
355 if vdu_params
.get("interface"):
356 for interface_params
in vdu_params
["interface"]:
357 if interface_params
.get("ip-address"):
358 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
359 vdu_params
["id"], "interfaces", interface_params
["name"],
361 interface_params
["ip-address"])
362 if interface_params
.get("mac-address"):
363 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
364 vdu_params
["id"], "interfaces", interface_params
["name"],
366 interface_params
["mac-address"])
367 if interface_params
.get("floating-ip-required"):
368 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
369 vdu_params
["id"], "interfaces", interface_params
["name"],
371 interface_params
["floating-ip-required"])
373 for internal_vld_params
in get_iterable(vnf_params
, "internal-vld"):
374 if internal_vld_params
.get("vim-network-name"):
375 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
376 internal_vld_params
["name"], "vim-network-name"),
377 internal_vld_params
["vim-network-name"])
378 if internal_vld_params
.get("vim-network-id"):
379 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
380 internal_vld_params
["name"], "vim-network-id"),
381 internal_vld_params
["vim-network-id"])
382 if internal_vld_params
.get("ip-profile"):
383 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
384 internal_vld_params
["name"], "ip-profile"),
385 ip_profile_2_RO(internal_vld_params
["ip-profile"]))
387 for icp_params
in get_iterable(internal_vld_params
, "internal-connection-point"):
390 for vdu_descriptor
in vnf_descriptor
["vdu"]:
391 for vdu_interface
in vdu_descriptor
["interface"]:
392 if vdu_interface
.get("internal-connection-point-ref") == icp_params
["id-ref"]:
393 if icp_params
.get("ip-address"):
394 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
395 vdu_descriptor
["id"], "interfaces",
396 vdu_interface
["name"], "ip_address"),
397 icp_params
["ip-address"])
399 if icp_params
.get("mac-address"):
400 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
401 vdu_descriptor
["id"], "interfaces",
402 vdu_interface
["name"], "mac_address"),
403 icp_params
["mac-address"])
409 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
410 "internal-vld:id-ref={} is not present at vnfd:internal-"
411 "connection-point".format(vnf_params
["member-vnf-index"],
412 icp_params
["id-ref"]))
414 for vld_params
in get_iterable(ns_params
, "vld"):
415 if "ip-profile" in vld_params
:
416 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "ip-profile"),
417 ip_profile_2_RO(vld_params
["ip-profile"]))
419 if "wimAccountId" in vld_params
and vld_params
["wimAccountId"] is not None:
420 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "wim_account"),
421 wim_account_2_RO(vld_params
["wimAccountId"])),
422 if vld_params
.get("vim-network-name"):
424 if isinstance(vld_params
["vim-network-name"], dict):
425 for vim_account
, vim_net
in vld_params
["vim-network-name"].items():
426 RO_vld_sites
.append({
427 "netmap-use": vim_net
,
428 "datacenter": vim_account_2_RO(vim_account
)
430 else: # isinstance str
431 RO_vld_sites
.append({"netmap-use": vld_params
["vim-network-name"]})
433 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "sites"), RO_vld_sites
)
434 if vld_params
.get("vim-network-id"):
436 if isinstance(vld_params
["vim-network-id"], dict):
437 for vim_account
, vim_net
in vld_params
["vim-network-id"].items():
438 RO_vld_sites
.append({
439 "netmap-use": vim_net
,
440 "datacenter": vim_account_2_RO(vim_account
)
442 else: # isinstance str
443 RO_vld_sites
.append({"netmap-use": vld_params
["vim-network-id"]})
445 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "sites"), RO_vld_sites
)
446 if vld_params
.get("ns-net"):
447 if isinstance(vld_params
["ns-net"], dict):
448 for vld_id
, instance_scenario_id
in vld_params
["ns-net"].items():
449 RO_vld_ns_net
= {"instance_scenario_id": instance_scenario_id
, "osm_id": vld_id
}
451 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "use-network"), RO_vld_ns_net
)
452 if "vnfd-connection-point-ref" in vld_params
:
453 for cp_params
in vld_params
["vnfd-connection-point-ref"]:
455 for constituent_vnfd
in nsd
["constituent-vnfd"]:
456 if constituent_vnfd
["member-vnf-index"] == cp_params
["member-vnf-index-ref"]:
457 vnf_descriptor
= vnfd_dict
[constituent_vnfd
["vnfd-id-ref"]]
461 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={} "
462 "is not present at nsd:constituent-vnfd".format(cp_params
["member-vnf-index-ref"]))
464 for vdu_descriptor
in vnf_descriptor
["vdu"]:
465 for interface_descriptor
in vdu_descriptor
["interface"]:
466 if interface_descriptor
.get("external-connection-point-ref") == \
467 cp_params
["vnfd-connection-point-ref"]:
474 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={}:"
475 "vnfd-connection-point-ref={} is not present at vnfd={}".format(
476 cp_params
["member-vnf-index-ref"],
477 cp_params
["vnfd-connection-point-ref"],
478 vnf_descriptor
["id"]))
479 if cp_params
.get("ip-address"):
480 populate_dict(RO_ns_params
, ("vnfs", cp_params
["member-vnf-index-ref"], "vdus",
481 vdu_descriptor
["id"], "interfaces",
482 interface_descriptor
["name"], "ip_address"),
483 cp_params
["ip-address"])
484 if cp_params
.get("mac-address"):
485 populate_dict(RO_ns_params
, ("vnfs", cp_params
["member-vnf-index-ref"], "vdus",
486 vdu_descriptor
["id"], "interfaces",
487 interface_descriptor
["name"], "mac_address"),
488 cp_params
["mac-address"])
491 def scale_vnfr(self
, db_vnfr
, vdu_create
=None, vdu_delete
=None):
492 # make a copy to do not change
493 vdu_create
= copy(vdu_create
)
494 vdu_delete
= copy(vdu_delete
)
496 vdurs
= db_vnfr
.get("vdur")
499 vdu_index
= len(vdurs
)
502 vdur
= vdurs
[vdu_index
]
503 if vdur
.get("pdu-type"):
505 vdu_id_ref
= vdur
["vdu-id-ref"]
506 if vdu_create
and vdu_create
.get(vdu_id_ref
):
507 for index
in range(0, vdu_create
[vdu_id_ref
]):
508 vdur
= deepcopy(vdur
)
509 vdur
["_id"] = str(uuid4())
510 vdur
["count-index"] += 1
511 vdurs
.insert(vdu_index
+1+index
, vdur
)
512 del vdu_create
[vdu_id_ref
]
513 if vdu_delete
and vdu_delete
.get(vdu_id_ref
):
515 vdu_delete
[vdu_id_ref
] -= 1
516 if not vdu_delete
[vdu_id_ref
]:
517 del vdu_delete
[vdu_id_ref
]
518 # check all operations are done
519 if vdu_create
or vdu_delete
:
520 raise LcmException("Error scaling OUT VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
523 raise LcmException("Error scaling IN VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
526 vnfr_update
= {"vdur": vdurs
}
527 db_vnfr
["vdur"] = vdurs
528 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
530 def ns_update_nsr(self
, ns_update_nsr
, db_nsr
, nsr_desc_RO
):
532 Updates database nsr with the RO info for the created vld
533 :param ns_update_nsr: dictionary to be filled with the updated info
534 :param db_nsr: content of db_nsr. This is also modified
535 :param nsr_desc_RO: nsr descriptor from RO
536 :return: Nothing, LcmException is raised on errors
539 for vld_index
, vld
in enumerate(get_iterable(db_nsr
, "vld")):
540 for net_RO
in get_iterable(nsr_desc_RO
, "nets"):
541 if vld
["id"] != net_RO
.get("ns_net_osm_id"):
543 vld
["vim-id"] = net_RO
.get("vim_net_id")
544 vld
["name"] = net_RO
.get("vim_name")
545 vld
["status"] = net_RO
.get("status")
546 vld
["status-detailed"] = net_RO
.get("error_msg")
547 ns_update_nsr
["vld.{}".format(vld_index
)] = vld
550 raise LcmException("ns_update_nsr: Not found vld={} at RO info".format(vld
["id"]))
552 def ns_update_vnfr(self
, db_vnfrs
, nsr_desc_RO
):
554 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
555 :param db_vnfrs: dictionary with member-vnf-index: vnfr-content
556 :param nsr_desc_RO: nsr descriptor from RO
557 :return: Nothing, LcmException is raised on errors
559 for vnf_index
, db_vnfr
in db_vnfrs
.items():
560 for vnf_RO
in nsr_desc_RO
["vnfs"]:
561 if vnf_RO
["member_vnf_index"] != vnf_index
:
564 if vnf_RO
.get("ip_address"):
565 db_vnfr
["ip-address"] = vnfr_update
["ip-address"] = vnf_RO
["ip_address"].split(";")[0]
566 elif not db_vnfr
.get("ip-address"):
567 raise LcmExceptionNoMgmtIP("ns member_vnf_index '{}' has no IP address".format(vnf_index
))
569 for vdu_index
, vdur
in enumerate(get_iterable(db_vnfr
, "vdur")):
570 vdur_RO_count_index
= 0
571 if vdur
.get("pdu-type"):
573 for vdur_RO
in get_iterable(vnf_RO
, "vms"):
574 if vdur
["vdu-id-ref"] != vdur_RO
["vdu_osm_id"]:
576 if vdur
["count-index"] != vdur_RO_count_index
:
577 vdur_RO_count_index
+= 1
579 vdur
["vim-id"] = vdur_RO
.get("vim_vm_id")
580 if vdur_RO
.get("ip_address"):
581 vdur
["ip-address"] = vdur_RO
["ip_address"].split(";")[0]
583 vdur
["ip-address"] = None
584 vdur
["vdu-id-ref"] = vdur_RO
.get("vdu_osm_id")
585 vdur
["name"] = vdur_RO
.get("vim_name")
586 vdur
["status"] = vdur_RO
.get("status")
587 vdur
["status-detailed"] = vdur_RO
.get("error_msg")
588 for ifacer
in get_iterable(vdur
, "interfaces"):
589 for interface_RO
in get_iterable(vdur_RO
, "interfaces"):
590 if ifacer
["name"] == interface_RO
.get("internal_name"):
591 ifacer
["ip-address"] = interface_RO
.get("ip_address")
592 ifacer
["mac-address"] = interface_RO
.get("mac_address")
595 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} interface={} "
597 .format(vnf_index
, vdur
["vdu-id-ref"], ifacer
["name"]))
598 vnfr_update
["vdur.{}".format(vdu_index
)] = vdur
601 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} count_index={} from "
602 "VIM info".format(vnf_index
, vdur
["vdu-id-ref"], vdur
["count-index"]))
604 for vld_index
, vld
in enumerate(get_iterable(db_vnfr
, "vld")):
605 for net_RO
in get_iterable(nsr_desc_RO
, "nets"):
606 if vld
["id"] != net_RO
.get("vnf_net_osm_id"):
608 vld
["vim-id"] = net_RO
.get("vim_net_id")
609 vld
["name"] = net_RO
.get("vim_name")
610 vld
["status"] = net_RO
.get("status")
611 vld
["status-detailed"] = net_RO
.get("error_msg")
612 vnfr_update
["vld.{}".format(vld_index
)] = vld
615 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vld={} from VIM info".format(
616 vnf_index
, vld
["id"]))
618 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
622 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} from VIM info".format(vnf_index
))
624 async def instantiate_RO(self
, logging_text
, nsr_id
, nsd
, db_nsr
,
625 db_nslcmop
, db_vnfrs
, db_vnfds_ref
, n2vc_key_list
):
628 RO_descriptor_number
= 0 # number of descriptors created at RO
629 vnf_index_2_RO_id
= {} # map between vnfd/nsd id to the id used at RO
630 start_deploy
= time()
631 vdu_flag
= False # If any of the VNFDs has VDUs
632 ns_params
= db_nslcmop
.get("operationParams")
636 # get vnfds, instantiate at RO
638 for c_vnf
in nsd
.get("constituent-vnfd", ()):
639 member_vnf_index
= c_vnf
["member-vnf-index"]
640 vnfd
= db_vnfds_ref
[c_vnf
['vnfd-id-ref']]
643 vnfd_ref
= vnfd
["id"]
644 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Creating vnfd='{}' member_vnf_index='{}' at" \
645 " RO".format(vnfd_ref
, member_vnf_index
)
646 # self.logger.debug(logging_text + step)
647 vnfd_id_RO
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, member_vnf_index
[:23])
648 vnf_index_2_RO_id
[member_vnf_index
] = vnfd_id_RO
649 RO_descriptor_number
+= 1
651 # look position at deployed.RO.vnfd if not present it will be appended at the end
652 for index
, vnf_deployed
in enumerate(db_nsr
["_admin"]["deployed"]["RO"]["vnfd"]):
653 if vnf_deployed
["member-vnf-index"] == member_vnf_index
:
656 index
= len(db_nsr
["_admin"]["deployed"]["RO"]["vnfd"])
657 db_nsr
["_admin"]["deployed"]["RO"]["vnfd"].append(None)
660 RO_update
= {"member-vnf-index": member_vnf_index
}
661 vnfd_list
= await self
.RO
.get_list("vnfd", filter_by
={"osm_id": vnfd_id_RO
})
663 RO_update
["id"] = vnfd_list
[0]["uuid"]
664 self
.logger
.debug(logging_text
+ "vnfd='{}' member_vnf_index='{}' exists at RO. Using RO_id={}".
665 format(vnfd_ref
, member_vnf_index
, vnfd_list
[0]["uuid"]))
667 vnfd_RO
= self
.vnfd2RO(vnfd
, vnfd_id_RO
, db_vnfrs
[c_vnf
["member-vnf-index"]].
668 get("additionalParamsForVnf"), nsr_id
)
669 desc
= await self
.RO
.create("vnfd", descriptor
=vnfd_RO
)
670 RO_update
["id"] = desc
["uuid"]
671 self
.logger
.debug(logging_text
+ "vnfd='{}' member_vnf_index='{}' created at RO. RO_id={}".format(
672 vnfd_ref
, member_vnf_index
, desc
["uuid"]))
673 db_nsr_update
["_admin.deployed.RO.vnfd.{}".format(index
)] = RO_update
674 db_nsr
["_admin"]["deployed"]["RO"]["vnfd"][index
] = RO_update
675 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
676 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
680 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Creating nsd={} at RO".format(nsd_ref
)
681 # self.logger.debug(logging_text + step)
683 RO_osm_nsd_id
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, nsd_ref
[:23])
684 RO_descriptor_number
+= 1
685 nsd_list
= await self
.RO
.get_list("nsd", filter_by
={"osm_id": RO_osm_nsd_id
})
687 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= nsd_list
[0]["uuid"]
688 self
.logger
.debug(logging_text
+ "nsd={} exists at RO. Using RO_id={}".format(
689 nsd_ref
, RO_nsd_uuid
))
691 nsd_RO
= deepcopy(nsd
)
692 nsd_RO
["id"] = RO_osm_nsd_id
693 nsd_RO
.pop("_id", None)
694 nsd_RO
.pop("_admin", None)
695 for c_vnf
in nsd_RO
.get("constituent-vnfd", ()):
696 member_vnf_index
= c_vnf
["member-vnf-index"]
697 c_vnf
["vnfd-id-ref"] = vnf_index_2_RO_id
[member_vnf_index
]
698 for c_vld
in nsd_RO
.get("vld", ()):
699 for cp
in c_vld
.get("vnfd-connection-point-ref", ()):
700 member_vnf_index
= cp
["member-vnf-index-ref"]
701 cp
["vnfd-id-ref"] = vnf_index_2_RO_id
[member_vnf_index
]
703 desc
= await self
.RO
.create("nsd", descriptor
=nsd_RO
)
704 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
705 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= desc
["uuid"]
706 self
.logger
.debug(logging_text
+ "nsd={} created at RO. RO_id={}".format(nsd_ref
, RO_nsd_uuid
))
707 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
708 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
711 # if present use it unless in error status
712 RO_nsr_id
= deep_get(db_nsr
, ("_admin", "deployed", "RO", "nsr_id"))
715 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Looking for existing ns at RO"
716 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
717 desc
= await self
.RO
.show("ns", RO_nsr_id
)
718 except ROclient
.ROClientException
as e
:
719 if e
.http_code
!= HTTPStatus
.NOT_FOUND
:
721 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
723 ns_status
, ns_status_info
= self
.RO
.check_ns_status(desc
)
724 db_nsr_update
["_admin.deployed.RO.nsr_status"] = ns_status
725 if ns_status
== "ERROR":
726 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Deleting ns at RO. RO_ns_id={}"\
728 self
.logger
.debug(logging_text
+ step
)
729 await self
.RO
.delete("ns", RO_nsr_id
)
730 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
732 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Checking dependencies"
733 # self.logger.debug(logging_text + step)
735 # check if VIM is creating and wait look if previous tasks in process
736 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account", ns_params
["vimAccountId"])
738 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
739 self
.logger
.debug(logging_text
+ step
)
740 await asyncio
.wait(task_dependency
, timeout
=3600)
741 if ns_params
.get("vnf"):
742 for vnf
in ns_params
["vnf"]:
743 if "vimAccountId" in vnf
:
744 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account",
747 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
748 self
.logger
.debug(logging_text
+ step
)
749 await asyncio
.wait(task_dependency
, timeout
=3600)
751 step
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Checking instantiation parameters"
753 RO_ns_params
= self
.ns_params_2_RO(ns_params
, nsd
, db_vnfds_ref
, n2vc_key_list
)
755 step
= db_nsr_update
["detailed-status"] = "Deploying ns at VIM"
756 # step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Deploying ns at VIM"
757 desc
= await self
.RO
.create("ns", descriptor
=RO_ns_params
, name
=db_nsr
["name"], scenario
=RO_nsd_uuid
)
758 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = desc
["uuid"]
759 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
760 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "BUILD"
761 self
.logger
.debug(logging_text
+ "ns created at RO. RO_id={}".format(desc
["uuid"]))
762 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
763 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
765 # wait until NS is ready
766 step
= ns_status_detailed
= detailed_status
= "Waiting VIM to deploy ns. RO_ns_id={}".format(RO_nsr_id
)
767 detailed_status_old
= None
768 self
.logger
.debug(logging_text
+ step
)
770 while time() <= start_deploy
+ self
.total_deploy_timeout
:
771 desc
= await self
.RO
.show("ns", RO_nsr_id
)
772 ns_status
, ns_status_info
= self
.RO
.check_ns_status(desc
)
773 db_nsr_update
["_admin.deployed.RO.nsr_status"] = ns_status
774 if ns_status
== "ERROR":
775 raise ROclient
.ROClientException(ns_status_info
)
776 elif ns_status
== "BUILD":
777 detailed_status
= ns_status_detailed
+ "; {}".format(ns_status_info
)
778 elif ns_status
== "ACTIVE":
779 step
= detailed_status
= "Waiting for management IP address reported by the VIM. Updating VNFRs"
782 self
.ns_update_vnfr(db_vnfrs
, desc
)
784 except LcmExceptionNoMgmtIP
:
787 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
788 if detailed_status
!= detailed_status_old
:
789 detailed_status_old
= db_nsr_update
["_admin.deployed.RO.detailed-status"] = detailed_status
790 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
791 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
792 await asyncio
.sleep(5, loop
=self
.loop
)
793 else: # total_deploy_timeout
794 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
796 step
= "Updating NSR"
797 self
.ns_update_nsr(db_nsr_update
, db_nsr
, desc
)
799 db_nsr_update
["_admin.deployed.RO.operational-status"] = "running"
800 db_nsr
["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
801 db_nsr_update
["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
802 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
803 self
._on
_update
_n
2vc
_db
("nsrs", {"_id": nsr_id
}, "_admin.deployed", db_nsr_update
)
805 step
= "Deployed at VIM"
806 self
.logger
.debug(logging_text
+ step
)
808 # wait for ip addres at RO, and optionally, insert public key in virtual machine
810 async def insert_key_ro(self
, logging_text
, nsr_id
, vnfr_id
, vdu_id
, vdu_index
, pub_key
=None, user
=None):
812 self
.logger
.debug(logging_text
+ "Starting insert_key_ro")
821 await asyncio
.sleep(10, loop
=self
.loop
)
822 # wait until NS is deployed at RO
824 db_nsrs
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
825 ro_nsr_id
= deep_get(db_nsrs
, ("_admin", "deployed", "RO", "nsr_id"))
830 if not target_vdu_id
:
831 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnfr_id
})
833 ip_address
= db_vnfr
.get("ip-address")
836 for vdur
in get_iterable(db_vnfr
, "vdur"):
837 if (vdur
["vdu-id-ref"] == vdu_id
and vdur
["count-index"] == vdu_index
) or \
838 (ip_address
and vdur
.get("ip-address") == ip_address
):
839 if vdur
["status"] == "ACTIVE":
840 target_vdu_id
= vdur
["vdu-id-ref"]
841 elif vdur
["status"] == "ERROR":
842 raise LcmException("Cannot inject ssh-key because target VM is in error state")
845 raise LcmException("Not found vnfr_id={}, vdu_index={}, vdu_index={}".format(
846 vnfr_id
, vdu_id
, vdu_index
849 if not target_vdu_id
:
852 self
.logger
.debug(logging_text
+ "IP address={}".format(ip_address
))
854 # inject public key into machine
856 self
.logger
.debug(logging_text
+ "Inserting RO key")
858 ro_vm_id
= "{}-{}".format(db_vnfr
["member-vnf-index-ref"], target_vdu_id
) # TODO add vdu_index
859 result_dict
= await self
.RO
.create_action(
861 item_id_name
=ro_nsr_id
,
862 descriptor
={"add_public_key": pub_key
, "vms": [ro_vm_id
], "user": user
}
864 # result_dict contains the format {VM-id: {vim_result: 200, description: text}}
865 if not result_dict
or not isinstance(result_dict
, dict):
866 raise LcmException("Unknown response from RO when injecting key")
867 for result
in result_dict
.values():
868 if result
.get("vim_result") == 200:
871 raise ROclient
.ROClientException("error injecting key: {}".format(
872 result
.get("description")))
874 except ROclient
.ROClientException
as e
:
877 raise LcmException("Reaching max tries injecting key. Error: {}".format(e
))
878 self
.logger
.debug(logging_text
+ "error injecting key: {}".format(e
))
884 async def instantiate_N2VC(self
, logging_text
, vca_index
, nsi_id
, db_nsr
, db_vnfr
, vdu_id
,
885 kdu_name
, vdu_index
, config_descriptor
, deploy_params
, base_folder
):
886 nsr_id
= db_nsr
["_id"]
887 db_update_entry
= "_admin.deployed.VCA.{}.".format(vca_index
)
888 vca_deployed
= db_nsr
["_admin"]["deployed"]["VCA"][vca_index
]
890 'collection': 'nsrs',
891 'filter': {'_id': nsr_id
},
892 'path': db_update_entry
896 logging_text
+= "member_vnf_index={} vdu_id={}, vdu_index={} "\
897 .format(db_vnfr
["member-vnf-index-ref"], vdu_id
, vdu_index
)
903 vnfr_id
= db_vnfr
["_id"]
905 namespace
= "{nsi}.{ns}".format(
906 nsi
=nsi_id
if nsi_id
else "",
909 namespace
+= "." + vnfr_id
911 namespace
+= ".{}-{}".format(vdu_id
, vdu_index
or 0)
914 artifact_path
= "/{}/{}/charms/{}".format(
915 base_folder
["folder"],
916 base_folder
["pkg-dir"],
917 config_descriptor
["juju"]["charm"]
920 is_proxy_charm
= deep_get(config_descriptor
, ('juju', 'charm')) is not None
921 if deep_get(config_descriptor
, ('juju', 'proxy')) is False:
922 is_proxy_charm
= False
924 # n2vc_redesign STEP 3.1
926 # find old ee_id if exists
927 ee_id
= vca_deployed
.get("ee_id")
929 # create or register execution environment in VCA
931 step
= "create execution environment"
932 self
.logger
.debug(logging_text
+ step
)
933 ee_id
, credentials
= await self
.n2vc
.create_execution_environment(
940 step
= "register execution envioronment"
941 # TODO wait until deployed by RO, when IP address has been filled. By pooling????
942 credentials
= {} # TODO db_credentials["ip_address"]
944 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
945 # merged. Meanwhile let's get username from initial-config-primitive
946 if config_descriptor
.get("initial-config-primitive"):
947 for param
in config_descriptor
["initial-config-primitive"][0].get("parameter", ()):
948 if param
["name"] == "ssh-username":
949 credentials
["username"] = param
["value"]
950 if config_descriptor
.get("config-access") and config_descriptor
["config-access"].get("ssh-access"):
951 if config_descriptor
["config-access"]["ssh-access"].get("required"):
952 credentials
["username"] = \
953 config_descriptor
["config-access"]["ssh-access"].get("default-user")
955 # n2vc_redesign STEP 3.2
956 self
.logger
.debug(logging_text
+ step
)
957 ee_id
= await self
.n2vc
.register_execution_environment(
958 credentials
=credentials
,
963 # for compatibility with MON/POL modules, the need model and application name at database
964 # TODO ask to N2VC instead of assuming the format "model_name.application_name"
965 ee_id_parts
= ee_id
.split('.')
966 model_name
= ee_id_parts
[0]
967 application_name
= ee_id_parts
[1]
968 self
.update_db_2("nsrs", nsr_id
, {db_update_entry
+ "model": model_name
,
969 db_update_entry
+ "application": application_name
,
970 db_update_entry
+ "ee_id": ee_id
})
972 # n2vc_redesign STEP 3.3
973 # TODO check if already done
974 step
= "Install configuration Software"
975 self
.logger
.debug(logging_text
+ step
)
976 await self
.n2vc
.install_configuration_sw(
978 artifact_path
=artifact_path
,
982 # if SSH access is required, then get execution environment SSH public
983 required
= deep_get(config_descriptor
, ("config-access", "ssh-access", "required"))
984 if is_proxy_charm
and required
:
987 pub_key
= await self
.n2vc
.get_ee_ssh_public__key(
992 user
= deep_get(config_descriptor
, ("config-access", "ssh-access", "default-user"))
993 # insert pub_key into VM
994 # n2vc_redesign STEP 5.1
995 step
= "Insert public key into VM"
996 self
.logger
.debug(logging_text
+ step
)
998 # wait for RO (ip-address)
999 rw_mgmt_ip
= await self
.insert_key_ro(
1000 logging_text
=logging_text
,
1004 vdu_index
=vdu_index
,
1009 # store rw_mgmt_ip in deploy params for later substitution
1010 self
.logger
.debug('rw_mgmt_ip={}'.format(rw_mgmt_ip
))
1011 deploy_params
["rw_mgmt_ip"] = rw_mgmt_ip
1013 # n2vc_redesign STEP 6 Execute initial config primitive
1014 initial_config_primitive_list
= config_descriptor
.get('initial-config-primitive', [])
1015 step
= 'execute initial config primitive'
1017 # sort initial config primitives by 'seq'
1019 initial_config_primitive_list
.sort(key
=lambda val
: int(val
['seq']))
1021 self
.logger
.warn(logging_text
+ 'Cannot sort by "seq" field' + step
)
1023 for initial_config_primitive
in initial_config_primitive_list
:
1024 # TODO check if already done
1025 primitive_params_
= self
._map
_primitive
_params
(initial_config_primitive
, {}, deploy_params
)
1026 step
= "execute primitive '{}' params '{}'".format(initial_config_primitive
["name"], primitive_params_
)
1027 self
.logger
.debug(logging_text
+ step
)
1028 await self
.n2vc
.exec_primitive(
1030 primitive_name
=initial_config_primitive
["name"],
1031 params_dict
=primitive_params_
,
1034 # TODO register in database that primitive is done
1036 step
= "instantiated at VCA"
1037 self
.logger
.debug(logging_text
+ step
)
1039 except Exception as e
: # TODO not use Exception but N2VC exception
1040 raise Exception("{} {}".format(step
, e
)) from e
1041 # TODO raise N2VC exception with 'step' extra information
1043 async def instantiate(self
, nsr_id
, nslcmop_id
):
1046 :param nsr_id: ns instance to deploy
1047 :param nslcmop_id: operation to run
1051 # Try to lock HA task here
1052 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
1053 if not task_is_locked_by_me
:
1054 self
.logger
.debug('instantiate() task is not locked by me')
1057 logging_text
= "Task ns={} instantiate={} ".format(nsr_id
, nslcmop_id
)
1058 self
.logger
.debug(logging_text
+ "Enter")
1060 # get all needed from database
1062 # database nsrs record
1065 # database nslcmops record
1068 # update operation on nsrs
1069 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
1070 "_admin.current-operation": nslcmop_id
,
1071 "_admin.operation-type": "instantiate"}
1072 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1074 # update operation on nslcmops
1075 db_nslcmop_update
= {}
1077 nslcmop_operation_state
= None
1078 db_vnfrs
= {} # vnf's info indexed by member-index
1080 # n2vc_key_list = [] # list of public keys to be injected as authorized to VMs
1081 task_instantiation_list
= []
1084 # wait for any previous tasks in process
1085 step
= "Waiting for previous tasks"
1086 self
.logger
.debug(logging_text
+ step
)
1087 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
1089 # STEP 0: Reading database (nslcmops, nsrs, nsds, vnfrs, vnfds)
1091 # read from db: operation
1092 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
1093 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1096 step
= "Getting nsr={} from db".format(nsr_id
)
1097 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1098 # nsd is replicated into ns (no db read)
1100 # nsr_name = db_nsr["name"] # TODO short-name??
1102 # read from db: vnf's of this ns
1103 step
= "Getting vnfrs from db"
1104 self
.logger
.debug(logging_text
+ step
)
1105 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1107 # read from db: vnfd's for every vnf
1108 db_vnfds_ref
= {} # every vnfd data indexed by vnf name
1109 db_vnfds
= {} # every vnfd data indexed by vnf id
1110 db_vnfds_index
= {} # every vnfd data indexed by vnf member-index
1112 # for each vnf in ns, read vnfd
1113 for vnfr
in db_vnfrs_list
:
1114 db_vnfrs
[vnfr
["member-vnf-index-ref"]] = vnfr
# vnf's dict indexed by member-index: '1', '2', etc
1115 vnfd_id
= vnfr
["vnfd-id"] # vnfd uuid for this vnf
1116 vnfd_ref
= vnfr
["vnfd-ref"] # vnfd name for this vnf
1117 # if we haven't this vnfd, read it from db
1118 if vnfd_id
not in db_vnfds
:
1120 step
= "Getting vnfd={} id='{}' from db".format(vnfd_id
, vnfd_ref
)
1121 self
.logger
.debug(logging_text
+ step
)
1122 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
1125 db_vnfds_ref
[vnfd_ref
] = vnfd
# vnfd's indexed by name
1126 db_vnfds
[vnfd_id
] = vnfd
# vnfd's indexed by id
1127 db_vnfds_index
[vnfr
["member-vnf-index-ref"]] = db_vnfds
[vnfd_id
] # vnfd's indexed by member-index
1129 # Get or generates the _admin.deployed.VCA list
1130 vca_deployed_list
= None
1131 if db_nsr
["_admin"].get("deployed"):
1132 vca_deployed_list
= db_nsr
["_admin"]["deployed"].get("VCA")
1133 if vca_deployed_list
is None:
1134 vca_deployed_list
= []
1135 db_nsr_update
["_admin.deployed.VCA"] = vca_deployed_list
1136 # add _admin.deployed.VCA to db_nsr dictionary, value=vca_deployed_list
1137 populate_dict(db_nsr
, ("_admin", "deployed", "VCA"), vca_deployed_list
)
1138 elif isinstance(vca_deployed_list
, dict):
1139 # maintain backward compatibility. Change a dict to list at database
1140 vca_deployed_list
= list(vca_deployed_list
.values())
1141 db_nsr_update
["_admin.deployed.VCA"] = vca_deployed_list
1142 populate_dict(db_nsr
, ("_admin", "deployed", "VCA"), vca_deployed_list
)
1144 db_nsr_update
["detailed-status"] = "creating"
1145 db_nsr_update
["operational-status"] = "init"
1147 if not isinstance(deep_get(db_nsr
, ("_admin", "deployed", "RO", "vnfd")), list):
1148 populate_dict(db_nsr
, ("_admin", "deployed", "RO", "vnfd"), [])
1149 db_nsr_update
["_admin.deployed.RO.vnfd"] = []
1151 # set state to INSTANTIATED. When instantiated NBI will not delete directly
1152 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1153 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1154 self
.logger
.debug(logging_text
+ "Before deploy_kdus")
1155 db_k8scluster_list
= self
.db
.get_list("k8sclusters", {})
1156 # Call to deploy_kdus in case exists the "vdu:kdu" param
1157 task_kdu
= asyncio
.ensure_future(
1159 logging_text
=logging_text
,
1163 db_nslcmop
=db_nslcmop
,
1165 db_vnfds_ref
=db_vnfds_ref
,
1166 db_k8scluster
=db_k8scluster_list
1169 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_KDUs", task_kdu
)
1170 task_instantiation_list
.append(task_kdu
)
1171 # n2vc_redesign STEP 1 Get VCA public ssh-key
1172 # feature 1429. Add n2vc public key to needed VMs
1173 n2vc_key
= await self
.n2vc
.get_public_key()
1175 # n2vc_redesign STEP 2 Deploy Network Scenario
1176 task_ro
= asyncio
.ensure_future(
1177 self
.instantiate_RO(
1178 logging_text
=logging_text
,
1182 db_nslcmop
=db_nslcmop
,
1184 db_vnfds_ref
=db_vnfds_ref
,
1185 n2vc_key_list
=[n2vc_key
]
1188 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_RO", task_ro
)
1189 task_instantiation_list
.append(task_ro
)
1191 # n2vc_redesign STEP 3 to 6 Deploy N2VC
1192 step
= "Looking for needed vnfd to configure with proxy charm"
1193 self
.logger
.debug(logging_text
+ step
)
1195 nsi_id
= None # TODO put nsi_id when this nsr belongs to a NSI
1196 # get_iterable() returns a value from a dict or empty tuple if key does not exist
1197 for c_vnf
in get_iterable(nsd
, "constituent-vnfd"):
1198 vnfd_id
= c_vnf
["vnfd-id-ref"]
1199 vnfd
= db_vnfds_ref
[vnfd_id
]
1200 member_vnf_index
= str(c_vnf
["member-vnf-index"])
1201 db_vnfr
= db_vnfrs
[member_vnf_index
]
1202 base_folder
= vnfd
["_admin"]["storage"]
1208 # Get additional parameters
1210 if db_vnfr
.get("additionalParamsForVnf"):
1211 deploy_params
= db_vnfr
["additionalParamsForVnf"].copy()
1212 for k
, v
in deploy_params
.items():
1213 if isinstance(v
, str) and v
.startswith("!!yaml "):
1214 deploy_params
[k
] = yaml
.safe_load(v
[7:])
1216 descriptor_config
= vnfd
.get("vnf-configuration")
1217 if descriptor_config
and descriptor_config
.get("juju"):
1219 logging_text
=logging_text
,
1222 nslcmop_id
=nslcmop_id
,
1228 member_vnf_index
=member_vnf_index
,
1229 vdu_index
=vdu_index
,
1231 deploy_params
=deploy_params
,
1232 descriptor_config
=descriptor_config
,
1233 base_folder
=base_folder
,
1234 task_instantiation_list
=task_instantiation_list
1237 # Deploy charms for each VDU that supports one.
1238 for vdud
in get_iterable(vnfd
, 'vdu'):
1240 descriptor_config
= vdud
.get('vdu-configuration')
1241 if descriptor_config
and descriptor_config
.get("juju"):
1242 # look for vdu index in the db_vnfr["vdu"] section
1243 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
1244 # if vdur["vdu-id-ref"] == vdu_id:
1247 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
1248 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
1249 # vdu_name = vdur.get("name")
1252 for vdu_index
in range(int(vdud
.get("count", 1))):
1253 # TODO vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
1255 logging_text
=logging_text
,
1258 nslcmop_id
=nslcmop_id
,
1264 member_vnf_index
=member_vnf_index
,
1265 vdu_index
=vdu_index
,
1267 deploy_params
=deploy_params
,
1268 descriptor_config
=descriptor_config
,
1269 base_folder
=base_folder
,
1270 task_instantiation_list
=task_instantiation_list
1272 for kdud
in get_iterable(vnfd
, 'kdu'):
1273 kdu_name
= kdud
["name"]
1274 descriptor_config
= kdud
.get('kdu-configuration')
1275 if descriptor_config
and descriptor_config
.get("juju"):
1279 # look for vdu index in the db_vnfr["vdu"] section
1280 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
1281 # if vdur["vdu-id-ref"] == vdu_id:
1284 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
1285 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
1286 # vdu_name = vdur.get("name")
1290 logging_text
=logging_text
,
1293 nslcmop_id
=nslcmop_id
,
1299 member_vnf_index
=member_vnf_index
,
1300 vdu_index
=vdu_index
,
1302 deploy_params
=deploy_params
,
1303 descriptor_config
=descriptor_config
,
1304 base_folder
=base_folder
,
1305 task_instantiation_list
=task_instantiation_list
1308 # Check if this NS has a charm configuration
1309 descriptor_config
= nsd
.get("ns-configuration")
1310 if descriptor_config
and descriptor_config
.get("juju"):
1313 member_vnf_index
= None
1318 # Get additional parameters
1320 if db_nsr
.get("additionalParamsForNs"):
1321 deploy_params
= db_nsr
["additionalParamsForNs"].copy()
1322 for k
, v
in deploy_params
.items():
1323 if isinstance(v
, str) and v
.startswith("!!yaml "):
1324 deploy_params
[k
] = yaml
.safe_load(v
[7:])
1325 base_folder
= nsd
["_admin"]["storage"]
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
1345 # Wait until all tasks of "task_instantiation_list" have been finished
1347 # while time() <= start_deploy + self.total_deploy_timeout:
1349 timeout
= 3600 # time() - start_deploy
1350 task_instantiation_set
= set(task_instantiation_list
) # build a set with tasks
1353 if len(task_instantiation_set
) > 0:
1354 done
, pending
= await asyncio
.wait(task_instantiation_set
, timeout
=timeout
)
1356 error_text
= "timeout"
1358 if task
.cancelled():
1360 error_text
= "cancelled"
1362 exc
= task
.exception()
1364 error_text
= str(exc
)
1367 db_nsr_update
["config-status"] = "failed"
1368 error_text
= "fail configuring " + error_text
1369 db_nsr_update
["detailed-status"] = error_text
1370 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED_TEMP"
1371 db_nslcmop_update
["detailed-status"] = error_text
1372 db_nslcmop_update
["statusEnteredTime"] = time()
1375 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
1376 db_nslcmop_update
["statusEnteredTime"] = time()
1377 db_nslcmop_update
["detailed-status"] = "done"
1378 db_nsr_update
["config-status"] = "configured"
1379 db_nsr_update
["detailed-status"] = "done"
1381 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
1382 self
.logger
.error(logging_text
+ "Exit Exception while '{}': {}".format(step
, e
))
1384 except asyncio
.CancelledError
:
1385 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1386 exc
= "Operation was cancelled"
1387 except Exception as e
:
1388 exc
= traceback
.format_exc()
1389 self
.logger
.critical(logging_text
+ "Exit Exception {} while '{}': {}".format(type(e
).__name
__, step
, e
),
1394 db_nsr_update
["detailed-status"] = "ERROR {}: {}".format(step
, exc
)
1395 db_nsr_update
["operational-status"] = "failed"
1397 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
1398 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
1399 db_nslcmop_update
["statusEnteredTime"] = time()
1402 db_nsr_update
["_admin.nslcmop"] = None
1403 db_nsr_update
["_admin.current-operation"] = None
1404 db_nsr_update
["_admin.operation-type"] = None
1405 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1406 if db_nslcmop_update
:
1407 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1408 except DbException
as e
:
1409 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
1410 if nslcmop_operation_state
:
1412 await self
.msg
.aiowrite("ns", "instantiated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
1413 "operationState": nslcmop_operation_state
},
1415 except Exception as e
:
1416 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1418 self
.logger
.debug(logging_text
+ "Exit")
1419 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_instantiate")
1421 async def deploy_kdus(self
, logging_text
, nsr_id
, nsd
, db_nsr
, db_nslcmop
, db_vnfrs
, db_vnfds_ref
, db_k8scluster
):
1422 # Launch kdus if present in the descriptor
1423 logging_text
= "Deploy kdus: "
1425 db_nsr_update
["_admin.deployed.K8s"] = []
1427 # Look for all vnfds
1428 # db_nsr_update["_admin.deployed.K8s"] = []
1431 for c_vnf
in nsd
.get("constituent-vnfd", ()):
1432 vnfr
= db_vnfrs
[c_vnf
["member-vnf-index"]]
1433 member_vnf_index
= c_vnf
["member-vnf-index"]
1434 vnfd
= db_vnfds_ref
[c_vnf
['vnfd-id-ref']]
1435 vnfd_ref
= vnfd
["id"]
1438 step
= "Checking kdu from vnf: {} - member-vnf-index: {}".format(vnfd_ref
, member_vnf_index
)
1439 self
.logger
.debug(logging_text
+ step
)
1441 step
= "vnf: {} has kdus".format(vnfd_ref
)
1442 self
.logger
.debug(logging_text
+ step
)
1443 for vnfr_name
, vnfr_data
in db_vnfrs
.items():
1444 if vnfr_data
["vnfd-ref"] == vnfd
["id"]:
1445 if vnfr_data
.get("additionalParamsForVnf"):
1446 desc_params
= self
._format
_additional
_params
(vnfr_data
["additionalParamsForVnf"])
1449 raise LcmException("VNF descriptor not found with id: {}".format(vnfr_data
["vnfd-ref"]))
1450 self
.logger
.debug(logging_text
+ step
)
1452 for kdur
in vnfr
.get("kdur"):
1454 for k8scluster
in db_k8scluster
:
1455 if kdur
["k8s-cluster"]["id"] == k8scluster
["_id"]:
1456 cluster_uuid
= k8scluster
["cluster-uuid"]
1459 raise LcmException("K8scluster not found with id: {}".format(kdur
["k8s-cluster"]["id"]))
1460 self
.logger
.debug(logging_text
+ step
)
1462 step
= "Instantiate KDU {} in k8s cluster {}".format(kdur
["kdu-name"], cluster_uuid
)
1463 self
.logger
.debug(logging_text
+ step
)
1464 for kdu
in vnfd
.get("kdu"):
1465 if kdu
.get("name") == kdur
["kdu-name"]:
1468 raise LcmException("KDU not found with name: {} in VNFD {}".format(kdur
["kdu-name"],
1470 self
.logger
.debug(logging_text
+ step
)
1472 k8sclustertype
= None
1473 if kdu
.get("helm-chart"):
1474 kdumodel
= kdu
["helm-chart"]
1475 k8sclustertype
= "chart"
1476 elif kdu
.get("juju-bundle"):
1477 kdumodel
= kdu
["juju-bundle"]
1478 k8sclustertype
= "juju"
1479 k8s_instace_info
= {"kdu-instance": None, "k8scluster-uuid": cluster_uuid
,
1480 "vnfr-id": vnfr
["id"], "k8scluster-type": k8sclustertype
,
1481 "kdu-name": kdur
["kdu-name"], "kdu-model": kdumodel
}
1482 db_nsr_update
["_admin.deployed.K8s"].append(k8s_instace_info
)
1483 db_dict
= {"collection": "nsrs", "filter": {"_id": nsr_id
}, "path": "_admin.deployed.K8s."
1485 if k8sclustertype
== "chart":
1486 task
= self
.k8sclusterhelm
.install(cluster_uuid
=cluster_uuid
,
1487 kdu_model
=kdumodel
, atomic
=True, params
=desc_params
,
1488 db_dict
=db_dict
, timeout
=300)
1490 # TODO I need the juju connector in place
1492 task_list
.append(task
)
1494 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1497 if len(task_list
) > 0:
1498 self
.logger
.debug('Waiting for terminate pending tasks...')
1499 done
, pending
= await asyncio
.wait(task_list
, timeout
=3600)
1502 k8s_instance
= fut
.result()
1503 k8s_instace_info
= {"kdu-instance": k8s_instance
, "k8scluster-uuid": cluster_uuid
,
1504 "vnfr-id": vnfr
["id"], "k8scluster-type": k8sclustertype
,
1505 "kdu-name": kdur
["kdu-name"], "kdu-model": kdumodel
}
1506 vnf_update
.append(k8s_instace_info
)
1507 self
.logger
.debug('All tasks finished...')
1509 self
.logger
.info('There are pending tasks: {}'.format(pending
))
1511 db_nsr_update
["_admin.deployed.K8s"] = vnf_update
1512 except Exception as e
:
1513 self
.logger
.critical(logging_text
+ "Exit Exception {} while '{}': {}".format(type(e
).__name
__, step
, e
))
1514 raise LcmException("{} Exit Exception {} while '{}': {}".format(logging_text
, type(e
).__name
__, step
, e
))
1516 # TODO Write in data base
1518 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1519 def _deploy_n2vc(self
, logging_text
, db_nsr
, db_vnfr
, nslcmop_id
, nsr_id
, nsi_id
, vnfd_id
, vdu_id
,
1520 kdu_name
, member_vnf_index
, vdu_index
, vdu_name
, deploy_params
, descriptor_config
,
1521 base_folder
, task_instantiation_list
):
1522 # launch instantiate_N2VC in a asyncio task and register task object
1523 # Look where information of this charm is at database <nsrs>._admin.deployed.VCA
1524 # if not found, create one entry and update database
1526 # fill db_nsr._admin.deployed.VCA.<index>
1528 for vca_index
, vca_deployed
in enumerate(db_nsr
["_admin"]["deployed"]["VCA"]):
1529 if not vca_deployed
:
1531 if vca_deployed
.get("member-vnf-index") == member_vnf_index
and \
1532 vca_deployed
.get("vdu_id") == vdu_id
and \
1533 vca_deployed
.get("kdu_name") == kdu_name
and \
1534 vca_deployed
.get("vdu_count_index", 0) == vdu_index
:
1537 # not found, create one.
1539 "member-vnf-index": member_vnf_index
,
1541 "kdu_name": kdu_name
,
1542 "vdu_count_index": vdu_index
,
1543 "operational-status": "init", # TODO revise
1544 "detailed-status": "", # TODO revise
1545 "step": "initial-deploy", # TODO revise
1547 "vdu_name": vdu_name
,
1550 self
.update_db_2("nsrs", nsr_id
, {"_admin.deployed.VCA.{}".format(vca_index
): vca_deployed
})
1551 db_nsr
["_admin"]["deployed"]["VCA"].append(vca_deployed
)
1554 task_n2vc
= asyncio
.ensure_future(
1555 self
.instantiate_N2VC(
1556 logging_text
=logging_text
,
1557 vca_index
=vca_index
,
1563 vdu_index
=vdu_index
,
1564 deploy_params
=deploy_params
,
1565 config_descriptor
=descriptor_config
,
1566 base_folder
=base_folder
,
1569 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_N2VC-{}".format(vca_index
), task_n2vc
)
1570 task_instantiation_list
.append(task_n2vc
)
1572 # Check if this VNFD has a configured terminate action
1573 def _has_terminate_config_primitive(self
, vnfd
):
1574 vnf_config
= vnfd
.get("vnf-configuration")
1575 if vnf_config
and vnf_config
.get("terminate-config-primitive"):
1581 def _get_terminate_config_primitive_seq_list(vnfd
):
1582 """ Get a numerically sorted list of the sequences for this VNFD's terminate action """
1583 # No need to check for existing primitive twice, already done before
1584 vnf_config
= vnfd
.get("vnf-configuration")
1585 seq_list
= vnf_config
.get("terminate-config-primitive")
1586 # Get all 'seq' tags in seq_list, order sequences numerically, ascending.
1587 seq_list_sorted
= sorted(seq_list
, key
=lambda x
: int(x
['seq']))
1588 return seq_list_sorted
1591 def _create_nslcmop(nsr_id
, operation
, params
):
1593 Creates a ns-lcm-opp content to be stored at database.
1594 :param nsr_id: internal id of the instance
1595 :param operation: instantiate, terminate, scale, action, ...
1596 :param params: user parameters for the operation
1597 :return: dictionary following SOL005 format
1599 # Raise exception if invalid arguments
1600 if not (nsr_id
and operation
and params
):
1602 "Parameters 'nsr_id', 'operation' and 'params' needed to create primitive not provided")
1608 # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1609 "operationState": "PROCESSING",
1610 "statusEnteredTime": now
,
1611 "nsInstanceId": nsr_id
,
1612 "lcmOperationType": operation
,
1614 "isAutomaticInvocation": False,
1615 "operationParams": params
,
1616 "isCancelPending": False,
1618 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
1619 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
1624 def _format_additional_params(self
, params
):
1626 for key
, value
in params
.items():
1627 if str(value
).startswith("!!yaml "):
1628 params
[key
] = yaml
.safe_load(value
[7:])
1632 def _get_terminate_primitive_params(self
, seq
, vnf_index
):
1633 primitive
= seq
.get('name')
1634 primitive_params
= {}
1636 "member_vnf_index": vnf_index
,
1637 "primitive": primitive
,
1638 "primitive_params": primitive_params
,
1641 return self
._map
_primitive
_params
(seq
, params
, desc_params
)
1645 def _reintent_or_skip_suboperation(self
, db_nslcmop
, op_index
):
1646 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
1647 if (op
.get('operationState') == 'COMPLETED'):
1648 # b. Skip sub-operation
1649 # _ns_execute_primitive() or RO.create_action() will NOT be executed
1650 return self
.SUBOPERATION_STATUS_SKIP
1652 # c. Reintent executing sub-operation
1653 # The sub-operation exists, and operationState != 'COMPLETED'
1654 # Update operationState = 'PROCESSING' to indicate a reintent.
1655 operationState
= 'PROCESSING'
1656 detailed_status
= 'In progress'
1657 self
._update
_suboperation
_status
(
1658 db_nslcmop
, op_index
, operationState
, detailed_status
)
1659 # Return the sub-operation index
1660 # _ns_execute_primitive() or RO.create_action() will be called from scale()
1661 # with arguments extracted from the sub-operation
1664 # Find a sub-operation where all keys in a matching dictionary must match
1665 # Returns the index of the matching sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if no match
1666 def _find_suboperation(self
, db_nslcmop
, match
):
1667 if (db_nslcmop
and match
):
1668 op_list
= db_nslcmop
.get('_admin', {}).get('operations', [])
1669 for i
, op
in enumerate(op_list
):
1670 if all(op
.get(k
) == match
[k
] for k
in match
):
1672 return self
.SUBOPERATION_STATUS_NOT_FOUND
1674 # Update status for a sub-operation given its index
1675 def _update_suboperation_status(self
, db_nslcmop
, op_index
, operationState
, detailed_status
):
1676 # Update DB for HA tasks
1677 q_filter
= {'_id': db_nslcmop
['_id']}
1678 update_dict
= {'_admin.operations.{}.operationState'.format(op_index
): operationState
,
1679 '_admin.operations.{}.detailed-status'.format(op_index
): detailed_status
}
1680 self
.db
.set_one("nslcmops",
1682 update_dict
=update_dict
,
1683 fail_on_empty
=False)
1685 # Add sub-operation, return the index of the added sub-operation
1686 # Optionally, set operationState, detailed-status, and operationType
1687 # Status and type are currently set for 'scale' sub-operations:
1688 # 'operationState' : 'PROCESSING' | 'COMPLETED' | 'FAILED'
1689 # 'detailed-status' : status message
1690 # 'operationType': may be any type, in the case of scaling: 'PRE-SCALE' | 'POST-SCALE'
1691 # Status and operation type are currently only used for 'scale', but NOT for 'terminate' sub-operations.
1692 def _add_suboperation(self
, db_nslcmop
, vnf_index
, vdu_id
, vdu_count_index
, vdu_name
, primitive
,
1693 mapped_primitive_params
, operationState
=None, detailed_status
=None, operationType
=None,
1694 RO_nsr_id
=None, RO_scaling_info
=None):
1695 if not (db_nslcmop
):
1696 return self
.SUBOPERATION_STATUS_NOT_FOUND
1697 # Get the "_admin.operations" list, if it exists
1698 db_nslcmop_admin
= db_nslcmop
.get('_admin', {})
1699 op_list
= db_nslcmop_admin
.get('operations')
1700 # Create or append to the "_admin.operations" list
1701 new_op
= {'member_vnf_index': vnf_index
,
1703 'vdu_count_index': vdu_count_index
,
1704 'primitive': primitive
,
1705 'primitive_params': mapped_primitive_params
}
1707 new_op
['operationState'] = operationState
1709 new_op
['detailed-status'] = detailed_status
1711 new_op
['lcmOperationType'] = operationType
1713 new_op
['RO_nsr_id'] = RO_nsr_id
1715 new_op
['RO_scaling_info'] = RO_scaling_info
1717 # No existing operations, create key 'operations' with current operation as first list element
1718 db_nslcmop_admin
.update({'operations': [new_op
]})
1719 op_list
= db_nslcmop_admin
.get('operations')
1721 # Existing operations, append operation to list
1722 op_list
.append(new_op
)
1724 db_nslcmop_update
= {'_admin.operations': op_list
}
1725 self
.update_db_2("nslcmops", db_nslcmop
['_id'], db_nslcmop_update
)
1726 op_index
= len(op_list
) - 1
1729 # Helper methods for scale() sub-operations
1731 # pre-scale/post-scale:
1732 # Check for 3 different cases:
1733 # a. New: First time execution, return SUBOPERATION_STATUS_NEW
1734 # b. Skip: Existing sub-operation exists, operationState == 'COMPLETED', return SUBOPERATION_STATUS_SKIP
1735 # c. Reintent: Existing sub-operation exists, operationState != 'COMPLETED', return op_index to re-execute
1736 def _check_or_add_scale_suboperation(self
, db_nslcmop
, vnf_index
, vnf_config_primitive
, primitive_params
,
1737 operationType
, RO_nsr_id
=None, RO_scaling_info
=None):
1738 # Find this sub-operation
1739 if (RO_nsr_id
and RO_scaling_info
):
1740 operationType
= 'SCALE-RO'
1742 'member_vnf_index': vnf_index
,
1743 'RO_nsr_id': RO_nsr_id
,
1744 'RO_scaling_info': RO_scaling_info
,
1748 'member_vnf_index': vnf_index
,
1749 'primitive': vnf_config_primitive
,
1750 'primitive_params': primitive_params
,
1751 'lcmOperationType': operationType
1753 op_index
= self
._find
_suboperation
(db_nslcmop
, match
)
1754 if (op_index
== self
.SUBOPERATION_STATUS_NOT_FOUND
):
1755 # a. New sub-operation
1756 # The sub-operation does not exist, add it.
1757 # _ns_execute_primitive() will be called from scale() as usual, with non-modified arguments
1758 # The following parameters are set to None for all kind of scaling:
1760 vdu_count_index
= None
1762 if (RO_nsr_id
and RO_scaling_info
):
1763 vnf_config_primitive
= None
1764 primitive_params
= None
1767 RO_scaling_info
= None
1768 # Initial status for sub-operation
1769 operationState
= 'PROCESSING'
1770 detailed_status
= 'In progress'
1771 # Add sub-operation for pre/post-scaling (zero or more operations)
1772 self
._add
_suboperation
(db_nslcmop
,
1777 vnf_config_primitive
,
1784 return self
.SUBOPERATION_STATUS_NEW
1786 # Return either SUBOPERATION_STATUS_SKIP (operationState == 'COMPLETED'),
1787 # or op_index (operationState != 'COMPLETED')
1788 return self
._reintent
_or
_skip
_suboperation
(db_nslcmop
, op_index
)
1790 # Helper methods for terminate()
1792 async def _terminate_action(self
, db_nslcmop
, nslcmop_id
, nsr_id
):
1793 """ Create a primitive with params from VNFD
1794 Called from terminate() before deleting instance
1795 Calls action() to execute the primitive """
1796 logging_text
= "Task ns={} _terminate_action={} ".format(nsr_id
, nslcmop_id
)
1797 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1800 for vnfr
in db_vnfrs_list
:
1801 vnfd_id
= vnfr
["vnfd-id"]
1802 vnf_index
= vnfr
["member-vnf-index-ref"]
1803 if vnfd_id
not in db_vnfds
:
1804 step
= "Getting vnfd={} id='{}' from db".format(vnfd_id
, vnfd_id
)
1805 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
1806 db_vnfds
[vnfd_id
] = vnfd
1807 vnfd
= db_vnfds
[vnfd_id
]
1808 if not self
._has
_terminate
_config
_primitive
(vnfd
):
1810 # Get the primitive's sorted sequence list
1811 seq_list
= self
._get
_terminate
_config
_primitive
_seq
_list
(vnfd
)
1812 for seq
in seq_list
:
1813 # For each sequence in list, get primitive and call _ns_execute_primitive()
1814 step
= "Calling terminate action for vnf_member_index={} primitive={}".format(
1815 vnf_index
, seq
.get("name"))
1816 self
.logger
.debug(logging_text
+ step
)
1817 # Create the primitive for each sequence, i.e. "primitive": "touch"
1818 primitive
= seq
.get('name')
1819 mapped_primitive_params
= self
._get
_terminate
_primitive
_params
(seq
, vnf_index
)
1820 # The following 3 parameters are currently set to None for 'terminate':
1821 # vdu_id, vdu_count_index, vdu_name
1822 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
1823 vdu_count_index
= db_nslcmop
["operationParams"].get("vdu_count_index")
1824 vdu_name
= db_nslcmop
["operationParams"].get("vdu_name")
1826 self
._add
_suboperation
(db_nslcmop
,
1833 mapped_primitive_params
)
1834 # Sub-operations: Call _ns_execute_primitive() instead of action()
1835 # db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1836 # nsr_deployed = db_nsr["_admin"]["deployed"]
1838 # nslcmop_operation_state, nslcmop_operation_state_detail = await self.action(
1839 # nsr_id, nslcmop_terminate_action_id)
1840 # Launch Exception if action() returns other than ['COMPLETED', 'PARTIALLY_COMPLETED']
1841 # result_ok = ['COMPLETED', 'PARTIALLY_COMPLETED']
1842 # if result not in result_ok:
1843 # raise LcmException(
1844 # "terminate_primitive_action for vnf_member_index={}",
1845 # " primitive={} fails with error {}".format(
1846 # vnf_index, seq.get("name"), result_detail))
1851 await self
.n2vc
.exec_primitive(
1853 primitive_name
=primitive
,
1854 params_dict
=mapped_primitive_params
1856 except Exception as e
:
1857 self
.logger
.error('Error executing primitive {}: {}'.format(primitive
, e
))
1859 "terminate_primitive_action for vnf_member_index={}, primitive={} fails with error {}"
1860 .format(vnf_index
, seq
.get("name"), e
),
1863 async def terminate(self
, nsr_id
, nslcmop_id
):
1865 # Try to lock HA task here
1866 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
1867 if not task_is_locked_by_me
:
1870 logging_text
= "Task ns={} terminate={} ".format(nsr_id
, nslcmop_id
)
1871 self
.logger
.debug(logging_text
+ "Enter")
1875 failed_detail
= [] # annotates all failed error messages
1876 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
1877 "_admin.current-operation": nslcmop_id
,
1878 "_admin.operation-type": "terminate"}
1879 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1880 db_nslcmop_update
= {}
1881 nslcmop_operation_state
= None
1882 autoremove
= False # autoremove after terminated
1885 # wait for any previous tasks in process
1886 await self
.lcm_tasks
.waitfor_related_HA("ns", 'nslcmops', nslcmop_id
)
1888 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
1889 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1890 step
= "Getting nsr={} from db".format(nsr_id
)
1891 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1892 # nsd = db_nsr["nsd"]
1893 nsr_deployed
= deepcopy(db_nsr
["_admin"].get("deployed"))
1894 if db_nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
1896 # #TODO check if VIM is creating and wait
1897 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
1898 # Call internal terminate action
1899 await self
._terminate
_action
(db_nslcmop
, nslcmop_id
, nsr_id
)
1903 db_nsr_update
["operational-status"] = "terminating"
1904 db_nsr_update
["config-status"] = "terminating"
1908 step
= "delete execution environment"
1909 self
.logger
.debug(logging_text
+ step
)
1911 task_delete_ee
= asyncio
.ensure_future(self
.n2vc
.delete_namespace(namespace
="." + nsr_id
))
1912 pending_tasks
.append(task_delete_ee
)
1913 except Exception as e
:
1914 msg
= "Failed while deleting NS in VCA: {}".format(e
)
1915 self
.logger
.error(msg
)
1916 failed_detail
.append(msg
)
1919 # Delete from k8scluster
1920 step
= "delete kdus"
1921 self
.logger
.debug(logging_text
+ step
)
1924 for kdu
in nsr_deployed
.get("K8s"):
1925 if kdu
.get("k8scluster-type") == "chart":
1926 task_delete_kdu_instance
= asyncio
.ensure_future(self
.k8sclusterhelm
.uninstall(
1927 cluster_uuid
=kdu
.get("k8scluster-uuid"), kdu_instance
=kdu
.get("kdu-instance")))
1928 elif kdu
.get("k8scluster-type") == "juju":
1929 # TODO Juju connector needed
1932 msg
= "k8scluster-type not defined"
1933 raise LcmException(msg
)
1935 pending_tasks
.append(task_delete_kdu_instance
)
1936 except LcmException
as e
:
1937 msg
= "Failed while deleting KDUs from NS: {}".format(e
)
1938 self
.logger
.error(msg
)
1939 failed_detail
.append(msg
)
1945 RO_nsr_id
= RO_delete_action
= None
1946 if nsr_deployed
and nsr_deployed
.get("RO"):
1947 RO_nsr_id
= nsr_deployed
["RO"].get("nsr_id")
1948 RO_delete_action
= nsr_deployed
["RO"].get("nsr_delete_action_id")
1951 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] = \
1952 "Deleting ns from VIM"
1953 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1954 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1955 self
.logger
.debug(logging_text
+ step
)
1956 desc
= await self
.RO
.delete("ns", RO_nsr_id
)
1957 RO_delete_action
= desc
["action_id"]
1958 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = RO_delete_action
1959 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1960 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
1961 if RO_delete_action
:
1962 # wait until NS is deleted from VIM
1963 step
= detailed_status
= "Waiting ns deleted from VIM. RO_id={} RO_delete_action={}".\
1964 format(RO_nsr_id
, RO_delete_action
)
1965 detailed_status_old
= None
1966 self
.logger
.debug(logging_text
+ step
)
1968 delete_timeout
= 20 * 60 # 20 minutes
1969 while delete_timeout
> 0:
1970 desc
= await self
.RO
.show(
1972 item_id_name
=RO_nsr_id
,
1973 extra_item
="action",
1974 extra_item_id
=RO_delete_action
)
1975 ns_status
, ns_status_info
= self
.RO
.check_action_status(desc
)
1976 if ns_status
== "ERROR":
1977 raise ROclient
.ROClientException(ns_status_info
)
1978 elif ns_status
== "BUILD":
1979 detailed_status
= step
+ "; {}".format(ns_status_info
)
1980 elif ns_status
== "ACTIVE":
1981 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
1982 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
1985 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
1986 if detailed_status
!= detailed_status_old
:
1987 detailed_status_old
= db_nslcmop_update
["detailed-status"] = \
1988 db_nsr_update
["detailed-status"] = detailed_status
1989 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1990 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1991 await asyncio
.sleep(5, loop
=self
.loop
)
1993 else: # delete_timeout <= 0:
1994 raise ROclient
.ROClientException("Timeout waiting ns deleted from VIM")
1996 except ROclient
.ROClientException
as e
:
1997 if e
.http_code
== 404: # not found
1998 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1999 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
2000 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
2001 self
.logger
.debug(logging_text
+ "RO_ns_id={} already deleted".format(RO_nsr_id
))
2002 elif e
.http_code
== 409: # conflict
2003 failed_detail
.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id
, e
))
2004 self
.logger
.debug(logging_text
+ failed_detail
[-1])
2007 failed_detail
.append("RO_ns_id={} delete error: {}".format(RO_nsr_id
, e
))
2008 self
.logger
.error(logging_text
+ failed_detail
[-1])
2012 if not RO_fail
and nsr_deployed
and nsr_deployed
.get("RO") and nsr_deployed
["RO"].get("nsd_id"):
2013 RO_nsd_id
= nsr_deployed
["RO"]["nsd_id"]
2015 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
2016 "Deleting nsd from RO"
2017 await self
.RO
.delete("nsd", RO_nsd_id
)
2018 self
.logger
.debug(logging_text
+ "RO_nsd_id={} deleted".format(RO_nsd_id
))
2019 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
2020 except ROclient
.ROClientException
as e
:
2021 if e
.http_code
== 404: # not found
2022 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
2023 self
.logger
.debug(logging_text
+ "RO_nsd_id={} already deleted".format(RO_nsd_id
))
2024 elif e
.http_code
== 409: # conflict
2025 failed_detail
.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id
, e
))
2026 self
.logger
.debug(logging_text
+ failed_detail
[-1])
2029 failed_detail
.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id
, e
))
2030 self
.logger
.error(logging_text
+ failed_detail
[-1])
2033 if not RO_fail
and nsr_deployed
and nsr_deployed
.get("RO") and nsr_deployed
["RO"].get("vnfd"):
2034 for index
, vnf_deployed
in enumerate(nsr_deployed
["RO"]["vnfd"]):
2035 if not vnf_deployed
or not vnf_deployed
["id"]:
2038 RO_vnfd_id
= vnf_deployed
["id"]
2039 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
2040 "Deleting member_vnf_index={} RO_vnfd_id={} from RO".format(
2041 vnf_deployed
["member-vnf-index"], RO_vnfd_id
)
2042 await self
.RO
.delete("vnfd", RO_vnfd_id
)
2043 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} deleted".format(RO_vnfd_id
))
2044 db_nsr_update
["_admin.deployed.RO.vnfd.{}.id".format(index
)] = None
2045 except ROclient
.ROClientException
as e
:
2046 if e
.http_code
== 404: # not found
2047 db_nsr_update
["_admin.deployed.RO.vnfd.{}.id".format(index
)] = None
2048 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} already deleted ".format(RO_vnfd_id
))
2049 elif e
.http_code
== 409: # conflict
2050 failed_detail
.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id
, e
))
2051 self
.logger
.debug(logging_text
+ failed_detail
[-1])
2053 failed_detail
.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id
, e
))
2054 self
.logger
.error(logging_text
+ failed_detail
[-1])
2057 self
.logger
.error(logging_text
+ " ;".join(failed_detail
))
2058 db_nsr_update
["operational-status"] = "failed"
2059 db_nsr_update
["detailed-status"] = "Deletion errors " + "; ".join(failed_detail
)
2060 db_nslcmop_update
["detailed-status"] = "; ".join(failed_detail
)
2061 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2062 db_nslcmop_update
["statusEnteredTime"] = time()
2064 db_nsr_update
["operational-status"] = "terminated"
2065 db_nsr_update
["detailed-status"] = "Done"
2066 db_nsr_update
["_admin.nsState"] = "NOT_INSTANTIATED"
2067 db_nslcmop_update
["detailed-status"] = "Done"
2068 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
2069 db_nslcmop_update
["statusEnteredTime"] = time()
2070 if db_nslcmop
["operationParams"].get("autoremove"):
2073 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
2074 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
2076 except asyncio
.CancelledError
:
2077 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
2078 exc
= "Operation was cancelled"
2079 except Exception as e
:
2080 exc
= traceback
.format_exc()
2081 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
2083 if exc
and db_nslcmop
:
2084 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
2085 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2086 db_nslcmop_update
["statusEnteredTime"] = time()
2088 if db_nslcmop
and db_nslcmop_update
:
2089 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2091 db_nsr_update
["_admin.nslcmop"] = None
2092 db_nsr_update
["_admin.current-operation"] = None
2093 db_nsr_update
["_admin.operation-type"] = None
2094 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2095 except DbException
as e
:
2096 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
2097 if nslcmop_operation_state
:
2099 await self
.msg
.aiowrite("ns", "terminated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2100 "operationState": nslcmop_operation_state
,
2101 "autoremove": autoremove
},
2103 except Exception as e
:
2104 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
2106 # wait for pending tasks
2110 self
.logger
.debug(logging_text
+ 'Waiting for terminate pending tasks...')
2111 done
, pending
= await asyncio
.wait(pending_tasks
, timeout
=3600)
2113 self
.logger
.debug(logging_text
+ 'All tasks finished...')
2115 self
.logger
.info(logging_text
+ 'There are pending tasks: {}'.format(pending
))
2117 self
.logger
.debug(logging_text
+ "Exit")
2118 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_terminate")
2121 def _map_primitive_params(primitive_desc
, params
, instantiation_params
):
2123 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
2124 The default-value is used. If it is between < > it look for a value at instantiation_params
2125 :param primitive_desc: portion of VNFD/NSD that describes primitive
2126 :param params: Params provided by user
2127 :param instantiation_params: Instantiation params provided by user
2128 :return: a dictionary with the calculated params
2130 calculated_params
= {}
2131 for parameter
in primitive_desc
.get("parameter", ()):
2132 param_name
= parameter
["name"]
2133 if param_name
in params
:
2134 calculated_params
[param_name
] = params
[param_name
]
2135 elif "default-value" in parameter
or "value" in parameter
:
2136 if "value" in parameter
:
2137 calculated_params
[param_name
] = parameter
["value"]
2139 calculated_params
[param_name
] = parameter
["default-value"]
2140 if isinstance(calculated_params
[param_name
], str) and calculated_params
[param_name
].startswith("<") \
2141 and calculated_params
[param_name
].endswith(">"):
2142 if calculated_params
[param_name
][1:-1] in instantiation_params
:
2143 calculated_params
[param_name
] = instantiation_params
[calculated_params
[param_name
][1:-1]]
2145 raise LcmException("Parameter {} needed to execute primitive {} not provided".
2146 format(calculated_params
[param_name
], primitive_desc
["name"]))
2148 raise LcmException("Parameter {} needed to execute primitive {} not provided".
2149 format(param_name
, primitive_desc
["name"]))
2151 if isinstance(calculated_params
[param_name
], (dict, list, tuple)):
2152 calculated_params
[param_name
] = yaml
.safe_dump(calculated_params
[param_name
], default_flow_style
=True,
2154 elif isinstance(calculated_params
[param_name
], str) and calculated_params
[param_name
].startswith("!!yaml "):
2155 calculated_params
[param_name
] = calculated_params
[param_name
][7:]
2156 return calculated_params
2158 async def _ns_execute_primitive(self
, db_deployed
, member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
,
2159 primitive
, primitive_params
, retries
=0, retries_interval
=30) -> (str, str):
2161 # find vca_deployed record for this action
2163 for vca_deployed
in db_deployed
["VCA"]:
2164 if not vca_deployed
:
2166 if member_vnf_index
!= vca_deployed
["member-vnf-index"] or vdu_id
!= vca_deployed
["vdu_id"]:
2168 if vdu_name
and vdu_name
!= vca_deployed
["vdu_name"]:
2170 if vdu_count_index
and vdu_count_index
!= vca_deployed
["vdu_count_index"]:
2174 # vca_deployed not found
2175 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} is not "
2176 "deployed".format(member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
))
2179 ee_id
= vca_deployed
.get("ee_id")
2181 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} has not "
2182 "execution environment"
2183 .format(member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
))
2185 if primitive
== "config":
2186 primitive_params
= {"params": primitive_params
}
2190 output
= await self
.n2vc
.exec_primitive(
2192 primitive_name
=primitive
,
2193 params_dict
=primitive_params
2197 except Exception as e
:
2200 self
.logger
.debug('Error executing action {} on {} -> {}'.format(primitive
, ee_id
, e
))
2202 await asyncio
.sleep(retries_interval
, loop
=self
.loop
)
2204 return 'Cannot execute action {} on {}: {}'.format(primitive
, ee_id
, e
), 'FAIL'
2208 except Exception as e
:
2209 return 'Error executing action {}: {}'.format(primitive
, e
), 'FAIL'
2211 async def action(self
, nsr_id
, nslcmop_id
):
2213 # Try to lock HA task here
2214 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
2215 if not task_is_locked_by_me
:
2218 logging_text
= "Task ns={} action={} ".format(nsr_id
, nslcmop_id
)
2219 self
.logger
.debug(logging_text
+ "Enter")
2220 # get all needed from database
2223 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
2224 "_admin.current-operation": nslcmop_id
,
2225 "_admin.operation-type": "action"}
2226 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2227 db_nslcmop_update
= {}
2228 nslcmop_operation_state
= None
2229 nslcmop_operation_state_detail
= None
2232 # wait for any previous tasks in process
2233 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
2235 step
= "Getting information from database"
2236 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
2237 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2239 nsr_deployed
= db_nsr
["_admin"].get("deployed")
2240 vnf_index
= db_nslcmop
["operationParams"].get("member_vnf_index")
2241 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
2242 kdu_name
= db_nslcmop
["operationParams"].get("kdu_name")
2243 vdu_count_index
= db_nslcmop
["operationParams"].get("vdu_count_index")
2244 vdu_name
= db_nslcmop
["operationParams"].get("vdu_name")
2247 step
= "Getting vnfr from database"
2248 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
2249 step
= "Getting vnfd from database"
2250 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
2252 if db_nsr
.get("nsd"):
2253 db_nsd
= db_nsr
.get("nsd") # TODO this will be removed
2255 step
= "Getting nsd from database"
2256 db_nsd
= self
.db
.get_one("nsds", {"_id": db_nsr
["nsd-id"]})
2258 # for backward compatibility
2259 if nsr_deployed
and isinstance(nsr_deployed
.get("VCA"), dict):
2260 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
2261 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
2262 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2264 primitive
= db_nslcmop
["operationParams"]["primitive"]
2265 primitive_params
= db_nslcmop
["operationParams"]["primitive_params"]
2267 # look for primitive
2268 config_primitive_desc
= None
2270 for vdu
in get_iterable(db_vnfd
, "vdu"):
2271 if vdu_id
== vdu
["id"]:
2272 for config_primitive
in vdu
.get("vdu-configuration", {}).get("config-primitive", ()):
2273 if config_primitive
["name"] == primitive
:
2274 config_primitive_desc
= config_primitive
2277 self
.logger
.debug(logging_text
+ "Checking actions in KDUs")
2280 if db_vnfr
.get("additionalParamsForVnf") and db_vnfr
["additionalParamsForVnf"].\
2281 get("member-vnf-index") == vnf_index
:
2282 desc_params
= self
._format
_additional
_params
(db_vnfr
["additionalParamsForVnf"].
2283 get("additionalParams"))
2284 if primitive_params
:
2285 desc_params
.update(primitive_params
)
2286 # TODO Check if we will need something at vnf level
2288 for kdu
in get_iterable(nsr_deployed
, "K8s"):
2289 if kdu_name
== kdu
["kdu-name"]:
2290 db_dict
= {"collection": "nsrs", "filter": {"_id": nsr_id
},
2291 "path": "_admin.deployed.K8s.{}".format(index
)}
2292 if primitive
== "upgrade":
2293 if desc_params
.get("kdu_model"):
2294 kdu_model
= desc_params
.get("kdu_model")
2295 del desc_params
["kdu_model"]
2297 kdu_model
= kdu
.get("kdu-model")
2298 parts
= kdu_model
.split(sep
=":")
2300 kdu_model
= parts
[0]
2302 if kdu
.get("k8scluster-type") == "chart":
2303 output
= await self
.k8sclusterhelm
.upgrade(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2304 kdu_instance
=kdu
.get("kdu-instance"),
2305 atomic
=True, kdu_model
=kdu_model
,
2306 params
=desc_params
, db_dict
=db_dict
, timeout
=300)
2307 elif kdu
.get("k8scluster-type") == "juju":
2308 # TODO Juju connector needed
2311 msg
= "k8scluster-type not defined"
2312 raise LcmException(msg
)
2314 self
.logger
.debug(logging_text
+ " Upgrade of kdu {} done".format(output
))
2316 elif primitive
== "rollback":
2317 if kdu
.get("k8scluster-type") == "chart":
2318 output
= await self
.k8sclusterhelm
.rollback(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2319 kdu_instance
=kdu
.get("kdu-instance"),
2321 elif kdu
.get("k8scluster-type") == "juju":
2322 # TODO Juju connector needed
2325 msg
= "k8scluster-type not defined"
2326 raise LcmException(msg
)
2328 elif primitive
== "status":
2329 if kdu
.get("k8scluster-type") == "chart":
2330 output
= await self
.k8sclusterhelm
.status_kdu(cluster_uuid
=kdu
.get("k8scluster-uuid"),
2331 kdu_instance
=kdu
.get("kdu-instance"))
2332 elif kdu
.get("k8scluster-type") == "juju":
2333 # TODO Juju connector needed
2336 msg
= "k8scluster-type not defined"
2337 raise LcmException(msg
)
2342 raise LcmException("KDU '{}' not found".format(kdu_name
))
2344 db_nslcmop_update
["detailed-status"] = output
2345 db_nslcmop_update
["operationState"] = 'COMPLETED'
2346 db_nslcmop_update
["statusEnteredTime"] = time()
2348 db_nslcmop_update
["detailed-status"] = ''
2349 db_nslcmop_update
["operationState"] = 'FAILED'
2350 db_nslcmop_update
["statusEnteredTime"] = time()
2353 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
2354 if config_primitive
["name"] == primitive
:
2355 config_primitive_desc
= config_primitive
2358 for config_primitive
in db_nsd
.get("ns-configuration", {}).get("config-primitive", ()):
2359 if config_primitive
["name"] == primitive
:
2360 config_primitive_desc
= config_primitive
2363 if not config_primitive_desc
:
2364 raise LcmException("Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".
2369 if db_vnfr
.get("additionalParamsForVnf"):
2370 desc_params
.update(db_vnfr
["additionalParamsForVnf"])
2372 if db_nsr
.get("additionalParamsForNs"):
2373 desc_params
.update(db_nsr
["additionalParamsForNs"])
2375 # TODO check if ns is in a proper status
2376 output
, detail
= await self
._ns
_execute
_primitive
(
2377 db_deployed
=nsr_deployed
,
2378 member_vnf_index
=vnf_index
,
2381 vdu_count_index
=vdu_count_index
,
2382 primitive
=primitive
,
2383 primitive_params
=self
._map
_primitive
_params
(config_primitive_desc
, primitive_params
, desc_params
))
2385 detailed_status
= output
2387 result
= 'COMPLETED'
2391 db_nslcmop_update
["detailed-status"] = nslcmop_operation_state_detail
= detailed_status
2392 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= result
2393 db_nslcmop_update
["statusEnteredTime"] = time()
2394 self
.logger
.debug(logging_text
+ " task Done with result {} {}".format(result
, detailed_status
))
2395 return # database update is called inside finally
2397 except (DbException
, LcmException
) as e
:
2398 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
2400 except asyncio
.CancelledError
:
2401 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
2402 exc
= "Operation was cancelled"
2403 except Exception as e
:
2404 exc
= traceback
.format_exc()
2405 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
2407 if exc
and db_nslcmop
:
2408 db_nslcmop_update
["detailed-status"] = nslcmop_operation_state_detail
= \
2409 "FAILED {}: {}".format(step
, exc
)
2410 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2411 db_nslcmop_update
["statusEnteredTime"] = time()
2413 if db_nslcmop_update
:
2414 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2416 db_nsr_update
["_admin.nslcmop"] = None
2417 db_nsr_update
["_admin.operation-type"] = None
2418 db_nsr_update
["_admin.nslcmop"] = None
2419 db_nsr_update
["_admin.current-operation"] = None
2420 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2421 except DbException
as e
:
2422 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
2423 self
.logger
.debug(logging_text
+ "Exit")
2424 if nslcmop_operation_state
:
2426 await self
.msg
.aiowrite("ns", "actioned", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2427 "operationState": nslcmop_operation_state
},
2429 except Exception as e
:
2430 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
2431 self
.logger
.debug(logging_text
+ "Exit")
2432 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_action")
2433 return nslcmop_operation_state
, nslcmop_operation_state_detail
2435 async def scale(self
, nsr_id
, nslcmop_id
):
2437 # Try to lock HA task here
2438 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
2439 if not task_is_locked_by_me
:
2442 logging_text
= "Task ns={} scale={} ".format(nsr_id
, nslcmop_id
)
2443 self
.logger
.debug(logging_text
+ "Enter")
2444 # get all needed from database
2447 db_nslcmop_update
= {}
2448 nslcmop_operation_state
= None
2449 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
,
2450 "_admin.current-operation": nslcmop_id
,
2451 "_admin.operation-type": "scale"}
2452 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2454 # in case of error, indicates what part of scale was failed to put nsr at error status
2455 scale_process
= None
2456 old_operational_status
= ""
2457 old_config_status
= ""
2460 # wait for any previous tasks in process
2461 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
2463 step
= "Getting nslcmop from database"
2464 self
.logger
.debug(step
+ " after having waited for previous tasks to be completed")
2465 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
2466 step
= "Getting nsr from database"
2467 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2469 old_operational_status
= db_nsr
["operational-status"]
2470 old_config_status
= db_nsr
["config-status"]
2471 step
= "Parsing scaling parameters"
2472 # self.logger.debug(step)
2473 db_nsr_update
["operational-status"] = "scaling"
2474 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2475 nsr_deployed
= db_nsr
["_admin"].get("deployed")
2478 nsr_deployed
= db_nsr
["_admin"].get("deployed")
2479 vnf_index
= db_nslcmop
["operationParams"].get("member_vnf_index")
2480 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
2481 vdu_count_index
= db_nslcmop
["operationParams"].get("vdu_count_index")
2482 vdu_name
= db_nslcmop
["operationParams"].get("vdu_name")
2485 RO_nsr_id
= nsr_deployed
["RO"]["nsr_id"]
2486 vnf_index
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
2487 scaling_group
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
2488 scaling_type
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleVnfType"]
2489 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
2491 # for backward compatibility
2492 if nsr_deployed
and isinstance(nsr_deployed
.get("VCA"), dict):
2493 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
2494 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
2495 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2497 step
= "Getting vnfr from database"
2498 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
2499 step
= "Getting vnfd from database"
2500 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
2502 step
= "Getting scaling-group-descriptor"
2503 for scaling_descriptor
in db_vnfd
["scaling-group-descriptor"]:
2504 if scaling_descriptor
["name"] == scaling_group
:
2507 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
2508 "at vnfd:scaling-group-descriptor".format(scaling_group
))
2511 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
2512 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
2513 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
2516 # TODO check if ns is in a proper status
2517 step
= "Sending scale order to VIM"
2519 if not db_nsr
["_admin"].get("scaling-group"):
2520 self
.update_db_2("nsrs", nsr_id
, {"_admin.scaling-group": [{"name": scaling_group
, "nb-scale-op": 0}]})
2521 admin_scale_index
= 0
2523 for admin_scale_index
, admin_scale_info
in enumerate(db_nsr
["_admin"]["scaling-group"]):
2524 if admin_scale_info
["name"] == scaling_group
:
2525 nb_scale_op
= admin_scale_info
.get("nb-scale-op", 0)
2527 else: # not found, set index one plus last element and add new entry with the name
2528 admin_scale_index
+= 1
2529 db_nsr_update
["_admin.scaling-group.{}.name".format(admin_scale_index
)] = scaling_group
2530 RO_scaling_info
= []
2531 vdu_scaling_info
= {"scaling_group_name": scaling_group
, "vdu": []}
2532 if scaling_type
== "SCALE_OUT":
2533 # count if max-instance-count is reached
2534 max_instance_count
= scaling_descriptor
.get("max-instance-count", 10)
2535 # self.logger.debug("MAX_INSTANCE_COUNT is {}".format(max_instance_count))
2536 if nb_scale_op
>= max_instance_count
:
2537 raise LcmException("reached the limit of {} (max-instance-count) "
2538 "scaling-out operations for the "
2539 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
2542 vdu_scaling_info
["scaling_direction"] = "OUT"
2543 vdu_scaling_info
["vdu-create"] = {}
2544 for vdu_scale_info
in scaling_descriptor
["vdu"]:
2545 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
2546 "type": "create", "count": vdu_scale_info
.get("count", 1)})
2547 vdu_scaling_info
["vdu-create"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
2549 elif scaling_type
== "SCALE_IN":
2550 # count if min-instance-count is reached
2551 min_instance_count
= 0
2552 if "min-instance-count" in scaling_descriptor
and scaling_descriptor
["min-instance-count"] is not None:
2553 min_instance_count
= int(scaling_descriptor
["min-instance-count"])
2554 if nb_scale_op
<= min_instance_count
:
2555 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
2556 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
2558 vdu_scaling_info
["scaling_direction"] = "IN"
2559 vdu_scaling_info
["vdu-delete"] = {}
2560 for vdu_scale_info
in scaling_descriptor
["vdu"]:
2561 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
2562 "type": "delete", "count": vdu_scale_info
.get("count", 1)})
2563 vdu_scaling_info
["vdu-delete"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
2565 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
2566 vdu_create
= vdu_scaling_info
.get("vdu-create")
2567 vdu_delete
= copy(vdu_scaling_info
.get("vdu-delete"))
2568 if vdu_scaling_info
["scaling_direction"] == "IN":
2569 for vdur
in reversed(db_vnfr
["vdur"]):
2570 if vdu_delete
.get(vdur
["vdu-id-ref"]):
2571 vdu_delete
[vdur
["vdu-id-ref"]] -= 1
2572 vdu_scaling_info
["vdu"].append({
2573 "name": vdur
["name"],
2574 "vdu_id": vdur
["vdu-id-ref"],
2577 for interface
in vdur
["interfaces"]:
2578 vdu_scaling_info
["vdu"][-1]["interface"].append({
2579 "name": interface
["name"],
2580 "ip_address": interface
["ip-address"],
2581 "mac_address": interface
.get("mac-address"),
2583 vdu_delete
= vdu_scaling_info
.pop("vdu-delete")
2586 step
= "Executing pre-scale vnf-config-primitive"
2587 if scaling_descriptor
.get("scaling-config-action"):
2588 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
2589 if (scaling_config_action
.get("trigger") == "pre-scale-in" and scaling_type
== "SCALE_IN") \
2590 or (scaling_config_action
.get("trigger") == "pre-scale-out" and scaling_type
== "SCALE_OUT"):
2591 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
2592 step
= db_nslcmop_update
["detailed-status"] = \
2593 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive
)
2595 # look for primitive
2596 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
2597 if config_primitive
["name"] == vnf_config_primitive
:
2601 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
2602 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
2603 "primitive".format(scaling_group
, config_primitive
))
2605 vnfr_params
= {"VDU_SCALE_INFO": vdu_scaling_info
}
2606 if db_vnfr
.get("additionalParamsForVnf"):
2607 vnfr_params
.update(db_vnfr
["additionalParamsForVnf"])
2609 scale_process
= "VCA"
2610 db_nsr_update
["config-status"] = "configuring pre-scaling"
2611 primitive_params
= self
._map
_primitive
_params
(config_primitive
, {}, vnfr_params
)
2613 # Pre-scale reintent check: Check if this sub-operation has been executed before
2614 op_index
= self
._check
_or
_add
_scale
_suboperation
(
2615 db_nslcmop
, nslcmop_id
, vnf_index
, vnf_config_primitive
, primitive_params
, 'PRE-SCALE')
2616 if (op_index
== self
.SUBOPERATION_STATUS_SKIP
):
2617 # Skip sub-operation
2618 result
= 'COMPLETED'
2619 result_detail
= 'Done'
2620 self
.logger
.debug(logging_text
+
2621 "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
2622 vnf_config_primitive
, result
, result_detail
))
2624 if (op_index
== self
.SUBOPERATION_STATUS_NEW
):
2625 # New sub-operation: Get index of this sub-operation
2626 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
2627 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} New sub-operation".
2628 format(vnf_config_primitive
))
2630 # Reintent: Get registered params for this existing sub-operation
2631 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
2632 vnf_index
= op
.get('member_vnf_index')
2633 vnf_config_primitive
= op
.get('primitive')
2634 primitive_params
= op
.get('primitive_params')
2635 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Sub-operation reintent".
2636 format(vnf_config_primitive
))
2637 # Execute the primitive, either with new (first-time) or registered (reintent) args
2638 result
, result_detail
= await self
._ns
_execute
_primitive
(
2639 nsr_deployed
, vnf_index
, None, None, None, vnf_config_primitive
, primitive_params
)
2640 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
2641 vnf_config_primitive
, result
, result_detail
))
2642 # Update operationState = COMPLETED | FAILED
2643 self
._update
_suboperation
_status
(
2644 db_nslcmop
, op_index
, result
, result_detail
)
2646 if result
== "FAILED":
2647 raise LcmException(result_detail
)
2648 db_nsr_update
["config-status"] = old_config_status
2649 scale_process
= None
2653 # Should this block be skipped if 'RO_nsr_id' == None ?
2654 # if (RO_nsr_id and RO_scaling_info):
2656 scale_process
= "RO"
2657 # Scale RO reintent check: Check if this sub-operation has been executed before
2658 op_index
= self
._check
_or
_add
_scale
_suboperation
(
2659 db_nslcmop
, vnf_index
, None, None, 'SCALE-RO', RO_nsr_id
, RO_scaling_info
)
2660 if (op_index
== self
.SUBOPERATION_STATUS_SKIP
):
2661 # Skip sub-operation
2662 result
= 'COMPLETED'
2663 result_detail
= 'Done'
2664 self
.logger
.debug(logging_text
+ "Skipped sub-operation RO, result {} {}".format(
2665 result
, result_detail
))
2667 if (op_index
== self
.SUBOPERATION_STATUS_NEW
):
2668 # New sub-operation: Get index of this sub-operation
2669 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
2670 self
.logger
.debug(logging_text
+ "New sub-operation RO")
2672 # Reintent: Get registered params for this existing sub-operation
2673 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
2674 RO_nsr_id
= op
.get('RO_nsr_id')
2675 RO_scaling_info
= op
.get('RO_scaling_info')
2676 self
.logger
.debug(logging_text
+ "Sub-operation RO reintent".format(
2677 vnf_config_primitive
))
2679 RO_desc
= await self
.RO
.create_action("ns", RO_nsr_id
, {"vdu-scaling": RO_scaling_info
})
2680 db_nsr_update
["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index
)] = nb_scale_op
2681 db_nsr_update
["_admin.scaling-group.{}.time".format(admin_scale_index
)] = time()
2683 RO_nslcmop_id
= RO_desc
["instance_action_id"]
2684 db_nslcmop_update
["_admin.deploy.RO"] = RO_nslcmop_id
2686 RO_task_done
= False
2687 step
= detailed_status
= "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id
)
2688 detailed_status_old
= None
2689 self
.logger
.debug(logging_text
+ step
)
2691 deployment_timeout
= 1 * 3600 # One hour
2692 while deployment_timeout
> 0:
2693 if not RO_task_done
:
2694 desc
= await self
.RO
.show("ns", item_id_name
=RO_nsr_id
, extra_item
="action",
2695 extra_item_id
=RO_nslcmop_id
)
2696 ns_status
, ns_status_info
= self
.RO
.check_action_status(desc
)
2697 if ns_status
== "ERROR":
2698 raise ROclient
.ROClientException(ns_status_info
)
2699 elif ns_status
== "BUILD":
2700 detailed_status
= step
+ "; {}".format(ns_status_info
)
2701 elif ns_status
== "ACTIVE":
2703 step
= detailed_status
= "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id
)
2704 self
.logger
.debug(logging_text
+ step
)
2706 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
2709 if ns_status
== "ERROR":
2710 raise ROclient
.ROClientException(ns_status_info
)
2711 elif ns_status
== "BUILD":
2712 detailed_status
= step
+ "; {}".format(ns_status_info
)
2713 elif ns_status
== "ACTIVE":
2714 step
= detailed_status
= \
2715 "Waiting for management IP address reported by the VIM. Updating VNFRs"
2717 self
.scale_vnfr(db_vnfr
, vdu_create
=vdu_create
, vdu_delete
=vdu_delete
)
2720 desc
= await self
.RO
.show("ns", RO_nsr_id
)
2721 # nsr_deployed["nsr_ip"] = RO.get_ns_vnf_info(desc)
2722 self
.ns_update_vnfr({db_vnfr
["member-vnf-index-ref"]: db_vnfr
}, desc
)
2724 except LcmExceptionNoMgmtIP
:
2727 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
2728 if detailed_status
!= detailed_status_old
:
2729 self
._update
_suboperation
_status
(
2730 db_nslcmop
, op_index
, 'COMPLETED', detailed_status
)
2731 detailed_status_old
= db_nslcmop_update
["detailed-status"] = detailed_status
2732 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2734 await asyncio
.sleep(5, loop
=self
.loop
)
2735 deployment_timeout
-= 5
2736 if deployment_timeout
<= 0:
2737 self
._update
_suboperation
_status
(
2738 db_nslcmop
, nslcmop_id
, op_index
, 'FAILED', "Timeout when waiting for ns to get ready")
2739 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
2741 # update VDU_SCALING_INFO with the obtained ip_addresses
2742 if vdu_scaling_info
["scaling_direction"] == "OUT":
2743 for vdur
in reversed(db_vnfr
["vdur"]):
2744 if vdu_scaling_info
["vdu-create"].get(vdur
["vdu-id-ref"]):
2745 vdu_scaling_info
["vdu-create"][vdur
["vdu-id-ref"]] -= 1
2746 vdu_scaling_info
["vdu"].append({
2747 "name": vdur
["name"],
2748 "vdu_id": vdur
["vdu-id-ref"],
2751 for interface
in vdur
["interfaces"]:
2752 vdu_scaling_info
["vdu"][-1]["interface"].append({
2753 "name": interface
["name"],
2754 "ip_address": interface
["ip-address"],
2755 "mac_address": interface
.get("mac-address"),
2757 del vdu_scaling_info
["vdu-create"]
2759 self
._update
_suboperation
_status
(db_nslcmop
, op_index
, 'COMPLETED', 'Done')
2762 scale_process
= None
2764 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2767 # execute primitive service POST-SCALING
2768 step
= "Executing post-scale vnf-config-primitive"
2769 if scaling_descriptor
.get("scaling-config-action"):
2770 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
2771 if (scaling_config_action
.get("trigger") == "post-scale-in" and scaling_type
== "SCALE_IN") \
2772 or (scaling_config_action
.get("trigger") == "post-scale-out" and scaling_type
== "SCALE_OUT"):
2773 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
2774 step
= db_nslcmop_update
["detailed-status"] = \
2775 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive
)
2777 vnfr_params
= {"VDU_SCALE_INFO": vdu_scaling_info
}
2778 if db_vnfr
.get("additionalParamsForVnf"):
2779 vnfr_params
.update(db_vnfr
["additionalParamsForVnf"])
2781 # look for primitive
2782 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
2783 if config_primitive
["name"] == vnf_config_primitive
:
2786 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
2787 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
2788 "match any vnf-configuration:config-primitive".format(scaling_group
,
2790 scale_process
= "VCA"
2791 db_nsr_update
["config-status"] = "configuring post-scaling"
2792 primitive_params
= self
._map
_primitive
_params
(config_primitive
, {}, vnfr_params
)
2794 # Post-scale reintent check: Check if this sub-operation has been executed before
2795 op_index
= self
._check
_or
_add
_scale
_suboperation
(
2796 db_nslcmop
, nslcmop_id
, vnf_index
, vnf_config_primitive
, primitive_params
, 'POST-SCALE')
2797 if (op_index
== self
.SUBOPERATION_STATUS_SKIP
):
2798 # Skip sub-operation
2799 result
= 'COMPLETED'
2800 result_detail
= 'Done'
2801 self
.logger
.debug(logging_text
+
2802 "vnf_config_primitive={} Skipped sub-operation, result {} {}".
2803 format(vnf_config_primitive
, result
, result_detail
))
2805 if (op_index
== self
.SUBOPERATION_STATUS_NEW
):
2806 # New sub-operation: Get index of this sub-operation
2807 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
2808 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} New sub-operation".
2809 format(vnf_config_primitive
))
2811 # Reintent: Get registered params for this existing sub-operation
2812 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
2813 vnf_index
= op
.get('member_vnf_index')
2814 vnf_config_primitive
= op
.get('primitive')
2815 primitive_params
= op
.get('primitive_params')
2816 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Sub-operation reintent".
2817 format(vnf_config_primitive
))
2818 # Execute the primitive, either with new (first-time) or registered (reintent) args
2819 result
, result_detail
= await self
._ns
_execute
_primitive
(
2820 nsr_deployed
, vnf_index
, None, None, None, vnf_config_primitive
, primitive_params
)
2821 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
2822 vnf_config_primitive
, result
, result_detail
))
2823 # Update operationState = COMPLETED | FAILED
2824 self
._update
_suboperation
_status
(
2825 db_nslcmop
, op_index
, result
, result_detail
)
2827 if result
== "FAILED":
2828 raise LcmException(result_detail
)
2829 db_nsr_update
["config-status"] = old_config_status
2830 scale_process
= None
2833 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
2834 db_nslcmop_update
["statusEnteredTime"] = time()
2835 db_nslcmop_update
["detailed-status"] = "done"
2836 db_nsr_update
["detailed-status"] = "" # "scaled {} {}".format(scaling_group, scaling_type)
2837 db_nsr_update
["operational-status"] = "running" if old_operational_status
== "failed" \
2838 else old_operational_status
2839 db_nsr_update
["config-status"] = old_config_status
2841 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
2842 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
2844 except asyncio
.CancelledError
:
2845 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
2846 exc
= "Operation was cancelled"
2847 except Exception as e
:
2848 exc
= traceback
.format_exc()
2849 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
2853 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
2854 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2855 db_nslcmop_update
["statusEnteredTime"] = time()
2857 db_nsr_update
["operational-status"] = old_operational_status
2858 db_nsr_update
["config-status"] = old_config_status
2859 db_nsr_update
["detailed-status"] = ""
2860 db_nsr_update
["_admin.nslcmop"] = None
2862 if "VCA" in scale_process
:
2863 db_nsr_update
["config-status"] = "failed"
2864 if "RO" in scale_process
:
2865 db_nsr_update
["operational-status"] = "failed"
2866 db_nsr_update
["detailed-status"] = "FAILED scaling nslcmop={} {}: {}".format(nslcmop_id
, step
,
2869 if db_nslcmop
and db_nslcmop_update
:
2870 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2872 db_nsr_update
["_admin.current-operation"] = None
2873 db_nsr_update
["_admin.operation-type"] = None
2874 db_nsr_update
["_admin.nslcmop"] = None
2875 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2876 except DbException
as e
:
2877 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
2878 if nslcmop_operation_state
:
2880 await self
.msg
.aiowrite("ns", "scaled", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2881 "operationState": nslcmop_operation_state
},
2884 # await asyncio.sleep(cooldown_time, loop=self.loop)
2885 # await self.msg.aiowrite("ns","scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
2886 except Exception as e
:
2887 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
2888 self
.logger
.debug(logging_text
+ "Exit")
2889 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_scale")