Fix bug 913 - LCM not getting VNF mgmt ip when using native charms
[osm/LCM.git] / osm_lcm / ns.py
1 # -*- coding: utf-8 -*-
2
3 ##
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
19 import asyncio
20 import yaml
21 import logging
22 import logging.handlers
23 import traceback
24 from jinja2 import Environment, Template, meta, TemplateError, TemplateNotFound, TemplateSyntaxError
25
26 from osm_lcm import ROclient
27 from osm_lcm.lcm_utils import LcmException, LcmExceptionNoMgmtIP, LcmBase, deep_get
28 from n2vc.k8s_helm_conn import K8sHelmConnector
29
30 from osm_common.dbbase import DbException
31 from osm_common.fsbase import FsException
32
33 from n2vc.n2vc_juju_conn import N2VCJujuConnector
34
35 from copy import copy, deepcopy
36 from http import HTTPStatus
37 from time import time
38 from uuid import uuid4
39
40 __author__ = "Alfonso Tierno"
41
42
43 def get_iterable(in_dict, in_key):
44 """
45 Similar to <dict>.get(), but if value is None, False, ..., An empty tuple is returned instead
46 :param in_dict: a dictionary
47 :param in_key: the key to look for at in_dict
48 :return: in_dict[in_var] or () if it is None or not present
49 """
50 if not in_dict.get(in_key):
51 return ()
52 return in_dict[in_key]
53
54
55 def populate_dict(target_dict, key_list, value):
56 """
57 Update target_dict creating nested dictionaries with the key_list. Last key_list item is asigned the value.
58 Example target_dict={K: J}; key_list=[a,b,c]; target_dict will be {K: J, a: {b: {c: value}}}
59 :param target_dict: dictionary to be changed
60 :param key_list: list of keys to insert at target_dict
61 :param value:
62 :return: None
63 """
64 for key in key_list[0:-1]:
65 if key not in target_dict:
66 target_dict[key] = {}
67 target_dict = target_dict[key]
68 target_dict[key_list[-1]] = value
69
70
71 class NsLcm(LcmBase):
72 timeout_vca_on_error = 5 * 60 # Time for charm from first time at blocked,error status to mark as failed
73 total_deploy_timeout = 2 * 3600 # global timeout for deployment
74 timeout_charm_delete = 10 * 60
75 timeout_primitive = 10 * 60 # timeout for primitive execution
76
77 SUBOPERATION_STATUS_NOT_FOUND = -1
78 SUBOPERATION_STATUS_NEW = -2
79 SUBOPERATION_STATUS_SKIP = -3
80
81 def __init__(self, db, msg, fs, lcm_tasks, ro_config, vca_config, loop):
82 """
83 Init, Connect to database, filesystem storage, and messaging
84 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
85 :return: None
86 """
87 super().__init__(
88 db=db,
89 msg=msg,
90 fs=fs,
91 logger=logging.getLogger('lcm.ns')
92 )
93
94 self.loop = loop
95 self.lcm_tasks = lcm_tasks
96 self.ro_config = ro_config
97 self.vca_config = vca_config
98 if 'pubkey' in self.vca_config:
99 self.vca_config['public_key'] = self.vca_config['pubkey']
100 if 'cacert' in self.vca_config:
101 self.vca_config['ca_cert'] = self.vca_config['cacert']
102 if 'apiproxy' in self.vca_config:
103 self.vca_config['api_proxy'] = self.vca_config['apiproxy']
104
105 # create N2VC connector
106 self.n2vc = N2VCJujuConnector(
107 db=self.db,
108 fs=self.fs,
109 log=self.logger,
110 loop=self.loop,
111 url='{}:{}'.format(self.vca_config['host'], self.vca_config['port']),
112 username=self.vca_config.get('user', None),
113 vca_config=self.vca_config,
114 on_update_db=self._on_update_n2vc_db,
115 # ca_cert=self.vca_config.get('cacert'),
116 # api_proxy=self.vca_config.get('apiproxy'),
117 )
118
119 self.k8sclusterhelm = K8sHelmConnector(
120 kubectl_command=self.vca_config.get("kubectlpath"),
121 helm_command=self.vca_config.get("helmpath"),
122 fs=self.fs,
123 log=self.logger,
124 db=self.db,
125 on_update_db=None,
126 )
127
128 # create RO client
129 self.RO = ROclient.ROClient(self.loop, **self.ro_config)
130
131 def _on_update_n2vc_db(self, table, filter, path, updated_data):
132
133 self.logger.debug('_on_update_n2vc_db(table={}, filter={}, path={}, updated_data={}'
134 .format(table, filter, path, updated_data))
135
136 return
137 # write NS status to database
138 # try:
139 # # nsrs_id = filter.get('_id')
140 # # print(nsrs_id)
141 # # get ns record
142 # nsr = self.db.get_one(table=table, q_filter=filter)
143 # # get VCA deployed list
144 # vca_list = deep_get(target_dict=nsr, key_list=('_admin', 'deployed', 'VCA'))
145 # # get RO deployed
146 # # ro_list = deep_get(target_dict=nsr, key_list=('_admin', 'deployed', 'RO'))
147 # for vca in vca_list:
148 # # status = vca.get('status')
149 # # print(status)
150 # # detailed_status = vca.get('detailed-status')
151 # # print(detailed_status)
152 # # for ro in ro_list:
153 # # print(ro)
154 #
155 # except Exception as e:
156 # self.logger.error('Error writing NS status to db: {}'.format(e))
157
158 def vnfd2RO(self, vnfd, new_id=None, additionalParams=None, nsrId=None):
159 """
160 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
161 :param vnfd: input vnfd
162 :param new_id: overrides vnf id if provided
163 :param additionalParams: Instantiation params for VNFs provided
164 :param nsrId: Id of the NSR
165 :return: copy of vnfd
166 """
167 try:
168 vnfd_RO = deepcopy(vnfd)
169 # remove unused by RO configuration, monitoring, scaling and internal keys
170 vnfd_RO.pop("_id", None)
171 vnfd_RO.pop("_admin", None)
172 vnfd_RO.pop("vnf-configuration", None)
173 vnfd_RO.pop("monitoring-param", None)
174 vnfd_RO.pop("scaling-group-descriptor", None)
175 vnfd_RO.pop("kdu", None)
176 vnfd_RO.pop("k8s-cluster", None)
177 if new_id:
178 vnfd_RO["id"] = new_id
179
180 # parse cloud-init or cloud-init-file with the provided variables using Jinja2
181 for vdu in get_iterable(vnfd_RO, "vdu"):
182 cloud_init_file = None
183 if vdu.get("cloud-init-file"):
184 base_folder = vnfd["_admin"]["storage"]
185 cloud_init_file = "{}/{}/cloud_init/{}".format(base_folder["folder"], base_folder["pkg-dir"],
186 vdu["cloud-init-file"])
187 with self.fs.file_open(cloud_init_file, "r") as ci_file:
188 cloud_init_content = ci_file.read()
189 vdu.pop("cloud-init-file", None)
190 elif vdu.get("cloud-init"):
191 cloud_init_content = vdu["cloud-init"]
192 else:
193 continue
194
195 env = Environment()
196 ast = env.parse(cloud_init_content)
197 mandatory_vars = meta.find_undeclared_variables(ast)
198 if mandatory_vars:
199 for var in mandatory_vars:
200 if not additionalParams or var not in additionalParams.keys():
201 raise LcmException("Variable '{}' defined at vnfd[id={}]:vdu[id={}]:cloud-init/cloud-init-"
202 "file, must be provided in the instantiation parameters inside the "
203 "'additionalParamsForVnf' block".format(var, vnfd["id"], vdu["id"]))
204 template = Template(cloud_init_content)
205 cloud_init_content = template.render(additionalParams or {})
206 vdu["cloud-init"] = cloud_init_content
207
208 return vnfd_RO
209 except FsException as e:
210 raise LcmException("Error reading vnfd[id={}]:vdu[id={}]:cloud-init-file={}: {}".
211 format(vnfd["id"], vdu["id"], cloud_init_file, e))
212 except (TemplateError, TemplateNotFound, TemplateSyntaxError) as e:
213 raise LcmException("Error parsing Jinja2 to cloud-init content at vnfd[id={}]:vdu[id={}]: {}".
214 format(vnfd["id"], vdu["id"], e))
215
216 def ns_params_2_RO(self, ns_params, nsd, vnfd_dict, n2vc_key_list):
217 """
218 Creates a RO ns descriptor from OSM ns_instantiate params
219 :param ns_params: OSM instantiate params
220 :return: The RO ns descriptor
221 """
222 vim_2_RO = {}
223 wim_2_RO = {}
224 # TODO feature 1417: Check that no instantiation is set over PDU
225 # check if PDU forces a concrete vim-network-id and add it
226 # check if PDU contains a SDN-assist info (dpid, switch, port) and pass it to RO
227
228 def vim_account_2_RO(vim_account):
229 if vim_account in vim_2_RO:
230 return vim_2_RO[vim_account]
231
232 db_vim = self.db.get_one("vim_accounts", {"_id": vim_account})
233 if db_vim["_admin"]["operationalState"] != "ENABLED":
234 raise LcmException("VIM={} is not available. operationalState={}".format(
235 vim_account, db_vim["_admin"]["operationalState"]))
236 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
237 vim_2_RO[vim_account] = RO_vim_id
238 return RO_vim_id
239
240 def wim_account_2_RO(wim_account):
241 if isinstance(wim_account, str):
242 if wim_account in wim_2_RO:
243 return wim_2_RO[wim_account]
244
245 db_wim = self.db.get_one("wim_accounts", {"_id": wim_account})
246 if db_wim["_admin"]["operationalState"] != "ENABLED":
247 raise LcmException("WIM={} is not available. operationalState={}".format(
248 wim_account, db_wim["_admin"]["operationalState"]))
249 RO_wim_id = db_wim["_admin"]["deployed"]["RO-account"]
250 wim_2_RO[wim_account] = RO_wim_id
251 return RO_wim_id
252 else:
253 return wim_account
254
255 def ip_profile_2_RO(ip_profile):
256 RO_ip_profile = deepcopy((ip_profile))
257 if "dns-server" in RO_ip_profile:
258 if isinstance(RO_ip_profile["dns-server"], list):
259 RO_ip_profile["dns-address"] = []
260 for ds in RO_ip_profile.pop("dns-server"):
261 RO_ip_profile["dns-address"].append(ds['address'])
262 else:
263 RO_ip_profile["dns-address"] = RO_ip_profile.pop("dns-server")
264 if RO_ip_profile.get("ip-version") == "ipv4":
265 RO_ip_profile["ip-version"] = "IPv4"
266 if RO_ip_profile.get("ip-version") == "ipv6":
267 RO_ip_profile["ip-version"] = "IPv6"
268 if "dhcp-params" in RO_ip_profile:
269 RO_ip_profile["dhcp"] = RO_ip_profile.pop("dhcp-params")
270 return RO_ip_profile
271
272 if not ns_params:
273 return None
274 RO_ns_params = {
275 # "name": ns_params["nsName"],
276 # "description": ns_params.get("nsDescription"),
277 "datacenter": vim_account_2_RO(ns_params["vimAccountId"]),
278 "wim_account": wim_account_2_RO(ns_params.get("wimAccountId")),
279 # "scenario": ns_params["nsdId"],
280 }
281
282 n2vc_key_list = n2vc_key_list or []
283 for vnfd_ref, vnfd in vnfd_dict.items():
284 vdu_needed_access = []
285 mgmt_cp = None
286 if vnfd.get("vnf-configuration"):
287 ssh_required = deep_get(vnfd, ("vnf-configuration", "config-access", "ssh-access", "required"))
288 if ssh_required and vnfd.get("mgmt-interface"):
289 if vnfd["mgmt-interface"].get("vdu-id"):
290 vdu_needed_access.append(vnfd["mgmt-interface"]["vdu-id"])
291 elif vnfd["mgmt-interface"].get("cp"):
292 mgmt_cp = vnfd["mgmt-interface"]["cp"]
293
294 for vdu in vnfd.get("vdu", ()):
295 if vdu.get("vdu-configuration"):
296 ssh_required = deep_get(vdu, ("vdu-configuration", "config-access", "ssh-access", "required"))
297 if ssh_required:
298 vdu_needed_access.append(vdu["id"])
299 elif mgmt_cp:
300 for vdu_interface in vdu.get("interface"):
301 if vdu_interface.get("external-connection-point-ref") and \
302 vdu_interface["external-connection-point-ref"] == mgmt_cp:
303 vdu_needed_access.append(vdu["id"])
304 mgmt_cp = None
305 break
306
307 if vdu_needed_access:
308 for vnf_member in nsd.get("constituent-vnfd"):
309 if vnf_member["vnfd-id-ref"] != vnfd_ref:
310 continue
311 for vdu in vdu_needed_access:
312 populate_dict(RO_ns_params,
313 ("vnfs", vnf_member["member-vnf-index"], "vdus", vdu, "mgmt_keys"),
314 n2vc_key_list)
315
316 if ns_params.get("vduImage"):
317 RO_ns_params["vduImage"] = ns_params["vduImage"]
318
319 if ns_params.get("ssh_keys"):
320 RO_ns_params["cloud-config"] = {"key-pairs": ns_params["ssh_keys"]}
321 for vnf_params in get_iterable(ns_params, "vnf"):
322 for constituent_vnfd in nsd["constituent-vnfd"]:
323 if constituent_vnfd["member-vnf-index"] == vnf_params["member-vnf-index"]:
324 vnf_descriptor = vnfd_dict[constituent_vnfd["vnfd-id-ref"]]
325 break
326 else:
327 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index={} is not present at nsd:"
328 "constituent-vnfd".format(vnf_params["member-vnf-index"]))
329 if vnf_params.get("vimAccountId"):
330 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "datacenter"),
331 vim_account_2_RO(vnf_params["vimAccountId"]))
332
333 for vdu_params in get_iterable(vnf_params, "vdu"):
334 # TODO feature 1417: check that this VDU exist and it is not a PDU
335 if vdu_params.get("volume"):
336 for volume_params in vdu_params["volume"]:
337 if volume_params.get("vim-volume-id"):
338 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
339 vdu_params["id"], "devices", volume_params["name"], "vim_id"),
340 volume_params["vim-volume-id"])
341 if vdu_params.get("interface"):
342 for interface_params in vdu_params["interface"]:
343 if interface_params.get("ip-address"):
344 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
345 vdu_params["id"], "interfaces", interface_params["name"],
346 "ip_address"),
347 interface_params["ip-address"])
348 if interface_params.get("mac-address"):
349 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
350 vdu_params["id"], "interfaces", interface_params["name"],
351 "mac_address"),
352 interface_params["mac-address"])
353 if interface_params.get("floating-ip-required"):
354 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
355 vdu_params["id"], "interfaces", interface_params["name"],
356 "floating-ip"),
357 interface_params["floating-ip-required"])
358
359 for internal_vld_params in get_iterable(vnf_params, "internal-vld"):
360 if internal_vld_params.get("vim-network-name"):
361 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "networks",
362 internal_vld_params["name"], "vim-network-name"),
363 internal_vld_params["vim-network-name"])
364 if internal_vld_params.get("vim-network-id"):
365 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "networks",
366 internal_vld_params["name"], "vim-network-id"),
367 internal_vld_params["vim-network-id"])
368 if internal_vld_params.get("ip-profile"):
369 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "networks",
370 internal_vld_params["name"], "ip-profile"),
371 ip_profile_2_RO(internal_vld_params["ip-profile"]))
372 if internal_vld_params.get("provider-network"):
373
374 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "networks",
375 internal_vld_params["name"], "provider-network"),
376 internal_vld_params["provider-network"].copy())
377
378 for icp_params in get_iterable(internal_vld_params, "internal-connection-point"):
379 # look for interface
380 iface_found = False
381 for vdu_descriptor in vnf_descriptor["vdu"]:
382 for vdu_interface in vdu_descriptor["interface"]:
383 if vdu_interface.get("internal-connection-point-ref") == icp_params["id-ref"]:
384 if icp_params.get("ip-address"):
385 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
386 vdu_descriptor["id"], "interfaces",
387 vdu_interface["name"], "ip_address"),
388 icp_params["ip-address"])
389
390 if icp_params.get("mac-address"):
391 populate_dict(RO_ns_params, ("vnfs", vnf_params["member-vnf-index"], "vdus",
392 vdu_descriptor["id"], "interfaces",
393 vdu_interface["name"], "mac_address"),
394 icp_params["mac-address"])
395 iface_found = True
396 break
397 if iface_found:
398 break
399 else:
400 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
401 "internal-vld:id-ref={} is not present at vnfd:internal-"
402 "connection-point".format(vnf_params["member-vnf-index"],
403 icp_params["id-ref"]))
404
405 for vld_params in get_iterable(ns_params, "vld"):
406 if "ip-profile" in vld_params:
407 populate_dict(RO_ns_params, ("networks", vld_params["name"], "ip-profile"),
408 ip_profile_2_RO(vld_params["ip-profile"]))
409
410 if vld_params.get("provider-network"):
411
412 populate_dict(RO_ns_params, ("networks", vld_params["name"], "provider-network"),
413 vld_params["provider-network"].copy())
414
415 if "wimAccountId" in vld_params and vld_params["wimAccountId"] is not None:
416 populate_dict(RO_ns_params, ("networks", vld_params["name"], "wim_account"),
417 wim_account_2_RO(vld_params["wimAccountId"])),
418 if vld_params.get("vim-network-name"):
419 RO_vld_sites = []
420 if isinstance(vld_params["vim-network-name"], dict):
421 for vim_account, vim_net in vld_params["vim-network-name"].items():
422 RO_vld_sites.append({
423 "netmap-use": vim_net,
424 "datacenter": vim_account_2_RO(vim_account)
425 })
426 else: # isinstance str
427 RO_vld_sites.append({"netmap-use": vld_params["vim-network-name"]})
428 if RO_vld_sites:
429 populate_dict(RO_ns_params, ("networks", vld_params["name"], "sites"), RO_vld_sites)
430
431 if vld_params.get("vim-network-id"):
432 RO_vld_sites = []
433 if isinstance(vld_params["vim-network-id"], dict):
434 for vim_account, vim_net in vld_params["vim-network-id"].items():
435 RO_vld_sites.append({
436 "netmap-use": vim_net,
437 "datacenter": vim_account_2_RO(vim_account)
438 })
439 else: # isinstance str
440 RO_vld_sites.append({"netmap-use": vld_params["vim-network-id"]})
441 if RO_vld_sites:
442 populate_dict(RO_ns_params, ("networks", vld_params["name"], "sites"), RO_vld_sites)
443 if vld_params.get("ns-net"):
444 if isinstance(vld_params["ns-net"], dict):
445 for vld_id, instance_scenario_id in vld_params["ns-net"].items():
446 RO_vld_ns_net = {"instance_scenario_id": instance_scenario_id, "osm_id": vld_id}
447 if RO_vld_ns_net:
448 populate_dict(RO_ns_params, ("networks", vld_params["name"], "use-network"), RO_vld_ns_net)
449 if "vnfd-connection-point-ref" in vld_params:
450 for cp_params in vld_params["vnfd-connection-point-ref"]:
451 # look for interface
452 for constituent_vnfd in nsd["constituent-vnfd"]:
453 if constituent_vnfd["member-vnf-index"] == cp_params["member-vnf-index-ref"]:
454 vnf_descriptor = vnfd_dict[constituent_vnfd["vnfd-id-ref"]]
455 break
456 else:
457 raise LcmException(
458 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={} "
459 "is not present at nsd:constituent-vnfd".format(cp_params["member-vnf-index-ref"]))
460 match_cp = False
461 for vdu_descriptor in vnf_descriptor["vdu"]:
462 for interface_descriptor in vdu_descriptor["interface"]:
463 if interface_descriptor.get("external-connection-point-ref") == \
464 cp_params["vnfd-connection-point-ref"]:
465 match_cp = True
466 break
467 if match_cp:
468 break
469 else:
470 raise LcmException(
471 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={}:"
472 "vnfd-connection-point-ref={} is not present at vnfd={}".format(
473 cp_params["member-vnf-index-ref"],
474 cp_params["vnfd-connection-point-ref"],
475 vnf_descriptor["id"]))
476 if cp_params.get("ip-address"):
477 populate_dict(RO_ns_params, ("vnfs", cp_params["member-vnf-index-ref"], "vdus",
478 vdu_descriptor["id"], "interfaces",
479 interface_descriptor["name"], "ip_address"),
480 cp_params["ip-address"])
481 if cp_params.get("mac-address"):
482 populate_dict(RO_ns_params, ("vnfs", cp_params["member-vnf-index-ref"], "vdus",
483 vdu_descriptor["id"], "interfaces",
484 interface_descriptor["name"], "mac_address"),
485 cp_params["mac-address"])
486 return RO_ns_params
487
488 def scale_vnfr(self, db_vnfr, vdu_create=None, vdu_delete=None):
489 # make a copy to do not change
490 vdu_create = copy(vdu_create)
491 vdu_delete = copy(vdu_delete)
492
493 vdurs = db_vnfr.get("vdur")
494 if vdurs is None:
495 vdurs = []
496 vdu_index = len(vdurs)
497 while vdu_index:
498 vdu_index -= 1
499 vdur = vdurs[vdu_index]
500 if vdur.get("pdu-type"):
501 continue
502 vdu_id_ref = vdur["vdu-id-ref"]
503 if vdu_create and vdu_create.get(vdu_id_ref):
504 for index in range(0, vdu_create[vdu_id_ref]):
505 vdur = deepcopy(vdur)
506 vdur["_id"] = str(uuid4())
507 vdur["count-index"] += 1
508 vdurs.insert(vdu_index+1+index, vdur)
509 del vdu_create[vdu_id_ref]
510 if vdu_delete and vdu_delete.get(vdu_id_ref):
511 del vdurs[vdu_index]
512 vdu_delete[vdu_id_ref] -= 1
513 if not vdu_delete[vdu_id_ref]:
514 del vdu_delete[vdu_id_ref]
515 # check all operations are done
516 if vdu_create or vdu_delete:
517 raise LcmException("Error scaling OUT VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
518 vdu_create))
519 if vdu_delete:
520 raise LcmException("Error scaling IN VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
521 vdu_delete))
522
523 vnfr_update = {"vdur": vdurs}
524 db_vnfr["vdur"] = vdurs
525 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
526
527 def ns_update_nsr(self, ns_update_nsr, db_nsr, nsr_desc_RO):
528 """
529 Updates database nsr with the RO info for the created vld
530 :param ns_update_nsr: dictionary to be filled with the updated info
531 :param db_nsr: content of db_nsr. This is also modified
532 :param nsr_desc_RO: nsr descriptor from RO
533 :return: Nothing, LcmException is raised on errors
534 """
535
536 for vld_index, vld in enumerate(get_iterable(db_nsr, "vld")):
537 for net_RO in get_iterable(nsr_desc_RO, "nets"):
538 if vld["id"] != net_RO.get("ns_net_osm_id"):
539 continue
540 vld["vim-id"] = net_RO.get("vim_net_id")
541 vld["name"] = net_RO.get("vim_name")
542 vld["status"] = net_RO.get("status")
543 vld["status-detailed"] = net_RO.get("error_msg")
544 ns_update_nsr["vld.{}".format(vld_index)] = vld
545 break
546 else:
547 raise LcmException("ns_update_nsr: Not found vld={} at RO info".format(vld["id"]))
548
549 def ns_update_vnfr(self, db_vnfrs, nsr_desc_RO):
550 """
551 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
552 :param db_vnfrs: dictionary with member-vnf-index: vnfr-content
553 :param nsr_desc_RO: nsr descriptor from RO
554 :return: Nothing, LcmException is raised on errors
555 """
556 for vnf_index, db_vnfr in db_vnfrs.items():
557 for vnf_RO in nsr_desc_RO["vnfs"]:
558 if vnf_RO["member_vnf_index"] != vnf_index:
559 continue
560 vnfr_update = {}
561 if vnf_RO.get("ip_address"):
562 db_vnfr["ip-address"] = vnfr_update["ip-address"] = vnf_RO["ip_address"].split(";")[0]
563 elif not db_vnfr.get("ip-address"):
564 raise LcmExceptionNoMgmtIP("ns member_vnf_index '{}' has no IP address".format(vnf_index))
565
566 for vdu_index, vdur in enumerate(get_iterable(db_vnfr, "vdur")):
567 vdur_RO_count_index = 0
568 if vdur.get("pdu-type"):
569 continue
570 for vdur_RO in get_iterable(vnf_RO, "vms"):
571 if vdur["vdu-id-ref"] != vdur_RO["vdu_osm_id"]:
572 continue
573 if vdur["count-index"] != vdur_RO_count_index:
574 vdur_RO_count_index += 1
575 continue
576 vdur["vim-id"] = vdur_RO.get("vim_vm_id")
577 if vdur_RO.get("ip_address"):
578 vdur["ip-address"] = vdur_RO["ip_address"].split(";")[0]
579 else:
580 vdur["ip-address"] = None
581 vdur["vdu-id-ref"] = vdur_RO.get("vdu_osm_id")
582 vdur["name"] = vdur_RO.get("vim_name")
583 vdur["status"] = vdur_RO.get("status")
584 vdur["status-detailed"] = vdur_RO.get("error_msg")
585 for ifacer in get_iterable(vdur, "interfaces"):
586 for interface_RO in get_iterable(vdur_RO, "interfaces"):
587 if ifacer["name"] == interface_RO.get("internal_name"):
588 ifacer["ip-address"] = interface_RO.get("ip_address")
589 ifacer["mac-address"] = interface_RO.get("mac_address")
590 break
591 else:
592 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} interface={} "
593 "from VIM info"
594 .format(vnf_index, vdur["vdu-id-ref"], ifacer["name"]))
595 vnfr_update["vdur.{}".format(vdu_index)] = vdur
596 break
597 else:
598 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} count_index={} from "
599 "VIM info".format(vnf_index, vdur["vdu-id-ref"], vdur["count-index"]))
600
601 for vld_index, vld in enumerate(get_iterable(db_vnfr, "vld")):
602 for net_RO in get_iterable(nsr_desc_RO, "nets"):
603 if vld["id"] != net_RO.get("vnf_net_osm_id"):
604 continue
605 vld["vim-id"] = net_RO.get("vim_net_id")
606 vld["name"] = net_RO.get("vim_name")
607 vld["status"] = net_RO.get("status")
608 vld["status-detailed"] = net_RO.get("error_msg")
609 vnfr_update["vld.{}".format(vld_index)] = vld
610 break
611 else:
612 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vld={} from VIM info".format(
613 vnf_index, vld["id"]))
614
615 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
616 break
617
618 else:
619 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} from VIM info".format(vnf_index))
620
621 @staticmethod
622 def _get_ns_config_info(vca_deployed_list):
623 """
624 Generates a mapping between vnf,vdu elements and the N2VC id
625 :param vca_deployed_list: List of database _admin.deploy.VCA that contains this list
626 :return: a dictionary with {osm-config-mapping: {}} where its element contains:
627 "<member-vnf-index>": <N2VC-id> for a vnf configuration, or
628 "<member-vnf-index>.<vdu.id>.<vdu replica(0, 1,..)>": <N2VC-id> for a vdu configuration
629 """
630 mapping = {}
631 ns_config_info = {"osm-config-mapping": mapping}
632 for vca in vca_deployed_list:
633 if not vca["member-vnf-index"]:
634 continue
635 if not vca["vdu_id"]:
636 mapping[vca["member-vnf-index"]] = vca["application"]
637 else:
638 mapping["{}.{}.{}".format(vca["member-vnf-index"], vca["vdu_id"], vca["vdu_count_index"])] =\
639 vca["application"]
640 return ns_config_info
641
642 @staticmethod
643 def _get_initial_config_primitive_list(desc_primitive_list, vca_deployed):
644 """
645 Generates a list of initial-config-primitive based on the list provided by the descriptor. It includes internal
646 primitives as verify-ssh-credentials, or config when needed
647 :param desc_primitive_list: information of the descriptor
648 :param vca_deployed: information of the deployed, needed for known if it is related to an NS, VNF, VDU and if
649 this element contains a ssh public key
650 :return: The modified list. Can ba an empty list, but always a list
651 """
652 if desc_primitive_list:
653 primitive_list = desc_primitive_list.copy()
654 else:
655 primitive_list = []
656 # look for primitive config, and get the position. None if not present
657 config_position = None
658 for index, primitive in enumerate(primitive_list):
659 if primitive["name"] == "config":
660 config_position = index
661 break
662
663 # for NS, add always a config primitive if not present (bug 874)
664 if not vca_deployed["member-vnf-index"] and config_position is None:
665 primitive_list.insert(0, {"name": "config", "parameter": []})
666 config_position = 0
667 # for VNF/VDU add verify-ssh-credentials after config
668 if vca_deployed["member-vnf-index"] and config_position is not None and vca_deployed.get("ssh-public-key"):
669 primitive_list.insert(config_position + 1, {"name": "verify-ssh-credentials", "parameter": []})
670 return primitive_list
671
672 async def instantiate_RO(self, logging_text, nsr_id, nsd, db_nsr,
673 db_nslcmop, db_vnfrs, db_vnfds_ref, n2vc_key_list):
674
675 db_nsr_update = {}
676 RO_descriptor_number = 0 # number of descriptors created at RO
677 vnf_index_2_RO_id = {} # map between vnfd/nsd id to the id used at RO
678 start_deploy = time()
679 vdu_flag = False # If any of the VNFDs has VDUs
680 ns_params = db_nslcmop.get("operationParams")
681
682 # deploy RO
683
684 # get vnfds, instantiate at RO
685
686 for c_vnf in nsd.get("constituent-vnfd", ()):
687 member_vnf_index = c_vnf["member-vnf-index"]
688 vnfd = db_vnfds_ref[c_vnf['vnfd-id-ref']]
689 if vnfd.get("vdu"):
690 vdu_flag = True
691 vnfd_ref = vnfd["id"]
692 step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Creating vnfd='{}' member_vnf_index='{}' at" \
693 " RO".format(vnfd_ref, member_vnf_index)
694 # self.logger.debug(logging_text + step)
695 vnfd_id_RO = "{}.{}.{}".format(nsr_id, RO_descriptor_number, member_vnf_index[:23])
696 vnf_index_2_RO_id[member_vnf_index] = vnfd_id_RO
697 RO_descriptor_number += 1
698
699 # look position at deployed.RO.vnfd if not present it will be appended at the end
700 for index, vnf_deployed in enumerate(db_nsr["_admin"]["deployed"]["RO"]["vnfd"]):
701 if vnf_deployed["member-vnf-index"] == member_vnf_index:
702 break
703 else:
704 index = len(db_nsr["_admin"]["deployed"]["RO"]["vnfd"])
705 db_nsr["_admin"]["deployed"]["RO"]["vnfd"].append(None)
706
707 # look if present
708 RO_update = {"member-vnf-index": member_vnf_index}
709 vnfd_list = await self.RO.get_list("vnfd", filter_by={"osm_id": vnfd_id_RO})
710 if vnfd_list:
711 RO_update["id"] = vnfd_list[0]["uuid"]
712 self.logger.debug(logging_text + "vnfd='{}' member_vnf_index='{}' exists at RO. Using RO_id={}".
713 format(vnfd_ref, member_vnf_index, vnfd_list[0]["uuid"]))
714 else:
715 vnfd_RO = self.vnfd2RO(vnfd, vnfd_id_RO, db_vnfrs[c_vnf["member-vnf-index"]].
716 get("additionalParamsForVnf"), nsr_id)
717 desc = await self.RO.create("vnfd", descriptor=vnfd_RO)
718 RO_update["id"] = desc["uuid"]
719 self.logger.debug(logging_text + "vnfd='{}' member_vnf_index='{}' created at RO. RO_id={}".format(
720 vnfd_ref, member_vnf_index, desc["uuid"]))
721 db_nsr_update["_admin.deployed.RO.vnfd.{}".format(index)] = RO_update
722 db_nsr["_admin"]["deployed"]["RO"]["vnfd"][index] = RO_update
723 self.update_db_2("nsrs", nsr_id, db_nsr_update)
724 self._on_update_n2vc_db("nsrs", {"_id": nsr_id}, "_admin.deployed", db_nsr_update)
725
726 # create nsd at RO
727 nsd_ref = nsd["id"]
728 step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Creating nsd={} at RO".format(nsd_ref)
729 # self.logger.debug(logging_text + step)
730
731 RO_osm_nsd_id = "{}.{}.{}".format(nsr_id, RO_descriptor_number, nsd_ref[:23])
732 RO_descriptor_number += 1
733 nsd_list = await self.RO.get_list("nsd", filter_by={"osm_id": RO_osm_nsd_id})
734 if nsd_list:
735 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = nsd_list[0]["uuid"]
736 self.logger.debug(logging_text + "nsd={} exists at RO. Using RO_id={}".format(
737 nsd_ref, RO_nsd_uuid))
738 else:
739 nsd_RO = deepcopy(nsd)
740 nsd_RO["id"] = RO_osm_nsd_id
741 nsd_RO.pop("_id", None)
742 nsd_RO.pop("_admin", None)
743 for c_vnf in nsd_RO.get("constituent-vnfd", ()):
744 member_vnf_index = c_vnf["member-vnf-index"]
745 c_vnf["vnfd-id-ref"] = vnf_index_2_RO_id[member_vnf_index]
746 for c_vld in nsd_RO.get("vld", ()):
747 for cp in c_vld.get("vnfd-connection-point-ref", ()):
748 member_vnf_index = cp["member-vnf-index-ref"]
749 cp["vnfd-id-ref"] = vnf_index_2_RO_id[member_vnf_index]
750
751 desc = await self.RO.create("nsd", descriptor=nsd_RO)
752 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
753 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = desc["uuid"]
754 self.logger.debug(logging_text + "nsd={} created at RO. RO_id={}".format(nsd_ref, RO_nsd_uuid))
755 self.update_db_2("nsrs", nsr_id, db_nsr_update)
756 self._on_update_n2vc_db("nsrs", {"_id": nsr_id}, "_admin.deployed", db_nsr_update)
757
758 # Crate ns at RO
759 # if present use it unless in error status
760 RO_nsr_id = deep_get(db_nsr, ("_admin", "deployed", "RO", "nsr_id"))
761 if RO_nsr_id:
762 try:
763 step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Looking for existing ns at RO"
764 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
765 desc = await self.RO.show("ns", RO_nsr_id)
766 except ROclient.ROClientException as e:
767 if e.http_code != HTTPStatus.NOT_FOUND:
768 raise
769 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
770 if RO_nsr_id:
771 ns_status, ns_status_info = self.RO.check_ns_status(desc)
772 db_nsr_update["_admin.deployed.RO.nsr_status"] = ns_status
773 if ns_status == "ERROR":
774 step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Deleting ns at RO. RO_ns_id={}"\
775 .format(RO_nsr_id)
776 self.logger.debug(logging_text + step)
777 await self.RO.delete("ns", RO_nsr_id)
778 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
779 if not RO_nsr_id:
780 step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Checking dependencies"
781 # self.logger.debug(logging_text + step)
782
783 # check if VIM is creating and wait look if previous tasks in process
784 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account", ns_params["vimAccountId"])
785 if task_dependency:
786 step = "Waiting for related tasks to be completed: {}".format(task_name)
787 self.logger.debug(logging_text + step)
788 await asyncio.wait(task_dependency, timeout=3600)
789 if ns_params.get("vnf"):
790 for vnf in ns_params["vnf"]:
791 if "vimAccountId" in vnf:
792 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account",
793 vnf["vimAccountId"])
794 if task_dependency:
795 step = "Waiting for related tasks to be completed: {}".format(task_name)
796 self.logger.debug(logging_text + step)
797 await asyncio.wait(task_dependency, timeout=3600)
798
799 step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Checking instantiation parameters"
800
801 RO_ns_params = self.ns_params_2_RO(ns_params, nsd, db_vnfds_ref, n2vc_key_list)
802
803 step = db_nsr_update["detailed-status"] = "Deploying ns at VIM"
804 # step = db_nsr_update["_admin.deployed.RO.detailed-status"] = "Deploying ns at VIM"
805 desc = await self.RO.create("ns", descriptor=RO_ns_params, name=db_nsr["name"], scenario=RO_nsd_uuid)
806 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = desc["uuid"]
807 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
808 db_nsr_update["_admin.deployed.RO.nsr_status"] = "BUILD"
809 self.logger.debug(logging_text + "ns created at RO. RO_id={}".format(desc["uuid"]))
810 self.update_db_2("nsrs", nsr_id, db_nsr_update)
811 self._on_update_n2vc_db("nsrs", {"_id": nsr_id}, "_admin.deployed", db_nsr_update)
812
813 # wait until NS is ready
814 step = ns_status_detailed = detailed_status = "Waiting VIM to deploy ns. RO_ns_id={}".format(RO_nsr_id)
815 detailed_status_old = None
816 self.logger.debug(logging_text + step)
817
818 while time() <= start_deploy + self.total_deploy_timeout:
819 desc = await self.RO.show("ns", RO_nsr_id)
820 ns_status, ns_status_info = self.RO.check_ns_status(desc)
821 db_nsr_update["_admin.deployed.RO.nsr_status"] = ns_status
822 if ns_status == "ERROR":
823 raise ROclient.ROClientException(ns_status_info)
824 elif ns_status == "BUILD":
825 detailed_status = ns_status_detailed + "; {}".format(ns_status_info)
826 elif ns_status == "ACTIVE":
827 step = detailed_status = "Waiting for management IP address reported by the VIM. Updating VNFRs"
828 try:
829 if vdu_flag:
830 self.ns_update_vnfr(db_vnfrs, desc)
831 break
832 except LcmExceptionNoMgmtIP:
833 pass
834 else:
835 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
836 if detailed_status != detailed_status_old:
837 detailed_status_old = db_nsr_update["_admin.deployed.RO.detailed-status"] = detailed_status
838 self.update_db_2("nsrs", nsr_id, db_nsr_update)
839 self._on_update_n2vc_db("nsrs", {"_id": nsr_id}, "_admin.deployed", db_nsr_update)
840 await asyncio.sleep(5, loop=self.loop)
841 else: # total_deploy_timeout
842 raise ROclient.ROClientException("Timeout waiting ns to be ready")
843
844 step = "Updating NSR"
845 self.ns_update_nsr(db_nsr_update, db_nsr, desc)
846
847 db_nsr_update["_admin.deployed.RO.operational-status"] = "running"
848 db_nsr["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
849 db_nsr_update["_admin.deployed.RO.detailed-status"] = "Deployed at VIM"
850 self.update_db_2("nsrs", nsr_id, db_nsr_update)
851 self._on_update_n2vc_db("nsrs", {"_id": nsr_id}, "_admin.deployed", db_nsr_update)
852
853 step = "Deployed at VIM"
854 self.logger.debug(logging_text + step)
855
856 async def wait_vm_up_insert_key_ro(self, logging_text, nsr_id, vnfr_id, vdu_id, vdu_index, pub_key=None, user=None):
857 """
858 Wait for ip addres at RO, and optionally, insert public key in virtual machine
859 :param logging_text: prefix use for logging
860 :param nsr_id:
861 :param vnfr_id:
862 :param vdu_id:
863 :param vdu_index:
864 :param pub_key: public ssh key to inject, None to skip
865 :param user: user to apply the public ssh key
866 :return: IP address
867 """
868
869 # self.logger.debug(logging_text + "Starting wait_vm_up_insert_key_ro")
870 ro_nsr_id = None
871 ip_address = None
872 nb_tries = 0
873 target_vdu_id = None
874 ro_retries = 0
875
876 while True:
877
878 ro_retries += 1
879 if ro_retries >= 360: # 1 hour
880 raise LcmException("Not found _admin.deployed.RO.nsr_id for nsr_id: {}".format(nsr_id))
881
882 await asyncio.sleep(10, loop=self.loop)
883 # wait until NS is deployed at RO
884 if not ro_nsr_id:
885 db_nsrs = self.db.get_one("nsrs", {"_id": nsr_id})
886 ro_nsr_id = deep_get(db_nsrs, ("_admin", "deployed", "RO", "nsr_id"))
887 if not ro_nsr_id:
888 continue
889
890 # get ip address
891 if not target_vdu_id:
892 db_vnfr = self.db.get_one("vnfrs", {"_id": vnfr_id})
893
894 if not vdu_id: # for the VNF case
895 ip_address = db_vnfr.get("ip-address")
896 if not ip_address:
897 continue
898 vdur = next((x for x in get_iterable(db_vnfr, "vdur") if x.get("ip-address") == ip_address), None)
899 else: # VDU case
900 vdur = next((x for x in get_iterable(db_vnfr, "vdur")
901 if x.get("vdu-id-ref") == vdu_id and x.get("count-index") == vdu_index), None)
902
903 if not vdur:
904 raise LcmException("Not found vnfr_id={}, vdu_index={}, vdu_index={}".format(
905 vnfr_id, vdu_id, vdu_index
906 ))
907
908 if vdur.get("status") == "ACTIVE":
909 ip_address = vdur.get("ip-address")
910 if not ip_address:
911 continue
912 target_vdu_id = vdur["vdu-id-ref"]
913 elif vdur.get("status") == "ERROR":
914 raise LcmException("Cannot inject ssh-key because target VM is in error state")
915
916 if not target_vdu_id:
917 continue
918
919 # self.logger.debug(logging_text + "IP address={}".format(ip_address))
920
921 # inject public key into machine
922 if pub_key and user:
923 # self.logger.debug(logging_text + "Inserting RO key")
924 try:
925 ro_vm_id = "{}-{}".format(db_vnfr["member-vnf-index-ref"], target_vdu_id) # TODO add vdu_index
926 result_dict = await self.RO.create_action(
927 item="ns",
928 item_id_name=ro_nsr_id,
929 descriptor={"add_public_key": pub_key, "vms": [ro_vm_id], "user": user}
930 )
931 # result_dict contains the format {VM-id: {vim_result: 200, description: text}}
932 if not result_dict or not isinstance(result_dict, dict):
933 raise LcmException("Unknown response from RO when injecting key")
934 for result in result_dict.values():
935 if result.get("vim_result") == 200:
936 break
937 else:
938 raise ROclient.ROClientException("error injecting key: {}".format(
939 result.get("description")))
940 break
941 except ROclient.ROClientException as e:
942 if not nb_tries:
943 self.logger.debug(logging_text + "error injecting key: {}. Retrying until {} seconds".
944 format(e, 20*10))
945 nb_tries += 1
946 if nb_tries >= 20:
947 raise LcmException("Reaching max tries injecting key. Error: {}".format(e))
948 else:
949 break
950
951 return ip_address
952
953 async def instantiate_N2VC(self, logging_text, vca_index, nsi_id, db_nsr, db_vnfr, vdu_id,
954 kdu_name, vdu_index, config_descriptor, deploy_params, base_folder):
955 nsr_id = db_nsr["_id"]
956 db_update_entry = "_admin.deployed.VCA.{}.".format(vca_index)
957 vca_deployed_list = db_nsr["_admin"]["deployed"]["VCA"]
958 vca_deployed = db_nsr["_admin"]["deployed"]["VCA"][vca_index]
959 db_dict = {
960 'collection': 'nsrs',
961 'filter': {'_id': nsr_id},
962 'path': db_update_entry
963 }
964 logging_text += "member_vnf_index={} vdu_id={}, vdu_index={} ".format(db_vnfr["member-vnf-index-ref"],
965 vdu_id, vdu_index)
966
967 step = ""
968 try:
969 vnfr_id = None
970 if db_vnfr:
971 vnfr_id = db_vnfr["_id"]
972
973 namespace = "{nsi}.{ns}".format(
974 nsi=nsi_id if nsi_id else "",
975 ns=nsr_id)
976 if vnfr_id:
977 namespace += "." + vnfr_id
978 if vdu_id:
979 namespace += ".{}-{}".format(vdu_id, vdu_index or 0)
980
981 # Get artifact path
982 artifact_path = "/{}/{}/charms/{}".format(
983 base_folder["folder"],
984 base_folder["pkg-dir"],
985 config_descriptor["juju"]["charm"]
986 )
987
988 is_proxy_charm = deep_get(config_descriptor, ('juju', 'charm')) is not None
989 if deep_get(config_descriptor, ('juju', 'proxy')) is False:
990 is_proxy_charm = False
991
992 # n2vc_redesign STEP 3.1
993
994 # find old ee_id if exists
995 ee_id = vca_deployed.get("ee_id")
996
997 # create or register execution environment in VCA
998 if is_proxy_charm:
999 step = "create execution environment"
1000 self.logger.debug(logging_text + step)
1001 ee_id, credentials = await self.n2vc.create_execution_environment(namespace=namespace,
1002 reuse_ee_id=ee_id,
1003 db_dict=db_dict)
1004 else:
1005 step = "Waiting to VM being up and getting IP address"
1006 self.logger.debug(logging_text + step)
1007 rw_mgmt_ip = await self.wait_vm_up_insert_key_ro(logging_text, nsr_id, vnfr_id, vdu_id, vdu_index,
1008 user=None, pub_key=None)
1009 credentials = {"hostname": rw_mgmt_ip}
1010 # get username
1011 username = deep_get(config_descriptor, ("config-access", "ssh-access", "default-user"))
1012 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
1013 # merged. Meanwhile let's get username from initial-config-primitive
1014 if not username and config_descriptor.get("initial-config-primitive"):
1015 for config_primitive in config_descriptor["initial-config-primitive"]:
1016 for param in config_primitive.get("parameter", ()):
1017 if param["name"] == "ssh-username":
1018 username = param["value"]
1019 break
1020 if not username:
1021 raise LcmException("Cannot determine the username neither with 'initial-config-promitive' nor with "
1022 "'config-access.ssh-access.default-user'")
1023 credentials["username"] = username
1024 # n2vc_redesign STEP 3.2
1025
1026 step = "register execution environment {}".format(credentials)
1027 self.logger.debug(logging_text + step)
1028 ee_id = await self.n2vc.register_execution_environment(credentials=credentials, namespace=namespace,
1029 db_dict=db_dict)
1030
1031 # for compatibility with MON/POL modules, the need model and application name at database
1032 # TODO ask to N2VC instead of assuming the format "model_name.application_name"
1033 ee_id_parts = ee_id.split('.')
1034 model_name = ee_id_parts[0]
1035 application_name = ee_id_parts[1]
1036 self.update_db_2("nsrs", nsr_id, {db_update_entry + "model": model_name,
1037 db_update_entry + "application": application_name,
1038 db_update_entry + "ee_id": ee_id})
1039
1040 # n2vc_redesign STEP 3.3
1041
1042 step = "Install configuration Software"
1043 # TODO check if already done
1044 self.logger.debug(logging_text + step)
1045 await self.n2vc.install_configuration_sw(ee_id=ee_id, artifact_path=artifact_path, db_dict=db_dict)
1046
1047 # if SSH access is required, then get execution environment SSH public
1048 if is_proxy_charm: # if native charm we have waited already to VM be UP
1049 pub_key = None
1050 user = None
1051 if deep_get(config_descriptor, ("config-access", "ssh-access", "required")):
1052 # Needed to inject a ssh key
1053 user = deep_get(config_descriptor, ("config-access", "ssh-access", "default-user"))
1054 step = "Install configuration Software, getting public ssh key"
1055 pub_key = await self.n2vc.get_ee_ssh_public__key(ee_id=ee_id, db_dict=db_dict)
1056
1057 step = "Insert public key into VM"
1058 else:
1059 step = "Waiting to VM being up and getting IP address"
1060 self.logger.debug(logging_text + step)
1061
1062 # n2vc_redesign STEP 5.1
1063 # wait for RO (ip-address) Insert pub_key into VM
1064 rw_mgmt_ip = await self.wait_vm_up_insert_key_ro(logging_text, nsr_id, vnfr_id, vdu_id, vdu_index,
1065 user=user, pub_key=pub_key)
1066
1067 self.logger.debug(logging_text + ' VM_ip_address={}'.format(rw_mgmt_ip))
1068
1069 # store rw_mgmt_ip in deploy params for later replacement
1070 deploy_params["rw_mgmt_ip"] = rw_mgmt_ip
1071
1072 # n2vc_redesign STEP 6 Execute initial config primitive
1073 step = 'execute initial config primitive'
1074 initial_config_primitive_list = config_descriptor.get('initial-config-primitive')
1075
1076 # sort initial config primitives by 'seq'
1077 try:
1078 initial_config_primitive_list.sort(key=lambda val: int(val['seq']))
1079 except Exception as e:
1080 self.logger.error(logging_text + step + ": " + str(e))
1081
1082 # add config if not present for NS charm
1083 initial_config_primitive_list = self._get_initial_config_primitive_list(initial_config_primitive_list,
1084 vca_deployed)
1085
1086 for initial_config_primitive in initial_config_primitive_list:
1087 # adding information on the vca_deployed if it is a NS execution environment
1088 if not vca_deployed["member-vnf-index"]:
1089 deploy_params["ns_config_info"] = self._get_ns_config_info(vca_deployed_list)
1090 # TODO check if already done
1091 primitive_params_ = self._map_primitive_params(initial_config_primitive, {}, deploy_params)
1092
1093 step = "execute primitive '{}' params '{}'".format(initial_config_primitive["name"], primitive_params_)
1094 self.logger.debug(logging_text + step)
1095 await self.n2vc.exec_primitive(
1096 ee_id=ee_id,
1097 primitive_name=initial_config_primitive["name"],
1098 params_dict=primitive_params_,
1099 db_dict=db_dict
1100 )
1101 # TODO register in database that primitive is done
1102
1103 step = "instantiated at VCA"
1104 self.logger.debug(logging_text + step)
1105
1106 except Exception as e: # TODO not use Exception but N2VC exception
1107 raise Exception("{} {}".format(step, e)) from e
1108 # TODO raise N2VC exception with 'step' extra information
1109
1110 async def instantiate(self, nsr_id, nslcmop_id):
1111 """
1112
1113 :param nsr_id: ns instance to deploy
1114 :param nslcmop_id: operation to run
1115 :return:
1116 """
1117
1118 # Try to lock HA task here
1119 task_is_locked_by_me = self.lcm_tasks.lock_HA('ns', 'nslcmops', nslcmop_id)
1120 if not task_is_locked_by_me:
1121 self.logger.debug('instantiate() task is not locked by me')
1122 return
1123
1124 logging_text = "Task ns={} instantiate={} ".format(nsr_id, nslcmop_id)
1125 self.logger.debug(logging_text + "Enter")
1126
1127 # get all needed from database
1128
1129 # database nsrs record
1130 db_nsr = None
1131
1132 # database nslcmops record
1133 db_nslcmop = None
1134
1135 # update operation on nsrs
1136 db_nsr_update = {"_admin.nslcmop": nslcmop_id,
1137 "_admin.current-operation": nslcmop_id,
1138 "_admin.operation-type": "instantiate"}
1139 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1140
1141 # update operation on nslcmops
1142 db_nslcmop_update = {}
1143
1144 nslcmop_operation_state = None
1145 db_vnfrs = {} # vnf's info indexed by member-index
1146 # n2vc_info = {}
1147 task_instantiation_list = []
1148 exc = None
1149 try:
1150 # wait for any previous tasks in process
1151 step = "Waiting for previous operations to terminate"
1152 await self.lcm_tasks.waitfor_related_HA('ns', 'nslcmops', nslcmop_id)
1153
1154 # STEP 0: Reading database (nslcmops, nsrs, nsds, vnfrs, vnfds)
1155
1156 # read from db: operation
1157 step = "Getting nslcmop={} from db".format(nslcmop_id)
1158 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
1159
1160 # read from db: ns
1161 step = "Getting nsr={} from db".format(nsr_id)
1162 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1163 # nsd is replicated into ns (no db read)
1164 nsd = db_nsr["nsd"]
1165 # nsr_name = db_nsr["name"] # TODO short-name??
1166
1167 # read from db: vnf's of this ns
1168 step = "Getting vnfrs from db"
1169 self.logger.debug(logging_text + step)
1170 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1171
1172 # read from db: vnfd's for every vnf
1173 db_vnfds_ref = {} # every vnfd data indexed by vnf name
1174 db_vnfds = {} # every vnfd data indexed by vnf id
1175 db_vnfds_index = {} # every vnfd data indexed by vnf member-index
1176
1177 # for each vnf in ns, read vnfd
1178 for vnfr in db_vnfrs_list:
1179 db_vnfrs[vnfr["member-vnf-index-ref"]] = vnfr # vnf's dict indexed by member-index: '1', '2', etc
1180 vnfd_id = vnfr["vnfd-id"] # vnfd uuid for this vnf
1181 vnfd_ref = vnfr["vnfd-ref"] # vnfd name for this vnf
1182 # if we haven't this vnfd, read it from db
1183 if vnfd_id not in db_vnfds:
1184 # read from cb
1185 step = "Getting vnfd={} id='{}' from db".format(vnfd_id, vnfd_ref)
1186 self.logger.debug(logging_text + step)
1187 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
1188
1189 # store vnfd
1190 db_vnfds_ref[vnfd_ref] = vnfd # vnfd's indexed by name
1191 db_vnfds[vnfd_id] = vnfd # vnfd's indexed by id
1192 db_vnfds_index[vnfr["member-vnf-index-ref"]] = db_vnfds[vnfd_id] # vnfd's indexed by member-index
1193
1194 # Get or generates the _admin.deployed.VCA list
1195 vca_deployed_list = None
1196 if db_nsr["_admin"].get("deployed"):
1197 vca_deployed_list = db_nsr["_admin"]["deployed"].get("VCA")
1198 if vca_deployed_list is None:
1199 vca_deployed_list = []
1200 db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
1201 # add _admin.deployed.VCA to db_nsr dictionary, value=vca_deployed_list
1202 populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
1203 elif isinstance(vca_deployed_list, dict):
1204 # maintain backward compatibility. Change a dict to list at database
1205 vca_deployed_list = list(vca_deployed_list.values())
1206 db_nsr_update["_admin.deployed.VCA"] = vca_deployed_list
1207 populate_dict(db_nsr, ("_admin", "deployed", "VCA"), vca_deployed_list)
1208
1209 db_nsr_update["detailed-status"] = "creating"
1210 db_nsr_update["operational-status"] = "init"
1211
1212 if not isinstance(deep_get(db_nsr, ("_admin", "deployed", "RO", "vnfd")), list):
1213 populate_dict(db_nsr, ("_admin", "deployed", "RO", "vnfd"), [])
1214 db_nsr_update["_admin.deployed.RO.vnfd"] = []
1215
1216 # set state to INSTANTIATED. When instantiated NBI will not delete directly
1217 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
1218 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1219 self.logger.debug(logging_text + "Before deploy_kdus")
1220 # Call to deploy_kdus in case exists the "vdu:kdu" param
1221 task_kdu = asyncio.ensure_future(
1222 self.deploy_kdus(
1223 logging_text=logging_text,
1224 nsr_id=nsr_id,
1225 db_nsr=db_nsr,
1226 db_vnfrs=db_vnfrs,
1227 )
1228 )
1229 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "instantiate_KDUs", task_kdu)
1230 task_instantiation_list.append(task_kdu)
1231 # n2vc_redesign STEP 1 Get VCA public ssh-key
1232 # feature 1429. Add n2vc public key to needed VMs
1233 n2vc_key = self.n2vc.get_public_key()
1234 n2vc_key_list = [n2vc_key]
1235 if self.vca_config.get("public_key"):
1236 n2vc_key_list.append(self.vca_config["public_key"])
1237
1238 # n2vc_redesign STEP 2 Deploy Network Scenario
1239 task_ro = asyncio.ensure_future(
1240 self.instantiate_RO(
1241 logging_text=logging_text,
1242 nsr_id=nsr_id,
1243 nsd=nsd,
1244 db_nsr=db_nsr,
1245 db_nslcmop=db_nslcmop,
1246 db_vnfrs=db_vnfrs,
1247 db_vnfds_ref=db_vnfds_ref,
1248 n2vc_key_list=n2vc_key_list
1249 )
1250 )
1251 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "instantiate_RO", task_ro)
1252 task_instantiation_list.append(task_ro)
1253
1254 # n2vc_redesign STEP 3 to 6 Deploy N2VC
1255 step = "Looking for needed vnfd to configure with proxy charm"
1256 self.logger.debug(logging_text + step)
1257
1258 nsi_id = None # TODO put nsi_id when this nsr belongs to a NSI
1259 # get_iterable() returns a value from a dict or empty tuple if key does not exist
1260 for c_vnf in get_iterable(nsd, "constituent-vnfd"):
1261 vnfd_id = c_vnf["vnfd-id-ref"]
1262 vnfd = db_vnfds_ref[vnfd_id]
1263 member_vnf_index = str(c_vnf["member-vnf-index"])
1264 db_vnfr = db_vnfrs[member_vnf_index]
1265 base_folder = vnfd["_admin"]["storage"]
1266 vdu_id = None
1267 vdu_index = 0
1268 vdu_name = None
1269 kdu_name = None
1270
1271 # Get additional parameters
1272 deploy_params = {}
1273 if db_vnfr.get("additionalParamsForVnf"):
1274 deploy_params = self._format_additional_params(db_vnfr["additionalParamsForVnf"].copy())
1275
1276 descriptor_config = vnfd.get("vnf-configuration")
1277 if descriptor_config and descriptor_config.get("juju"):
1278 self._deploy_n2vc(
1279 logging_text=logging_text,
1280 db_nsr=db_nsr,
1281 db_vnfr=db_vnfr,
1282 nslcmop_id=nslcmop_id,
1283 nsr_id=nsr_id,
1284 nsi_id=nsi_id,
1285 vnfd_id=vnfd_id,
1286 vdu_id=vdu_id,
1287 kdu_name=kdu_name,
1288 member_vnf_index=member_vnf_index,
1289 vdu_index=vdu_index,
1290 vdu_name=vdu_name,
1291 deploy_params=deploy_params,
1292 descriptor_config=descriptor_config,
1293 base_folder=base_folder,
1294 task_instantiation_list=task_instantiation_list
1295 )
1296
1297 # Deploy charms for each VDU that supports one.
1298 for vdud in get_iterable(vnfd, 'vdu'):
1299 vdu_id = vdud["id"]
1300 descriptor_config = vdud.get('vdu-configuration')
1301 vdur = next((x for x in db_vnfr["vdur"] if x["vdu-id-ref"] == vdu_id), None)
1302 if vdur.get("additionalParams"):
1303 deploy_params_vdu = self._format_additional_params(vdur["additionalParams"])
1304 else:
1305 deploy_params_vdu = deploy_params
1306 if descriptor_config and descriptor_config.get("juju"):
1307 # look for vdu index in the db_vnfr["vdu"] section
1308 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
1309 # if vdur["vdu-id-ref"] == vdu_id:
1310 # break
1311 # else:
1312 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
1313 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
1314 # vdu_name = vdur.get("name")
1315 vdu_name = None
1316 kdu_name = None
1317 for vdu_index in range(int(vdud.get("count", 1))):
1318 # TODO vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
1319 self._deploy_n2vc(
1320 logging_text=logging_text,
1321 db_nsr=db_nsr,
1322 db_vnfr=db_vnfr,
1323 nslcmop_id=nslcmop_id,
1324 nsr_id=nsr_id,
1325 nsi_id=nsi_id,
1326 vnfd_id=vnfd_id,
1327 vdu_id=vdu_id,
1328 kdu_name=kdu_name,
1329 member_vnf_index=member_vnf_index,
1330 vdu_index=vdu_index,
1331 vdu_name=vdu_name,
1332 deploy_params=deploy_params_vdu,
1333 descriptor_config=descriptor_config,
1334 base_folder=base_folder,
1335 task_instantiation_list=task_instantiation_list
1336 )
1337 for kdud in get_iterable(vnfd, 'kdu'):
1338 kdu_name = kdud["name"]
1339 descriptor_config = kdud.get('kdu-configuration')
1340 if descriptor_config and descriptor_config.get("juju"):
1341 vdu_id = None
1342 vdu_index = 0
1343 vdu_name = None
1344 # look for vdu index in the db_vnfr["vdu"] section
1345 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
1346 # if vdur["vdu-id-ref"] == vdu_id:
1347 # break
1348 # else:
1349 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
1350 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
1351 # vdu_name = vdur.get("name")
1352 # vdu_name = None
1353
1354 self._deploy_n2vc(
1355 logging_text=logging_text,
1356 db_nsr=db_nsr,
1357 db_vnfr=db_vnfr,
1358 nslcmop_id=nslcmop_id,
1359 nsr_id=nsr_id,
1360 nsi_id=nsi_id,
1361 vnfd_id=vnfd_id,
1362 vdu_id=vdu_id,
1363 kdu_name=kdu_name,
1364 member_vnf_index=member_vnf_index,
1365 vdu_index=vdu_index,
1366 vdu_name=vdu_name,
1367 deploy_params=deploy_params,
1368 descriptor_config=descriptor_config,
1369 base_folder=base_folder,
1370 task_instantiation_list=task_instantiation_list
1371 )
1372
1373 # Check if this NS has a charm configuration
1374 descriptor_config = nsd.get("ns-configuration")
1375 if descriptor_config and descriptor_config.get("juju"):
1376 vnfd_id = None
1377 db_vnfr = None
1378 member_vnf_index = None
1379 vdu_id = None
1380 kdu_name = None
1381 vdu_index = 0
1382 vdu_name = None
1383
1384 # Get additional parameters
1385 deploy_params = {}
1386 if db_nsr.get("additionalParamsForNs"):
1387 deploy_params = self._format_additional_params(db_nsr["additionalParamsForNs"].copy())
1388 base_folder = nsd["_admin"]["storage"]
1389 self._deploy_n2vc(
1390 logging_text=logging_text,
1391 db_nsr=db_nsr,
1392 db_vnfr=db_vnfr,
1393 nslcmop_id=nslcmop_id,
1394 nsr_id=nsr_id,
1395 nsi_id=nsi_id,
1396 vnfd_id=vnfd_id,
1397 vdu_id=vdu_id,
1398 kdu_name=kdu_name,
1399 member_vnf_index=member_vnf_index,
1400 vdu_index=vdu_index,
1401 vdu_name=vdu_name,
1402 deploy_params=deploy_params,
1403 descriptor_config=descriptor_config,
1404 base_folder=base_folder,
1405 task_instantiation_list=task_instantiation_list
1406 )
1407
1408 # Wait until all tasks of "task_instantiation_list" have been finished
1409
1410 # while time() <= start_deploy + self.total_deploy_timeout:
1411 error_text = None
1412 timeout = 3600 # time() - start_deploy
1413 task_instantiation_set = set(task_instantiation_list) # build a set with tasks
1414 done = None
1415 pending = None
1416 if len(task_instantiation_set) > 0:
1417 done, pending = await asyncio.wait(task_instantiation_set, timeout=timeout)
1418 if pending:
1419 error_text = "timeout"
1420 for task in done:
1421 if task.cancelled():
1422 if not error_text:
1423 error_text = "cancelled"
1424 elif task.done():
1425 exc = task.exception()
1426 if exc:
1427 error_text = str(exc)
1428
1429 if error_text:
1430 db_nsr_update["config-status"] = "failed"
1431 error_text = "fail configuring " + error_text
1432 db_nsr_update["detailed-status"] = error_text
1433 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED_TEMP"
1434 db_nslcmop_update["detailed-status"] = error_text
1435 db_nslcmop_update["statusEnteredTime"] = time()
1436 else:
1437 # all is done
1438 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
1439 db_nslcmop_update["statusEnteredTime"] = time()
1440 db_nslcmop_update["detailed-status"] = "done"
1441 db_nsr_update["config-status"] = "configured"
1442 db_nsr_update["detailed-status"] = "done"
1443
1444 except (ROclient.ROClientException, DbException, LcmException) as e:
1445 self.logger.error(logging_text + "Exit Exception while '{}': {}".format(step, e))
1446 exc = e
1447 except asyncio.CancelledError:
1448 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1449 exc = "Operation was cancelled"
1450 except Exception as e:
1451 exc = traceback.format_exc()
1452 self.logger.critical(logging_text + "Exit Exception {} while '{}': {}".format(type(e).__name__, step, e),
1453 exc_info=True)
1454 finally:
1455 if exc:
1456 if db_nsr:
1457 db_nsr_update["detailed-status"] = "ERROR {}: {}".format(step, exc)
1458 db_nsr_update["operational-status"] = "failed"
1459 if db_nslcmop:
1460 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
1461 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
1462 db_nslcmop_update["statusEnteredTime"] = time()
1463 try:
1464 if db_nsr:
1465 db_nsr_update["_admin.nslcmop"] = None
1466 db_nsr_update["_admin.current-operation"] = None
1467 db_nsr_update["_admin.operation-type"] = None
1468 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1469 if db_nslcmop_update:
1470 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1471 except DbException as e:
1472 self.logger.error(logging_text + "Cannot update database: {}".format(e))
1473 if nslcmop_operation_state:
1474 try:
1475 await self.msg.aiowrite("ns", "instantiated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
1476 "operationState": nslcmop_operation_state},
1477 loop=self.loop)
1478 except Exception as e:
1479 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1480
1481 self.logger.debug(logging_text + "Exit")
1482 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_instantiate")
1483
1484 async def deploy_kdus(self, logging_text, nsr_id, db_nsr, db_vnfrs):
1485 # Launch kdus if present in the descriptor
1486
1487 k8scluster_id_2_uuic = {"helm-chart": {}, "juju-bundle": {}}
1488
1489 def _get_cluster_id(cluster_id, cluster_type):
1490 nonlocal k8scluster_id_2_uuic
1491 if cluster_id in k8scluster_id_2_uuic[cluster_type]:
1492 return k8scluster_id_2_uuic[cluster_type][cluster_id]
1493
1494 db_k8scluster = self.db.get_one("k8sclusters", {"_id": cluster_id}, fail_on_empty=False)
1495 if not db_k8scluster:
1496 raise LcmException("K8s cluster {} cannot be found".format(cluster_id))
1497 k8s_id = deep_get(db_k8scluster, ("_admin", cluster_type, "id"))
1498 if not k8s_id:
1499 raise LcmException("K8s cluster '{}' has not been initilized for '{}'".format(cluster_id, cluster_type))
1500 k8scluster_id_2_uuic[cluster_type][cluster_id] = k8s_id
1501 return k8s_id
1502
1503 logging_text += "Deploy kdus: "
1504 try:
1505 db_nsr_update = {"_admin.deployed.K8s": []}
1506 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1507
1508 # Look for all vnfds
1509 pending_tasks = {}
1510 index = 0
1511 for vnfr_data in db_vnfrs.values():
1512 for kdur in get_iterable(vnfr_data, "kdur"):
1513 desc_params = self._format_additional_params(kdur.get("additionalParams"))
1514 kdumodel = None
1515 k8sclustertype = None
1516 error_text = None
1517 cluster_uuid = None
1518 if kdur.get("helm-chart"):
1519 kdumodel = kdur["helm-chart"]
1520 k8sclustertype = "chart"
1521 k8sclustertype_full = "helm-chart"
1522 elif kdur.get("juju-bundle"):
1523 kdumodel = kdur["juju-bundle"]
1524 k8sclustertype = "juju"
1525 k8sclustertype_full = "juju-bundle"
1526 else:
1527 error_text = "kdu type is neither helm-chart not juju-bundle. Maybe an old NBI version is" \
1528 " running"
1529 try:
1530 if not error_text:
1531 cluster_uuid = _get_cluster_id(kdur["k8s-cluster"]["id"], k8sclustertype_full)
1532 except LcmException as e:
1533 error_text = str(e)
1534 step = "Instantiate KDU {} in k8s cluster {}".format(kdur["kdu-name"], cluster_uuid)
1535
1536 k8s_instace_info = {"kdu-instance": None, "k8scluster-uuid": cluster_uuid,
1537 "k8scluster-type": k8sclustertype,
1538 "kdu-name": kdur["kdu-name"], "kdu-model": kdumodel}
1539 if error_text:
1540 k8s_instace_info["detailed-status"] = error_text
1541 db_nsr_update["_admin.deployed.K8s.{}".format(index)] = k8s_instace_info
1542 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1543 if error_text:
1544 continue
1545
1546 db_dict = {"collection": "nsrs", "filter": {"_id": nsr_id}, "path": "_admin.deployed.K8s."
1547 "{}".format(index)}
1548 if k8sclustertype == "chart":
1549 task = asyncio.ensure_future(
1550 self.k8sclusterhelm.install(cluster_uuid=cluster_uuid, kdu_model=kdumodel, atomic=True,
1551 params=desc_params, db_dict=db_dict, timeout=3600)
1552 )
1553 else:
1554 # TODO juju-bundle connector in place
1555 pass
1556 pending_tasks[task] = "_admin.deployed.K8s.{}.".format(index)
1557 index += 1
1558 if not pending_tasks:
1559 return
1560 self.logger.debug(logging_text + 'Waiting for terminate pending tasks...')
1561 pending_list = list(pending_tasks.keys())
1562 while pending_list:
1563 done_list, pending_list = await asyncio.wait(pending_list, timeout=30*60,
1564 return_when=asyncio.FIRST_COMPLETED)
1565 if not done_list: # timeout
1566 for task in pending_list:
1567 db_nsr_update[pending_tasks(task) + "detailed-status"] = "Timeout"
1568 break
1569 for task in done_list:
1570 exc = task.exception()
1571 if exc:
1572 db_nsr_update[pending_tasks[task] + "detailed-status"] = "{}".format(exc)
1573 else:
1574 db_nsr_update[pending_tasks[task] + "kdu-instance"] = task.result()
1575
1576 except Exception as e:
1577 self.logger.critical(logging_text + "Exit Exception {} while '{}': {}".format(type(e).__name__, step, e))
1578 raise LcmException("{} Exit Exception {} while '{}': {}".format(logging_text, type(e).__name__, step, e))
1579 finally:
1580 # TODO Write in data base
1581 if db_nsr_update:
1582 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1583
1584 def _deploy_n2vc(self, logging_text, db_nsr, db_vnfr, nslcmop_id, nsr_id, nsi_id, vnfd_id, vdu_id,
1585 kdu_name, member_vnf_index, vdu_index, vdu_name, deploy_params, descriptor_config,
1586 base_folder, task_instantiation_list):
1587 # launch instantiate_N2VC in a asyncio task and register task object
1588 # Look where information of this charm is at database <nsrs>._admin.deployed.VCA
1589 # if not found, create one entry and update database
1590
1591 # fill db_nsr._admin.deployed.VCA.<index>
1592 vca_index = -1
1593 for vca_index, vca_deployed in enumerate(db_nsr["_admin"]["deployed"]["VCA"]):
1594 if not vca_deployed:
1595 continue
1596 if vca_deployed.get("member-vnf-index") == member_vnf_index and \
1597 vca_deployed.get("vdu_id") == vdu_id and \
1598 vca_deployed.get("kdu_name") == kdu_name and \
1599 vca_deployed.get("vdu_count_index", 0) == vdu_index:
1600 break
1601 else:
1602 # not found, create one.
1603 vca_deployed = {
1604 "member-vnf-index": member_vnf_index,
1605 "vdu_id": vdu_id,
1606 "kdu_name": kdu_name,
1607 "vdu_count_index": vdu_index,
1608 "operational-status": "init", # TODO revise
1609 "detailed-status": "", # TODO revise
1610 "step": "initial-deploy", # TODO revise
1611 "vnfd_id": vnfd_id,
1612 "vdu_name": vdu_name,
1613 }
1614 vca_index += 1
1615 self.update_db_2("nsrs", nsr_id, {"_admin.deployed.VCA.{}".format(vca_index): vca_deployed})
1616 db_nsr["_admin"]["deployed"]["VCA"].append(vca_deployed)
1617
1618 # Launch task
1619 task_n2vc = asyncio.ensure_future(
1620 self.instantiate_N2VC(
1621 logging_text=logging_text,
1622 vca_index=vca_index,
1623 nsi_id=nsi_id,
1624 db_nsr=db_nsr,
1625 db_vnfr=db_vnfr,
1626 vdu_id=vdu_id,
1627 kdu_name=kdu_name,
1628 vdu_index=vdu_index,
1629 deploy_params=deploy_params,
1630 config_descriptor=descriptor_config,
1631 base_folder=base_folder,
1632 )
1633 )
1634 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "instantiate_N2VC-{}".format(vca_index), task_n2vc)
1635 task_instantiation_list.append(task_n2vc)
1636
1637 # Check if this VNFD has a configured terminate action
1638 def _has_terminate_config_primitive(self, vnfd):
1639 vnf_config = vnfd.get("vnf-configuration")
1640 if vnf_config and vnf_config.get("terminate-config-primitive"):
1641 return True
1642 else:
1643 return False
1644
1645 @staticmethod
1646 def _get_terminate_config_primitive_seq_list(vnfd):
1647 """ Get a numerically sorted list of the sequences for this VNFD's terminate action """
1648 # No need to check for existing primitive twice, already done before
1649 vnf_config = vnfd.get("vnf-configuration")
1650 seq_list = vnf_config.get("terminate-config-primitive")
1651 # Get all 'seq' tags in seq_list, order sequences numerically, ascending.
1652 seq_list_sorted = sorted(seq_list, key=lambda x: int(x['seq']))
1653 return seq_list_sorted
1654
1655 @staticmethod
1656 def _create_nslcmop(nsr_id, operation, params):
1657 """
1658 Creates a ns-lcm-opp content to be stored at database.
1659 :param nsr_id: internal id of the instance
1660 :param operation: instantiate, terminate, scale, action, ...
1661 :param params: user parameters for the operation
1662 :return: dictionary following SOL005 format
1663 """
1664 # Raise exception if invalid arguments
1665 if not (nsr_id and operation and params):
1666 raise LcmException(
1667 "Parameters 'nsr_id', 'operation' and 'params' needed to create primitive not provided")
1668 now = time()
1669 _id = str(uuid4())
1670 nslcmop = {
1671 "id": _id,
1672 "_id": _id,
1673 # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1674 "operationState": "PROCESSING",
1675 "statusEnteredTime": now,
1676 "nsInstanceId": nsr_id,
1677 "lcmOperationType": operation,
1678 "startTime": now,
1679 "isAutomaticInvocation": False,
1680 "operationParams": params,
1681 "isCancelPending": False,
1682 "links": {
1683 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
1684 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
1685 }
1686 }
1687 return nslcmop
1688
1689 def _format_additional_params(self, params):
1690 params = params or {}
1691 for key, value in params.items():
1692 if str(value).startswith("!!yaml "):
1693 params[key] = yaml.safe_load(value[7:])
1694 return params
1695
1696 def _get_terminate_primitive_params(self, seq, vnf_index):
1697 primitive = seq.get('name')
1698 primitive_params = {}
1699 params = {
1700 "member_vnf_index": vnf_index,
1701 "primitive": primitive,
1702 "primitive_params": primitive_params,
1703 }
1704 desc_params = {}
1705 return self._map_primitive_params(seq, params, desc_params)
1706
1707 # sub-operations
1708
1709 def _reintent_or_skip_suboperation(self, db_nslcmop, op_index):
1710 op = db_nslcmop.get('_admin', {}).get('operations', [])[op_index]
1711 if (op.get('operationState') == 'COMPLETED'):
1712 # b. Skip sub-operation
1713 # _ns_execute_primitive() or RO.create_action() will NOT be executed
1714 return self.SUBOPERATION_STATUS_SKIP
1715 else:
1716 # c. Reintent executing sub-operation
1717 # The sub-operation exists, and operationState != 'COMPLETED'
1718 # Update operationState = 'PROCESSING' to indicate a reintent.
1719 operationState = 'PROCESSING'
1720 detailed_status = 'In progress'
1721 self._update_suboperation_status(
1722 db_nslcmop, op_index, operationState, detailed_status)
1723 # Return the sub-operation index
1724 # _ns_execute_primitive() or RO.create_action() will be called from scale()
1725 # with arguments extracted from the sub-operation
1726 return op_index
1727
1728 # Find a sub-operation where all keys in a matching dictionary must match
1729 # Returns the index of the matching sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if no match
1730 def _find_suboperation(self, db_nslcmop, match):
1731 if (db_nslcmop and match):
1732 op_list = db_nslcmop.get('_admin', {}).get('operations', [])
1733 for i, op in enumerate(op_list):
1734 if all(op.get(k) == match[k] for k in match):
1735 return i
1736 return self.SUBOPERATION_STATUS_NOT_FOUND
1737
1738 # Update status for a sub-operation given its index
1739 def _update_suboperation_status(self, db_nslcmop, op_index, operationState, detailed_status):
1740 # Update DB for HA tasks
1741 q_filter = {'_id': db_nslcmop['_id']}
1742 update_dict = {'_admin.operations.{}.operationState'.format(op_index): operationState,
1743 '_admin.operations.{}.detailed-status'.format(op_index): detailed_status}
1744 self.db.set_one("nslcmops",
1745 q_filter=q_filter,
1746 update_dict=update_dict,
1747 fail_on_empty=False)
1748
1749 # Add sub-operation, return the index of the added sub-operation
1750 # Optionally, set operationState, detailed-status, and operationType
1751 # Status and type are currently set for 'scale' sub-operations:
1752 # 'operationState' : 'PROCESSING' | 'COMPLETED' | 'FAILED'
1753 # 'detailed-status' : status message
1754 # 'operationType': may be any type, in the case of scaling: 'PRE-SCALE' | 'POST-SCALE'
1755 # Status and operation type are currently only used for 'scale', but NOT for 'terminate' sub-operations.
1756 def _add_suboperation(self, db_nslcmop, vnf_index, vdu_id, vdu_count_index, vdu_name, primitive,
1757 mapped_primitive_params, operationState=None, detailed_status=None, operationType=None,
1758 RO_nsr_id=None, RO_scaling_info=None):
1759 if not (db_nslcmop):
1760 return self.SUBOPERATION_STATUS_NOT_FOUND
1761 # Get the "_admin.operations" list, if it exists
1762 db_nslcmop_admin = db_nslcmop.get('_admin', {})
1763 op_list = db_nslcmop_admin.get('operations')
1764 # Create or append to the "_admin.operations" list
1765 new_op = {'member_vnf_index': vnf_index,
1766 'vdu_id': vdu_id,
1767 'vdu_count_index': vdu_count_index,
1768 'primitive': primitive,
1769 'primitive_params': mapped_primitive_params}
1770 if operationState:
1771 new_op['operationState'] = operationState
1772 if detailed_status:
1773 new_op['detailed-status'] = detailed_status
1774 if operationType:
1775 new_op['lcmOperationType'] = operationType
1776 if RO_nsr_id:
1777 new_op['RO_nsr_id'] = RO_nsr_id
1778 if RO_scaling_info:
1779 new_op['RO_scaling_info'] = RO_scaling_info
1780 if not op_list:
1781 # No existing operations, create key 'operations' with current operation as first list element
1782 db_nslcmop_admin.update({'operations': [new_op]})
1783 op_list = db_nslcmop_admin.get('operations')
1784 else:
1785 # Existing operations, append operation to list
1786 op_list.append(new_op)
1787
1788 db_nslcmop_update = {'_admin.operations': op_list}
1789 self.update_db_2("nslcmops", db_nslcmop['_id'], db_nslcmop_update)
1790 op_index = len(op_list) - 1
1791 return op_index
1792
1793 # Helper methods for scale() sub-operations
1794
1795 # pre-scale/post-scale:
1796 # Check for 3 different cases:
1797 # a. New: First time execution, return SUBOPERATION_STATUS_NEW
1798 # b. Skip: Existing sub-operation exists, operationState == 'COMPLETED', return SUBOPERATION_STATUS_SKIP
1799 # c. Reintent: Existing sub-operation exists, operationState != 'COMPLETED', return op_index to re-execute
1800 def _check_or_add_scale_suboperation(self, db_nslcmop, vnf_index, vnf_config_primitive, primitive_params,
1801 operationType, RO_nsr_id=None, RO_scaling_info=None):
1802 # Find this sub-operation
1803 if (RO_nsr_id and RO_scaling_info):
1804 operationType = 'SCALE-RO'
1805 match = {
1806 'member_vnf_index': vnf_index,
1807 'RO_nsr_id': RO_nsr_id,
1808 'RO_scaling_info': RO_scaling_info,
1809 }
1810 else:
1811 match = {
1812 'member_vnf_index': vnf_index,
1813 'primitive': vnf_config_primitive,
1814 'primitive_params': primitive_params,
1815 'lcmOperationType': operationType
1816 }
1817 op_index = self._find_suboperation(db_nslcmop, match)
1818 if (op_index == self.SUBOPERATION_STATUS_NOT_FOUND):
1819 # a. New sub-operation
1820 # The sub-operation does not exist, add it.
1821 # _ns_execute_primitive() will be called from scale() as usual, with non-modified arguments
1822 # The following parameters are set to None for all kind of scaling:
1823 vdu_id = None
1824 vdu_count_index = None
1825 vdu_name = None
1826 if (RO_nsr_id and RO_scaling_info):
1827 vnf_config_primitive = None
1828 primitive_params = None
1829 else:
1830 RO_nsr_id = None
1831 RO_scaling_info = None
1832 # Initial status for sub-operation
1833 operationState = 'PROCESSING'
1834 detailed_status = 'In progress'
1835 # Add sub-operation for pre/post-scaling (zero or more operations)
1836 self._add_suboperation(db_nslcmop,
1837 vnf_index,
1838 vdu_id,
1839 vdu_count_index,
1840 vdu_name,
1841 vnf_config_primitive,
1842 primitive_params,
1843 operationState,
1844 detailed_status,
1845 operationType,
1846 RO_nsr_id,
1847 RO_scaling_info)
1848 return self.SUBOPERATION_STATUS_NEW
1849 else:
1850 # Return either SUBOPERATION_STATUS_SKIP (operationState == 'COMPLETED'),
1851 # or op_index (operationState != 'COMPLETED')
1852 return self._reintent_or_skip_suboperation(db_nslcmop, op_index)
1853
1854 # Helper methods for terminate()
1855
1856 async def _terminate_action(self, db_nslcmop, nslcmop_id, nsr_id):
1857 """ Create a primitive with params from VNFD
1858 Called from terminate() before deleting instance
1859 Calls action() to execute the primitive """
1860 logging_text = "Task ns={} _terminate_action={} ".format(nsr_id, nslcmop_id)
1861 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1862 db_vnfds = {}
1863 # Loop over VNFRs
1864 for vnfr in db_vnfrs_list:
1865 vnfd_id = vnfr["vnfd-id"]
1866 vnf_index = vnfr["member-vnf-index-ref"]
1867 if vnfd_id not in db_vnfds:
1868 step = "Getting vnfd={} id='{}' from db".format(vnfd_id, vnfd_id)
1869 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
1870 db_vnfds[vnfd_id] = vnfd
1871 vnfd = db_vnfds[vnfd_id]
1872 if not self._has_terminate_config_primitive(vnfd):
1873 continue
1874 # Get the primitive's sorted sequence list
1875 seq_list = self._get_terminate_config_primitive_seq_list(vnfd)
1876 for seq in seq_list:
1877 # For each sequence in list, get primitive and call _ns_execute_primitive()
1878 step = "Calling terminate action for vnf_member_index={} primitive={}".format(
1879 vnf_index, seq.get("name"))
1880 self.logger.debug(logging_text + step)
1881 # Create the primitive for each sequence, i.e. "primitive": "touch"
1882 primitive = seq.get('name')
1883 mapped_primitive_params = self._get_terminate_primitive_params(seq, vnf_index)
1884 # The following 3 parameters are currently set to None for 'terminate':
1885 # vdu_id, vdu_count_index, vdu_name
1886 vdu_id = db_nslcmop["operationParams"].get("vdu_id")
1887 vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
1888 vdu_name = db_nslcmop["operationParams"].get("vdu_name")
1889 # Add sub-operation
1890 self._add_suboperation(db_nslcmop,
1891 nslcmop_id,
1892 vnf_index,
1893 vdu_id,
1894 vdu_count_index,
1895 vdu_name,
1896 primitive,
1897 mapped_primitive_params)
1898 # Sub-operations: Call _ns_execute_primitive() instead of action()
1899 # db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1900 # nsr_deployed = db_nsr["_admin"]["deployed"]
1901
1902 # nslcmop_operation_state, nslcmop_operation_state_detail = await self.action(
1903 # nsr_id, nslcmop_terminate_action_id)
1904 # Launch Exception if action() returns other than ['COMPLETED', 'PARTIALLY_COMPLETED']
1905 # result_ok = ['COMPLETED', 'PARTIALLY_COMPLETED']
1906 # if result not in result_ok:
1907 # raise LcmException(
1908 # "terminate_primitive_action for vnf_member_index={}",
1909 # " primitive={} fails with error {}".format(
1910 # vnf_index, seq.get("name"), result_detail))
1911
1912 # TODO: find ee_id
1913 ee_id = None
1914 try:
1915 await self.n2vc.exec_primitive(
1916 ee_id=ee_id,
1917 primitive_name=primitive,
1918 params_dict=mapped_primitive_params
1919 )
1920 except Exception as e:
1921 self.logger.error('Error executing primitive {}: {}'.format(primitive, e))
1922 raise LcmException(
1923 "terminate_primitive_action for vnf_member_index={}, primitive={} fails with error {}"
1924 .format(vnf_index, seq.get("name"), e),
1925 )
1926
1927 async def terminate(self, nsr_id, nslcmop_id):
1928
1929 # Try to lock HA task here
1930 task_is_locked_by_me = self.lcm_tasks.lock_HA('ns', 'nslcmops', nslcmop_id)
1931 if not task_is_locked_by_me:
1932 return
1933
1934 logging_text = "Task ns={} terminate={} ".format(nsr_id, nslcmop_id)
1935 self.logger.debug(logging_text + "Enter")
1936 db_nsr = None
1937 db_nslcmop = None
1938 exc = None
1939 failed_detail = [] # annotates all failed error messages
1940 db_nsr_update = {"_admin.nslcmop": nslcmop_id,
1941 "_admin.current-operation": nslcmop_id,
1942 "_admin.operation-type": "terminate"}
1943 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1944 db_nslcmop_update = {}
1945 nslcmop_operation_state = None
1946 autoremove = False # autoremove after terminated
1947 pending_tasks = []
1948 try:
1949 # wait for any previous tasks in process
1950 step = "Waiting for previous operations to terminate"
1951 await self.lcm_tasks.waitfor_related_HA("ns", 'nslcmops', nslcmop_id)
1952
1953 step = "Getting nslcmop={} from db".format(nslcmop_id)
1954 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
1955 step = "Getting nsr={} from db".format(nsr_id)
1956 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1957 # nsd = db_nsr["nsd"]
1958 nsr_deployed = deepcopy(db_nsr["_admin"].get("deployed"))
1959 if db_nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
1960 return
1961 # #TODO check if VIM is creating and wait
1962 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
1963 # Call internal terminate action
1964 await self._terminate_action(db_nslcmop, nslcmop_id, nsr_id)
1965
1966 pending_tasks = []
1967
1968 db_nsr_update["operational-status"] = "terminating"
1969 db_nsr_update["config-status"] = "terminating"
1970
1971 # remove NS
1972 try:
1973 step = "delete execution environment"
1974 self.logger.debug(logging_text + step)
1975
1976 task_delete_ee = asyncio.ensure_future(self.n2vc.delete_namespace(namespace="." + nsr_id))
1977 pending_tasks.append(task_delete_ee)
1978 except Exception as e:
1979 msg = "Failed while deleting NS in VCA: {}".format(e)
1980 self.logger.error(msg)
1981 failed_detail.append(msg)
1982
1983 try:
1984 # Delete from k8scluster
1985 step = "delete kdus"
1986 self.logger.debug(logging_text + step)
1987 # print(nsr_deployed)
1988 if nsr_deployed:
1989 for kdu in nsr_deployed.get("K8s", ()):
1990 kdu_instance = kdu.get("kdu-instance")
1991 if not kdu_instance:
1992 continue
1993 if kdu.get("k8scluster-type") == "chart":
1994 task_delete_kdu_instance = asyncio.ensure_future(
1995 self.k8sclusterhelm.uninstall(cluster_uuid=kdu.get("k8scluster-uuid"),
1996 kdu_instance=kdu_instance))
1997 elif kdu.get("k8scluster-type") == "juju":
1998 # TODO Juju connector needed
1999 continue
2000 else:
2001 self.error(logging_text + "Unknown k8s deployment type {}".
2002 format(kdu.get("k8scluster-type")))
2003 continue
2004 pending_tasks.append(task_delete_kdu_instance)
2005 except LcmException as e:
2006 msg = "Failed while deleting KDUs from NS: {}".format(e)
2007 self.logger.error(msg)
2008 failed_detail.append(msg)
2009
2010 # remove from RO
2011 RO_fail = False
2012
2013 # Delete ns
2014 RO_nsr_id = RO_delete_action = None
2015 if nsr_deployed and nsr_deployed.get("RO"):
2016 RO_nsr_id = nsr_deployed["RO"].get("nsr_id")
2017 RO_delete_action = nsr_deployed["RO"].get("nsr_delete_action_id")
2018 try:
2019 if RO_nsr_id:
2020 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] = \
2021 "Deleting ns from VIM"
2022 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
2023 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2024 self.logger.debug(logging_text + step)
2025 desc = await self.RO.delete("ns", RO_nsr_id)
2026 RO_delete_action = desc["action_id"]
2027 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = RO_delete_action
2028 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
2029 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
2030 if RO_delete_action:
2031 # wait until NS is deleted from VIM
2032 step = detailed_status = "Waiting ns deleted from VIM. RO_id={} RO_delete_action={}".\
2033 format(RO_nsr_id, RO_delete_action)
2034 detailed_status_old = None
2035 self.logger.debug(logging_text + step)
2036
2037 delete_timeout = 20 * 60 # 20 minutes
2038 while delete_timeout > 0:
2039 desc = await self.RO.show(
2040 "ns",
2041 item_id_name=RO_nsr_id,
2042 extra_item="action",
2043 extra_item_id=RO_delete_action)
2044 ns_status, ns_status_info = self.RO.check_action_status(desc)
2045 if ns_status == "ERROR":
2046 raise ROclient.ROClientException(ns_status_info)
2047 elif ns_status == "BUILD":
2048 detailed_status = step + "; {}".format(ns_status_info)
2049 elif ns_status == "ACTIVE":
2050 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
2051 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
2052 break
2053 else:
2054 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
2055 if detailed_status != detailed_status_old:
2056 detailed_status_old = db_nslcmop_update["detailed-status"] = \
2057 db_nsr_update["detailed-status"] = detailed_status
2058 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
2059 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2060 await asyncio.sleep(5, loop=self.loop)
2061 delete_timeout -= 5
2062 else: # delete_timeout <= 0:
2063 raise ROclient.ROClientException("Timeout waiting ns deleted from VIM")
2064
2065 except ROclient.ROClientException as e:
2066 if e.http_code == 404: # not found
2067 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
2068 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
2069 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = None
2070 self.logger.debug(logging_text + "RO_ns_id={} already deleted".format(RO_nsr_id))
2071 elif e.http_code == 409: # conflict
2072 failed_detail.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id, e))
2073 self.logger.debug(logging_text + failed_detail[-1])
2074 RO_fail = True
2075 else:
2076 failed_detail.append("RO_ns_id={} delete error: {}".format(RO_nsr_id, e))
2077 self.logger.error(logging_text + failed_detail[-1])
2078 RO_fail = True
2079
2080 # Delete nsd
2081 if not RO_fail and nsr_deployed and nsr_deployed.get("RO") and nsr_deployed["RO"].get("nsd_id"):
2082 RO_nsd_id = nsr_deployed["RO"]["nsd_id"]
2083 try:
2084 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
2085 "Deleting nsd from RO"
2086 await self.RO.delete("nsd", RO_nsd_id)
2087 self.logger.debug(logging_text + "RO_nsd_id={} deleted".format(RO_nsd_id))
2088 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
2089 except ROclient.ROClientException as e:
2090 if e.http_code == 404: # not found
2091 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
2092 self.logger.debug(logging_text + "RO_nsd_id={} already deleted".format(RO_nsd_id))
2093 elif e.http_code == 409: # conflict
2094 failed_detail.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id, e))
2095 self.logger.debug(logging_text + failed_detail[-1])
2096 RO_fail = True
2097 else:
2098 failed_detail.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id, e))
2099 self.logger.error(logging_text + failed_detail[-1])
2100 RO_fail = True
2101
2102 if not RO_fail and nsr_deployed and nsr_deployed.get("RO") and nsr_deployed["RO"].get("vnfd"):
2103 for index, vnf_deployed in enumerate(nsr_deployed["RO"]["vnfd"]):
2104 if not vnf_deployed or not vnf_deployed["id"]:
2105 continue
2106 try:
2107 RO_vnfd_id = vnf_deployed["id"]
2108 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
2109 "Deleting member_vnf_index={} RO_vnfd_id={} from RO".format(
2110 vnf_deployed["member-vnf-index"], RO_vnfd_id)
2111 await self.RO.delete("vnfd", RO_vnfd_id)
2112 self.logger.debug(logging_text + "RO_vnfd_id={} deleted".format(RO_vnfd_id))
2113 db_nsr_update["_admin.deployed.RO.vnfd.{}.id".format(index)] = None
2114 except ROclient.ROClientException as e:
2115 if e.http_code == 404: # not found
2116 db_nsr_update["_admin.deployed.RO.vnfd.{}.id".format(index)] = None
2117 self.logger.debug(logging_text + "RO_vnfd_id={} already deleted ".format(RO_vnfd_id))
2118 elif e.http_code == 409: # conflict
2119 failed_detail.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id, e))
2120 self.logger.debug(logging_text + failed_detail[-1])
2121 else:
2122 failed_detail.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id, e))
2123 self.logger.error(logging_text + failed_detail[-1])
2124
2125 if failed_detail:
2126 self.logger.error(logging_text + " ;".join(failed_detail))
2127 db_nsr_update["operational-status"] = "failed"
2128 db_nsr_update["detailed-status"] = "Deletion errors " + "; ".join(failed_detail)
2129 db_nslcmop_update["detailed-status"] = "; ".join(failed_detail)
2130 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
2131 db_nslcmop_update["statusEnteredTime"] = time()
2132 else:
2133 db_nsr_update["operational-status"] = "terminated"
2134 db_nsr_update["detailed-status"] = "Done"
2135 db_nsr_update["_admin.nsState"] = "NOT_INSTANTIATED"
2136 db_nslcmop_update["detailed-status"] = "Done"
2137 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
2138 db_nslcmop_update["statusEnteredTime"] = time()
2139 if db_nslcmop["operationParams"].get("autoremove"):
2140 autoremove = True
2141
2142 except (ROclient.ROClientException, DbException, LcmException) as e:
2143 self.logger.error(logging_text + "Exit Exception {}".format(e))
2144 exc = e
2145 except asyncio.CancelledError:
2146 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
2147 exc = "Operation was cancelled"
2148 except Exception as e:
2149 exc = traceback.format_exc()
2150 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
2151 finally:
2152 if exc and db_nslcmop:
2153 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
2154 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
2155 db_nslcmop_update["statusEnteredTime"] = time()
2156 try:
2157 if db_nslcmop and db_nslcmop_update:
2158 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
2159 if db_nsr:
2160 db_nsr_update["_admin.nslcmop"] = None
2161 db_nsr_update["_admin.current-operation"] = None
2162 db_nsr_update["_admin.operation-type"] = None
2163 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2164 except DbException as e:
2165 self.logger.error(logging_text + "Cannot update database: {}".format(e))
2166 if nslcmop_operation_state:
2167 try:
2168 await self.msg.aiowrite("ns", "terminated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
2169 "operationState": nslcmop_operation_state,
2170 "autoremove": autoremove},
2171 loop=self.loop)
2172 except Exception as e:
2173 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
2174
2175 # wait for pending tasks
2176 done = None
2177 pending = None
2178 if pending_tasks:
2179 self.logger.debug(logging_text + 'Waiting for terminate pending tasks...')
2180 done, pending = await asyncio.wait(pending_tasks, timeout=3600)
2181 if not pending:
2182 self.logger.debug(logging_text + 'All tasks finished...')
2183 else:
2184 self.logger.info(logging_text + 'There are pending tasks: {}'.format(pending))
2185
2186 self.logger.debug(logging_text + "Exit")
2187 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_terminate")
2188
2189 @staticmethod
2190 def _map_primitive_params(primitive_desc, params, instantiation_params):
2191 """
2192 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
2193 The default-value is used. If it is between < > it look for a value at instantiation_params
2194 :param primitive_desc: portion of VNFD/NSD that describes primitive
2195 :param params: Params provided by user
2196 :param instantiation_params: Instantiation params provided by user
2197 :return: a dictionary with the calculated params
2198 """
2199 calculated_params = {}
2200 for parameter in primitive_desc.get("parameter", ()):
2201 param_name = parameter["name"]
2202 if param_name in params:
2203 calculated_params[param_name] = params[param_name]
2204 elif "default-value" in parameter or "value" in parameter:
2205 if "value" in parameter:
2206 calculated_params[param_name] = parameter["value"]
2207 else:
2208 calculated_params[param_name] = parameter["default-value"]
2209 if isinstance(calculated_params[param_name], str) and calculated_params[param_name].startswith("<") \
2210 and calculated_params[param_name].endswith(">"):
2211 if calculated_params[param_name][1:-1] in instantiation_params:
2212 calculated_params[param_name] = instantiation_params[calculated_params[param_name][1:-1]]
2213 else:
2214 raise LcmException("Parameter {} needed to execute primitive {} not provided".
2215 format(calculated_params[param_name], primitive_desc["name"]))
2216 else:
2217 raise LcmException("Parameter {} needed to execute primitive {} not provided".
2218 format(param_name, primitive_desc["name"]))
2219
2220 if isinstance(calculated_params[param_name], (dict, list, tuple)):
2221 calculated_params[param_name] = yaml.safe_dump(calculated_params[param_name], default_flow_style=True,
2222 width=256)
2223 elif isinstance(calculated_params[param_name], str) and calculated_params[param_name].startswith("!!yaml "):
2224 calculated_params[param_name] = calculated_params[param_name][7:]
2225
2226 # add always ns_config_info if primitive name is config
2227 if primitive_desc["name"] == "config":
2228 if "ns_config_info" in instantiation_params:
2229 calculated_params["ns_config_info"] = instantiation_params["ns_config_info"]
2230 return calculated_params
2231
2232 async def _ns_execute_primitive(self, db_deployed, member_vnf_index, vdu_id, vdu_name, vdu_count_index,
2233 primitive, primitive_params, retries=0, retries_interval=30) -> (str, str):
2234
2235 # find vca_deployed record for this action
2236 try:
2237 for vca_deployed in db_deployed["VCA"]:
2238 if not vca_deployed:
2239 continue
2240 if member_vnf_index != vca_deployed["member-vnf-index"] or vdu_id != vca_deployed["vdu_id"]:
2241 continue
2242 if vdu_name and vdu_name != vca_deployed["vdu_name"]:
2243 continue
2244 if vdu_count_index and vdu_count_index != vca_deployed["vdu_count_index"]:
2245 continue
2246 break
2247 else:
2248 # vca_deployed not found
2249 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} is not "
2250 "deployed".format(member_vnf_index, vdu_id, vdu_name, vdu_count_index))
2251
2252 # get ee_id
2253 ee_id = vca_deployed.get("ee_id")
2254 if not ee_id:
2255 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} has not "
2256 "execution environment"
2257 .format(member_vnf_index, vdu_id, vdu_name, vdu_count_index))
2258
2259 if primitive == "config":
2260 primitive_params = {"params": primitive_params}
2261
2262 while retries >= 0:
2263 try:
2264 output = await self.n2vc.exec_primitive(
2265 ee_id=ee_id,
2266 primitive_name=primitive,
2267 params_dict=primitive_params
2268 )
2269 # execution was OK
2270 break
2271 except Exception as e:
2272 retries -= 1
2273 if retries >= 0:
2274 self.logger.debug('Error executing action {} on {} -> {}'.format(primitive, ee_id, e))
2275 # wait and retry
2276 await asyncio.sleep(retries_interval, loop=self.loop)
2277 else:
2278 return 'Cannot execute action {} on {}: {}'.format(primitive, ee_id, e), 'FAIL'
2279
2280 return output, 'OK'
2281
2282 except Exception as e:
2283 return 'Error executing action {}: {}'.format(primitive, e), 'FAIL'
2284
2285 async def action(self, nsr_id, nslcmop_id):
2286
2287 # Try to lock HA task here
2288 task_is_locked_by_me = self.lcm_tasks.lock_HA('ns', 'nslcmops', nslcmop_id)
2289 if not task_is_locked_by_me:
2290 return
2291
2292 logging_text = "Task ns={} action={} ".format(nsr_id, nslcmop_id)
2293 self.logger.debug(logging_text + "Enter")
2294 # get all needed from database
2295 db_nsr = None
2296 db_nslcmop = None
2297 db_nsr_update = {"_admin.nslcmop": nslcmop_id,
2298 "_admin.current-operation": nslcmop_id,
2299 "_admin.operation-type": "action"}
2300 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2301 db_nslcmop_update = {}
2302 nslcmop_operation_state = None
2303 nslcmop_operation_state_detail = None
2304 exc = None
2305 try:
2306 # wait for any previous tasks in process
2307 step = "Waiting for previous operations to terminate"
2308 await self.lcm_tasks.waitfor_related_HA('ns', 'nslcmops', nslcmop_id)
2309
2310 step = "Getting information from database"
2311 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
2312 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2313
2314 nsr_deployed = db_nsr["_admin"].get("deployed")
2315 vnf_index = db_nslcmop["operationParams"].get("member_vnf_index")
2316 vdu_id = db_nslcmop["operationParams"].get("vdu_id")
2317 kdu_name = db_nslcmop["operationParams"].get("kdu_name")
2318 vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
2319 vdu_name = db_nslcmop["operationParams"].get("vdu_name")
2320
2321 if vnf_index:
2322 step = "Getting vnfr from database"
2323 db_vnfr = self.db.get_one("vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id})
2324 step = "Getting vnfd from database"
2325 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
2326 else:
2327 if db_nsr.get("nsd"):
2328 db_nsd = db_nsr.get("nsd") # TODO this will be removed
2329 else:
2330 step = "Getting nsd from database"
2331 db_nsd = self.db.get_one("nsds", {"_id": db_nsr["nsd-id"]})
2332
2333 # for backward compatibility
2334 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
2335 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
2336 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
2337 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2338
2339 primitive = db_nslcmop["operationParams"]["primitive"]
2340 primitive_params = db_nslcmop["operationParams"]["primitive_params"]
2341
2342 # look for primitive
2343 config_primitive_desc = None
2344 if vdu_id:
2345 for vdu in get_iterable(db_vnfd, "vdu"):
2346 if vdu_id == vdu["id"]:
2347 for config_primitive in vdu.get("vdu-configuration", {}).get("config-primitive", ()):
2348 if config_primitive["name"] == primitive:
2349 config_primitive_desc = config_primitive
2350 break
2351 elif kdu_name:
2352 self.logger.debug(logging_text + "Checking actions in KDUs")
2353 kdur = next((x for x in db_vnfr["kdur"] if x["kdu_name"] == kdu_name), None)
2354 desc_params = self._format_additional_params(kdur.get("additionalParams")) or {}
2355 if primitive_params:
2356 desc_params.update(primitive_params)
2357 # TODO Check if we will need something at vnf level
2358 index = 0
2359 for kdu in get_iterable(nsr_deployed, "K8s"):
2360 if kdu_name == kdu["kdu-name"]:
2361 db_dict = {"collection": "nsrs", "filter": {"_id": nsr_id},
2362 "path": "_admin.deployed.K8s.{}".format(index)}
2363 if primitive == "upgrade":
2364 if desc_params.get("kdu_model"):
2365 kdu_model = desc_params.get("kdu_model")
2366 del desc_params["kdu_model"]
2367 else:
2368 kdu_model = kdu.get("kdu-model")
2369 parts = kdu_model.split(sep=":")
2370 if len(parts) == 2:
2371 kdu_model = parts[0]
2372
2373 if kdu.get("k8scluster-type") == "chart":
2374 output = await self.k8sclusterhelm.upgrade(cluster_uuid=kdu.get("k8scluster-uuid"),
2375 kdu_instance=kdu.get("kdu-instance"),
2376 atomic=True, kdu_model=kdu_model,
2377 params=desc_params, db_dict=db_dict,
2378 timeout=300)
2379 elif kdu.get("k8scluster-type") == "juju":
2380 # TODO Juju connector needed
2381 pass
2382 else:
2383 msg = "k8scluster-type not defined"
2384 raise LcmException(msg)
2385
2386 self.logger.debug(logging_text + " Upgrade of kdu {} done".format(output))
2387 break
2388 elif primitive == "rollback":
2389 if kdu.get("k8scluster-type") == "chart":
2390 output = await self.k8sclusterhelm.rollback(cluster_uuid=kdu.get("k8scluster-uuid"),
2391 kdu_instance=kdu.get("kdu-instance"),
2392 db_dict=db_dict)
2393 elif kdu.get("k8scluster-type") == "juju":
2394 # TODO Juju connector needed
2395 pass
2396 else:
2397 msg = "k8scluster-type not defined"
2398 raise LcmException(msg)
2399 break
2400 elif primitive == "status":
2401 if kdu.get("k8scluster-type") == "chart":
2402 output = await self.k8sclusterhelm.status_kdu(cluster_uuid=kdu.get("k8scluster-uuid"),
2403 kdu_instance=kdu.get("kdu-instance"))
2404 elif kdu.get("k8scluster-type") == "juju":
2405 # TODO Juju connector needed
2406 pass
2407 else:
2408 msg = "k8scluster-type not defined"
2409 raise LcmException(msg)
2410 break
2411 index += 1
2412
2413 else:
2414 raise LcmException("KDU '{}' not found".format(kdu_name))
2415 if output:
2416 db_nslcmop_update["detailed-status"] = output
2417 db_nslcmop_update["operationState"] = 'COMPLETED'
2418 db_nslcmop_update["statusEnteredTime"] = time()
2419 else:
2420 db_nslcmop_update["detailed-status"] = ''
2421 db_nslcmop_update["operationState"] = 'FAILED'
2422 db_nslcmop_update["statusEnteredTime"] = time()
2423 return
2424 elif vnf_index:
2425 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
2426 if config_primitive["name"] == primitive:
2427 config_primitive_desc = config_primitive
2428 break
2429 else:
2430 for config_primitive in db_nsd.get("ns-configuration", {}).get("config-primitive", ()):
2431 if config_primitive["name"] == primitive:
2432 config_primitive_desc = config_primitive
2433 break
2434
2435 if not config_primitive_desc:
2436 raise LcmException("Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".
2437 format(primitive))
2438
2439 desc_params = {}
2440 if vnf_index:
2441 if db_vnfr.get("additionalParamsForVnf"):
2442 desc_params = self._format_additional_params(db_vnfr["additionalParamsForVnf"])
2443 if vdu_id:
2444 vdur = next((x for x in db_vnfr["vdur"] if x["vdu-id-ref"] == vdu_id), None)
2445 if vdur.get("additionalParams"):
2446 desc_params = self._format_additional_params(vdur["additionalParams"])
2447 else:
2448 if db_nsr.get("additionalParamsForNs"):
2449 desc_params.update(self._format_additional_params(db_nsr["additionalParamsForNs"]))
2450
2451 # TODO check if ns is in a proper status
2452 output, detail = await self._ns_execute_primitive(
2453 db_deployed=nsr_deployed,
2454 member_vnf_index=vnf_index,
2455 vdu_id=vdu_id,
2456 vdu_name=vdu_name,
2457 vdu_count_index=vdu_count_index,
2458 primitive=primitive,
2459 primitive_params=self._map_primitive_params(config_primitive_desc, primitive_params, desc_params))
2460
2461 detailed_status = output
2462 if detail == 'OK':
2463 result = 'COMPLETED'
2464 else:
2465 result = 'FAILED'
2466
2467 db_nslcmop_update["detailed-status"] = nslcmop_operation_state_detail = detailed_status
2468 db_nslcmop_update["operationState"] = nslcmop_operation_state = result
2469 db_nslcmop_update["statusEnteredTime"] = time()
2470 self.logger.debug(logging_text + " task Done with result {} {}".format(result, detailed_status))
2471 return # database update is called inside finally
2472
2473 except (DbException, LcmException) as e:
2474 self.logger.error(logging_text + "Exit Exception {}".format(e))
2475 exc = e
2476 except asyncio.CancelledError:
2477 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
2478 exc = "Operation was cancelled"
2479 except Exception as e:
2480 exc = traceback.format_exc()
2481 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
2482 finally:
2483 if exc and db_nslcmop:
2484 db_nslcmop_update["detailed-status"] = nslcmop_operation_state_detail = \
2485 "FAILED {}: {}".format(step, exc)
2486 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
2487 db_nslcmop_update["statusEnteredTime"] = time()
2488 try:
2489 if db_nslcmop_update:
2490 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
2491 if db_nsr:
2492 db_nsr_update["_admin.nslcmop"] = None
2493 db_nsr_update["_admin.operation-type"] = None
2494 db_nsr_update["_admin.nslcmop"] = None
2495 db_nsr_update["_admin.current-operation"] = None
2496 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2497 except DbException as e:
2498 self.logger.error(logging_text + "Cannot update database: {}".format(e))
2499 self.logger.debug(logging_text + "Exit")
2500 if nslcmop_operation_state:
2501 try:
2502 await self.msg.aiowrite("ns", "actioned", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
2503 "operationState": nslcmop_operation_state},
2504 loop=self.loop)
2505 except Exception as e:
2506 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
2507 self.logger.debug(logging_text + "Exit")
2508 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_action")
2509 return nslcmop_operation_state, nslcmop_operation_state_detail
2510
2511 async def scale(self, nsr_id, nslcmop_id):
2512
2513 # Try to lock HA task here
2514 task_is_locked_by_me = self.lcm_tasks.lock_HA('ns', 'nslcmops', nslcmop_id)
2515 if not task_is_locked_by_me:
2516 return
2517
2518 logging_text = "Task ns={} scale={} ".format(nsr_id, nslcmop_id)
2519 self.logger.debug(logging_text + "Enter")
2520 # get all needed from database
2521 db_nsr = None
2522 db_nslcmop = None
2523 db_nslcmop_update = {}
2524 nslcmop_operation_state = None
2525 db_nsr_update = {"_admin.nslcmop": nslcmop_id,
2526 "_admin.current-operation": nslcmop_id,
2527 "_admin.operation-type": "scale"}
2528 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2529 exc = None
2530 # in case of error, indicates what part of scale was failed to put nsr at error status
2531 scale_process = None
2532 old_operational_status = ""
2533 old_config_status = ""
2534 vnfr_scaled = False
2535 try:
2536 # wait for any previous tasks in process
2537 step = "Waiting for previous operations to terminate"
2538 await self.lcm_tasks.waitfor_related_HA('ns', 'nslcmops', nslcmop_id)
2539
2540 step = "Getting nslcmop from database"
2541 self.logger.debug(step + " after having waited for previous tasks to be completed")
2542 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
2543 step = "Getting nsr from database"
2544 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2545
2546 old_operational_status = db_nsr["operational-status"]
2547 old_config_status = db_nsr["config-status"]
2548 step = "Parsing scaling parameters"
2549 # self.logger.debug(step)
2550 db_nsr_update["operational-status"] = "scaling"
2551 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2552 nsr_deployed = db_nsr["_admin"].get("deployed")
2553
2554 #######
2555 nsr_deployed = db_nsr["_admin"].get("deployed")
2556 vnf_index = db_nslcmop["operationParams"].get("member_vnf_index")
2557 # vdu_id = db_nslcmop["operationParams"].get("vdu_id")
2558 # vdu_count_index = db_nslcmop["operationParams"].get("vdu_count_index")
2559 # vdu_name = db_nslcmop["operationParams"].get("vdu_name")
2560 #######
2561
2562 RO_nsr_id = nsr_deployed["RO"]["nsr_id"]
2563 vnf_index = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
2564 scaling_group = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
2565 scaling_type = db_nslcmop["operationParams"]["scaleVnfData"]["scaleVnfType"]
2566 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
2567
2568 # for backward compatibility
2569 if nsr_deployed and isinstance(nsr_deployed.get("VCA"), dict):
2570 nsr_deployed["VCA"] = list(nsr_deployed["VCA"].values())
2571 db_nsr_update["_admin.deployed.VCA"] = nsr_deployed["VCA"]
2572 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2573
2574 step = "Getting vnfr from database"
2575 db_vnfr = self.db.get_one("vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id})
2576 step = "Getting vnfd from database"
2577 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
2578
2579 step = "Getting scaling-group-descriptor"
2580 for scaling_descriptor in db_vnfd["scaling-group-descriptor"]:
2581 if scaling_descriptor["name"] == scaling_group:
2582 break
2583 else:
2584 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
2585 "at vnfd:scaling-group-descriptor".format(scaling_group))
2586
2587 # cooldown_time = 0
2588 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
2589 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
2590 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
2591 # break
2592
2593 # TODO check if ns is in a proper status
2594 step = "Sending scale order to VIM"
2595 nb_scale_op = 0
2596 if not db_nsr["_admin"].get("scaling-group"):
2597 self.update_db_2("nsrs", nsr_id, {"_admin.scaling-group": [{"name": scaling_group, "nb-scale-op": 0}]})
2598 admin_scale_index = 0
2599 else:
2600 for admin_scale_index, admin_scale_info in enumerate(db_nsr["_admin"]["scaling-group"]):
2601 if admin_scale_info["name"] == scaling_group:
2602 nb_scale_op = admin_scale_info.get("nb-scale-op", 0)
2603 break
2604 else: # not found, set index one plus last element and add new entry with the name
2605 admin_scale_index += 1
2606 db_nsr_update["_admin.scaling-group.{}.name".format(admin_scale_index)] = scaling_group
2607 RO_scaling_info = []
2608 vdu_scaling_info = {"scaling_group_name": scaling_group, "vdu": []}
2609 if scaling_type == "SCALE_OUT":
2610 # count if max-instance-count is reached
2611 max_instance_count = scaling_descriptor.get("max-instance-count", 10)
2612 # self.logger.debug("MAX_INSTANCE_COUNT is {}".format(max_instance_count))
2613 if nb_scale_op >= max_instance_count:
2614 raise LcmException("reached the limit of {} (max-instance-count) "
2615 "scaling-out operations for the "
2616 "scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group))
2617
2618 nb_scale_op += 1
2619 vdu_scaling_info["scaling_direction"] = "OUT"
2620 vdu_scaling_info["vdu-create"] = {}
2621 for vdu_scale_info in scaling_descriptor["vdu"]:
2622 RO_scaling_info.append({"osm_vdu_id": vdu_scale_info["vdu-id-ref"], "member-vnf-index": vnf_index,
2623 "type": "create", "count": vdu_scale_info.get("count", 1)})
2624 vdu_scaling_info["vdu-create"][vdu_scale_info["vdu-id-ref"]] = vdu_scale_info.get("count", 1)
2625
2626 elif scaling_type == "SCALE_IN":
2627 # count if min-instance-count is reached
2628 min_instance_count = 0
2629 if "min-instance-count" in scaling_descriptor and scaling_descriptor["min-instance-count"] is not None:
2630 min_instance_count = int(scaling_descriptor["min-instance-count"])
2631 if nb_scale_op <= min_instance_count:
2632 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
2633 "scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group))
2634 nb_scale_op -= 1
2635 vdu_scaling_info["scaling_direction"] = "IN"
2636 vdu_scaling_info["vdu-delete"] = {}
2637 for vdu_scale_info in scaling_descriptor["vdu"]:
2638 RO_scaling_info.append({"osm_vdu_id": vdu_scale_info["vdu-id-ref"], "member-vnf-index": vnf_index,
2639 "type": "delete", "count": vdu_scale_info.get("count", 1)})
2640 vdu_scaling_info["vdu-delete"][vdu_scale_info["vdu-id-ref"]] = vdu_scale_info.get("count", 1)
2641
2642 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
2643 vdu_create = vdu_scaling_info.get("vdu-create")
2644 vdu_delete = copy(vdu_scaling_info.get("vdu-delete"))
2645 if vdu_scaling_info["scaling_direction"] == "IN":
2646 for vdur in reversed(db_vnfr["vdur"]):
2647 if vdu_delete.get(vdur["vdu-id-ref"]):
2648 vdu_delete[vdur["vdu-id-ref"]] -= 1
2649 vdu_scaling_info["vdu"].append({
2650 "name": vdur["name"],
2651 "vdu_id": vdur["vdu-id-ref"],
2652 "interface": []
2653 })
2654 for interface in vdur["interfaces"]:
2655 vdu_scaling_info["vdu"][-1]["interface"].append({
2656 "name": interface["name"],
2657 "ip_address": interface["ip-address"],
2658 "mac_address": interface.get("mac-address"),
2659 })
2660 vdu_delete = vdu_scaling_info.pop("vdu-delete")
2661
2662 # PRE-SCALE BEGIN
2663 step = "Executing pre-scale vnf-config-primitive"
2664 if scaling_descriptor.get("scaling-config-action"):
2665 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
2666 if (scaling_config_action.get("trigger") == "pre-scale-in" and scaling_type == "SCALE_IN") \
2667 or (scaling_config_action.get("trigger") == "pre-scale-out" and scaling_type == "SCALE_OUT"):
2668 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
2669 step = db_nslcmop_update["detailed-status"] = \
2670 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive)
2671
2672 # look for primitive
2673 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
2674 if config_primitive["name"] == vnf_config_primitive:
2675 break
2676 else:
2677 raise LcmException(
2678 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
2679 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
2680 "primitive".format(scaling_group, config_primitive))
2681
2682 vnfr_params = {"VDU_SCALE_INFO": vdu_scaling_info}
2683 if db_vnfr.get("additionalParamsForVnf"):
2684 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
2685
2686 scale_process = "VCA"
2687 db_nsr_update["config-status"] = "configuring pre-scaling"
2688 primitive_params = self._map_primitive_params(config_primitive, {}, vnfr_params)
2689
2690 # Pre-scale reintent check: Check if this sub-operation has been executed before
2691 op_index = self._check_or_add_scale_suboperation(
2692 db_nslcmop, nslcmop_id, vnf_index, vnf_config_primitive, primitive_params, 'PRE-SCALE')
2693 if (op_index == self.SUBOPERATION_STATUS_SKIP):
2694 # Skip sub-operation
2695 result = 'COMPLETED'
2696 result_detail = 'Done'
2697 self.logger.debug(logging_text +
2698 "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
2699 vnf_config_primitive, result, result_detail))
2700 else:
2701 if (op_index == self.SUBOPERATION_STATUS_NEW):
2702 # New sub-operation: Get index of this sub-operation
2703 op_index = len(db_nslcmop.get('_admin', {}).get('operations')) - 1
2704 self.logger.debug(logging_text + "vnf_config_primitive={} New sub-operation".
2705 format(vnf_config_primitive))
2706 else:
2707 # Reintent: Get registered params for this existing sub-operation
2708 op = db_nslcmop.get('_admin', {}).get('operations', [])[op_index]
2709 vnf_index = op.get('member_vnf_index')
2710 vnf_config_primitive = op.get('primitive')
2711 primitive_params = op.get('primitive_params')
2712 self.logger.debug(logging_text + "vnf_config_primitive={} Sub-operation reintent".
2713 format(vnf_config_primitive))
2714 # Execute the primitive, either with new (first-time) or registered (reintent) args
2715 result, result_detail = await self._ns_execute_primitive(
2716 nsr_deployed, vnf_index, None, None, None, vnf_config_primitive, primitive_params)
2717 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
2718 vnf_config_primitive, result, result_detail))
2719 # Update operationState = COMPLETED | FAILED
2720 self._update_suboperation_status(
2721 db_nslcmop, op_index, result, result_detail)
2722
2723 if result == "FAILED":
2724 raise LcmException(result_detail)
2725 db_nsr_update["config-status"] = old_config_status
2726 scale_process = None
2727 # PRE-SCALE END
2728
2729 # SCALE RO - BEGIN
2730 # Should this block be skipped if 'RO_nsr_id' == None ?
2731 # if (RO_nsr_id and RO_scaling_info):
2732 if RO_scaling_info:
2733 scale_process = "RO"
2734 # Scale RO reintent check: Check if this sub-operation has been executed before
2735 op_index = self._check_or_add_scale_suboperation(
2736 db_nslcmop, vnf_index, None, None, 'SCALE-RO', RO_nsr_id, RO_scaling_info)
2737 if (op_index == self.SUBOPERATION_STATUS_SKIP):
2738 # Skip sub-operation
2739 result = 'COMPLETED'
2740 result_detail = 'Done'
2741 self.logger.debug(logging_text + "Skipped sub-operation RO, result {} {}".format(
2742 result, result_detail))
2743 else:
2744 if (op_index == self.SUBOPERATION_STATUS_NEW):
2745 # New sub-operation: Get index of this sub-operation
2746 op_index = len(db_nslcmop.get('_admin', {}).get('operations')) - 1
2747 self.logger.debug(logging_text + "New sub-operation RO")
2748 else:
2749 # Reintent: Get registered params for this existing sub-operation
2750 op = db_nslcmop.get('_admin', {}).get('operations', [])[op_index]
2751 RO_nsr_id = op.get('RO_nsr_id')
2752 RO_scaling_info = op.get('RO_scaling_info')
2753 self.logger.debug(logging_text + "Sub-operation RO reintent".format(
2754 vnf_config_primitive))
2755
2756 RO_desc = await self.RO.create_action("ns", RO_nsr_id, {"vdu-scaling": RO_scaling_info})
2757 db_nsr_update["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index)] = nb_scale_op
2758 db_nsr_update["_admin.scaling-group.{}.time".format(admin_scale_index)] = time()
2759 # wait until ready
2760 RO_nslcmop_id = RO_desc["instance_action_id"]
2761 db_nslcmop_update["_admin.deploy.RO"] = RO_nslcmop_id
2762
2763 RO_task_done = False
2764 step = detailed_status = "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id)
2765 detailed_status_old = None
2766 self.logger.debug(logging_text + step)
2767
2768 deployment_timeout = 1 * 3600 # One hour
2769 while deployment_timeout > 0:
2770 if not RO_task_done:
2771 desc = await self.RO.show("ns", item_id_name=RO_nsr_id, extra_item="action",
2772 extra_item_id=RO_nslcmop_id)
2773 ns_status, ns_status_info = self.RO.check_action_status(desc)
2774 if ns_status == "ERROR":
2775 raise ROclient.ROClientException(ns_status_info)
2776 elif ns_status == "BUILD":
2777 detailed_status = step + "; {}".format(ns_status_info)
2778 elif ns_status == "ACTIVE":
2779 RO_task_done = True
2780 step = detailed_status = "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id)
2781 self.logger.debug(logging_text + step)
2782 else:
2783 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
2784 else:
2785
2786 if ns_status == "ERROR":
2787 raise ROclient.ROClientException(ns_status_info)
2788 elif ns_status == "BUILD":
2789 detailed_status = step + "; {}".format(ns_status_info)
2790 elif ns_status == "ACTIVE":
2791 step = detailed_status = \
2792 "Waiting for management IP address reported by the VIM. Updating VNFRs"
2793 if not vnfr_scaled:
2794 self.scale_vnfr(db_vnfr, vdu_create=vdu_create, vdu_delete=vdu_delete)
2795 vnfr_scaled = True
2796 try:
2797 desc = await self.RO.show("ns", RO_nsr_id)
2798 # nsr_deployed["nsr_ip"] = RO.get_ns_vnf_info(desc)
2799 self.ns_update_vnfr({db_vnfr["member-vnf-index-ref"]: db_vnfr}, desc)
2800 break
2801 except LcmExceptionNoMgmtIP:
2802 pass
2803 else:
2804 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
2805 if detailed_status != detailed_status_old:
2806 self._update_suboperation_status(
2807 db_nslcmop, op_index, 'COMPLETED', detailed_status)
2808 detailed_status_old = db_nslcmop_update["detailed-status"] = detailed_status
2809 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
2810
2811 await asyncio.sleep(5, loop=self.loop)
2812 deployment_timeout -= 5
2813 if deployment_timeout <= 0:
2814 self._update_suboperation_status(
2815 db_nslcmop, nslcmop_id, op_index, 'FAILED', "Timeout when waiting for ns to get ready")
2816 raise ROclient.ROClientException("Timeout waiting ns to be ready")
2817
2818 # update VDU_SCALING_INFO with the obtained ip_addresses
2819 if vdu_scaling_info["scaling_direction"] == "OUT":
2820 for vdur in reversed(db_vnfr["vdur"]):
2821 if vdu_scaling_info["vdu-create"].get(vdur["vdu-id-ref"]):
2822 vdu_scaling_info["vdu-create"][vdur["vdu-id-ref"]] -= 1
2823 vdu_scaling_info["vdu"].append({
2824 "name": vdur["name"],
2825 "vdu_id": vdur["vdu-id-ref"],
2826 "interface": []
2827 })
2828 for interface in vdur["interfaces"]:
2829 vdu_scaling_info["vdu"][-1]["interface"].append({
2830 "name": interface["name"],
2831 "ip_address": interface["ip-address"],
2832 "mac_address": interface.get("mac-address"),
2833 })
2834 del vdu_scaling_info["vdu-create"]
2835
2836 self._update_suboperation_status(db_nslcmop, op_index, 'COMPLETED', 'Done')
2837 # SCALE RO - END
2838
2839 scale_process = None
2840 if db_nsr_update:
2841 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2842
2843 # POST-SCALE BEGIN
2844 # execute primitive service POST-SCALING
2845 step = "Executing post-scale vnf-config-primitive"
2846 if scaling_descriptor.get("scaling-config-action"):
2847 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
2848 if (scaling_config_action.get("trigger") == "post-scale-in" and scaling_type == "SCALE_IN") \
2849 or (scaling_config_action.get("trigger") == "post-scale-out" and scaling_type == "SCALE_OUT"):
2850 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
2851 step = db_nslcmop_update["detailed-status"] = \
2852 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive)
2853
2854 vnfr_params = {"VDU_SCALE_INFO": vdu_scaling_info}
2855 if db_vnfr.get("additionalParamsForVnf"):
2856 vnfr_params.update(db_vnfr["additionalParamsForVnf"])
2857
2858 # look for primitive
2859 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
2860 if config_primitive["name"] == vnf_config_primitive:
2861 break
2862 else:
2863 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
2864 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
2865 "match any vnf-configuration:config-primitive".format(scaling_group,
2866 config_primitive))
2867 scale_process = "VCA"
2868 db_nsr_update["config-status"] = "configuring post-scaling"
2869 primitive_params = self._map_primitive_params(config_primitive, {}, vnfr_params)
2870
2871 # Post-scale reintent check: Check if this sub-operation has been executed before
2872 op_index = self._check_or_add_scale_suboperation(
2873 db_nslcmop, nslcmop_id, vnf_index, vnf_config_primitive, primitive_params, 'POST-SCALE')
2874 if (op_index == self.SUBOPERATION_STATUS_SKIP):
2875 # Skip sub-operation
2876 result = 'COMPLETED'
2877 result_detail = 'Done'
2878 self.logger.debug(logging_text +
2879 "vnf_config_primitive={} Skipped sub-operation, result {} {}".
2880 format(vnf_config_primitive, result, result_detail))
2881 else:
2882 if (op_index == self.SUBOPERATION_STATUS_NEW):
2883 # New sub-operation: Get index of this sub-operation
2884 op_index = len(db_nslcmop.get('_admin', {}).get('operations')) - 1
2885 self.logger.debug(logging_text + "vnf_config_primitive={} New sub-operation".
2886 format(vnf_config_primitive))
2887 else:
2888 # Reintent: Get registered params for this existing sub-operation
2889 op = db_nslcmop.get('_admin', {}).get('operations', [])[op_index]
2890 vnf_index = op.get('member_vnf_index')
2891 vnf_config_primitive = op.get('primitive')
2892 primitive_params = op.get('primitive_params')
2893 self.logger.debug(logging_text + "vnf_config_primitive={} Sub-operation reintent".
2894 format(vnf_config_primitive))
2895 # Execute the primitive, either with new (first-time) or registered (reintent) args
2896 result, result_detail = await self._ns_execute_primitive(
2897 nsr_deployed, vnf_index, None, None, None, vnf_config_primitive, primitive_params)
2898 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
2899 vnf_config_primitive, result, result_detail))
2900 # Update operationState = COMPLETED | FAILED
2901 self._update_suboperation_status(
2902 db_nslcmop, op_index, result, result_detail)
2903
2904 if result == "FAILED":
2905 raise LcmException(result_detail)
2906 db_nsr_update["config-status"] = old_config_status
2907 scale_process = None
2908 # POST-SCALE END
2909
2910 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
2911 db_nslcmop_update["statusEnteredTime"] = time()
2912 db_nslcmop_update["detailed-status"] = "done"
2913 db_nsr_update["detailed-status"] = "" # "scaled {} {}".format(scaling_group, scaling_type)
2914 db_nsr_update["operational-status"] = "running" if old_operational_status == "failed" \
2915 else old_operational_status
2916 db_nsr_update["config-status"] = old_config_status
2917 return
2918 except (ROclient.ROClientException, DbException, LcmException) as e:
2919 self.logger.error(logging_text + "Exit Exception {}".format(e))
2920 exc = e
2921 except asyncio.CancelledError:
2922 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
2923 exc = "Operation was cancelled"
2924 except Exception as e:
2925 exc = traceback.format_exc()
2926 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
2927 finally:
2928 if exc:
2929 if db_nslcmop:
2930 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
2931 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
2932 db_nslcmop_update["statusEnteredTime"] = time()
2933 if db_nsr:
2934 db_nsr_update["operational-status"] = old_operational_status
2935 db_nsr_update["config-status"] = old_config_status
2936 db_nsr_update["detailed-status"] = ""
2937 db_nsr_update["_admin.nslcmop"] = None
2938 if scale_process:
2939 if "VCA" in scale_process:
2940 db_nsr_update["config-status"] = "failed"
2941 if "RO" in scale_process:
2942 db_nsr_update["operational-status"] = "failed"
2943 db_nsr_update["detailed-status"] = "FAILED scaling nslcmop={} {}: {}".format(nslcmop_id, step,
2944 exc)
2945 try:
2946 if db_nslcmop and db_nslcmop_update:
2947 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
2948 if db_nsr:
2949 db_nsr_update["_admin.current-operation"] = None
2950 db_nsr_update["_admin.operation-type"] = None
2951 db_nsr_update["_admin.nslcmop"] = None
2952 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2953 except DbException as e:
2954 self.logger.error(logging_text + "Cannot update database: {}".format(e))
2955 if nslcmop_operation_state:
2956 try:
2957 await self.msg.aiowrite("ns", "scaled", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
2958 "operationState": nslcmop_operation_state},
2959 loop=self.loop)
2960 # if cooldown_time:
2961 # await asyncio.sleep(cooldown_time, loop=self.loop)
2962 # await self.msg.aiowrite("ns","scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
2963 except Exception as e:
2964 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
2965 self.logger.debug(logging_text + "Exit")
2966 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_scale")