blob: fe8fc65e2aa9a653434e49080ee2e1533db07e4f [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
23import functools
24import traceback
gcalvino35be9152018-12-20 09:33:12 +010025from jinja2 import Environment, Template, meta, TemplateError, TemplateNotFound, TemplateSyntaxError
tierno59d22d22018-09-25 18:10:19 +020026
27import ROclient
tiernof578e552018-11-08 19:07:20 +010028from lcm_utils import LcmException, LcmExceptionNoMgmtIP, LcmBase
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
tierno9597c292019-02-06 09:21:27 +000032from n2vc.vnf import N2VC, N2VCPrimitiveExecutionFailed, NetworkServiceDoesNotExist
tierno59d22d22018-09-25 18:10:19 +020033
tierno27246d82018-09-27 15:59:09 +020034from copy import copy, deepcopy
tierno59d22d22018-09-25 18:10:19 +020035from http import HTTPStatus
36from time import time
tierno27246d82018-09-27 15:59:09 +020037from uuid import uuid4
tierno59d22d22018-09-25 18:10:19 +020038
39__author__ = "Alfonso Tierno"
40
41
tierno27246d82018-09-27 15:59:09 +020042def get_iterable(in_dict, in_key):
43 """
44 Similar to <dict>.get(), but if value is None, False, ..., An empty tuple is returned instead
45 :param in_dict: a dictionary
46 :param in_key: the key to look for at in_dict
47 :return: in_dict[in_var] or () if it is None or not present
48 """
49 if not in_dict.get(in_key):
50 return ()
51 return in_dict[in_key]
52
53
54def populate_dict(target_dict, key_list, value):
55 """
56 Upate target_dict creating nested dictionaries with the key_list. Last key_list item is asigned the value.
57 Example target_dict={K: J}; key_list=[a,b,c]; target_dict will be {K: J, a: {b: {c: value}}}
58 :param target_dict: dictionary to be changed
59 :param key_list: list of keys to insert at target_dict
60 :param value:
61 :return: None
62 """
63 for key in key_list[0:-1]:
64 if key not in target_dict:
65 target_dict[key] = {}
66 target_dict = target_dict[key]
67 target_dict[key_list[-1]] = value
68
69
tierno59d22d22018-09-25 18:10:19 +020070class NsLcm(LcmBase):
tierno63de62e2018-10-31 16:38:52 +010071 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 +020072 total_deploy_timeout = 2 * 3600 # global timeout for deployment
73 timeout_charm_delete = 10 * 60
74 timeout_primitive = 10 * 60 # timeout for primitive execution
tierno59d22d22018-09-25 18:10:19 +020075
76 def __init__(self, db, msg, fs, lcm_tasks, ro_config, vca_config, loop):
77 """
78 Init, Connect to database, filesystem storage, and messaging
79 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
80 :return: None
81 """
82 # logging
83 self.logger = logging.getLogger('lcm.ns')
84 self.loop = loop
85 self.lcm_tasks = lcm_tasks
86
87 super().__init__(db, msg, fs, self.logger)
88
89 self.ro_config = ro_config
90
91 self.n2vc = N2VC(
92 log=self.logger,
93 server=vca_config['host'],
94 port=vca_config['port'],
95 user=vca_config['user'],
96 secret=vca_config['secret'],
97 # TODO: This should point to the base folder where charms are stored,
98 # if there is a common one (like object storage). Otherwise, leave
99 # it unset and pass it via DeployCharms
100 # artifacts=vca_config[''],
101 artifacts=None,
tierno9597c292019-02-06 09:21:27 +0000102 juju_public_key=vca_config.get('pubkey'),
103 ca_cert=vca_config.get('cacert'),
tierno59d22d22018-09-25 18:10:19 +0200104 )
105
gcalvino35be9152018-12-20 09:33:12 +0100106 def vnfd2RO(self, vnfd, new_id=None, additionalParams=None, nsrId=None):
tierno59d22d22018-09-25 18:10:19 +0200107 """
108 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
109 :param vnfd: input vnfd
110 :param new_id: overrides vnf id if provided
tierno8a518872018-12-21 13:42:14 +0000111 :param additionalParams: Instantiation params for VNFs provided
gcalvino35be9152018-12-20 09:33:12 +0100112 :param nsrId: Id of the NSR
tierno59d22d22018-09-25 18:10:19 +0200113 :return: copy of vnfd
114 """
tierno59d22d22018-09-25 18:10:19 +0200115 try:
116 vnfd_RO = deepcopy(vnfd)
tierno8a518872018-12-21 13:42:14 +0000117 # remove unused by RO configuration, monitoring, scaling and internal keys
tierno59d22d22018-09-25 18:10:19 +0200118 vnfd_RO.pop("_id", None)
119 vnfd_RO.pop("_admin", None)
tierno8a518872018-12-21 13:42:14 +0000120 vnfd_RO.pop("vnf-configuration", None)
121 vnfd_RO.pop("monitoring-param", None)
122 vnfd_RO.pop("scaling-group-descriptor", None)
tierno59d22d22018-09-25 18:10:19 +0200123 if new_id:
124 vnfd_RO["id"] = new_id
tierno8a518872018-12-21 13:42:14 +0000125
126 # parse cloud-init or cloud-init-file with the provided variables using Jinja2
127 for vdu in get_iterable(vnfd_RO, "vdu"):
128 cloud_init_file = None
129 if vdu.get("cloud-init-file"):
tierno59d22d22018-09-25 18:10:19 +0200130 base_folder = vnfd["_admin"]["storage"]
gcalvino35be9152018-12-20 09:33:12 +0100131 cloud_init_file = "{}/{}/cloud_init/{}".format(base_folder["folder"], base_folder["pkg-dir"],
132 vdu["cloud-init-file"])
133 with self.fs.file_open(cloud_init_file, "r") as ci_file:
134 cloud_init_content = ci_file.read()
tierno59d22d22018-09-25 18:10:19 +0200135 vdu.pop("cloud-init-file", None)
tierno8a518872018-12-21 13:42:14 +0000136 elif vdu.get("cloud-init"):
gcalvino35be9152018-12-20 09:33:12 +0100137 cloud_init_content = vdu["cloud-init"]
tierno8a518872018-12-21 13:42:14 +0000138 else:
139 continue
140
141 env = Environment()
142 ast = env.parse(cloud_init_content)
143 mandatory_vars = meta.find_undeclared_variables(ast)
144 if mandatory_vars:
145 for var in mandatory_vars:
146 if not additionalParams or var not in additionalParams.keys():
147 raise LcmException("Variable '{}' defined at vnfd[id={}]:vdu[id={}]:cloud-init/cloud-init-"
148 "file, must be provided in the instantiation parameters inside the "
149 "'additionalParamsForVnf' block".format(var, vnfd["id"], vdu["id"]))
150 template = Template(cloud_init_content)
tierno2b611dd2019-01-11 10:30:57 +0000151 cloud_init_content = template.render(additionalParams or {})
gcalvino35be9152018-12-20 09:33:12 +0100152 vdu["cloud-init"] = cloud_init_content
tierno8a518872018-12-21 13:42:14 +0000153
tierno59d22d22018-09-25 18:10:19 +0200154 return vnfd_RO
155 except FsException as e:
tierno8a518872018-12-21 13:42:14 +0000156 raise LcmException("Error reading vnfd[id={}]:vdu[id={}]:cloud-init-file={}: {}".
tiernoda964822019-01-14 15:53:47 +0000157 format(vnfd["id"], vdu["id"], cloud_init_file, e))
tierno8a518872018-12-21 13:42:14 +0000158 except (TemplateError, TemplateNotFound, TemplateSyntaxError) as e:
159 raise LcmException("Error parsing Jinja2 to cloud-init content at vnfd[id={}]:vdu[id={}]: {}".
160 format(vnfd["id"], vdu["id"], e))
tierno59d22d22018-09-25 18:10:19 +0200161
162 def n2vc_callback(self, model_name, application_name, status, message, n2vc_info, task=None):
163 """
164 Callback both for charm status change and task completion
165 :param model_name: Charm model name
166 :param application_name: Charm application name
167 :param status: Can be
168 - blocked: The unit needs manual intervention
169 - maintenance: The unit is actively deploying/configuring
170 - waiting: The unit is waiting for another charm to be ready
171 - active: The unit is deployed, configured, and ready
172 - error: The charm has failed and needs attention.
173 - terminated: The charm has been destroyed
174 - removing,
175 - removed
176 :param message: detailed message error
tierno27246d82018-09-27 15:59:09 +0200177 :param n2vc_info: dictionary with information shared with instantiate task. It contains:
tierno59d22d22018-09-25 18:10:19 +0200178 nsr_id:
179 nslcmop_id:
180 lcmOperationType: currently "instantiate"
181 deployed: dictionary with {<application>: {operational-status: <status>, detailed-status: <text>}}
182 db_update: dictionary to be filled with the changes to be wrote to database with format key.key.key: value
183 n2vc_event: event used to notify instantiation task that some change has been produced
184 :param task: None for charm status change, or task for completion task callback
185 :return:
186 """
187 try:
188 nsr_id = n2vc_info["nsr_id"]
189 deployed = n2vc_info["deployed"]
190 db_nsr_update = n2vc_info["db_update"]
191 nslcmop_id = n2vc_info["nslcmop_id"]
192 ns_operation = n2vc_info["lcmOperationType"]
193 n2vc_event = n2vc_info["n2vc_event"]
194 logging_text = "Task ns={} {}={} [n2vc_callback] application={}".format(nsr_id, ns_operation, nslcmop_id,
195 application_name)
tiernoe4f7e6c2018-11-27 14:55:30 +0000196 for vca_index, vca_deployed in enumerate(deployed):
197 if not vca_deployed:
198 continue
199 if model_name == vca_deployed["model"] and application_name == vca_deployed["application"]:
200 break
201 else:
tierno9597c292019-02-06 09:21:27 +0000202 self.logger.error(logging_text + " Not present at nsr._admin.deployed.VCA. Received model_name={}".
203 format(model_name))
tierno59d22d22018-09-25 18:10:19 +0200204 return
tierno59d22d22018-09-25 18:10:19 +0200205 if task:
206 if task.cancelled():
207 self.logger.debug(logging_text + " task Cancelled")
208 vca_deployed['operational-status'] = "error"
tiernoe4f7e6c2018-11-27 14:55:30 +0000209 db_nsr_update["_admin.deployed.VCA.{}.operational-status".format(vca_index)] = "error"
tierno59d22d22018-09-25 18:10:19 +0200210 vca_deployed['detailed-status'] = "Task Cancelled"
tiernoe4f7e6c2018-11-27 14:55:30 +0000211 db_nsr_update["_admin.deployed.VCA.{}.detailed-status".format(vca_index)] = "Task Cancelled"
tierno59d22d22018-09-25 18:10:19 +0200212
213 elif task.done():
214 exc = task.exception()
215 if exc:
216 self.logger.error(logging_text + " task Exception={}".format(exc))
217 vca_deployed['operational-status'] = "error"
tiernoe4f7e6c2018-11-27 14:55:30 +0000218 db_nsr_update["_admin.deployed.VCA.{}.operational-status".format(vca_index)] = "error"
tierno59d22d22018-09-25 18:10:19 +0200219 vca_deployed['detailed-status'] = str(exc)
tiernoe4f7e6c2018-11-27 14:55:30 +0000220 db_nsr_update["_admin.deployed.VCA.{}.detailed-status".format(vca_index)] = str(exc)
tierno59d22d22018-09-25 18:10:19 +0200221 else:
222 self.logger.debug(logging_text + " task Done")
223 # task is Done, but callback is still ongoing. So ignore
224 return
225 elif status:
tierno27246d82018-09-27 15:59:09 +0200226 self.logger.debug(logging_text + " Enter status={} message={}".format(status, message))
tierno59d22d22018-09-25 18:10:19 +0200227 if vca_deployed['operational-status'] == status:
228 return # same status, ignore
229 vca_deployed['operational-status'] = status
tiernoe4f7e6c2018-11-27 14:55:30 +0000230 db_nsr_update["_admin.deployed.VCA.{}.operational-status".format(vca_index)] = status
tierno59d22d22018-09-25 18:10:19 +0200231 vca_deployed['detailed-status'] = str(message)
tiernoe4f7e6c2018-11-27 14:55:30 +0000232 db_nsr_update["_admin.deployed.VCA.{}.detailed-status".format(vca_index)] = str(message)
tierno59d22d22018-09-25 18:10:19 +0200233 else:
234 self.logger.critical(logging_text + " Enter with bad parameters", exc_info=True)
235 return
236 # wake up instantiate task
237 n2vc_event.set()
238 except Exception as e:
239 self.logger.critical(logging_text + " Exception {}".format(e), exc_info=True)
240
tierno27246d82018-09-27 15:59:09 +0200241 def ns_params_2_RO(self, ns_params, nsd, vnfd_dict, n2vc_key_list):
tierno59d22d22018-09-25 18:10:19 +0200242 """
tierno27246d82018-09-27 15:59:09 +0200243 Creates a RO ns descriptor from OSM ns_instantiate params
tierno59d22d22018-09-25 18:10:19 +0200244 :param ns_params: OSM instantiate params
245 :return: The RO ns descriptor
246 """
247 vim_2_RO = {}
tiernob7f3f0d2019-03-20 17:17:21 +0000248 wim_2_RO = {}
tierno27246d82018-09-27 15:59:09 +0200249 # TODO feature 1417: Check that no instantiation is set over PDU
250 # check if PDU forces a concrete vim-network-id and add it
251 # check if PDU contains a SDN-assist info (dpid, switch, port) and pass it to RO
tierno59d22d22018-09-25 18:10:19 +0200252
253 def vim_account_2_RO(vim_account):
254 if vim_account in vim_2_RO:
255 return vim_2_RO[vim_account]
256
257 db_vim = self.db.get_one("vim_accounts", {"_id": vim_account})
258 if db_vim["_admin"]["operationalState"] != "ENABLED":
259 raise LcmException("VIM={} is not available. operationalState={}".format(
260 vim_account, db_vim["_admin"]["operationalState"]))
261 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
262 vim_2_RO[vim_account] = RO_vim_id
263 return RO_vim_id
264
tiernob7f3f0d2019-03-20 17:17:21 +0000265 def wim_account_2_RO(wim_account):
266 if isinstance(wim_account, str):
267 if wim_account in wim_2_RO:
268 return wim_2_RO[wim_account]
269
270 db_wim = self.db.get_one("wim_accounts", {"_id": wim_account})
271 if db_wim["_admin"]["operationalState"] != "ENABLED":
272 raise LcmException("WIM={} is not available. operationalState={}".format(
273 wim_account, db_wim["_admin"]["operationalState"]))
274 RO_wim_id = db_wim["_admin"]["deployed"]["RO-account"]
275 wim_2_RO[wim_account] = RO_wim_id
276 return RO_wim_id
277 else:
278 return wim_account
279
tierno59d22d22018-09-25 18:10:19 +0200280 def ip_profile_2_RO(ip_profile):
281 RO_ip_profile = deepcopy((ip_profile))
282 if "dns-server" in RO_ip_profile:
283 if isinstance(RO_ip_profile["dns-server"], list):
284 RO_ip_profile["dns-address"] = []
285 for ds in RO_ip_profile.pop("dns-server"):
286 RO_ip_profile["dns-address"].append(ds['address'])
287 else:
288 RO_ip_profile["dns-address"] = RO_ip_profile.pop("dns-server")
289 if RO_ip_profile.get("ip-version") == "ipv4":
290 RO_ip_profile["ip-version"] = "IPv4"
291 if RO_ip_profile.get("ip-version") == "ipv6":
292 RO_ip_profile["ip-version"] = "IPv6"
293 if "dhcp-params" in RO_ip_profile:
294 RO_ip_profile["dhcp"] = RO_ip_profile.pop("dhcp-params")
295 return RO_ip_profile
296
297 if not ns_params:
298 return None
299 RO_ns_params = {
300 # "name": ns_params["nsName"],
301 # "description": ns_params.get("nsDescription"),
302 "datacenter": vim_account_2_RO(ns_params["vimAccountId"]),
tiernob7f3f0d2019-03-20 17:17:21 +0000303 "wim_account": wim_account_2_RO(ns_params.get("wimAccountId")),
tierno59d22d22018-09-25 18:10:19 +0200304 # "scenario": ns_params["nsdId"],
tierno59d22d22018-09-25 18:10:19 +0200305 }
tierno27246d82018-09-27 15:59:09 +0200306 if n2vc_key_list:
307 for vnfd_ref, vnfd in vnfd_dict.items():
308 vdu_needed_access = []
309 mgmt_cp = None
310 if vnfd.get("vnf-configuration"):
311 if vnfd.get("mgmt-interface"):
312 if vnfd["mgmt-interface"].get("vdu-id"):
313 vdu_needed_access.append(vnfd["mgmt-interface"]["vdu-id"])
314 elif vnfd["mgmt-interface"].get("cp"):
315 mgmt_cp = vnfd["mgmt-interface"]["cp"]
316
gcalvino911ff7d2018-11-13 17:19:32 +0100317 for vdu in vnfd.get("vdu", ()):
tierno27246d82018-09-27 15:59:09 +0200318 if vdu.get("vdu-configuration"):
319 vdu_needed_access.append(vdu["id"])
320 elif mgmt_cp:
321 for vdu_interface in vdu.get("interface"):
322 if vdu_interface.get("external-connection-point-ref") and \
323 vdu_interface["external-connection-point-ref"] == mgmt_cp:
324 vdu_needed_access.append(vdu["id"])
325 mgmt_cp = None
326 break
327
328 if vdu_needed_access:
329 for vnf_member in nsd.get("constituent-vnfd"):
330 if vnf_member["vnfd-id-ref"] != vnfd_ref:
331 continue
332 for vdu in vdu_needed_access:
333 populate_dict(RO_ns_params,
334 ("vnfs", vnf_member["member-vnf-index"], "vdus", vdu, "mgmt_keys"),
335 n2vc_key_list)
336
tierno25ec7732018-10-24 18:47:11 +0200337 if ns_params.get("vduImage"):
338 RO_ns_params["vduImage"] = ns_params["vduImage"]
339
tiernoc255a822018-10-31 09:41:53 +0100340 if ns_params.get("ssh_keys"):
341 RO_ns_params["cloud-config"] = {"key-pairs": ns_params["ssh_keys"]}
tierno27246d82018-09-27 15:59:09 +0200342 for vnf_params in get_iterable(ns_params, "vnf"):
343 for constituent_vnfd in nsd["constituent-vnfd"]:
344 if constituent_vnfd["member-vnf-index"] == vnf_params["member-vnf-index"]:
345 vnf_descriptor = vnfd_dict[constituent_vnfd["vnfd-id-ref"]]
346 break
347 else:
348 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index={} is not present at nsd:"
349 "constituent-vnfd".format(vnf_params["member-vnf-index"]))
350 if vnf_params.get("vimAccountId"):
351 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "datacenter"),
352 vim_account_2_RO(vnf_params["vimAccountId"]))
tierno59d22d22018-09-25 18:10:19 +0200353
tierno27246d82018-09-27 15:59:09 +0200354 for vdu_params in get_iterable(vnf_params, "vdu"):
355 # TODO feature 1417: check that this VDU exist and it is not a PDU
356 if vdu_params.get("volume"):
357 for volume_params in vdu_params["volume"]:
358 if volume_params.get("vim-volume-id"):
359 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
360 vdu_params["id"], "devices", volume_params["name"], "vim_id"),
361 volume_params["vim-volume-id"])
362 if vdu_params.get("interface"):
363 for interface_params in vdu_params["interface"]:
364 if interface_params.get("ip-address"):
365 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
366 vdu_params["id"], "interfaces", interface_params["name"],
367 "ip_address"),
368 interface_params["ip-address"])
369 if interface_params.get("mac-address"):
370 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
371 vdu_params["id"], "interfaces", interface_params["name"],
372 "mac_address"),
373 interface_params["mac-address"])
374 if interface_params.get("floating-ip-required"):
375 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
376 vdu_params["id"], "interfaces", interface_params["name"],
377 "floating-ip"),
378 interface_params["floating-ip-required"])
379
380 for internal_vld_params in get_iterable(vnf_params, "internal-vld"):
381 if internal_vld_params.get("vim-network-name"):
382 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "networks",
383 internal_vld_params["name"], "vim-network-name"),
384 internal_vld_params["vim-network-name"])
gcalvino0d7ac8d2018-12-17 16:24:08 +0100385 if internal_vld_params.get("vim-network-id"):
386 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "networks",
387 internal_vld_params["name"], "vim-network-id"),
388 internal_vld_params["vim-network-id"])
tierno27246d82018-09-27 15:59:09 +0200389 if internal_vld_params.get("ip-profile"):
390 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "networks",
391 internal_vld_params["name"], "ip-profile"),
392 ip_profile_2_RO(internal_vld_params["ip-profile"]))
393
394 for icp_params in get_iterable(internal_vld_params, "internal-connection-point"):
395 # look for interface
396 iface_found = False
397 for vdu_descriptor in vnf_descriptor["vdu"]:
398 for vdu_interface in vdu_descriptor["interface"]:
399 if vdu_interface.get("internal-connection-point-ref") == icp_params["id-ref"]:
400 if icp_params.get("ip-address"):
401 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
402 vdu_descriptor["id"], "interfaces",
403 vdu_interface["name"], "ip_address"),
404 icp_params["ip-address"])
405
406 if icp_params.get("mac-address"):
407 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
408 vdu_descriptor["id"], "interfaces",
409 vdu_interface["name"], "mac_address"),
410 icp_params["mac-address"])
411 iface_found = True
tierno59d22d22018-09-25 18:10:19 +0200412 break
tierno27246d82018-09-27 15:59:09 +0200413 if iface_found:
414 break
415 else:
416 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
417 "internal-vld:id-ref={} is not present at vnfd:internal-"
418 "connection-point".format(vnf_params["member-vnf-index"],
419 icp_params["id-ref"]))
420
421 for vld_params in get_iterable(ns_params, "vld"):
422 if "ip-profile" in vld_params:
423 populate_dict(RO_ns_params, ("networks", vld_params["name"], "ip-profile"),
424 ip_profile_2_RO(vld_params["ip-profile"]))
tiernob7f3f0d2019-03-20 17:17:21 +0000425
426 if "wimAccountId" in vld_params and vld_params["wimAccountId"] is not None:
427 populate_dict(RO_ns_params, ("networks", vld_params["name"], "wim_account"),
428 wim_account_2_RO(vld_params["wimAccountId"])),
tierno27246d82018-09-27 15:59:09 +0200429 if vld_params.get("vim-network-name"):
430 RO_vld_sites = []
431 if isinstance(vld_params["vim-network-name"], dict):
432 for vim_account, vim_net in vld_params["vim-network-name"].items():
433 RO_vld_sites.append({
434 "netmap-use": vim_net,
435 "datacenter": vim_account_2_RO(vim_account)
436 })
437 else: # isinstance str
438 RO_vld_sites.append({"netmap-use": vld_params["vim-network-name"]})
439 if RO_vld_sites:
440 populate_dict(RO_ns_params, ("networks", vld_params["name"], "sites"), RO_vld_sites)
gcalvino0d7ac8d2018-12-17 16:24:08 +0100441 if vld_params.get("vim-network-id"):
442 RO_vld_sites = []
443 if isinstance(vld_params["vim-network-id"], dict):
444 for vim_account, vim_net in vld_params["vim-network-id"].items():
445 RO_vld_sites.append({
446 "netmap-use": vim_net,
447 "datacenter": vim_account_2_RO(vim_account)
448 })
449 else: # isinstance str
450 RO_vld_sites.append({"netmap-use": vld_params["vim-network-id"]})
451 if RO_vld_sites:
452 populate_dict(RO_ns_params, ("networks", vld_params["name"], "sites"), RO_vld_sites)
Felipe Vicens720b07a2019-01-31 02:32:09 +0100453 if vld_params.get("ns-net"):
454 if isinstance(vld_params["ns-net"], dict):
455 for vld_id, instance_scenario_id in vld_params["ns-net"].items():
456 RO_vld_ns_net = {"instance_scenario_id": instance_scenario_id, "osm_id": vld_id}
457 if RO_vld_ns_net:
458 populate_dict(RO_ns_params, ("networks", vld_params["name"], "use-network"), RO_vld_ns_net)
tierno27246d82018-09-27 15:59:09 +0200459 if "vnfd-connection-point-ref" in vld_params:
460 for cp_params in vld_params["vnfd-connection-point-ref"]:
461 # look for interface
462 for constituent_vnfd in nsd["constituent-vnfd"]:
463 if constituent_vnfd["member-vnf-index"] == cp_params["member-vnf-index-ref"]:
464 vnf_descriptor = vnfd_dict[constituent_vnfd["vnfd-id-ref"]]
465 break
466 else:
467 raise LcmException(
468 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={} "
469 "is not present at nsd:constituent-vnfd".format(cp_params["member-vnf-index-ref"]))
470 match_cp = False
471 for vdu_descriptor in vnf_descriptor["vdu"]:
472 for interface_descriptor in vdu_descriptor["interface"]:
473 if interface_descriptor.get("external-connection-point-ref") == \
474 cp_params["vnfd-connection-point-ref"]:
475 match_cp = True
tierno59d22d22018-09-25 18:10:19 +0200476 break
tierno27246d82018-09-27 15:59:09 +0200477 if match_cp:
478 break
479 else:
480 raise LcmException(
481 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={}:"
482 "vnfd-connection-point-ref={} is not present at vnfd={}".format(
483 cp_params["member-vnf-index-ref"],
484 cp_params["vnfd-connection-point-ref"],
485 vnf_descriptor["id"]))
486 if cp_params.get("ip-address"):
487 populate_dict(RO_ns_params, ("vnfs", cp_params["member-vnf-index-ref"], "vdus",
488 vdu_descriptor["id"], "interfaces",
489 interface_descriptor["name"], "ip_address"),
490 cp_params["ip-address"])
491 if cp_params.get("mac-address"):
492 populate_dict(RO_ns_params, ("vnfs", cp_params["member-vnf-index-ref"], "vdus",
493 vdu_descriptor["id"], "interfaces",
494 interface_descriptor["name"], "mac_address"),
495 cp_params["mac-address"])
tierno59d22d22018-09-25 18:10:19 +0200496 return RO_ns_params
497
tierno27246d82018-09-27 15:59:09 +0200498 def scale_vnfr(self, db_vnfr, vdu_create=None, vdu_delete=None):
499 # make a copy to do not change
500 vdu_create = copy(vdu_create)
501 vdu_delete = copy(vdu_delete)
502
503 vdurs = db_vnfr.get("vdur")
504 if vdurs is None:
505 vdurs = []
506 vdu_index = len(vdurs)
507 while vdu_index:
508 vdu_index -= 1
509 vdur = vdurs[vdu_index]
510 if vdur.get("pdu-type"):
511 continue
512 vdu_id_ref = vdur["vdu-id-ref"]
513 if vdu_create and vdu_create.get(vdu_id_ref):
514 for index in range(0, vdu_create[vdu_id_ref]):
515 vdur = deepcopy(vdur)
516 vdur["_id"] = str(uuid4())
517 vdur["count-index"] += 1
518 vdurs.insert(vdu_index+1+index, vdur)
519 del vdu_create[vdu_id_ref]
520 if vdu_delete and vdu_delete.get(vdu_id_ref):
521 del vdurs[vdu_index]
522 vdu_delete[vdu_id_ref] -= 1
523 if not vdu_delete[vdu_id_ref]:
524 del vdu_delete[vdu_id_ref]
525 # check all operations are done
526 if vdu_create or vdu_delete:
527 raise LcmException("Error scaling OUT VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
528 vdu_create))
529 if vdu_delete:
530 raise LcmException("Error scaling IN VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
531 vdu_delete))
532
533 vnfr_update = {"vdur": vdurs}
534 db_vnfr["vdur"] = vdurs
535 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
536
tiernof578e552018-11-08 19:07:20 +0100537 def ns_update_nsr(self, ns_update_nsr, db_nsr, nsr_desc_RO):
538 """
539 Updates database nsr with the RO info for the created vld
540 :param ns_update_nsr: dictionary to be filled with the updated info
541 :param db_nsr: content of db_nsr. This is also modified
542 :param nsr_desc_RO: nsr descriptor from RO
543 :return: Nothing, LcmException is raised on errors
544 """
545
546 for vld_index, vld in enumerate(get_iterable(db_nsr, "vld")):
547 for net_RO in get_iterable(nsr_desc_RO, "nets"):
548 if vld["id"] != net_RO.get("ns_net_osm_id"):
549 continue
550 vld["vim-id"] = net_RO.get("vim_net_id")
551 vld["name"] = net_RO.get("vim_name")
552 vld["status"] = net_RO.get("status")
553 vld["status-detailed"] = net_RO.get("error_msg")
554 ns_update_nsr["vld.{}".format(vld_index)] = vld
555 break
556 else:
557 raise LcmException("ns_update_nsr: Not found vld={} at RO info".format(vld["id"]))
558
tierno59d22d22018-09-25 18:10:19 +0200559 def ns_update_vnfr(self, db_vnfrs, nsr_desc_RO):
560 """
561 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 +0200562 :param db_vnfrs: dictionary with member-vnf-index: vnfr-content
563 :param nsr_desc_RO: nsr descriptor from RO
564 :return: Nothing, LcmException is raised on errors
tierno59d22d22018-09-25 18:10:19 +0200565 """
566 for vnf_index, db_vnfr in db_vnfrs.items():
567 for vnf_RO in nsr_desc_RO["vnfs"]:
tierno27246d82018-09-27 15:59:09 +0200568 if vnf_RO["member_vnf_index"] != vnf_index:
569 continue
570 vnfr_update = {}
tiernof578e552018-11-08 19:07:20 +0100571 if vnf_RO.get("ip_address"):
tierno1674de82019-04-09 13:03:14 +0000572 db_vnfr["ip-address"] = vnfr_update["ip-address"] = vnf_RO["ip_address"].split(";")[0]
tiernof578e552018-11-08 19:07:20 +0100573 elif not db_vnfr.get("ip-address"):
574 raise LcmExceptionNoMgmtIP("ns member_vnf_index '{}' has no IP address".format(vnf_index))
tierno59d22d22018-09-25 18:10:19 +0200575
tierno27246d82018-09-27 15:59:09 +0200576 for vdu_index, vdur in enumerate(get_iterable(db_vnfr, "vdur")):
577 vdur_RO_count_index = 0
578 if vdur.get("pdu-type"):
579 continue
580 for vdur_RO in get_iterable(vnf_RO, "vms"):
581 if vdur["vdu-id-ref"] != vdur_RO["vdu_osm_id"]:
582 continue
583 if vdur["count-index"] != vdur_RO_count_index:
584 vdur_RO_count_index += 1
585 continue
586 vdur["vim-id"] = vdur_RO.get("vim_vm_id")
tierno1674de82019-04-09 13:03:14 +0000587 if vdur_RO.get("ip_address"):
588 vdur["ip-address"] = vdur_RO["ip_address"].split(";")[0]
tierno274ed572019-04-04 13:33:27 +0000589 else:
590 vdur["ip-address"] = None
tierno27246d82018-09-27 15:59:09 +0200591 vdur["vdu-id-ref"] = vdur_RO.get("vdu_osm_id")
592 vdur["name"] = vdur_RO.get("vim_name")
593 vdur["status"] = vdur_RO.get("status")
594 vdur["status-detailed"] = vdur_RO.get("error_msg")
595 for ifacer in get_iterable(vdur, "interfaces"):
596 for interface_RO in get_iterable(vdur_RO, "interfaces"):
597 if ifacer["name"] == interface_RO.get("internal_name"):
598 ifacer["ip-address"] = interface_RO.get("ip_address")
599 ifacer["mac-address"] = interface_RO.get("mac_address")
600 break
601 else:
602 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} interface={} "
603 "at RO info".format(vnf_index, vdur["vdu-id-ref"], ifacer["name"]))
604 vnfr_update["vdur.{}".format(vdu_index)] = vdur
605 break
606 else:
607 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} count_index={} at "
608 "RO info".format(vnf_index, vdur["vdu-id-ref"], vdur["count-index"]))
tiernof578e552018-11-08 19:07:20 +0100609
610 for vld_index, vld in enumerate(get_iterable(db_vnfr, "vld")):
611 for net_RO in get_iterable(nsr_desc_RO, "nets"):
612 if vld["id"] != net_RO.get("vnf_net_osm_id"):
613 continue
614 vld["vim-id"] = net_RO.get("vim_net_id")
615 vld["name"] = net_RO.get("vim_name")
616 vld["status"] = net_RO.get("status")
617 vld["status-detailed"] = net_RO.get("error_msg")
618 vnfr_update["vld.{}".format(vld_index)] = vld
619 break
620 else:
621 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vld={} at RO info".format(
622 vnf_index, vld["id"]))
623
tierno27246d82018-09-27 15:59:09 +0200624 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
625 break
tierno59d22d22018-09-25 18:10:19 +0200626
627 else:
628 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} at RO info".format(vnf_index))
629
tierno59d22d22018-09-25 18:10:19 +0200630 async def instantiate(self, nsr_id, nslcmop_id):
631 logging_text = "Task ns={} instantiate={} ".format(nsr_id, nslcmop_id)
632 self.logger.debug(logging_text + "Enter")
633 # get all needed from database
tierno63de62e2018-10-31 16:38:52 +0100634 start_deploy = time()
tierno59d22d22018-09-25 18:10:19 +0200635 db_nsr = None
636 db_nslcmop = None
tierno47e86b52018-10-10 14:05:55 +0200637 db_nsr_update = {"_admin.nslcmop": nslcmop_id}
tierno59d22d22018-09-25 18:10:19 +0200638 db_nslcmop_update = {}
639 nslcmop_operation_state = None
640 db_vnfrs = {}
641 RO_descriptor_number = 0 # number of descriptors created at RO
gcalvino35be9152018-12-20 09:33:12 +0100642 vnf_index_2_RO_id = {} # map between vnfd/nsd id to the id used at RO
tierno59d22d22018-09-25 18:10:19 +0200643 n2vc_info = {}
tierno98ad6ea2019-05-30 17:16:28 +0000644 n2vc_key_list = [] # list of public keys to be injected as authorized to VMs
tierno59d22d22018-09-25 18:10:19 +0200645 exc = None
646 try:
647 step = "Getting nslcmop={} from db".format(nslcmop_id)
648 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
649 step = "Getting nsr={} from db".format(nsr_id)
650 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
tiernof578e552018-11-08 19:07:20 +0100651 ns_params = db_nslcmop.get("operationParams")
tierno59d22d22018-09-25 18:10:19 +0200652 nsd = db_nsr["nsd"]
653 nsr_name = db_nsr["name"] # TODO short-name??
tierno47e86b52018-10-10 14:05:55 +0200654
655 # look if previous tasks in process
656 task_name, task_dependency = self.lcm_tasks.lookfor_related("ns", nsr_id, nslcmop_id)
657 if task_dependency:
658 step = db_nslcmop_update["detailed-status"] = \
659 "Waiting for related tasks to be completed: {}".format(task_name)
660 self.logger.debug(logging_text + step)
661 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
662 _, pending = await asyncio.wait(task_dependency, timeout=3600)
663 if pending:
664 raise LcmException("Timeout waiting related tasks to be completed")
665
tierno27246d82018-09-27 15:59:09 +0200666 step = "Getting vnfrs from db"
667 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
668 db_vnfds_ref = {}
669 db_vnfds = {}
tierno98ad6ea2019-05-30 17:16:28 +0000670 db_vnfds_index = {}
tierno27246d82018-09-27 15:59:09 +0200671 for vnfr in db_vnfrs_list:
672 db_vnfrs[vnfr["member-vnf-index-ref"]] = vnfr
673 vnfd_id = vnfr["vnfd-id"]
674 vnfd_ref = vnfr["vnfd-ref"]
675 if vnfd_id not in db_vnfds:
676 step = "Getting vnfd={} id='{}' from db".format(vnfd_id, vnfd_ref)
677 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
678 db_vnfds_ref[vnfd_ref] = vnfd
679 db_vnfds[vnfd_id] = vnfd
tierno98ad6ea2019-05-30 17:16:28 +0000680 db_vnfds_index[vnfr["member-vnf-index-ref"]] = db_vnfds[vnfd_id]
tierno27246d82018-09-27 15:59:09 +0200681
tiernoe4f7e6c2018-11-27 14:55:30 +0000682 # Get or generates the _admin.deployed,VCA list
683 vca_deployed_list = None
tierno9597c292019-02-06 09:21:27 +0000684 vca_model_name = None
tiernoe4f7e6c2018-11-27 14:55:30 +0000685 if db_nsr["_admin"].get("deployed"):
686 vca_deployed_list = db_nsr["_admin"]["deployed"].get("VCA")
tierno9597c292019-02-06 09:21:27 +0000687 vca_model_name = db_nsr["_admin"]["deployed"].get("VCA-model-name")
tiernoe4f7e6c2018-11-27 14:55:30 +0000688 if vca_deployed_list is None:
689 vca_deployed_list = []
690 db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
tierno98ad6ea2019-05-30 17:16:28 +0000691 populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
tiernoe4f7e6c2018-11-27 14:55:30 +0000692 elif isinstance(vca_deployed_list, dict):
693 # maintain backward compatibility. Change a dict to list at database
694 vca_deployed_list = list(vca_deployed_list.values())
695 db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
tierno98ad6ea2019-05-30 17:16:28 +0000696 populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
tiernoe4f7e6c2018-11-27 14:55:30 +0000697
tierno59d22d22018-09-25 18:10:19 +0200698 db_nsr_update["detailed-status"] = "creating"
699 db_nsr_update["operational-status"] = "init"
tiernoa009e552019-01-30 16:45:44 +0000700 if not db_nsr["_admin"].get("deployed") or not db_nsr["_admin"]["deployed"].get("RO") or \
701 not db_nsr["_admin"]["deployed"]["RO"].get("vnfd"):
702 populate_dict(db_nsr, ("_admin", "deployed", "RO", "vnfd"), [])
703 db_nsr_update["_admin.deployed.RO.vnfd"] = []
tierno59d22d22018-09-25 18:10:19 +0200704
tiernobaa51102018-12-14 13:16:18 +0000705 # set state to INSTANTIATED. When instantiated NBI will not delete directly
706 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
707 self.update_db_2("nsrs", nsr_id, db_nsr_update)
708
tierno98ad6ea2019-05-30 17:16:28 +0000709 # Deploy charms
710 # The parameters we'll need to deploy a charm
711 number_to_configure = 0
712
713 def deploy_charm(vnf_index, vdu_id, vdu_name, vdu_count_index, charm_params, n2vc_info, native_charm=False):
714 """An inner function to deploy the charm from either ns, vnf or vdu
715 For ns both vnf_index and vdu_id are None.
716 For vnf only vdu_id is None
717 For vdu both vnf_index and vdu_id contain a value
718 """
719 # if not charm_params.get("rw_mgmt_ip") and vnf_index: # if NS skip mgmt_ip checking
720 # raise LcmException("ns/vnfd/vdu has not management ip address to configure it")
721
722 machine_spec = {}
723 if native_charm:
724 machine_spec["username"] = charm_params.get("username"),
tierno240fcac2019-06-03 13:39:39 +0000725 machine_spec["hostname"] = charm_params.get("rw_mgmt_ip")
tierno98ad6ea2019-05-30 17:16:28 +0000726
727 # Note: The charm needs to exist on disk at the location
728 # specified by charm_path.
729 descriptor = vnfd if vnf_index else nsd
730 base_folder = descriptor["_admin"]["storage"]
731 storage_params = self.fs.get_params()
732 charm_path = "{}{}/{}/charms/{}".format(
733 storage_params["path"],
734 base_folder["folder"],
735 base_folder["pkg-dir"],
736 proxy_charm
737 )
738
739 # ns_name will be ignored in the current version of N2VC
740 # but will be implemented for the next point release.
741 model_name = nsr_id
742 vdu_id_text = (str(vdu_id) if vdu_id else "") + "-"
743 vnf_index_text = (str(vnf_index) if vnf_index else "") + "-"
744 application_name = self.n2vc.FormatApplicationName(nsr_name, vnf_index_text, vdu_id_text)
745
746 vca_index = len(vca_deployed_list)
747 # trunk name and add two char index at the end to ensure that it is unique. It is assumed no more than
748 # 26*26 charm in the same NS
749 application_name = application_name[0:48]
750 application_name += chr(97 + vca_index // 26) + chr(97 + vca_index % 26)
751 vca_deployed_ = {
752 "member-vnf-index": vnf_index,
753 "vdu_id": vdu_id,
754 "model": model_name,
755 "application": application_name,
756 "operational-status": "init",
757 "detailed-status": "",
758 "step": "initial-deploy",
759 "vnfd_id": vnfd_id,
760 "vdu_name": vdu_name,
761 "vdu_count_index": vdu_count_index,
762 }
763 vca_deployed_list.append(vca_deployed_)
764 db_nsr_update["_admin.deployed.VCA.{}".format(vca_index)] = vca_deployed_
765 self.update_db_2("nsrs", nsr_id, db_nsr_update)
766
767 self.logger.debug("Task create_ns={} Passing artifacts path '{}' for {}".format(nsr_id, charm_path,
768 proxy_charm))
769 if not n2vc_info:
770 n2vc_info["nsr_id"] = nsr_id
771 n2vc_info["nslcmop_id"] = nslcmop_id
772 n2vc_info["n2vc_event"] = asyncio.Event(loop=self.loop)
773 n2vc_info["lcmOperationType"] = "instantiate"
774 n2vc_info["deployed"] = vca_deployed_list
775 n2vc_info["db_update"] = db_nsr_update
776 task = asyncio.ensure_future(
777 self.n2vc.DeployCharms(
778 model_name, # The network service name
779 application_name, # The application name
780 descriptor, # The vnf/nsd descriptor
781 charm_path, # Path to charm
782 charm_params, # Runtime params, like mgmt ip
783 machine_spec, # for native charms only
784 self.n2vc_callback, # Callback for status changes
785 n2vc_info, # Callback parameter
786 None, # Callback parameter (task)
787 )
788 )
789 task.add_done_callback(functools.partial(self.n2vc_callback, model_name, application_name, None, None,
790 n2vc_info))
791 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "create_charm:" + application_name, task)
792
793 step = "Looking for needed vnfd to configure with proxy charm"
794 self.logger.debug(logging_text + step)
795
796 for c_vnf in get_iterable(nsd, "constituent-vnfd"):
797 vnfd_id = c_vnf["vnfd-id-ref"]
798 vnf_index = str(c_vnf["member-vnf-index"])
799 vnfd = db_vnfds_ref[vnfd_id]
800
801 # Get additional parameters
802 vnfr_params = {}
803 if db_vnfrs[vnf_index].get("additionalParamsForVnf"):
804 vnfr_params = db_vnfrs[vnf_index]["additionalParamsForVnf"].copy()
805 for k, v in vnfr_params.items():
806 if isinstance(v, str) and v.startswith("!!yaml "):
807 vnfr_params[k] = yaml.safe_load(v[7:])
808
809 step = "deploying proxy charms for configuration"
810 # Check if this VNF has a charm configuration
811 vnf_config = vnfd.get("vnf-configuration")
812 if vnf_config and vnf_config.get("juju"):
813 proxy_charm = vnf_config["juju"]["charm"]
814 if vnf_config["juju"].get("proxy") is False:
815 # native_charm, will be deployed after VM. Skip
816 proxy_charm = None
817
818 if proxy_charm:
819 if not vca_model_name:
820 step = "creating VCA model name '{}'".format(nsr_id)
821 self.logger.debug(logging_text + step)
822 await self.n2vc.CreateNetworkService(nsr_id)
823 vca_model_name = nsr_id
824 db_nsr_update["_admin.deployed.VCA-model-name"] = nsr_id
825 self.update_db_2("nsrs", nsr_id, db_nsr_update)
826 step = "deploying proxy charm to configure vnf {}".format(vnf_index)
827 vnfr_params["rw_mgmt_ip"] = db_vnfrs[vnf_index]["ip-address"]
828 charm_params = {
829 "user_values": vnfr_params,
830 "rw_mgmt_ip": db_vnfrs[vnf_index]["ip-address"],
831 "initial-config-primitive": {} # vnf_config.get('initial-config-primitive') or {}
832 }
833
834 # Login to the VCA. If there are multiple calls to login(),
835 # subsequent calls will be a nop and return immediately.
836 await self.n2vc.login()
837
838 deploy_charm(vnf_index, None, None, None, charm_params, n2vc_info)
839 number_to_configure += 1
840
841 # Deploy charms for each VDU that supports one.
842 for vdu_index, vdu in enumerate(get_iterable(vnfd, 'vdu')):
843 vdu_config = vdu.get('vdu-configuration')
844 proxy_charm = None
845
846 if vdu_config and vdu_config.get("juju"):
847 proxy_charm = vdu_config["juju"]["charm"]
tierno240fcac2019-06-03 13:39:39 +0000848 if vdu_config["juju"].get("proxy") is False:
tierno98ad6ea2019-05-30 17:16:28 +0000849 # native_charm, will be deployed after VM. Skip
850 proxy_charm = None
851
852 if proxy_charm:
853 if not vca_model_name:
854 step = "creating VCA model name"
855 await self.n2vc.CreateNetworkService(nsr_id)
856 vca_model_name = nsr_id
857 db_nsr_update["_admin.deployed.VCA-model-name"] = nsr_id
858 self.update_db_2("nsrs", nsr_id, db_nsr_update)
859 step = "deploying proxy charm to configure member_vnf_index={} vdu={}".format(vnf_index,
860 vdu["id"])
861 await self.n2vc.login()
862 vdur = db_vnfrs[vnf_index]["vdur"][vdu_index]
863 # TODO for the moment only first vdu_id contains a charm deployed
864 if vdur["vdu-id-ref"] != vdu["id"]:
865 raise LcmException("Mismatch vdur {}, vdu {} at index {} for member_vnf_index={}"
866 .format(vdur["vdu-id-ref"], vdu["id"], vdu_index, vnf_index))
867 vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
868 charm_params = {
869 "user_values": vnfr_params,
870 "rw_mgmt_ip": vdur["ip-address"],
871 "initial-config-primitive": {} # vdu_config.get('initial-config-primitive') or {}
872 }
873 deploy_charm(vnf_index, vdu["id"], vdur.get("name"), vdur["count-index"],
874 charm_params, n2vc_info)
875 number_to_configure += 1
876
877 # Check if this NS has a charm configuration
878
879 ns_config = nsd.get("ns-configuration")
880 if ns_config and ns_config.get("juju"):
881 proxy_charm = ns_config["juju"]["charm"]
tierno240fcac2019-06-03 13:39:39 +0000882 if ns_config["juju"].get("proxy") is False:
tierno98ad6ea2019-05-30 17:16:28 +0000883 # native_charm, will be deployed after VM. Skip
884 proxy_charm = None
885
886 if proxy_charm:
887 step = "deploying proxy charm to configure ns"
888 # TODO is NS magmt IP address needed?
889
890 # Get additional parameters
891 additional_params = {}
892 if db_nsr.get("additionalParamsForNs"):
893 additional_params = db_nsr["additionalParamsForNs"].copy()
894 for k, v in additional_params.items():
895 if isinstance(v, str) and v.startswith("!!yaml "):
896 additional_params[k] = yaml.safe_load(v[7:])
897
898 # additional_params["rw_mgmt_ip"] = db_nsr["ip-address"]
899 charm_params = {
900 "user_values": additional_params,
901 # "rw_mgmt_ip": db_nsr["ip-address"],
902 "initial-config-primitive": {} # ns_config.get('initial-config-primitive') or {}
903 }
904
905 # Login to the VCA. If there are multiple calls to login(),
906 # subsequent calls will be a nop and return immediately.
907 await self.n2vc.login()
908 deploy_charm(None, None, None, None, charm_params, n2vc_info)
909 number_to_configure += 1
910
911 db_nsr_update["operational-status"] = "running"
912
913 # Wait until all charms has reached blocked or active status
914 step = "waiting proxy charms to be ready"
915 if number_to_configure:
916 # wait until all charms are configured.
917 # steps are:
918 # initial-deploy
919 # get-ssh-public-key
920 # generate-ssh-key
921 # retry-get-ssh-public-key
922 # ssh-public-key-obtained
923 while time() <= start_deploy + self.total_deploy_timeout:
924 if db_nsr_update:
925 self.update_db_2("nsrs", nsr_id, db_nsr_update)
926 if db_nslcmop_update:
927 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
928
929 all_active = True
930 for vca_index, vca_deployed in enumerate(vca_deployed_list):
931 database_entry = "_admin.deployed.VCA.{}.".format(vca_index)
932 if vca_deployed["step"] == "initial-deploy":
933 if vca_deployed["operational-status"] in ("active", "blocked"):
934 step = "execute charm primitive get-ssh-public-key for member_vnf_index={} vdu_id={}" \
935 .format(vca_deployed["member-vnf-index"],
936 vca_deployed["vdu_id"])
937 self.logger.debug(logging_text + step)
938 primitive_id = await self.n2vc.ExecutePrimitive(
939 vca_deployed["model"],
940 vca_deployed["application"],
941 "get-ssh-public-key",
942 None,
943 )
944 vca_deployed["step"] = db_nsr_update[database_entry + "step"] = "get-ssh-public-key"
945 vca_deployed["primitive_id"] = db_nsr_update[database_entry + "primitive_id"] =\
946 primitive_id
947 db_nsr_update[database_entry + "operational-status"] =\
948 vca_deployed["operational-status"]
949 elif vca_deployed["step"] in ("get-ssh-public-key", "retry-get-ssh-public-key"):
950 primitive_id = vca_deployed["primitive_id"]
951 primitive_status = await self.n2vc.GetPrimitiveStatus(vca_deployed["model"],
952 primitive_id)
953 if primitive_status in ("completed", "failed"):
954 primitive_result = await self.n2vc.GetPrimitiveOutput(vca_deployed["model"],
955 primitive_id)
956 vca_deployed["primitive_id"] = db_nsr_update[database_entry + "primitive_id"] = None
957 if primitive_status == "completed" and isinstance(primitive_result, dict) and \
958 primitive_result.get("pubkey"):
959 ssh_public_key = primitive_result.get("pubkey")
960 vca_deployed["step"] = db_nsr_update[database_entry + "step"] =\
961 "ssh-public-key-obtained"
962 vca_deployed["ssh-public-key"] = db_nsr_update[database_entry + "ssh-public-key"] =\
963 ssh_public_key
964 n2vc_key_list.append(ssh_public_key)
965 step = "charm ssh-public-key for member_vnf_index={} vdu_id={} is '{}'".format(
tierno240fcac2019-06-03 13:39:39 +0000966 vca_deployed["member-vnf-index"], vca_deployed["vdu_id"], ssh_public_key)
tierno98ad6ea2019-05-30 17:16:28 +0000967 self.logger.debug(logging_text + step)
968 else: # primitive_status == "failed":
969 if vca_deployed["step"] == "get-ssh-public-key":
970 step = "execute charm primitive generate-ssh-public-key for member_vnf_index="\
971 "{} vdu_id={}".format(vca_deployed["member-vnf-index"],
972 vca_deployed["vdu_id"])
973 self.logger.debug(logging_text + step)
974 vca_deployed["step"] = db_nsr_update[database_entry + "step"] =\
975 "generate-ssh-key"
976 primitive_id = await self.n2vc.ExecutePrimitive(
977 vca_deployed["model"],
978 vca_deployed["application"],
979 "generate-ssh-key",
980 None,
981 )
982 vca_deployed["primitive_id"] = db_nsr_update[database_entry + "primitive_id"] =\
983 primitive_id
984 else: # failed for second time
985 raise LcmException(
986 "error executing primitive get-ssh-public-key: {}".format(primitive_result))
987
988 elif vca_deployed["step"] == "generate-ssh-key":
989 primitive_id = vca_deployed["primitive_id"]
990 primitive_status = await self.n2vc.GetPrimitiveStatus(vca_deployed["model"],
991 primitive_id)
992 if primitive_status in ("completed", "failed"):
993 primitive_result = await self.n2vc.GetPrimitiveOutput(vca_deployed["model"],
994 primitive_id)
995 vca_deployed["primitive_id"] = db_nsr_update[
996 database_entry + "primitive_id"] = None
997 if primitive_status == "completed":
998 step = "execute primitive get-ssh-public-key again for member_vnf_index={} "\
999 "vdu_id={}".format(vca_deployed["member-vnf-index"],
1000 vca_deployed["vdu_id"])
1001 self.logger.debug(logging_text + step)
1002 vca_deployed["step"] = db_nsr_update[database_entry + "step"] = \
1003 "retry-get-ssh-public-key"
1004 primitive_id = await self.n2vc.ExecutePrimitive(
1005 vca_deployed["model"],
1006 vca_deployed["application"],
1007 "get-ssh-public-key",
1008 None,
1009 )
1010 vca_deployed["primitive_id"] = db_nsr_update[database_entry + "primitive_id"] =\
1011 primitive_id
1012
1013 else: # primitive_status == "failed":
1014 raise LcmException("error executing primitive generate-ssh-key: {}"
1015 .format(primitive_result))
1016
1017 if vca_deployed["step"] != "ssh-public-key-obtained":
1018 all_active = False
1019
1020 if all_active:
1021 break
1022 await asyncio.sleep(5)
1023 else: # total_deploy_timeout
1024 raise LcmException("Timeout waiting charm to be initialized for member_vnf_index={} vdu_id={}"
1025 .format(vca_deployed["member-vnf-index"], vca_deployed["vdu_id"]))
1026
1027 # deploy RO
1028 RO = ROclient.ROClient(self.loop, **self.ro_config)
tierno59d22d22018-09-25 18:10:19 +02001029 # get vnfds, instantiate at RO
gcalvino35be9152018-12-20 09:33:12 +01001030 for c_vnf in nsd.get("constituent-vnfd", ()):
1031 member_vnf_index = c_vnf["member-vnf-index"]
tiernoa009e552019-01-30 16:45:44 +00001032 vnfd = db_vnfds_ref[c_vnf['vnfd-id-ref']]
tierno27246d82018-09-27 15:59:09 +02001033 vnfd_ref = vnfd["id"]
tierno98ad6ea2019-05-30 17:16:28 +00001034 step = db_nsr_update["detailed-status"] = "Creating vnfd='{}' member_vnf_index='{}' at RO".format(
tiernoa009e552019-01-30 16:45:44 +00001035 vnfd_ref, member_vnf_index)
tierno59d22d22018-09-25 18:10:19 +02001036 # self.logger.debug(logging_text + step)
gcalvino35be9152018-12-20 09:33:12 +01001037 vnfd_id_RO = "{}.{}.{}".format(nsr_id, RO_descriptor_number, member_vnf_index[:23])
1038 vnf_index_2_RO_id[member_vnf_index] = vnfd_id_RO
tierno59d22d22018-09-25 18:10:19 +02001039 RO_descriptor_number += 1
1040
tiernoa009e552019-01-30 16:45:44 +00001041 # look position at deployed.RO.vnfd if not present it will be appended at the end
1042 for index, vnf_deployed in enumerate(db_nsr["_admin"]["deployed"]["RO"]["vnfd"]):
1043 if vnf_deployed["member-vnf-index"] == member_vnf_index:
1044 break
1045 else:
1046 index = len(db_nsr["_admin"]["deployed"]["RO"]["vnfd"])
1047 db_nsr["_admin"]["deployed"]["RO"]["vnfd"].append(None)
1048
tierno59d22d22018-09-25 18:10:19 +02001049 # look if present
tiernoa009e552019-01-30 16:45:44 +00001050 RO_update = {"member-vnf-index": member_vnf_index}
tierno59d22d22018-09-25 18:10:19 +02001051 vnfd_list = await RO.get_list("vnfd", filter_by={"osm_id": vnfd_id_RO})
1052 if vnfd_list:
tiernoa009e552019-01-30 16:45:44 +00001053 RO_update["id"] = vnfd_list[0]["uuid"]
tierno98ad6ea2019-05-30 17:16:28 +00001054 self.logger.debug(logging_text + "vnfd='{}' member_vnf_index='{}' exists at RO. Using RO_id={}".
tiernoa009e552019-01-30 16:45:44 +00001055 format(vnfd_ref, member_vnf_index, vnfd_list[0]["uuid"]))
tierno59d22d22018-09-25 18:10:19 +02001056 else:
gcalvino35be9152018-12-20 09:33:12 +01001057 vnfd_RO = self.vnfd2RO(vnfd, vnfd_id_RO, db_vnfrs[c_vnf["member-vnf-index"]].
1058 get("additionalParamsForVnf"), nsr_id)
tierno59d22d22018-09-25 18:10:19 +02001059 desc = await RO.create("vnfd", descriptor=vnfd_RO)
tiernoa009e552019-01-30 16:45:44 +00001060 RO_update["id"] = desc["uuid"]
tierno98ad6ea2019-05-30 17:16:28 +00001061 self.logger.debug(logging_text + "vnfd='{}' member_vnf_index='{}' created at RO. RO_id={}".format(
tiernoa009e552019-01-30 16:45:44 +00001062 vnfd_ref, member_vnf_index, desc["uuid"]))
1063 db_nsr_update["_admin.deployed.RO.vnfd.{}".format(index)] = RO_update
1064 db_nsr["_admin"]["deployed"]["RO"]["vnfd"][index] = RO_update
tierno59d22d22018-09-25 18:10:19 +02001065 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1066
1067 # create nsd at RO
tierno27246d82018-09-27 15:59:09 +02001068 nsd_ref = nsd["id"]
1069 step = db_nsr_update["detailed-status"] = "Creating nsd={} at RO".format(nsd_ref)
tierno59d22d22018-09-25 18:10:19 +02001070 # self.logger.debug(logging_text + step)
1071
tierno27246d82018-09-27 15:59:09 +02001072 RO_osm_nsd_id = "{}.{}.{}".format(nsr_id, RO_descriptor_number, nsd_ref[:23])
tierno59d22d22018-09-25 18:10:19 +02001073 RO_descriptor_number += 1
1074 nsd_list = await RO.get_list("nsd", filter_by={"osm_id": RO_osm_nsd_id})
1075 if nsd_list:
1076 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = nsd_list[0]["uuid"]
1077 self.logger.debug(logging_text + "nsd={} exists at RO. Using RO_id={}".format(
tierno27246d82018-09-27 15:59:09 +02001078 nsd_ref, RO_nsd_uuid))
tierno59d22d22018-09-25 18:10:19 +02001079 else:
1080 nsd_RO = deepcopy(nsd)
1081 nsd_RO["id"] = RO_osm_nsd_id
1082 nsd_RO.pop("_id", None)
1083 nsd_RO.pop("_admin", None)
gcalvinoea0cc0a2018-11-06 13:20:29 +01001084 for c_vnf in nsd_RO.get("constituent-vnfd", ()):
gcalvino35be9152018-12-20 09:33:12 +01001085 member_vnf_index = c_vnf["member-vnf-index"]
1086 c_vnf["vnfd-id-ref"] = vnf_index_2_RO_id[member_vnf_index]
1087 for c_vld in nsd_RO.get("vld", ()):
1088 for cp in c_vld.get("vnfd-connection-point-ref", ()):
1089 member_vnf_index = cp["member-vnf-index-ref"]
1090 cp["vnfd-id-ref"] = vnf_index_2_RO_id[member_vnf_index]
1091
tierno59d22d22018-09-25 18:10:19 +02001092 desc = await RO.create("nsd", descriptor=nsd_RO)
1093 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
1094 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = desc["uuid"]
tierno27246d82018-09-27 15:59:09 +02001095 self.logger.debug(logging_text + "nsd={} created at RO. RO_id={}".format(nsd_ref, RO_nsd_uuid))
tierno59d22d22018-09-25 18:10:19 +02001096 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1097
1098 # Crate ns at RO
1099 # if present use it unless in error status
1100 RO_nsr_id = db_nsr["_admin"].get("deployed", {}).get("RO", {}).get("nsr_id")
1101 if RO_nsr_id:
1102 try:
1103 step = db_nsr_update["detailed-status"] = "Looking for existing ns at RO"
1104 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
1105 desc = await RO.show("ns", RO_nsr_id)
1106 except ROclient.ROClientException as e:
1107 if e.http_code != HTTPStatus.NOT_FOUND:
1108 raise
1109 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
1110 if RO_nsr_id:
1111 ns_status, ns_status_info = RO.check_ns_status(desc)
1112 db_nsr_update["_admin.deployed.RO.nsr_status"] = ns_status
1113 if ns_status == "ERROR":
1114 step = db_nsr_update["detailed-status"] = "Deleting ns at RO. RO_ns_id={}".format(RO_nsr_id)
1115 self.logger.debug(logging_text + step)
1116 await RO.delete("ns", RO_nsr_id)
1117 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
1118 if not RO_nsr_id:
1119 step = db_nsr_update["detailed-status"] = "Checking dependencies"
1120 # self.logger.debug(logging_text + step)
1121
1122 # check if VIM is creating and wait look if previous tasks in process
1123 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account", ns_params["vimAccountId"])
1124 if task_dependency:
1125 step = "Waiting for related tasks to be completed: {}".format(task_name)
1126 self.logger.debug(logging_text + step)
1127 await asyncio.wait(task_dependency, timeout=3600)
1128 if ns_params.get("vnf"):
1129 for vnf in ns_params["vnf"]:
1130 if "vimAccountId" in vnf:
1131 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account",
1132 vnf["vimAccountId"])
1133 if task_dependency:
1134 step = "Waiting for related tasks to be completed: {}".format(task_name)
1135 self.logger.debug(logging_text + step)
1136 await asyncio.wait(task_dependency, timeout=3600)
1137
1138 step = db_nsr_update["detailed-status"] = "Checking instantiation parameters"
tierno25ec7732018-10-24 18:47:11 +02001139
tierno27246d82018-09-27 15:59:09 +02001140 # feature 1429. Add n2vc public key to needed VMs
tierno25ec7732018-10-24 18:47:11 +02001141 n2vc_key = await self.n2vc.GetPublicKey()
tierno98ad6ea2019-05-30 17:16:28 +00001142 n2vc_key_list.append(n2vc_key)
1143 RO_ns_params = self.ns_params_2_RO(ns_params, nsd, db_vnfds_ref, n2vc_key_list)
tierno25ec7732018-10-24 18:47:11 +02001144
tierno59d22d22018-09-25 18:10:19 +02001145 step = db_nsr_update["detailed-status"] = "Creating ns at RO"
1146 desc = await RO.create("ns", descriptor=RO_ns_params,
1147 name=db_nsr["name"],
1148 scenario=RO_nsd_uuid)
1149 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = desc["uuid"]
1150 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
1151 db_nsr_update["_admin.deployed.RO.nsr_status"] = "BUILD"
1152 self.logger.debug(logging_text + "ns created at RO. RO_id={}".format(desc["uuid"]))
1153 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1154
tierno59d22d22018-09-25 18:10:19 +02001155 # wait until NS is ready
1156 step = ns_status_detailed = detailed_status = "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id)
1157 detailed_status_old = None
1158 self.logger.debug(logging_text + step)
1159
tierno63de62e2018-10-31 16:38:52 +01001160 while time() <= start_deploy + self.total_deploy_timeout:
tierno59d22d22018-09-25 18:10:19 +02001161 desc = await RO.show("ns", RO_nsr_id)
1162 ns_status, ns_status_info = RO.check_ns_status(desc)
tierno12650ec2019-03-01 09:26:30 +00001163 db_nsr_update["_admin.deployed.RO.nsr_status"] = ns_status
tierno59d22d22018-09-25 18:10:19 +02001164 if ns_status == "ERROR":
1165 raise ROclient.ROClientException(ns_status_info)
1166 elif ns_status == "BUILD":
1167 detailed_status = ns_status_detailed + "; {}".format(ns_status_info)
1168 elif ns_status == "ACTIVE":
tiernof578e552018-11-08 19:07:20 +01001169 step = detailed_status = "Waiting for management IP address reported by the VIM. Updating VNFRs"
tierno59d22d22018-09-25 18:10:19 +02001170 try:
tiernof578e552018-11-08 19:07:20 +01001171 self.ns_update_vnfr(db_vnfrs, desc)
tierno59d22d22018-09-25 18:10:19 +02001172 break
tiernof578e552018-11-08 19:07:20 +01001173 except LcmExceptionNoMgmtIP:
1174 pass
tierno59d22d22018-09-25 18:10:19 +02001175 else:
1176 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
1177 if detailed_status != detailed_status_old:
1178 detailed_status_old = db_nsr_update["detailed-status"] = detailed_status
1179 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1180 await asyncio.sleep(5, loop=self.loop)
tierno63de62e2018-10-31 16:38:52 +01001181 else: # total_deploy_timeout
tierno59d22d22018-09-25 18:10:19 +02001182 raise ROclient.ROClientException("Timeout waiting ns to be ready")
1183
tiernof578e552018-11-08 19:07:20 +01001184 step = "Updating NSR"
1185 self.ns_update_nsr(db_nsr_update, db_nsr, desc)
tierno59d22d22018-09-25 18:10:19 +02001186
tierno98ad6ea2019-05-30 17:16:28 +00001187 db_nsr_update["operational-status"] = "running"
tierno59d22d22018-09-25 18:10:19 +02001188 db_nsr["detailed-status"] = "Configuring vnfr"
1189 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1190
tierno98ad6ea2019-05-30 17:16:28 +00001191 # Configure proxy charms once VMs are up
1192 for vca_index, vca_deployed in enumerate(vca_deployed_list):
1193 vnf_index = vca_deployed.get("member-vnf-index")
1194 vdu_id = vca_deployed.get("vdu_id")
1195 vdu_name = None
1196 vdu_count_index = None
tierno59d22d22018-09-25 18:10:19 +02001197
tierno98ad6ea2019-05-30 17:16:28 +00001198 step = "executing proxy charm initial primitives for member_vnf_index={} vdu_id={}".format(vnf_index,
1199 vdu_id)
1200 add_params = {}
1201 initial_config_primitive_list = []
1202 if vnf_index:
1203 if db_vnfrs[vnf_index].get("additionalParamsForVnf"):
1204 add_params = db_vnfrs[vnf_index]["additionalParamsForVnf"].copy()
1205 vnfd = db_vnfds_index[vnf_index]
tiernod5102d22019-05-29 11:34:57 +00001206
tierno98ad6ea2019-05-30 17:16:28 +00001207 if vdu_id:
1208 for vdu_index, vdu in enumerate(get_iterable(vnfd, 'vdu')):
1209 if vdu["id"] == vdu_id:
1210 initial_config_primitive_list = vdu['vdu-configuration'].get(
1211 'initial-config-primitive', ())
1212 break
1213 else:
1214 raise LcmException("Not found vdu_id={} at vnfd:vdu".format(vdu_id))
1215 vdur = db_vnfrs[vnf_index]["vdur"][vdu_index]
1216 # TODO for the moment only first vdu_id contains a charm deployed
1217 if vdur["vdu-id-ref"] != vdu["id"]:
1218 raise LcmException("Mismatch vdur {}, vdu {} at index {} for vnf {}"
1219 .format(vdur["vdu-id-ref"], vdu["id"], vdu_index, vnf_index))
1220 add_params["rw_mgmt_ip"] = vdur["ip-address"]
1221 else:
1222 add_params["rw_mgmt_ip"] = db_vnfrs[vnf_index]["ip-address"]
1223 initial_config_primitive_list = vnfd["vnf-configuration"].get('initial-config-primitive', ())
1224 else:
1225 if db_nsr.get("additionalParamsForNs"):
1226 add_params = db_nsr["additionalParamsForNs"].copy()
1227 for k, v in add_params.items():
1228 if isinstance(v, str) and v.startswith("!!yaml "):
1229 add_params[k] = yaml.safe_load(v[7:])
1230 add_params["rw_mgmt_ip"] = None
tiernod5102d22019-05-29 11:34:57 +00001231
tierno98ad6ea2019-05-30 17:16:28 +00001232 # add primitive verify-ssh-credentials to the list after config only when is a vnf or vdu charm
1233 initial_config_primitive_list = initial_config_primitive_list.copy()
1234 if initial_config_primitive_list and vnf_index:
tierno2fc7ce52019-06-11 22:50:01 +00001235 initial_config_primitive_list.insert(1, {"name": "verify-ssh-credentials", "parameter": []})
tierno59d22d22018-09-25 18:10:19 +02001236
tierno98ad6ea2019-05-30 17:16:28 +00001237 for initial_config_primitive in initial_config_primitive_list:
1238 primitive_result, primitive_detail = await self._ns_execute_primitive(
1239 db_nsr["_admin"]["deployed"], vnf_index, vdu_id, vdu_name, vdu_count_index,
1240 initial_config_primitive["name"],
tierno2fc7ce52019-06-11 22:50:01 +00001241 self._map_primitive_params(initial_config_primitive, {}, add_params),
1242 retries=10 if initial_config_primitive["name"] == "verify-ssh-credentials" else 0,
1243 retries_interval=30)
tierno98ad6ea2019-05-30 17:16:28 +00001244 if primitive_result != "COMPLETED":
1245 raise LcmException("charm error executing primitive {} for member_vnf_index={} vdu_id={}: '{}'"
1246 .format(initial_config_primitive["name"], vca_deployed["member-vnf-index"],
1247 vca_deployed["vdu_id"], primitive_detail))
tierno59d22d22018-09-25 18:10:19 +02001248
tierno98ad6ea2019-05-30 17:16:28 +00001249 # Deploy native charms
1250 step = "Looking for needed vnfd to configure with native charm"
tierno59d22d22018-09-25 18:10:19 +02001251 self.logger.debug(logging_text + step)
1252
tiernoe4f7e6c2018-11-27 14:55:30 +00001253 for c_vnf in get_iterable(nsd, "constituent-vnfd"):
tierno59d22d22018-09-25 18:10:19 +02001254 vnfd_id = c_vnf["vnfd-id-ref"]
1255 vnf_index = str(c_vnf["member-vnf-index"])
tierno27246d82018-09-27 15:59:09 +02001256 vnfd = db_vnfds_ref[vnfd_id]
tierno59d22d22018-09-25 18:10:19 +02001257
tierno8a518872018-12-21 13:42:14 +00001258 # Get additional parameters
1259 vnfr_params = {}
1260 if db_vnfrs[vnf_index].get("additionalParamsForVnf"):
1261 vnfr_params = db_vnfrs[vnf_index]["additionalParamsForVnf"].copy()
1262 for k, v in vnfr_params.items():
1263 if isinstance(v, str) and v.startswith("!!yaml "):
1264 vnfr_params[k] = yaml.safe_load(v[7:])
1265
tierno59d22d22018-09-25 18:10:19 +02001266 # Check if this VNF has a charm configuration
1267 vnf_config = vnfd.get("vnf-configuration")
tierno59d22d22018-09-25 18:10:19 +02001268 if vnf_config and vnf_config.get("juju"):
tiernod5102d22019-05-29 11:34:57 +00001269 native_charm = vnf_config["juju"].get("proxy") is False
tierno59d22d22018-09-25 18:10:19 +02001270
tierno98ad6ea2019-05-30 17:16:28 +00001271 if native_charm:
tierno9597c292019-02-06 09:21:27 +00001272 if not vca_model_name:
1273 step = "creating VCA model name '{}'".format(nsr_id)
1274 self.logger.debug(logging_text + step)
1275 await self.n2vc.CreateNetworkService(nsr_id)
1276 vca_model_name = nsr_id
1277 db_nsr_update["_admin.deployed.VCA-model-name"] = nsr_id
1278 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tierno98ad6ea2019-05-30 17:16:28 +00001279 step = "deploying native charm for vnf_member_index={}".format(vnf_index)
tierno8a518872018-12-21 13:42:14 +00001280 vnfr_params["rw_mgmt_ip"] = db_vnfrs[vnf_index]["ip-address"]
1281 charm_params = {
1282 "user_values": vnfr_params,
1283 "rw_mgmt_ip": db_vnfrs[vnf_index]["ip-address"],
tiernod5102d22019-05-29 11:34:57 +00001284 "initial-config-primitive": vnf_config.get('initial-config-primitive') or {},
tierno8a518872018-12-21 13:42:14 +00001285 }
tierno59d22d22018-09-25 18:10:19 +02001286
tiernod5102d22019-05-29 11:34:57 +00001287 # get username
1288 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1289 # merged. Meanwhile let's get username from initial-config-primitive
1290 if vnf_config.get("initial-config-primitive"):
1291 for param in vnf_config["initial-config-primitive"][0].get("parameter", ()):
1292 if param["name"] == "ssh-username":
1293 charm_params["username"] = param["value"]
1294 if vnf_config.get("config-access") and vnf_config["config-access"].get("ssh-access"):
1295 if vnf_config["config-access"]["ssh-access"].get("required"):
1296 charm_params["username"] = vnf_config["config-access"]["ssh-access"].get("default-user")
1297
tierno59d22d22018-09-25 18:10:19 +02001298 # Login to the VCA. If there are multiple calls to login(),
1299 # subsequent calls will be a nop and return immediately.
tierno59d22d22018-09-25 18:10:19 +02001300 await self.n2vc.login()
tierno9597c292019-02-06 09:21:27 +00001301
tiernod5102d22019-05-29 11:34:57 +00001302 deploy_charm(vnf_index, None, None, None, charm_params, n2vc_info, native_charm)
tierno59d22d22018-09-25 18:10:19 +02001303 number_to_configure += 1
1304
1305 # Deploy charms for each VDU that supports one.
tiernoe4f7e6c2018-11-27 14:55:30 +00001306 for vdu_index, vdu in enumerate(get_iterable(vnfd, 'vdu')):
tierno59d22d22018-09-25 18:10:19 +02001307 vdu_config = vdu.get('vdu-configuration')
tierno98ad6ea2019-05-30 17:16:28 +00001308 native_charm = False
tierno59d22d22018-09-25 18:10:19 +02001309
1310 if vdu_config and vdu_config.get("juju"):
tiernod5102d22019-05-29 11:34:57 +00001311 native_charm = vdu_config["juju"].get("proxy") is False
tierno59d22d22018-09-25 18:10:19 +02001312
tierno98ad6ea2019-05-30 17:16:28 +00001313 if native_charm:
tierno9597c292019-02-06 09:21:27 +00001314 if not vca_model_name:
1315 step = "creating VCA model name"
1316 await self.n2vc.CreateNetworkService(nsr_id)
1317 vca_model_name = nsr_id
1318 db_nsr_update["_admin.deployed.VCA-model-name"] = nsr_id
1319 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tierno98ad6ea2019-05-30 17:16:28 +00001320 step = "deploying native charm for vnf_member_index={} vdu_id={}".format(vnf_index,
1321 vdu["id"])
tierno59d22d22018-09-25 18:10:19 +02001322 await self.n2vc.login()
tiernoe4f7e6c2018-11-27 14:55:30 +00001323 vdur = db_vnfrs[vnf_index]["vdur"][vdu_index]
1324 # TODO for the moment only first vdu_id contains a charm deployed
1325 if vdur["vdu-id-ref"] != vdu["id"]:
1326 raise LcmException("Mismatch vdur {}, vdu {} at index {} for vnf {}"
1327 .format(vdur["vdu-id-ref"], vdu["id"], vdu_index, vnf_index))
tierno8a518872018-12-21 13:42:14 +00001328 vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
1329 charm_params = {
1330 "user_values": vnfr_params,
1331 "rw_mgmt_ip": vdur["ip-address"],
1332 "initial-config-primitive": vdu_config.get('initial-config-primitive') or {}
1333 }
tiernod5102d22019-05-29 11:34:57 +00001334
1335 # get username
1336 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1337 # merged. Meanwhile let's get username from initial-config-primitive
1338 if vdu_config.get("initial-config-primitive"):
1339 for param in vdu_config["initial-config-primitive"][0].get("parameter", ()):
1340 if param["name"] == "ssh-username":
1341 charm_params["username"] = param["value"]
1342 if vdu_config.get("config-access") and vdu_config["config-access"].get("ssh-access"):
1343 if vdu_config["config-access"]["ssh-access"].get("required"):
1344 charm_params["username"] = vdu_config["config-access"]["ssh-access"].get(
1345 "default-user")
1346
tiernoe4f7e6c2018-11-27 14:55:30 +00001347 deploy_charm(vnf_index, vdu["id"], vdur.get("name"), vdur["count-index"],
tiernod5102d22019-05-29 11:34:57 +00001348 charm_params, n2vc_info, native_charm)
tierno59d22d22018-09-25 18:10:19 +02001349 number_to_configure += 1
tierno59d22d22018-09-25 18:10:19 +02001350
tierno1b633412019-02-25 16:48:23 +00001351 # Check if this NS has a charm configuration
1352
1353 ns_config = nsd.get("ns-configuration")
1354 if ns_config and ns_config.get("juju"):
tiernod5102d22019-05-29 11:34:57 +00001355 native_charm = ns_config["juju"].get("proxy") is False
tierno1b633412019-02-25 16:48:23 +00001356
tierno98ad6ea2019-05-30 17:16:28 +00001357 if native_charm:
1358 step = "deploying native charm to configure ns"
tierno1b633412019-02-25 16:48:23 +00001359 # TODO is NS magmt IP address needed?
1360
1361 # Get additional parameters
1362 additional_params = {}
1363 if db_nsr.get("additionalParamsForNs"):
1364 additional_params = db_nsr["additionalParamsForNs"].copy()
1365 for k, v in additional_params.items():
1366 if isinstance(v, str) and v.startswith("!!yaml "):
1367 additional_params[k] = yaml.safe_load(v[7:])
1368
1369 # additional_params["rw_mgmt_ip"] = db_nsr["ip-address"]
1370 charm_params = {
1371 "user_values": additional_params,
tiernod5102d22019-05-29 11:34:57 +00001372 "rw_mgmt_ip": db_nsr.get("ip-address"),
tierno1b633412019-02-25 16:48:23 +00001373 "initial-config-primitive": ns_config.get('initial-config-primitive') or {}
1374 }
1375
tiernod5102d22019-05-29 11:34:57 +00001376 # get username
1377 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1378 # merged. Meanwhile let's get username from initial-config-primitive
1379 if ns_config.get("initial-config-primitive"):
1380 for param in ns_config["initial-config-primitive"][0].get("parameter", ()):
1381 if param["name"] == "ssh-username":
1382 charm_params["username"] = param["value"]
1383 if ns_config.get("config-access") and ns_config["config-access"].get("ssh-access"):
1384 if ns_config["config-access"]["ssh-access"].get("required"):
1385 charm_params["username"] = ns_config["config-access"]["ssh-access"].get("default-user")
1386
tierno1b633412019-02-25 16:48:23 +00001387 # Login to the VCA. If there are multiple calls to login(),
1388 # subsequent calls will be a nop and return immediately.
1389 await self.n2vc.login()
tiernod5102d22019-05-29 11:34:57 +00001390 deploy_charm(None, None, None, None, charm_params, n2vc_info, native_charm)
tierno1b633412019-02-25 16:48:23 +00001391 number_to_configure += 1
1392
tierno98ad6ea2019-05-30 17:16:28 +00001393 # waiting all charms are ok
tierno59d22d22018-09-25 18:10:19 +02001394 configuration_failed = False
1395 if number_to_configure:
1396 old_status = "configuring: init: {}".format(number_to_configure)
1397 db_nsr_update["config-status"] = old_status
1398 db_nsr_update["detailed-status"] = old_status
1399 db_nslcmop_update["detailed-status"] = old_status
1400
1401 # wait until all are configured.
tierno63de62e2018-10-31 16:38:52 +01001402 while time() <= start_deploy + self.total_deploy_timeout:
tierno59d22d22018-09-25 18:10:19 +02001403 if db_nsr_update:
1404 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1405 if db_nslcmop_update:
1406 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
tierno8a518872018-12-21 13:42:14 +00001407 # TODO add a fake task that set n2vc_event after some time
tierno59d22d22018-09-25 18:10:19 +02001408 await n2vc_info["n2vc_event"].wait()
1409 n2vc_info["n2vc_event"].clear()
1410 all_active = True
1411 status_map = {}
1412 n2vc_error_text = [] # contain text error list. If empty no one is in error status
tierno63de62e2018-10-31 16:38:52 +01001413 now = time()
tiernoe4f7e6c2018-11-27 14:55:30 +00001414 for vca_deployed in vca_deployed_list:
1415 vca_status = vca_deployed["operational-status"]
tierno59d22d22018-09-25 18:10:19 +02001416 if vca_status not in status_map:
1417 # Initialize it
1418 status_map[vca_status] = 0
1419 status_map[vca_status] += 1
1420
tierno63de62e2018-10-31 16:38:52 +01001421 if vca_status == "active":
tiernoe4f7e6c2018-11-27 14:55:30 +00001422 vca_deployed.pop("time_first_error", None)
1423 vca_deployed.pop("status_first_error", None)
tierno63de62e2018-10-31 16:38:52 +01001424 continue
1425
1426 all_active = False
tierno59d22d22018-09-25 18:10:19 +02001427 if vca_status in ("error", "blocked"):
tiernoe4f7e6c2018-11-27 14:55:30 +00001428 vca_deployed["detailed-status-error"] = vca_deployed["detailed-status"]
tierno63de62e2018-10-31 16:38:52 +01001429 # if not first time in this status error
tiernoe4f7e6c2018-11-27 14:55:30 +00001430 if not vca_deployed.get("time_first_error"):
1431 vca_deployed["time_first_error"] = now
tierno63de62e2018-10-31 16:38:52 +01001432 continue
tiernoe4f7e6c2018-11-27 14:55:30 +00001433 if vca_deployed.get("time_first_error") and \
1434 now <= vca_deployed["time_first_error"] + self.timeout_vca_on_error:
tierno63de62e2018-10-31 16:38:52 +01001435 n2vc_error_text.append("member_vnf_index={} vdu_id={} {}: {}"
tiernoe4f7e6c2018-11-27 14:55:30 +00001436 .format(vca_deployed["member-vnf-index"],
1437 vca_deployed["vdu_id"], vca_status,
1438 vca_deployed["detailed-status-error"]))
tierno59d22d22018-09-25 18:10:19 +02001439
1440 if all_active:
1441 break
1442 elif n2vc_error_text:
1443 db_nsr_update["config-status"] = "failed"
1444 error_text = "fail configuring " + ";".join(n2vc_error_text)
1445 db_nsr_update["detailed-status"] = error_text
1446 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED_TEMP"
1447 db_nslcmop_update["detailed-status"] = error_text
1448 db_nslcmop_update["statusEnteredTime"] = time()
1449 configuration_failed = True
1450 break
1451 else:
1452 cs = "configuring: "
1453 separator = ""
1454 for status, num in status_map.items():
1455 cs += separator + "{}: {}".format(status, num)
1456 separator = ", "
1457 if old_status != cs:
1458 db_nsr_update["config-status"] = cs
1459 db_nsr_update["detailed-status"] = cs
1460 db_nslcmop_update["detailed-status"] = cs
1461 old_status = cs
tierno63de62e2018-10-31 16:38:52 +01001462 else: # total_deploy_timeout
1463 raise LcmException("Timeout waiting ns to be configured")
tierno59d22d22018-09-25 18:10:19 +02001464
1465 if not configuration_failed:
1466 # all is done
1467 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
1468 db_nslcmop_update["statusEnteredTime"] = time()
1469 db_nslcmop_update["detailed-status"] = "done"
1470 db_nsr_update["config-status"] = "configured"
1471 db_nsr_update["detailed-status"] = "done"
1472
tierno59d22d22018-09-25 18:10:19 +02001473 return
1474
1475 except (ROclient.ROClientException, DbException, LcmException) as e:
1476 self.logger.error(logging_text + "Exit Exception while '{}': {}".format(step, e))
1477 exc = e
1478 except asyncio.CancelledError:
1479 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1480 exc = "Operation was cancelled"
1481 except Exception as e:
1482 exc = traceback.format_exc()
1483 self.logger.critical(logging_text + "Exit Exception {} while '{}': {}".format(type(e).__name__, step, e),
1484 exc_info=True)
1485 finally:
1486 if exc:
1487 if db_nsr:
1488 db_nsr_update["detailed-status"] = "ERROR {}: {}".format(step, exc)
1489 db_nsr_update["operational-status"] = "failed"
1490 if db_nslcmop:
1491 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
1492 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
1493 db_nslcmop_update["statusEnteredTime"] = time()
tiernobaa51102018-12-14 13:16:18 +00001494 try:
1495 if db_nsr:
1496 db_nsr_update["_admin.nslcmop"] = None
1497 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1498 if db_nslcmop_update:
1499 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1500 except DbException as e:
1501 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno59d22d22018-09-25 18:10:19 +02001502 if nslcmop_operation_state:
1503 try:
1504 await self.msg.aiowrite("ns", "instantiated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
tierno8a518872018-12-21 13:42:14 +00001505 "operationState": nslcmop_operation_state},
1506 loop=self.loop)
tierno59d22d22018-09-25 18:10:19 +02001507 except Exception as e:
1508 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1509
1510 self.logger.debug(logging_text + "Exit")
1511 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_instantiate")
1512
tiernobaa51102018-12-14 13:16:18 +00001513 async def _destroy_charm(self, model, application):
1514 """
1515 Order N2VC destroy a charm
1516 :param model:
1517 :param application:
1518 :return: True if charm does not exist. False if it exist
1519 """
1520 if not await self.n2vc.HasApplication(model, application):
1521 return True # Already removed
1522 await self.n2vc.RemoveCharms(model, application)
1523 return False
1524
1525 async def _wait_charm_destroyed(self, model, application, timeout):
1526 """
1527 Wait until charm does not exist
1528 :param model:
1529 :param application:
1530 :param timeout:
1531 :return: True if not exist, False if timeout
1532 """
1533 while True:
1534 if not await self.n2vc.HasApplication(model, application):
1535 return True
1536 if timeout < 0:
1537 return False
1538 await asyncio.sleep(10)
1539 timeout -= 10
1540
kuuse0ca67472019-05-13 15:59:27 +02001541 # Check if this VNFD has a configured terminate action
1542 def _has_terminate_config_primitive(self, vnfd):
1543 vnf_config = vnfd.get("vnf-configuration")
1544 if vnf_config and vnf_config.get("terminate-config-primitive"):
1545 return True
1546 else:
1547 return False
1548
1549 # Get a numerically sorted list of the sequences for this VNFD's terminate action
1550 def _get_terminate_config_primitive_seq_list(self, vnfd):
1551 # No need to check for existing primitive twice, already done before
1552 vnf_config = vnfd.get("vnf-configuration")
1553 seq_list = vnf_config.get("terminate-config-primitive")
1554 # Get all 'seq' tags in seq_list, order sequences numerically, ascending.
1555 seq_list_sorted = sorted(seq_list, key=lambda x: int(x['seq']))
1556 return seq_list_sorted
1557
1558 @staticmethod
1559 def _create_nslcmop(nsr_id, operation, params):
1560 """
1561 Creates a ns-lcm-opp content to be stored at database.
1562 :param nsr_id: internal id of the instance
1563 :param operation: instantiate, terminate, scale, action, ...
1564 :param params: user parameters for the operation
1565 :return: dictionary following SOL005 format
1566 """
1567 # Raise exception if invalid arguments
1568 if not (nsr_id and operation and params):
1569 raise LcmException(
1570 "Parameters 'nsr_id', 'operation' and 'params' needed to create primitive not provided")
1571 now = time()
1572 _id = str(uuid4())
1573 nslcmop = {
1574 "id": _id,
1575 "_id": _id,
1576 # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1577 "operationState": "PROCESSING",
1578 "statusEnteredTime": now,
1579 "nsInstanceId": nsr_id,
1580 "lcmOperationType": operation,
1581 "startTime": now,
1582 "isAutomaticInvocation": False,
1583 "operationParams": params,
1584 "isCancelPending": False,
1585 "links": {
1586 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
1587 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
1588 }
1589 }
1590 return nslcmop
1591
1592 # Create a primitive with params from VNFD
1593 # - Called from terminate() before deleting instance
1594 # - Calls action() to execute the primitive
1595 async def _terminate_action(self, db_nslcmop, nslcmop_id, nsr_id):
1596 logging_text = "Task ns={} _terminate_action={} ".format(nsr_id, nslcmop_id)
1597 db_vnfds = {}
1598 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1599 # Loop over VNFRs
1600 for vnfr in db_vnfrs_list:
1601 vnfd_id = vnfr["vnfd-id"]
1602 vnf_index = vnfr["member-vnf-index-ref"]
1603 if vnfd_id not in db_vnfds:
1604 step = "Getting vnfd={} id='{}' from db".format(vnfd_id, vnfd_id)
1605 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
1606 db_vnfds[vnfd_id] = vnfd
1607 vnfd = db_vnfds[vnfd_id]
1608 if not self._has_terminate_config_primitive(vnfd):
1609 continue
1610 # Get the primitive's sorted sequence list
1611 seq_list = self._get_terminate_config_primitive_seq_list(vnfd)
1612 for seq in seq_list:
1613 # For each sequence in list, call terminate action
1614 step = "Calling terminate action for vnf_member_index={} primitive={}".format(
1615 vnf_index, seq.get("name"))
1616 self.logger.debug(logging_text + step)
1617 # Create the primitive for each sequence
1618 operation = "action"
1619 # primitive, i.e. "primitive": "touch"
1620 primitive = seq.get('name')
1621 primitive_params = {}
1622 params = {
1623 "member_vnf_index": vnf_index,
1624 "primitive": primitive,
1625 "primitive_params": primitive_params,
1626 }
1627 nslcmop_primitive = self._create_nslcmop(nsr_id, operation, params)
1628 # Get a copy of db_nslcmop 'admin' part
1629 db_nslcmop_action = {"_admin": deepcopy(db_nslcmop["_admin"])}
1630 # Update db_nslcmop with the primitive data
1631 db_nslcmop_action.update(nslcmop_primitive)
1632 # Create a new db entry for the created primitive, returns the new ID.
1633 # (The ID is normally obtained from Kafka.)
1634 nslcmop_terminate_action_id = self.db.create(
1635 "nslcmops", db_nslcmop_action)
1636 # Execute the primitive
1637 nslcmop_operation_state, nslcmop_operation_state_detail = await self.action(
1638 nsr_id, nslcmop_terminate_action_id)
1639 # Launch Exception if action() returns other than ['COMPLETED', 'PARTIALLY_COMPLETED']
1640 nslcmop_operation_states_ok = ['COMPLETED', 'PARTIALLY_COMPLETED']
tierno98ad6ea2019-05-30 17:16:28 +00001641 if nslcmop_operation_state not in nslcmop_operation_states_ok:
kuuse0ca67472019-05-13 15:59:27 +02001642 raise LcmException(
1643 "terminate_primitive_action for vnf_member_index={}",
1644 " primitive={} fails with error {}".format(
1645 vnf_index, seq.get("name"), nslcmop_operation_state_detail))
1646
tierno59d22d22018-09-25 18:10:19 +02001647 async def terminate(self, nsr_id, nslcmop_id):
1648 logging_text = "Task ns={} terminate={} ".format(nsr_id, nslcmop_id)
1649 self.logger.debug(logging_text + "Enter")
1650 db_nsr = None
1651 db_nslcmop = None
1652 exc = None
1653 failed_detail = [] # annotates all failed error messages
tiernobaa51102018-12-14 13:16:18 +00001654 vca_time_destroy = None # time of where destroy charm order
tierno47e86b52018-10-10 14:05:55 +02001655 db_nsr_update = {"_admin.nslcmop": nslcmop_id}
tierno59d22d22018-09-25 18:10:19 +02001656 db_nslcmop_update = {}
1657 nslcmop_operation_state = None
tiernoc2564fe2019-01-28 16:18:56 +00001658 autoremove = False # autoremove after terminated
tierno59d22d22018-09-25 18:10:19 +02001659 try:
1660 step = "Getting nslcmop={} from db".format(nslcmop_id)
1661 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
1662 step = "Getting nsr={} from db".format(nsr_id)
1663 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1664 # nsd = db_nsr["nsd"]
tiernoe4f7e6c2018-11-27 14:55:30 +00001665 nsr_deployed = deepcopy(db_nsr["_admin"].get("deployed"))
tierno59d22d22018-09-25 18:10:19 +02001666 if db_nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
1667 return
tierno59d22d22018-09-25 18:10:19 +02001668 # #TODO check if VIM is creating and wait
1669 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
kuuse0ca67472019-05-13 15:59:27 +02001670 # Call internal terminate action
1671 await self._terminate_action(db_nslcmop, nslcmop_id, nsr_id)
tierno59d22d22018-09-25 18:10:19 +02001672
1673 db_nsr_update["operational-status"] = "terminating"
1674 db_nsr_update["config-status"] = "terminating"
1675
tierno9597c292019-02-06 09:21:27 +00001676 if nsr_deployed and nsr_deployed.get("VCA-model-name"):
1677 vca_model_name = nsr_deployed["VCA-model-name"]
1678 step = "deleting VCA model name '{}' and all charms".format(vca_model_name)
1679 self.logger.debug(logging_text + step)
1680 try:
1681 await self.n2vc.DestroyNetworkService(vca_model_name)
1682 except NetworkServiceDoesNotExist:
1683 pass
1684 db_nsr_update["_admin.deployed.VCA-model-name"] = None
1685 if nsr_deployed.get("VCA"):
1686 for vca_index in range(0, len(nsr_deployed["VCA"])):
1687 db_nsr_update["_admin.deployed.VCA.{}".format(vca_index)] = None
1688 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1689 # for backward compatibility if charm have been created with "default" model name delete one by one
1690 elif nsr_deployed and nsr_deployed.get("VCA"):
tierno59d22d22018-09-25 18:10:19 +02001691 try:
1692 step = "Scheduling configuration charms removing"
1693 db_nsr_update["detailed-status"] = "Deleting charms"
1694 self.logger.debug(logging_text + step)
1695 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tierno82974b22018-11-27 21:55:36 +00001696 # for backward compatibility
1697 if isinstance(nsr_deployed["VCA"], dict):
1698 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
1699 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
1700 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1701
tiernoe4f7e6c2018-11-27 14:55:30 +00001702 for vca_index, vca_deployed in enumerate(nsr_deployed["VCA"]):
tiernobaa51102018-12-14 13:16:18 +00001703 if vca_deployed:
1704 if await self._destroy_charm(vca_deployed['model'], vca_deployed["application"]):
1705 vca_deployed.clear()
1706 db_nsr["_admin.deployed.VCA.{}".format(vca_index)] = None
1707 else:
1708 vca_time_destroy = time()
tierno59d22d22018-09-25 18:10:19 +02001709 except Exception as e:
1710 self.logger.debug(logging_text + "Failed while deleting charms: {}".format(e))
1711
1712 # remove from RO
1713 RO_fail = False
1714 RO = ROclient.ROClient(self.loop, **self.ro_config)
1715
1716 # Delete ns
1717 RO_nsr_id = RO_delete_action = None
tiernoe4f7e6c2018-11-27 14:55:30 +00001718 if nsr_deployed and nsr_deployed.get("RO"):
1719 RO_nsr_id = nsr_deployed["RO"].get("nsr_id")
1720 RO_delete_action = nsr_deployed["RO"].get("nsr_delete_action_id")
tierno59d22d22018-09-25 18:10:19 +02001721 try:
1722 if RO_nsr_id:
1723 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] = "Deleting ns at RO"
tiernoeb55b012018-11-29 08:10:04 +00001724 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1725 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tierno59d22d22018-09-25 18:10:19 +02001726 self.logger.debug(logging_text + step)
1727 desc = await RO.delete("ns", RO_nsr_id)
1728 RO_delete_action = desc["action_id"]
1729 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = RO_delete_action
1730 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
1731 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
1732 if RO_delete_action:
1733 # wait until NS is deleted from VIM
tiernobaa51102018-12-14 13:16:18 +00001734 step = detailed_status = "Waiting ns deleted from VIM. RO_id={} RO_delete_action={}".\
1735 format(RO_nsr_id, RO_delete_action)
tierno59d22d22018-09-25 18:10:19 +02001736 detailed_status_old = None
1737 self.logger.debug(logging_text + step)
1738
1739 delete_timeout = 20 * 60 # 20 minutes
1740 while delete_timeout > 0:
1741 desc = await RO.show("ns", item_id_name=RO_nsr_id, extra_item="action",
1742 extra_item_id=RO_delete_action)
1743 ns_status, ns_status_info = RO.check_action_status(desc)
1744 if ns_status == "ERROR":
1745 raise ROclient.ROClientException(ns_status_info)
1746 elif ns_status == "BUILD":
1747 detailed_status = step + "; {}".format(ns_status_info)
1748 elif ns_status == "ACTIVE":
tiernobaa51102018-12-14 13:16:18 +00001749 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
1750 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
tierno59d22d22018-09-25 18:10:19 +02001751 break
1752 else:
1753 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
tiernoeb55b012018-11-29 08:10:04 +00001754 if detailed_status != detailed_status_old:
1755 detailed_status_old = db_nslcmop_update["detailed-status"] = \
1756 db_nsr_update["detailed-status"] = detailed_status
1757 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1758 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tierno59d22d22018-09-25 18:10:19 +02001759 await asyncio.sleep(5, loop=self.loop)
1760 delete_timeout -= 5
tierno59d22d22018-09-25 18:10:19 +02001761 else: # delete_timeout <= 0:
1762 raise ROclient.ROClientException("Timeout waiting ns deleted from VIM")
1763
1764 except ROclient.ROClientException as e:
1765 if e.http_code == 404: # not found
1766 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
1767 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
tiernobaa51102018-12-14 13:16:18 +00001768 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
tierno59d22d22018-09-25 18:10:19 +02001769 self.logger.debug(logging_text + "RO_ns_id={} already deleted".format(RO_nsr_id))
1770 elif e.http_code == 409: # conflict
1771 failed_detail.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id, e))
1772 self.logger.debug(logging_text + failed_detail[-1])
1773 RO_fail = True
1774 else:
1775 failed_detail.append("RO_ns_id={} delete error: {}".format(RO_nsr_id, e))
1776 self.logger.error(logging_text + failed_detail[-1])
1777 RO_fail = True
1778
1779 # Delete nsd
tiernoe4f7e6c2018-11-27 14:55:30 +00001780 if not RO_fail and nsr_deployed and nsr_deployed.get("RO") and nsr_deployed["RO"].get("nsd_id"):
1781 RO_nsd_id = nsr_deployed["RO"]["nsd_id"]
tierno59d22d22018-09-25 18:10:19 +02001782 try:
1783 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
1784 "Deleting nsd at RO"
1785 await RO.delete("nsd", RO_nsd_id)
1786 self.logger.debug(logging_text + "RO_nsd_id={} deleted".format(RO_nsd_id))
1787 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
1788 except ROclient.ROClientException as e:
1789 if e.http_code == 404: # not found
1790 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
1791 self.logger.debug(logging_text + "RO_nsd_id={} already deleted".format(RO_nsd_id))
1792 elif e.http_code == 409: # conflict
1793 failed_detail.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id, e))
1794 self.logger.debug(logging_text + failed_detail[-1])
1795 RO_fail = True
1796 else:
1797 failed_detail.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id, e))
1798 self.logger.error(logging_text + failed_detail[-1])
1799 RO_fail = True
1800
tiernoa009e552019-01-30 16:45:44 +00001801 if not RO_fail and nsr_deployed and nsr_deployed.get("RO") and nsr_deployed["RO"].get("vnfd"):
1802 for index, vnf_deployed in enumerate(nsr_deployed["RO"]["vnfd"]):
1803 if not vnf_deployed or not vnf_deployed["id"]:
tierno59d22d22018-09-25 18:10:19 +02001804 continue
1805 try:
tiernoa009e552019-01-30 16:45:44 +00001806 RO_vnfd_id = vnf_deployed["id"]
tierno59d22d22018-09-25 18:10:19 +02001807 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
tierno98ad6ea2019-05-30 17:16:28 +00001808 "Deleting member_vnf_index={} RO_vnfd_id={} from RO".format(
tiernoa009e552019-01-30 16:45:44 +00001809 vnf_deployed["member-vnf-index"], RO_vnfd_id)
tierno59d22d22018-09-25 18:10:19 +02001810 await RO.delete("vnfd", RO_vnfd_id)
1811 self.logger.debug(logging_text + "RO_vnfd_id={} deleted".format(RO_vnfd_id))
tiernoa009e552019-01-30 16:45:44 +00001812 db_nsr_update["_admin.deployed.RO.vnfd.{}.id".format(index)] = None
tierno59d22d22018-09-25 18:10:19 +02001813 except ROclient.ROClientException as e:
1814 if e.http_code == 404: # not found
tiernoa009e552019-01-30 16:45:44 +00001815 db_nsr_update["_admin.deployed.RO.vnfd.{}.id".format(index)] = None
tierno59d22d22018-09-25 18:10:19 +02001816 self.logger.debug(logging_text + "RO_vnfd_id={} already deleted ".format(RO_vnfd_id))
1817 elif e.http_code == 409: # conflict
1818 failed_detail.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id, e))
1819 self.logger.debug(logging_text + failed_detail[-1])
1820 else:
1821 failed_detail.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id, e))
1822 self.logger.error(logging_text + failed_detail[-1])
1823
tiernobaa51102018-12-14 13:16:18 +00001824 # wait until charm deleted
1825 if vca_time_destroy:
1826 db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] = step = \
tierno59d22d22018-09-25 18:10:19 +02001827 "Waiting for deletion of configuration charms"
1828 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1829 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernobaa51102018-12-14 13:16:18 +00001830 for vca_index, vca_deployed in enumerate(nsr_deployed["VCA"]):
1831 if not vca_deployed:
1832 continue
1833 step = "Waiting for deletion of charm application_name={}".format(vca_deployed["application"])
1834 timeout = self.timeout_charm_delete - int(time() - vca_time_destroy)
1835 if not await self._wait_charm_destroyed(vca_deployed['model'], vca_deployed["application"],
1836 timeout):
1837 failed_detail.append("VCA[application_name={}] Deletion timeout".format(
1838 vca_deployed["application"]))
tierno59d22d22018-09-25 18:10:19 +02001839 else:
tiernobaa51102018-12-14 13:16:18 +00001840 db_nsr["_admin.deployed.VCA.{}".format(vca_index)] = None
tierno59d22d22018-09-25 18:10:19 +02001841
1842 if failed_detail:
1843 self.logger.error(logging_text + " ;".join(failed_detail))
1844 db_nsr_update["operational-status"] = "failed"
1845 db_nsr_update["detailed-status"] = "Deletion errors " + "; ".join(failed_detail)
1846 db_nslcmop_update["detailed-status"] = "; ".join(failed_detail)
1847 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
1848 db_nslcmop_update["statusEnteredTime"] = time()
tierno59d22d22018-09-25 18:10:19 +02001849 else:
1850 db_nsr_update["operational-status"] = "terminated"
1851 db_nsr_update["detailed-status"] = "Done"
1852 db_nsr_update["_admin.nsState"] = "NOT_INSTANTIATED"
1853 db_nslcmop_update["detailed-status"] = "Done"
1854 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
1855 db_nslcmop_update["statusEnteredTime"] = time()
tiernoc2564fe2019-01-28 16:18:56 +00001856 if db_nslcmop["operationParams"].get("autoremove"):
1857 autoremove = True
tierno59d22d22018-09-25 18:10:19 +02001858
kuuse0ca67472019-05-13 15:59:27 +02001859 except (ROclient.ROClientException, DbException, LcmException) as e:
tierno59d22d22018-09-25 18:10:19 +02001860 self.logger.error(logging_text + "Exit Exception {}".format(e))
1861 exc = e
1862 except asyncio.CancelledError:
1863 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1864 exc = "Operation was cancelled"
1865 except Exception as e:
1866 exc = traceback.format_exc()
1867 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
1868 finally:
1869 if exc and db_nslcmop:
1870 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
1871 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
1872 db_nslcmop_update["statusEnteredTime"] = time()
tiernobaa51102018-12-14 13:16:18 +00001873 try:
1874 if db_nslcmop and db_nslcmop_update:
1875 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1876 if db_nsr:
1877 db_nsr_update["_admin.nslcmop"] = None
1878 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1879 except DbException as e:
1880 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno59d22d22018-09-25 18:10:19 +02001881 if nslcmop_operation_state:
1882 try:
1883 await self.msg.aiowrite("ns", "terminated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
tiernoc2564fe2019-01-28 16:18:56 +00001884 "operationState": nslcmop_operation_state,
1885 "autoremove": autoremove},
tierno8a518872018-12-21 13:42:14 +00001886 loop=self.loop)
tierno59d22d22018-09-25 18:10:19 +02001887 except Exception as e:
1888 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1889 self.logger.debug(logging_text + "Exit")
1890 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_terminate")
1891
tiernoda964822019-01-14 15:53:47 +00001892 @staticmethod
1893 def _map_primitive_params(primitive_desc, params, instantiation_params):
1894 """
1895 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
1896 The default-value is used. If it is between < > it look for a value at instantiation_params
1897 :param primitive_desc: portion of VNFD/NSD that describes primitive
1898 :param params: Params provided by user
1899 :param instantiation_params: Instantiation params provided by user
1900 :return: a dictionary with the calculated params
1901 """
1902 calculated_params = {}
1903 for parameter in primitive_desc.get("parameter", ()):
1904 param_name = parameter["name"]
1905 if param_name in params:
1906 calculated_params[param_name] = params[param_name]
tierno98ad6ea2019-05-30 17:16:28 +00001907 elif "default-value" in parameter or "value" in parameter:
1908 if "value" in parameter:
1909 calculated_params[param_name] = parameter["value"]
1910 else:
1911 calculated_params[param_name] = parameter["default-value"]
1912 if isinstance(calculated_params[param_name], str) and calculated_params[param_name].startswith("<") \
1913 and calculated_params[param_name].endswith(">"):
1914 if calculated_params[param_name][1:-1] in instantiation_params:
1915 calculated_params[param_name] = instantiation_params[calculated_params[param_name][1:-1]]
tiernoda964822019-01-14 15:53:47 +00001916 else:
1917 raise LcmException("Parameter {} needed to execute primitive {} not provided".
1918 format(parameter["default-value"], primitive_desc["name"]))
1919 else:
1920 raise LcmException("Parameter {} needed to execute primitive {} not provided".
1921 format(param_name, primitive_desc["name"]))
tierno59d22d22018-09-25 18:10:19 +02001922
tiernoda964822019-01-14 15:53:47 +00001923 if isinstance(calculated_params[param_name], (dict, list, tuple)):
1924 calculated_params[param_name] = yaml.safe_dump(calculated_params[param_name], default_flow_style=True,
1925 width=256)
1926 elif isinstance(calculated_params[param_name], str) and calculated_params[param_name].startswith("!!yaml "):
1927 calculated_params[param_name] = calculated_params[param_name][7:]
1928 return calculated_params
1929
1930 async def _ns_execute_primitive(self, db_deployed, member_vnf_index, vdu_id, vdu_name, vdu_count_index,
tierno2fc7ce52019-06-11 22:50:01 +00001931 primitive, primitive_params, retries=0, retries_interval=30):
tiernoda964822019-01-14 15:53:47 +00001932 start_primitive_time = time()
1933 try:
1934 for vca_deployed in db_deployed["VCA"]:
1935 if not vca_deployed:
1936 continue
1937 if member_vnf_index != vca_deployed["member-vnf-index"] or vdu_id != vca_deployed["vdu_id"]:
1938 continue
1939 if vdu_name and vdu_name != vca_deployed["vdu_name"]:
1940 continue
1941 if vdu_count_index and vdu_count_index != vca_deployed["vdu_count_index"]:
1942 continue
1943 break
1944 else:
1945 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} is not "
1946 "deployed".format(member_vnf_index, vdu_id, vdu_name, vdu_count_index))
1947 model_name = vca_deployed.get("model")
1948 application_name = vca_deployed.get("application")
1949 if not model_name or not application_name:
1950 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} has not "
1951 "model or application name" .format(member_vnf_index, vdu_id, vdu_name,
1952 vdu_count_index))
tierno98ad6ea2019-05-30 17:16:28 +00001953 # if vca_deployed["operational-status"] != "active":
1954 # raise LcmException("charm for member_vnf_index={} vdu_id={} operational_status={} not 'active'".format(
1955 # member_vnf_index, vdu_id, vca_deployed["operational-status"]))
tiernoda964822019-01-14 15:53:47 +00001956 callback = None # self.n2vc_callback
1957 callback_args = () # [db_nsr, db_nslcmop, member_vnf_index, None]
1958 await self.n2vc.login()
tierno98ad6ea2019-05-30 17:16:28 +00001959 if primitive == "config":
1960 primitive_params = {"params": primitive_params}
tierno2fc7ce52019-06-11 22:50:01 +00001961 while retries >= 0:
1962 primitive_id = await self.n2vc.ExecutePrimitive(
1963 model_name,
1964 application_name,
1965 primitive,
1966 callback,
1967 *callback_args,
1968 **primitive_params
1969 )
1970 while time() - start_primitive_time < self.timeout_primitive:
1971 primitive_result_ = await self.n2vc.GetPrimitiveStatus(model_name, primitive_id)
1972 if primitive_result_ in ("completed", "failed"):
1973 primitive_result = "COMPLETED" if primitive_result_ == "completed" else "FAILED"
1974 detailed_result = await self.n2vc.GetPrimitiveOutput(model_name, primitive_id)
1975 break
1976 elif primitive_result_ is None and primitive == "config":
1977 primitive_result = "COMPLETED"
1978 detailed_result = None
1979 break
1980 else: # ("running", "pending", None):
1981 pass
1982 await asyncio.sleep(5)
1983 else:
1984 raise LcmException("timeout after {} seconds".format(self.timeout_primitive))
1985 if primitive_result == "COMPLETED":
tiernoda964822019-01-14 15:53:47 +00001986 break
tierno2fc7ce52019-06-11 22:50:01 +00001987 retries -= 1
1988 if retries >= 0:
1989 await asyncio.sleep(retries_interval)
1990
tiernoda964822019-01-14 15:53:47 +00001991 return primitive_result, detailed_result
1992 except (N2VCPrimitiveExecutionFailed, LcmException) as e:
1993 return "FAILED", str(e)
tierno59d22d22018-09-25 18:10:19 +02001994
1995 async def action(self, nsr_id, nslcmop_id):
1996 logging_text = "Task ns={} action={} ".format(nsr_id, nslcmop_id)
1997 self.logger.debug(logging_text + "Enter")
1998 # get all needed from database
1999 db_nsr = None
2000 db_nslcmop = None
tierno47e86b52018-10-10 14:05:55 +02002001 db_nsr_update = {"_admin.nslcmop": nslcmop_id}
tierno59d22d22018-09-25 18:10:19 +02002002 db_nslcmop_update = {}
2003 nslcmop_operation_state = None
kuuse0ca67472019-05-13 15:59:27 +02002004 nslcmop_operation_state_detail = None
tierno59d22d22018-09-25 18:10:19 +02002005 exc = None
2006 try:
2007 step = "Getting information from database"
2008 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
2009 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
tiernoda964822019-01-14 15:53:47 +00002010
tiernoe4f7e6c2018-11-27 14:55:30 +00002011 nsr_deployed = db_nsr["_admin"].get("deployed")
tierno1b633412019-02-25 16:48:23 +00002012 vnf_index = db_nslcmop["operationParams"].get("member_vnf_index")
tierno59d22d22018-09-25 18:10:19 +02002013 vdu_id = db_nslcmop["operationParams"].get("vdu_id")
tiernoe4f7e6c2018-11-27 14:55:30 +00002014 vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
2015 vdu_name = db_nslcmop["operationParams"].get("vdu_name")
tierno59d22d22018-09-25 18:10:19 +02002016
tierno1b633412019-02-25 16:48:23 +00002017 if vnf_index:
2018 step = "Getting vnfr from database"
2019 db_vnfr = self.db.get_one("vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id})
2020 step = "Getting vnfd from database"
2021 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
2022 else:
2023 if db_nsr.get("nsd"):
2024 db_nsd = db_nsr.get("nsd") # TODO this will be removed
2025 else:
2026 step = "Getting nsd from database"
2027 db_nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
tiernoda964822019-01-14 15:53:47 +00002028
tierno47e86b52018-10-10 14:05:55 +02002029 # look if previous tasks in process
2030 task_name, task_dependency = self.lcm_tasks.lookfor_related("ns", nsr_id, nslcmop_id)
2031 if task_dependency:
2032 step = db_nslcmop_update["detailed-status"] = \
2033 "Waiting for related tasks to be completed: {}".format(task_name)
2034 self.logger.debug(logging_text + step)
2035 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
2036 _, pending = await asyncio.wait(task_dependency, timeout=3600)
2037 if pending:
2038 raise LcmException("Timeout waiting related tasks to be completed")
2039
tierno82974b22018-11-27 21:55:36 +00002040 # for backward compatibility
2041 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
2042 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
2043 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
2044 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2045
tierno59d22d22018-09-25 18:10:19 +02002046 primitive = db_nslcmop["operationParams"]["primitive"]
2047 primitive_params = db_nslcmop["operationParams"]["primitive_params"]
tiernoda964822019-01-14 15:53:47 +00002048
2049 # look for primitive
2050 config_primitive_desc = None
2051 if vdu_id:
2052 for vdu in get_iterable(db_vnfd, "vdu"):
2053 if vdu_id == vdu["id"]:
2054 for config_primitive in vdu.get("vdu-configuration", {}).get("config-primitive", ()):
2055 if config_primitive["name"] == primitive:
2056 config_primitive_desc = config_primitive
2057 break
tierno1b633412019-02-25 16:48:23 +00002058 elif vnf_index:
2059 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
2060 if config_primitive["name"] == primitive:
2061 config_primitive_desc = config_primitive
2062 break
2063 else:
2064 for config_primitive in db_nsd.get("ns-configuration", {}).get("config-primitive", ()):
2065 if config_primitive["name"] == primitive:
2066 config_primitive_desc = config_primitive
2067 break
tiernoda964822019-01-14 15:53:47 +00002068
tierno1b633412019-02-25 16:48:23 +00002069 if not config_primitive_desc:
2070 raise LcmException("Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".
2071 format(primitive))
2072
2073 desc_params = {}
2074 if vnf_index:
2075 if db_vnfr.get("additionalParamsForVnf"):
2076 desc_params.update(db_vnfr["additionalParamsForVnf"])
2077 else:
2078 if db_nsr.get("additionalParamsForVnf"):
2079 desc_params.update(db_nsr["additionalParamsForNs"])
tiernoda964822019-01-14 15:53:47 +00002080
2081 # TODO check if ns is in a proper status
2082 result, result_detail = await self._ns_execute_primitive(
2083 nsr_deployed, vnf_index, vdu_id, vdu_name, vdu_count_index, primitive,
tierno1b633412019-02-25 16:48:23 +00002084 self._map_primitive_params(config_primitive_desc, primitive_params, desc_params))
kuuse0ca67472019-05-13 15:59:27 +02002085 db_nslcmop_update["detailed-status"] = nslcmop_operation_state_detail = result_detail
tierno59d22d22018-09-25 18:10:19 +02002086 db_nslcmop_update["operationState"] = nslcmop_operation_state = result
2087 db_nslcmop_update["statusEnteredTime"] = time()
2088 self.logger.debug(logging_text + " task Done with result {} {}".format(result, result_detail))
2089 return # database update is called inside finally
2090
2091 except (DbException, LcmException) as e:
2092 self.logger.error(logging_text + "Exit Exception {}".format(e))
2093 exc = e
2094 except asyncio.CancelledError:
2095 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
2096 exc = "Operation was cancelled"
2097 except Exception as e:
2098 exc = traceback.format_exc()
2099 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
2100 finally:
2101 if exc and db_nslcmop:
kuuse0ca67472019-05-13 15:59:27 +02002102 db_nslcmop_update["detailed-status"] = nslcmop_operation_state_detail = \
2103 "FAILED {}: {}".format(step, exc)
tierno59d22d22018-09-25 18:10:19 +02002104 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
2105 db_nslcmop_update["statusEnteredTime"] = time()
tiernobaa51102018-12-14 13:16:18 +00002106 try:
2107 if db_nslcmop_update:
2108 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
2109 if db_nsr:
2110 db_nsr_update["_admin.nslcmop"] = None
2111 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2112 except DbException as e:
2113 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno59d22d22018-09-25 18:10:19 +02002114 self.logger.debug(logging_text + "Exit")
2115 if nslcmop_operation_state:
2116 try:
2117 await self.msg.aiowrite("ns", "actioned", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
tierno8a518872018-12-21 13:42:14 +00002118 "operationState": nslcmop_operation_state},
2119 loop=self.loop)
tierno59d22d22018-09-25 18:10:19 +02002120 except Exception as e:
2121 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
2122 self.logger.debug(logging_text + "Exit")
2123 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_action")
kuuse0ca67472019-05-13 15:59:27 +02002124 return nslcmop_operation_state, nslcmop_operation_state_detail
tierno59d22d22018-09-25 18:10:19 +02002125
2126 async def scale(self, nsr_id, nslcmop_id):
2127 logging_text = "Task ns={} scale={} ".format(nsr_id, nslcmop_id)
2128 self.logger.debug(logging_text + "Enter")
2129 # get all needed from database
2130 db_nsr = None
2131 db_nslcmop = None
2132 db_nslcmop_update = {}
2133 nslcmop_operation_state = None
tierno47e86b52018-10-10 14:05:55 +02002134 db_nsr_update = {"_admin.nslcmop": nslcmop_id}
tierno59d22d22018-09-25 18:10:19 +02002135 exc = None
tierno9ab95942018-10-10 16:44:22 +02002136 # in case of error, indicates what part of scale was failed to put nsr at error status
2137 scale_process = None
tiernod6de1992018-10-11 13:05:52 +02002138 old_operational_status = ""
2139 old_config_status = ""
tiernof578e552018-11-08 19:07:20 +01002140 vnfr_scaled = False
tierno59d22d22018-09-25 18:10:19 +02002141 try:
tierno47e86b52018-10-10 14:05:55 +02002142 # look if previous tasks in process
2143 task_name, task_dependency = self.lcm_tasks.lookfor_related("ns", nsr_id, nslcmop_id)
2144 if task_dependency:
2145 step = db_nslcmop_update["detailed-status"] = \
2146 "Waiting for related tasks to be completed: {}".format(task_name)
2147 self.logger.debug(logging_text + step)
2148 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
2149 _, pending = await asyncio.wait(task_dependency, timeout=3600)
2150 if pending:
2151 raise LcmException("Timeout waiting related tasks to be completed")
2152
ikalyvas02d9e7b2019-05-27 18:16:01 +03002153 step = "Getting nslcmop from database"
ikalyvas02d9e7b2019-05-27 18:16:01 +03002154 self.logger.debug(step + " after having waited for previous tasks to be completed")
2155 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
2156 step = "Getting nsr from database"
2157 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2158
2159 old_operational_status = db_nsr["operational-status"]
2160 old_config_status = db_nsr["config-status"]
tierno59d22d22018-09-25 18:10:19 +02002161 step = "Parsing scaling parameters"
tierno9babfda2019-06-07 12:36:50 +00002162 # self.logger.debug(step)
tierno59d22d22018-09-25 18:10:19 +02002163 db_nsr_update["operational-status"] = "scaling"
2164 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernoe4f7e6c2018-11-27 14:55:30 +00002165 nsr_deployed = db_nsr["_admin"].get("deployed")
2166 RO_nsr_id = nsr_deployed["RO"]["nsr_id"]
tierno59d22d22018-09-25 18:10:19 +02002167 vnf_index = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
2168 scaling_group = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
2169 scaling_type = db_nslcmop["operationParams"]["scaleVnfData"]["scaleVnfType"]
2170 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
2171
tierno82974b22018-11-27 21:55:36 +00002172 # for backward compatibility
2173 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
2174 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
2175 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
2176 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2177
tierno59d22d22018-09-25 18:10:19 +02002178 step = "Getting vnfr from database"
2179 db_vnfr = self.db.get_one("vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id})
2180 step = "Getting vnfd from database"
2181 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
ikalyvas02d9e7b2019-05-27 18:16:01 +03002182
tierno59d22d22018-09-25 18:10:19 +02002183 step = "Getting scaling-group-descriptor"
2184 for scaling_descriptor in db_vnfd["scaling-group-descriptor"]:
2185 if scaling_descriptor["name"] == scaling_group:
2186 break
2187 else:
2188 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
2189 "at vnfd:scaling-group-descriptor".format(scaling_group))
ikalyvas02d9e7b2019-05-27 18:16:01 +03002190
tierno59d22d22018-09-25 18:10:19 +02002191 # cooldown_time = 0
2192 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
2193 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
2194 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
2195 # break
2196
2197 # TODO check if ns is in a proper status
2198 step = "Sending scale order to RO"
2199 nb_scale_op = 0
2200 if not db_nsr["_admin"].get("scaling-group"):
2201 self.update_db_2("nsrs", nsr_id, {"_admin.scaling-group": [{"name": scaling_group, "nb-scale-op": 0}]})
2202 admin_scale_index = 0
2203 else:
2204 for admin_scale_index, admin_scale_info in enumerate(db_nsr["_admin"]["scaling-group"]):
2205 if admin_scale_info["name"] == scaling_group:
2206 nb_scale_op = admin_scale_info.get("nb-scale-op", 0)
2207 break
tierno9ab95942018-10-10 16:44:22 +02002208 else: # not found, set index one plus last element and add new entry with the name
2209 admin_scale_index += 1
2210 db_nsr_update["_admin.scaling-group.{}.name".format(admin_scale_index)] = scaling_group
tierno59d22d22018-09-25 18:10:19 +02002211 RO_scaling_info = []
2212 vdu_scaling_info = {"scaling_group_name": scaling_group, "vdu": []}
2213 if scaling_type == "SCALE_OUT":
2214 # count if max-instance-count is reached
2215 if "max-instance-count" in scaling_descriptor and scaling_descriptor["max-instance-count"] is not None:
2216 max_instance_count = int(scaling_descriptor["max-instance-count"])
ikalyvas02d9e7b2019-05-27 18:16:01 +03002217
tierno9babfda2019-06-07 12:36:50 +00002218 # self.logger.debug("MAX_INSTANCE_COUNT is {}".format(scaling_descriptor["max-instance-count"]))
tierno59d22d22018-09-25 18:10:19 +02002219 if nb_scale_op >= max_instance_count:
ikalyvas02d9e7b2019-05-27 18:16:01 +03002220 raise LcmException("reached the limit of {} (max-instance-count) "
2221 "scaling-out operations for the "
2222 "scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group))
2223
ikalyvas02d9e7b2019-05-27 18:16:01 +03002224 nb_scale_op += 1
tierno59d22d22018-09-25 18:10:19 +02002225 vdu_scaling_info["scaling_direction"] = "OUT"
2226 vdu_scaling_info["vdu-create"] = {}
2227 for vdu_scale_info in scaling_descriptor["vdu"]:
2228 RO_scaling_info.append({"osm_vdu_id": vdu_scale_info["vdu-id-ref"], "member-vnf-index": vnf_index,
2229 "type": "create", "count": vdu_scale_info.get("count", 1)})
2230 vdu_scaling_info["vdu-create"][vdu_scale_info["vdu-id-ref"]] = vdu_scale_info.get("count", 1)
ikalyvas02d9e7b2019-05-27 18:16:01 +03002231
tierno59d22d22018-09-25 18:10:19 +02002232 elif scaling_type == "SCALE_IN":
2233 # count if min-instance-count is reached
tierno27246d82018-09-27 15:59:09 +02002234 min_instance_count = 0
tierno59d22d22018-09-25 18:10:19 +02002235 if "min-instance-count" in scaling_descriptor and scaling_descriptor["min-instance-count"] is not None:
2236 min_instance_count = int(scaling_descriptor["min-instance-count"])
tierno9babfda2019-06-07 12:36:50 +00002237 if nb_scale_op <= min_instance_count:
2238 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
2239 "scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group))
ikalyvas02d9e7b2019-05-27 18:16:01 +03002240 nb_scale_op -= 1
tierno59d22d22018-09-25 18:10:19 +02002241 vdu_scaling_info["scaling_direction"] = "IN"
2242 vdu_scaling_info["vdu-delete"] = {}
2243 for vdu_scale_info in scaling_descriptor["vdu"]:
2244 RO_scaling_info.append({"osm_vdu_id": vdu_scale_info["vdu-id-ref"], "member-vnf-index": vnf_index,
2245 "type": "delete", "count": vdu_scale_info.get("count", 1)})
2246 vdu_scaling_info["vdu-delete"][vdu_scale_info["vdu-id-ref"]] = vdu_scale_info.get("count", 1)
2247
2248 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
tierno27246d82018-09-27 15:59:09 +02002249 vdu_create = vdu_scaling_info.get("vdu-create")
2250 vdu_delete = copy(vdu_scaling_info.get("vdu-delete"))
tierno59d22d22018-09-25 18:10:19 +02002251 if vdu_scaling_info["scaling_direction"] == "IN":
2252 for vdur in reversed(db_vnfr["vdur"]):
tierno27246d82018-09-27 15:59:09 +02002253 if vdu_delete.get(vdur["vdu-id-ref"]):
2254 vdu_delete[vdur["vdu-id-ref"]] -= 1
tierno59d22d22018-09-25 18:10:19 +02002255 vdu_scaling_info["vdu"].append({
2256 "name": vdur["name"],
2257 "vdu_id": vdur["vdu-id-ref"],
2258 "interface": []
2259 })
2260 for interface in vdur["interfaces"]:
2261 vdu_scaling_info["vdu"][-1]["interface"].append({
2262 "name": interface["name"],
2263 "ip_address": interface["ip-address"],
2264 "mac_address": interface.get("mac-address"),
2265 })
tierno27246d82018-09-27 15:59:09 +02002266 vdu_delete = vdu_scaling_info.pop("vdu-delete")
tierno59d22d22018-09-25 18:10:19 +02002267
2268 # execute primitive service PRE-SCALING
2269 step = "Executing pre-scale vnf-config-primitive"
2270 if scaling_descriptor.get("scaling-config-action"):
2271 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
2272 if scaling_config_action.get("trigger") and scaling_config_action["trigger"] == "pre-scale-in" \
2273 and scaling_type == "SCALE_IN":
2274 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
2275 step = db_nslcmop_update["detailed-status"] = \
2276 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive)
tiernoda964822019-01-14 15:53:47 +00002277
tierno59d22d22018-09-25 18:10:19 +02002278 # look for primitive
tierno59d22d22018-09-25 18:10:19 +02002279 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
2280 if config_primitive["name"] == vnf_config_primitive:
tierno59d22d22018-09-25 18:10:19 +02002281 break
2282 else:
2283 raise LcmException(
2284 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
tiernoda964822019-01-14 15:53:47 +00002285 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
tierno59d22d22018-09-25 18:10:19 +02002286 "primitive".format(scaling_group, config_primitive))
tiernoda964822019-01-14 15:53:47 +00002287
tierno16fedf52019-05-24 08:38:26 +00002288 vnfr_params = {"VDU_SCALE_INFO": vdu_scaling_info}
tiernoda964822019-01-14 15:53:47 +00002289 if db_vnfr.get("additionalParamsForVnf"):
2290 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
2291
tierno9ab95942018-10-10 16:44:22 +02002292 scale_process = "VCA"
tiernod6de1992018-10-11 13:05:52 +02002293 db_nsr_update["config-status"] = "configuring pre-scaling"
tiernoda964822019-01-14 15:53:47 +00002294 result, result_detail = await self._ns_execute_primitive(
2295 nsr_deployed, vnf_index, None, None, None, vnf_config_primitive,
2296 self._map_primitive_params(config_primitive, {}, vnfr_params))
tierno59d22d22018-09-25 18:10:19 +02002297 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
2298 vnf_config_primitive, result, result_detail))
2299 if result == "FAILED":
2300 raise LcmException(result_detail)
tiernod6de1992018-10-11 13:05:52 +02002301 db_nsr_update["config-status"] = old_config_status
2302 scale_process = None
tierno59d22d22018-09-25 18:10:19 +02002303
2304 if RO_scaling_info:
tierno9ab95942018-10-10 16:44:22 +02002305 scale_process = "RO"
tierno59d22d22018-09-25 18:10:19 +02002306 RO = ROclient.ROClient(self.loop, **self.ro_config)
2307 RO_desc = await RO.create_action("ns", RO_nsr_id, {"vdu-scaling": RO_scaling_info})
2308 db_nsr_update["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index)] = nb_scale_op
2309 db_nsr_update["_admin.scaling-group.{}.time".format(admin_scale_index)] = time()
tierno59d22d22018-09-25 18:10:19 +02002310 # wait until ready
2311 RO_nslcmop_id = RO_desc["instance_action_id"]
2312 db_nslcmop_update["_admin.deploy.RO"] = RO_nslcmop_id
2313
2314 RO_task_done = False
2315 step = detailed_status = "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id)
2316 detailed_status_old = None
2317 self.logger.debug(logging_text + step)
2318
tierno9ab95942018-10-10 16:44:22 +02002319 deployment_timeout = 1 * 3600 # One hour
tierno59d22d22018-09-25 18:10:19 +02002320 while deployment_timeout > 0:
2321 if not RO_task_done:
2322 desc = await RO.show("ns", item_id_name=RO_nsr_id, extra_item="action",
2323 extra_item_id=RO_nslcmop_id)
2324 ns_status, ns_status_info = RO.check_action_status(desc)
2325 if ns_status == "ERROR":
2326 raise ROclient.ROClientException(ns_status_info)
2327 elif ns_status == "BUILD":
2328 detailed_status = step + "; {}".format(ns_status_info)
2329 elif ns_status == "ACTIVE":
2330 RO_task_done = True
2331 step = detailed_status = "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id)
2332 self.logger.debug(logging_text + step)
2333 else:
2334 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
2335 else:
2336 desc = await RO.show("ns", RO_nsr_id)
2337 ns_status, ns_status_info = RO.check_ns_status(desc)
2338 if ns_status == "ERROR":
2339 raise ROclient.ROClientException(ns_status_info)
2340 elif ns_status == "BUILD":
2341 detailed_status = step + "; {}".format(ns_status_info)
2342 elif ns_status == "ACTIVE":
tiernof578e552018-11-08 19:07:20 +01002343 step = detailed_status = \
2344 "Waiting for management IP address reported by the VIM. Updating VNFRs"
2345 if not vnfr_scaled:
2346 self.scale_vnfr(db_vnfr, vdu_create=vdu_create, vdu_delete=vdu_delete)
2347 vnfr_scaled = True
tierno59d22d22018-09-25 18:10:19 +02002348 try:
2349 desc = await RO.show("ns", RO_nsr_id)
tiernoe4f7e6c2018-11-27 14:55:30 +00002350 # nsr_deployed["nsr_ip"] = RO.get_ns_vnf_info(desc)
tiernof578e552018-11-08 19:07:20 +01002351 self.ns_update_vnfr({db_vnfr["member-vnf-index-ref"]: db_vnfr}, desc)
tierno59d22d22018-09-25 18:10:19 +02002352 break
tiernof578e552018-11-08 19:07:20 +01002353 except LcmExceptionNoMgmtIP:
2354 pass
tierno59d22d22018-09-25 18:10:19 +02002355 else:
2356 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
2357 if detailed_status != detailed_status_old:
2358 detailed_status_old = db_nslcmop_update["detailed-status"] = detailed_status
2359 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
2360
2361 await asyncio.sleep(5, loop=self.loop)
2362 deployment_timeout -= 5
2363 if deployment_timeout <= 0:
2364 raise ROclient.ROClientException("Timeout waiting ns to be ready")
2365
tierno59d22d22018-09-25 18:10:19 +02002366 # update VDU_SCALING_INFO with the obtained ip_addresses
2367 if vdu_scaling_info["scaling_direction"] == "OUT":
2368 for vdur in reversed(db_vnfr["vdur"]):
2369 if vdu_scaling_info["vdu-create"].get(vdur["vdu-id-ref"]):
2370 vdu_scaling_info["vdu-create"][vdur["vdu-id-ref"]] -= 1
2371 vdu_scaling_info["vdu"].append({
2372 "name": vdur["name"],
2373 "vdu_id": vdur["vdu-id-ref"],
2374 "interface": []
2375 })
2376 for interface in vdur["interfaces"]:
2377 vdu_scaling_info["vdu"][-1]["interface"].append({
2378 "name": interface["name"],
2379 "ip_address": interface["ip-address"],
2380 "mac_address": interface.get("mac-address"),
2381 })
2382 del vdu_scaling_info["vdu-create"]
2383
tierno9ab95942018-10-10 16:44:22 +02002384 scale_process = None
tierno59d22d22018-09-25 18:10:19 +02002385 if db_nsr_update:
2386 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2387
2388 # execute primitive service POST-SCALING
2389 step = "Executing post-scale vnf-config-primitive"
2390 if scaling_descriptor.get("scaling-config-action"):
2391 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
2392 if scaling_config_action.get("trigger") and scaling_config_action["trigger"] == "post-scale-out" \
2393 and scaling_type == "SCALE_OUT":
2394 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
2395 step = db_nslcmop_update["detailed-status"] = \
2396 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive)
tiernoda964822019-01-14 15:53:47 +00002397
tierno589befb2019-05-29 07:06:23 +00002398 vnfr_params = {"VDU_SCALE_INFO": vdu_scaling_info}
tiernoda964822019-01-14 15:53:47 +00002399 if db_vnfr.get("additionalParamsForVnf"):
2400 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
2401
tierno59d22d22018-09-25 18:10:19 +02002402 # look for primitive
tierno59d22d22018-09-25 18:10:19 +02002403 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
2404 if config_primitive["name"] == vnf_config_primitive:
tierno59d22d22018-09-25 18:10:19 +02002405 break
2406 else:
2407 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
2408 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
tierno47e86b52018-10-10 14:05:55 +02002409 "match any vnf-configuration:config-primitive".format(scaling_group,
2410 config_primitive))
tierno9ab95942018-10-10 16:44:22 +02002411 scale_process = "VCA"
tiernod6de1992018-10-11 13:05:52 +02002412 db_nsr_update["config-status"] = "configuring post-scaling"
2413
tiernoda964822019-01-14 15:53:47 +00002414 result, result_detail = await self._ns_execute_primitive(
2415 nsr_deployed, vnf_index, None, None, None, vnf_config_primitive,
2416 self._map_primitive_params(config_primitive, {}, vnfr_params))
tierno59d22d22018-09-25 18:10:19 +02002417 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
2418 vnf_config_primitive, result, result_detail))
2419 if result == "FAILED":
2420 raise LcmException(result_detail)
tiernod6de1992018-10-11 13:05:52 +02002421 db_nsr_update["config-status"] = old_config_status
2422 scale_process = None
tierno59d22d22018-09-25 18:10:19 +02002423
2424 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
2425 db_nslcmop_update["statusEnteredTime"] = time()
2426 db_nslcmop_update["detailed-status"] = "done"
tiernod6de1992018-10-11 13:05:52 +02002427 db_nsr_update["detailed-status"] = "" # "scaled {} {}".format(scaling_group, scaling_type)
ikalyvas02d9e7b2019-05-27 18:16:01 +03002428 db_nsr_update["operational-status"] = "running" if old_operational_status == "failed" \
2429 else old_operational_status
tiernod6de1992018-10-11 13:05:52 +02002430 db_nsr_update["config-status"] = old_config_status
tierno59d22d22018-09-25 18:10:19 +02002431 return
2432 except (ROclient.ROClientException, DbException, LcmException) as e:
2433 self.logger.error(logging_text + "Exit Exception {}".format(e))
2434 exc = e
2435 except asyncio.CancelledError:
2436 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
2437 exc = "Operation was cancelled"
2438 except Exception as e:
2439 exc = traceback.format_exc()
2440 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
2441 finally:
2442 if exc:
2443 if db_nslcmop:
2444 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
2445 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
2446 db_nslcmop_update["statusEnteredTime"] = time()
2447 if db_nsr:
tiernod6de1992018-10-11 13:05:52 +02002448 db_nsr_update["operational-status"] = old_operational_status
2449 db_nsr_update["config-status"] = old_config_status
2450 db_nsr_update["detailed-status"] = ""
tierno47e86b52018-10-10 14:05:55 +02002451 db_nsr_update["_admin.nslcmop"] = None
tiernod6de1992018-10-11 13:05:52 +02002452 if scale_process:
2453 if "VCA" in scale_process:
2454 db_nsr_update["config-status"] = "failed"
2455 if "RO" in scale_process:
2456 db_nsr_update["operational-status"] = "failed"
2457 db_nsr_update["detailed-status"] = "FAILED scaling nslcmop={} {}: {}".format(nslcmop_id, step,
2458 exc)
tiernobaa51102018-12-14 13:16:18 +00002459 try:
2460 if db_nslcmop and db_nslcmop_update:
2461 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
2462 if db_nsr:
2463 db_nsr_update["_admin.nslcmop"] = None
2464 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2465 except DbException as e:
2466 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno59d22d22018-09-25 18:10:19 +02002467 if nslcmop_operation_state:
2468 try:
2469 await self.msg.aiowrite("ns", "scaled", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
tierno8a518872018-12-21 13:42:14 +00002470 "operationState": nslcmop_operation_state},
2471 loop=self.loop)
tierno59d22d22018-09-25 18:10:19 +02002472 # if cooldown_time:
2473 # await asyncio.sleep(cooldown_time)
2474 # await self.msg.aiowrite("ns","scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
2475 except Exception as e:
2476 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
2477 self.logger.debug(logging_text + "Exit")
2478 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_scale")