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