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