blob: c4488230f286bf1dcdb735bb0adec73e015c0f2b [file] [log] [blame]
tierno59d22d22018-09-25 18:10:19 +02001# -*- coding: utf-8 -*-
2
tierno2e215512018-11-28 09:37:52 +00003##
4# Copyright 2018 Telefonica S.A.
5#
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
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
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
16# under the License.
17##
18
tierno59d22d22018-09-25 18:10:19 +020019import asyncio
20import yaml
21import logging
22import logging.handlers
tierno59d22d22018-09-25 18:10:19 +020023import traceback
gcalvino35be9152018-12-20 09:33:12 +010024from jinja2 import Environment, Template, meta, TemplateError, TemplateNotFound, TemplateSyntaxError
tierno59d22d22018-09-25 18:10:19 +020025
tierno77677d92019-08-22 13:46:35 +000026from osm_lcm import ROclient
27from osm_lcm.lcm_utils import LcmException, LcmExceptionNoMgmtIP, LcmBase
calvinosanch9f9c6f22019-11-04 13:37:39 +010028from n2vc.k8s_helm_conn import K8sHelmConnector
tierno59d22d22018-09-25 18:10:19 +020029
tierno27246d82018-09-27 15:59:09 +020030from osm_common.dbbase import DbException
tierno59d22d22018-09-25 18:10:19 +020031from osm_common.fsbase import FsException
quilesj7e13aeb2019-10-08 13:34:55 +020032
33from n2vc.n2vc_juju_conn import N2VCJujuConnector
tierno59d22d22018-09-25 18:10:19 +020034
tierno27246d82018-09-27 15:59:09 +020035from copy import copy, deepcopy
tierno59d22d22018-09-25 18:10:19 +020036from http import HTTPStatus
37from time import time
tierno27246d82018-09-27 15:59:09 +020038from uuid import uuid4
tierno59d22d22018-09-25 18:10:19 +020039
40__author__ = "Alfonso Tierno"
41
42
tierno27246d82018-09-27 15:59:09 +020043def get_iterable(in_dict, in_key):
44 """
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
49 """
50 if not in_dict.get(in_key):
51 return ()
52 return in_dict[in_key]
53
54
55def populate_dict(target_dict, key_list, value):
56 """
Adam Israel78770df2019-09-04 11:55:55 -040057 Update target_dict creating nested dictionaries with the key_list. Last key_list item is asigned the value.
tierno27246d82018-09-27 15:59:09 +020058 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
61 :param value:
62 :return: None
63 """
64 for key in key_list[0:-1]:
65 if key not in target_dict:
66 target_dict[key] = {}
67 target_dict = target_dict[key]
68 target_dict[key_list[-1]] = value
69
70
tierno6cf25f52019-09-12 09:33:40 +000071def deep_get(target_dict, key_list):
72 """
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
78 """
79 for key in key_list:
80 if not isinstance(target_dict, dict) or key not in target_dict:
81 return None
82 target_dict = target_dict[key]
83 return target_dict
84
85
tierno59d22d22018-09-25 18:10:19 +020086class NsLcm(LcmBase):
tierno63de62e2018-10-31 16:38:52 +010087 timeout_vca_on_error = 5 * 60 # Time for charm from first time at blocked,error status to mark as failed
garciadeblasf9b04952019-04-09 18:53:58 +020088 total_deploy_timeout = 2 * 3600 # global timeout for deployment
89 timeout_charm_delete = 10 * 60
90 timeout_primitive = 10 * 60 # timeout for primitive execution
tierno59d22d22018-09-25 18:10:19 +020091
kuuseac3a8882019-10-03 10:48:06 +020092 SUBOPERATION_STATUS_NOT_FOUND = -1
93 SUBOPERATION_STATUS_NEW = -2
94 SUBOPERATION_STATUS_SKIP = -3
95
tierno59d22d22018-09-25 18:10:19 +020096 def __init__(self, db, msg, fs, lcm_tasks, ro_config, vca_config, loop):
97 """
98 Init, Connect to database, filesystem storage, and messaging
99 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
100 :return: None
101 """
quilesj7e13aeb2019-10-08 13:34:55 +0200102 super().__init__(
103 db=db,
104 msg=msg,
105 fs=fs,
106 logger=logging.getLogger('lcm.ns')
107 )
108
tierno59d22d22018-09-25 18:10:19 +0200109 self.loop = loop
110 self.lcm_tasks = lcm_tasks
tierno59d22d22018-09-25 18:10:19 +0200111 self.ro_config = ro_config
quilesj7e13aeb2019-10-08 13:34:55 +0200112 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']
tierno59d22d22018-09-25 18:10:19 +0200117
quilesj7e13aeb2019-10-08 13:34:55 +0200118 # create N2VC connector
119 self.n2vc = N2VCJujuConnector(
120 db=self.db,
121 fs=self.fs,
tierno59d22d22018-09-25 18:10:19 +0200122 log=self.logger,
quilesj7e13aeb2019-10-08 13:34:55 +0200123 loop=self.loop,
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_n2vc_db
128 # TODO
129 # New N2VC argument
130 # api_proxy=vca_config.get('apiproxy')
tierno59d22d22018-09-25 18:10:19 +0200131 )
quilesj7e13aeb2019-10-08 13:34:55 +0200132
calvinosanch9f9c6f22019-11-04 13:37:39 +0100133 self.k8sclusterhelm = K8sHelmConnector(
134 kubectl_command=self.vca_config.get("kubectlpath"),
135 helm_command=self.vca_config.get("helmpath"),
136 fs=self.fs,
137 log=self.logger,
138 db=self.db,
139 on_update_db=None,
140 )
141
quilesj7e13aeb2019-10-08 13:34:55 +0200142 # create RO client
tierno77677d92019-08-22 13:46:35 +0000143 self.RO = ROclient.ROClient(self.loop, **self.ro_config)
tierno59d22d22018-09-25 18:10:19 +0200144
quilesj7e13aeb2019-10-08 13:34:55 +0200145 def _on_update_n2vc_db(self, table, filter, path, updated_data):
146
calvinosanch9f9c6f22019-11-04 13:37:39 +0100147 self.logger.debug('_on_update_n2vc_db(table={}, filter={}, path={}, updated_data={}'
quilesj7e13aeb2019-10-08 13:34:55 +0200148 .format(table, filter, path, updated_data))
149
calvinosanch9f9c6f22019-11-04 13:37:39 +0100150 return
quilesj7e13aeb2019-10-08 13:34:55 +0200151 # write NS status to database
tierno73d8bd02019-11-18 17:33:27 +0000152 # try:
153 # # nsrs_id = filter.get('_id')
calvinosanch9f9c6f22019-11-04 13:37:39 +0100154 # # print(nsrs_id)
tierno73d8bd02019-11-18 17:33:27 +0000155 # # get ns record
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'))
159 # # get RO deployed
calvinosanch9f9c6f22019-11-04 13:37:39 +0100160 # # ro_list = deep_get(target_dict=nsr, key_list=('_admin', 'deployed', 'RO'))
tierno73d8bd02019-11-18 17:33:27 +0000161 # for vca in vca_list:
calvinosanch9f9c6f22019-11-04 13:37:39 +0100162 # # status = vca.get('status')
163 # # print(status)
164 # # detailed_status = vca.get('detailed-status')
165 # # print(detailed_status)
166 # # for ro in ro_list:
167 # # print(ro)
tierno73d8bd02019-11-18 17:33:27 +0000168 #
169 # except Exception as e:
calvinosanch9f9c6f22019-11-04 13:37:39 +0100170 # self.logger.error('Error writing NS status to db: {}'.format(e))
quilesj7e13aeb2019-10-08 13:34:55 +0200171
gcalvino35be9152018-12-20 09:33:12 +0100172 def vnfd2RO(self, vnfd, new_id=None, additionalParams=None, nsrId=None):
tierno59d22d22018-09-25 18:10:19 +0200173 """
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
tierno8a518872018-12-21 13:42:14 +0000177 :param additionalParams: Instantiation params for VNFs provided
gcalvino35be9152018-12-20 09:33:12 +0100178 :param nsrId: Id of the NSR
tierno59d22d22018-09-25 18:10:19 +0200179 :return: copy of vnfd
180 """
tierno59d22d22018-09-25 18:10:19 +0200181 try:
182 vnfd_RO = deepcopy(vnfd)
tierno8a518872018-12-21 13:42:14 +0000183 # remove unused by RO configuration, monitoring, scaling and internal keys
tierno59d22d22018-09-25 18:10:19 +0200184 vnfd_RO.pop("_id", None)
185 vnfd_RO.pop("_admin", None)
tierno8a518872018-12-21 13:42:14 +0000186 vnfd_RO.pop("vnf-configuration", None)
187 vnfd_RO.pop("monitoring-param", None)
188 vnfd_RO.pop("scaling-group-descriptor", None)
calvinosanch9f9c6f22019-11-04 13:37:39 +0100189 vnfd_RO.pop("kdu", None)
190 vnfd_RO.pop("k8s-cluster", None)
tierno59d22d22018-09-25 18:10:19 +0200191 if new_id:
192 vnfd_RO["id"] = new_id
tierno8a518872018-12-21 13:42:14 +0000193
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"):
tierno59d22d22018-09-25 18:10:19 +0200198 base_folder = vnfd["_admin"]["storage"]
gcalvino35be9152018-12-20 09:33:12 +0100199 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()
tierno59d22d22018-09-25 18:10:19 +0200203 vdu.pop("cloud-init-file", None)
tierno8a518872018-12-21 13:42:14 +0000204 elif vdu.get("cloud-init"):
gcalvino35be9152018-12-20 09:33:12 +0100205 cloud_init_content = vdu["cloud-init"]
tierno8a518872018-12-21 13:42:14 +0000206 else:
207 continue
208
209 env = Environment()
210 ast = env.parse(cloud_init_content)
211 mandatory_vars = meta.find_undeclared_variables(ast)
212 if mandatory_vars:
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)
tierno2b611dd2019-01-11 10:30:57 +0000219 cloud_init_content = template.render(additionalParams or {})
gcalvino35be9152018-12-20 09:33:12 +0100220 vdu["cloud-init"] = cloud_init_content
tierno8a518872018-12-21 13:42:14 +0000221
tierno59d22d22018-09-25 18:10:19 +0200222 return vnfd_RO
223 except FsException as e:
tierno8a518872018-12-21 13:42:14 +0000224 raise LcmException("Error reading vnfd[id={}]:vdu[id={}]:cloud-init-file={}: {}".
tiernoda964822019-01-14 15:53:47 +0000225 format(vnfd["id"], vdu["id"], cloud_init_file, e))
tierno8a518872018-12-21 13:42:14 +0000226 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))
tierno59d22d22018-09-25 18:10:19 +0200229
tierno27246d82018-09-27 15:59:09 +0200230 def ns_params_2_RO(self, ns_params, nsd, vnfd_dict, n2vc_key_list):
tierno59d22d22018-09-25 18:10:19 +0200231 """
tierno27246d82018-09-27 15:59:09 +0200232 Creates a RO ns descriptor from OSM ns_instantiate params
tierno59d22d22018-09-25 18:10:19 +0200233 :param ns_params: OSM instantiate params
234 :return: The RO ns descriptor
235 """
236 vim_2_RO = {}
tiernob7f3f0d2019-03-20 17:17:21 +0000237 wim_2_RO = {}
tierno27246d82018-09-27 15:59:09 +0200238 # 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
tierno59d22d22018-09-25 18:10:19 +0200241
242 def vim_account_2_RO(vim_account):
243 if vim_account in vim_2_RO:
244 return vim_2_RO[vim_account]
245
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
252 return RO_vim_id
253
tiernob7f3f0d2019-03-20 17:17:21 +0000254 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]
258
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
265 return RO_wim_id
266 else:
267 return wim_account
268
tierno59d22d22018-09-25 18:10:19 +0200269 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'])
276 else:
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")
284 return RO_ip_profile
285
286 if not ns_params:
287 return None
288 RO_ns_params = {
289 # "name": ns_params["nsName"],
290 # "description": ns_params.get("nsDescription"),
291 "datacenter": vim_account_2_RO(ns_params["vimAccountId"]),
tiernob7f3f0d2019-03-20 17:17:21 +0000292 "wim_account": wim_account_2_RO(ns_params.get("wimAccountId")),
tierno59d22d22018-09-25 18:10:19 +0200293 # "scenario": ns_params["nsdId"],
tierno59d22d22018-09-25 18:10:19 +0200294 }
quilesj7e13aeb2019-10-08 13:34:55 +0200295
tiernoe64f7fb2019-09-11 08:55:52 +0000296 n2vc_key_list = n2vc_key_list or []
297 for vnfd_ref, vnfd in vnfd_dict.items():
298 vdu_needed_access = []
299 mgmt_cp = None
300 if vnfd.get("vnf-configuration"):
tierno6cf25f52019-09-12 09:33:40 +0000301 ssh_required = deep_get(vnfd, ("vnf-configuration", "config-access", "ssh-access", "required"))
tiernoe64f7fb2019-09-11 08:55:52 +0000302 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"]
tierno27246d82018-09-27 15:59:09 +0200307
tiernoe64f7fb2019-09-11 08:55:52 +0000308 for vdu in vnfd.get("vdu", ()):
309 if vdu.get("vdu-configuration"):
tierno6cf25f52019-09-12 09:33:40 +0000310 ssh_required = deep_get(vdu, ("vdu-configuration", "config-access", "ssh-access", "required"))
tiernoe64f7fb2019-09-11 08:55:52 +0000311 if ssh_required:
tierno27246d82018-09-27 15:59:09 +0200312 vdu_needed_access.append(vdu["id"])
tiernoe64f7fb2019-09-11 08:55:52 +0000313 elif mgmt_cp:
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"])
318 mgmt_cp = None
319 break
tierno27246d82018-09-27 15:59:09 +0200320
tiernoe64f7fb2019-09-11 08:55:52 +0000321 if vdu_needed_access:
322 for vnf_member in nsd.get("constituent-vnfd"):
323 if vnf_member["vnfd-id-ref"] != vnfd_ref:
324 continue
325 for vdu in vdu_needed_access:
326 populate_dict(RO_ns_params,
327 ("vnfs", vnf_member["member-vnf-index"], "vdus", vdu, "mgmt_keys"),
328 n2vc_key_list)
tierno27246d82018-09-27 15:59:09 +0200329
tierno25ec7732018-10-24 18:47:11 +0200330 if ns_params.get("vduImage"):
331 RO_ns_params["vduImage"] = ns_params["vduImage"]
332
tiernoc255a822018-10-31 09:41:53 +0100333 if ns_params.get("ssh_keys"):
334 RO_ns_params["cloud-config"] = {"key-pairs": ns_params["ssh_keys"]}
tierno27246d82018-09-27 15:59:09 +0200335 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"]]
339 break
340 else:
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"]))
tierno59d22d22018-09-25 18:10:19 +0200346
tierno27246d82018-09-27 15:59:09 +0200347 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"],
360 "ip_address"),
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"],
365 "mac_address"),
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"],
370 "floating-ip"),
371 interface_params["floating-ip-required"])
372
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"])
gcalvino0d7ac8d2018-12-17 16:24:08 +0100378 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"])
tierno27246d82018-09-27 15:59:09 +0200382 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"]))
kbsub4d761eb2019-10-17 16:28:48 +0000386 if internal_vld_params.get("provider-network"):
387
388 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "networks",
389 internal_vld_params["name"], "provider-network"),
390 internal_vld_params["provider-network"].copy())
tierno27246d82018-09-27 15:59:09 +0200391
392 for icp_params in get_iterable(internal_vld_params, "internal-connection-point"):
393 # look for interface
394 iface_found = False
395 for vdu_descriptor in vnf_descriptor["vdu"]:
396 for vdu_interface in vdu_descriptor["interface"]:
397 if vdu_interface.get("internal-connection-point-ref") == icp_params["id-ref"]:
398 if icp_params.get("ip-address"):
399 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
400 vdu_descriptor["id"], "interfaces",
401 vdu_interface["name"], "ip_address"),
402 icp_params["ip-address"])
403
404 if icp_params.get("mac-address"):
405 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
406 vdu_descriptor["id"], "interfaces",
407 vdu_interface["name"], "mac_address"),
408 icp_params["mac-address"])
409 iface_found = True
tierno59d22d22018-09-25 18:10:19 +0200410 break
tierno27246d82018-09-27 15:59:09 +0200411 if iface_found:
412 break
413 else:
414 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
415 "internal-vld:id-ref={} is not present at vnfd:internal-"
416 "connection-point".format(vnf_params["member-vnf-index"],
417 icp_params["id-ref"]))
418
419 for vld_params in get_iterable(ns_params, "vld"):
420 if "ip-profile" in vld_params:
421 populate_dict(RO_ns_params, ("networks", vld_params["name"], "ip-profile"),
422 ip_profile_2_RO(vld_params["ip-profile"]))
tiernob7f3f0d2019-03-20 17:17:21 +0000423
kbsub4d761eb2019-10-17 16:28:48 +0000424 if vld_params.get("provider-network"):
425
426 populate_dict(RO_ns_params, ("networks", vld_params["name"], "provider-network"),
427 vld_params["provider-network"].copy())
428
tiernob7f3f0d2019-03-20 17:17:21 +0000429 if "wimAccountId" in vld_params and vld_params["wimAccountId"] is not None:
430 populate_dict(RO_ns_params, ("networks", vld_params["name"], "wim_account"),
431 wim_account_2_RO(vld_params["wimAccountId"])),
tierno27246d82018-09-27 15:59:09 +0200432 if vld_params.get("vim-network-name"):
433 RO_vld_sites = []
434 if isinstance(vld_params["vim-network-name"], dict):
435 for vim_account, vim_net in vld_params["vim-network-name"].items():
436 RO_vld_sites.append({
437 "netmap-use": vim_net,
438 "datacenter": vim_account_2_RO(vim_account)
439 })
440 else: # isinstance str
441 RO_vld_sites.append({"netmap-use": vld_params["vim-network-name"]})
442 if RO_vld_sites:
443 populate_dict(RO_ns_params, ("networks", vld_params["name"], "sites"), RO_vld_sites)
kbsub4d761eb2019-10-17 16:28:48 +0000444
gcalvino0d7ac8d2018-12-17 16:24:08 +0100445 if vld_params.get("vim-network-id"):
446 RO_vld_sites = []
447 if isinstance(vld_params["vim-network-id"], dict):
448 for vim_account, vim_net in vld_params["vim-network-id"].items():
449 RO_vld_sites.append({
450 "netmap-use": vim_net,
451 "datacenter": vim_account_2_RO(vim_account)
452 })
453 else: # isinstance str
454 RO_vld_sites.append({"netmap-use": vld_params["vim-network-id"]})
455 if RO_vld_sites:
456 populate_dict(RO_ns_params, ("networks", vld_params["name"], "sites"), RO_vld_sites)
Felipe Vicens720b07a2019-01-31 02:32:09 +0100457 if vld_params.get("ns-net"):
458 if isinstance(vld_params["ns-net"], dict):
459 for vld_id, instance_scenario_id in vld_params["ns-net"].items():
460 RO_vld_ns_net = {"instance_scenario_id": instance_scenario_id, "osm_id": vld_id}
461 if RO_vld_ns_net:
quilesj7e13aeb2019-10-08 13:34:55 +0200462 populate_dict(RO_ns_params, ("networks", vld_params["name"], "use-network"), RO_vld_ns_net)
tierno27246d82018-09-27 15:59:09 +0200463 if "vnfd-connection-point-ref" in vld_params:
464 for cp_params in vld_params["vnfd-connection-point-ref"]:
465 # look for interface
466 for constituent_vnfd in nsd["constituent-vnfd"]:
467 if constituent_vnfd["member-vnf-index"] == cp_params["member-vnf-index-ref"]:
468 vnf_descriptor = vnfd_dict[constituent_vnfd["vnfd-id-ref"]]
469 break
470 else:
471 raise LcmException(
472 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={} "
473 "is not present at nsd:constituent-vnfd".format(cp_params["member-vnf-index-ref"]))
474 match_cp = False
475 for vdu_descriptor in vnf_descriptor["vdu"]:
476 for interface_descriptor in vdu_descriptor["interface"]:
477 if interface_descriptor.get("external-connection-point-ref") == \
478 cp_params["vnfd-connection-point-ref"]:
479 match_cp = True
tierno59d22d22018-09-25 18:10:19 +0200480 break
tierno27246d82018-09-27 15:59:09 +0200481 if match_cp:
482 break
483 else:
484 raise LcmException(
485 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={}:"
486 "vnfd-connection-point-ref={} is not present at vnfd={}".format(
487 cp_params["member-vnf-index-ref"],
488 cp_params["vnfd-connection-point-ref"],
489 vnf_descriptor["id"]))
490 if cp_params.get("ip-address"):
491 populate_dict(RO_ns_params, ("vnfs", cp_params["member-vnf-index-ref"], "vdus",
492 vdu_descriptor["id"], "interfaces",
493 interface_descriptor["name"], "ip_address"),
494 cp_params["ip-address"])
495 if cp_params.get("mac-address"):
496 populate_dict(RO_ns_params, ("vnfs", cp_params["member-vnf-index-ref"], "vdus",
497 vdu_descriptor["id"], "interfaces",
498 interface_descriptor["name"], "mac_address"),
499 cp_params["mac-address"])
tierno59d22d22018-09-25 18:10:19 +0200500 return RO_ns_params
501
tierno27246d82018-09-27 15:59:09 +0200502 def scale_vnfr(self, db_vnfr, vdu_create=None, vdu_delete=None):
503 # make a copy to do not change
504 vdu_create = copy(vdu_create)
505 vdu_delete = copy(vdu_delete)
506
507 vdurs = db_vnfr.get("vdur")
508 if vdurs is None:
509 vdurs = []
510 vdu_index = len(vdurs)
511 while vdu_index:
512 vdu_index -= 1
513 vdur = vdurs[vdu_index]
514 if vdur.get("pdu-type"):
515 continue
516 vdu_id_ref = vdur["vdu-id-ref"]
517 if vdu_create and vdu_create.get(vdu_id_ref):
518 for index in range(0, vdu_create[vdu_id_ref]):
519 vdur = deepcopy(vdur)
520 vdur["_id"] = str(uuid4())
521 vdur["count-index"] += 1
522 vdurs.insert(vdu_index+1+index, vdur)
523 del vdu_create[vdu_id_ref]
524 if vdu_delete and vdu_delete.get(vdu_id_ref):
525 del vdurs[vdu_index]
526 vdu_delete[vdu_id_ref] -= 1
527 if not vdu_delete[vdu_id_ref]:
528 del vdu_delete[vdu_id_ref]
529 # check all operations are done
530 if vdu_create or vdu_delete:
531 raise LcmException("Error scaling OUT VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
532 vdu_create))
533 if vdu_delete:
534 raise LcmException("Error scaling IN VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
535 vdu_delete))
536
537 vnfr_update = {"vdur": vdurs}
538 db_vnfr["vdur"] = vdurs
539 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
540
tiernof578e552018-11-08 19:07:20 +0100541 def ns_update_nsr(self, ns_update_nsr, db_nsr, nsr_desc_RO):
542 """
543 Updates database nsr with the RO info for the created vld
544 :param ns_update_nsr: dictionary to be filled with the updated info
545 :param db_nsr: content of db_nsr. This is also modified
546 :param nsr_desc_RO: nsr descriptor from RO
547 :return: Nothing, LcmException is raised on errors
548 """
549
550 for vld_index, vld in enumerate(get_iterable(db_nsr, "vld")):
551 for net_RO in get_iterable(nsr_desc_RO, "nets"):
552 if vld["id"] != net_RO.get("ns_net_osm_id"):
553 continue
554 vld["vim-id"] = net_RO.get("vim_net_id")
555 vld["name"] = net_RO.get("vim_name")
556 vld["status"] = net_RO.get("status")
557 vld["status-detailed"] = net_RO.get("error_msg")
558 ns_update_nsr["vld.{}".format(vld_index)] = vld
559 break
560 else:
561 raise LcmException("ns_update_nsr: Not found vld={} at RO info".format(vld["id"]))
562
tierno59d22d22018-09-25 18:10:19 +0200563 def ns_update_vnfr(self, db_vnfrs, nsr_desc_RO):
564 """
565 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
tierno27246d82018-09-27 15:59:09 +0200566 :param db_vnfrs: dictionary with member-vnf-index: vnfr-content
567 :param nsr_desc_RO: nsr descriptor from RO
568 :return: Nothing, LcmException is raised on errors
tierno59d22d22018-09-25 18:10:19 +0200569 """
570 for vnf_index, db_vnfr in db_vnfrs.items():
571 for vnf_RO in nsr_desc_RO["vnfs"]:
tierno27246d82018-09-27 15:59:09 +0200572 if vnf_RO["member_vnf_index"] != vnf_index:
573 continue
574 vnfr_update = {}
tiernof578e552018-11-08 19:07:20 +0100575 if vnf_RO.get("ip_address"):
tierno1674de82019-04-09 13:03:14 +0000576 db_vnfr["ip-address"] = vnfr_update["ip-address"] = vnf_RO["ip_address"].split(";")[0]
tiernof578e552018-11-08 19:07:20 +0100577 elif not db_vnfr.get("ip-address"):
578 raise LcmExceptionNoMgmtIP("ns member_vnf_index '{}' has no IP address".format(vnf_index))
tierno59d22d22018-09-25 18:10:19 +0200579
tierno27246d82018-09-27 15:59:09 +0200580 for vdu_index, vdur in enumerate(get_iterable(db_vnfr, "vdur")):
581 vdur_RO_count_index = 0
582 if vdur.get("pdu-type"):
583 continue
584 for vdur_RO in get_iterable(vnf_RO, "vms"):
585 if vdur["vdu-id-ref"] != vdur_RO["vdu_osm_id"]:
586 continue
587 if vdur["count-index"] != vdur_RO_count_index:
588 vdur_RO_count_index += 1
589 continue
590 vdur["vim-id"] = vdur_RO.get("vim_vm_id")
tierno1674de82019-04-09 13:03:14 +0000591 if vdur_RO.get("ip_address"):
592 vdur["ip-address"] = vdur_RO["ip_address"].split(";")[0]
tierno274ed572019-04-04 13:33:27 +0000593 else:
594 vdur["ip-address"] = None
tierno27246d82018-09-27 15:59:09 +0200595 vdur["vdu-id-ref"] = vdur_RO.get("vdu_osm_id")
596 vdur["name"] = vdur_RO.get("vim_name")
597 vdur["status"] = vdur_RO.get("status")
598 vdur["status-detailed"] = vdur_RO.get("error_msg")
599 for ifacer in get_iterable(vdur, "interfaces"):
600 for interface_RO in get_iterable(vdur_RO, "interfaces"):
601 if ifacer["name"] == interface_RO.get("internal_name"):
602 ifacer["ip-address"] = interface_RO.get("ip_address")
603 ifacer["mac-address"] = interface_RO.get("mac_address")
604 break
605 else:
606 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} interface={} "
quilesj7e13aeb2019-10-08 13:34:55 +0200607 "from VIM info"
608 .format(vnf_index, vdur["vdu-id-ref"], ifacer["name"]))
tierno27246d82018-09-27 15:59:09 +0200609 vnfr_update["vdur.{}".format(vdu_index)] = vdur
610 break
611 else:
tierno15b1cf12019-08-29 13:21:40 +0000612 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} count_index={} from "
613 "VIM info".format(vnf_index, vdur["vdu-id-ref"], vdur["count-index"]))
tiernof578e552018-11-08 19:07:20 +0100614
615 for vld_index, vld in enumerate(get_iterable(db_vnfr, "vld")):
616 for net_RO in get_iterable(nsr_desc_RO, "nets"):
617 if vld["id"] != net_RO.get("vnf_net_osm_id"):
618 continue
619 vld["vim-id"] = net_RO.get("vim_net_id")
620 vld["name"] = net_RO.get("vim_name")
621 vld["status"] = net_RO.get("status")
622 vld["status-detailed"] = net_RO.get("error_msg")
623 vnfr_update["vld.{}".format(vld_index)] = vld
624 break
625 else:
tierno15b1cf12019-08-29 13:21:40 +0000626 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vld={} from VIM info".format(
tiernof578e552018-11-08 19:07:20 +0100627 vnf_index, vld["id"]))
628
tierno27246d82018-09-27 15:59:09 +0200629 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
630 break
tierno59d22d22018-09-25 18:10:19 +0200631
632 else:
tierno15b1cf12019-08-29 13:21:40 +0000633 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} from VIM info".format(vnf_index))
tierno59d22d22018-09-25 18:10:19 +0200634
tiernoc3f2a822019-11-05 13:45:04 +0000635 @staticmethod
636 def _get_ns_config_info(vca_deployed_list):
637 """
638 Generates a mapping between vnf,vdu elements and the N2VC id
639 :param vca_deployed_list: List of database _admin.deploy.VCA that contains this list
640 :return: a dictionary with {osm-config-mapping: {}} where its element contains:
641 "<member-vnf-index>": <N2VC-id> for a vnf configuration, or
642 "<member-vnf-index>.<vdu.id>.<vdu replica(0, 1,..)>": <N2VC-id> for a vdu configuration
643 """
644 mapping = {}
645 ns_config_info = {"osm-config-mapping": mapping}
646 for vca in vca_deployed_list:
647 if not vca["member-vnf-index"]:
648 continue
649 if not vca["vdu_id"]:
650 mapping[vca["member-vnf-index"]] = vca["application"]
651 else:
652 mapping["{}.{}.{}".format(vca["member-vnf-index"], vca["vdu_id"], vca["vdu_count_index"])] =\
653 vca["application"]
654 return ns_config_info
655
656 @staticmethod
657 def _get_initial_config_primitive_list(desc_primitive_list, vca_deployed):
658 """
659 Generates a list of initial-config-primitive based on the list provided by the descriptor. It includes internal
660 primitives as verify-ssh-credentials, or config when needed
661 :param desc_primitive_list: information of the descriptor
662 :param vca_deployed: information of the deployed, needed for known if it is related to an NS, VNF, VDU and if
663 this element contains a ssh public key
664 :return: The modified list. Can ba an empty list, but always a list
665 """
666 if desc_primitive_list:
667 primitive_list = desc_primitive_list.copy()
668 else:
669 primitive_list = []
670 # look for primitive config, and get the position. None if not present
671 config_position = None
672 for index, primitive in enumerate(primitive_list):
673 if primitive["name"] == "config":
674 config_position = index
675 break
676
677 # for NS, add always a config primitive if not present (bug 874)
678 if not vca_deployed["member-vnf-index"] and config_position is None:
679 primitive_list.insert(0, {"name": "config", "parameter": []})
680 config_position = 0
681 # for VNF/VDU add verify-ssh-credentials after config
682 if vca_deployed["member-vnf-index"] and config_position is not None and vca_deployed.get("ssh-public-key"):
683 primitive_list.insert(config_position + 1, {"name": "verify-ssh-credentials", "parameter": []})
684 return primitive_list
685
quilesj7e13aeb2019-10-08 13:34:55 +0200686 async def instantiate_RO(self, logging_text, nsr_id, nsd, db_nsr,
687 db_nslcmop, db_vnfrs, db_vnfds_ref, n2vc_key_list):
688
tiernod8323042019-08-09 11:32:23 +0000689 db_nsr_update = {}
690 RO_descriptor_number = 0 # number of descriptors created at RO
691 vnf_index_2_RO_id = {} # map between vnfd/nsd id to the id used at RO
692 start_deploy = time()
calvinosanch9f9c6f22019-11-04 13:37:39 +0100693 vdu_flag = False # If any of the VNFDs has VDUs
tiernod8323042019-08-09 11:32:23 +0000694 ns_params = db_nslcmop.get("operationParams")
quilesj7e13aeb2019-10-08 13:34:55 +0200695
tiernod8323042019-08-09 11:32:23 +0000696 # deploy RO
quilesj7e13aeb2019-10-08 13:34:55 +0200697
tiernod8323042019-08-09 11:32:23 +0000698 # get vnfds, instantiate at RO
calvinosanch9f9c6f22019-11-04 13:37:39 +0100699
tiernod8323042019-08-09 11:32:23 +0000700 for c_vnf in nsd.get("constituent-vnfd", ()):
701 member_vnf_index = c_vnf["member-vnf-index"]
702 vnfd = db_vnfds_ref[c_vnf['vnfd-id-ref']]
calvinosanch9f9c6f22019-11-04 13:37:39 +0100703 if vnfd.get("vdu"):
704 vdu_flag = True
tiernod8323042019-08-09 11:32:23 +0000705 vnfd_ref = vnfd["id"]
calvinosanch9f9c6f22019-11-04 13:37:39 +0100706 step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Creating vnfd='{}' member_vnf_index='{}' at" \
707 " RO".format(vnfd_ref, member_vnf_index)
tiernod8323042019-08-09 11:32:23 +0000708 # self.logger.debug(logging_text + step)
709 vnfd_id_RO = "{}.{}.{}".format(nsr_id, RO_descriptor_number, member_vnf_index[:23])
710 vnf_index_2_RO_id[member_vnf_index] = vnfd_id_RO
711 RO_descriptor_number += 1
kuused124bfe2019-06-18 12:09:24 +0200712
tiernod8323042019-08-09 11:32:23 +0000713 # look position at deployed.RO.vnfd if not present it will be appended at the end
714 for index, vnf_deployed in enumerate(db_nsr["_admin"]["deployed"]["RO"]["vnfd"]):
715 if vnf_deployed["member-vnf-index"] == member_vnf_index:
716 break
717 else:
718 index = len(db_nsr["_admin"]["deployed"]["RO"]["vnfd"])
719 db_nsr["_admin"]["deployed"]["RO"]["vnfd"].append(None)
720
721 # look if present
722 RO_update = {"member-vnf-index": member_vnf_index}
723 vnfd_list = await self.RO.get_list("vnfd", filter_by={"osm_id": vnfd_id_RO})
724 if vnfd_list:
725 RO_update["id"] = vnfd_list[0]["uuid"]
726 self.logger.debug(logging_text + "vnfd='{}' member_vnf_index='{}' exists at RO. Using RO_id={}".
727 format(vnfd_ref, member_vnf_index, vnfd_list[0]["uuid"]))
728 else:
729 vnfd_RO = self.vnfd2RO(vnfd, vnfd_id_RO, db_vnfrs[c_vnf["member-vnf-index"]].
730 get("additionalParamsForVnf"), nsr_id)
731 desc = await self.RO.create("vnfd", descriptor=vnfd_RO)
732 RO_update["id"] = desc["uuid"]
733 self.logger.debug(logging_text + "vnfd='{}' member_vnf_index='{}' created at RO. RO_id={}".format(
734 vnfd_ref, member_vnf_index, desc["uuid"]))
735 db_nsr_update["_admin.deployed.RO.vnfd.{}".format(index)] = RO_update
736 db_nsr["_admin"]["deployed"]["RO"]["vnfd"][index] = RO_update
737 self.update_db_2("nsrs", nsr_id, db_nsr_update)
calvinosanch9f9c6f22019-11-04 13:37:39 +0100738 self._on_update_n2vc_db("nsrs", {"_id": nsr_id}, "_admin.deployed", db_nsr_update)
tiernod8323042019-08-09 11:32:23 +0000739
740 # create nsd at RO
741 nsd_ref = nsd["id"]
calvinosanch9f9c6f22019-11-04 13:37:39 +0100742 step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Creating nsd={} at RO".format(nsd_ref)
tiernod8323042019-08-09 11:32:23 +0000743 # self.logger.debug(logging_text + step)
744
745 RO_osm_nsd_id = "{}.{}.{}".format(nsr_id, RO_descriptor_number, nsd_ref[:23])
746 RO_descriptor_number += 1
747 nsd_list = await self.RO.get_list("nsd", filter_by={"osm_id": RO_osm_nsd_id})
748 if nsd_list:
749 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = nsd_list[0]["uuid"]
750 self.logger.debug(logging_text + "nsd={} exists at RO. Using RO_id={}".format(
751 nsd_ref, RO_nsd_uuid))
752 else:
753 nsd_RO = deepcopy(nsd)
754 nsd_RO["id"] = RO_osm_nsd_id
755 nsd_RO.pop("_id", None)
756 nsd_RO.pop("_admin", None)
757 for c_vnf in nsd_RO.get("constituent-vnfd", ()):
758 member_vnf_index = c_vnf["member-vnf-index"]
759 c_vnf["vnfd-id-ref"] = vnf_index_2_RO_id[member_vnf_index]
760 for c_vld in nsd_RO.get("vld", ()):
761 for cp in c_vld.get("vnfd-connection-point-ref", ()):
762 member_vnf_index = cp["member-vnf-index-ref"]
763 cp["vnfd-id-ref"] = vnf_index_2_RO_id[member_vnf_index]
764
765 desc = await self.RO.create("nsd", descriptor=nsd_RO)
766 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
767 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = desc["uuid"]
768 self.logger.debug(logging_text + "nsd={} created at RO. RO_id={}".format(nsd_ref, RO_nsd_uuid))
769 self.update_db_2("nsrs", nsr_id, db_nsr_update)
calvinosanch9f9c6f22019-11-04 13:37:39 +0100770 self._on_update_n2vc_db("nsrs", {"_id": nsr_id}, "_admin.deployed", db_nsr_update)
tiernod8323042019-08-09 11:32:23 +0000771
772 # Crate ns at RO
773 # if present use it unless in error status
774 RO_nsr_id = deep_get(db_nsr, ("_admin", "deployed", "RO", "nsr_id"))
775 if RO_nsr_id:
776 try:
calvinosanch9f9c6f22019-11-04 13:37:39 +0100777 step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Looking for existing ns at RO"
tiernod8323042019-08-09 11:32:23 +0000778 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
779 desc = await self.RO.show("ns", RO_nsr_id)
780 except ROclient.ROClientException as e:
781 if e.http_code != HTTPStatus.NOT_FOUND:
782 raise
783 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
784 if RO_nsr_id:
785 ns_status, ns_status_info = self.RO.check_ns_status(desc)
786 db_nsr_update["_admin.deployed.RO.nsr_status"] = ns_status
787 if ns_status == "ERROR":
calvinosanch9f9c6f22019-11-04 13:37:39 +0100788 step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Deleting ns at RO. RO_ns_id={}"\
789 .format(RO_nsr_id)
tiernod8323042019-08-09 11:32:23 +0000790 self.logger.debug(logging_text + step)
791 await self.RO.delete("ns", RO_nsr_id)
792 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
793 if not RO_nsr_id:
calvinosanch9f9c6f22019-11-04 13:37:39 +0100794 step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Checking dependencies"
tiernod8323042019-08-09 11:32:23 +0000795 # self.logger.debug(logging_text + step)
796
797 # check if VIM is creating and wait look if previous tasks in process
798 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account", ns_params["vimAccountId"])
799 if task_dependency:
800 step = "Waiting for related tasks to be completed: {}".format(task_name)
801 self.logger.debug(logging_text + step)
802 await asyncio.wait(task_dependency, timeout=3600)
803 if ns_params.get("vnf"):
804 for vnf in ns_params["vnf"]:
805 if "vimAccountId" in vnf:
806 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account",
807 vnf["vimAccountId"])
808 if task_dependency:
809 step = "Waiting for related tasks to be completed: {}".format(task_name)
810 self.logger.debug(logging_text + step)
811 await asyncio.wait(task_dependency, timeout=3600)
812
calvinosanch9f9c6f22019-11-04 13:37:39 +0100813 step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Checking instantiation parameters"
tiernod8323042019-08-09 11:32:23 +0000814
815 RO_ns_params = self.ns_params_2_RO(ns_params, nsd, db_vnfds_ref, n2vc_key_list)
816
817 step = db_nsr_update["detailed-status"] = "Deploying ns at VIM"
calvinosanch9f9c6f22019-11-04 13:37:39 +0100818 # step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Deploying ns at VIM"
quilesj7e13aeb2019-10-08 13:34:55 +0200819 desc = await self.RO.create("ns", descriptor=RO_ns_params, name=db_nsr["name"], scenario=RO_nsd_uuid)
tiernod8323042019-08-09 11:32:23 +0000820 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = desc["uuid"]
821 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
822 db_nsr_update["_admin.deployed.RO.nsr_status"] = "BUILD"
823 self.logger.debug(logging_text + "ns created at RO. RO_id={}".format(desc["uuid"]))
824 self.update_db_2("nsrs", nsr_id, db_nsr_update)
calvinosanch9f9c6f22019-11-04 13:37:39 +0100825 self._on_update_n2vc_db("nsrs", {"_id": nsr_id}, "_admin.deployed", db_nsr_update)
tiernod8323042019-08-09 11:32:23 +0000826
827 # wait until NS is ready
828 step = ns_status_detailed = detailed_status = "Waiting VIM to deploy ns. RO_ns_id={}".format(RO_nsr_id)
829 detailed_status_old = None
830 self.logger.debug(logging_text + step)
831
832 while time() <= start_deploy + self.total_deploy_timeout:
833 desc = await self.RO.show("ns", RO_nsr_id)
834 ns_status, ns_status_info = self.RO.check_ns_status(desc)
835 db_nsr_update["_admin.deployed.RO.nsr_status"] = ns_status
836 if ns_status == "ERROR":
837 raise ROclient.ROClientException(ns_status_info)
838 elif ns_status == "BUILD":
839 detailed_status = ns_status_detailed + "; {}".format(ns_status_info)
840 elif ns_status == "ACTIVE":
841 step = detailed_status = "Waiting for management IP address reported by the VIM. Updating VNFRs"
842 try:
calvinosanch9f9c6f22019-11-04 13:37:39 +0100843 if vdu_flag:
844 self.ns_update_vnfr(db_vnfrs, desc)
tiernod8323042019-08-09 11:32:23 +0000845 break
846 except LcmExceptionNoMgmtIP:
847 pass
848 else:
849 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
850 if detailed_status != detailed_status_old:
calvinosanch9f9c6f22019-11-04 13:37:39 +0100851 detailed_status_old = db_nsr_update["_admin.deployed.RO.detailed-status"] = detailed_status
tiernod8323042019-08-09 11:32:23 +0000852 self.update_db_2("nsrs", nsr_id, db_nsr_update)
calvinosanch9f9c6f22019-11-04 13:37:39 +0100853 self._on_update_n2vc_db("nsrs", {"_id": nsr_id}, "_admin.deployed", db_nsr_update)
tiernod8323042019-08-09 11:32:23 +0000854 await asyncio.sleep(5, loop=self.loop)
855 else: # total_deploy_timeout
856 raise ROclient.ROClientException("Timeout waiting ns to be ready")
857
858 step = "Updating NSR"
859 self.ns_update_nsr(db_nsr_update, db_nsr, desc)
860
calvinosanch9f9c6f22019-11-04 13:37:39 +0100861 db_nsr_update["_admin.deployed.RO.operational-status"] = "running"
862 db_nsr["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
863 db_nsr_update["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
tiernod8323042019-08-09 11:32:23 +0000864 self.update_db_2("nsrs", nsr_id, db_nsr_update)
calvinosanch9f9c6f22019-11-04 13:37:39 +0100865 self._on_update_n2vc_db("nsrs", {"_id": nsr_id}, "_admin.deployed", db_nsr_update)
quilesj7e13aeb2019-10-08 13:34:55 +0200866
867 step = "Deployed at VIM"
868 self.logger.debug(logging_text + step)
869
tiernoa5088192019-11-26 16:12:53 +0000870 async def wait_vm_up_insert_key_ro(self, logging_text, nsr_id, vnfr_id, vdu_id, vdu_index, pub_key=None, user=None):
871 """
872 Wait for ip addres at RO, and optionally, insert public key in virtual machine
873 :param logging_text: prefix use for logging
874 :param nsr_id:
875 :param vnfr_id:
876 :param vdu_id:
877 :param vdu_index:
878 :param pub_key: public ssh key to inject, None to skip
879 :param user: user to apply the public ssh key
880 :return: IP address
881 """
quilesj7e13aeb2019-10-08 13:34:55 +0200882
tiernoa5088192019-11-26 16:12:53 +0000883 # self.logger.debug(logging_text + "Starting wait_vm_up_insert_key_ro")
tiernod8323042019-08-09 11:32:23 +0000884 ro_nsr_id = None
885 ip_address = None
886 nb_tries = 0
887 target_vdu_id = None
quilesj7e13aeb2019-10-08 13:34:55 +0200888
tiernod8323042019-08-09 11:32:23 +0000889 while True:
quilesj7e13aeb2019-10-08 13:34:55 +0200890
tiernod8323042019-08-09 11:32:23 +0000891 await asyncio.sleep(10, loop=self.loop)
quilesj7e13aeb2019-10-08 13:34:55 +0200892 # wait until NS is deployed at RO
tiernod8323042019-08-09 11:32:23 +0000893 if not ro_nsr_id:
894 db_nsrs = self.db.get_one("nsrs", {"_id": nsr_id})
895 ro_nsr_id = deep_get(db_nsrs, ("_admin", "deployed", "RO", "nsr_id"))
896 if not ro_nsr_id:
897 continue
quilesj7e13aeb2019-10-08 13:34:55 +0200898
899 # get ip address
tiernod8323042019-08-09 11:32:23 +0000900 if not target_vdu_id:
901 db_vnfr = self.db.get_one("vnfrs", {"_id": vnfr_id})
902 if not vdu_id:
903 ip_address = db_vnfr.get("ip-address")
904 if not ip_address:
905 continue
906 for vdur in get_iterable(db_vnfr, "vdur"):
907 if (vdur["vdu-id-ref"] == vdu_id and vdur["count-index"] == vdu_index) or \
908 (ip_address and vdur.get("ip-address") == ip_address):
909 if vdur["status"] == "ACTIVE":
910 target_vdu_id = vdur["vdu-id-ref"]
911 elif vdur["status"] == "ERROR":
912 raise LcmException("Cannot inject ssh-key because target VM is in error state")
913 break
914 else:
915 raise LcmException("Not found vnfr_id={}, vdu_index={}, vdu_index={}".format(
916 vnfr_id, vdu_id, vdu_index
917 ))
quilesj7e13aeb2019-10-08 13:34:55 +0200918
tiernod8323042019-08-09 11:32:23 +0000919 if not target_vdu_id:
920 continue
tiernod8323042019-08-09 11:32:23 +0000921
tiernoa5088192019-11-26 16:12:53 +0000922 # self.logger.debug(logging_text + "IP address={}".format(ip_address))
calvinosanch9f9c6f22019-11-04 13:37:39 +0100923
quilesj7e13aeb2019-10-08 13:34:55 +0200924 # inject public key into machine
925 if pub_key and user:
tiernoa5088192019-11-26 16:12:53 +0000926 # self.logger.debug(logging_text + "Inserting RO key")
quilesj7e13aeb2019-10-08 13:34:55 +0200927 try:
928 ro_vm_id = "{}-{}".format(db_vnfr["member-vnf-index-ref"], target_vdu_id) # TODO add vdu_index
929 result_dict = await self.RO.create_action(
930 item="ns",
931 item_id_name=ro_nsr_id,
932 descriptor={"add_public_key": pub_key, "vms": [ro_vm_id], "user": user}
933 )
934 # result_dict contains the format {VM-id: {vim_result: 200, description: text}}
935 if not result_dict or not isinstance(result_dict, dict):
936 raise LcmException("Unknown response from RO when injecting key")
937 for result in result_dict.values():
938 if result.get("vim_result") == 200:
939 break
940 else:
941 raise ROclient.ROClientException("error injecting key: {}".format(
942 result.get("description")))
943 break
944 except ROclient.ROClientException as e:
tiernoa5088192019-11-26 16:12:53 +0000945 if not nb_tries:
946 self.logger.debug(logging_text + "error injecting key: {}. Retrying until {} seconds".
947 format(e, 20*10))
quilesj7e13aeb2019-10-08 13:34:55 +0200948 nb_tries += 1
tiernoa5088192019-11-26 16:12:53 +0000949 if nb_tries >= 20:
quilesj7e13aeb2019-10-08 13:34:55 +0200950 raise LcmException("Reaching max tries injecting key. Error: {}".format(e))
quilesj7e13aeb2019-10-08 13:34:55 +0200951 else:
quilesj7e13aeb2019-10-08 13:34:55 +0200952 break
953
954 return ip_address
955
956 async def instantiate_N2VC(self, logging_text, vca_index, nsi_id, db_nsr, db_vnfr, vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +0100957 kdu_name, vdu_index, config_descriptor, deploy_params, base_folder):
tiernod8323042019-08-09 11:32:23 +0000958 nsr_id = db_nsr["_id"]
959 db_update_entry = "_admin.deployed.VCA.{}.".format(vca_index)
tiernoda6fb102019-11-23 00:36:52 +0000960 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
tiernod8323042019-08-09 11:32:23 +0000961 vca_deployed = db_nsr["_admin"]["deployed"]["VCA"][vca_index]
quilesj7e13aeb2019-10-08 13:34:55 +0200962 db_dict = {
963 'collection': 'nsrs',
964 'filter': {'_id': nsr_id},
965 'path': db_update_entry
966 }
tiernoda6fb102019-11-23 00:36:52 +0000967 logging_text += "member_vnf_index={} vdu_id={}, vdu_index={} ".format(db_vnfr["member-vnf-index-ref"],
968 vdu_id, vdu_index)
quilesj7e13aeb2019-10-08 13:34:55 +0200969
tiernod8323042019-08-09 11:32:23 +0000970 step = ""
971 try:
972 vnfr_id = None
973 if db_vnfr:
974 vnfr_id = db_vnfr["_id"]
975
976 namespace = "{nsi}.{ns}".format(
977 nsi=nsi_id if nsi_id else "",
978 ns=nsr_id)
979 if vnfr_id:
980 namespace += "." + vnfr_id
981 if vdu_id:
982 namespace += ".{}-{}".format(vdu_id, vdu_index or 0)
983
984 # Get artifact path
quilesj7e13aeb2019-10-08 13:34:55 +0200985 artifact_path = "/{}/{}/charms/{}".format(
tiernod8323042019-08-09 11:32:23 +0000986 base_folder["folder"],
987 base_folder["pkg-dir"],
988 config_descriptor["juju"]["charm"]
989 )
990
quilesj7e13aeb2019-10-08 13:34:55 +0200991 is_proxy_charm = deep_get(config_descriptor, ('juju', 'charm')) is not None
992 if deep_get(config_descriptor, ('juju', 'proxy')) is False:
tiernod8323042019-08-09 11:32:23 +0000993 is_proxy_charm = False
994
995 # n2vc_redesign STEP 3.1
quilesj7e13aeb2019-10-08 13:34:55 +0200996
997 # find old ee_id if exists
tiernod8323042019-08-09 11:32:23 +0000998 ee_id = vca_deployed.get("ee_id")
tiernod8323042019-08-09 11:32:23 +0000999
quilesj7e13aeb2019-10-08 13:34:55 +02001000 # create or register execution environment in VCA
1001 if is_proxy_charm:
1002 step = "create execution environment"
1003 self.logger.debug(logging_text + step)
1004 ee_id, credentials = await self.n2vc.create_execution_environment(
1005 namespace=namespace,
1006 reuse_ee_id=ee_id,
1007 db_dict=db_dict
1008 )
tiernod8323042019-08-09 11:32:23 +00001009
quilesj7e13aeb2019-10-08 13:34:55 +02001010 else:
tiernoda6fb102019-11-23 00:36:52 +00001011 step = "register execution environment"
quilesj7e13aeb2019-10-08 13:34:55 +02001012 # TODO wait until deployed by RO, when IP address has been filled. By pooling????
1013 credentials = {} # TODO db_credentials["ip_address"]
1014 # get username
1015 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1016 # merged. Meanwhile let's get username from initial-config-primitive
1017 if config_descriptor.get("initial-config-primitive"):
1018 for param in config_descriptor["initial-config-primitive"][0].get("parameter", ()):
1019 if param["name"] == "ssh-username":
1020 credentials["username"] = param["value"]
1021 if config_descriptor.get("config-access") and config_descriptor["config-access"].get("ssh-access"):
1022 if config_descriptor["config-access"]["ssh-access"].get("required"):
1023 credentials["username"] = \
1024 config_descriptor["config-access"]["ssh-access"].get("default-user")
1025
1026 # n2vc_redesign STEP 3.2
1027 self.logger.debug(logging_text + step)
1028 ee_id = await self.n2vc.register_execution_environment(
1029 credentials=credentials,
1030 namespace=namespace,
1031 db_dict=db_dict
1032 )
1033
1034 # for compatibility with MON/POL modules, the need model and application name at database
1035 # TODO ask to N2VC instead of assuming the format "model_name.application_name"
1036 ee_id_parts = ee_id.split('.')
1037 model_name = ee_id_parts[0]
1038 application_name = ee_id_parts[1]
1039 self.update_db_2("nsrs", nsr_id, {db_update_entry + "model": model_name,
1040 db_update_entry + "application": application_name,
1041 db_update_entry + "ee_id": ee_id})
tiernod8323042019-08-09 11:32:23 +00001042
1043 # n2vc_redesign STEP 3.3
1044 # TODO check if already done
1045 step = "Install configuration Software"
quilesj7e13aeb2019-10-08 13:34:55 +02001046 self.logger.debug(logging_text + step)
1047 await self.n2vc.install_configuration_sw(
1048 ee_id=ee_id,
1049 artifact_path=artifact_path,
1050 db_dict=db_dict
1051 )
1052
1053 # if SSH access is required, then get execution environment SSH public
1054 required = deep_get(config_descriptor, ("config-access", "ssh-access", "required"))
tiernoa5088192019-11-26 16:12:53 +00001055 pub_key = None
1056 user = None
quilesj7e13aeb2019-10-08 13:34:55 +02001057 if is_proxy_charm and required:
tiernoa5088192019-11-26 16:12:53 +00001058 user = deep_get(config_descriptor, ("config-access", "ssh-access", "default-user"))
1059 step = "Install configuration Software, getting public ssh key"
quilesj7e13aeb2019-10-08 13:34:55 +02001060 pub_key = await self.n2vc.get_ee_ssh_public__key(
1061 ee_id=ee_id,
1062 db_dict=db_dict
1063 )
1064
quilesj7e13aeb2019-10-08 13:34:55 +02001065 step = "Insert public key into VM"
tiernoa5088192019-11-26 16:12:53 +00001066 else:
1067 step = "Waiting to VM being up and getting IP address"
1068 self.logger.debug(logging_text + step)
quilesj7e13aeb2019-10-08 13:34:55 +02001069
tiernoa5088192019-11-26 16:12:53 +00001070 # n2vc_redesign STEP 5.1
1071 # wait for RO (ip-address) Insert pub_key into VM
1072 rw_mgmt_ip = await self.wait_vm_up_insert_key_ro(
quilesj7e13aeb2019-10-08 13:34:55 +02001073 logging_text=logging_text,
1074 nsr_id=nsr_id,
1075 vnfr_id=vnfr_id,
1076 vdu_id=vdu_id,
1077 vdu_index=vdu_index,
1078 user=user,
1079 pub_key=pub_key
1080 )
tiernoa5088192019-11-26 16:12:53 +00001081 self.logger.debug(logging_text + ' VM_ip_address={}'.format(rw_mgmt_ip))
quilesj7e13aeb2019-10-08 13:34:55 +02001082
tiernoa5088192019-11-26 16:12:53 +00001083 # store rw_mgmt_ip in deploy params for later replacement
quilesj7e13aeb2019-10-08 13:34:55 +02001084 deploy_params["rw_mgmt_ip"] = rw_mgmt_ip
tiernod8323042019-08-09 11:32:23 +00001085
1086 # n2vc_redesign STEP 6 Execute initial config primitive
quilesj7e13aeb2019-10-08 13:34:55 +02001087 step = 'execute initial config primitive'
tiernoa5088192019-11-26 16:12:53 +00001088 initial_config_primitive_list = config_descriptor.get('initial-config-primitive')
quilesj7e13aeb2019-10-08 13:34:55 +02001089
1090 # sort initial config primitives by 'seq'
1091 try:
1092 initial_config_primitive_list.sort(key=lambda val: int(val['seq']))
tiernoa5088192019-11-26 16:12:53 +00001093 except Exception as e:
1094 self.logger.error(logging_text + step + ": " + str(e))
quilesj7e13aeb2019-10-08 13:34:55 +02001095
tiernoda6fb102019-11-23 00:36:52 +00001096 # add config if not present for NS charm
1097 initial_config_primitive_list = self._get_initial_config_primitive_list(initial_config_primitive_list,
1098 vca_deployed)
1099
tiernod8323042019-08-09 11:32:23 +00001100 for initial_config_primitive in initial_config_primitive_list:
tiernoda6fb102019-11-23 00:36:52 +00001101 # adding information on the vca_deployed if it is a NS execution environment
1102 if not vca_deployed["member-vnf-index"]:
1103 deploy_params["ns_config_info"] = self._get_ns_config_info(vca_deployed_list)
tiernod8323042019-08-09 11:32:23 +00001104 # TODO check if already done
1105 primitive_params_ = self._map_primitive_params(initial_config_primitive, {}, deploy_params)
1106 step = "execute primitive '{}' params '{}'".format(initial_config_primitive["name"], primitive_params_)
1107 self.logger.debug(logging_text + step)
quilesj7e13aeb2019-10-08 13:34:55 +02001108 await self.n2vc.exec_primitive(
1109 ee_id=ee_id,
1110 primitive_name=initial_config_primitive["name"],
1111 params_dict=primitive_params_,
1112 db_dict=db_dict
1113 )
tiernod8323042019-08-09 11:32:23 +00001114 # TODO register in database that primitive is done
quilesj7e13aeb2019-10-08 13:34:55 +02001115
1116 step = "instantiated at VCA"
1117 self.logger.debug(logging_text + step)
1118
tiernod8323042019-08-09 11:32:23 +00001119 except Exception as e: # TODO not use Exception but N2VC exception
quilesj7e13aeb2019-10-08 13:34:55 +02001120 raise Exception("{} {}".format(step, e)) from e
tiernod8323042019-08-09 11:32:23 +00001121 # TODO raise N2VC exception with 'step' extra information
1122
tierno59d22d22018-09-25 18:10:19 +02001123 async def instantiate(self, nsr_id, nslcmop_id):
quilesj7e13aeb2019-10-08 13:34:55 +02001124 """
1125
1126 :param nsr_id: ns instance to deploy
1127 :param nslcmop_id: operation to run
1128 :return:
1129 """
kuused124bfe2019-06-18 12:09:24 +02001130
1131 # Try to lock HA task here
1132 task_is_locked_by_me = self.lcm_tasks.lock_HA('ns', 'nslcmops', nslcmop_id)
1133 if not task_is_locked_by_me:
quilesj7e13aeb2019-10-08 13:34:55 +02001134 self.logger.debug('instantiate() task is not locked by me')
kuused124bfe2019-06-18 12:09:24 +02001135 return
1136
tierno59d22d22018-09-25 18:10:19 +02001137 logging_text = "Task ns={} instantiate={} ".format(nsr_id, nslcmop_id)
1138 self.logger.debug(logging_text + "Enter")
quilesj7e13aeb2019-10-08 13:34:55 +02001139
tierno59d22d22018-09-25 18:10:19 +02001140 # get all needed from database
quilesj7e13aeb2019-10-08 13:34:55 +02001141
1142 # database nsrs record
tierno59d22d22018-09-25 18:10:19 +02001143 db_nsr = None
quilesj7e13aeb2019-10-08 13:34:55 +02001144
1145 # database nslcmops record
tierno59d22d22018-09-25 18:10:19 +02001146 db_nslcmop = None
quilesj7e13aeb2019-10-08 13:34:55 +02001147
1148 # update operation on nsrs
calvinosanch9f9c6f22019-11-04 13:37:39 +01001149 db_nsr_update = {"_admin.nslcmop": nslcmop_id,
1150 "_admin.current-operation": nslcmop_id,
1151 "_admin.operation-type": "instantiate"}
1152 self.update_db_2("nsrs", nsr_id, db_nsr_update)
quilesj7e13aeb2019-10-08 13:34:55 +02001153
1154 # update operation on nslcmops
tierno59d22d22018-09-25 18:10:19 +02001155 db_nslcmop_update = {}
quilesj7e13aeb2019-10-08 13:34:55 +02001156
tierno59d22d22018-09-25 18:10:19 +02001157 nslcmop_operation_state = None
quilesj7e13aeb2019-10-08 13:34:55 +02001158 db_vnfrs = {} # vnf's info indexed by member-index
1159 # n2vc_info = {}
tiernod8323042019-08-09 11:32:23 +00001160 task_instantiation_list = []
tierno59d22d22018-09-25 18:10:19 +02001161 exc = None
1162 try:
kuused124bfe2019-06-18 12:09:24 +02001163 # wait for any previous tasks in process
tierno3cf81a32019-11-11 17:07:00 +00001164 step = "Waiting for previous operations to terminate"
kuused124bfe2019-06-18 12:09:24 +02001165 await self.lcm_tasks.waitfor_related_HA('ns', 'nslcmops', nslcmop_id)
1166
quilesj7e13aeb2019-10-08 13:34:55 +02001167 # STEP 0: Reading database (nslcmops, nsrs, nsds, vnfrs, vnfds)
1168
1169 # read from db: operation
tierno59d22d22018-09-25 18:10:19 +02001170 step = "Getting nslcmop={} from db".format(nslcmop_id)
1171 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
quilesj7e13aeb2019-10-08 13:34:55 +02001172
1173 # read from db: ns
tierno59d22d22018-09-25 18:10:19 +02001174 step = "Getting nsr={} from db".format(nsr_id)
1175 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
quilesj7e13aeb2019-10-08 13:34:55 +02001176 # nsd is replicated into ns (no db read)
tierno59d22d22018-09-25 18:10:19 +02001177 nsd = db_nsr["nsd"]
tiernod8323042019-08-09 11:32:23 +00001178 # nsr_name = db_nsr["name"] # TODO short-name??
tierno47e86b52018-10-10 14:05:55 +02001179
quilesj7e13aeb2019-10-08 13:34:55 +02001180 # read from db: vnf's of this ns
tierno27246d82018-09-27 15:59:09 +02001181 step = "Getting vnfrs from db"
calvinosanch9f9c6f22019-11-04 13:37:39 +01001182 self.logger.debug(logging_text + step)
tierno27246d82018-09-27 15:59:09 +02001183 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
tierno27246d82018-09-27 15:59:09 +02001184
quilesj7e13aeb2019-10-08 13:34:55 +02001185 # read from db: vnfd's for every vnf
1186 db_vnfds_ref = {} # every vnfd data indexed by vnf name
1187 db_vnfds = {} # every vnfd data indexed by vnf id
1188 db_vnfds_index = {} # every vnfd data indexed by vnf member-index
1189
1190 # for each vnf in ns, read vnfd
tierno27246d82018-09-27 15:59:09 +02001191 for vnfr in db_vnfrs_list:
quilesj7e13aeb2019-10-08 13:34:55 +02001192 db_vnfrs[vnfr["member-vnf-index-ref"]] = vnfr # vnf's dict indexed by member-index: '1', '2', etc
1193 vnfd_id = vnfr["vnfd-id"] # vnfd uuid for this vnf
1194 vnfd_ref = vnfr["vnfd-ref"] # vnfd name for this vnf
1195 # if we haven't this vnfd, read it from db
tierno27246d82018-09-27 15:59:09 +02001196 if vnfd_id not in db_vnfds:
quilesj7e13aeb2019-10-08 13:34:55 +02001197 # read from cb
tierno27246d82018-09-27 15:59:09 +02001198 step = "Getting vnfd={} id='{}' from db".format(vnfd_id, vnfd_ref)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001199 self.logger.debug(logging_text + step)
tierno27246d82018-09-27 15:59:09 +02001200 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
tierno27246d82018-09-27 15:59:09 +02001201
quilesj7e13aeb2019-10-08 13:34:55 +02001202 # store vnfd
1203 db_vnfds_ref[vnfd_ref] = vnfd # vnfd's indexed by name
1204 db_vnfds[vnfd_id] = vnfd # vnfd's indexed by id
1205 db_vnfds_index[vnfr["member-vnf-index-ref"]] = db_vnfds[vnfd_id] # vnfd's indexed by member-index
1206
1207 # Get or generates the _admin.deployed.VCA list
tiernoe4f7e6c2018-11-27 14:55:30 +00001208 vca_deployed_list = None
1209 if db_nsr["_admin"].get("deployed"):
1210 vca_deployed_list = db_nsr["_admin"]["deployed"].get("VCA")
1211 if vca_deployed_list is None:
1212 vca_deployed_list = []
1213 db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
quilesj7e13aeb2019-10-08 13:34:55 +02001214 # add _admin.deployed.VCA to db_nsr dictionary, value=vca_deployed_list
tierno98ad6ea2019-05-30 17:16:28 +00001215 populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
tiernoe4f7e6c2018-11-27 14:55:30 +00001216 elif isinstance(vca_deployed_list, dict):
1217 # maintain backward compatibility. Change a dict to list at database
1218 vca_deployed_list = list(vca_deployed_list.values())
1219 db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
tierno98ad6ea2019-05-30 17:16:28 +00001220 populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
tiernoe4f7e6c2018-11-27 14:55:30 +00001221
tierno59d22d22018-09-25 18:10:19 +02001222 db_nsr_update["detailed-status"] = "creating"
1223 db_nsr_update["operational-status"] = "init"
quilesj7e13aeb2019-10-08 13:34:55 +02001224
tierno6cf25f52019-09-12 09:33:40 +00001225 if not isinstance(deep_get(db_nsr, ("_admin", "deployed", "RO", "vnfd")), list):
tiernoa009e552019-01-30 16:45:44 +00001226 populate_dict(db_nsr, ("_admin", "deployed", "RO", "vnfd"), [])
1227 db_nsr_update["_admin.deployed.RO.vnfd"] = []
tierno59d22d22018-09-25 18:10:19 +02001228
tiernobaa51102018-12-14 13:16:18 +00001229 # set state to INSTANTIATED. When instantiated NBI will not delete directly
1230 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
1231 self.update_db_2("nsrs", nsr_id, db_nsr_update)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001232 self.logger.debug(logging_text + "Before deploy_kdus")
1233 db_k8scluster_list = self.db.get_list("k8sclusters", {})
1234 # Call to deploy_kdus in case exists the "vdu:kdu" param
1235 task_kdu = asyncio.ensure_future(
1236 self.deploy_kdus(
1237 logging_text=logging_text,
1238 nsr_id=nsr_id,
1239 nsd=nsd,
1240 db_nsr=db_nsr,
1241 db_nslcmop=db_nslcmop,
1242 db_vnfrs=db_vnfrs,
1243 db_vnfds_ref=db_vnfds_ref,
1244 db_k8scluster=db_k8scluster_list
tierno98ad6ea2019-05-30 17:16:28 +00001245 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001246 )
1247 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "instantiate_KDUs", task_kdu)
1248 task_instantiation_list.append(task_kdu)
tiernod8323042019-08-09 11:32:23 +00001249 # n2vc_redesign STEP 1 Get VCA public ssh-key
1250 # feature 1429. Add n2vc public key to needed VMs
quilesj7e13aeb2019-10-08 13:34:55 +02001251 n2vc_key = await self.n2vc.get_public_key()
tiernoa5088192019-11-26 16:12:53 +00001252 n2vc_key_list = [n2vc_key]
1253 if self.vca_config.get("public_key"):
1254 n2vc_key_list.append(self.vca_config["public_key"])
tierno98ad6ea2019-05-30 17:16:28 +00001255
tiernod8323042019-08-09 11:32:23 +00001256 # n2vc_redesign STEP 2 Deploy Network Scenario
1257 task_ro = asyncio.ensure_future(
quilesj7e13aeb2019-10-08 13:34:55 +02001258 self.instantiate_RO(
1259 logging_text=logging_text,
1260 nsr_id=nsr_id,
1261 nsd=nsd,
1262 db_nsr=db_nsr,
1263 db_nslcmop=db_nslcmop,
1264 db_vnfrs=db_vnfrs,
1265 db_vnfds_ref=db_vnfds_ref,
tiernoa5088192019-11-26 16:12:53 +00001266 n2vc_key_list=n2vc_key_list
tierno98ad6ea2019-05-30 17:16:28 +00001267 )
tiernod8323042019-08-09 11:32:23 +00001268 )
1269 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "instantiate_RO", task_ro)
1270 task_instantiation_list.append(task_ro)
tierno98ad6ea2019-05-30 17:16:28 +00001271
tiernod8323042019-08-09 11:32:23 +00001272 # n2vc_redesign STEP 3 to 6 Deploy N2VC
tierno98ad6ea2019-05-30 17:16:28 +00001273 step = "Looking for needed vnfd to configure with proxy charm"
1274 self.logger.debug(logging_text + step)
1275
tiernod8323042019-08-09 11:32:23 +00001276 nsi_id = None # TODO put nsi_id when this nsr belongs to a NSI
quilesj7e13aeb2019-10-08 13:34:55 +02001277 # get_iterable() returns a value from a dict or empty tuple if key does not exist
tierno98ad6ea2019-05-30 17:16:28 +00001278 for c_vnf in get_iterable(nsd, "constituent-vnfd"):
1279 vnfd_id = c_vnf["vnfd-id-ref"]
tierno98ad6ea2019-05-30 17:16:28 +00001280 vnfd = db_vnfds_ref[vnfd_id]
tiernod8323042019-08-09 11:32:23 +00001281 member_vnf_index = str(c_vnf["member-vnf-index"])
1282 db_vnfr = db_vnfrs[member_vnf_index]
1283 base_folder = vnfd["_admin"]["storage"]
1284 vdu_id = None
1285 vdu_index = 0
tierno98ad6ea2019-05-30 17:16:28 +00001286 vdu_name = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01001287 kdu_name = None
tierno59d22d22018-09-25 18:10:19 +02001288
tierno8a518872018-12-21 13:42:14 +00001289 # Get additional parameters
tiernod8323042019-08-09 11:32:23 +00001290 deploy_params = {}
1291 if db_vnfr.get("additionalParamsForVnf"):
1292 deploy_params = db_vnfr["additionalParamsForVnf"].copy()
1293 for k, v in deploy_params.items():
tierno8a518872018-12-21 13:42:14 +00001294 if isinstance(v, str) and v.startswith("!!yaml "):
tiernod8323042019-08-09 11:32:23 +00001295 deploy_params[k] = yaml.safe_load(v[7:])
tierno8a518872018-12-21 13:42:14 +00001296
tiernod8323042019-08-09 11:32:23 +00001297 descriptor_config = vnfd.get("vnf-configuration")
1298 if descriptor_config and descriptor_config.get("juju"):
quilesj7e13aeb2019-10-08 13:34:55 +02001299 self._deploy_n2vc(
1300 logging_text=logging_text,
1301 db_nsr=db_nsr,
1302 db_vnfr=db_vnfr,
1303 nslcmop_id=nslcmop_id,
1304 nsr_id=nsr_id,
1305 nsi_id=nsi_id,
1306 vnfd_id=vnfd_id,
1307 vdu_id=vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01001308 kdu_name=kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02001309 member_vnf_index=member_vnf_index,
1310 vdu_index=vdu_index,
1311 vdu_name=vdu_name,
1312 deploy_params=deploy_params,
1313 descriptor_config=descriptor_config,
1314 base_folder=base_folder,
1315 task_instantiation_list=task_instantiation_list
1316 )
tierno59d22d22018-09-25 18:10:19 +02001317
1318 # Deploy charms for each VDU that supports one.
tiernod8323042019-08-09 11:32:23 +00001319 for vdud in get_iterable(vnfd, 'vdu'):
1320 vdu_id = vdud["id"]
1321 descriptor_config = vdud.get('vdu-configuration')
1322 if descriptor_config and descriptor_config.get("juju"):
1323 # look for vdu index in the db_vnfr["vdu"] section
1324 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
1325 # if vdur["vdu-id-ref"] == vdu_id:
1326 # break
1327 # else:
1328 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
1329 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
1330 # vdu_name = vdur.get("name")
1331 vdu_name = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01001332 kdu_name = None
tiernod8323042019-08-09 11:32:23 +00001333 for vdu_index in range(int(vdud.get("count", 1))):
1334 # TODO vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
quilesj7e13aeb2019-10-08 13:34:55 +02001335 self._deploy_n2vc(
1336 logging_text=logging_text,
1337 db_nsr=db_nsr,
1338 db_vnfr=db_vnfr,
1339 nslcmop_id=nslcmop_id,
1340 nsr_id=nsr_id,
1341 nsi_id=nsi_id,
1342 vnfd_id=vnfd_id,
1343 vdu_id=vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01001344 kdu_name=kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02001345 member_vnf_index=member_vnf_index,
1346 vdu_index=vdu_index,
1347 vdu_name=vdu_name,
1348 deploy_params=deploy_params,
1349 descriptor_config=descriptor_config,
1350 base_folder=base_folder,
1351 task_instantiation_list=task_instantiation_list
1352 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001353 for kdud in get_iterable(vnfd, 'kdu'):
1354 kdu_name = kdud["name"]
1355 descriptor_config = kdud.get('kdu-configuration')
1356 if descriptor_config and descriptor_config.get("juju"):
1357 vdu_id = None
1358 vdu_index = 0
1359 vdu_name = None
1360 # look for vdu index in the db_vnfr["vdu"] section
1361 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
1362 # if vdur["vdu-id-ref"] == vdu_id:
1363 # break
1364 # else:
1365 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
1366 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
1367 # vdu_name = vdur.get("name")
1368 # vdu_name = None
tierno59d22d22018-09-25 18:10:19 +02001369
calvinosanch9f9c6f22019-11-04 13:37:39 +01001370 self._deploy_n2vc(
1371 logging_text=logging_text,
1372 db_nsr=db_nsr,
1373 db_vnfr=db_vnfr,
1374 nslcmop_id=nslcmop_id,
1375 nsr_id=nsr_id,
1376 nsi_id=nsi_id,
1377 vnfd_id=vnfd_id,
1378 vdu_id=vdu_id,
1379 kdu_name=kdu_name,
1380 member_vnf_index=member_vnf_index,
1381 vdu_index=vdu_index,
1382 vdu_name=vdu_name,
1383 deploy_params=deploy_params,
1384 descriptor_config=descriptor_config,
1385 base_folder=base_folder,
1386 task_instantiation_list=task_instantiation_list
1387 )
tierno59d22d22018-09-25 18:10:19 +02001388
tierno1b633412019-02-25 16:48:23 +00001389 # Check if this NS has a charm configuration
tiernod8323042019-08-09 11:32:23 +00001390 descriptor_config = nsd.get("ns-configuration")
1391 if descriptor_config and descriptor_config.get("juju"):
1392 vnfd_id = None
1393 db_vnfr = None
1394 member_vnf_index = None
1395 vdu_id = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01001396 kdu_name = None
tiernod8323042019-08-09 11:32:23 +00001397 vdu_index = 0
1398 vdu_name = None
tierno1b633412019-02-25 16:48:23 +00001399
tiernod8323042019-08-09 11:32:23 +00001400 # Get additional parameters
1401 deploy_params = {}
1402 if db_nsr.get("additionalParamsForNs"):
1403 deploy_params = db_nsr["additionalParamsForNs"].copy()
1404 for k, v in deploy_params.items():
1405 if isinstance(v, str) and v.startswith("!!yaml "):
1406 deploy_params[k] = yaml.safe_load(v[7:])
1407 base_folder = nsd["_admin"]["storage"]
quilesj7e13aeb2019-10-08 13:34:55 +02001408 self._deploy_n2vc(
1409 logging_text=logging_text,
1410 db_nsr=db_nsr,
1411 db_vnfr=db_vnfr,
1412 nslcmop_id=nslcmop_id,
1413 nsr_id=nsr_id,
1414 nsi_id=nsi_id,
1415 vnfd_id=vnfd_id,
1416 vdu_id=vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01001417 kdu_name=kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02001418 member_vnf_index=member_vnf_index,
1419 vdu_index=vdu_index,
1420 vdu_name=vdu_name,
1421 deploy_params=deploy_params,
1422 descriptor_config=descriptor_config,
1423 base_folder=base_folder,
1424 task_instantiation_list=task_instantiation_list
1425 )
tierno1b633412019-02-25 16:48:23 +00001426
tiernod8323042019-08-09 11:32:23 +00001427 # Wait until all tasks of "task_instantiation_list" have been finished
tierno1b633412019-02-25 16:48:23 +00001428
tiernod8323042019-08-09 11:32:23 +00001429 # while time() <= start_deploy + self.total_deploy_timeout:
1430 error_text = None
1431 timeout = 3600 # time() - start_deploy
quilesj7e13aeb2019-10-08 13:34:55 +02001432 task_instantiation_set = set(task_instantiation_list) # build a set with tasks
1433 done = None
1434 pending = None
1435 if len(task_instantiation_set) > 0:
1436 done, pending = await asyncio.wait(task_instantiation_set, timeout=timeout)
tiernod8323042019-08-09 11:32:23 +00001437 if pending:
1438 error_text = "timeout"
1439 for task in done:
1440 if task.cancelled():
1441 if not error_text:
1442 error_text = "cancelled"
1443 elif task.done():
1444 exc = task.exception()
1445 if exc:
1446 error_text = str(exc)
tierno1b633412019-02-25 16:48:23 +00001447
tiernod8323042019-08-09 11:32:23 +00001448 if error_text:
1449 db_nsr_update["config-status"] = "failed"
1450 error_text = "fail configuring " + error_text
1451 db_nsr_update["detailed-status"] = error_text
1452 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED_TEMP"
1453 db_nslcmop_update["detailed-status"] = error_text
1454 db_nslcmop_update["statusEnteredTime"] = time()
1455 else:
tierno59d22d22018-09-25 18:10:19 +02001456 # all is done
1457 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
1458 db_nslcmop_update["statusEnteredTime"] = time()
1459 db_nslcmop_update["detailed-status"] = "done"
1460 db_nsr_update["config-status"] = "configured"
1461 db_nsr_update["detailed-status"] = "done"
1462
tierno59d22d22018-09-25 18:10:19 +02001463 except (ROclient.ROClientException, DbException, LcmException) as e:
1464 self.logger.error(logging_text + "Exit Exception while '{}': {}".format(step, e))
1465 exc = e
1466 except asyncio.CancelledError:
1467 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1468 exc = "Operation was cancelled"
1469 except Exception as e:
1470 exc = traceback.format_exc()
1471 self.logger.critical(logging_text + "Exit Exception {} while '{}': {}".format(type(e).__name__, step, e),
1472 exc_info=True)
1473 finally:
1474 if exc:
1475 if db_nsr:
1476 db_nsr_update["detailed-status"] = "ERROR {}: {}".format(step, exc)
1477 db_nsr_update["operational-status"] = "failed"
1478 if db_nslcmop:
1479 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
1480 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
1481 db_nslcmop_update["statusEnteredTime"] = time()
tiernobaa51102018-12-14 13:16:18 +00001482 try:
1483 if db_nsr:
1484 db_nsr_update["_admin.nslcmop"] = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01001485 db_nsr_update["_admin.current-operation"] = None
1486 db_nsr_update["_admin.operation-type"] = None
tiernobaa51102018-12-14 13:16:18 +00001487 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1488 if db_nslcmop_update:
1489 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1490 except DbException as e:
1491 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno59d22d22018-09-25 18:10:19 +02001492 if nslcmop_operation_state:
1493 try:
1494 await self.msg.aiowrite("ns", "instantiated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
tierno8a518872018-12-21 13:42:14 +00001495 "operationState": nslcmop_operation_state},
1496 loop=self.loop)
tierno59d22d22018-09-25 18:10:19 +02001497 except Exception as e:
1498 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1499
1500 self.logger.debug(logging_text + "Exit")
1501 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_instantiate")
1502
calvinosanch9f9c6f22019-11-04 13:37:39 +01001503 async def deploy_kdus(self, logging_text, nsr_id, nsd, db_nsr, db_nslcmop, db_vnfrs, db_vnfds_ref, db_k8scluster):
1504 # Launch kdus if present in the descriptor
1505 logging_text = "Deploy kdus: "
1506 db_nsr_update = {}
1507 db_nsr_update["_admin.deployed.K8s"] = []
1508 try:
1509 # Look for all vnfds
1510 # db_nsr_update["_admin.deployed.K8s"] = []
1511 vnf_update = []
1512 task_list = []
1513 for c_vnf in nsd.get("constituent-vnfd", ()):
1514 vnfr = db_vnfrs[c_vnf["member-vnf-index"]]
1515 member_vnf_index = c_vnf["member-vnf-index"]
1516 vnfd = db_vnfds_ref[c_vnf['vnfd-id-ref']]
1517 vnfd_ref = vnfd["id"]
1518 desc_params = {}
tiernobaa51102018-12-14 13:16:18 +00001519
calvinosanch9f9c6f22019-11-04 13:37:39 +01001520 step = "Checking kdu from vnf: {} - member-vnf-index: {}".format(vnfd_ref, member_vnf_index)
1521 self.logger.debug(logging_text + step)
1522 if vnfd.get("kdu"):
1523 step = "vnf: {} has kdus".format(vnfd_ref)
1524 self.logger.debug(logging_text + step)
1525 for vnfr_name, vnfr_data in db_vnfrs.items():
1526 if vnfr_data["vnfd-ref"] == vnfd["id"]:
1527 if vnfr_data.get("additionalParamsForVnf"):
1528 desc_params = self._format_additional_params(vnfr_data["additionalParamsForVnf"])
1529 break
1530 else:
1531 raise LcmException("VNF descriptor not found with id: {}".format(vnfr_data["vnfd-ref"]))
1532 self.logger.debug(logging_text + step)
1533
1534 for kdur in vnfr.get("kdur"):
1535 index = 0
1536 for k8scluster in db_k8scluster:
1537 if kdur["k8s-cluster"]["id"] == k8scluster["_id"]:
1538 cluster_uuid = k8scluster["cluster-uuid"]
1539 break
1540 else:
1541 raise LcmException("K8scluster not found with id: {}".format(kdur["k8s-cluster"]["id"]))
1542 self.logger.debug(logging_text + step)
1543
1544 step = "Instantiate KDU {} in k8s cluster {}".format(kdur["kdu-name"], cluster_uuid)
1545 self.logger.debug(logging_text + step)
1546 for kdu in vnfd.get("kdu"):
1547 if kdu.get("name") == kdur["kdu-name"]:
1548 break
1549 else:
1550 raise LcmException("KDU not found with name: {} in VNFD {}".format(kdur["kdu-name"],
1551 vnfd["name"]))
1552 self.logger.debug(logging_text + step)
1553 kdumodel = None
1554 k8sclustertype = None
1555 if kdu.get("helm-chart"):
1556 kdumodel = kdu["helm-chart"]
1557 k8sclustertype = "chart"
1558 elif kdu.get("juju-bundle"):
1559 kdumodel = kdu["juju-bundle"]
1560 k8sclustertype = "juju"
1561 k8s_instace_info = {"kdu-instance": None, "k8scluster-uuid": cluster_uuid,
1562 "vnfr-id": vnfr["id"], "k8scluster-type": k8sclustertype,
1563 "kdu-name": kdur["kdu-name"], "kdu-model": kdumodel}
1564 db_nsr_update["_admin.deployed.K8s"].append(k8s_instace_info)
1565 db_dict = {"collection": "nsrs", "filter": {"_id": nsr_id}, "path": "_admin.deployed.K8s."
1566 "{}".format(index)}
1567 if k8sclustertype == "chart":
tiernoda6fb102019-11-23 00:36:52 +00001568 task = self.k8sclusterhelm.install(cluster_uuid=cluster_uuid, kdu_model=kdumodel,
1569 atomic=True, params=desc_params,
1570 db_dict=db_dict, timeout=300)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001571 else:
1572 # TODO I need the juju connector in place
1573 pass
1574 task_list.append(task)
1575 index += 1
1576 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1577 done = None
1578 pending = None
1579 if len(task_list) > 0:
1580 self.logger.debug('Waiting for terminate pending tasks...')
1581 done, pending = await asyncio.wait(task_list, timeout=3600)
1582 if not pending:
1583 for fut in done:
1584 k8s_instance = fut.result()
1585 k8s_instace_info = {"kdu-instance": k8s_instance, "k8scluster-uuid": cluster_uuid,
1586 "vnfr-id": vnfr["id"], "k8scluster-type": k8sclustertype,
1587 "kdu-name": kdur["kdu-name"], "kdu-model": kdumodel}
1588 vnf_update.append(k8s_instace_info)
1589 self.logger.debug('All tasks finished...')
1590 else:
1591 self.logger.info('There are pending tasks: {}'.format(pending))
1592
1593 db_nsr_update["_admin.deployed.K8s"] = vnf_update
1594 except Exception as e:
1595 self.logger.critical(logging_text + "Exit Exception {} while '{}': {}".format(type(e).__name__, step, e))
1596 raise LcmException("{} Exit Exception {} while '{}': {}".format(logging_text, type(e).__name__, step, e))
1597 finally:
1598 # TODO Write in data base
1599 if db_nsr_update:
1600 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernoda6fb102019-11-23 00:36:52 +00001601
quilesj7e13aeb2019-10-08 13:34:55 +02001602 def _deploy_n2vc(self, logging_text, db_nsr, db_vnfr, nslcmop_id, nsr_id, nsi_id, vnfd_id, vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01001603 kdu_name, member_vnf_index, vdu_index, vdu_name, deploy_params, descriptor_config,
quilesj7e13aeb2019-10-08 13:34:55 +02001604 base_folder, task_instantiation_list):
1605 # launch instantiate_N2VC in a asyncio task and register task object
1606 # Look where information of this charm is at database <nsrs>._admin.deployed.VCA
1607 # if not found, create one entry and update database
tiernobaa51102018-12-14 13:16:18 +00001608
quilesj7e13aeb2019-10-08 13:34:55 +02001609 # fill db_nsr._admin.deployed.VCA.<index>
1610 vca_index = -1
1611 for vca_index, vca_deployed in enumerate(db_nsr["_admin"]["deployed"]["VCA"]):
1612 if not vca_deployed:
1613 continue
1614 if vca_deployed.get("member-vnf-index") == member_vnf_index and \
1615 vca_deployed.get("vdu_id") == vdu_id and \
calvinosanch9f9c6f22019-11-04 13:37:39 +01001616 vca_deployed.get("kdu_name") == kdu_name and \
quilesj7e13aeb2019-10-08 13:34:55 +02001617 vca_deployed.get("vdu_count_index", 0) == vdu_index:
1618 break
1619 else:
1620 # not found, create one.
1621 vca_deployed = {
1622 "member-vnf-index": member_vnf_index,
1623 "vdu_id": vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01001624 "kdu_name": kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02001625 "vdu_count_index": vdu_index,
1626 "operational-status": "init", # TODO revise
1627 "detailed-status": "", # TODO revise
1628 "step": "initial-deploy", # TODO revise
1629 "vnfd_id": vnfd_id,
1630 "vdu_name": vdu_name,
1631 }
1632 vca_index += 1
1633 self.update_db_2("nsrs", nsr_id, {"_admin.deployed.VCA.{}".format(vca_index): vca_deployed})
1634 db_nsr["_admin"]["deployed"]["VCA"].append(vca_deployed)
1635
1636 # Launch task
1637 task_n2vc = asyncio.ensure_future(
1638 self.instantiate_N2VC(
1639 logging_text=logging_text,
1640 vca_index=vca_index,
1641 nsi_id=nsi_id,
1642 db_nsr=db_nsr,
1643 db_vnfr=db_vnfr,
1644 vdu_id=vdu_id,
calvinosanch9f9c6f22019-11-04 13:37:39 +01001645 kdu_name=kdu_name,
quilesj7e13aeb2019-10-08 13:34:55 +02001646 vdu_index=vdu_index,
1647 deploy_params=deploy_params,
1648 config_descriptor=descriptor_config,
1649 base_folder=base_folder,
1650 )
1651 )
1652 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "instantiate_N2VC-{}".format(vca_index), task_n2vc)
1653 task_instantiation_list.append(task_n2vc)
tiernobaa51102018-12-14 13:16:18 +00001654
kuuse0ca67472019-05-13 15:59:27 +02001655 # Check if this VNFD has a configured terminate action
1656 def _has_terminate_config_primitive(self, vnfd):
1657 vnf_config = vnfd.get("vnf-configuration")
1658 if vnf_config and vnf_config.get("terminate-config-primitive"):
1659 return True
1660 else:
1661 return False
1662
tiernoc9556972019-07-05 15:25:25 +00001663 @staticmethod
1664 def _get_terminate_config_primitive_seq_list(vnfd):
1665 """ Get a numerically sorted list of the sequences for this VNFD's terminate action """
kuuse0ca67472019-05-13 15:59:27 +02001666 # No need to check for existing primitive twice, already done before
1667 vnf_config = vnfd.get("vnf-configuration")
1668 seq_list = vnf_config.get("terminate-config-primitive")
1669 # Get all 'seq' tags in seq_list, order sequences numerically, ascending.
1670 seq_list_sorted = sorted(seq_list, key=lambda x: int(x['seq']))
1671 return seq_list_sorted
1672
1673 @staticmethod
1674 def _create_nslcmop(nsr_id, operation, params):
1675 """
1676 Creates a ns-lcm-opp content to be stored at database.
1677 :param nsr_id: internal id of the instance
1678 :param operation: instantiate, terminate, scale, action, ...
1679 :param params: user parameters for the operation
1680 :return: dictionary following SOL005 format
1681 """
1682 # Raise exception if invalid arguments
1683 if not (nsr_id and operation and params):
1684 raise LcmException(
1685 "Parameters 'nsr_id', 'operation' and 'params' needed to create primitive not provided")
1686 now = time()
1687 _id = str(uuid4())
1688 nslcmop = {
1689 "id": _id,
1690 "_id": _id,
1691 # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1692 "operationState": "PROCESSING",
1693 "statusEnteredTime": now,
1694 "nsInstanceId": nsr_id,
1695 "lcmOperationType": operation,
1696 "startTime": now,
1697 "isAutomaticInvocation": False,
1698 "operationParams": params,
1699 "isCancelPending": False,
1700 "links": {
1701 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
1702 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
1703 }
1704 }
1705 return nslcmop
1706
calvinosanch9f9c6f22019-11-04 13:37:39 +01001707 def _format_additional_params(self, params):
1708
1709 for key, value in params.items():
1710 if str(value).startswith("!!yaml "):
1711 params[key] = yaml.safe_load(value[7:])
1712
1713 return params
1714
kuuse8b998e42019-07-30 15:22:16 +02001715 def _get_terminate_primitive_params(self, seq, vnf_index):
1716 primitive = seq.get('name')
1717 primitive_params = {}
1718 params = {
1719 "member_vnf_index": vnf_index,
1720 "primitive": primitive,
1721 "primitive_params": primitive_params,
1722 }
1723 desc_params = {}
1724 return self._map_primitive_params(seq, params, desc_params)
1725
kuuseac3a8882019-10-03 10:48:06 +02001726 # sub-operations
1727
1728 def _reintent_or_skip_suboperation(self, db_nslcmop, op_index):
1729 op = db_nslcmop.get('_admin', {}).get('operations', [])[op_index]
1730 if (op.get('operationState') == 'COMPLETED'):
1731 # b. Skip sub-operation
1732 # _ns_execute_primitive() or RO.create_action() will NOT be executed
1733 return self.SUBOPERATION_STATUS_SKIP
1734 else:
1735 # c. Reintent executing sub-operation
1736 # The sub-operation exists, and operationState != 'COMPLETED'
1737 # Update operationState = 'PROCESSING' to indicate a reintent.
1738 operationState = 'PROCESSING'
1739 detailed_status = 'In progress'
1740 self._update_suboperation_status(
1741 db_nslcmop, op_index, operationState, detailed_status)
1742 # Return the sub-operation index
1743 # _ns_execute_primitive() or RO.create_action() will be called from scale()
1744 # with arguments extracted from the sub-operation
1745 return op_index
1746
1747 # Find a sub-operation where all keys in a matching dictionary must match
1748 # Returns the index of the matching sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if no match
1749 def _find_suboperation(self, db_nslcmop, match):
1750 if (db_nslcmop and match):
1751 op_list = db_nslcmop.get('_admin', {}).get('operations', [])
1752 for i, op in enumerate(op_list):
1753 if all(op.get(k) == match[k] for k in match):
1754 return i
1755 return self.SUBOPERATION_STATUS_NOT_FOUND
1756
1757 # Update status for a sub-operation given its index
1758 def _update_suboperation_status(self, db_nslcmop, op_index, operationState, detailed_status):
1759 # Update DB for HA tasks
1760 q_filter = {'_id': db_nslcmop['_id']}
1761 update_dict = {'_admin.operations.{}.operationState'.format(op_index): operationState,
1762 '_admin.operations.{}.detailed-status'.format(op_index): detailed_status}
1763 self.db.set_one("nslcmops",
1764 q_filter=q_filter,
1765 update_dict=update_dict,
1766 fail_on_empty=False)
1767
1768 # Add sub-operation, return the index of the added sub-operation
1769 # Optionally, set operationState, detailed-status, and operationType
1770 # Status and type are currently set for 'scale' sub-operations:
1771 # 'operationState' : 'PROCESSING' | 'COMPLETED' | 'FAILED'
1772 # 'detailed-status' : status message
1773 # 'operationType': may be any type, in the case of scaling: 'PRE-SCALE' | 'POST-SCALE'
1774 # Status and operation type are currently only used for 'scale', but NOT for 'terminate' sub-operations.
quilesj7e13aeb2019-10-08 13:34:55 +02001775 def _add_suboperation(self, db_nslcmop, vnf_index, vdu_id, vdu_count_index, vdu_name, primitive,
1776 mapped_primitive_params, operationState=None, detailed_status=None, operationType=None,
kuuseac3a8882019-10-03 10:48:06 +02001777 RO_nsr_id=None, RO_scaling_info=None):
1778 if not (db_nslcmop):
1779 return self.SUBOPERATION_STATUS_NOT_FOUND
1780 # Get the "_admin.operations" list, if it exists
1781 db_nslcmop_admin = db_nslcmop.get('_admin', {})
1782 op_list = db_nslcmop_admin.get('operations')
1783 # Create or append to the "_admin.operations" list
kuuse8b998e42019-07-30 15:22:16 +02001784 new_op = {'member_vnf_index': vnf_index,
1785 'vdu_id': vdu_id,
1786 'vdu_count_index': vdu_count_index,
1787 'primitive': primitive,
1788 'primitive_params': mapped_primitive_params}
kuuseac3a8882019-10-03 10:48:06 +02001789 if operationState:
1790 new_op['operationState'] = operationState
1791 if detailed_status:
1792 new_op['detailed-status'] = detailed_status
1793 if operationType:
1794 new_op['lcmOperationType'] = operationType
1795 if RO_nsr_id:
1796 new_op['RO_nsr_id'] = RO_nsr_id
1797 if RO_scaling_info:
1798 new_op['RO_scaling_info'] = RO_scaling_info
1799 if not op_list:
1800 # No existing operations, create key 'operations' with current operation as first list element
1801 db_nslcmop_admin.update({'operations': [new_op]})
1802 op_list = db_nslcmop_admin.get('operations')
1803 else:
1804 # Existing operations, append operation to list
1805 op_list.append(new_op)
kuuse8b998e42019-07-30 15:22:16 +02001806
kuuseac3a8882019-10-03 10:48:06 +02001807 db_nslcmop_update = {'_admin.operations': op_list}
1808 self.update_db_2("nslcmops", db_nslcmop['_id'], db_nslcmop_update)
1809 op_index = len(op_list) - 1
1810 return op_index
1811
1812 # Helper methods for scale() sub-operations
1813
1814 # pre-scale/post-scale:
1815 # Check for 3 different cases:
1816 # a. New: First time execution, return SUBOPERATION_STATUS_NEW
1817 # b. Skip: Existing sub-operation exists, operationState == 'COMPLETED', return SUBOPERATION_STATUS_SKIP
1818 # c. Reintent: Existing sub-operation exists, operationState != 'COMPLETED', return op_index to re-execute
quilesj7e13aeb2019-10-08 13:34:55 +02001819 def _check_or_add_scale_suboperation(self, db_nslcmop, vnf_index, vnf_config_primitive, primitive_params,
1820 operationType, RO_nsr_id=None, RO_scaling_info=None):
kuuseac3a8882019-10-03 10:48:06 +02001821 # Find this sub-operation
1822 if (RO_nsr_id and RO_scaling_info):
1823 operationType = 'SCALE-RO'
1824 match = {
1825 'member_vnf_index': vnf_index,
1826 'RO_nsr_id': RO_nsr_id,
1827 'RO_scaling_info': RO_scaling_info,
1828 }
1829 else:
1830 match = {
1831 'member_vnf_index': vnf_index,
1832 'primitive': vnf_config_primitive,
1833 'primitive_params': primitive_params,
1834 'lcmOperationType': operationType
1835 }
1836 op_index = self._find_suboperation(db_nslcmop, match)
1837 if (op_index == self.SUBOPERATION_STATUS_NOT_FOUND):
1838 # a. New sub-operation
1839 # The sub-operation does not exist, add it.
1840 # _ns_execute_primitive() will be called from scale() as usual, with non-modified arguments
1841 # The following parameters are set to None for all kind of scaling:
1842 vdu_id = None
1843 vdu_count_index = None
1844 vdu_name = None
1845 if (RO_nsr_id and RO_scaling_info):
1846 vnf_config_primitive = None
1847 primitive_params = None
1848 else:
1849 RO_nsr_id = None
1850 RO_scaling_info = None
1851 # Initial status for sub-operation
1852 operationState = 'PROCESSING'
1853 detailed_status = 'In progress'
1854 # Add sub-operation for pre/post-scaling (zero or more operations)
1855 self._add_suboperation(db_nslcmop,
1856 vnf_index,
1857 vdu_id,
1858 vdu_count_index,
1859 vdu_name,
1860 vnf_config_primitive,
1861 primitive_params,
1862 operationState,
1863 detailed_status,
1864 operationType,
1865 RO_nsr_id,
1866 RO_scaling_info)
1867 return self.SUBOPERATION_STATUS_NEW
1868 else:
1869 # Return either SUBOPERATION_STATUS_SKIP (operationState == 'COMPLETED'),
1870 # or op_index (operationState != 'COMPLETED')
1871 return self._reintent_or_skip_suboperation(db_nslcmop, op_index)
1872
1873 # Helper methods for terminate()
kuuse8b998e42019-07-30 15:22:16 +02001874
kuuse0ca67472019-05-13 15:59:27 +02001875 async def _terminate_action(self, db_nslcmop, nslcmop_id, nsr_id):
tiernoc9556972019-07-05 15:25:25 +00001876 """ Create a primitive with params from VNFD
1877 Called from terminate() before deleting instance
1878 Calls action() to execute the primitive """
kuuse0ca67472019-05-13 15:59:27 +02001879 logging_text = "Task ns={} _terminate_action={} ".format(nsr_id, nslcmop_id)
kuuse0ca67472019-05-13 15:59:27 +02001880 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
kuuse8b998e42019-07-30 15:22:16 +02001881 db_vnfds = {}
kuuse0ca67472019-05-13 15:59:27 +02001882 # Loop over VNFRs
1883 for vnfr in db_vnfrs_list:
1884 vnfd_id = vnfr["vnfd-id"]
1885 vnf_index = vnfr["member-vnf-index-ref"]
1886 if vnfd_id not in db_vnfds:
1887 step = "Getting vnfd={} id='{}' from db".format(vnfd_id, vnfd_id)
1888 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
1889 db_vnfds[vnfd_id] = vnfd
1890 vnfd = db_vnfds[vnfd_id]
1891 if not self._has_terminate_config_primitive(vnfd):
1892 continue
1893 # Get the primitive's sorted sequence list
1894 seq_list = self._get_terminate_config_primitive_seq_list(vnfd)
1895 for seq in seq_list:
kuuse8b998e42019-07-30 15:22:16 +02001896 # For each sequence in list, get primitive and call _ns_execute_primitive()
kuuse0ca67472019-05-13 15:59:27 +02001897 step = "Calling terminate action for vnf_member_index={} primitive={}".format(
1898 vnf_index, seq.get("name"))
1899 self.logger.debug(logging_text + step)
kuuse8b998e42019-07-30 15:22:16 +02001900 # Create the primitive for each sequence, i.e. "primitive": "touch"
kuuse0ca67472019-05-13 15:59:27 +02001901 primitive = seq.get('name')
kuuse8b998e42019-07-30 15:22:16 +02001902 mapped_primitive_params = self._get_terminate_primitive_params(seq, vnf_index)
1903 # The following 3 parameters are currently set to None for 'terminate':
1904 # vdu_id, vdu_count_index, vdu_name
1905 vdu_id = db_nslcmop["operationParams"].get("vdu_id")
1906 vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
1907 vdu_name = db_nslcmop["operationParams"].get("vdu_name")
kuuseac3a8882019-10-03 10:48:06 +02001908 # Add sub-operation
kuuse8b998e42019-07-30 15:22:16 +02001909 self._add_suboperation(db_nslcmop,
1910 nslcmop_id,
1911 vnf_index,
1912 vdu_id,
1913 vdu_count_index,
1914 vdu_name,
1915 primitive,
1916 mapped_primitive_params)
kuuseac3a8882019-10-03 10:48:06 +02001917 # Sub-operations: Call _ns_execute_primitive() instead of action()
quilesj7e13aeb2019-10-08 13:34:55 +02001918 # db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1919 # nsr_deployed = db_nsr["_admin"]["deployed"]
kuuse8b998e42019-07-30 15:22:16 +02001920
1921 # nslcmop_operation_state, nslcmop_operation_state_detail = await self.action(
1922 # nsr_id, nslcmop_terminate_action_id)
kuuse0ca67472019-05-13 15:59:27 +02001923 # Launch Exception if action() returns other than ['COMPLETED', 'PARTIALLY_COMPLETED']
quilesj7e13aeb2019-10-08 13:34:55 +02001924 # result_ok = ['COMPLETED', 'PARTIALLY_COMPLETED']
1925 # if result not in result_ok:
1926 # raise LcmException(
1927 # "terminate_primitive_action for vnf_member_index={}",
1928 # " primitive={} fails with error {}".format(
1929 # vnf_index, seq.get("name"), result_detail))
1930
1931 # TODO: find ee_id
1932 ee_id = None
1933 try:
1934 await self.n2vc.exec_primitive(
1935 ee_id=ee_id,
1936 primitive_name=primitive,
1937 params_dict=mapped_primitive_params
1938 )
1939 except Exception as e:
1940 self.logger.error('Error executing primitive {}: {}'.format(primitive, e))
kuuse0ca67472019-05-13 15:59:27 +02001941 raise LcmException(
quilesj7e13aeb2019-10-08 13:34:55 +02001942 "terminate_primitive_action for vnf_member_index={}, primitive={} fails with error {}"
1943 .format(vnf_index, seq.get("name"), e),
1944 )
kuuse0ca67472019-05-13 15:59:27 +02001945
tierno59d22d22018-09-25 18:10:19 +02001946 async def terminate(self, nsr_id, nslcmop_id):
kuused124bfe2019-06-18 12:09:24 +02001947
1948 # Try to lock HA task here
1949 task_is_locked_by_me = self.lcm_tasks.lock_HA('ns', 'nslcmops', nslcmop_id)
1950 if not task_is_locked_by_me:
1951 return
1952
tierno59d22d22018-09-25 18:10:19 +02001953 logging_text = "Task ns={} terminate={} ".format(nsr_id, nslcmop_id)
1954 self.logger.debug(logging_text + "Enter")
1955 db_nsr = None
1956 db_nslcmop = None
1957 exc = None
1958 failed_detail = [] # annotates all failed error messages
calvinosanch9f9c6f22019-11-04 13:37:39 +01001959 db_nsr_update = {"_admin.nslcmop": nslcmop_id,
1960 "_admin.current-operation": nslcmop_id,
1961 "_admin.operation-type": "terminate"}
1962 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tierno59d22d22018-09-25 18:10:19 +02001963 db_nslcmop_update = {}
1964 nslcmop_operation_state = None
tiernoc2564fe2019-01-28 16:18:56 +00001965 autoremove = False # autoremove after terminated
tierno73d8bd02019-11-18 17:33:27 +00001966 pending_tasks = []
tierno59d22d22018-09-25 18:10:19 +02001967 try:
kuused124bfe2019-06-18 12:09:24 +02001968 # wait for any previous tasks in process
tierno3cf81a32019-11-11 17:07:00 +00001969 step = "Waiting for previous operations to terminate"
kuused124bfe2019-06-18 12:09:24 +02001970 await self.lcm_tasks.waitfor_related_HA("ns", 'nslcmops', nslcmop_id)
1971
tierno59d22d22018-09-25 18:10:19 +02001972 step = "Getting nslcmop={} from db".format(nslcmop_id)
1973 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
1974 step = "Getting nsr={} from db".format(nsr_id)
1975 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1976 # nsd = db_nsr["nsd"]
tiernoe4f7e6c2018-11-27 14:55:30 +00001977 nsr_deployed = deepcopy(db_nsr["_admin"].get("deployed"))
tierno59d22d22018-09-25 18:10:19 +02001978 if db_nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
1979 return
tierno59d22d22018-09-25 18:10:19 +02001980 # #TODO check if VIM is creating and wait
1981 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
kuuse0ca67472019-05-13 15:59:27 +02001982 # Call internal terminate action
1983 await self._terminate_action(db_nslcmop, nslcmop_id, nsr_id)
tierno59d22d22018-09-25 18:10:19 +02001984
calvinosanch9f9c6f22019-11-04 13:37:39 +01001985 pending_tasks = []
1986
tierno59d22d22018-09-25 18:10:19 +02001987 db_nsr_update["operational-status"] = "terminating"
1988 db_nsr_update["config-status"] = "terminating"
1989
quilesj7e13aeb2019-10-08 13:34:55 +02001990 # remove NS
1991 try:
1992 step = "delete execution environment"
tierno9597c292019-02-06 09:21:27 +00001993 self.logger.debug(logging_text + step)
tierno82974b22018-11-27 21:55:36 +00001994
quilesj7e13aeb2019-10-08 13:34:55 +02001995 task_delete_ee = asyncio.ensure_future(self.n2vc.delete_namespace(namespace="." + nsr_id))
1996 pending_tasks.append(task_delete_ee)
1997 except Exception as e:
1998 msg = "Failed while deleting NS in VCA: {}".format(e)
1999 self.logger.error(msg)
2000 failed_detail.append(msg)
tierno59d22d22018-09-25 18:10:19 +02002001
calvinosanch9f9c6f22019-11-04 13:37:39 +01002002 try:
2003 # Delete from k8scluster
2004 step = "delete kdus"
2005 self.logger.debug(logging_text + step)
2006 print(nsr_deployed)
2007 if nsr_deployed:
2008 for kdu in nsr_deployed.get("K8s"):
2009 if kdu.get("k8scluster-type") == "chart":
2010 task_delete_kdu_instance = asyncio.ensure_future(self.k8sclusterhelm.uninstall(
2011 cluster_uuid=kdu.get("k8scluster-uuid"), kdu_instance=kdu.get("kdu-instance")))
2012 elif kdu.get("k8scluster-type") == "juju":
2013 # TODO Juju connector needed
2014 pass
2015 else:
2016 msg = "k8scluster-type not defined"
2017 raise LcmException(msg)
2018
2019 pending_tasks.append(task_delete_kdu_instance)
2020 except LcmException as e:
2021 msg = "Failed while deleting KDUs from NS: {}".format(e)
2022 self.logger.error(msg)
2023 failed_detail.append(msg)
tierno59d22d22018-09-25 18:10:19 +02002024
2025 # remove from RO
2026 RO_fail = False
tierno59d22d22018-09-25 18:10:19 +02002027
2028 # Delete ns
2029 RO_nsr_id = RO_delete_action = None
tiernoe4f7e6c2018-11-27 14:55:30 +00002030 if nsr_deployed and nsr_deployed.get("RO"):
2031 RO_nsr_id = nsr_deployed["RO"].get("nsr_id")
2032 RO_delete_action = nsr_deployed["RO"].get("nsr_delete_action_id")
tierno59d22d22018-09-25 18:10:19 +02002033 try:
2034 if RO_nsr_id:
tierno15b1cf12019-08-29 13:21:40 +00002035 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] = \
2036 "Deleting ns from VIM"
tiernoeb55b012018-11-29 08:10:04 +00002037 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
2038 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tierno59d22d22018-09-25 18:10:19 +02002039 self.logger.debug(logging_text + step)
tierno77677d92019-08-22 13:46:35 +00002040 desc = await self.RO.delete("ns", RO_nsr_id)
tierno59d22d22018-09-25 18:10:19 +02002041 RO_delete_action = desc["action_id"]
2042 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = RO_delete_action
2043 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
2044 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
2045 if RO_delete_action:
2046 # wait until NS is deleted from VIM
tiernobaa51102018-12-14 13:16:18 +00002047 step = detailed_status = "Waiting ns deleted from VIM. RO_id={} RO_delete_action={}".\
2048 format(RO_nsr_id, RO_delete_action)
tierno59d22d22018-09-25 18:10:19 +02002049 detailed_status_old = None
2050 self.logger.debug(logging_text + step)
2051
2052 delete_timeout = 20 * 60 # 20 minutes
2053 while delete_timeout > 0:
quilesj7e13aeb2019-10-08 13:34:55 +02002054 desc = await self.RO.show(
2055 "ns",
2056 item_id_name=RO_nsr_id,
2057 extra_item="action",
2058 extra_item_id=RO_delete_action)
tierno77677d92019-08-22 13:46:35 +00002059 ns_status, ns_status_info = self.RO.check_action_status(desc)
tierno59d22d22018-09-25 18:10:19 +02002060 if ns_status == "ERROR":
2061 raise ROclient.ROClientException(ns_status_info)
2062 elif ns_status == "BUILD":
2063 detailed_status = step + "; {}".format(ns_status_info)
2064 elif ns_status == "ACTIVE":
tiernobaa51102018-12-14 13:16:18 +00002065 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
2066 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
tierno59d22d22018-09-25 18:10:19 +02002067 break
2068 else:
2069 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
tiernoeb55b012018-11-29 08:10:04 +00002070 if detailed_status != detailed_status_old:
2071 detailed_status_old = db_nslcmop_update["detailed-status"] = \
2072 db_nsr_update["detailed-status"] = detailed_status
2073 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
2074 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tierno59d22d22018-09-25 18:10:19 +02002075 await asyncio.sleep(5, loop=self.loop)
2076 delete_timeout -= 5
tierno59d22d22018-09-25 18:10:19 +02002077 else: # delete_timeout <= 0:
2078 raise ROclient.ROClientException("Timeout waiting ns deleted from VIM")
2079
2080 except ROclient.ROClientException as e:
2081 if e.http_code == 404: # not found
2082 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
2083 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
tiernobaa51102018-12-14 13:16:18 +00002084 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
tierno59d22d22018-09-25 18:10:19 +02002085 self.logger.debug(logging_text + "RO_ns_id={} already deleted".format(RO_nsr_id))
2086 elif e.http_code == 409: # conflict
2087 failed_detail.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id, e))
2088 self.logger.debug(logging_text + failed_detail[-1])
2089 RO_fail = True
2090 else:
2091 failed_detail.append("RO_ns_id={} delete error: {}".format(RO_nsr_id, e))
2092 self.logger.error(logging_text + failed_detail[-1])
2093 RO_fail = True
2094
2095 # Delete nsd
tiernoe4f7e6c2018-11-27 14:55:30 +00002096 if not RO_fail and nsr_deployed and nsr_deployed.get("RO") and nsr_deployed["RO"].get("nsd_id"):
2097 RO_nsd_id = nsr_deployed["RO"]["nsd_id"]
tierno59d22d22018-09-25 18:10:19 +02002098 try:
2099 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
tierno15b1cf12019-08-29 13:21:40 +00002100 "Deleting nsd from RO"
tierno77677d92019-08-22 13:46:35 +00002101 await self.RO.delete("nsd", RO_nsd_id)
tierno59d22d22018-09-25 18:10:19 +02002102 self.logger.debug(logging_text + "RO_nsd_id={} deleted".format(RO_nsd_id))
2103 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
2104 except ROclient.ROClientException as e:
2105 if e.http_code == 404: # not found
2106 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
2107 self.logger.debug(logging_text + "RO_nsd_id={} already deleted".format(RO_nsd_id))
2108 elif e.http_code == 409: # conflict
2109 failed_detail.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id, e))
2110 self.logger.debug(logging_text + failed_detail[-1])
2111 RO_fail = True
2112 else:
2113 failed_detail.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id, e))
2114 self.logger.error(logging_text + failed_detail[-1])
2115 RO_fail = True
2116
tiernoa009e552019-01-30 16:45:44 +00002117 if not RO_fail and nsr_deployed and nsr_deployed.get("RO") and nsr_deployed["RO"].get("vnfd"):
2118 for index, vnf_deployed in enumerate(nsr_deployed["RO"]["vnfd"]):
2119 if not vnf_deployed or not vnf_deployed["id"]:
tierno59d22d22018-09-25 18:10:19 +02002120 continue
2121 try:
tiernoa009e552019-01-30 16:45:44 +00002122 RO_vnfd_id = vnf_deployed["id"]
tierno59d22d22018-09-25 18:10:19 +02002123 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
tierno98ad6ea2019-05-30 17:16:28 +00002124 "Deleting member_vnf_index={} RO_vnfd_id={} from RO".format(
tiernoa009e552019-01-30 16:45:44 +00002125 vnf_deployed["member-vnf-index"], RO_vnfd_id)
tierno77677d92019-08-22 13:46:35 +00002126 await self.RO.delete("vnfd", RO_vnfd_id)
tierno59d22d22018-09-25 18:10:19 +02002127 self.logger.debug(logging_text + "RO_vnfd_id={} deleted".format(RO_vnfd_id))
tiernoa009e552019-01-30 16:45:44 +00002128 db_nsr_update["_admin.deployed.RO.vnfd.{}.id".format(index)] = None
tierno59d22d22018-09-25 18:10:19 +02002129 except ROclient.ROClientException as e:
2130 if e.http_code == 404: # not found
tiernoa009e552019-01-30 16:45:44 +00002131 db_nsr_update["_admin.deployed.RO.vnfd.{}.id".format(index)] = None
tierno59d22d22018-09-25 18:10:19 +02002132 self.logger.debug(logging_text + "RO_vnfd_id={} already deleted ".format(RO_vnfd_id))
2133 elif e.http_code == 409: # conflict
2134 failed_detail.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id, e))
2135 self.logger.debug(logging_text + failed_detail[-1])
2136 else:
2137 failed_detail.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id, e))
2138 self.logger.error(logging_text + failed_detail[-1])
2139
tierno59d22d22018-09-25 18:10:19 +02002140 if failed_detail:
2141 self.logger.error(logging_text + " ;".join(failed_detail))
2142 db_nsr_update["operational-status"] = "failed"
2143 db_nsr_update["detailed-status"] = "Deletion errors " + "; ".join(failed_detail)
2144 db_nslcmop_update["detailed-status"] = "; ".join(failed_detail)
2145 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
2146 db_nslcmop_update["statusEnteredTime"] = time()
tierno59d22d22018-09-25 18:10:19 +02002147 else:
2148 db_nsr_update["operational-status"] = "terminated"
2149 db_nsr_update["detailed-status"] = "Done"
2150 db_nsr_update["_admin.nsState"] = "NOT_INSTANTIATED"
2151 db_nslcmop_update["detailed-status"] = "Done"
2152 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
2153 db_nslcmop_update["statusEnteredTime"] = time()
tiernoc2564fe2019-01-28 16:18:56 +00002154 if db_nslcmop["operationParams"].get("autoremove"):
2155 autoremove = True
tierno59d22d22018-09-25 18:10:19 +02002156
kuuse0ca67472019-05-13 15:59:27 +02002157 except (ROclient.ROClientException, DbException, LcmException) as e:
tierno59d22d22018-09-25 18:10:19 +02002158 self.logger.error(logging_text + "Exit Exception {}".format(e))
2159 exc = e
2160 except asyncio.CancelledError:
2161 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
2162 exc = "Operation was cancelled"
2163 except Exception as e:
2164 exc = traceback.format_exc()
2165 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
2166 finally:
2167 if exc and db_nslcmop:
2168 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
2169 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
2170 db_nslcmop_update["statusEnteredTime"] = time()
tiernobaa51102018-12-14 13:16:18 +00002171 try:
2172 if db_nslcmop and db_nslcmop_update:
2173 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
2174 if db_nsr:
2175 db_nsr_update["_admin.nslcmop"] = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01002176 db_nsr_update["_admin.current-operation"] = None
2177 db_nsr_update["_admin.operation-type"] = None
tiernobaa51102018-12-14 13:16:18 +00002178 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2179 except DbException as e:
2180 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno59d22d22018-09-25 18:10:19 +02002181 if nslcmop_operation_state:
2182 try:
2183 await self.msg.aiowrite("ns", "terminated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
tiernoc2564fe2019-01-28 16:18:56 +00002184 "operationState": nslcmop_operation_state,
2185 "autoremove": autoremove},
tierno8a518872018-12-21 13:42:14 +00002186 loop=self.loop)
tierno59d22d22018-09-25 18:10:19 +02002187 except Exception as e:
2188 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
quilesj7e13aeb2019-10-08 13:34:55 +02002189
2190 # wait for pending tasks
2191 done = None
2192 pending = None
2193 if pending_tasks:
2194 self.logger.debug(logging_text + 'Waiting for terminate pending tasks...')
2195 done, pending = await asyncio.wait(pending_tasks, timeout=3600)
2196 if not pending:
2197 self.logger.debug(logging_text + 'All tasks finished...')
2198 else:
2199 self.logger.info(logging_text + 'There are pending tasks: {}'.format(pending))
2200
tierno59d22d22018-09-25 18:10:19 +02002201 self.logger.debug(logging_text + "Exit")
2202 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_terminate")
2203
tiernoda964822019-01-14 15:53:47 +00002204 @staticmethod
2205 def _map_primitive_params(primitive_desc, params, instantiation_params):
2206 """
2207 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
2208 The default-value is used. If it is between < > it look for a value at instantiation_params
2209 :param primitive_desc: portion of VNFD/NSD that describes primitive
2210 :param params: Params provided by user
2211 :param instantiation_params: Instantiation params provided by user
2212 :return: a dictionary with the calculated params
2213 """
2214 calculated_params = {}
2215 for parameter in primitive_desc.get("parameter", ()):
2216 param_name = parameter["name"]
2217 if param_name in params:
2218 calculated_params[param_name] = params[param_name]
tierno98ad6ea2019-05-30 17:16:28 +00002219 elif "default-value" in parameter or "value" in parameter:
2220 if "value" in parameter:
2221 calculated_params[param_name] = parameter["value"]
2222 else:
2223 calculated_params[param_name] = parameter["default-value"]
2224 if isinstance(calculated_params[param_name], str) and calculated_params[param_name].startswith("<") \
2225 and calculated_params[param_name].endswith(">"):
2226 if calculated_params[param_name][1:-1] in instantiation_params:
2227 calculated_params[param_name] = instantiation_params[calculated_params[param_name][1:-1]]
tiernoda964822019-01-14 15:53:47 +00002228 else:
2229 raise LcmException("Parameter {} needed to execute primitive {} not provided".
tiernod8323042019-08-09 11:32:23 +00002230 format(calculated_params[param_name], primitive_desc["name"]))
tiernoda964822019-01-14 15:53:47 +00002231 else:
2232 raise LcmException("Parameter {} needed to execute primitive {} not provided".
2233 format(param_name, primitive_desc["name"]))
tierno59d22d22018-09-25 18:10:19 +02002234
tiernoda964822019-01-14 15:53:47 +00002235 if isinstance(calculated_params[param_name], (dict, list, tuple)):
2236 calculated_params[param_name] = yaml.safe_dump(calculated_params[param_name], default_flow_style=True,
2237 width=256)
2238 elif isinstance(calculated_params[param_name], str) and calculated_params[param_name].startswith("!!yaml "):
2239 calculated_params[param_name] = calculated_params[param_name][7:]
tiernoc3f2a822019-11-05 13:45:04 +00002240
2241 # add always ns_config_info if primitive name is config
2242 if primitive_desc["name"] == "config":
2243 if "ns_config_info" in instantiation_params:
2244 calculated_params["ns_config_info"] = instantiation_params["ns_config_info"]
tiernoda964822019-01-14 15:53:47 +00002245 return calculated_params
2246
2247 async def _ns_execute_primitive(self, db_deployed, member_vnf_index, vdu_id, vdu_name, vdu_count_index,
tierno73d8bd02019-11-18 17:33:27 +00002248 primitive, primitive_params, retries=0, retries_interval=30) -> (str, str):
quilesj7e13aeb2019-10-08 13:34:55 +02002249
2250 # find vca_deployed record for this action
tiernoda964822019-01-14 15:53:47 +00002251 try:
2252 for vca_deployed in db_deployed["VCA"]:
2253 if not vca_deployed:
2254 continue
2255 if member_vnf_index != vca_deployed["member-vnf-index"] or vdu_id != vca_deployed["vdu_id"]:
2256 continue
2257 if vdu_name and vdu_name != vca_deployed["vdu_name"]:
2258 continue
2259 if vdu_count_index and vdu_count_index != vca_deployed["vdu_count_index"]:
2260 continue
2261 break
2262 else:
quilesj7e13aeb2019-10-08 13:34:55 +02002263 # vca_deployed not found
tiernoda964822019-01-14 15:53:47 +00002264 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} is not "
2265 "deployed".format(member_vnf_index, vdu_id, vdu_name, vdu_count_index))
quilesj7e13aeb2019-10-08 13:34:55 +02002266
2267 # get ee_id
2268 ee_id = vca_deployed.get("ee_id")
2269 if not ee_id:
tiernoda964822019-01-14 15:53:47 +00002270 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} has not "
quilesj7e13aeb2019-10-08 13:34:55 +02002271 "execution environment"
2272 .format(member_vnf_index, vdu_id, vdu_name, vdu_count_index))
2273
tierno98ad6ea2019-05-30 17:16:28 +00002274 if primitive == "config":
2275 primitive_params = {"params": primitive_params}
tierno2fc7ce52019-06-11 22:50:01 +00002276
quilesj7e13aeb2019-10-08 13:34:55 +02002277 while retries >= 0:
2278 try:
2279 output = await self.n2vc.exec_primitive(
2280 ee_id=ee_id,
2281 primitive_name=primitive,
2282 params_dict=primitive_params
2283 )
2284 # execution was OK
2285 break
2286 except Exception as e:
quilesj7e13aeb2019-10-08 13:34:55 +02002287 retries -= 1
2288 if retries >= 0:
tierno73d8bd02019-11-18 17:33:27 +00002289 self.logger.debug('Error executing action {} on {} -> {}'.format(primitive, ee_id, e))
quilesj7e13aeb2019-10-08 13:34:55 +02002290 # wait and retry
2291 await asyncio.sleep(retries_interval, loop=self.loop)
tierno73d8bd02019-11-18 17:33:27 +00002292 else:
2293 return 'Cannot execute action {} on {}: {}'.format(primitive, ee_id, e), 'FAIL'
quilesj7e13aeb2019-10-08 13:34:55 +02002294
2295 return output, 'OK'
2296
2297 except Exception as e:
2298 return 'Error executing action {}: {}'.format(primitive, e), 'FAIL'
tierno59d22d22018-09-25 18:10:19 +02002299
2300 async def action(self, nsr_id, nslcmop_id):
kuused124bfe2019-06-18 12:09:24 +02002301
2302 # Try to lock HA task here
2303 task_is_locked_by_me = self.lcm_tasks.lock_HA('ns', 'nslcmops', nslcmop_id)
2304 if not task_is_locked_by_me:
2305 return
2306
tierno59d22d22018-09-25 18:10:19 +02002307 logging_text = "Task ns={} action={} ".format(nsr_id, nslcmop_id)
2308 self.logger.debug(logging_text + "Enter")
2309 # get all needed from database
2310 db_nsr = None
2311 db_nslcmop = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01002312 db_nsr_update = {"_admin.nslcmop": nslcmop_id,
2313 "_admin.current-operation": nslcmop_id,
2314 "_admin.operation-type": "action"}
2315 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tierno59d22d22018-09-25 18:10:19 +02002316 db_nslcmop_update = {}
2317 nslcmop_operation_state = None
kuuse0ca67472019-05-13 15:59:27 +02002318 nslcmop_operation_state_detail = None
tierno59d22d22018-09-25 18:10:19 +02002319 exc = None
2320 try:
kuused124bfe2019-06-18 12:09:24 +02002321 # wait for any previous tasks in process
tierno3cf81a32019-11-11 17:07:00 +00002322 step = "Waiting for previous operations to terminate"
kuused124bfe2019-06-18 12:09:24 +02002323 await self.lcm_tasks.waitfor_related_HA('ns', 'nslcmops', nslcmop_id)
2324
tierno59d22d22018-09-25 18:10:19 +02002325 step = "Getting information from database"
2326 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
2327 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
tiernoda964822019-01-14 15:53:47 +00002328
tiernoe4f7e6c2018-11-27 14:55:30 +00002329 nsr_deployed = db_nsr["_admin"].get("deployed")
tierno1b633412019-02-25 16:48:23 +00002330 vnf_index = db_nslcmop["operationParams"].get("member_vnf_index")
tierno59d22d22018-09-25 18:10:19 +02002331 vdu_id = db_nslcmop["operationParams"].get("vdu_id")
calvinosanch9f9c6f22019-11-04 13:37:39 +01002332 kdu_name = db_nslcmop["operationParams"].get("kdu_name")
tiernoe4f7e6c2018-11-27 14:55:30 +00002333 vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
2334 vdu_name = db_nslcmop["operationParams"].get("vdu_name")
tierno59d22d22018-09-25 18:10:19 +02002335
tierno1b633412019-02-25 16:48:23 +00002336 if vnf_index:
2337 step = "Getting vnfr from database"
2338 db_vnfr = self.db.get_one("vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id})
2339 step = "Getting vnfd from database"
2340 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
2341 else:
2342 if db_nsr.get("nsd"):
2343 db_nsd = db_nsr.get("nsd") # TODO this will be removed
2344 else:
2345 step = "Getting nsd from database"
2346 db_nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
tiernoda964822019-01-14 15:53:47 +00002347
tierno82974b22018-11-27 21:55:36 +00002348 # for backward compatibility
2349 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
2350 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
2351 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
2352 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2353
tierno59d22d22018-09-25 18:10:19 +02002354 primitive = db_nslcmop["operationParams"]["primitive"]
2355 primitive_params = db_nslcmop["operationParams"]["primitive_params"]
tiernoda964822019-01-14 15:53:47 +00002356
2357 # look for primitive
2358 config_primitive_desc = None
2359 if vdu_id:
2360 for vdu in get_iterable(db_vnfd, "vdu"):
2361 if vdu_id == vdu["id"]:
2362 for config_primitive in vdu.get("vdu-configuration", {}).get("config-primitive", ()):
2363 if config_primitive["name"] == primitive:
2364 config_primitive_desc = config_primitive
2365 break
calvinosanch9f9c6f22019-11-04 13:37:39 +01002366 elif kdu_name:
2367 self.logger.debug(logging_text + "Checking actions in KDUs")
2368 desc_params = {}
2369 if vnf_index:
2370 if db_vnfr.get("additionalParamsForVnf") and db_vnfr["additionalParamsForVnf"].\
2371 get("member-vnf-index") == vnf_index:
2372 desc_params = self._format_additional_params(db_vnfr["additionalParamsForVnf"].
2373 get("additionalParams"))
2374 if primitive_params:
2375 desc_params.update(primitive_params)
2376 # TODO Check if we will need something at vnf level
2377 index = 0
2378 for kdu in get_iterable(nsr_deployed, "K8s"):
2379 if kdu_name == kdu["kdu-name"]:
2380 db_dict = {"collection": "nsrs", "filter": {"_id": nsr_id},
2381 "path": "_admin.deployed.K8s.{}".format(index)}
2382 if primitive == "upgrade":
2383 if desc_params.get("kdu_model"):
2384 kdu_model = desc_params.get("kdu_model")
2385 del desc_params["kdu_model"]
2386 else:
2387 kdu_model = kdu.get("kdu-model")
2388 parts = kdu_model.split(sep=":")
2389 if len(parts) == 2:
2390 kdu_model = parts[0]
2391
2392 if kdu.get("k8scluster-type") == "chart":
2393 output = await self.k8sclusterhelm.upgrade(cluster_uuid=kdu.get("k8scluster-uuid"),
tiernoda6fb102019-11-23 00:36:52 +00002394 kdu_instance=kdu.get("kdu-instance"),
2395 atomic=True, kdu_model=kdu_model,
2396 params=desc_params, db_dict=db_dict,
2397 timeout=300)
calvinosanch9f9c6f22019-11-04 13:37:39 +01002398 elif kdu.get("k8scluster-type") == "juju":
2399 # TODO Juju connector needed
2400 pass
2401 else:
2402 msg = "k8scluster-type not defined"
2403 raise LcmException(msg)
2404
2405 self.logger.debug(logging_text + " Upgrade of kdu {} done".format(output))
2406 break
2407 elif primitive == "rollback":
2408 if kdu.get("k8scluster-type") == "chart":
2409 output = await self.k8sclusterhelm.rollback(cluster_uuid=kdu.get("k8scluster-uuid"),
2410 kdu_instance=kdu.get("kdu-instance"),
2411 db_dict=db_dict)
2412 elif kdu.get("k8scluster-type") == "juju":
2413 # TODO Juju connector needed
2414 pass
2415 else:
2416 msg = "k8scluster-type not defined"
2417 raise LcmException(msg)
2418 break
2419 elif primitive == "status":
2420 if kdu.get("k8scluster-type") == "chart":
2421 output = await self.k8sclusterhelm.status_kdu(cluster_uuid=kdu.get("k8scluster-uuid"),
2422 kdu_instance=kdu.get("kdu-instance"))
2423 elif kdu.get("k8scluster-type") == "juju":
2424 # TODO Juju connector needed
2425 pass
2426 else:
2427 msg = "k8scluster-type not defined"
2428 raise LcmException(msg)
2429 break
2430 index += 1
2431
2432 else:
2433 raise LcmException("KDU '{}' not found".format(kdu_name))
2434 if output:
2435 db_nslcmop_update["detailed-status"] = output
2436 db_nslcmop_update["operationState"] = 'COMPLETED'
2437 db_nslcmop_update["statusEnteredTime"] = time()
2438 else:
2439 db_nslcmop_update["detailed-status"] = ''
2440 db_nslcmop_update["operationState"] = 'FAILED'
2441 db_nslcmop_update["statusEnteredTime"] = time()
2442 return
tierno1b633412019-02-25 16:48:23 +00002443 elif vnf_index:
2444 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
2445 if config_primitive["name"] == primitive:
2446 config_primitive_desc = config_primitive
2447 break
2448 else:
2449 for config_primitive in db_nsd.get("ns-configuration", {}).get("config-primitive", ()):
2450 if config_primitive["name"] == primitive:
2451 config_primitive_desc = config_primitive
2452 break
tiernoda964822019-01-14 15:53:47 +00002453
tierno1b633412019-02-25 16:48:23 +00002454 if not config_primitive_desc:
2455 raise LcmException("Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".
2456 format(primitive))
2457
2458 desc_params = {}
2459 if vnf_index:
2460 if db_vnfr.get("additionalParamsForVnf"):
2461 desc_params.update(db_vnfr["additionalParamsForVnf"])
2462 else:
calvinosanch9f9c6f22019-11-04 13:37:39 +01002463 if db_nsr.get("additionalParamsForNs"):
tierno1b633412019-02-25 16:48:23 +00002464 desc_params.update(db_nsr["additionalParamsForNs"])
tiernoda964822019-01-14 15:53:47 +00002465
2466 # TODO check if ns is in a proper status
quilesj7e13aeb2019-10-08 13:34:55 +02002467 output, detail = await self._ns_execute_primitive(
2468 db_deployed=nsr_deployed,
2469 member_vnf_index=vnf_index,
2470 vdu_id=vdu_id,
2471 vdu_name=vdu_name,
2472 vdu_count_index=vdu_count_index,
2473 primitive=primitive,
2474 primitive_params=self._map_primitive_params(config_primitive_desc, primitive_params, desc_params))
2475
2476 detailed_status = output
2477 if detail == 'OK':
2478 result = 'COMPLETED'
2479 else:
2480 result = 'FAILED'
2481
2482 db_nslcmop_update["detailed-status"] = nslcmop_operation_state_detail = detailed_status
tierno59d22d22018-09-25 18:10:19 +02002483 db_nslcmop_update["operationState"] = nslcmop_operation_state = result
2484 db_nslcmop_update["statusEnteredTime"] = time()
quilesj7e13aeb2019-10-08 13:34:55 +02002485 self.logger.debug(logging_text + " task Done with result {} {}".format(result, detailed_status))
tierno59d22d22018-09-25 18:10:19 +02002486 return # database update is called inside finally
2487
2488 except (DbException, LcmException) as e:
2489 self.logger.error(logging_text + "Exit Exception {}".format(e))
2490 exc = e
2491 except asyncio.CancelledError:
2492 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
2493 exc = "Operation was cancelled"
2494 except Exception as e:
2495 exc = traceback.format_exc()
2496 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
2497 finally:
2498 if exc and db_nslcmop:
kuuse0ca67472019-05-13 15:59:27 +02002499 db_nslcmop_update["detailed-status"] = nslcmop_operation_state_detail = \
2500 "FAILED {}: {}".format(step, exc)
tierno59d22d22018-09-25 18:10:19 +02002501 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
2502 db_nslcmop_update["statusEnteredTime"] = time()
tiernobaa51102018-12-14 13:16:18 +00002503 try:
2504 if db_nslcmop_update:
2505 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
2506 if db_nsr:
2507 db_nsr_update["_admin.nslcmop"] = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01002508 db_nsr_update["_admin.operation-type"] = None
2509 db_nsr_update["_admin.nslcmop"] = None
2510 db_nsr_update["_admin.current-operation"] = None
tiernobaa51102018-12-14 13:16:18 +00002511 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2512 except DbException as e:
2513 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno59d22d22018-09-25 18:10:19 +02002514 self.logger.debug(logging_text + "Exit")
2515 if nslcmop_operation_state:
2516 try:
2517 await self.msg.aiowrite("ns", "actioned", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
tierno8a518872018-12-21 13:42:14 +00002518 "operationState": nslcmop_operation_state},
2519 loop=self.loop)
tierno59d22d22018-09-25 18:10:19 +02002520 except Exception as e:
2521 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
2522 self.logger.debug(logging_text + "Exit")
2523 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_action")
kuuse0ca67472019-05-13 15:59:27 +02002524 return nslcmop_operation_state, nslcmop_operation_state_detail
tierno59d22d22018-09-25 18:10:19 +02002525
2526 async def scale(self, nsr_id, nslcmop_id):
kuused124bfe2019-06-18 12:09:24 +02002527
2528 # Try to lock HA task here
2529 task_is_locked_by_me = self.lcm_tasks.lock_HA('ns', 'nslcmops', nslcmop_id)
2530 if not task_is_locked_by_me:
2531 return
2532
tierno59d22d22018-09-25 18:10:19 +02002533 logging_text = "Task ns={} scale={} ".format(nsr_id, nslcmop_id)
2534 self.logger.debug(logging_text + "Enter")
2535 # get all needed from database
2536 db_nsr = None
2537 db_nslcmop = None
2538 db_nslcmop_update = {}
2539 nslcmop_operation_state = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01002540 db_nsr_update = {"_admin.nslcmop": nslcmop_id,
2541 "_admin.current-operation": nslcmop_id,
2542 "_admin.operation-type": "scale"}
2543 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tierno59d22d22018-09-25 18:10:19 +02002544 exc = None
tierno9ab95942018-10-10 16:44:22 +02002545 # in case of error, indicates what part of scale was failed to put nsr at error status
2546 scale_process = None
tiernod6de1992018-10-11 13:05:52 +02002547 old_operational_status = ""
2548 old_config_status = ""
tiernof578e552018-11-08 19:07:20 +01002549 vnfr_scaled = False
tierno59d22d22018-09-25 18:10:19 +02002550 try:
kuused124bfe2019-06-18 12:09:24 +02002551 # wait for any previous tasks in process
tierno3cf81a32019-11-11 17:07:00 +00002552 step = "Waiting for previous operations to terminate"
kuused124bfe2019-06-18 12:09:24 +02002553 await self.lcm_tasks.waitfor_related_HA('ns', 'nslcmops', nslcmop_id)
tierno47e86b52018-10-10 14:05:55 +02002554
ikalyvas02d9e7b2019-05-27 18:16:01 +03002555 step = "Getting nslcmop from database"
ikalyvas02d9e7b2019-05-27 18:16:01 +03002556 self.logger.debug(step + " after having waited for previous tasks to be completed")
2557 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
2558 step = "Getting nsr from database"
2559 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2560
2561 old_operational_status = db_nsr["operational-status"]
2562 old_config_status = db_nsr["config-status"]
tierno59d22d22018-09-25 18:10:19 +02002563 step = "Parsing scaling parameters"
tierno9babfda2019-06-07 12:36:50 +00002564 # self.logger.debug(step)
tierno59d22d22018-09-25 18:10:19 +02002565 db_nsr_update["operational-status"] = "scaling"
2566 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernoe4f7e6c2018-11-27 14:55:30 +00002567 nsr_deployed = db_nsr["_admin"].get("deployed")
calvinosanch9f9c6f22019-11-04 13:37:39 +01002568
2569 #######
2570 nsr_deployed = db_nsr["_admin"].get("deployed")
2571 vnf_index = db_nslcmop["operationParams"].get("member_vnf_index")
tiernoda6fb102019-11-23 00:36:52 +00002572 # vdu_id = db_nslcmop["operationParams"].get("vdu_id")
2573 # vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
2574 # vdu_name = db_nslcmop["operationParams"].get("vdu_name")
calvinosanch9f9c6f22019-11-04 13:37:39 +01002575 #######
2576
tiernoe4f7e6c2018-11-27 14:55:30 +00002577 RO_nsr_id = nsr_deployed["RO"]["nsr_id"]
tierno59d22d22018-09-25 18:10:19 +02002578 vnf_index = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
2579 scaling_group = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
2580 scaling_type = db_nslcmop["operationParams"]["scaleVnfData"]["scaleVnfType"]
2581 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
2582
tierno82974b22018-11-27 21:55:36 +00002583 # for backward compatibility
2584 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
2585 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
2586 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
2587 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2588
tierno59d22d22018-09-25 18:10:19 +02002589 step = "Getting vnfr from database"
2590 db_vnfr = self.db.get_one("vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id})
2591 step = "Getting vnfd from database"
2592 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
ikalyvas02d9e7b2019-05-27 18:16:01 +03002593
tierno59d22d22018-09-25 18:10:19 +02002594 step = "Getting scaling-group-descriptor"
2595 for scaling_descriptor in db_vnfd["scaling-group-descriptor"]:
2596 if scaling_descriptor["name"] == scaling_group:
2597 break
2598 else:
2599 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
2600 "at vnfd:scaling-group-descriptor".format(scaling_group))
ikalyvas02d9e7b2019-05-27 18:16:01 +03002601
tierno59d22d22018-09-25 18:10:19 +02002602 # cooldown_time = 0
2603 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
2604 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
2605 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
2606 # break
2607
2608 # TODO check if ns is in a proper status
tierno15b1cf12019-08-29 13:21:40 +00002609 step = "Sending scale order to VIM"
tierno59d22d22018-09-25 18:10:19 +02002610 nb_scale_op = 0
2611 if not db_nsr["_admin"].get("scaling-group"):
2612 self.update_db_2("nsrs", nsr_id, {"_admin.scaling-group": [{"name": scaling_group, "nb-scale-op": 0}]})
2613 admin_scale_index = 0
2614 else:
2615 for admin_scale_index, admin_scale_info in enumerate(db_nsr["_admin"]["scaling-group"]):
2616 if admin_scale_info["name"] == scaling_group:
2617 nb_scale_op = admin_scale_info.get("nb-scale-op", 0)
2618 break
tierno9ab95942018-10-10 16:44:22 +02002619 else: # not found, set index one plus last element and add new entry with the name
2620 admin_scale_index += 1
2621 db_nsr_update["_admin.scaling-group.{}.name".format(admin_scale_index)] = scaling_group
tierno59d22d22018-09-25 18:10:19 +02002622 RO_scaling_info = []
2623 vdu_scaling_info = {"scaling_group_name": scaling_group, "vdu": []}
2624 if scaling_type == "SCALE_OUT":
2625 # count if max-instance-count is reached
kuuse818d70c2019-08-07 14:43:44 +02002626 max_instance_count = scaling_descriptor.get("max-instance-count", 10)
2627 # self.logger.debug("MAX_INSTANCE_COUNT is {}".format(max_instance_count))
2628 if nb_scale_op >= max_instance_count:
2629 raise LcmException("reached the limit of {} (max-instance-count) "
2630 "scaling-out operations for the "
2631 "scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group))
kuuse8b998e42019-07-30 15:22:16 +02002632
ikalyvas02d9e7b2019-05-27 18:16:01 +03002633 nb_scale_op += 1
tierno59d22d22018-09-25 18:10:19 +02002634 vdu_scaling_info["scaling_direction"] = "OUT"
2635 vdu_scaling_info["vdu-create"] = {}
2636 for vdu_scale_info in scaling_descriptor["vdu"]:
2637 RO_scaling_info.append({"osm_vdu_id": vdu_scale_info["vdu-id-ref"], "member-vnf-index": vnf_index,
2638 "type": "create", "count": vdu_scale_info.get("count", 1)})
2639 vdu_scaling_info["vdu-create"][vdu_scale_info["vdu-id-ref"]] = vdu_scale_info.get("count", 1)
ikalyvas02d9e7b2019-05-27 18:16:01 +03002640
tierno59d22d22018-09-25 18:10:19 +02002641 elif scaling_type == "SCALE_IN":
2642 # count if min-instance-count is reached
tierno27246d82018-09-27 15:59:09 +02002643 min_instance_count = 0
tierno59d22d22018-09-25 18:10:19 +02002644 if "min-instance-count" in scaling_descriptor and scaling_descriptor["min-instance-count"] is not None:
2645 min_instance_count = int(scaling_descriptor["min-instance-count"])
tierno9babfda2019-06-07 12:36:50 +00002646 if nb_scale_op <= min_instance_count:
2647 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
2648 "scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group))
ikalyvas02d9e7b2019-05-27 18:16:01 +03002649 nb_scale_op -= 1
tierno59d22d22018-09-25 18:10:19 +02002650 vdu_scaling_info["scaling_direction"] = "IN"
2651 vdu_scaling_info["vdu-delete"] = {}
2652 for vdu_scale_info in scaling_descriptor["vdu"]:
2653 RO_scaling_info.append({"osm_vdu_id": vdu_scale_info["vdu-id-ref"], "member-vnf-index": vnf_index,
2654 "type": "delete", "count": vdu_scale_info.get("count", 1)})
2655 vdu_scaling_info["vdu-delete"][vdu_scale_info["vdu-id-ref"]] = vdu_scale_info.get("count", 1)
2656
2657 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
tierno27246d82018-09-27 15:59:09 +02002658 vdu_create = vdu_scaling_info.get("vdu-create")
2659 vdu_delete = copy(vdu_scaling_info.get("vdu-delete"))
tierno59d22d22018-09-25 18:10:19 +02002660 if vdu_scaling_info["scaling_direction"] == "IN":
2661 for vdur in reversed(db_vnfr["vdur"]):
tierno27246d82018-09-27 15:59:09 +02002662 if vdu_delete.get(vdur["vdu-id-ref"]):
2663 vdu_delete[vdur["vdu-id-ref"]] -= 1
tierno59d22d22018-09-25 18:10:19 +02002664 vdu_scaling_info["vdu"].append({
2665 "name": vdur["name"],
2666 "vdu_id": vdur["vdu-id-ref"],
2667 "interface": []
2668 })
2669 for interface in vdur["interfaces"]:
2670 vdu_scaling_info["vdu"][-1]["interface"].append({
2671 "name": interface["name"],
2672 "ip_address": interface["ip-address"],
2673 "mac_address": interface.get("mac-address"),
2674 })
tierno27246d82018-09-27 15:59:09 +02002675 vdu_delete = vdu_scaling_info.pop("vdu-delete")
tierno59d22d22018-09-25 18:10:19 +02002676
kuuseac3a8882019-10-03 10:48:06 +02002677 # PRE-SCALE BEGIN
tierno59d22d22018-09-25 18:10:19 +02002678 step = "Executing pre-scale vnf-config-primitive"
2679 if scaling_descriptor.get("scaling-config-action"):
2680 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
kuuseac3a8882019-10-03 10:48:06 +02002681 if (scaling_config_action.get("trigger") == "pre-scale-in" and scaling_type == "SCALE_IN") \
2682 or (scaling_config_action.get("trigger") == "pre-scale-out" and scaling_type == "SCALE_OUT"):
tierno59d22d22018-09-25 18:10:19 +02002683 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
2684 step = db_nslcmop_update["detailed-status"] = \
2685 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive)
tiernoda964822019-01-14 15:53:47 +00002686
tierno59d22d22018-09-25 18:10:19 +02002687 # look for primitive
tierno59d22d22018-09-25 18:10:19 +02002688 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
2689 if config_primitive["name"] == vnf_config_primitive:
tierno59d22d22018-09-25 18:10:19 +02002690 break
2691 else:
2692 raise LcmException(
2693 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
tiernoda964822019-01-14 15:53:47 +00002694 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
tierno59d22d22018-09-25 18:10:19 +02002695 "primitive".format(scaling_group, config_primitive))
tiernoda964822019-01-14 15:53:47 +00002696
tierno16fedf52019-05-24 08:38:26 +00002697 vnfr_params = {"VDU_SCALE_INFO": vdu_scaling_info}
tiernoda964822019-01-14 15:53:47 +00002698 if db_vnfr.get("additionalParamsForVnf"):
2699 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
quilesj7e13aeb2019-10-08 13:34:55 +02002700
tierno9ab95942018-10-10 16:44:22 +02002701 scale_process = "VCA"
tiernod6de1992018-10-11 13:05:52 +02002702 db_nsr_update["config-status"] = "configuring pre-scaling"
kuuseac3a8882019-10-03 10:48:06 +02002703 primitive_params = self._map_primitive_params(config_primitive, {}, vnfr_params)
2704
2705 # Pre-scale reintent check: Check if this sub-operation has been executed before
2706 op_index = self._check_or_add_scale_suboperation(
2707 db_nslcmop, nslcmop_id, vnf_index, vnf_config_primitive, primitive_params, 'PRE-SCALE')
2708 if (op_index == self.SUBOPERATION_STATUS_SKIP):
2709 # Skip sub-operation
2710 result = 'COMPLETED'
2711 result_detail = 'Done'
2712 self.logger.debug(logging_text +
2713 "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
2714 vnf_config_primitive, result, result_detail))
2715 else:
2716 if (op_index == self.SUBOPERATION_STATUS_NEW):
2717 # New sub-operation: Get index of this sub-operation
2718 op_index = len(db_nslcmop.get('_admin', {}).get('operations')) - 1
2719 self.logger.debug(logging_text + "vnf_config_primitive={} New sub-operation".
2720 format(vnf_config_primitive))
2721 else:
2722 # Reintent: Get registered params for this existing sub-operation
2723 op = db_nslcmop.get('_admin', {}).get('operations', [])[op_index]
2724 vnf_index = op.get('member_vnf_index')
2725 vnf_config_primitive = op.get('primitive')
2726 primitive_params = op.get('primitive_params')
2727 self.logger.debug(logging_text + "vnf_config_primitive={} Sub-operation reintent".
2728 format(vnf_config_primitive))
2729 # Execute the primitive, either with new (first-time) or registered (reintent) args
2730 result, result_detail = await self._ns_execute_primitive(
2731 nsr_deployed, vnf_index, None, None, None, vnf_config_primitive, primitive_params)
2732 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
2733 vnf_config_primitive, result, result_detail))
2734 # Update operationState = COMPLETED | FAILED
2735 self._update_suboperation_status(
2736 db_nslcmop, op_index, result, result_detail)
2737
tierno59d22d22018-09-25 18:10:19 +02002738 if result == "FAILED":
2739 raise LcmException(result_detail)
tiernod6de1992018-10-11 13:05:52 +02002740 db_nsr_update["config-status"] = old_config_status
2741 scale_process = None
kuuseac3a8882019-10-03 10:48:06 +02002742 # PRE-SCALE END
tierno59d22d22018-09-25 18:10:19 +02002743
kuuseac3a8882019-10-03 10:48:06 +02002744 # SCALE RO - BEGIN
2745 # Should this block be skipped if 'RO_nsr_id' == None ?
2746 # if (RO_nsr_id and RO_scaling_info):
tierno59d22d22018-09-25 18:10:19 +02002747 if RO_scaling_info:
tierno9ab95942018-10-10 16:44:22 +02002748 scale_process = "RO"
kuuseac3a8882019-10-03 10:48:06 +02002749 # Scale RO reintent check: Check if this sub-operation has been executed before
2750 op_index = self._check_or_add_scale_suboperation(
2751 db_nslcmop, vnf_index, None, None, 'SCALE-RO', RO_nsr_id, RO_scaling_info)
2752 if (op_index == self.SUBOPERATION_STATUS_SKIP):
2753 # Skip sub-operation
2754 result = 'COMPLETED'
2755 result_detail = 'Done'
2756 self.logger.debug(logging_text + "Skipped sub-operation RO, result {} {}".format(
2757 result, result_detail))
2758 else:
2759 if (op_index == self.SUBOPERATION_STATUS_NEW):
2760 # New sub-operation: Get index of this sub-operation
2761 op_index = len(db_nslcmop.get('_admin', {}).get('operations')) - 1
2762 self.logger.debug(logging_text + "New sub-operation RO")
tierno59d22d22018-09-25 18:10:19 +02002763 else:
kuuseac3a8882019-10-03 10:48:06 +02002764 # Reintent: Get registered params for this existing sub-operation
2765 op = db_nslcmop.get('_admin', {}).get('operations', [])[op_index]
2766 RO_nsr_id = op.get('RO_nsr_id')
2767 RO_scaling_info = op.get('RO_scaling_info')
2768 self.logger.debug(logging_text + "Sub-operation RO reintent".format(
2769 vnf_config_primitive))
2770
2771 RO_desc = await self.RO.create_action("ns", RO_nsr_id, {"vdu-scaling": RO_scaling_info})
2772 db_nsr_update["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index)] = nb_scale_op
2773 db_nsr_update["_admin.scaling-group.{}.time".format(admin_scale_index)] = time()
2774 # wait until ready
2775 RO_nslcmop_id = RO_desc["instance_action_id"]
2776 db_nslcmop_update["_admin.deploy.RO"] = RO_nslcmop_id
2777
2778 RO_task_done = False
2779 step = detailed_status = "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id)
2780 detailed_status_old = None
2781 self.logger.debug(logging_text + step)
2782
2783 deployment_timeout = 1 * 3600 # One hour
2784 while deployment_timeout > 0:
2785 if not RO_task_done:
2786 desc = await self.RO.show("ns", item_id_name=RO_nsr_id, extra_item="action",
2787 extra_item_id=RO_nslcmop_id)
2788 ns_status, ns_status_info = self.RO.check_action_status(desc)
2789 if ns_status == "ERROR":
2790 raise ROclient.ROClientException(ns_status_info)
2791 elif ns_status == "BUILD":
2792 detailed_status = step + "; {}".format(ns_status_info)
2793 elif ns_status == "ACTIVE":
2794 RO_task_done = True
2795 step = detailed_status = "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id)
2796 self.logger.debug(logging_text + step)
2797 else:
2798 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
tierno59d22d22018-09-25 18:10:19 +02002799 else:
quilesj7e13aeb2019-10-08 13:34:55 +02002800
kuuseac3a8882019-10-03 10:48:06 +02002801 if ns_status == "ERROR":
2802 raise ROclient.ROClientException(ns_status_info)
2803 elif ns_status == "BUILD":
2804 detailed_status = step + "; {}".format(ns_status_info)
2805 elif ns_status == "ACTIVE":
2806 step = detailed_status = \
2807 "Waiting for management IP address reported by the VIM. Updating VNFRs"
2808 if not vnfr_scaled:
2809 self.scale_vnfr(db_vnfr, vdu_create=vdu_create, vdu_delete=vdu_delete)
2810 vnfr_scaled = True
2811 try:
2812 desc = await self.RO.show("ns", RO_nsr_id)
2813 # nsr_deployed["nsr_ip"] = RO.get_ns_vnf_info(desc)
2814 self.ns_update_vnfr({db_vnfr["member-vnf-index-ref"]: db_vnfr}, desc)
2815 break
2816 except LcmExceptionNoMgmtIP:
2817 pass
2818 else:
2819 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
2820 if detailed_status != detailed_status_old:
2821 self._update_suboperation_status(
2822 db_nslcmop, op_index, 'COMPLETED', detailed_status)
2823 detailed_status_old = db_nslcmop_update["detailed-status"] = detailed_status
2824 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
tierno59d22d22018-09-25 18:10:19 +02002825
kuuseac3a8882019-10-03 10:48:06 +02002826 await asyncio.sleep(5, loop=self.loop)
2827 deployment_timeout -= 5
2828 if deployment_timeout <= 0:
2829 self._update_suboperation_status(
2830 db_nslcmop, nslcmop_id, op_index, 'FAILED', "Timeout when waiting for ns to get ready")
2831 raise ROclient.ROClientException("Timeout waiting ns to be ready")
tierno59d22d22018-09-25 18:10:19 +02002832
kuuseac3a8882019-10-03 10:48:06 +02002833 # update VDU_SCALING_INFO with the obtained ip_addresses
2834 if vdu_scaling_info["scaling_direction"] == "OUT":
2835 for vdur in reversed(db_vnfr["vdur"]):
2836 if vdu_scaling_info["vdu-create"].get(vdur["vdu-id-ref"]):
2837 vdu_scaling_info["vdu-create"][vdur["vdu-id-ref"]] -= 1
2838 vdu_scaling_info["vdu"].append({
2839 "name": vdur["name"],
2840 "vdu_id": vdur["vdu-id-ref"],
2841 "interface": []
tierno59d22d22018-09-25 18:10:19 +02002842 })
kuuseac3a8882019-10-03 10:48:06 +02002843 for interface in vdur["interfaces"]:
2844 vdu_scaling_info["vdu"][-1]["interface"].append({
2845 "name": interface["name"],
2846 "ip_address": interface["ip-address"],
2847 "mac_address": interface.get("mac-address"),
2848 })
2849 del vdu_scaling_info["vdu-create"]
2850
2851 self._update_suboperation_status(db_nslcmop, op_index, 'COMPLETED', 'Done')
2852 # SCALE RO - END
tierno59d22d22018-09-25 18:10:19 +02002853
tierno9ab95942018-10-10 16:44:22 +02002854 scale_process = None
tierno59d22d22018-09-25 18:10:19 +02002855 if db_nsr_update:
2856 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2857
kuuseac3a8882019-10-03 10:48:06 +02002858 # POST-SCALE BEGIN
tierno59d22d22018-09-25 18:10:19 +02002859 # execute primitive service POST-SCALING
2860 step = "Executing post-scale vnf-config-primitive"
2861 if scaling_descriptor.get("scaling-config-action"):
2862 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
kuuseac3a8882019-10-03 10:48:06 +02002863 if (scaling_config_action.get("trigger") == "post-scale-in" and scaling_type == "SCALE_IN") \
2864 or (scaling_config_action.get("trigger") == "post-scale-out" and scaling_type == "SCALE_OUT"):
tierno59d22d22018-09-25 18:10:19 +02002865 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
2866 step = db_nslcmop_update["detailed-status"] = \
2867 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive)
tiernoda964822019-01-14 15:53:47 +00002868
tierno589befb2019-05-29 07:06:23 +00002869 vnfr_params = {"VDU_SCALE_INFO": vdu_scaling_info}
tiernoda964822019-01-14 15:53:47 +00002870 if db_vnfr.get("additionalParamsForVnf"):
2871 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
2872
tierno59d22d22018-09-25 18:10:19 +02002873 # look for primitive
tierno59d22d22018-09-25 18:10:19 +02002874 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
2875 if config_primitive["name"] == vnf_config_primitive:
tierno59d22d22018-09-25 18:10:19 +02002876 break
2877 else:
2878 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
2879 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
tierno47e86b52018-10-10 14:05:55 +02002880 "match any vnf-configuration:config-primitive".format(scaling_group,
2881 config_primitive))
tierno9ab95942018-10-10 16:44:22 +02002882 scale_process = "VCA"
tiernod6de1992018-10-11 13:05:52 +02002883 db_nsr_update["config-status"] = "configuring post-scaling"
kuuseac3a8882019-10-03 10:48:06 +02002884 primitive_params = self._map_primitive_params(config_primitive, {}, vnfr_params)
tiernod6de1992018-10-11 13:05:52 +02002885
kuuseac3a8882019-10-03 10:48:06 +02002886 # Post-scale reintent check: Check if this sub-operation has been executed before
2887 op_index = self._check_or_add_scale_suboperation(
2888 db_nslcmop, nslcmop_id, vnf_index, vnf_config_primitive, primitive_params, 'POST-SCALE')
2889 if (op_index == self.SUBOPERATION_STATUS_SKIP):
2890 # Skip sub-operation
2891 result = 'COMPLETED'
2892 result_detail = 'Done'
2893 self.logger.debug(logging_text +
2894 "vnf_config_primitive={} Skipped sub-operation, result {} {}".
2895 format(vnf_config_primitive, result, result_detail))
2896 else:
2897 if (op_index == self.SUBOPERATION_STATUS_NEW):
2898 # New sub-operation: Get index of this sub-operation
2899 op_index = len(db_nslcmop.get('_admin', {}).get('operations')) - 1
2900 self.logger.debug(logging_text + "vnf_config_primitive={} New sub-operation".
2901 format(vnf_config_primitive))
2902 else:
2903 # Reintent: Get registered params for this existing sub-operation
2904 op = db_nslcmop.get('_admin', {}).get('operations', [])[op_index]
2905 vnf_index = op.get('member_vnf_index')
2906 vnf_config_primitive = op.get('primitive')
2907 primitive_params = op.get('primitive_params')
2908 self.logger.debug(logging_text + "vnf_config_primitive={} Sub-operation reintent".
2909 format(vnf_config_primitive))
2910 # Execute the primitive, either with new (first-time) or registered (reintent) args
2911 result, result_detail = await self._ns_execute_primitive(
2912 nsr_deployed, vnf_index, None, None, None, vnf_config_primitive, primitive_params)
2913 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
2914 vnf_config_primitive, result, result_detail))
2915 # Update operationState = COMPLETED | FAILED
2916 self._update_suboperation_status(
2917 db_nslcmop, op_index, result, result_detail)
2918
tierno59d22d22018-09-25 18:10:19 +02002919 if result == "FAILED":
2920 raise LcmException(result_detail)
tiernod6de1992018-10-11 13:05:52 +02002921 db_nsr_update["config-status"] = old_config_status
2922 scale_process = None
kuuseac3a8882019-10-03 10:48:06 +02002923 # POST-SCALE END
tierno59d22d22018-09-25 18:10:19 +02002924
2925 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
2926 db_nslcmop_update["statusEnteredTime"] = time()
2927 db_nslcmop_update["detailed-status"] = "done"
tiernod6de1992018-10-11 13:05:52 +02002928 db_nsr_update["detailed-status"] = "" # "scaled {} {}".format(scaling_group, scaling_type)
ikalyvas02d9e7b2019-05-27 18:16:01 +03002929 db_nsr_update["operational-status"] = "running" if old_operational_status == "failed" \
2930 else old_operational_status
tiernod6de1992018-10-11 13:05:52 +02002931 db_nsr_update["config-status"] = old_config_status
tierno59d22d22018-09-25 18:10:19 +02002932 return
2933 except (ROclient.ROClientException, DbException, LcmException) as e:
2934 self.logger.error(logging_text + "Exit Exception {}".format(e))
2935 exc = e
2936 except asyncio.CancelledError:
2937 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
2938 exc = "Operation was cancelled"
2939 except Exception as e:
2940 exc = traceback.format_exc()
2941 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
2942 finally:
2943 if exc:
2944 if db_nslcmop:
2945 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
2946 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
2947 db_nslcmop_update["statusEnteredTime"] = time()
2948 if db_nsr:
tiernod6de1992018-10-11 13:05:52 +02002949 db_nsr_update["operational-status"] = old_operational_status
2950 db_nsr_update["config-status"] = old_config_status
2951 db_nsr_update["detailed-status"] = ""
tierno47e86b52018-10-10 14:05:55 +02002952 db_nsr_update["_admin.nslcmop"] = None
tiernod6de1992018-10-11 13:05:52 +02002953 if scale_process:
2954 if "VCA" in scale_process:
2955 db_nsr_update["config-status"] = "failed"
2956 if "RO" in scale_process:
2957 db_nsr_update["operational-status"] = "failed"
2958 db_nsr_update["detailed-status"] = "FAILED scaling nslcmop={} {}: {}".format(nslcmop_id, step,
2959 exc)
tiernobaa51102018-12-14 13:16:18 +00002960 try:
2961 if db_nslcmop and db_nslcmop_update:
2962 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
2963 if db_nsr:
calvinosanch9f9c6f22019-11-04 13:37:39 +01002964 db_nsr_update["_admin.current-operation"] = None
2965 db_nsr_update["_admin.operation-type"] = None
tiernobaa51102018-12-14 13:16:18 +00002966 db_nsr_update["_admin.nslcmop"] = None
2967 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2968 except DbException as e:
2969 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno59d22d22018-09-25 18:10:19 +02002970 if nslcmop_operation_state:
2971 try:
2972 await self.msg.aiowrite("ns", "scaled", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
tierno8a518872018-12-21 13:42:14 +00002973 "operationState": nslcmop_operation_state},
2974 loop=self.loop)
tierno59d22d22018-09-25 18:10:19 +02002975 # if cooldown_time:
tiernod8323042019-08-09 11:32:23 +00002976 # await asyncio.sleep(cooldown_time, loop=self.loop)
tierno59d22d22018-09-25 18:10:19 +02002977 # await self.msg.aiowrite("ns","scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
2978 except Exception as e:
2979 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
2980 self.logger.debug(logging_text + "Exit")
2981 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_scale")